feat: initial lifelog project

- 待办事项(支持优先级、截止日期)
- 每日记录(上午/下午/晚上分条目)
- Go后端 + Gin + GORM + MySQL
- React前端 + TailwindCSS
This commit is contained in:
2026-07-28 16:22:46 +08:00
commit d495a2b798
32 changed files with 4501 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
node_modules/
dist/
.env
*.log
.DS_Store
+104
View File
@@ -0,0 +1,104 @@
package main
import (
"context"
"fmt"
"lifelog/internal/handler"
"lifelog/internal/model"
"lifelog/internal/repository"
"lifelog/internal/service"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
gin.SetMode(gin.ReleaseMode)
// 数据库连接
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
getEnv("DB_USER", "rhett_claw"),
getEnv("DB_PASS", "Zhugezhongli001"),
getEnv("DB_HOST", "localhost"),
getEnv("DB_NAME", "rhett_claw"),
)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalf("连接数据库失败: %v", err)
}
// 自动建表
db.AutoMigrate(&model.Todo{}, &model.DailyLog{})
// 初始化各层
todoRepo := repository.NewTodoRepository(db)
dailyLogRepo := repository.NewDailyLogRepository(db)
todoSvc := service.NewTodoService(todoRepo)
dailyLogSvc := service.NewDailyLogService(dailyLogRepo)
h := handler.NewHandler(todoSvc, dailyLogSvc)
// Gin 路由
r := gin.New()
r.Use(gin.Recovery())
// 静态文件(前端构建产物)
distPath := "/var/www/lifelog/web/dist"
r.Static("/assets", distPath+"/assets")
r.StaticFile("/favicon.svg", distPath+"/favicon.svg")
// 前端路由兜底
r.NoRoute(func(c *gin.Context) {
c.File(distPath + "/index.html")
})
// API 路由
api := r.Group("/api")
{
api.GET("/todos", h.GetTodos)
api.POST("/todos", h.CreateTodo)
api.PUT("/todos/:id", h.UpdateTodo)
api.PATCH("/todos/:id/done", h.ToggleTodo)
api.DELETE("/todos/:id", h.DeleteTodo)
api.GET("/logs/:date", h.GetDailyLog)
api.GET("/logs", h.GetRecentLogs)
api.PUT("/logs/:date", h.SaveDailyLog)
}
port := getEnv("PORT", "17010")
srv := &http.Server{Addr: ":" + port, Handler: r}
go func() {
log.Printf("LifeLog 服务启动: http://localhost:%s", port)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("服务启动失败: %v", err)
}
}()
// 优雅关机
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("正在关闭服务...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("服务强制退出: %v", err)
}
log.Println("服务已关闭")
}
func getEnv(key, defaultVal string) string {
if val := os.Getenv(key); val != "" {
return val
}
return defaultVal
}
+108
View File
@@ -0,0 +1,108 @@
# LifeLog 项目设计文档
## 1. 项目概述
- **项目名**LifeLog
- **定位**:个人日志与待办管理工具
- **核心功能**
1. 待办事项管理(增删改查,完成标记)
2. 每日三时段记录(上午/下午/晚上)
- **目标用户**:个人使用,简约高效
## 2. 技术栈
| 层 | 技术 |
|----|------|
| 后端 | Go + Gin 框架 |
| 前端 | React + Vite + TailwindCSS |
| 数据库 | MySQL (`rhett_claw`) |
| 部署 | 独立项目,端口 17010 |
## 3. 数据库设计
### 表:todos(待办事项)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | BIGINT UNSIGNED AUTO_INCREMENT | 主键 |
| title | VARCHAR(255) NOT NULL | 事项标题 |
| done | TINYINT(1) NOT NULL DEFAULT 0 | 是否完成(0否 1是) |
| priority | TINYINT(1) NOT NULL DEFAULT 2 | 优先级(1高 2中 3低) |
| created_at | DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP | 创建时间 |
| updated_at | DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP | 更新时间 |
### 表:daily_logs(每日记录)
| 字段 | 类型 | 说明 |
|------|------|------|
| id | BIGINT UNSIGNED AUTO_INCREMENT | 主键 |
| date | DATE NOT NULL UNIQUE | 日期(格式:2024-07-24 |
| morning | TEXT | 上午记录 |
| afternoon | TEXT | 下午记录 |
| evening | TEXT | 晚上记录 |
| created_at | DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP | 创建时间 |
| updated_at | DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP | 更新时间 |
## 4. API 设计
### 待办事项(/api/todos
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | /api/todos | 获取所有待办 |
| POST | /api/todos | 新增待办 |
| PUT | /api/todos/:id | 更新待办 |
| PATCH | /api/todos/:id/done | 标记完成/未完成 |
| DELETE | /api/todos/:id | 删除待办 |
### 每日记录(/api/logs
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | /api/logs/:date | 获取某日记录(date格式:2024-07-24 |
| GET | /api/logs | 获取最近N条记录 |
| PUT | /api/logs/:date | 创建或更新某日记录 |
## 5. 前端页面
### 页面一:待办事项(/
- 顶部:标题 + 添加按钮
- 中部:待办列表(显示优先级、完成状态、标题)
- 支持:勾选完成、删除、筛选
### 页面二:每日记录(/logs)
- 日期选择器(顶部)
- 三个文本区域:上午 / 下午 / 晚上
- 自动保存(输入后延迟保存)
## 6. 项目结构
```
/var/www/lifelog/
├── cmd/
│ └── server/
│ └── main.go # 入口
├── internal/
│ ├── handler/ # HTTP handlers
│ ├── model/ # 数据模型
│ ├── repository/ # 数据库操作
│ └── service/ # 业务逻辑
├── web/ # 前端 React
│ ├── src/
│ │ ├── components/
│ │ ├── pages/
│ │ └── App.tsx
│ ├── index.html
│ └── vite.config.ts
├── docs/
│ └── plans/
├── go.mod
├── go.sum
└── Makefile
```
## 7. 部署
- 后端端口:**17010**
- 数据库:使用已有的 `rhett_claw`MySQL
- PM2 管理进程
+72
View File
@@ -0,0 +1,72 @@
# LifeLog 实现计划
## 阶段一:后端开发
### Task 1.1:初始化 Go 项目
- 初始化 go.mod
- 安装依赖:gin、gorm、mysql-driver
- 创建目录结构
- 验证:`go build ./...`
### Task 1.2:数据库初始化
- 连接 MySQLrhett_claw
- 自动建表(todos、daily_logs
- 验证:表创建成功
### Task 1.3Model 层
- 定义 Todo 模型
- 定义 DailyLog 模型
- 验证:模型定义正确
### Task 1.4Repository 层
- Todo CRUD 实现
- DailyLog CRUD 实现
- 验证:单元测试通过
### Task 1.5Service 层
- TodoService 实现
- DailyLogService 实现
- 验证:业务逻辑正确
### Task 1.6Handler 层 + 路由
- Todo HTTP handlers
- DailyLog HTTP handlers
- Gin 路由注册
- 验证:`curl localhost:17010/api/todos` 返回200
## 阶段二:前端开发
### Task 2.1:初始化 React 项目
- Vite + React + TypeScript
- 安装 TailwindCSS
- 验证:页面能运行
### Task 2.2:待办页面
- TodoList 组件
- TodoItem 组件
- AddTodo 表单
- API 调用(React Query
- 验证:CRUD 功能正常
### Task 2.3:每日记录页面
- DatePicker 组件
- DailyLogForm 组件(三个时段)
- 自动保存逻辑
- 验证:记录能保存和加载
### Task 2.4:页面美化
- 简约 UI 风格
- 响应式布局
- 验证:视觉符合设计
## 阶段三:部署
### Task 3.1:构建和启动
- 前端 `npm run build`
- 后端 `go build`
- PM2 配置并启动
- 验证:`curl localhost:17010` 返回200
### Task 3.2:收尾
- PM2 save
- 验证服务稳定运行
+38
View File
@@ -0,0 +1,38 @@
module lifelog
go 1.22.4
require (
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.10.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/go-sql-driver/mysql v1.7.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/mysql v1.5.7 // indirect
gorm.io/gorm v1.25.12 // indirect
)
+90
View File
@@ -0,0 +1,90 @@
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
+167
View File
@@ -0,0 +1,167 @@
package handler
import (
"net/http"
"strconv"
"time"
"lifelog/internal/service"
"github.com/gin-gonic/gin"
)
type Handler struct {
todoSvc *service.TodoService
dailyLogSvc *service.DailyLogService
}
func NewHandler(todoSvc *service.TodoService, dailyLogSvc *service.DailyLogService) *Handler {
return &Handler{todoSvc: todoSvc, dailyLogSvc: dailyLogSvc}
}
// Todo handlers
func (h *Handler) GetTodos(c *gin.Context) {
todos, err := h.todoSvc.GetAll()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": todos})
}
func (h *Handler) CreateTodo(c *gin.Context) {
var req struct {
Title string `json:"title" binding:"required"`
Priority int `json:"priority"`
DueDate string `json:"due_date"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if req.Priority == 0 {
req.Priority = 2
}
var dueDate *time.Time
if req.DueDate != "" {
t, err := time.Parse("2006-01-02", req.DueDate)
if err == nil {
dueDate = &t
}
}
todo, err := h.todoSvc.Create(req.Title, req.Priority, dueDate)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, gin.H{"data": todo})
}
func (h *Handler) UpdateTodo(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
var req struct {
Title string `json:"title" binding:"required"`
Priority int `json:"priority"`
Done bool `json:"done"`
DueDate string `json:"due_date"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var dueDate *time.Time
if req.DueDate != "" {
t, err := time.Parse("2006-01-02", req.DueDate)
if err == nil {
dueDate = &t
}
}
todo, err := h.todoSvc.Update(id, req.Title, req.Priority, req.Done, dueDate)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": todo})
}
func (h *Handler) ToggleTodo(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
todo, err := h.todoSvc.ToggleDone(id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": todo})
}
func (h *Handler) DeleteTodo(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
return
}
err = h.todoSvc.Delete(id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "deleted"})
}
// DailyLog handlers
func (h *Handler) GetDailyLog(c *gin.Context) {
date := c.Param("date")
if date == "" {
date = time.Now().Format("2006-01-02")
}
log, err := h.dailyLogSvc.GetByDate(date)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": log})
}
func (h *Handler) GetRecentLogs(c *gin.Context) {
limitStr := c.DefaultQuery("limit", "30")
limit, _ := strconv.Atoi(limitStr)
logs, err := h.dailyLogSvc.GetRecent(limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": logs})
}
func (h *Handler) SaveDailyLog(c *gin.Context) {
date := c.Param("date")
if date == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "date is required"})
return
}
var req struct {
Morning string `json:"morning"`
Afternoon string `json:"afternoon"`
Evening string `json:"evening"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
log, err := h.dailyLogSvc.Save(date, req.Morning, req.Afternoon, req.Evening)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": log})
}
+33
View File
@@ -0,0 +1,33 @@
package model
import (
"time"
)
type Todo struct {
ID uint64 `gorm:"primaryKey;autoIncrement" json:"id"`
Title string `gorm:"type:varchar(255);not null" json:"title"`
Done bool `gorm:"type:tinyint(1);not null;default:0" json:"done"`
Priority int `gorm:"type:tinyint(1);not null;default:2" json:"priority"` // 1高 2中 3低
DueDate *time.Time `gorm:"type:date" json:"due_date"` // 可选截止日期
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
}
func (Todo) TableName() string {
return "todos"
}
type DailyLog struct {
ID uint64 `gorm:"primaryKey;autoIncrement" json:"id"`
Date string `gorm:"type:date;not null;uniqueIndex" json:"date"` // 格式:2024-07-24
Morning string `gorm:"type:text" json:"morning"`
Afternoon string `gorm:"type:text" json:"afternoon"`
Evening string `gorm:"type:text" json:"evening"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
}
func (DailyLog) TableName() string {
return "daily_logs"
}
+78
View File
@@ -0,0 +1,78 @@
package repository
import (
"lifelog/internal/model"
"gorm.io/gorm"
)
type TodoRepository struct {
db *gorm.DB
}
func NewTodoRepository(db *gorm.DB) *TodoRepository {
return &TodoRepository{db: db}
}
func (r *TodoRepository) GetAll() ([]model.Todo, error) {
var todos []model.Todo
err := r.db.Order("priority asc, created_at desc").Find(&todos).Error
return todos, err
}
func (r *TodoRepository) Create(todo *model.Todo) error {
return r.db.Create(todo).Error
}
func (r *TodoRepository) Update(todo *model.Todo) error {
return r.db.Save(todo).Error
}
func (r *TodoRepository) Delete(id uint64) error {
return r.db.Delete(&model.Todo{}, id).Error
}
func (r *TodoRepository) GetByID(id uint64) (*model.Todo, error) {
var todo model.Todo
err := r.db.First(&todo, id).Error
return &todo, err
}
type DailyLogRepository struct {
db *gorm.DB
}
func NewDailyLogRepository(db *gorm.DB) *DailyLogRepository {
return &DailyLogRepository{db: db}
}
func (r *DailyLogRepository) GetByDate(date string) (*model.DailyLog, error) {
var log model.DailyLog
err := r.db.Where("date = ?", date).First(&log).Error
if err == gorm.ErrRecordNotFound {
return nil, nil
}
return &log, err
}
func (r *DailyLogRepository) GetRecent(limit int) ([]model.DailyLog, error) {
var logs []model.DailyLog
err := r.db.Order("date desc").Limit(limit).Find(&logs).Error
return logs, err
}
func (r *DailyLogRepository) Upsert(log *model.DailyLog) error {
var existing model.DailyLog
err := r.db.Where("date = ?", log.Date).First(&existing).Error
if err == gorm.ErrRecordNotFound {
return r.db.Create(log).Error
}
if err != nil {
return err
}
// 更新已有记录
existing.Morning = log.Morning
existing.Afternoon = log.Afternoon
existing.Evening = log.Evening
return r.db.Save(&existing).Error
}
+99
View File
@@ -0,0 +1,99 @@
package service
import (
"errors"
"lifelog/internal/model"
"lifelog/internal/repository"
"time"
)
type TodoService struct {
repo *repository.TodoRepository
}
func NewTodoService(repo *repository.TodoRepository) *TodoService {
return &TodoService{repo: repo}
}
func (s *TodoService) GetAll() ([]model.Todo, error) {
return s.repo.GetAll()
}
func (s *TodoService) Create(title string, priority int, dueDate *time.Time) (*model.Todo, error) {
todo := &model.Todo{
Title: title,
Done: false,
Priority: priority,
DueDate: dueDate,
}
err := s.repo.Create(todo)
return todo, err
}
func (s *TodoService) Update(id uint64, title string, priority int, done bool, dueDate *time.Time) (*model.Todo, error) {
todo, err := s.repo.GetByID(id)
if err != nil {
return nil, err
}
todo.Title = title
todo.Priority = priority
todo.Done = done
todo.DueDate = dueDate
err = s.repo.Update(todo)
return todo, err
}
func (s *TodoService) ToggleDone(id uint64) (*model.Todo, error) {
todo, err := s.repo.GetByID(id)
if err != nil {
return nil, err
}
todo.Done = !todo.Done
err = s.repo.Update(todo)
return todo, err
}
func (s *TodoService) Delete(id uint64) error {
return s.repo.Delete(id)
}
type DailyLogService struct {
repo *repository.DailyLogRepository
}
func NewDailyLogService(repo *repository.DailyLogRepository) *DailyLogService {
return &DailyLogService{repo: repo}
}
func (s *DailyLogService) GetByDate(date string) (*model.DailyLog, error) {
log, err := s.repo.GetByDate(date)
if err != nil {
return nil, err
}
if log == nil {
// 返回空记录
return &model.DailyLog{Date: date}, nil
}
return log, nil
}
func (s *DailyLogService) GetRecent(limit int) ([]model.DailyLog, error) {
if limit <= 0 {
limit = 30
}
return s.repo.GetRecent(limit)
}
func (s *DailyLogService) Save(date, morning, afternoon, evening string) (*model.DailyLog, error) {
if date == "" {
return nil, errors.New("date is required")
}
log := &model.DailyLog{
Date: date,
Morning: morning,
Afternoon: afternoon,
Evening: evening,
}
err := s.repo.Upsert(log)
return log, err
}
Executable
BIN
View File
Binary file not shown.
+73
View File
@@ -0,0 +1,73 @@
# 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 [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## 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 defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// 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,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
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 defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+23
View File
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>LifeLog - 每日工作台</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+2996
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "lifelog-web",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.7.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.0"
},
"devDependencies": {
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.5.4",
"postcss": "^8.5.8",
"tailwindcss": "^3.4.19",
"typescript": "~5.5.0",
"vite": "^5.4.0"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32">
<rect width="32" height="32" rx="6" fill="#3b82f6"/>
<rect x="7" y="8" width="18" height="2.5" rx="1.25" fill="white" opacity="0.9"/>
<rect x="7" y="12.5" width="14" height="2.5" rx="1.25" fill="white" opacity="0.7"/>
<rect x="7" y="17" width="16" height="2.5" rx="1.25" fill="white" opacity="0.7"/>
<rect x="7" y="21.5" width="10" height="2.5" rx="1.25" fill="white" opacity="0.5"/>
</svg>

After

Width:  |  Height:  |  Size: 485 B

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+22
View File
@@ -0,0 +1,22 @@
import HomePage from './pages/HomePage'
function App() {
return (
<div className="min-h-screen bg-slate-50">
<nav className="bg-white border-b border-slate-200 mb-8">
<div className="max-w-5xl mx-auto px-4">
<div className="flex items-center gap-2 py-4">
<span className="text-xl">📒</span>
<span className="font-bold text-lg text-slate-800">LifeLog</span>
<span className="text-slate-400 text-sm ml-2"></span>
</div>
</div>
</nav>
<main className="px-4 pb-12">
<HomePage />
</main>
</div>
)
}
export default App
+43
View File
@@ -0,0 +1,43 @@
import axios from 'axios'
const api = axios.create({
baseURL: '/api',
})
export interface Todo {
id: number
title: string
done: boolean
priority: number
due_date: string | null
created_at: string
updated_at: string
}
export interface DailyLog {
id: number
date: string
morning: string
afternoon: string
evening: string
}
export const todoApi = {
getAll: () => api.get<{ data: Todo[] }>('/todos').then(r => r.data.data),
create: (title: string, priority: number, dueDate?: string) =>
api.post<{ data: Todo }>('/todos', { title, priority, due_date: dueDate || null }).then(r => r.data.data),
update: (id: number, data: Partial<Todo>) =>
api.put<{ data: Todo }>(`/todos/${id}`, data).then(r => r.data.data),
toggle: (id: number) =>
api.patch<{ data: Todo }>(`/todos/${id}/done`).then(r => r.data.data),
delete: (id: number) => api.delete(`/todos/${id}`),
}
export const logApi = {
getByDate: (date: string) =>
api.get<{ data: DailyLog }>(`/logs/${date}`).then(r => r.data.data),
save: (date: string, data: { morning: string; afternoon: string; evening: string }) =>
api.put(`/logs/${date}`, data),
getRecent: (limit = 30) =>
api.get<{ data: DailyLog[] }>(`/logs?limit=${limit}`).then(r => r.data.data),
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

+9
View File
@@ -0,0 +1,9 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background-color: #f8fafc;
color: #1e293b;
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+381
View File
@@ -0,0 +1,381 @@
import { useState, useEffect, useCallback } from 'react'
import { todoApi, logApi, type Todo, type DailyLog } from '../api'
type Filter = 'all' | 'active' | 'done'
// 每日记录的单条内容
interface LogItem {
id: string
text: string
}
const parseLog = (content: string): LogItem[] => {
return content.split('\n').filter(l => l.trim()).map((l, i) => ({
id: `item-${i}-${Date.now()}`,
text: l.trim()
}))
}
const formatLog = (items: LogItem[]): string => {
return items.map(i => i.text).join('\n')
}
export default function HomePage() {
const [todos, setTodos] = useState<Todo[]>([])
const [newTitle, setNewTitle] = useState('')
const [newPriority, setNewPriority] = useState(2)
const [newDueDate, setNewDueDate] = useState('')
const [filter, setFilter] = useState<Filter>('all')
const [loading, setLoading] = useState(true)
const today = new Date()
const todayStr = today.toISOString().split('T')[0]
const [date, setDate] = useState(todayStr)
// 每时段内容转为卡片数组
const [morningItems, setMorningItems] = useState<LogItem[]>([])
const [afternoonItems, setAfternoonItems] = useState<LogItem[]>([])
const [eveningItems, setEveningItems] = useState<LogItem[]>([])
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const [logLoading, setLogLoading] = useState(true)
useEffect(() => {
Promise.all([loadTodos(), loadLog(date)]).finally(() => setLoading(false))
}, [])
const loadTodos = async () => {
const data = await todoApi.getAll()
setTodos(data)
}
const loadLog = async (d: string) => {
setLogLoading(true)
const data = await logApi.getByDate(d)
setMorningItems(data?.morning ? parseLog(data.morning) : [])
setAfternoonItems(data?.afternoon ? parseLog(data.afternoon) : [])
setEveningItems(data?.evening ? parseLog(data.evening) : [])
setLogLoading(false)
}
// 防抖自动保存(仅今日)
useEffect(() => {
if (date !== todayStr) return
const timer = setTimeout(() => {
if (morningItems.length || afternoonItems.length || eveningItems.length) {
handleSave(true)
}
}, 1000)
return () => clearTimeout(timer)
}, [morningItems, afternoonItems, eveningItems])
const handleSave = useCallback(async (isAuto = false) => {
setSaving(true)
setSaved(false)
await logApi.save(date, {
morning: formatLog(morningItems),
afternoon: formatLog(afternoonItems),
evening: formatLog(eveningItems),
})
setSaving(false)
if (!isAuto) {
setSaved(true)
setTimeout(() => setSaved(false), 2000)
}
}, [date, morningItems, afternoonItems, eveningItems])
const handleAdd = async (e: React.FormEvent) => {
e.preventDefault()
if (!newTitle.trim()) return
const todo = await todoApi.create(newTitle, newPriority)
setTodos([todo, ...todos])
setNewTitle('')
setNewDueDate('')
}
const handleToggle = async (id: number) => {
const updated = await todoApi.toggle(id)
setTodos(todos.map(t => t.id === id ? updated : t))
}
const handleDelete = async (id: number) => {
await todoApi.delete(id)
setTodos(todos.filter(t => t.id !== id))
}
const priorityDot = (p: number) => {
const colors = ['bg-red-400', 'bg-yellow-400', 'bg-green-400']
return <span className={`w-2 h-2 rounded-full ${colors[p - 1] || 'bg-slate-300'} flex-shrink-0`} />
}
const isOverdue = (dueDate: string | null) => {
if (!dueDate) return false
return new Date(dueDate + 'T23:59:59') < new Date(todayStr + 'T23:59:59')
}
const isDueToday = (dueDate: string | null) => {
if (!dueDate) return false
return dueDate === todayStr
}
const formatDueDate = (dueDate: string | null) => {
if (!dueDate) return null
const d = new Date(dueDate + 'T00:00:00')
const diff = Math.round((d.getTime() - today.getTime()) / 86400000)
if (diff === 0) return '今天'
if (diff === 1) return '明天'
if (diff === -1) return '昨天'
if (diff > 0) return `${diff}天后`
return `${Math.abs(diff)}天前`
}
const filteredTodos = todos.filter(t => {
if (filter === 'active') return !t.done
if (filter === 'done') return t.done
return true
})
const pendingCount = todos.filter(t => !t.done).length
const doneCount = todos.filter(t => t.done).length
const hasLogContent = morningItems.length || afternoonItems.length || eveningItems.length
const dateLabel = date === todayStr ? '今天' : date
// 每日记录卡片组件
const LogSection = ({ label, icon, items, onChange }: {
label: string
icon: string
items: LogItem[]
onChange: (items: LogItem[]) => void
}) => {
const [newItemText, setNewItemText] = useState('')
const addItem = () => {
if (!newItemText.trim()) return
onChange([...items, { id: `item-${Date.now()}`, text: newItemText.trim() }])
setNewItemText('')
}
const updateItem = (id: string, text: string) => {
onChange(items.map(i => i.id === id ? { ...i, text } : i))
}
const deleteItem = (id: string) => {
onChange(items.filter(i => i.id !== id))
}
return (
<div>
<label className="block text-sm font-medium text-slate-600 mb-2">{icon} {label}</label>
<div className="space-y-1.5">
{items.map(item => (
<div key={item.id} className="group flex items-start gap-2 bg-slate-50 rounded-xl px-3 py-2 hover:bg-slate-100 transition">
<span className="text-slate-300 mt-0.5 text-xs flex-shrink-0"></span>
<textarea
value={item.text}
onChange={e => updateItem(item.id, e.target.value)}
rows={1}
className="flex-1 bg-transparent text-sm text-slate-700 resize-none focus:outline-none leading-relaxed"
placeholder="输入内容..."
onKeyDown={e => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
addItem()
}
}}
/>
<button
onClick={() => deleteItem(item.id)}
className="text-slate-300 hover:text-red-400 transition text-xs opacity-0 group-hover:opacity-100 mt-0.5 flex-shrink-0"
>
</button>
</div>
))}
{/* 添加新条目 */}
<div className="flex items-center gap-2">
<input
type="text"
value={newItemText}
onChange={e => setNewItemText(e.target.value)}
onKeyDown={e => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
addItem()
}
}}
placeholder="按回车添加新条目..."
className="flex-1 text-sm px-3 py-2 border border-dashed border-slate-200 rounded-xl focus:outline-none focus:border-blue-400 bg-white transition"
/>
</div>
</div>
</div>
)
}
return (
<div className="max-w-5xl mx-auto">
{/* 顶部概览 */}
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-4">
<h1 className="text-2xl font-bold text-slate-800">📒 LifeLog</h1>
<div className="flex items-center gap-3 text-sm text-slate-500">
<span className="bg-blue-50 text-blue-600 px-2 py-0.5 rounded-full font-medium">
{pendingCount}
</span>
<span className="bg-green-50 text-green-600 px-2 py-0.5 rounded-full font-medium">
{doneCount}
</span>
<span className={`px-2 py-0.5 rounded-full font-medium ${hasLogContent ? 'bg-amber-50 text-amber-600' : 'bg-slate-100 text-slate-400'}`}>
{dateLabel} {hasLogContent ? '已记录' : '未记录'}
</span>
</div>
</div>
<button
onClick={() => { setDate(todayStr); loadLog(todayStr) }}
className="text-sm text-blue-500 hover:text-blue-600 hover:underline"
>
</button>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 左侧:待办事项 */}
<div className="bg-white rounded-2xl shadow-sm border border-slate-100 p-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-bold text-slate-800">📋 </h2>
<div className="flex gap-1 bg-slate-100 rounded-lg p-0.5">
{([['all', '全部'], ['active', '进行中'], ['done', '已完成']] as [Filter, string][]).map(([key, label]) => (
<button
key={key}
onClick={() => setFilter(key)}
className={`px-3 py-1 rounded-md text-xs font-medium transition ${
filter === key ? 'bg-white text-slate-800 shadow-sm' : 'text-slate-500 hover:text-slate-700'
}`}
>
{label}
</button>
))}
</div>
</div>
<form onSubmit={handleAdd} className="mb-4 space-y-2">
<input
type="text"
value={newTitle}
onChange={e => setNewTitle(e.target.value)}
placeholder="输入新事项,按回车添加..."
className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 text-sm"
/>
<div className="flex items-center gap-2">
<select
value={newPriority}
onChange={e => setNewPriority(Number(e.target.value))}
className="px-2 py-1.5 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 text-sm"
>
<option value={1}>🔴</option>
<option value={2}>🟡</option>
<option value={3}>🟢</option>
</select>
<input
type="date"
value={newDueDate}
onChange={e => setNewDueDate(e.target.value)}
className="flex-1 px-2 py-1.5 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 text-sm"
/>
<button
type="submit"
className="px-4 py-1.5 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition text-sm font-medium"
>
</button>
</div>
</form>
<div className="space-y-1 max-h-80 overflow-y-auto">
{loading ? (
<div className="text-center text-slate-400 text-sm py-8">...</div>
) : filteredTodos.length === 0 ? (
<div className="text-center py-8">
<div className="text-4xl mb-2"></div>
<p className="text-slate-400 text-sm">
{filter === 'all' ? '暂无待办事项' : filter === 'active' ? '太棒了,所有事都做完了!' : '还没有已完成的事项'}
</p>
</div>
) : (
filteredTodos.map(todo => (
<div
key={todo.id}
className={`flex items-center gap-3 p-3 rounded-xl transition group hover:bg-slate-50 ${todo.done ? 'opacity-60' : ''}`}
>
<input
type="checkbox"
checked={todo.done}
onChange={() => handleToggle(todo.id)}
className="w-4 h-4 rounded accent-blue-500 flex-shrink-0 cursor-pointer"
/>
<div className="flex-1 min-w-0">
<span className={`text-sm block ${todo.done ? 'line-through text-slate-400' : 'text-slate-700'}`}>
{todo.title}
</span>
{todo.due_date && (
<span className={`text-xs mt-0.5 block ${
todo.done ? 'text-slate-400' : isOverdue(todo.due_date) ? 'text-red-500 font-medium' : isDueToday(todo.due_date) ? 'text-amber-500 font-medium' : 'text-slate-400'
}`}>
📅 {formatDueDate(todo.due_date)}
</span>
)}
</div>
{priorityDot(todo.priority)}
<button
onClick={() => handleDelete(todo.id)}
className="text-slate-300 hover:text-red-400 transition text-xs opacity-0 group-hover:opacity-100"
>
</button>
</div>
))
)}
</div>
</div>
{/* 右侧:每日记录 */}
<div className="bg-white rounded-2xl shadow-sm border border-slate-100 p-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-bold text-slate-800">📓 </h2>
<div className="flex items-center gap-2">
{saved && <span className="text-green-500 text-xs animate-pulse"> </span>}
{saving && <span className="text-slate-400 text-xs">...</span>}
{date !== todayStr && (
<button
onClick={() => handleSave()}
className="px-3 py-1 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition text-xs font-medium"
>
</button>
)}
</div>
</div>
<div className="flex items-center gap-2 mb-4">
<input
type="date"
value={date}
onChange={e => { setDate(e.target.value); loadLog(e.target.value) }}
className="flex-1 px-3 py-2 border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 text-sm"
/>
</div>
{logLoading ? (
<div className="text-center text-slate-400 text-sm py-8">...</div>
) : (
<div className="space-y-4 max-h-[500px] overflow-y-auto">
<LogSection label="上午" icon="🌅" items={morningItems} onChange={setMorningItems} />
<LogSection label="下午" icon="☀️" items={afternoonItems} onChange={setAfternoonItems} />
<LogSection label="晚上" icon="🌙" items={eveningItems} onChange={setEveningItems} />
</div>
)}
</div>
</div>
</div>
)
}
+11
View File
@@ -0,0 +1,11 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": []
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': {
target: 'http://localhost:17010',
changeOrigin: true,
},
},
},
})