feat: 初始化孕育无忧全栈项目基础代码结构

完成项目初始搭建,包含后端FastAPI+MongoDB服务、前端React+Vite项目的完整基础结构,添加各类配置文件与依赖清单,涵盖核心业务初始框架。
This commit is contained in:
2026-05-21 00:46:48 +08:00
commit 409dabafb5
142 changed files with 31010 additions and 0 deletions

3
frontend/.dockerignore Normal file
View File

@@ -0,0 +1,3 @@
node_modules
dist
.git

30
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
# Dependencies
node_modules/
# Build output
dist/
*.tsbuildinfo
# Environment variables
.env
.env.local
.env.*.local
# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
# Claude Code
.claude/

View File

@@ -0,0 +1,256 @@
# 孕期健康检查报告解读应用 - 完整流程
## 📱 应用架构概览
本应用包含三个核心模块,共7个页面,完整覆盖从用户登录到AI报告解读的全流程。
---
## 🎯 模块一:登录与初始化
### 1. 登录页面 (LoginPage)
**路由:** `/`
**功能:**
- 支持微信、手机号、Apple ID 快捷登录
- 温馨的欢迎文案和视觉设计
- 隐私保护说明
**导航:**
- 登录成功后 → `/onboarding` (首次用户)
- 登录成功后 → `/home` (老用户)
---
### 2. 用户画像页面 (OnboardingPage)
**路由:** `/onboarding`
**功能:**
- 收集孕周信息(末次月经日期 / 直接输入孕周)
- 收集预产期
- 收集孕妈基本信息(年龄、身高、体重等)
- 情感化设计,温馨的引导文案
**导航:**
- 完成设置后 → `/home`
---
## 🎯 模块二:报告采集与录入
### 3. 首页 (HomePage)
**路由:** `/home`
**功能:**
- 显示当前孕周信息
- 快捷操作:拍照录入、趋势分析
- 报告列表展示(带三色预警标识)
- 孕期小贴士
- 浮动"+"按钮快速添加报告
**导航:**
- 点击"拍照录入"按钮 → `/camera`
- 点击浮动"+"按钮 → `/camera`
- 点击报告列表项 → `/analysis/:reportId`
---
### 4. OCR 拍照页面 (CameraCapturePage)
**路由:** `/camera`
**功能:**
- 实时相机预览
- 智能取景框引导
- 拍摄提示(光线、角度、防抖)
- AI OCR 识别提示
- 隐私自动脱敏说明
- 重拍/确认功能
- 相册导入选项
**导航:**
- 点击返回 → `/home`
- 确认拍照后 → `/review` (数据校对页面)
---
### 5. 数据校对页面 (DataVerificationPage)
**路由:** `/review` 或 `/verify`
**功能:**
- OCR识别结果展示
- 分类折叠展示(血液检查、激素水平等)
- Inline 编辑功能(点击即改)
- 三色预警标识(正常/注意/异常)
- 补充录入区域(自觉症状、备注)
- 错误提示和修正引导
- 隐私脱敏数据显示(姓名、身份证等)
**导航:**
- 点击返回 → `/camera`
- 点击"完成校对,生成解读" → `/analysis/:reportId`
---
## 🎯 模块三:AI 解读
### 6. AI 智能解读页面 (AIAnalysisPage)
**路由:** `/analysis/:reportId`
**功能:**
- 整体评估卡片(三色状态、综合风险评级)
- 分类详细解读
- 血液指标、激素水平等
- 每项指标包含:
- 术语白话化(如"血液中的'氧气快递员'")
- 通俗解释(这是什么?)
- 影响说明(对宝宝的影响)
- 行动建议(建议措施)
- 复查提醒
- 行动建议列表(优先级排序:高/中/低)
- 温馨提示
- 情感化文案("宝宝发育良好"而非"正常")
**导航:**
- 点击返回 → `/home`
- 点击"查看原始报告" → `/report/:reportId`
- 分享/下载功能
---
### 7. 报告详情页面 (ReportDetailPage)
**路由:** `/report/:reportId`
**功能:**
- 完整报告数据表格展示
- 原始检查数据
- 参考范围对比
- 历史趋势图表(如有)
- 打印/导出功能
**导航:**
- 点击返回 → `/analysis/:reportId`
- 点击"AI解读" → `/analysis/:reportId`
---
## 🔄 完整用户流程示例
### 新用户首次使用流程:
```
1. 打开应用 (/)
↓
2. 选择登录方式(微信/手机/Apple ID)
↓
3. 进入用户画像设置 (/onboarding)
- 输入孕周信息
- 输入个人信息
↓
4. 进入首页 (/home)
- 查看孕周卡片
- 浏览孕期小贴士
↓
5. 点击"拍照录入"或浮动"+" (/camera)
- 拍摄检查报告
- AI OCR 识别
↓
6. 数据校对 (/review)
- 检查识别结果
- 修正错误数据
- 补充症状信息
↓
7. 生成AI解读 (/analysis/1)
- 查看整体评估
- 阅读详细解读
- 了解行动建议
↓
8. (可选)查看原始报告 (/report/1)
- 查看完整数据表格
```
### 老用户日常使用流程:
```
1. 打开应用 (/)
↓
2. 自动登录跳转到首页 (/home)
↓
3. 查看历史报告列表
↓
4. 点击某个报告查看AI解读 (/analysis/1)
↓
5. 或添加新报告 (/camera)
```
---
## 📋 页面完整列表
| 页面 | 路由 | 所属模块 | 核心功能 |
|-----|------|---------|---------|
| LoginPage | `/` | 模块一 | 用户登录 |
| OnboardingPage | `/onboarding` | 模块一 | 用户画像创建 |
| HomePage | `/home` | 模块二 | 报告管理中心 |
| CameraCapturePage | `/camera` | 模块二 | OCR 拍照 |
| DataVerificationPage | `/review` | 模块二 | 数据校对 |
| AIAnalysisPage | `/analysis/:reportId` | 模块三 | AI 智能解读 |
| ReportDetailPage | `/report/:reportId` | 模块三 | 原始报告详情 |
---
## 🎨 情感化设计特色
1. **温和的视觉语言**
- 柔和的渐变色(粉色、紫色、蓝色)
- 圆角设计(rounded-2xl, rounded-3xl)
- 柔和的阴影效果
2. **关怀的文案**
- "宝宝发育良好" vs "正常值"
- "血液中的'氧气快递员'" vs "血红蛋白"
- "孕育无忧" vs "报告系统"
3. **三色预警系统**
- 🟢 绿色:正常,宝宝发育良好
- 🟠 橙色:需关注,有改善建议
- 🔴 红色:异常,需及时就医
4. **情感化图标**
- 💕 心形图标表达关爱
- 👶 宝宝图标增加亲近感
- 🎉 庆祝图标鼓励积极情绪
---
## 🔒 隐私保护
- 自动脱敏个人信息(姓名、身份证、电话等)
- 本地加密存储
- 数据传输安全提示
- 隐私保护说明文案
---
## 📱 技术栈
- **前端框架:** React + TypeScript
- **样式方案:** Tailwind CSS v4
- **路由管理:** React Router v7
- **动画库:** Motion (Framer Motion)
- **图标库:** Lucide React
- **UI 组件:** 自定义组件库
---
## 🚀 快速测试流程
1. 访问 `/` - 看到登录页面
2. 点击任意登录方式 - 跳转到 `/onboarding`
3. 填写用户信息 - 跳转到 `/home`
4. 点击"拍照录入" - 跳转到 `/camera`
5. 点击拍摄按钮 - 模拟拍照
6. 点击"确认使用" - 跳转到 `/review`
7. 检查数据并点击"完成校对" - 跳转到 `/analysis/1`
8. 查看AI解读 - 可点击"查看原始报告"跳转到 `/report/1`
---
**所有模块都已完整实现!** ✅

3
frontend/ATTRIBUTIONS.md Normal file
View File

@@ -0,0 +1,3 @@
This Figma Make file includes components from [shadcn/ui](https://ui.shadcn.com/) used under [MIT license](https://github.com/shadcn-ui/ui/blob/main/LICENSE.md).
This Figma Make file includes photos from [Unsplash](https://unsplash.com) used under [license](https://unsplash.com/license).

View File

@@ -0,0 +1,383 @@
# 🤰 孕期健康检查报告解读应用 - 完整功能列表
## 📊 应用概览
**总共 6 个核心模块 | 18 个完整页面 | 全流程闭环**
---
## 模块一:登录与初始化 ✅
### 1. 登录页面 (`/`)
- ✅ 微信、手机号、Apple ID 快捷登录
- ✅ 温馨的欢迎文案
- ✅ 隐私保护说明
### 2. 用户画像页面 (`/onboarding`)
- ✅ 收集孕周信息(末次月经 / 直接输入)
- ✅ 收集预产期
- ✅ 收集孕妈基本信息
- ✅ 情感化设计
---
## 模块二:报告采集与录入 ✅
### 3. 首页 (`/home`)
- ✅ 当前孕周信息卡片
- ✅ 快捷操作:拍照录入、健康档案、运动方案
- ✅ 报告列表(三色预警)
- ✅ 孕期小贴士
- ✅ 浮动"+"按钮
### 4. OCR 拍照页面 (`/camera`)
- ✅ 实时相机预览
- ✅ 智能取景框引导
- ✅ 拍摄提示(光线、角度、防抖)
- ✅ AI OCR 识别
- ✅ 隐私自动脱敏说明
- ✅ 重拍/确认功能
### 5. 数据校对页面 (`/review` 或 `/verify`)
- ✅ OCR 识别结果展示
- ✅ 分类折叠展示
- ✅ Inline 编辑功能
- ✅ 三色预警标识
- ✅ 补充录入区域
- ✅ 隐私脱敏显示
---
## 模块三:AI 解读 ✅
### 6. AI 智能解读页面 (`/analysis/:reportId`)
- ✅ 整体评估卡片
- ✅ 综合风险评级
- ✅ 分类详细解读(血液、激素等)
- ✅ 术语白话化(如"氧气快递员")
- ✅ 通俗解释(这是什么?)
- ✅ 影响说明(对宝宝的影响)
- ✅ 行动建议(优先级排序)
- ✅ 情感化文案
- ✅ **新增:深度服务入口**
- AI 对话追问
- 饮食建议
- 运动方案
- 问诊清单
- 专家复核
### 7. 报告详情页面 (`/report/:reportId`)
- ✅ 完整报告数据表格
- ✅ 原始检查数据
- ✅ 参考范围对比
- ✅ 打印/导出功能
---
## 🎯 模块四:AI 深度解读 ✅ **新增**
### 8. AI 对话追问页面 (`/chat/:reportId`)
**功能:**
- ✅ 对话式 AI 问答
- ✅ 针对报告具体指标提问
- ✅ 关联医学知识库回答
- ✅ 快捷提问建议
- ✅ 聊天记录保存
**特色:**
- 实时对话界面
- AI 打字效果
- 历史消息展示
---
### 9. AI 饮食建议页面 (`/nutrition/:reportId`)
**功能:**
- ✅ 基于报告定制食谱
- ✅ 详细食材清单
- ✅ 制作步骤说明
- ✅ 营养成分标注
- ✅ 一键收藏功能
- ✅ 饮食禁忌提醒
**特色:**
- 针对性推荐(如补铁食谱)
- 孕周适配
- 难度分级
- 时长预估
---
### 10. AI 运动建议页面 (`/exercise`)
**功能:**
- ✅ 适配孕周的运动方案
- ✅ 详细动作要领
- ✅ 运动益处说明
- ✅ 注意事项提醒
- ✅ 一键跟练
- ✅ 一键收藏
- ✅ 作息建议
**特色:**
- 运动 / 作息双标签
- 孕早期专属方案
- 强度分级(轻度/中度/高度)
- 每日作息时间表
---
## 📁 模块五:健康档案管理 ✅ **新增**
### 11. 健康档案主页 (`/health-records`)
**功能:**
- ✅ 四大功能入口
- 胎儿生长曲线
- 报告时间轴
- 产检日历
- 我的收藏
- ✅ 数据概览统计
- ✅ 最近活动展示
---
### 12. 胎儿生长曲线页面 (`/growth-curve`)
**功能:**
- ✅ 自动提取 B 超数据
- ✅ 生成发育曲线图(双顶径/腹围/股骨长)
- ✅ 对比标准曲线
- ✅ 正常范围区域显示
- ✅ 详细数据表格
- ✅ 分享/导出功能
**特色:**
- 使用 recharts 可视化
- 三个指标切换
- 趋势分析
- 评估结果
---
### 13. 报告时间轴页面 (`/timeline`)
**功能:**
- ✅ 按孕早/中/晚期分类
- ✅ 时间轴展示
- ✅ 搜索功能
- ✅ 筛选功能
- ✅ 统计数据(正常/关注/异常)
- ✅ 支持按指标搜索历史变化
**特色:**
- 可视化时间轴
- 月份分组
- 三色状态标识
- 快速跳转到解读页
---
### 14. 产检日历页面 (`/calendar`)
**功能:**
- ✅ 根据孕周推送下次产检项目
- ✅ 详细检查项目列表
- ✅ 注意事项(需空腹/需憋尿)
- ✅ 下次产检倒计时
- ✅ 设置提醒
- ✅ 添加到日历
**特色:**
- 完整孕期产检计划
- 重要度标识
- 响应时间提示
- 医生提示说明
---
### 15. 收藏清单页面 (`/favorites`)
**功能:**
- ✅ 查看收藏的食谱
- ✅ 查看收藏的运动
- ✅ 分类筛选(全部/食谱/运动)
- ✅ 取消收藏
- ✅ 快速跳转到详情
**特色:**
- 分类展示
- 收藏时间记录
- 一键跳转
- 空状态引导
---
## 🔧 模块六:辅助工具与闭环 ✅ **新增**
### 16. 问诊清单页面 (`/doctor-questions/:reportId`)
**功能:**
- ✅ 针对报告异常项生成 3-5 条问诊话术
- ✅ 优先级排序(重要/建议/了解)
- ✅ 一键复制单个问题
- ✅ 一键复制全部问题
- ✅ 问题原因说明
- ✅ 分享/导出 PDF
**特色:**
- AI 智能生成
- 就医沟通话术
- 避免紧张忘记
- 医学知识关联
---
### 17. 分享长图页面 (`/share/:reportId`)
**功能:**
- ✅ 生成不含隐私信息的解读长图
- ✅ 隐私模式开关
- ✅ 包含详细数据开关
- ✅ 实时预览
- ✅ 生成长图
- ✅ 下载图片
- ✅ 分享到微信
**特色:**
- 加密长图
- 自动脱敏
- 美观设计
- 适合社交分享
---
### 18. 专家复核页面 (`/expert-consultation`)
**功能:**
- ✅ 真人医生付费解读入口
- ✅ 三甲医院主任医师
- ✅ 多种咨询方式
- 图文咨询(¥50,24 小时回复)
- 视频问诊(¥200,预约时间)
- 加急咨询(¥100,2 小时回复)
- ✅ 医生列表展示
- ✅ 医生评分/评价数
- ✅ 响应时间显示
- ✅ 立即咨询
**特色:**
- AI 无法判定的复杂情况
- 专业医生一对一
- 价格透明
- 咨询流程说明
---
## 🎨 设计亮点
### 情感化设计
- ✅ 温和的视觉语言(柔和渐变、圆角设计)
- ✅ 关怀的文案("宝宝发育良好" vs "正常值")
- ✅ 三色预警系统(绿色/橙色/红色)
- ✅ 情感化图标(❤️💕👶🎉)
### 交互体验
- ✅ 流畅的动画效果(Motion)
- ✅ Inline 编辑
- ✅ 分类折叠展示
- ✅ 渐进式信息披露
- ✅ 一键收藏/跟练
- ✅ 快捷复制
### 隐私保护
- ✅ 自动脱敏(姓名、身份证、电话)
- ✅ 本地加密存储
- ✅ 数据传输安全提示
- ✅ 分享隐私模式
---
## 🚀 技术栈
- **前端框架:** React + TypeScript
- **样式方案:** Tailwind CSS v4
- **路由管理:** React Router v7
- **动画库:** Motion (Framer Motion)
- **图表库:** Recharts
- **图标库:** Lucide React
- **UI 组件:** 自定义组件库(Radix UI)
---
## 📱 完整用户流程
```
登录 (/)
↓
用户画像 (/onboarding)
↓
首页 (/home)
↓
【场景 1:添加新报告】
拍照 (/camera) → 数据校对 (/review) → AI 解读 (/analysis/1)
↓
【场景 2:深度解读】
AI 对话追问 (/chat/1)
饮食建议 (/nutrition/1)
运动方案 (/exercise)
问诊清单 (/doctor-questions/1)
↓
【场景 3:健康管理】
健康档案 (/health-records)
├─ 生长曲线 (/growth-curve)
├─ 报告时间轴 (/timeline)
├─ 产检日历 (/calendar)
└─ 收藏清单 (/favorites)
↓
【场景 4:分享与咨询】
分享长图 (/share/1)
专家复核 (/expert-consultation)
```
---
## 🎯 核心创新点
1. **情感化设计贯穿始终**
- 温和的色彩、圆角设计
- 白话化术语、关怀文案
- 缓解孕妈焦虑感
2. **AI + 真人医生闭环**
- AI 快速解读
- 复杂情况转真人医生
- 完整的就医准备(问诊清单)
3. **深度交互体验**
- OCR 高效修改流程
- AI 对话式追问
- 一键收藏/跟练
- 渐进式信息披露
4. **数据可视化**
- 胎儿生长曲线
- 报告时间轴
- 趋势分析
- 产检日历
5. **个性化服务**
- 基于报告的饮食建议
- 适配孕周的运动方案
- 针对性问诊话术
- 定制化 AI 解读
---
## 📝 待优化项(未来迭代)
- [ ] 接入真实 OCR API
- [ ] 接入真实 AI 模型
- [ ] 接入真实医生咨询平台
- [ ] 数据持久化(Supabase)
- [ ] 消息推送功能
- [ ] 社区功能(孕妈交流)
- [ ] 多语言支持
- [ ] 深色模式
---
**当前状态:** ✅ **所有 6 个模块、18 个页面全部完成!**
**测试入口:** 访问 `/dev` 页面查看完整导航

20
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,20 @@
# Build stage
FROM node:20-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
# Serve stage
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
# nginx config will be mounted via docker-compose
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

11
frontend/README.md Normal file
View File

@@ -0,0 +1,11 @@
# Untitled
This is a code bundle for Untitled. The original project is available at https://www.figma.com/design/8RgbYsTPkWPmXG6cEdfzSj/Untitled.
## Running the code
Run `npm i` to install the dependencies.
Run `npm run dev` to start the development server.

View File

@@ -0,0 +1,61 @@
**Add your own guidelines here**
<!--
System Guidelines
Use this file to provide the AI with rules and guidelines you want it to follow.
This template outlines a few examples of things you can add. You can add your own sections and format it to suit your needs
TIP: More context isn't always better. It can confuse the LLM. Try and add the most important rules you need
# General guidelines
Any general rules you want the AI to follow.
For example:
* Only use absolute positioning when necessary. Opt for responsive and well structured layouts that use flexbox and grid by default
* Refactor code as you go to keep code clean
* Keep file sizes small and put helper functions and components in their own files.
--------------
# Design system guidelines
Rules for how the AI should make generations look like your company's design system
Additionally, if you select a design system to use in the prompt box, you can reference
your design system's components, tokens, variables and components.
For example:
* Use a base font-size of 14px
* Date formats should always be in the format “Jun 10”
* The bottom toolbar should only ever have a maximum of 4 items
* Never use the floating action button with the bottom toolbar
* Chips should always come in sets of 3 or more
* Don't use a dropdown if there are 2 or fewer options
You can also create sub sections and add more specific details
For example:
## Button
The Button component is a fundamental interactive element in our design system, designed to trigger actions or navigate
users through the application. It provides visual feedback and clear affordances to enhance user experience.
### Usage
Buttons should be used for important actions that users need to take, such as form submissions, confirming choices,
or initiating processes. They communicate interactivity and should have clear, action-oriented labels.
### Variants
* Primary Button
* Purpose : Used for the main action in a section or page
* Visual Style : Bold, filled with the primary brand color
* Usage : One primary button per section to guide users toward the most important action
* Secondary Button
* Purpose : Used for alternative or supporting actions
* Visual Style : Outlined with the primary color, transparent background
* Usage : Can appear alongside a primary button for less important actions
* Tertiary Button
* Purpose : Used for the least important actions
* Visual Style : Text-only with no border, using primary color
* Usage : For actions that should be available but not emphasized
-->

16
frontend/index.html Normal file
View File

@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="zh-CN" translate="no">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<meta name="google" content="notranslate" />
<title>孕育无忧</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

5517
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

91
frontend/package.json Normal file
View File

@@ -0,0 +1,91 @@
{
"name": "@figma/my-make-file",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"dependencies": {
"@emotion/react": "11.14.0",
"@emotion/styled": "11.14.1",
"@mui/icons-material": "7.3.5",
"@mui/material": "7.3.5",
"@popperjs/core": "2.11.8",
"@radix-ui/react-accordion": "1.2.3",
"@radix-ui/react-alert-dialog": "1.1.6",
"@radix-ui/react-aspect-ratio": "1.1.2",
"@radix-ui/react-avatar": "1.1.3",
"@radix-ui/react-checkbox": "1.1.4",
"@radix-ui/react-collapsible": "1.1.3",
"@radix-ui/react-context-menu": "2.2.6",
"@radix-ui/react-dialog": "1.1.6",
"@radix-ui/react-dropdown-menu": "2.1.6",
"@radix-ui/react-hover-card": "1.1.6",
"@radix-ui/react-label": "2.1.2",
"@radix-ui/react-menubar": "1.1.6",
"@radix-ui/react-navigation-menu": "1.2.5",
"@radix-ui/react-popover": "1.1.6",
"@radix-ui/react-progress": "1.1.2",
"@radix-ui/react-radio-group": "1.2.3",
"@radix-ui/react-scroll-area": "1.2.3",
"@radix-ui/react-select": "2.1.6",
"@radix-ui/react-separator": "1.1.2",
"@radix-ui/react-slider": "1.2.3",
"@radix-ui/react-slot": "1.1.2",
"@radix-ui/react-switch": "1.1.3",
"@radix-ui/react-tabs": "1.1.3",
"@radix-ui/react-toggle": "1.1.2",
"@radix-ui/react-toggle-group": "1.1.2",
"@radix-ui/react-tooltip": "1.1.8",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",
"cmdk": "1.1.1",
"date-fns": "3.6.0",
"embla-carousel-react": "8.6.0",
"html-to-image": "^1.11.13",
"input-otp": "1.4.2",
"lucide-react": "0.487.0",
"motion": "12.23.24",
"next-themes": "0.4.6",
"react-day-picker": "8.10.1",
"react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1",
"react-hook-form": "7.55.0",
"react-popper": "2.3.0",
"react-resizable-panels": "2.1.7",
"react-responsive-masonry": "2.7.1",
"react-router": "7.13.0",
"react-slick": "0.31.0",
"recharts": "2.15.2",
"sonner": "2.0.3",
"tailwind-merge": "3.2.0",
"tw-animate-css": "1.3.8",
"vaul": "1.1.2"
},
"devDependencies": {
"@tailwindcss/vite": "4.1.12",
"@vitejs/plugin-basic-ssl": "^2.2.0",
"@vitejs/plugin-react": "4.7.0",
"tailwindcss": "4.1.12",
"vite": "6.3.5"
},
"peerDependencies": {
"react": "18.3.1",
"react-dom": "18.3.1"
},
"peerDependenciesMeta": {
"react": {
"optional": true
},
"react-dom": {
"optional": true
}
},
"pnpm": {
"overrides": {
"vite": "6.3.5"
}
}
}

4304
frontend/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,15 @@
/**
* PostCSS Configuration
*
* Tailwind CSS v4 (via @tailwindcss/vite) automatically sets up all required
* PostCSS plugins — you do NOT need to include `tailwindcss` or `autoprefixer` here.
*
* This file only exists for adding additional PostCSS plugins, if needed.
* For example:
*
* import postcssNested from 'postcss-nested'
* export default { plugins: [postcssNested()] }
*
* Otherwise, you can leave this file empty.
*/
export default {}

16
frontend/src/app/App.tsx Normal file
View File

@@ -0,0 +1,16 @@
import { RouterProvider } from "react-router";
import { router } from "./routes";
import { Toaster } from "./components/ui/sonner";
import { UserProvider } from "./context/UserContext";
import { ErrorBoundary } from "./components/ErrorBoundary";
export default function App() {
return (
<ErrorBoundary>
<UserProvider>
<RouterProvider router={router} />
<Toaster position="top-center" />
</UserProvider>
</ErrorBoundary>
);
}

View File

@@ -0,0 +1,44 @@
import { Component, type ReactNode } from "react";
interface Props {
children: ReactNode;
}
interface State {
hasError: boolean;
}
export class ErrorBoundary extends Component<Props, State> {
state: State = { hasError: false };
static getDerivedStateFromError(): State {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return (
<div style={{ padding: 32, textAlign: "center" }}>
<p style={{ fontSize: 18, marginBottom: 16 }}>页面加载出错了</p>
<button
onClick={() => {
this.setState({ hasError: false });
window.location.reload();
}}
style={{
padding: "10px 24px",
borderRadius: 12,
border: "none",
background: "#b5a89a",
color: "#fff",
fontSize: 16,
}}
>
刷新重试
</button>
</div>
);
}
return this.props.children;
}
}

View File

@@ -0,0 +1,15 @@
import { Outlet } from "react-router";
/**
* H5 移动端全局布局容器
* - max-w-md (448px) 限制最大宽度,大屏居中显示
* - min-h-dvh 使用动态视口高度,解决 Safari 地址栏问题
* - safe-area padding 适配刘海屏/底部手势条
*/
export function MobileLayout() {
return (
<div className="max-w-md mx-auto min-h-dvh relative bg-morandi-50 shadow-[0_0_40px_rgba(0,0,0,0.06)]">
<Outlet />
</div>
);
}

View File

@@ -0,0 +1,27 @@
import React, { useState } from 'react'
const ERROR_IMG_SRC =
'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODgiIGhlaWdodD0iODgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgc3Ryb2tlPSIjMDAwIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBvcGFjaXR5PSIuMyIgZmlsbD0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIzLjciPjxyZWN0IHg9IjE2IiB5PSIxNiIgd2lkdGg9IjU2IiBoZWlnaHQ9IjU2IiByeD0iNiIvPjxwYXRoIGQ9Im0xNiA1OCAxNi0xOCAzMiAzMiIvPjxjaXJjbGUgY3g9IjUzIiBjeT0iMzUiIHI9IjciLz48L3N2Zz4KCg=='
export function ImageWithFallback(props: React.ImgHTMLAttributes<HTMLImageElement>) {
const [didError, setDidError] = useState(false)
const handleError = () => {
setDidError(true)
}
const { src, alt, style, className, ...rest } = props
return didError ? (
<div
className={`inline-block bg-gray-100 text-center align-middle ${className ?? ''}`}
style={style}
>
<div className="flex items-center justify-center w-full h-full">
<img src={ERROR_IMG_SRC} alt="Error loading image" {...rest} data-original-url={src} />
</div>
</div>
) : (
<img src={src} alt={alt} className={className} style={style} {...rest} onError={handleError} />
)
}

View File

@@ -0,0 +1,66 @@
"use client";
import * as React from "react";
import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { ChevronDownIcon } from "lucide-react";
import { cn } from "./utils";
function Accordion({
...props
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />;
}
function AccordionItem({
className,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("border-b last:border-b-0", className)}
{...props}
/>
);
}
function AccordionTrigger({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
className,
)}
{...props}
>
{children}
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
);
}
function AccordionContent({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
{...props}
>
<div className={cn("pt-0 pb-4", className)}>{children}</div>
</AccordionPrimitive.Content>
);
}
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };

View File

@@ -0,0 +1,157 @@
"use client";
import * as React from "react";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import { cn } from "./utils";
import { buttonVariants } from "./button";
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
);
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
);
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
);
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
);
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
);
}
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
);
}
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};

View File

@@ -0,0 +1,66 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "./utils";
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
},
},
defaultVariants: {
variant: "default",
},
},
);
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
);
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className,
)}
{...props}
/>
);
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
className,
)}
{...props}
/>
);
}
export { Alert, AlertTitle, AlertDescription };

View File

@@ -0,0 +1,11 @@
"use client";
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
function AspectRatio({
...props
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />;
}
export { AspectRatio };

View File

@@ -0,0 +1,53 @@
"use client";
import * as React from "react";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
import { cn } from "./utils";
function Avatar({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn(
"relative flex size-10 shrink-0 overflow-hidden rounded-full",
className,
)}
{...props}
/>
);
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
);
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted flex size-full items-center justify-center rounded-full",
className,
)}
{...props}
/>
);
}
export { Avatar, AvatarImage, AvatarFallback };

View File

@@ -0,0 +1,46 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "./utils";
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span";
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,109 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { ChevronRight, MoreHorizontal } from "lucide-react";
import { cn } from "./utils";
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />;
}
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
return (
<ol
data-slot="breadcrumb-list"
className={cn(
"text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
className,
)}
{...props}
/>
);
}
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-item"
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
);
}
function BreadcrumbLink({
asChild,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean;
}) {
const Comp = asChild ? Slot : "a";
return (
<Comp
data-slot="breadcrumb-link"
className={cn("hover:text-foreground transition-colors", className)}
{...props}
/>
);
}
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-page"
role="link"
aria-disabled="true"
aria-current="page"
className={cn("text-foreground font-normal", className)}
{...props}
/>
);
}
function BreadcrumbSeparator({
children,
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-separator"
role="presentation"
aria-hidden="true"
className={cn("[&>svg]:size-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
);
}
function BreadcrumbEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-ellipsis"
role="presentation"
aria-hidden="true"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="size-4" />
<span className="sr-only">More</span>
</span>
);
}
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
};

View File

@@ -0,0 +1,58 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "./utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background text-foreground hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9 rounded-md",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean;
}) {
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Button, buttonVariants };

View File

@@ -0,0 +1,75 @@
"use client";
import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "./utils";
import { buttonVariants } from "./button";
function Calendar({
className,
classNames,
showOutsideDays = true,
...props
}: React.ComponentProps<typeof DayPicker>) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn("p-3", className)}
classNames={{
months: "flex flex-col sm:flex-row gap-2",
month: "flex flex-col gap-4",
caption: "flex justify-center pt-1 relative items-center w-full",
caption_label: "text-sm font-medium",
nav: "flex items-center gap-1",
nav_button: cn(
buttonVariants({ variant: "outline" }),
"size-7 bg-transparent p-0 opacity-50 hover:opacity-100",
),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-x-1",
head_row: "flex",
head_cell:
"text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: cn(
"relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-range-end)]:rounded-r-md",
props.mode === "range"
? "[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md"
: "[&:has([aria-selected])]:rounded-md",
),
day: cn(
buttonVariants({ variant: "ghost" }),
"size-8 p-0 font-normal aria-selected:opacity-100",
),
day_range_start:
"day-range-start aria-selected:bg-primary aria-selected:text-primary-foreground",
day_range_end:
"day-range-end aria-selected:bg-primary aria-selected:text-primary-foreground",
day_selected:
"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
day_today: "bg-accent text-accent-foreground",
day_outside:
"day-outside text-muted-foreground aria-selected:text-muted-foreground",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle:
"aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",
...classNames,
}}
components={{
IconLeft: ({ className, ...props }) => (
<ChevronLeft className={cn("size-4", className)} {...props} />
),
IconRight: ({ className, ...props }) => (
<ChevronRight className={cn("size-4", className)} {...props} />
),
}}
{...props}
/>
);
}
export { Calendar };

View File

@@ -0,0 +1,92 @@
import * as React from "react";
import { cn } from "./utils";
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",
className,
)}
{...props}
/>
);
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className,
)}
{...props}
/>
);
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<h4
data-slot="card-title"
className={cn("leading-none", className)}
{...props}
/>
);
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<p
data-slot="card-description"
className={cn("text-muted-foreground", className)}
{...props}
/>
);
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className,
)}
{...props}
/>
);
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6 [&:last-child]:pb-6", className)}
{...props}
/>
);
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 pb-6 [.border-t]:pt-6", className)}
{...props}
/>
);
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
};

View File

@@ -0,0 +1,241 @@
"use client";
import * as React from "react";
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from "embla-carousel-react";
import { ArrowLeft, ArrowRight } from "lucide-react";
import { cn } from "./utils";
import { Button } from "./button";
type CarouselApi = UseEmblaCarouselType[1];
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>;
type CarouselOptions = UseCarouselParameters[0];
type CarouselPlugin = UseCarouselParameters[1];
type CarouselProps = {
opts?: CarouselOptions;
plugins?: CarouselPlugin;
orientation?: "horizontal" | "vertical";
setApi?: (api: CarouselApi) => void;
};
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0];
api: ReturnType<typeof useEmblaCarousel>[1];
scrollPrev: () => void;
scrollNext: () => void;
canScrollPrev: boolean;
canScrollNext: boolean;
} & CarouselProps;
const CarouselContext = React.createContext<CarouselContextProps | null>(null);
function useCarousel() {
const context = React.useContext(CarouselContext);
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />");
}
return context;
}
function Carousel({
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
}: React.ComponentProps<"div"> & CarouselProps) {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins,
);
const [canScrollPrev, setCanScrollPrev] = React.useState(false);
const [canScrollNext, setCanScrollNext] = React.useState(false);
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) return;
setCanScrollPrev(api.canScrollPrev());
setCanScrollNext(api.canScrollNext());
}, []);
const scrollPrev = React.useCallback(() => {
api?.scrollPrev();
}, [api]);
const scrollNext = React.useCallback(() => {
api?.scrollNext();
}, [api]);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
scrollPrev();
} else if (event.key === "ArrowRight") {
event.preventDefault();
scrollNext();
}
},
[scrollPrev, scrollNext],
);
React.useEffect(() => {
if (!api || !setApi) return;
setApi(api);
}, [api, setApi]);
React.useEffect(() => {
if (!api) return;
onSelect(api);
api.on("reInit", onSelect);
api.on("select", onSelect);
return () => {
api?.off("select", onSelect);
};
}, [api, onSelect]);
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation:
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
data-slot="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
);
}
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
const { carouselRef, orientation } = useCarousel();
return (
<div
ref={carouselRef}
className="overflow-hidden"
data-slot="carousel-content"
>
<div
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className,
)}
{...props}
/>
</div>
);
}
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
const { orientation } = useCarousel();
return (
<div
role="group"
aria-roledescription="slide"
data-slot="carousel-item"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className,
)}
{...props}
/>
);
}
function CarouselPrevious({
className,
variant = "outline",
size = "icon",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
data-slot="carousel-previous"
variant={variant}
size={size}
className={cn(
"absolute size-8 rounded-full",
orientation === "horizontal"
? "top-1/2 -left-12 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft />
<span className="sr-only">Previous slide</span>
</Button>
);
}
function CarouselNext({
className,
variant = "outline",
size = "icon",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
data-slot="carousel-next"
variant={variant}
size={size}
className={cn(
"absolute size-8 rounded-full",
orientation === "horizontal"
? "top-1/2 -right-12 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight />
<span className="sr-only">Next slide</span>
</Button>
);
}
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
};

View File

@@ -0,0 +1,353 @@
"use client";
import * as React from "react";
import * as RechartsPrimitive from "recharts";
import { cn } from "./utils";
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const;
export type ChartConfig = {
[k in string]: {
label?: React.ReactNode;
icon?: React.ComponentType;
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
);
};
type ChartContextProps = {
config: ChartConfig;
};
const ChartContext = React.createContext<ChartContextProps | null>(null);
function useChart() {
const context = React.useContext(ChartContext);
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />");
}
return context;
}
function ChartContainer({
id,
className,
children,
config,
...props
}: React.ComponentProps<"div"> & {
config: ChartConfig;
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>["children"];
}) {
const uniqueId = React.useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`;
return (
<ChartContext.Provider value={{ config }}>
<div
data-slot="chart"
data-chart={chartId}
className={cn(
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className,
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
);
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme || config.color,
);
if (!colorConfig.length) {
return null;
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
itemConfig.color;
return color ? ` --color-${key}: ${color};` : null;
})
.join("\n")}
}
`,
)
.join("\n"),
}}
/>
);
};
const ChartTooltip = RechartsPrimitive.Tooltip;
function ChartTooltipContent({
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean;
hideIndicator?: boolean;
indicator?: "line" | "dot" | "dashed";
nameKey?: string;
labelKey?: string;
}) {
const { config } = useChart();
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null;
}
const [item] = payload;
const key = `${labelKey || item?.dataKey || item?.name || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const value =
!labelKey && typeof label === "string"
? config[label as keyof typeof config]?.label || label
: itemConfig?.label;
if (labelFormatter) {
return (
<div className={cn("font-medium", labelClassName)}>
{labelFormatter(value, payload)}
</div>
);
}
if (!value) {
return null;
}
return <div className={cn("font-medium", labelClassName)}>{value}</div>;
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
]);
if (!active || !payload?.length) {
return null;
}
const nestLabel = payload.length === 1 && indicator !== "dot";
return (
<div
className={cn(
"border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",
className,
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const indicatorColor = color || item.payload.fill || item.color;
return (
<div
key={item.dataKey}
className={cn(
"[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
indicator === "dot" && "items-center",
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
{
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
},
)}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
"flex flex-1 justify-between leading-none",
nestLabel ? "items-end" : "items-center",
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label || item.name}
</span>
</div>
{item.value && (
<span className="text-foreground font-mono font-medium tabular-nums">
{item.value.toLocaleString()}
</span>
)}
</div>
</>
)}
</div>
);
})}
</div>
</div>
);
}
const ChartLegend = RechartsPrimitive.Legend;
function ChartLegendContent({
className,
hideIcon = false,
payload,
verticalAlign = "bottom",
nameKey,
}: React.ComponentProps<"div"> &
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
hideIcon?: boolean;
nameKey?: string;
}) {
const { config } = useChart();
if (!payload?.length) {
return null;
}
return (
<div
className={cn(
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className,
)}
>
{payload.map((item) => {
const key = `${nameKey || item.dataKey || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
return (
<div
key={item.value}
className={cn(
"[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3",
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
);
})}
</div>
);
}
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string,
) {
if (typeof payload !== "object" || payload === null) {
return undefined;
}
const payloadPayload =
"payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined;
let configLabelKey: string = key;
if (
key in payload &&
typeof payload[key as keyof typeof payload] === "string"
) {
configLabelKey = payload[key as keyof typeof payload] as string;
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string;
}
return configLabelKey in config
? config[configLabelKey]
: config[key as keyof typeof config];
}
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
ChartStyle,
};

View File

@@ -0,0 +1,32 @@
"use client";
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { CheckIcon } from "lucide-react";
import { cn } from "./utils";
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer border bg-input-background dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="flex items-center justify-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
);
}
export { Checkbox };

View File

@@ -0,0 +1,33 @@
"use client";
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
function Collapsible({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;
}
function CollapsibleTrigger({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return (
<CollapsiblePrimitive.CollapsibleTrigger
data-slot="collapsible-trigger"
{...props}
/>
);
}
function CollapsibleContent({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return (
<CollapsiblePrimitive.CollapsibleContent
data-slot="collapsible-content"
{...props}
/>
);
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent };

View File

@@ -0,0 +1,177 @@
"use client";
import * as React from "react";
import { Command as CommandPrimitive } from "cmdk";
import { SearchIcon } from "lucide-react";
import { cn } from "./utils";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "./dialog";
function Command({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
className,
)}
{...props}
/>
);
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string;
description?: string;
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent className="overflow-hidden p-0">
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
);
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
/>
</div>
);
}
function CommandList({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className,
)}
{...props}
/>
);
}
function CommandEmpty({
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
);
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
className,
)}
{...props}
/>
);
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn("bg-border -mx-1 h-px", className)}
{...props}
/>
);
}
function CommandItem({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function CommandShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="command-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props}
/>
);
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
};

View File

@@ -0,0 +1,252 @@
"use client";
import * as React from "react";
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "./utils";
function ContextMenu({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />;
}
function ContextMenuTrigger({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
return (
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
);
}
function ContextMenuGroup({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
return (
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
);
}
function ContextMenuPortal({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
return (
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
);
}
function ContextMenuSub({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />;
}
function ContextMenuRadioGroup({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
return (
<ContextMenuPrimitive.RadioGroup
data-slot="context-menu-radio-group"
{...props}
/>
);
}
function ContextMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean;
}) {
return (
<ContextMenuPrimitive.SubTrigger
data-slot="context-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</ContextMenuPrimitive.SubTrigger>
);
}
function ContextMenuSubContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
return (
<ContextMenuPrimitive.SubContent
data-slot="context-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className,
)}
{...props}
/>
);
}
function ContextMenuContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
return (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
data-slot="context-menu-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className,
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
);
}
function ContextMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<ContextMenuPrimitive.Item
data-slot="context-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function ContextMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
return (
<ContextMenuPrimitive.CheckboxItem
data-slot="context-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
);
}
function ContextMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
return (
<ContextMenuPrimitive.RadioItem
data-slot="context-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
);
}
function ContextMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
inset?: boolean;
}) {
return (
<ContextMenuPrimitive.Label
data-slot="context-menu-label"
data-inset={inset}
className={cn(
"text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className,
)}
{...props}
/>
);
}
function ContextMenuSeparator({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
return (
<ContextMenuPrimitive.Separator
data-slot="context-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
);
}
function ContextMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="context-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props}
/>
);
}
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
};

View File

@@ -0,0 +1,135 @@
"use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { XIcon } from "lucide-react";
import { cn } from "./utils";
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function DialogContent({
className,
children,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className,
)}
{...props}
>
{children}
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
);
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
};

View File

@@ -0,0 +1,132 @@
"use client";
import * as React from "react";
import { Drawer as DrawerPrimitive } from "vaul";
import { cn } from "./utils";
function Drawer({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
return <DrawerPrimitive.Root data-slot="drawer" {...props} />;
}
function DrawerTrigger({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />;
}
function DrawerPortal({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />;
}
function DrawerClose({
...props
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />;
}
function DrawerOverlay({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
return (
<DrawerPrimitive.Overlay
data-slot="drawer-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function DrawerContent({
className,
children,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
return (
<DrawerPortal data-slot="drawer-portal">
<DrawerOverlay />
<DrawerPrimitive.Content
data-slot="drawer-content"
className={cn(
"group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
className,
)}
{...props}
>
<div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
);
}
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
);
}
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="drawer-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
);
}
function DrawerTitle({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
return (
<DrawerPrimitive.Title
data-slot="drawer-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
);
}
function DrawerDescription({
className,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
return (
<DrawerPrimitive.Description
data-slot="drawer-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
};

View File

@@ -0,0 +1,257 @@
"use client";
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "./utils";
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
);
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
);
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
);
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
);
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
);
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
);
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
);
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className,
)}
{...props}
/>
);
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
);
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props}
/>
);
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
);
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className,
)}
{...props}
/>
);
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
};

View File

@@ -0,0 +1,168 @@
"use client";
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { Slot } from "@radix-ui/react-slot";
import {
Controller,
FormProvider,
useFormContext,
useFormState,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form";
import { cn } from "./utils";
import { Label } from "./label";
const Form = FormProvider;
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName;
};
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue,
);
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
);
};
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState } = useFormContext();
const formState = useFormState({ name: fieldContext.name });
const fieldState = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>");
}
const { id } = itemContext;
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
};
};
type FormItemContextValue = {
id: string;
};
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue,
);
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div
data-slot="form-item"
className={cn("grid gap-2", className)}
{...props}
/>
</FormItemContext.Provider>
);
}
function FormLabel({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
const { error, formItemId } = useFormField();
return (
<Label
data-slot="form-label"
data-error={!!error}
className={cn("data-[error=true]:text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
);
}
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
const { error, formItemId, formDescriptionId, formMessageId } =
useFormField();
return (
<Slot
data-slot="form-control"
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
);
}
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
const { formDescriptionId } = useFormField();
return (
<p
data-slot="form-description"
id={formDescriptionId}
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message ?? "") : props.children;
if (!body) {
return null;
}
return (
<p
data-slot="form-message"
id={formMessageId}
className={cn("text-destructive text-sm", className)}
{...props}
>
{body}
</p>
);
}
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
};

View File

@@ -0,0 +1,44 @@
"use client";
import * as React from "react";
import * as HoverCardPrimitive from "@radix-ui/react-hover-card";
import { cn } from "./utils";
function HoverCard({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />;
}
function HoverCardTrigger({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
return (
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
);
}
function HoverCardContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
return (
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
<HoverCardPrimitive.Content
data-slot="hover-card-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className,
)}
{...props}
/>
</HoverCardPrimitive.Portal>
);
}
export { HoverCard, HoverCardTrigger, HoverCardContent };

View File

@@ -0,0 +1,77 @@
"use client";
import * as React from "react";
import { OTPInput, OTPInputContext } from "input-otp";
import { MinusIcon } from "lucide-react";
import { cn } from "./utils";
function InputOTP({
className,
containerClassName,
...props
}: React.ComponentProps<typeof OTPInput> & {
containerClassName?: string;
}) {
return (
<OTPInput
data-slot="input-otp"
containerClassName={cn(
"flex items-center gap-2 has-disabled:opacity-50",
containerClassName,
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
);
}
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="input-otp-group"
className={cn("flex items-center gap-1", className)}
{...props}
/>
);
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<"div"> & {
index: number;
}) {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {};
return (
<div
data-slot="input-otp-slot"
data-active={isActive}
className={cn(
"data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm bg-input-background transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",
className,
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
</div>
)}
</div>
);
}
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
return (
<div data-slot="input-otp-separator" role="separator" {...props}>
<MinusIcon />
</div>
);
}
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };

View File

@@ -0,0 +1,21 @@
import * as React from "react";
import { cn } from "./utils";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className,
)}
{...props}
/>
);
}
export { Input };

View File

@@ -0,0 +1,24 @@
"use client";
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cn } from "./utils";
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className,
)}
{...props}
/>
);
}
export { Label };

View File

@@ -0,0 +1,276 @@
"use client";
import * as React from "react";
import * as MenubarPrimitive from "@radix-ui/react-menubar";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "./utils";
function Menubar({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
return (
<MenubarPrimitive.Root
data-slot="menubar"
className={cn(
"bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs",
className,
)}
{...props}
/>
);
}
function MenubarMenu({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />;
}
function MenubarGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />;
}
function MenubarPortal({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />;
}
function MenubarRadioGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
return (
<MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
);
}
function MenubarTrigger({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
return (
<MenubarPrimitive.Trigger
data-slot="menubar-trigger"
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none",
className,
)}
{...props}
/>
);
}
function MenubarContent({
className,
align = "start",
alignOffset = -4,
sideOffset = 8,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
return (
<MenubarPortal>
<MenubarPrimitive.Content
data-slot="menubar-content"
align={align}
alignOffset={alignOffset}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md",
className,
)}
{...props}
/>
</MenubarPortal>
);
}
function MenubarItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<MenubarPrimitive.Item
data-slot="menubar-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function MenubarCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem>) {
return (
<MenubarPrimitive.CheckboxItem
data-slot="menubar-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.CheckboxItem>
);
}
function MenubarRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof MenubarPrimitive.RadioItem>) {
return (
<MenubarPrimitive.RadioItem
data-slot="menubar-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.RadioItem>
);
}
function MenubarLabel({
className,
inset,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
inset?: boolean;
}) {
return (
<MenubarPrimitive.Label
data-slot="menubar-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className,
)}
{...props}
/>
);
}
function MenubarSeparator({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
return (
<MenubarPrimitive.Separator
data-slot="menubar-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
);
}
function MenubarShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="menubar-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className,
)}
{...props}
/>
);
}
function MenubarSub({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />;
}
function MenubarSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
inset?: boolean;
}) {
return (
<MenubarPrimitive.SubTrigger
data-slot="menubar-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto h-4 w-4" />
</MenubarPrimitive.SubTrigger>
);
}
function MenubarSubContent({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
return (
<MenubarPrimitive.SubContent
data-slot="menubar-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className,
)}
{...props}
/>
);
}
export {
Menubar,
MenubarPortal,
MenubarMenu,
MenubarTrigger,
MenubarContent,
MenubarGroup,
MenubarSeparator,
MenubarLabel,
MenubarItem,
MenubarShortcut,
MenubarCheckboxItem,
MenubarRadioGroup,
MenubarRadioItem,
MenubarSub,
MenubarSubTrigger,
MenubarSubContent,
};

View File

@@ -0,0 +1,168 @@
import * as React from "react";
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu";
import { cva } from "class-variance-authority";
import { ChevronDownIcon } from "lucide-react";
import { cn } from "./utils";
function NavigationMenu({
className,
children,
viewport = true,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Root> & {
viewport?: boolean;
}) {
return (
<NavigationMenuPrimitive.Root
data-slot="navigation-menu"
data-viewport={viewport}
className={cn(
"group/navigation-menu relative flex max-w-max flex-1 items-center justify-center",
className,
)}
{...props}
>
{children}
{viewport && <NavigationMenuViewport />}
</NavigationMenuPrimitive.Root>
);
}
function NavigationMenuList({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.List>) {
return (
<NavigationMenuPrimitive.List
data-slot="navigation-menu-list"
className={cn(
"group flex flex-1 list-none items-center justify-center gap-1",
className,
)}
{...props}
/>
);
}
function NavigationMenuItem({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Item>) {
return (
<NavigationMenuPrimitive.Item
data-slot="navigation-menu-item"
className={cn("relative", className)}
{...props}
/>
);
}
const navigationMenuTriggerStyle = cva(
"group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=open]:hover:bg-accent data-[state=open]:text-accent-foreground data-[state=open]:focus:bg-accent data-[state=open]:bg-accent/50 focus-visible:ring-ring/50 outline-none transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1",
);
function NavigationMenuTrigger({
className,
children,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Trigger>) {
return (
<NavigationMenuPrimitive.Trigger
data-slot="navigation-menu-trigger"
className={cn(navigationMenuTriggerStyle(), "group", className)}
{...props}
>
{children}{" "}
<ChevronDownIcon
className="relative top-[1px] ml-1 size-3 transition duration-300 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
);
}
function NavigationMenuContent({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Content>) {
return (
<NavigationMenuPrimitive.Content
data-slot="navigation-menu-content"
className={cn(
"data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 top-0 left-0 w-full p-2 pr-2.5 md:absolute md:w-auto",
"group-data-[viewport=false]/navigation-menu:bg-popover group-data-[viewport=false]/navigation-menu:text-popover-foreground group-data-[viewport=false]/navigation-menu:data-[state=open]:animate-in group-data-[viewport=false]/navigation-menu:data-[state=closed]:animate-out group-data-[viewport=false]/navigation-menu:data-[state=closed]:zoom-out-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:zoom-in-95 group-data-[viewport=false]/navigation-menu:data-[state=open]:fade-in-0 group-data-[viewport=false]/navigation-menu:data-[state=closed]:fade-out-0 group-data-[viewport=false]/navigation-menu:top-full group-data-[viewport=false]/navigation-menu:mt-1.5 group-data-[viewport=false]/navigation-menu:overflow-hidden group-data-[viewport=false]/navigation-menu:rounded-md group-data-[viewport=false]/navigation-menu:border group-data-[viewport=false]/navigation-menu:shadow group-data-[viewport=false]/navigation-menu:duration-200 **:data-[slot=navigation-menu-link]:focus:ring-0 **:data-[slot=navigation-menu-link]:focus:outline-none",
className,
)}
{...props}
/>
);
}
function NavigationMenuViewport({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Viewport>) {
return (
<div
className={cn(
"absolute top-full left-0 isolate z-50 flex justify-center",
)}
>
<NavigationMenuPrimitive.Viewport
data-slot="navigation-menu-viewport"
className={cn(
"origin-top-center bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border shadow md:w-[var(--radix-navigation-menu-viewport-width)]",
className,
)}
{...props}
/>
</div>
);
}
function NavigationMenuLink({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Link>) {
return (
<NavigationMenuPrimitive.Link
data-slot="navigation-menu-link"
className={cn(
"data-[active=true]:focus:bg-accent data-[active=true]:hover:bg-accent data-[active=true]:bg-accent/50 data-[active=true]:text-accent-foreground hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus-visible:ring-ring/50 [&_svg:not([class*='text-'])]:text-muted-foreground flex flex-col gap-1 rounded-sm p-2 text-sm transition-all outline-none focus-visible:ring-[3px] focus-visible:outline-1 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function NavigationMenuIndicator({
className,
...props
}: React.ComponentProps<typeof NavigationMenuPrimitive.Indicator>) {
return (
<NavigationMenuPrimitive.Indicator
data-slot="navigation-menu-indicator"
className={cn(
"data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden",
className,
)}
{...props}
>
<div className="bg-border relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm shadow-md" />
</NavigationMenuPrimitive.Indicator>
);
}
export {
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
navigationMenuTriggerStyle,
};

View File

@@ -0,0 +1,127 @@
import * as React from "react";
import {
ChevronLeftIcon,
ChevronRightIcon,
MoreHorizontalIcon,
} from "lucide-react";
import { cn } from "./utils";
import { Button, buttonVariants } from "./button";
function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
role="navigation"
aria-label="pagination"
data-slot="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
);
}
function PaginationContent({
className,
...props
}: React.ComponentProps<"ul">) {
return (
<ul
data-slot="pagination-content"
className={cn("flex flex-row items-center gap-1", className)}
{...props}
/>
);
}
function PaginationItem({ ...props }: React.ComponentProps<"li">) {
return <li data-slot="pagination-item" {...props} />;
}
type PaginationLinkProps = {
isActive?: boolean;
} & Pick<React.ComponentProps<typeof Button>, "size"> &
React.ComponentProps<"a">;
function PaginationLink({
className,
isActive,
size = "icon",
...props
}: PaginationLinkProps) {
return (
<a
aria-current={isActive ? "page" : undefined}
data-slot="pagination-link"
data-active={isActive}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className,
)}
{...props}
/>
);
}
function PaginationPrevious({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn("gap-1 px-2.5 sm:pl-2.5", className)}
{...props}
>
<ChevronLeftIcon />
<span className="hidden sm:block">Previous</span>
</PaginationLink>
);
}
function PaginationNext({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn("gap-1 px-2.5 sm:pr-2.5", className)}
{...props}
>
<span className="hidden sm:block">Next</span>
<ChevronRightIcon />
</PaginationLink>
);
}
function PaginationEllipsis({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
aria-hidden
data-slot="pagination-ellipsis"
className={cn("flex size-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontalIcon className="size-4" />
<span className="sr-only">More pages</span>
</span>
);
}
export {
Pagination,
PaginationContent,
PaginationLink,
PaginationItem,
PaginationPrevious,
PaginationNext,
PaginationEllipsis,
};

View File

@@ -0,0 +1,48 @@
"use client";
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "./utils";
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />;
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
);
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };

View File

@@ -0,0 +1,31 @@
"use client";
import * as React from "react";
import * as ProgressPrimitive from "@radix-ui/react-progress";
import { cn } from "./utils";
function Progress({
className,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
className,
)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className="bg-primary h-full w-full flex-1 transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
);
}
export { Progress };

View File

@@ -0,0 +1,45 @@
"use client";
import * as React from "react";
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";
import { CircleIcon } from "lucide-react";
import { cn } from "./utils";
function RadioGroup({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
return (
<RadioGroupPrimitive.Root
data-slot="radio-group"
className={cn("grid gap-3", className)}
{...props}
/>
);
}
function RadioGroupItem({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
return (
<RadioGroupPrimitive.Item
data-slot="radio-group-item"
className={cn(
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
<RadioGroupPrimitive.Indicator
data-slot="radio-group-indicator"
className="relative flex items-center justify-center"
>
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
);
}
export { RadioGroup, RadioGroupItem };

View File

@@ -0,0 +1,56 @@
"use client";
import * as React from "react";
import { GripVerticalIcon } from "lucide-react";
import * as ResizablePrimitive from "react-resizable-panels";
import { cn } from "./utils";
function ResizablePanelGroup({
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) {
return (
<ResizablePrimitive.PanelGroup
data-slot="resizable-panel-group"
className={cn(
"flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
className,
)}
{...props}
/>
);
}
function ResizablePanel({
...props
}: React.ComponentProps<typeof ResizablePrimitive.Panel>) {
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />;
}
function ResizableHandle({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean;
}) {
return (
<ResizablePrimitive.PanelResizeHandle
data-slot="resizable-handle"
className={cn(
"bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",
className,
)}
{...props}
>
{withHandle && (
<div className="bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border">
<GripVerticalIcon className="size-2.5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
);
}
export { ResizablePanelGroup, ResizablePanel, ResizableHandle };

View File

@@ -0,0 +1,58 @@
"use client";
import * as React from "react";
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import { cn } from "./utils";
function ScrollArea({
className,
children,
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
className={cn("relative", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
data-slot="scroll-area-viewport"
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
);
}
function ScrollBar({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
return (
<ScrollAreaPrimitive.ScrollAreaScrollbar
data-slot="scroll-area-scrollbar"
orientation={orientation}
className={cn(
"flex touch-none p-px transition-colors select-none",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent",
className,
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb
data-slot="scroll-area-thumb"
className="bg-border relative flex-1 rounded-full"
/>
</ScrollAreaPrimitive.ScrollAreaScrollbar>
);
}
export { ScrollArea, ScrollBar };

View File

@@ -0,0 +1,189 @@
"use client";
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import {
CheckIcon,
ChevronDownIcon,
ChevronUpIcon,
} from "lucide-react";
import { cn } from "./utils";
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />;
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default";
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-full items-center justify-between gap-2 rounded-md border bg-input-background px-3 py-2 text-sm whitespace-nowrap transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
);
}
function SelectContent({
className,
children,
position = "popper",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className,
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
);
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
);
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className,
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
);
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
);
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className,
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
);
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className,
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
);
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
};

View File

@@ -0,0 +1,28 @@
"use client";
import * as React from "react";
import * as SeparatorPrimitive from "@radix-ui/react-separator";
import { cn } from "./utils";
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator-root"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className,
)}
{...props}
/>
);
}
export { Separator };

View File

@@ -0,0 +1,139 @@
"use client";
import * as React from "react";
import * as SheetPrimitive from "@radix-ui/react-dialog";
import { XIcon } from "lucide-react";
import { cn } from "./utils";
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function SheetContent({
className,
children,
side = "right",
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left";
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className,
)}
{...props}
>
{children}
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
);
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
);
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
);
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
);
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
};

View File

@@ -0,0 +1,726 @@
"use client";
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { VariantProps, cva } from "class-variance-authority";
import { PanelLeftIcon } from "lucide-react";
import { useIsMobile } from "./use-mobile";
import { cn } from "./utils";
import { Button } from "./button";
import { Input } from "./input";
import { Separator } from "./separator";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "./sheet";
import { Skeleton } from "./skeleton";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "./tooltip";
const SIDEBAR_COOKIE_NAME = "sidebar_state";
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "18rem";
const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
type SidebarContextProps = {
state: "expanded" | "collapsed";
open: boolean;
setOpen: (open: boolean) => void;
openMobile: boolean;
setOpenMobile: (open: boolean) => void;
isMobile: boolean;
toggleSidebar: () => void;
};
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
function useSidebar() {
const context = React.useContext(SidebarContext);
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.");
}
return context;
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
const isMobile = useIsMobile();
const [openMobile, setOpenMobile] = React.useState(false);
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen);
const open = openProp ?? _open;
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value;
if (setOpenProp) {
setOpenProp(openState);
} else {
_setOpen(openState);
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
},
[setOpenProp, open],
);
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
}, [isMobile, setOpen, setOpenMobile]);
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault();
toggleSidebar();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [toggleSidebar]);
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed";
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
);
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
className,
)}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
);
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right";
variant?: "sidebar" | "floating" | "inset";
collapsible?: "offcanvas" | "icon" | "none";
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
if (collapsible === "none") {
return (
<div
data-slot="sidebar"
className={cn(
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
className,
)}
{...props}
>
{children}
</div>
);
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
);
}
return (
<div
className="group peer text-sidebar-foreground hidden md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
data-slot="sidebar"
>
{/* This is what handles the sidebar gap on desktop */}
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className,
)}
{...props}
>
<div
data-sidebar="sidebar"
data-slot="sidebar-inner"
className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
>
{children}
</div>
</div>
</div>
);
}
function SidebarTrigger({
className,
onClick,
...props
}: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar();
return (
<Button
data-sidebar="trigger"
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
className={cn("size-7", className)}
onClick={(event) => {
onClick?.(event);
toggleSidebar();
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
</Button>
);
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar();
return (
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className,
)}
{...props}
/>
);
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"bg-background relative flex w-full flex-1 flex-col",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className,
)}
{...props}
/>
);
}
function SidebarInput({
className,
...props
}: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("bg-background h-8 w-full shadow-none", className)}
{...props}
/>
);
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
}
function SidebarSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("bg-sidebar-border mx-2 w-auto", className)}
{...props}
/>
);
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className,
)}
{...props}
/>
);
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
);
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div";
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className,
)}
{...props}
/>
);
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
function SidebarGroupContent({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
);
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
);
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
);
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean;
isActive?: boolean;
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot : "button";
const { isMobile, state } = useSidebar();
const button = (
<Comp
data-slot="sidebar-menu-button"
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
);
if (!tooltip) {
return button;
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
};
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
);
}
function SidebarMenuAction({
className,
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean;
showOnHover?: boolean;
}) {
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
className,
)}
{...props}
/>
);
}
function SidebarMenuBadge({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean;
}) {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`;
}, []);
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
);
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
function SidebarMenuSubItem({
className,
...props
}: React.ComponentProps<"li">) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
{...props}
/>
);
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean;
size?: "sm" | "md";
isActive?: boolean;
}) {
const Comp = asChild ? Slot : "a";
return (
<Comp
data-slot="sidebar-menu-sub-button"
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className,
)}
{...props}
/>
);
}
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
};

View File

@@ -0,0 +1,13 @@
import { cn } from "./utils";
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
);
}
export { Skeleton };

View File

@@ -0,0 +1,63 @@
"use client";
import * as React from "react";
import * as SliderPrimitive from "@radix-ui/react-slider";
import { cn } from "./utils";
function Slider({
className,
defaultValue,
value,
min = 0,
max = 100,
...props
}: React.ComponentProps<typeof SliderPrimitive.Root>) {
const _values = React.useMemo(
() =>
Array.isArray(value)
? value
: Array.isArray(defaultValue)
? defaultValue
: [min, max],
[value, defaultValue, min, max],
);
return (
<SliderPrimitive.Root
data-slot="slider"
defaultValue={defaultValue}
value={value}
min={min}
max={max}
className={cn(
"relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
className,
)}
{...props}
>
<SliderPrimitive.Track
data-slot="slider-track"
className={cn(
"bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-4 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",
)}
>
<SliderPrimitive.Range
data-slot="slider-range"
className={cn(
"bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full",
)}
/>
</SliderPrimitive.Track>
{Array.from({ length: _values.length }, (_, index) => (
<SliderPrimitive.Thumb
data-slot="slider-thumb"
key={index}
className="border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
/>
))}
</SliderPrimitive.Root>
);
}
export { Slider };

View File

@@ -0,0 +1,25 @@
"use client";
import { useTheme } from "next-themes";
import { Toaster as Sonner, ToasterProps } from "sonner";
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme();
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
} as React.CSSProperties
}
{...props}
/>
);
};
export { Toaster };

View File

@@ -0,0 +1,31 @@
"use client";
import * as React from "react";
import * as SwitchPrimitive from "@radix-ui/react-switch";
import { cn } from "./utils";
function Switch({
className,
...props
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
return (
<SwitchPrimitive.Root
data-slot="switch"
className={cn(
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-switch-background focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={cn(
"bg-card dark:data-[state=unchecked]:bg-card-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0",
)}
/>
</SwitchPrimitive.Root>
);
}
export { Switch };

View File

@@ -0,0 +1,116 @@
"use client";
import * as React from "react";
import { cn } from "./utils";
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
);
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className,
)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className,
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};

View File

@@ -0,0 +1,66 @@
"use client";
import * as React from "react";
import * as TabsPrimitive from "@radix-ui/react-tabs";
import { cn } from "./utils";
function Tabs({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
);
}
function TabsList({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.List>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",
className,
)}
{...props}
/>
);
}
function TabsTrigger({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"data-[state=active]:bg-card dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-xl border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
/>
);
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
);
}
export { Tabs, TabsList, TabsTrigger, TabsContent };

View File

@@ -0,0 +1,18 @@
import * as React from "react";
import { cn } from "./utils";
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"resize-none border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-input-background px-3 py-2 text-base transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className,
)}
{...props}
/>
);
}
export { Textarea };

View File

@@ -0,0 +1,73 @@
"use client";
import * as React from "react";
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group";
import { type VariantProps } from "class-variance-authority";
import { cn } from "./utils";
import { toggleVariants } from "./toggle";
const ToggleGroupContext = React.createContext<
VariantProps<typeof toggleVariants>
>({
size: "default",
variant: "default",
});
function ToggleGroup({
className,
variant,
size,
children,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
VariantProps<typeof toggleVariants>) {
return (
<ToggleGroupPrimitive.Root
data-slot="toggle-group"
data-variant={variant}
data-size={size}
className={cn(
"group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",
className,
)}
{...props}
>
<ToggleGroupContext.Provider value={{ variant, size }}>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
);
}
function ToggleGroupItem({
className,
children,
variant,
size,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
VariantProps<typeof toggleVariants>) {
const context = React.useContext(ToggleGroupContext);
return (
<ToggleGroupPrimitive.Item
data-slot="toggle-group-item"
data-variant={context.variant || variant}
data-size={context.size || size}
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
"min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",
className,
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
);
}
export { ToggleGroup, ToggleGroupItem };

View File

@@ -0,0 +1,47 @@
"use client";
import * as React from "react";
import * as TogglePrimitive from "@radix-ui/react-toggle";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "./utils";
const toggleVariants = cva(
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-9 px-2 min-w-9",
sm: "h-8 px-1.5 min-w-8",
lg: "h-10 px-2.5 min-w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function Toggle({
className,
variant,
size,
...props
}: React.ComponentProps<typeof TogglePrimitive.Root> &
VariantProps<typeof toggleVariants>) {
return (
<TogglePrimitive.Root
data-slot="toggle"
className={cn(toggleVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Toggle, toggleVariants };

View File

@@ -0,0 +1,61 @@
"use client";
import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "./utils";
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
);
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
);
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className,
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
);
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };

View File

@@ -0,0 +1,21 @@
import * as React from "react";
const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
undefined,
);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange);
}, []);
return !!isMobile;
}

View File

@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

View File

@@ -0,0 +1,263 @@
import { createContext, useContext, useState, useCallback, useEffect, type ReactNode } from "react";
import {
getToken,
setToken as saveToken,
clearToken,
getUserProfile,
updateUserProfile,
type UserProfileDTO,
} from "../services/api";
export interface UserProfile {
name: string;
age: number | null;
phone: string;
lastPeriodDate: string; // YYYY-MM-DD
dueDate: string;
currentWeek: number;
currentDay: number;
isFirstPregnancy: boolean;
height: number | null;
prePregnancyWeight: number | null;
currentWeight: number | null;
bloodType: string;
allergies: string[];
medicalHistory: string[];
emergencyContact: {
name: string;
relation: string;
phone: string;
};
isOnboarded: boolean;
}
const DEFAULT_PROFILE: UserProfile = {
name: "",
age: null,
phone: "",
lastPeriodDate: "",
dueDate: "",
currentWeek: 0,
currentDay: 0,
isFirstPregnancy: true,
height: null,
prePregnancyWeight: null,
currentWeight: null,
bloodType: "",
allergies: [],
medicalHistory: [],
emergencyContact: { name: "", relation: "", phone: "" },
isOnboarded: false,
};
const STORAGE_KEY = "pregnancy_user_profile";
function loadProfile(): UserProfile {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
const saved = JSON.parse(raw) as UserProfile;
if (saved.lastPeriodDate) {
const { weeks, days } = calcPregnancyWeek(saved.lastPeriodDate);
saved.currentWeek = weeks;
saved.currentDay = days;
}
return saved;
}
} catch {}
return DEFAULT_PROFILE;
}
function saveProfile(profile: UserProfile) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(profile));
}
export function calcPregnancyWeek(lastPeriodDate: string) {
const lmp = new Date(lastPeriodDate);
const now = new Date();
const diffDays = Math.floor((now.getTime() - lmp.getTime()) / (24 * 60 * 60 * 1000));
return { weeks: Math.max(0, Math.floor(diffDays / 7)), days: Math.max(0, diffDays % 7) };
}
export function calcDueDate(lastPeriodDate: string): string {
const lmp = new Date(lastPeriodDate);
const due = new Date(lmp.getTime() + 280 * 24 * 60 * 60 * 1000);
return due.toISOString().split("T")[0];
}
export function getPregnancyStage(week: number): string {
if (week <= 12) return "孕早期";
if (week <= 28) return "孕中期";
return "孕晚期";
}
// 基于WHO标准,4-19周为头臀长,20周起为全身长
export function getBabySize(week: number): string {
const sizes: Record<number, string> = {
4: "约0.1厘米,像一粒罂粟种子",
5: "约0.2厘米,像一粒芝麻",
6: "约0.6厘米,像一粒小扁豆",
7: "约1.3厘米,像一颗蓝莓",
8: "约1.6厘米,像一颗覆盆子",
9: "约2.3厘米,像一颗葡萄",
10: "约3.1厘米,像一颗金橘",
11: "约4.1厘米,像一颗无花果",
12: "约5.4厘米,像一颗青柠",
13: "约7.4厘米,像一颗柠檬",
14: "约8.7厘米,像一颗桃子",
16: "约11.6厘米,像一个牛油果",
18: "约14.2厘米,像一个甜椒",
20: "约25.6厘米,像一根香蕉",
22: "约27.8厘米,像一个木瓜",
24: "约30厘米,像一穗玉米",
26: "约35.6厘米,像一颗菜花",
28: "约37.6厘米,像一颗茄子",
30: "约39.9厘米,像一颗卷心菜",
32: "约42.4厘米,像一个椰子",
34: "约45厘米,像一颗哈密瓜",
36: "约47.4厘米,像一颗蜜瓜",
38: "约49.8厘米,像一颗南瓜",
40: "约51.2厘米,像一颗小西瓜",
};
const weeks = Object.keys(sizes).map(Number).sort((a, b) => a - b);
let closest = weeks[0];
for (const w of weeks) {
if (w <= week) closest = w;
else break;
}
return sizes[closest] || `约${week}周`;
}
/** 将后端 DTO 映射为前端 UserProfile */
function mapDtoToProfile(dto: UserProfileDTO): UserProfile {
const lmpDate = dto.last_period_date ? dto.last_period_date.split("T")[0] : "";
let currentWeek = dto.pregnancy_week || 0;
let currentDay = dto.pregnancy_day || 0;
let dueDate = dto.due_date ? dto.due_date.split("T")[0] : "";
// 如果有 LMP 日期,实时计算孕周和预产期
if (lmpDate) {
const calc = calcPregnancyWeek(lmpDate);
currentWeek = calc.weeks;
currentDay = calc.days;
dueDate = calcDueDate(lmpDate);
}
return {
name: dto.name || "",
age: dto.age,
phone: dto.phone || "",
lastPeriodDate: lmpDate,
dueDate,
currentWeek,
currentDay,
isFirstPregnancy: true,
height: dto.height,
prePregnancyWeight: dto.pre_pregnancy_weight,
currentWeight: dto.current_weight,
bloodType: dto.blood_type || "",
allergies: dto.allergies || [],
medicalHistory: dto.medical_history || [],
emergencyContact: dto.emergency_contact || { name: "", relation: "", phone: "" },
isOnboarded: dto.is_onboarded,
};
}
interface UserContextValue {
user: UserProfile;
token: string | null;
updateUser: (data: Partial<UserProfile>) => void;
updateUserRemote: (data: Partial<UserProfile>) => Promise<void>;
setToken: (token: string) => void;
fetchProfile: () => Promise<void>;
logout: () => void;
}
const UserContext = createContext<UserContextValue | null>(null);
export function UserProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<UserProfile>(loadProfile);
const [token, setTokenState] = useState<string | null>(getToken);
const setToken = useCallback((newToken: string) => {
// 清理前一个用户的本地数据,防止用户间数据残留
localStorage.removeItem(STORAGE_KEY);
setUser(DEFAULT_PROFILE);
saveToken(newToken);
setTokenState(newToken);
}, []);
const updateUser = useCallback((data: Partial<UserProfile>) => {
setUser((prev) => {
const updated = { ...prev, ...data };
if (data.lastPeriodDate) {
const { weeks, days } = calcPregnancyWeek(data.lastPeriodDate);
updated.currentWeek = weeks;
updated.currentDay = days;
updated.dueDate = calcDueDate(data.lastPeriodDate);
}
saveProfile(updated);
return updated;
});
}, []);
const updateUserRemote = useCallback(async (data: Partial<UserProfile>) => {
// 乐观更新本地
updateUser(data);
// 同步到后端(camelCase → snake_case)
const payload: Record<string, unknown> = {};
if (data.name !== undefined) payload.name = data.name;
if (data.age !== undefined) payload.age = data.age;
if (data.phone !== undefined) payload.phone = data.phone;
if (data.height !== undefined) payload.height = data.height;
if (data.prePregnancyWeight !== undefined) payload.pre_pregnancy_weight = data.prePregnancyWeight;
if (data.currentWeight !== undefined) payload.current_weight = data.currentWeight;
if (data.bloodType !== undefined) payload.blood_type = data.bloodType;
if (data.allergies !== undefined) payload.allergies = data.allergies;
if (data.medicalHistory !== undefined) payload.medical_history = data.medicalHistory;
if (data.lastPeriodDate !== undefined) payload.last_period_date = data.lastPeriodDate || null;
if (data.emergencyContact !== undefined) payload.emergency_contact = data.emergencyContact;
try {
await updateUserProfile(payload);
} catch (e) {
console.error("同步用户数据到后端失败:", e);
}
}, [updateUser]);
const fetchProfile = useCallback(async () => {
try {
const dto = await getUserProfile();
const profile = mapDtoToProfile(dto);
setUser(profile);
saveProfile(profile);
} catch {
// Token 失效会被 api.ts 自动处理(跳转登录页)
}
}, []);
const logout = useCallback(() => {
clearToken();
localStorage.removeItem(STORAGE_KEY);
setTokenState(null);
setUser(DEFAULT_PROFILE);
}, []);
// 启动时如果有 token,自动拉取后端数据
useEffect(() => {
if (token) {
fetchProfile();
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return (
<UserContext.Provider value={{ user, token, updateUser, updateUserRemote, setToken, fetchProfile, logout }}>
{children}
</UserContext.Provider>
);
}
export function useUser() {
const ctx = useContext(UserContext);
if (!ctx) throw new Error("useUser must be used within UserProvider");
return ctx;
}

View File

@@ -0,0 +1,105 @@
/** 产检计划公共数据,供 CalendarPage 和 NotificationPage 共享 */
export interface CheckupTemplate {
title: string;
week: number;
items: string[];
preparations: string[];
notes: string;
importance: "high" | "medium" | "low";
}
export const checkupSchedule: CheckupTemplate[] = [
{
title: "第一次产检",
week: 12,
items: [
"NT检查(胎儿颈部透明带)",
"血常规",
"尿常规",
"肝肾功能",
"血型检查",
"传染病筛查",
],
preparations: ["需空腹", "携带身份证和病历本"],
notes: "NT检查是早期排畸的重要项目,建议孕11-13周+6天进行",
importance: "high",
},
{
title: "唐氏筛查",
week: 16,
items: ["血清学唐氏筛查", "B超检查"],
preparations: ["无需空腹", "前一晚正常饮食"],
notes: "评估胎儿患唐氏综合征的风险",
importance: "high",
},
{
title: "大排畸检查",
week: 22,
items: ["四维彩超", "胎儿系统超声筛查", "血常规", "尿常规"],
preparations: ["无需空腹", "建议提前预约", "穿宽松衣服"],
notes: "最重要的排畸检查,全面筛查胎儿结构异常",
importance: "high",
},
{
title: "糖耐量检查",
week: 24,
items: ["75g OGTT(葡萄糖耐量试验)", "血常规", "尿常规"],
preparations: [
"需空腹8-12小时",
"前三天正常饮食",
"检查当天携带糖粉",
"准备2-3小时检查时间",
],
notes: "筛查妊娠期糖尿病,需要在医院待2-3小时",
importance: "high",
},
{
title: "常规产检",
week: 28,
items: ["B超检查", "血常规", "尿常规", "胎心监护"],
preparations: ["无需空腹"],
notes: "进入孕晚期,之后每2周检查一次",
importance: "medium",
},
{
title: "常规产检",
week: 36,
items: ["B超检查", "血常规", "尿常规", "胎心监护", "骨盆测量", "心电图"],
preparations: ["无需空腹"],
notes: "36周后每周检查一次,评估分娩方式",
importance: "medium",
},
{
title: "孕37周产检",
week: 37,
items: ["胎心监护", "尿常规", "血压测量", "宫高腹围"],
preparations: ["无需空腹", "建议家人陪同"],
notes: "每周监测胎儿状况,随时准备分娩",
importance: "medium",
},
{
title: "孕38周产检",
week: 38,
items: ["胎心监护", "尿常规", "血压测量", "宫高腹围", "B超检查"],
preparations: ["无需空腹", "建议家人陪同"],
notes: "评估胎儿大小和羊水情况,确认分娩方式",
importance: "high",
},
{
title: "孕39周产检",
week: 39,
items: ["胎心监护", "尿常规", "血压测量", "宫高腹围"],
preparations: ["无需空腹", "建议家人陪同", "准备好待产包"],
notes: "密切监测,随时可能临产",
importance: "high",
},
{
title: "孕40周产检",
week: 40,
items: ["胎心监护", "尿常规", "血压测量", "宫高腹围", "B超检查"],
preparations: ["无需空腹", "必须家人陪同", "携带待产包"],
notes: "已到预产期,医生会评估是否需要催产",
importance: "high",
},
];

View File

@@ -0,0 +1,721 @@
import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router";
import { motion, AnimatePresence } from "motion/react";
import {
ChevronLeft,
Heart,
TrendingUp,
AlertCircle,
CheckCircle2,
Info,
Calendar,
Share2,
Download,
Sparkles,
Activity,
Baby,
MessageCircle,
FileText,
X,
Link2,
Check,
AlertTriangle,
ShieldAlert,
Loader2,
Image as ImageIcon,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Card } from "../components/ui/card";
import { Badge } from "../components/ui/badge";
import { generateAnalysis, type AnalysisResponse } from "../services/api";
export function AIAnalysisPage() {
const navigate = useNavigate();
const { reportId } = useParams();
const [showShareSheet, setShowShareSheet] = useState(false);
const [linkCopied, setLinkCopied] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [analysisData, setAnalysisData] = useState<AnalysisResponse | null>(null);
useEffect(() => {
if (!reportId) return;
setLoading(true);
generateAnalysis(reportId)
.then((data) => setAnalysisData(data))
.catch((err) => setError(err instanceof Error ? err.message : "加载失败"))
.finally(() => setLoading(false));
}, [reportId]);
const handleCopyLink = async () => {
try {
const shareUrl = `${window.location.origin}/share/${reportId}`;
await navigator.clipboard.writeText(shareUrl);
setLinkCopied(true);
setTimeout(() => setLinkCopied(false), 2000);
} catch (error) {
console.error('复制失败:', error);
// 降级方案:使用旧的复制方法
const textArea = document.createElement('textarea');
textArea.value = `${window.location.origin}/share/${reportId}`;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
document.body.appendChild(textArea);
textArea.select();
try {
document.execCommand('copy');
setLinkCopied(true);
setTimeout(() => setLinkCopied(false), 2000);
} catch (err) {
alert('复制失败,请手动复制链接');
}
document.body.removeChild(textArea);
}
};
if (loading) {
return (
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
<div className="text-center">
<Loader2 className="w-12 h-12 text-morandi-400 animate-spin mx-auto mb-4" />
<p className="text-gray-600 font-medium">AI 正在解读您的报告...</p>
<p className="text-gray-400 text-sm mt-2">这可能需要几秒钟</p>
</div>
</div>
);
}
if (error || !analysisData) {
return (
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
<div className="text-center px-8">
<AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-4" />
<p className="text-gray-800 font-medium mb-2">解读失败</p>
<p className="text-gray-500 text-sm mb-4">{error || "未知错误"}</p>
<Button onClick={() => navigate("/home")} variant="outline">返回首页</Button>
</div>
</div>
);
}
const getStatusColor = (status: string) => {
switch (status) {
case "normal":
return {
bg: "bg-morandi-sage-100",
border: "border-morandi-sage-200",
text: "text-morandi-sage-600",
badge: "bg-morandi-sage-100 text-morandi-sage-600",
icon: "text-morandi-sage-400",
};
case "attention":
return {
bg: "bg-morandi-rose-100",
border: "border-morandi-200",
text: "text-morandi-600",
badge: "bg-morandi-rose-100 text-morandi-600",
icon: "text-morandi-rose-400",
};
case "high":
return {
bg: "bg-red-50",
border: "border-red-200",
text: "text-red-700",
badge: "bg-red-100 text-red-700",
icon: "text-red-500",
};
default:
return {
bg: "bg-gray-50",
border: "border-gray-200",
text: "text-gray-700",
badge: "bg-gray-100 text-gray-700",
icon: "text-gray-500",
};
}
};
const statusColors = getStatusColor(analysisData.overall_status);
// 指标状态颜色(紫色系色温区分:冷调sage→中性purple→暖调rose)
const getIndicatorColor = (indicatorStatus: string) => {
switch (indicatorStatus) {
case "normal":
return {
bg: "bg-morandi-sage-100",
border: "border-morandi-sage-200",
text: "text-morandi-sage-600",
badge: "bg-morandi-sage-100 text-morandi-sage-600",
barBg: "bg-morandi-sage-200",
barFill: "bg-morandi-sage-400",
};
case "borderline":
return {
bg: "bg-morandi-100",
border: "border-morandi-200",
text: "text-morandi-600",
badge: "bg-morandi-200 text-morandi-700",
barBg: "bg-morandi-200",
barFill: "bg-morandi-400",
};
case "abnormal":
return {
bg: "bg-morandi-rose-100",
border: "border-morandi-rose-300",
text: "text-morandi-700",
badge: "bg-morandi-rose-100 text-morandi-rose-400",
barBg: "bg-morandi-rose-100",
barFill: "bg-morandi-rose-400",
};
default:
return {
bg: "bg-gray-50",
border: "border-gray-200",
text: "text-gray-700",
badge: "bg-gray-100 text-gray-700",
barBg: "bg-gray-100",
barFill: "bg-gray-400",
};
}
};
const getRiskLabel = (riskLevel: string) => {
switch (riskLevel) {
case "low":
return { label: "低风险", color: "bg-morandi-100 text-morandi-600" };
case "medium":
return { label: "中风险", color: "bg-morandi-rose-100 text-morandi-rose-400" };
case "high":
return { label: "高风险", color: "bg-morandi-rose-100 text-morandi-700" };
default:
return { label: "", color: "" };
}
};
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-20">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<button
onClick={() => navigate(-1)}
className="flex items-center text-gray-600 hover:text-gray-900"
>
<ChevronLeft className="w-5 h-5 mr-1" />
返回
</button>
<h1 className="font-semibold text-gray-800">AI 智能解读</h1>
<button
onClick={() => setShowShareSheet(true)}
className="p-2 hover:bg-gray-100 rounded-lg"
>
<Share2 className="w-5 h-5 text-gray-600" />
</button>
</div>
</div>
<div className="mx-auto p-4 space-y-6 pb-20">
{/* AI 解读标识 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="flex items-center justify-center gap-2 text-morandi-500"
>
<Sparkles className="w-5 h-5" />
<span className="text-sm font-medium">AI 深度解读 · 个性化定制</span>
</motion.div>
{/* 整体评估卡片 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
>
<Card
className={`${statusColors.bg} border-2 ${statusColors.border} rounded-3xl p-6 shadow-sm`}
>
<div className="flex items-start gap-4 mb-4">
<div
className={`w-16 h-16 ${statusColors.badge} rounded-2xl flex items-center justify-center flex-shrink-0`}
>
<Baby className={`w-8 h-8 ${statusColors.icon}`} />
</div>
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<h2 className="text-xl font-semibold text-gray-800">
整体评估
</h2>
<Badge className={statusColors.badge}>
{analysisData.overall_status === "normal"
? "一切正常"
: analysisData.overall_status === "attention"
? "需要关注"
: "需要重视"}
</Badge>
</div>
<p className={`text-sm ${statusColors.text} mb-3 leading-relaxed`}>
{analysisData.emotional_summary || analysisData.overall_summary}
</p>
<div className="flex flex-wrap gap-3 text-xs text-gray-600">
<div className="flex items-center gap-1">
<Calendar className="w-3 h-3" />
<span>{new Date(analysisData.created_at).toLocaleDateString("zh-CN")}</span>
</div>
</div>
</div>
</div>
{/* 风险等级指示器 */}
<div className="bg-white/50 backdrop-blur-sm rounded-2xl p-4">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium text-gray-700">
综合风险评级
</span>
<span
className={`text-sm font-semibold ${
analysisData.risk_level === "low"
? "text-morandi-sage-500"
: analysisData.risk_level === "medium"
? "text-morandi-600"
: "text-red-600"
}`}
>
{analysisData.risk_level === "low"
? "低风险"
: analysisData.risk_level === "medium"
? "中风险"
: "高风险"}
</span>
</div>
<div className="h-2 bg-gray-200 rounded-full overflow-hidden">
<motion.div
initial={{ width: 0 }}
animate={{
width:
analysisData.risk_level === "low"
? "25%"
: analysisData.risk_level === "medium"
? "60%"
: "90%",
}}
transition={{ delay: 0.5, duration: 0.8 }}
className={`h-full rounded-full ${
analysisData.risk_level === "low"
? "bg-morandi-sage-400"
: analysisData.risk_level === "medium"
? "bg-morandi-rose-400"
: "bg-red-500"
}`}
/>
</div>
</div>
</Card>
</motion.div>
{/* 分类详情 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
>
<h2 className="text-lg font-semibold text-gray-800 mb-4">详细解读</h2>
<div className="space-y-4">
{analysisData.categories.map((category, index) => {
const colors = getStatusColor(category.status);
return (
<motion.div
key={category.category}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 + index * 0.1 }}
>
<Card className="bg-white rounded-3xl shadow-sm overflow-hidden border-0">
{/* 分类头部 */}
<div className={`${colors.bg} border-b-2 ${colors.border} p-5`}>
<div className="flex items-center gap-3 mb-2">
<div
className={`w-10 h-10 ${colors.badge} rounded-xl flex items-center justify-center`}
>
<Activity className={`w-5 h-5 ${colors.icon}`} />
</div>
<div className="flex-1">
<h3 className="font-semibold text-gray-800">
{category.category}
</h3>
</div>
<Badge className={colors.badge}>
{category.status === "normal"
? "正常"
: category.status === "attention"
? "需关注"
: "异常"}
</Badge>
</div>
</div>
{/* 指标详情 */}
<div className="p-5 space-y-4">
{category.indicators.map((item, itemIdx) => {
const indicatorStatus = item.status === "normal" ? "normal" : item.status === "low" || item.status === "high" ? "abnormal" : "borderline";
const indColors = getIndicatorColor(indicatorStatus);
return (
<div
key={itemIdx}
className={`${indColors.bg} border-2 ${indColors.border} rounded-2xl p-4`}
>
{/* 指标名称和数值 */}
<div className="flex items-start justify-between mb-3">
<div className="flex-1">
<h4 className="font-semibold text-gray-800 mb-1">
{item.name}
</h4>
{item.nickname && (
<p className="text-xs text-gray-500 mb-2">
{item.nickname}
</p>
)}
<div className="flex items-baseline gap-2">
<span
className={`text-2xl font-semibold ${indColors.text}`}
>
{item.value}
</span>
<span className="text-sm text-gray-500">
{item.unit}
</span>
</div>
{item.reference_range && (
<p className="text-xs text-gray-400 mt-1">
参考范围:{item.reference_range}
</p>
)}
</div>
<div className="flex flex-col items-end gap-1.5">
<div
className={`px-3 py-1 ${indColors.badge} rounded-full flex items-center gap-1`}
>
{indicatorStatus === "normal" ? (
<CheckCircle2 className="w-4 h-4" />
) : (
<AlertCircle className="w-4 h-4" />
)}
<span className="text-xs font-medium">
{item.status === "normal" ? "正常" : item.status === "high" ? "偏高" : "偏低"}
</span>
</div>
</div>
</div>
{/* 状态指示条 */}
<div className="mb-3">
<div className={`h-1.5 ${indColors.barBg} rounded-full overflow-hidden`}>
<div
className={`h-full ${indColors.barFill} rounded-full transition-all`}
style={{
width: indicatorStatus === "normal" ? "100%" : indicatorStatus === "borderline" ? "60%" : "30%",
}}
/>
</div>
</div>
{/* 白话解释 */}
<div className="space-y-3">
{item.what_is_it && (
<div className="bg-white/70 rounded-xl p-3">
<div className="flex items-start gap-2">
<Info className="w-4 h-4 text-morandi-400 flex-shrink-0 mt-0.5" />
<div className="flex-1">
<p className="text-xs font-medium text-gray-700 mb-1">这是什么?</p>
<p className="text-xs text-gray-600 leading-relaxed">{item.what_is_it}</p>
</div>
</div>
</div>
)}
{item.baby_impact && (
<div className="bg-white/70 rounded-xl p-3">
<div className="flex items-start gap-2">
<Baby className="w-4 h-4 text-morandi-400 flex-shrink-0 mt-0.5" />
<div className="flex-1">
<p className="text-xs font-medium text-gray-700 mb-1">对宝宝的影响</p>
<p className="text-xs text-gray-600 leading-relaxed">{item.baby_impact}</p>
</div>
</div>
</div>
)}
{item.suggestion && (
<div className="bg-morandi-100/50 rounded-xl p-3">
<div className="flex items-start gap-2">
<Heart className="w-4 h-4 text-morandi-400 flex-shrink-0 mt-0.5" />
<div className="flex-1">
<p className="text-xs font-medium text-gray-700 mb-1">建议措施</p>
<p className="text-xs text-gray-600 leading-relaxed">{item.suggestion}</p>
</div>
</div>
</div>
)}
{item.follow_up && (
<div className="flex items-center gap-2 text-xs text-morandi-500">
<Calendar className="w-3 h-3" />
<span>{item.follow_up}</span>
</div>
)}
</div>
</div>
);
})}
</div>
</Card>
</motion.div>
);
})}
</div>
</motion.div>
{/* 行动建议 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.5 }}
>
<h2 className="text-lg font-semibold text-gray-800 mb-4">
接下来该做什么?
</h2>
<div className="space-y-3">
{analysisData.action_items.map((rec, index) => (
<motion.div
key={index}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.6 + index * 0.1 }}
>
<Card
className={`rounded-2xl p-4 border-2 ${
rec.priority === "high"
? "bg-morandi-rose-100 border-morandi-200"
: rec.priority === "medium"
? "bg-morandi-50 border-morandi-200"
: "bg-gray-50 border-gray-200"
}`}
>
<div className="flex items-start gap-3">
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<h4 className="font-semibold text-gray-800">
{rec.title}
</h4>
{rec.priority === "high" && (
<Badge className="bg-morandi-rose-100 text-morandi-600 text-xs">
重要
</Badge>
)}
</div>
<p className="text-sm text-gray-600 mb-2">
{rec.description}
</p>
{rec.timeframe && (
<div className="flex items-center gap-2 text-xs text-gray-500">
<Calendar className="w-3 h-3" />
<span>{rec.timeframe}</span>
</div>
)}
</div>
</div>
</Card>
</motion.div>
))}
</div>
</motion.div>
{/* 深度服务 - 新增 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.7 }}
>
<h2 className="text-lg font-semibold text-gray-800 mb-4">
🎯 获取更多帮助
</h2>
<div className="grid grid-cols-2 gap-3">
<Card
onClick={() => navigate(`/chat/${reportId}`)}
className="bg-morandi-100 rounded-2xl p-4 border-0 cursor-pointer hover:scale-105 transition-transform"
>
<div className="w-12 h-12 bg-morandi-400 rounded-xl flex items-center justify-center mb-3">
<MessageCircle className="w-6 h-6 text-white" />
</div>
<h3 className="font-semibold text-gray-800 mb-1">AI对话追问</h3>
<p className="text-xs text-gray-600">针对报告提问</p>
</Card>
<Card
onClick={() => navigate(`/doctor-questions/${reportId}`)}
className="bg-gradient-to-br from-morandi-slate-100 to-morandi-slate-50 rounded-2xl p-4 border-0 cursor-pointer hover:scale-105 transition-transform"
>
<div className="w-12 h-12 bg-morandi-slate-500 rounded-xl flex items-center justify-center mb-3">
<FileText className="w-6 h-6 text-white" />
</div>
<h3 className="font-semibold text-gray-800 mb-1">问诊清单</h3>
<p className="text-xs text-gray-600">就医沟通话术</p>
</Card>
</div>
</motion.div>
{/* 温馨提示 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.9 }}
>
<Card className="bg-morandi-50 border-morandi-200 rounded-2xl p-4">
<div className="flex items-start gap-3">
<Heart className="w-5 h-5 text-morandi-400 flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h4 className="font-semibold text-gray-800 mb-1">
温馨提示
</h4>
<p className="text-sm text-gray-600 leading-relaxed">
以上解读仅供参考,不能替代医生的专业诊断。如有任何疑问或不适,请及时就医咨询专业医生。保持好心情,宝宝能感受到妈妈的情绪哦 💕
</p>
</div>
</div>
</Card>
</motion.div>
</div>
{/* 底部操作栏 */}
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 pb-safe z-10">
<div className="max-w-md mx-auto flex gap-3">
<Button
onClick={() => navigate("/home")}
variant="outline"
className="flex-1 h-12 rounded-xl border-2 border-gray-300"
>
返回首页
</Button>
<Button
onClick={() => navigate(`/report/${reportId}`)}
className="flex-1 h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white"
>
查看原始报告
</Button>
</div>
</div>
{/* 分享弹窗 */}
<AnimatePresence>
{showShareSheet && (
<>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={() => setShowShareSheet(false)}
className="fixed inset-0 bg-black/40 z-40"
/>
<motion.div
initial={{ y: "100%" }}
animate={{ y: 0 }}
exit={{ y: "100%" }}
transition={{ type: "spring", damping: 25, stiffness: 300 }}
className="fixed bottom-0 left-0 right-0 bg-white rounded-t-3xl z-50 max-h-[70vh] overflow-y-auto"
>
<div className="mx-auto p-5">
{/* 拖拽指示器 */}
<div className="w-10 h-1 bg-gray-200 rounded-full mx-auto mb-4" />
<div className="flex items-center justify-between mb-5">
<h3 className="font-semibold text-gray-800 text-lg">分享报告</h3>
<button
onClick={() => setShowShareSheet(false)}
className="w-8 h-8 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<X className="w-5 h-5 text-gray-400" />
</button>
</div>
{/* 分享方式 */}
<div className="space-y-3 mb-6">
{/* 生成分享长图 */}
<button
onClick={() => {
setShowShareSheet(false);
navigate(`/share/${reportId}`);
}}
className="w-full flex items-center gap-4 py-4 px-4 bg-gradient-to-r from-morandi-100 to-morandi-50 hover:from-morandi-200 hover:to-morandi-100 rounded-2xl transition-colors"
>
<div className="w-12 h-12 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-xl flex items-center justify-center flex-shrink-0">
<ImageIcon className="w-6 h-6 text-white" />
</div>
<div className="text-left flex-1">
<div className="font-semibold text-gray-800">
生成分享长图
</div>
<div className="text-xs text-gray-500">
生成精美报告长图,一键保存到相册
</div>
</div>
<ChevronLeft className="w-5 h-5 text-gray-300 rotate-180" />
</button>
{/* 复制链接 */}
<button
onClick={handleCopyLink}
className="w-full flex items-center gap-4 py-4 px-4 bg-morandi-50 hover:bg-morandi-100 rounded-2xl transition-colors"
>
<div className="w-12 h-12 bg-morandi-400 rounded-xl flex items-center justify-center flex-shrink-0">
{linkCopied ? (
<Check className="w-6 h-6 text-white" />
) : (
<Link2 className="w-6 h-6 text-white" />
)}
</div>
<div className="text-left flex-1">
<div className="font-semibold text-gray-800">
{linkCopied ? "链接已复制" : "复制分享链接"}
</div>
<div className="text-xs text-gray-500">
{linkCopied ? "可以分享给家人或医生" : "复制链接发送给家人或医生"}
</div>
</div>
</button>
</div>
{/* 分享预览卡片 */}
<Card className="bg-morandi-50 border-morandi-100 rounded-2xl p-4 mb-4">
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-xl flex items-center justify-center flex-shrink-0">
<FileText className="w-6 h-6 text-white" />
</div>
<div className="flex-1 min-w-0">
<h4 className="font-medium text-gray-800 text-sm truncate">
{analysisData.categories[0]?.category || "检查报告"} · AI解读
</h4>
<p className="text-xs text-gray-500 mt-0.5 truncate">
{analysisData.overall_summary}
</p>
<div className="flex items-center gap-2 mt-1">
<span className="text-xs text-gray-400">{new Date(analysisData.created_at).toLocaleDateString("zh-CN")}</span>
</div>
</div>
</div>
</Card>
{/* 隐私提示 */}
<div className="flex items-center gap-2 text-xs text-gray-400 mb-2">
<Info className="w-3.5 h-3.5 flex-shrink-0" />
<span>分享时将自动隐藏个人敏感信息,保护您的隐私</span>
</div>
</div>
</motion.div>
</>
)}
</AnimatePresence>
</div>
);
}

View File

@@ -0,0 +1,271 @@
import { useState, useRef, useEffect } from "react";
import { useNavigate, useParams } from "react-router";
import { motion, AnimatePresence } from "motion/react";
import {
ChevronLeft,
Send,
Sparkles,
Lightbulb,
User,
Bot,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Card } from "../components/ui/card";
import { sendChatMessage, getChatHistory } from "../services/api";
interface Message {
id: string;
role: "user" | "assistant";
content: string;
timestamp: Date;
}
export function AIChatPage() {
const navigate = useNavigate();
const { reportId } = useParams();
const [messages, setMessages] = useState<Message[]>([
{
id: "1",
role: "assistant",
content:
"您好!我是您的孕期健康助手。您可以向我询问报告中的任何指标,我会结合医学知识为您详细解答。",
timestamp: new Date(),
},
]);
const [input, setInput] = useState("");
const [isTyping, setIsTyping] = useState(false);
const [quickQuestions, setQuickQuestions] = useState<string[]>([
"这个指标偏高对宝宝有影响吗?",
"我需要补充什么营养?",
"下次检查需要注意什么?",
"这种情况多久会恢复正常?",
]);
const messagesEndRef = useRef<HTMLDivElement>(null);
// Load chat history on mount
useEffect(() => {
if (!reportId) return;
getChatHistory(reportId).then((data) => {
if (data.messages.length > 0) {
setMessages(
data.messages.map((m, i) => ({
id: String(i),
role: m.role as "user" | "assistant",
content: m.content,
timestamp: new Date(m.timestamp),
}))
);
}
if (data.quick_questions.length > 0) {
setQuickQuestions(data.quick_questions);
}
}).catch(() => {/* keep defaults */});
}, [reportId]);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
useEffect(() => {
scrollToBottom();
}, [messages]);
const handleSend = async () => {
if (!input.trim() || !reportId) return;
const userMessage: Message = {
id: Date.now().toString(),
role: "user",
content: input,
timestamp: new Date(),
};
setMessages((prev) => [...prev, userMessage]);
const question = input;
setInput("");
setIsTyping(true);
try {
const result = await sendChatMessage(reportId, question);
const aiResponse: Message = {
id: (Date.now() + 1).toString(),
role: "assistant",
content: result.ai_message.content,
timestamp: new Date(result.ai_message.timestamp),
};
setMessages((prev) => [...prev, aiResponse]);
} catch {
const errorMsg: Message = {
id: (Date.now() + 1).toString(),
role: "assistant",
content: "抱歉,AI 服务暂时不可用,请稍后重试。",
timestamp: new Date(),
};
setMessages((prev) => [...prev, errorMsg]);
} finally {
setIsTyping(false);
}
};
const handleQuickQuestion = (question: string) => {
setInput(question);
};
return (
<div className="min-h-dvh bg-morandi-50 flex flex-col">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => navigate(-1)}
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<ChevronLeft className="w-6 h-6 text-gray-600" />
</button>
<div className="flex items-center gap-2">
<div className="w-10 h-10 bg-morandi-400 rounded-full flex items-center justify-center">
<Sparkles className="w-5 h-5 text-white" />
</div>
<div>
<h1 className="font-semibold text-gray-800">AI 健康顾问</h1>
<p className="text-xs text-gray-500">智能解答,随时陪伴</p>
</div>
</div>
</div>
</div>
</div>
{/* 消息列表 */}
<div className="flex-1 overflow-y-auto">
<div className="mx-auto px-4 py-6 space-y-4">
<AnimatePresence>
{messages.map((message) => (
<motion.div
key={message.id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
className={`flex gap-3 ${
message.role === "user" ? "flex-row-reverse" : ""
}`}
>
<div
className={`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${
message.role === "user"
? "bg-morandi-100"
: "bg-morandi-400"
}`}
>
{message.role === "user" ? (
<User className="w-5 h-5 text-morandi-500" />
) : (
<Bot className="w-5 h-5 text-white" />
)}
</div>
<Card
className={`max-w-[75%] p-4 rounded-2xl border-0 ${
message.role === "user"
? "bg-morandi-400 text-white"
: "bg-white shadow-sm"
}`}
>
<p
className={`text-sm leading-relaxed whitespace-pre-line ${
message.role === "user" ? "text-white" : "text-gray-700"
}`}
>
{message.content}
</p>
<p
className={`text-xs mt-2 ${
message.role === "user"
? "text-morandi-100"
: "text-gray-400"
}`}
>
{message.timestamp.toLocaleTimeString("zh-CN", {
hour: "2-digit",
minute: "2-digit",
})}
</p>
</Card>
</motion.div>
))}
</AnimatePresence>
{isTyping && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="flex gap-3"
>
<div className="w-10 h-10 bg-morandi-400 rounded-full flex items-center justify-center">
<Bot className="w-5 h-5 text-white" />
</div>
<Card className="bg-white shadow-sm p-4 rounded-2xl">
<div className="flex gap-1">
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
<div
className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"
style={{ animationDelay: "0.1s" }}
></div>
<div
className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"
style={{ animationDelay: "0.2s" }}
></div>
</div>
</Card>
</motion.div>
)}
<div ref={messagesEndRef} />
</div>
</div>
{/* 快捷提问 */}
{messages.length <= 1 && (
<div className="mx-auto px-4 pb-4">
<div className="flex items-center gap-2 mb-3">
<Lightbulb className="w-4 h-4 text-morandi-400" />
<p className="text-sm text-gray-600">试试这样问:</p>
</div>
<div className="grid grid-cols-2 gap-2">
{quickQuestions.map((question, index) => (
<button
key={index}
onClick={() => handleQuickQuestion(question)}
className="bg-white rounded-xl p-3 text-sm text-left text-gray-600 hover:bg-morandi-50 hover:text-morandi-500 transition-colors border border-gray-100"
>
{question}
</button>
))}
</div>
</div>
)}
{/* 输入框 */}
<div className="bg-white border-t border-gray-100 sticky bottom-0">
<div className="mx-auto px-4 py-4">
<div className="flex gap-3">
<Input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === "Enter" && handleSend()}
placeholder="输入您的问题..."
className="flex-1 rounded-full border-gray-200 focus:border-morandi-200"
/>
<Button
onClick={handleSend}
disabled={!input.trim() || isTyping}
className="w-12 h-12 rounded-full bg-morandi-400 hover:from-morandi-500 hover:to-morandi-500 disabled:opacity-50"
>
<Send className="w-5 h-5 text-white" />
</Button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,842 @@
import { useState, useRef, useEffect, useMemo } from "react";
import { useNavigate } from "react-router";
import { motion } from "motion/react";
import {
ChevronLeft,
Calendar as CalendarIcon,
Bell,
Clock,
AlertCircle,
CheckCircle2,
Plus,
X,
FileText,
ChevronRight,
Upload,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Card } from "../components/ui/card";
import { Badge } from "../components/ui/badge";
import { useUser } from "../context/UserContext";
import { checkupSchedule } from "../data/checkupSchedule";
import {
getCheckupPlan,
completeCheckup,
getReportList,
type ReportListItem,
} from "../services/api";
interface Checkup {
id: string;
title: string;
week: number;
date: string;
items: string[];
preparations: string[];
notes: string;
status: "upcoming" | "completed" | "missed";
importance: "high" | "medium" | "low";
report_ids: string[];
}
/**
* 检查项目 → 报告类型 关键词映射
* checkup.items 中的项目名 → 报告 report_type 中可能出现的关键词
*/
const ITEM_REPORT_KEYWORDS: Record<string, string[]> = {
"NT检查(胎儿颈部透明带)": ["NT", "颈部透明带", "B超", "超声"],
"血常规": ["血常规"],
"尿常规": ["尿常规"],
"肝肾功能": ["肝功能", "肾功能", "肝肾", "生化"],
"血型检查": ["血型"],
"传染病筛查": ["传染病", "乙肝", "艾滋", "梅毒", "丙肝"],
"血清学唐氏筛查": ["唐筛", "唐氏", "唐氏筛查"],
"B超检查": ["B超", "超声", "彩超"],
"四维彩超": ["四维", "彩超", "大排畸", "B超", "超声"],
"胎儿系统超声筛查": ["系统超声", "四维", "大排畸", "B超", "超声"],
"75g OGTT(葡萄糖耐量试验)": ["糖耐", "OGTT", "葡萄糖耐量", "血糖"],
"胎心监护": ["胎心", "胎监", "NST"],
"骨盆测量": ["骨盆"],
"心电图": ["心电图", "ECG"],
"血压测量": ["血压"],
"宫高腹围": ["宫高", "腹围"],
};
/** 判断某个检查项目是否有对应的报告覆盖 */
function isItemCoveredByReports(item: string, reports: ReportListItem[]): boolean {
// 先查映射表
const keywords = ITEM_REPORT_KEYWORDS[item];
if (keywords) {
return reports.some((r) =>
keywords.some((kw) => r.report_type.includes(kw))
);
}
// 兜底:直接用项目名中的核心关键词匹配
// 去掉括号内容后取前几个字
const core = item.replace(/[((].+?[))]/g, "").trim();
return reports.some((r) => r.report_type.includes(core) || core.includes(r.report_type));
}
/** 获取某次产检中缺少报告的检查项目 */
function getMissingItems(checkup: Checkup, linkedReports: ReportListItem[]): string[] {
if (linkedReports.length === 0) return checkup.items;
// 血压测量、宫高腹围通常不需要独立报告,排除
const skipItems = ["血压测量", "宫高腹围"];
return checkup.items.filter(
(item) => !skipItems.includes(item) && !isItemCoveredByReports(item, linkedReports)
);
}
/** 将报告匹配到产检:优先使用服务端关联的 report_ids,其次按 pregnancy_week ±2 周模糊匹配 */
function buildCheckupReportMap(
checkups: Checkup[],
reports: ReportListItem[]
): Map<string, ReportListItem[]> {
const map = new Map<string, ReportListItem[]>();
const assigned = new Set<string>();
const reportById = new Map(reports.map((r) => [r.id, r]));
const sorted = [...checkups].sort((a, b) => a.week - b.week);
// First pass: use server-linked report_ids
for (const c of sorted) {
const linked: ReportListItem[] = [];
for (const rid of c.report_ids || []) {
const r = reportById.get(rid);
if (r) {
linked.push(r);
assigned.add(rid);
}
}
map.set(c.id, linked);
}
// Second pass: fuzzy match remaining reports by pregnancy_week (±2 weeks)
for (const c of sorted) {
const existing = map.get(c.id) || [];
const fuzzyMatched = reports
.filter(
(r) =>
!assigned.has(r.id) &&
r.pregnancy_week != null &&
Math.abs(r.pregnancy_week - c.week) <= 2
)
.sort(
(a, b) =>
Math.abs(a.pregnancy_week! - c.week) -
Math.abs(b.pregnancy_week! - c.week)
);
map.set(c.id, [...existing, ...fuzzyMatched]);
fuzzyMatched.forEach((r) => assigned.add(r.id));
}
return map;
}
export function CalendarPage() {
const navigate = useNavigate();
const { user } = useUser();
const calcCheckupDate = (week: number): string => {
if (!user.lastPeriodDate) return "";
const lmp = new Date(user.lastPeriodDate);
const date = new Date(lmp.getTime() + week * 7 * 24 * 60 * 60 * 1000);
return date.toISOString().split("T")[0];
};
const currentWeek = user.currentWeek || 0;
const getCheckupStatus = (week: number): "upcoming" | "completed" | "missed" => {
if (week < currentWeek) return "completed";
return "upcoming";
};
const [checkups, setCheckups] = useState<Checkup[]>(() =>
checkupSchedule.map((tpl, i) => ({
id: String(i + 1),
title: tpl.title,
week: tpl.week,
date: calcCheckupDate(tpl.week),
items: tpl.items,
preparations: tpl.preparations,
notes: tpl.notes,
status: getCheckupStatus(tpl.week),
importance: tpl.importance,
report_ids: [],
}))
);
const [reports, setReports] = useState<ReportListItem[]>([]);
// 获取产检计划 + 报告列表
useEffect(() => {
getCheckupPlan()
.then((data) => {
if (data.checkups && data.checkups.length > 0) {
setCheckups(
data.checkups.map((c, i) => ({
id: String(i + 1),
title: c.title,
week: c.week,
date: calcCheckupDate(c.week),
items: c.items,
preparations: c.preparations,
notes: c.notes,
status: (c.status as Checkup["status"]) || getCheckupStatus(c.week),
importance: (c.importance as Checkup["importance"]) || "medium",
report_ids: c.report_ids || [],
}))
);
}
})
.catch(() => {});
getReportList(100)
.then(setReports)
.catch(() => {});
}, []);
const checkupReportMap = useMemo(
() => buildCheckupReportMap(checkups, reports),
[checkups, reports]
);
const pastCheckups = checkups.filter((c) => c.week < currentWeek);
const upcomingCheckups = checkups.filter((c) => c.week >= currentWeek);
const nextCheckup = upcomingCheckups[0];
const detailsRefs = useRef<Record<string, HTMLDetailsElement | null>>({});
const nextCheckupRef = useRef<HTMLDivElement>(null);
// 自动滚动到即将进行的产检
useEffect(() => {
const timer = setTimeout(() => {
nextCheckupRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
}, 500);
return () => clearTimeout(timer);
}, []);
const [showAddForm, setShowAddForm] = useState(false);
const [newCheckup, setNewCheckup] = useState({
title: "",
week: "",
date: "",
items: "",
preparations: "",
notes: "",
importance: "medium" as "high" | "medium" | "low",
});
const handleAddCheckup = () => {
if (!newCheckup.title || !newCheckup.date) return;
const checkup: Checkup = {
id: Date.now().toString(),
title: newCheckup.title,
week: newCheckup.week ? parseInt(newCheckup.week) : 0,
date: newCheckup.date,
items: newCheckup.items ? newCheckup.items.split(",").map((s) => s.trim()).filter(Boolean) : [],
preparations: newCheckup.preparations ? newCheckup.preparations.split(",").map((s) => s.trim()).filter(Boolean) : [],
notes: newCheckup.notes,
status: "upcoming",
importance: newCheckup.importance,
report_ids: [],
};
setCheckups((prev) =>
[...prev, checkup].sort((a, b) => a.week - b.week)
);
setNewCheckup({ title: "", week: "", date: "", items: "", preparations: "", notes: "", importance: "medium" });
setShowAddForm(false);
};
const handleComplete = (week: number) => {
completeCheckup(week)
.then(() => {
setCheckups((prev) =>
prev.map((c) =>
c.week === week ? { ...c, status: "completed" as const } : c
)
);
})
.catch(() => {});
};
/** 渲染单个产检卡片 */
const renderCheckupCard = (checkup: Checkup, index: number, isFirstUpcoming: boolean) => {
const isPast = checkup.week < currentWeek;
const isCurrent = checkup.week >= currentWeek && checkup.week <= currentWeek + 4;
const linkedReports = checkupReportMap.get(checkup.id) || [];
const hasReports = linkedReports.length > 0;
const showUploadPrompt = isPast && !hasReports;
const missingItems = isPast ? getMissingItems(checkup, linkedReports) : [];
const hasMissing = missingItems.length > 0 && hasReports; // 有报告但不全
return (
<motion.div
key={checkup.id}
ref={isFirstUpcoming ? nextCheckupRef : undefined}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.1 + index * 0.04 }}
>
<Card
className={`rounded-2xl p-5 shadow-sm border-0 ${
isCurrent
? "bg-morandi-rose-100 border-2 border-morandi-rose-300"
: "bg-white"
} ${isPast ? "opacity-70" : ""}`}
>
<div className="flex items-start gap-4 mb-4">
<div
className={`w-12 h-12 rounded-xl flex items-center justify-center ${
checkup.status === "completed"
? "bg-morandi-sage-100"
: checkup.status === "missed"
? "bg-red-100"
: checkup.importance === "high"
? "bg-morandi-rose-100"
: "bg-morandi-100"
}`}
>
{checkup.status === "completed" ? (
<CheckCircle2 className="w-6 h-6 text-morandi-sage-400" />
) : checkup.status === "missed" ? (
<AlertCircle className="w-6 h-6 text-red-500" />
) : (
<CalendarIcon
className={`w-6 h-6 ${
checkup.importance === "high"
? "text-morandi-rose-400"
: "text-morandi-400"
}`}
/>
)}
</div>
<div className="flex-1">
<div className="flex items-center gap-2 mb-2 flex-wrap">
<h3 className="font-semibold text-gray-800 text-lg">
{checkup.title}
</h3>
{checkup.importance === "high" && (
<Badge className="bg-red-100 text-red-700 hover:bg-red-100">
重要
</Badge>
)}
{isCurrent && (
<Badge className="bg-morandi-rose-100 text-morandi-600 hover:bg-morandi-rose-100">
即将进行
</Badge>
)}
{/* 报告状态徽章 */}
{hasReports && (
<Badge className="bg-morandi-sage-50 text-morandi-sage-600 hover:bg-morandi-sage-50">
{linkedReports.length}份报告
</Badge>
)}
{hasMissing && (
<Badge className="bg-orange-50 text-orange-600 hover:bg-orange-50">
{missingItems.length}项待补传
</Badge>
)}
{showUploadPrompt && (
<Badge className="bg-amber-50 text-amber-600 hover:bg-amber-50">
缺少报告
</Badge>
)}
</div>
<div className="flex items-center gap-4 text-sm text-gray-600 mb-3">
<div className="flex items-center gap-1">
<Clock className="w-4 h-4" />
{checkup.date || "待确定"}
</div>
<div className="flex items-center gap-1">
<CalendarIcon className="w-4 h-4" />
孕{checkup.week}周
</div>
{checkup.status === "completed" && (
<Badge className="bg-morandi-sage-100 text-morandi-sage-600 hover:bg-morandi-sage-100">
已完成
</Badge>
)}
</div>
</div>
</div>
{/* 卡片级操作按钮(不需要展开即可见) */}
<div className="flex gap-2 mb-3">
{!isPast && (
<>
<Button
size="sm"
className="flex-1 bg-morandi-400 hover:bg-morandi-500 text-white"
onClick={() => navigate("/camera")}
>
<Upload className="w-4 h-4 mr-1" />
上传报告
</Button>
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={() => handleComplete(checkup.week)}
>
<CheckCircle2 className="w-4 h-4 mr-1" />
标记完成
</Button>
</>
)}
{isPast && !hasReports && (
<Button
size="sm"
className="w-full bg-morandi-rose-400 hover:bg-morandi-rose-500 text-white"
onClick={() => navigate("/camera")}
>
<Upload className="w-4 h-4 mr-1" />
上传历史报告,解读更专业
</Button>
)}
{isPast && hasReports && (
<Button
variant="outline"
size="sm"
className="w-full"
onClick={() => {
if (linkedReports.length === 1) {
navigate(`/analysis/${linkedReports[0].id}`);
} else {
const el = detailsRefs.current[checkup.id];
if (el) { el.open = true; }
}
}}
>
<FileText className="w-4 h-4 mr-1" />
{linkedReports.length === 1 ? "查看报告解读" : `查看 ${linkedReports.length} 份报告`}
</Button>
)}
</div>
{/* 漏传报告提醒 */}
{hasMissing && (
<div className="mb-3 bg-orange-50 rounded-xl p-3">
<div className="flex items-start gap-2 mb-2">
<AlertCircle className="w-4 h-4 text-orange-500 mt-0.5 flex-shrink-0" />
<div className="flex-1">
<p className="text-xs font-medium text-orange-700 mb-1.5">
以下检查项目还未上传报告,建议补充上传以获得更完整的解读
</p>
<div className="flex flex-wrap gap-1.5">
{missingItems.map((item, i) => (
<span
key={i}
className="inline-flex items-center text-[11px] bg-orange-100 text-orange-700 rounded-md px-2 py-0.5"
>
{item}
</span>
))}
</div>
</div>
</div>
<Button
size="sm"
className="w-full bg-orange-500 hover:bg-orange-600 text-white mt-1"
onClick={() => navigate("/camera")}
>
<Upload className="w-3.5 h-3.5 mr-1" />
补充上传报告
</Button>
</div>
)}
<details
ref={(el) => { detailsRefs.current[checkup.id] = el; }}
className="group"
>
<summary className="cursor-pointer text-morandi-500 text-sm font-semibold hover:text-morandi-500 list-none flex items-center gap-2 mb-3">
查看检查详情
<span className="text-xs">▼</span>
</summary>
<div className="space-y-4 pt-2">
{/* 检查项目 */}
<div>
<h4 className="font-semibold text-gray-700 mb-2 text-sm">
检查项目
</h4>
<div className="grid grid-cols-2 gap-2">
{checkup.items.map((item, i) => {
const covered = isPast && hasReports && isItemCoveredByReports(item, linkedReports);
const missing = isPast && hasReports && !isItemCoveredByReports(item, linkedReports) && !["血压测量", "宫高腹围"].includes(item);
return (
<div
key={i}
className={`text-sm flex items-center gap-2 rounded-lg px-3 py-2 ${
missing ? "bg-orange-50 text-orange-700" : covered ? "bg-morandi-sage-50 text-morandi-sage-700" : "bg-gray-50 text-gray-600"
}`}
>
<div className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${
missing ? "bg-orange-400" : covered ? "bg-morandi-sage-400" : "bg-morandi-400"
}`} />
{item}
{covered && <CheckCircle2 className="w-3 h-3 text-morandi-sage-400 ml-auto flex-shrink-0" />}
</div>
);
})}
</div>
</div>
{/* 注意事项 */}
{checkup.preparations.length > 0 && (
<div className="bg-morandi-rose-100 rounded-xl p-3">
<h4 className="font-semibold text-morandi-700 mb-2 text-sm flex items-center gap-2">
<AlertCircle className="w-4 h-4" />
注意事项
</h4>
<ul className="space-y-1">
{checkup.preparations.map((prep, i) => (
<li
key={i}
className="text-sm text-morandi-600 flex items-center gap-2"
>
<span className="w-1.5 h-1.5 bg-morandi-rose-400 rounded-full"></span>
{prep}
</li>
))}
</ul>
</div>
)}
{/* 医生提示 */}
{checkup.notes && (
<div className="bg-morandi-slate-50 rounded-xl p-3">
<p className="text-sm text-morandi-500 leading-relaxed">
💡 {checkup.notes}
</p>
</div>
)}
{/* 关联报告 */}
{hasReports && (
<div>
<h4 className="font-semibold text-gray-700 mb-2 text-sm flex items-center gap-2">
<FileText className="w-4 h-4" />
检查报告
</h4>
<div className="space-y-2">
{linkedReports.map((report) => (
<div
key={report.id}
onClick={() => navigate(`/analysis/${report.id}`)}
className="flex items-center justify-between bg-morandi-50 rounded-xl px-3 py-2.5 cursor-pointer hover:bg-morandi-100 transition-colors"
>
<div className="flex items-center gap-2 min-w-0">
<div
className={`w-2 h-2 rounded-full flex-shrink-0 ${
report.overall_status === "normal"
? "bg-morandi-sage-400"
: report.overall_status === "attention"
? "bg-amber-400"
: "bg-red-400"
}`}
/>
<span className="text-sm text-gray-700 font-medium truncate">
{report.report_type}
</span>
{report.summary && (
<span className="text-xs text-gray-400 truncate hidden sm:inline">
{report.summary}
</span>
)}
</div>
<ChevronRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
</div>
))}
</div>
</div>
)}
{/* 缺少报告提示 - 已在顶部显示,不再重复 */}
</div>
</details>
</Card>
</motion.div>
);
};
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => navigate(-1)}
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<ChevronLeft className="w-6 h-6 text-gray-600" />
</button>
<div className="flex items-center gap-2">
<div className="w-10 h-10 bg-gradient-to-br from-morandi-300 to-morandi-rose-400 rounded-full flex items-center justify-center">
<CalendarIcon className="w-5 h-5 text-white" />
</div>
<div>
<h1 className="font-semibold text-gray-800">产检日历</h1>
<p className="text-xs text-gray-500">孕期检查安排与提醒</p>
</div>
</div>
</div>
<Button
onClick={() => setShowAddForm(true)}
variant="outline"
size="sm"
className="rounded-full"
>
<Plus className="w-4 h-4 mr-2" />
自定义
</Button>
</div>
</div>
<div className="mx-auto p-4 space-y-6">
{/* 下次产检提醒 */}
{nextCheckup && (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
>
<Card className="bg-gradient-to-br from-morandi-400 to-morandi-rose-400 border-0 text-white p-6 rounded-3xl shadow-sm">
<div className="flex items-start justify-between mb-4">
<div>
<div className="flex items-center gap-2 mb-2">
<Bell className="w-5 h-5" />
<span className="text-sm text-white/90">下次产检</span>
</div>
<h2 className="text-2xl font-semibold mb-2">{nextCheckup.title}</h2>
<div className="space-y-1 text-sm text-white/90">
<div className="flex items-center gap-2">
<Clock className="w-4 h-4" />
{nextCheckup.date ? nextCheckup.date : "请设置末次月经日期"} (孕{nextCheckup.week}周)
</div>
<div className="flex items-center gap-2">
<CalendarIcon className="w-4 h-4" />
{nextCheckup.date ? (
<>
距离现在还有{" "}
{Math.max(
0,
Math.ceil(
(new Date(nextCheckup.date).getTime() -
new Date().getTime()) /
(1000 * 60 * 60 * 24)
)
)}{" "}
天
</>
) : (
<>还有 {Math.max(0, nextCheckup.week - currentWeek)} 周</>
)}
</div>
</div>
</div>
<div className="bg-white/20 backdrop-blur-sm rounded-2xl px-4 py-2">
<div className="text-xs text-white/80">当前孕周</div>
<div className="text-2xl font-semibold">{currentWeek}</div>
</div>
</div>
<Button
onClick={() => {
if (nextCheckup) {
const el = detailsRefs.current[nextCheckup.id];
if (el) {
el.open = true;
el.scrollIntoView({ behavior: "smooth", block: "start" });
}
}
}}
className="w-full bg-white text-morandi-500 hover:bg-white/90"
>
查看详情
</Button>
</Card>
</motion.div>
)}
{/* 已过产检 */}
{pastCheckups.length > 0 && (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
>
<h2 className="text-lg font-semibold text-gray-800 mb-4">
📋 已过产检
</h2>
<div className="space-y-4">
{pastCheckups.map((checkup, index) =>
renderCheckupCard(checkup, index, false)
)}
</div>
</motion.div>
)}
{/* 即将到来的产检 */}
{upcomingCheckups.length > 0 && (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.15 }}
>
<h2 className="text-lg font-semibold text-gray-800 mb-4">
📅 即将到来
</h2>
<div className="space-y-4">
{upcomingCheckups.map((checkup, index) =>
renderCheckupCard(checkup, index, index === 0)
)}
</div>
</motion.div>
)}
{/* 温馨提示 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.6 }}
>
<Card className="bg-gradient-to-r from-morandi-50 to-morandi-50 border-morandi-200 rounded-2xl p-4">
<h3 className="font-semibold text-gray-800 mb-2">📅 产检小贴士</h3>
<ul className="space-y-1 text-sm text-gray-600">
<li>• 建议提前预约,避免等待时间过长</li>
<li>• 携带好病历本和既往检查结果</li>
<li>• 产检当天穿宽松舒适的衣服,便于检查</li>
<li>• 有问题记录下来,产检时向医生咨询</li>
<li>• 孕晚期建议家人陪同产检</li>
</ul>
</Card>
</motion.div>
</div>
{/* 自定义产检弹窗 */}
{showAddForm && (
<div className="fixed inset-0 bg-black/40 z-50 flex items-end sm:items-center justify-center">
<motion.div
initial={{ opacity: 0, y: 40 }}
animate={{ opacity: 1, y: 0 }}
className="bg-white w-full sm:max-w-md rounded-t-3xl sm:rounded-3xl p-6 max-h-[85vh] overflow-y-auto"
>
<div className="flex items-center justify-between mb-5">
<h2 className="font-semibold text-gray-800 text-lg">添加自定义产检</h2>
<button
onClick={() => setShowAddForm(false)}
className="w-8 h-8 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<X className="w-5 h-5 text-gray-400" />
</button>
</div>
<div className="space-y-4">
<div>
<label className="text-sm text-gray-600 mb-1 block">产检名称 *</label>
<input
type="text"
placeholder="例如:常规产检"
value={newCheckup.title}
onChange={(e) => setNewCheckup({ ...newCheckup, title: e.target.value })}
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-sm text-gray-600 mb-1 block">孕周</label>
<input
type="number"
placeholder="例如:20"
value={newCheckup.week}
onChange={(e) => setNewCheckup({ ...newCheckup, week: e.target.value })}
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
/>
</div>
<div>
<label className="text-sm text-gray-600 mb-1 block">日期 *</label>
<input
type="date"
value={newCheckup.date}
onChange={(e) => setNewCheckup({ ...newCheckup, date: e.target.value })}
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
/>
</div>
</div>
<div>
<label className="text-sm text-gray-600 mb-1 block">重要程度</label>
<div className="flex gap-2">
{([["high", "重要"], ["medium", "一般"], ["low", "普通"]] as const).map(([val, label]) => (
<button
key={val}
onClick={() => setNewCheckup({ ...newCheckup, importance: val })}
className={`flex-1 py-2 rounded-xl text-sm font-medium transition-all ${
newCheckup.importance === val
? "bg-morandi-400 text-white"
: "bg-morandi-50 text-gray-500 hover:bg-morandi-100"
}`}
>
{label}
</button>
))}
</div>
</div>
<div>
<label className="text-sm text-gray-600 mb-1 block">检查项目</label>
<input
type="text"
placeholder="用中文逗号分隔,例如:血常规,尿常规"
value={newCheckup.items}
onChange={(e) => setNewCheckup({ ...newCheckup, items: e.target.value })}
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
/>
</div>
<div>
<label className="text-sm text-gray-600 mb-1 block">注意事项</label>
<input
type="text"
placeholder="用中文逗号分隔,例如:需空腹,携带病历本"
value={newCheckup.preparations}
onChange={(e) => setNewCheckup({ ...newCheckup, preparations: e.target.value })}
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
/>
</div>
<div>
<label className="text-sm text-gray-600 mb-1 block">备注</label>
<input
type="text"
placeholder="可选,医生提示或其他备注"
value={newCheckup.notes}
onChange={(e) => setNewCheckup({ ...newCheckup, notes: e.target.value })}
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
/>
</div>
<div className="flex gap-3 pt-2">
<Button
variant="outline"
className="flex-1"
onClick={() => setShowAddForm(false)}
>
取消
</Button>
<Button
className="flex-1 bg-morandi-400 hover:bg-morandi-500 text-white"
onClick={handleAddCheckup}
>
添加
</Button>
</div>
</div>
</motion.div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,511 @@
import { useState, useRef, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import { motion, AnimatePresence } from "motion/react";
import {
Camera,
X,
Check,
RotateCw,
Zap,
Image as ImageIcon,
AlertCircle,
Loader2,
Plus,
ChevronRight,
Trash2,
} from "lucide-react";
import { Button } from "../components/ui/button";
import {
uploadReportImage,
addImageToReport,
type UploadReportResponse,
type OcrDataItem,
} from "../services/api";
/** 压缩图片:限制最大宽度 1200px,JPEG 质量 0.7 */
function compressImage(file: File, maxWidth = 1200, quality = 0.7): Promise<File> {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
let { width, height } = img;
if (width > maxWidth) {
height = Math.round((height * maxWidth) / width);
width = maxWidth;
}
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d")!;
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(
(blob) => {
resolve(blob ? new File([blob], "report.jpg", { type: "image/jpeg" }) : file);
},
"image/jpeg",
quality
);
};
img.src = URL.createObjectURL(file);
});
}
interface ImageEntry {
id: string;
preview: string; // data URL for thumbnail
status: "uploading" | "done" | "error";
error?: string;
ocrItems: OcrDataItem[];
reportType: string;
}
export function CameraCapturePage() {
const navigate = useNavigate();
// Multi-image state
const [images, setImages] = useState<ImageEntry[]>([]);
const [reportId, setReportId] = useState<string | null>(null);
const [notPregnancyTip, setNotPregnancyTip] = useState<string | null>(null);
// Camera state
const [isCapturing, setIsCapturing] = useState(true); // show camera view
const [showTips, setShowTips] = useState(true);
const [cameraError, setCameraError] = useState<string | null>(null);
const [cameraReady, setCameraReady] = useState(false);
const videoRef = useRef<HTMLVideoElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const streamRef = useRef<MediaStream | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
// 启动摄像头
const startCamera = useCallback(async () => {
try {
setCameraError(null);
if (!window.isSecureContext) {
setCameraError("摄像头需要 HTTPS 安全连接,请使用「从相册选择」");
return;
}
if (!navigator.mediaDevices?.getUserMedia) {
setCameraError("当前浏览器不支持摄像头,请使用相册上传");
return;
}
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: "environment", width: { ideal: 1920 }, height: { ideal: 1080 } },
audio: false,
});
streamRef.current = stream;
if (videoRef.current) {
videoRef.current.srcObject = stream;
videoRef.current.onloadedmetadata = () => {
videoRef.current?.play();
setCameraReady(true);
};
}
} catch {
setCameraError("无法访问摄像头,请检查权限设置或使用相册上传");
}
}, []);
const stopCamera = useCallback(() => {
if (streamRef.current) {
streamRef.current.getTracks().forEach((track) => track.stop());
streamRef.current = null;
}
setCameraReady(false);
}, []);
useEffect(() => {
if (isCapturing) startCamera();
return () => stopCamera();
}, [isCapturing, startCamera, stopCamera]);
// 上传单张图片(自动判断是首张还是追加)
const uploadImage = useCallback(
async (file: File, preview: string) => {
const entryId = Date.now().toString();
const entry: ImageEntry = {
id: entryId,
preview,
status: "uploading",
ocrItems: [],
reportType: "",
};
setImages((prev) => [...prev, entry]);
try {
const compressed = await compressImage(file);
let ocrItems: OcrDataItem[] = [];
let reportType = "";
if (!reportId) {
// First image — create report
const result: UploadReportResponse = await uploadReportImage(compressed);
setReportId(result.report_id);
ocrItems = result.ocr_result.data_items;
reportType = result.ocr_result.report_type;
} else {
// Additional image — add to existing report
const result = await addImageToReport(reportId, compressed);
ocrItems = result.ocr_result.data_items;
reportType = result.ocr_result.report_type;
}
setImages((prev) =>
prev.map((img) =>
img.id === entryId
? { ...img, status: "done", ocrItems, reportType }
: img
)
);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "识别失败";
// 非孕期报告提示
if (msg.includes("请上传孕期检查报告") || msg.includes("请上传孕期")) {
setNotPregnancyTip(msg);
// 移除该图片
setImages((prev) => prev.filter((img) => img.id !== entryId));
return;
}
const friendlyMsg = /load failed|failed to fetch|networkerror/i.test(msg)
? "网络连接失败"
: msg.length > 100
? "AI 识别服务暂时不可用"
: msg;
setImages((prev) =>
prev.map((img) =>
img.id === entryId ? { ...img, status: "error", error: friendlyMsg } : img
)
);
}
},
[reportId]
);
// 拍照
const handleCapture = () => {
if (!videoRef.current || !canvasRef.current) return;
const video = videoRef.current;
const canvas = canvasRef.current;
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.drawImage(video, 0, 0);
const dataUrl = canvas.toDataURL("image/jpeg", 0.9);
setShowTips(false);
canvas.toBlob((blob) => {
if (blob) {
const file = new File([blob], "report.jpg", { type: "image/jpeg" });
uploadImage(file, dataUrl);
}
}, "image/jpeg", 0.9);
};
// 相册选择(支持多选)
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files?.length) return;
setShowTips(false);
Array.from(files).forEach((file) => {
const reader = new FileReader();
reader.onload = (ev) => {
const preview = ev.target?.result as string;
uploadImage(file, preview);
};
reader.readAsDataURL(file);
});
e.target.value = "";
};
// 删除某张图片(仅从前端列表移除,不影响已上传的数据)
const removeImage = (id: string) => {
setImages((prev) => prev.filter((img) => img.id !== id));
};
// 统计
const doneCount = images.filter((img) => img.status === "done").length;
const uploadingCount = images.filter((img) => img.status === "uploading").length;
const totalOcrItems = images.reduce((sum, img) => sum + img.ocrItems.length, 0);
const allDone = images.length > 0 && uploadingCount === 0;
// 进入校验页面
const handleGoToVerify = () => {
if (!reportId || !allDone) return;
// Merge all OCR items for navigation state
const mergedItems = images.flatMap((img) => img.ocrItems);
const reportTypes = [...new Set(images.map((img) => img.reportType).filter(Boolean))];
navigate("/verify", {
state: {
reportId,
ocrResult: {
report_type: reportTypes.join("+"),
data_items: mergedItems,
patient_name: "",
},
imageUrls: images.map((img) => img.preview),
},
});
};
const handleAlbumClick = () => {
fileInputRef.current?.click();
};
return (
<div className="min-h-dvh bg-black relative overflow-hidden">
<input
ref={fileInputRef}
type="file"
accept="image/*"
multiple
className="hidden"
onChange={handleFileChange}
/>
<canvas ref={canvasRef} className="hidden" />
{/* 顶部导航栏 */}
<div className="absolute top-0 left-0 right-0 z-20 bg-gradient-to-b from-black/50 to-transparent">
<div className="flex items-center justify-between p-4">
<button
onClick={() => { stopCamera(); navigate(-1); }}
className="p-2 rounded-full bg-black/30 backdrop-blur-sm"
>
<X className="w-6 h-6 text-white" />
</button>
<h1 className="text-white font-medium">拍摄检查报告</h1>
<div className="w-10" />
</div>
</div>
{/* 相机预览区域 */}
<div className="relative w-full h-screen flex items-center justify-center">
<video
ref={videoRef}
autoPlay playsInline muted
className={`w-full h-full object-cover ${cameraReady ? "block" : "hidden"}`}
/>
{!cameraReady && (
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
className="w-full h-full bg-gray-900 flex items-center justify-center">
<div className="text-center px-8">
{cameraError ? (
<>
<AlertCircle className="w-12 h-12 text-gray-500 mx-auto mb-4" />
<p className="text-gray-400 text-sm mb-4">{cameraError}</p>
<Button onClick={handleAlbumClick} className="bg-morandi-400 hover:bg-morandi-500 text-white">
<ImageIcon className="w-4 h-4 mr-2" />从相册选择
</Button>
</>
) : (
<>
<motion.div animate={{ rotate: 360 }} transition={{ duration: 2, repeat: Infinity, ease: "linear" }}>
<Camera className="w-12 h-12 text-gray-500 mx-auto" />
</motion.div>
<p className="text-gray-400 mt-4">正在启动摄像头...</p>
</>
)}
</div>
</motion.div>
)}
{/* 取景框辅助线 */}
{cameraReady && (
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
className="absolute inset-0 flex items-center justify-center pointer-events-none">
<div className="relative w-11/12 max-w-md aspect-[3/4] border-2 border-white/50 rounded-2xl">
<div className="absolute top-0 left-0 w-8 h-8 border-l-4 border-t-4 border-morandi-500 rounded-tl-2xl" />
<div className="absolute top-0 right-0 w-8 h-8 border-r-4 border-t-4 border-morandi-500 rounded-tr-2xl" />
<div className="absolute bottom-0 left-0 w-8 h-8 border-l-4 border-b-4 border-morandi-500 rounded-bl-2xl" />
<div className="absolute bottom-0 right-0 w-8 h-8 border-r-4 border-b-4 border-morandi-500 rounded-br-2xl" />
</div>
</motion.div>
)}
</div>
{/* 拍摄提示 */}
<AnimatePresence>
{showTips && cameraReady && images.length === 0 && (
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -20 }}
className="absolute top-24 left-0 right-0 z-10">
<div className="mx-auto max-w-sm px-4">
<div className="bg-morandi-400 text-white rounded-2xl p-4 shadow-sm">
<div className="flex items-start gap-3">
<Zap className="w-5 h-5 flex-shrink-0 mt-0.5" />
<div className="flex-1">
<h3 className="font-semibold mb-1">支持多张报告</h3>
<ul className="text-sm space-y-1 opacity-90">
<li>- 可拍摄多张报告,AI 合并解读</li>
<li>- 确保光线充足,避免反光</li>
<li>- 将报告完整放入取景框内</li>
</ul>
</div>
<button onClick={() => setShowTips(false)} className="p-1 hover:bg-white/20 rounded-lg">
<X className="w-4 h-4" />
</button>
</div>
</div>
</div>
</motion.div>
)}
</AnimatePresence>
{/* 已添加图片缩略图条 */}
{images.length > 0 && (
<div className="absolute top-20 left-0 right-0 z-10 px-4">
<div className="mx-auto max-w-lg">
<div className="bg-black/60 backdrop-blur-sm rounded-2xl p-3">
<div className="flex items-center justify-between mb-2">
<span className="text-white text-sm font-medium">
已添加 {images.length} 张报告
{totalOcrItems > 0 && (
<span className="text-white/70 ml-1">· {totalOcrItems} 项指标</span>
)}
</span>
{uploadingCount > 0 && (
<span className="text-amber-300 text-xs flex items-center">
<Loader2 className="w-3 h-3 mr-1 animate-spin" />
识别中 {uploadingCount} 张
</span>
)}
</div>
<div className="flex gap-2 overflow-x-auto pb-1">
{images.map((img) => (
<div key={img.id} className="relative flex-shrink-0 w-16 h-16 rounded-xl overflow-hidden">
<img src={img.preview} alt="" className="w-full h-full object-cover" />
{/* Status overlay */}
{img.status === "uploading" && (
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
<Loader2 className="w-5 h-5 text-white animate-spin" />
</div>
)}
{img.status === "done" && (
<div className="absolute top-1 right-1 w-5 h-5 bg-green-500 rounded-full flex items-center justify-center">
<Check className="w-3 h-3 text-white" />
</div>
)}
{img.status === "error" && (
<div className="absolute inset-0 bg-red-500/50 flex items-center justify-center">
<AlertCircle className="w-5 h-5 text-white" />
</div>
)}
{/* Remove button */}
<button
onClick={() => removeImage(img.id)}
className="absolute top-1 left-1 w-5 h-5 bg-black/60 rounded-full flex items-center justify-center"
>
<X className="w-3 h-3 text-white" />
</button>
</div>
))}
</div>
</div>
</div>
</div>
)}
{/* 底部操作区 */}
<div className="absolute bottom-0 left-0 right-0 z-20 bg-gradient-to-t from-black/80 to-transparent pb-8 pt-12">
<div className="mx-auto px-4">
{/* 主操作按钮行 */}
<div className="flex items-center justify-center gap-8">
{/* 相册 */}
<motion.div initial={{ scale: 0.8, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} className="text-center">
<Button onClick={handleAlbumClick} variant="outline" size="lg"
className="w-16 h-16 rounded-full bg-white/20 backdrop-blur-sm border-2 border-white/50 hover:bg-white/30">
<ImageIcon className="w-6 h-6 text-white" />
</Button>
<p className="text-white text-xs text-center mt-2">相册</p>
</motion.div>
{/* 拍摄 */}
<motion.div initial={{ scale: 0.8, opacity: 0 }} animate={{ scale: 1, opacity: 1 }}
transition={{ delay: 0.1 }} className="text-center">
<Button onClick={handleCapture} disabled={!cameraReady} size="lg"
className="w-20 h-20 rounded-full bg-white hover:bg-gray-100 shadow-sm shadow-white/50 border-4 border-gray-800 disabled:opacity-50">
<div className="w-16 h-16 rounded-full bg-gradient-to-br from-morandi-400 to-morandi-500" />
</Button>
<p className="text-white text-sm text-center mt-2 font-medium">拍摄</p>
</motion.div>
{/* 开始解读 / 继续添加状态 */}
<motion.div initial={{ scale: 0.8, opacity: 0 }} animate={{ scale: 1, opacity: 1 }}
transition={{ delay: 0.2 }} className="text-center">
{images.length > 0 ? (
<>
<Button
onClick={handleGoToVerify}
disabled={!allDone || doneCount === 0}
size="lg"
className="w-16 h-16 rounded-full bg-gradient-to-br from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 shadow-sm disabled:opacity-50"
>
<ChevronRight className="w-7 h-7 text-white" />
</Button>
<p className="text-white text-xs text-center mt-2">
{uploadingCount > 0 ? "识别中..." : "开始解读"}
</p>
</>
) : (
<div className="w-16" />
)}
</motion.div>
</div>
</div>
</div>
{/* 隐私保护提示 */}
{images.length === 0 && !notPregnancyTip && (
<div className="absolute bottom-32 left-0 right-0 z-10">
<div className="mx-auto max-w-sm px-4">
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.5 }}
className="bg-black/50 backdrop-blur-sm text-white rounded-xl p-3 flex items-center gap-2">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
<p className="text-xs opacity-90">您的隐私受到保护,个人信息将自动脱敏处理</p>
</motion.div>
</div>
</div>
)}
{/* 非孕期报告提示弹窗 */}
<AnimatePresence>
{notPregnancyTip && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 px-8"
onClick={() => setNotPregnancyTip(null)}
>
<motion.div
initial={{ scale: 0.85, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.85, opacity: 0 }}
onClick={(e) => e.stopPropagation()}
className="bg-white rounded-2xl p-6 w-full max-w-sm shadow-xl"
>
<div className="flex flex-col items-center gap-3 mb-5">
<div className="w-14 h-14 bg-amber-50 rounded-full flex items-center justify-center">
<AlertCircle className="w-7 h-7 text-amber-500" />
</div>
<h3 className="font-semibold text-gray-800 text-lg">非孕期报告</h3>
<p className="text-sm text-gray-500 text-center leading-relaxed">
{notPregnancyTip}
</p>
</div>
<div className="bg-amber-50 rounded-xl p-3 mb-5">
<p className="text-xs text-gray-600 leading-relaxed">
💡 支持的报告类型:B超/彩超、血常规、尿常规、唐氏筛查、糖耐量、肝肾功能、TORCH、甲功等孕期产检报告
</p>
</div>
<Button
onClick={() => setNotPregnancyTip(null)}
className="w-full h-11 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium"
>
我知道了,重新上传
</Button>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}

View File

@@ -0,0 +1,398 @@
import { useState } from "react";
import { useNavigate, useLocation } from "react-router";
import { motion, AnimatePresence } from "motion/react";
import {
Check,
X,
Edit2,
ChevronLeft,
CheckCircle2,
Info,
ChevronDown,
ChevronUp,
Loader2,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Checkbox } from "../components/ui/checkbox";
import { Badge } from "../components/ui/badge";
import { verifyReport } from "../services/api";
interface DataItem {
id: string;
name: string;
value: string;
unit: string;
referenceRange: string;
status: "normal" | "high" | "low";
editable: boolean;
category: string;
}
export function DataVerificationPage() {
const navigate = useNavigate();
const location = useLocation();
const { reportId, ocrResult, imageUrls } = (location.state || {}) as {
reportId?: string;
ocrResult?: { report_type: string; data_items: { name: string; value: string; unit: string; reference_range: string; status: "normal" | "high" | "low"; category: string }[]; patient_name: string };
imageUrl?: string;
imageUrls?: string[];
};
const imageCount = imageUrls?.length || 1;
const [editingId, setEditingId] = useState<string | null>(null);
const [symptoms, setSymptoms] = useState<string[]>([]);
const [submitting, setSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
// Initialize from OCR data or fallback to empty
const initialItems: DataItem[] = ocrResult?.data_items?.map((item, i) => ({
id: String(i),
name: item.name,
value: item.value,
unit: item.unit,
referenceRange: item.reference_range,
status: item.status,
editable: true,
category: item.category || "检查项目",
})) || [];
const [dataItems, setDataItems] = useState<DataItem[]>(initialItems);
const [expandedCategories, setExpandedCategories] = useState<string[]>(
() => {
const cats = Array.from(new Set(initialItems.map((item) => item.category)));
return cats.length > 0 ? [cats[0]] : [];
}
);
const symptomOptions = [
{ id: "bleeding", label: "见红", icon: "🩸" },
{ id: "pain", label: "腹痛", icon: "💔" },
{ id: "vomit", label: "严重孕吐", icon: "🤢" },
{ id: "dizzy", label: "头晕", icon: "😵" },
{ id: "tired", label: "极度疲劳", icon: "😴" },
];
const categories = Array.from(new Set(dataItems.map((item) => item.category)));
const handleEdit = (id: string) => {
setEditingId(id);
};
const handleSave = (id: string, newValue: string) => {
setDataItems(
dataItems.map((item) =>
item.id === id ? { ...item, value: newValue } : item
)
);
setEditingId(null);
};
const handleSymptomToggle = (symptomId: string) => {
setSymptoms(
symptoms.includes(symptomId)
? symptoms.filter((s) => s !== symptomId)
: [...symptoms, symptomId]
);
};
const toggleCategory = (category: string) => {
setExpandedCategories(
expandedCategories.includes(category)
? expandedCategories.filter((c) => c !== category)
: [...expandedCategories, category]
);
};
const handleSubmit = async () => {
if (!reportId) {
navigate("/camera");
return;
}
setSubmitting(true);
setSubmitError(null);
try {
await verifyReport(reportId, {
data_items: dataItems.map((item) => ({
name: item.name,
value: item.value,
unit: item.unit,
reference_range: item.referenceRange,
status: item.status,
category: item.category,
})),
symptoms,
notes: "",
report_type: ocrResult?.report_type,
});
navigate(`/analysis/${reportId}`);
} catch (err: unknown) {
setSubmitError(err instanceof Error ? err.message : "提交失败,请重试");
} finally {
setSubmitting(false);
}
};
const totalCount = dataItems.length;
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<button
onClick={() => navigate(-1)}
className="flex items-center text-gray-600 hover:text-gray-900"
>
<ChevronLeft className="w-5 h-5 mr-1" />
返回
</button>
<h1 className="font-semibold text-gray-800">数据核对</h1>
<div className="w-16"></div>
</div>
</div>
<div className="mx-auto p-4 space-y-6">
{/* 识别状态卡片 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="bg-white rounded-3xl shadow-sm p-6"
>
<div className="flex items-start gap-4">
<div className="w-12 h-12 bg-morandi-sage-100 rounded-full flex items-center justify-center flex-shrink-0">
<CheckCircle2 className="w-6 h-6 text-morandi-sage-400" />
</div>
<div className="flex-1">
<h2 className="font-semibold text-gray-800 mb-1">
识别完成!
</h2>
<p className="text-sm text-gray-600 mb-3">
{imageCount > 1 ? `已从 ${imageCount} 张报告中` : "已"}识别 {totalCount} 项指标,请核对数据是否准确
</p>
<Badge className="bg-morandi-100 text-morandi-500 hover:bg-morandi-100">
共 {totalCount} 项
</Badge>
</div>
</div>
</motion.div>
{/* 快速操作提示 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
className="bg-morandi-50 border border-morandi-200 rounded-2xl p-4"
>
<div className="flex items-start gap-3">
<Info className="w-5 h-5 text-morandi-400 flex-shrink-0 mt-0.5" />
<div className="flex-1">
<p className="text-sm text-morandi-500 font-medium mb-1">
快速校对指南
</p>
<p className="text-xs text-morandi-600 leading-relaxed">
• 点击数值可快速编辑 • 请仔细核对识别结果 • 确认无误后生成AI解读
</p>
</div>
</div>
</motion.div>
{/* 数据列表 - 按分类展示 */}
<div className="space-y-4">
{categories.map((category, categoryIndex) => {
const categoryItems = dataItems.filter((item) => item.category === category);
const isExpanded = expandedCategories.includes(category);
return (
<motion.div
key={category}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 + categoryIndex * 0.1 }}
className="bg-white rounded-3xl shadow-sm overflow-hidden"
>
{/* 分类标题 */}
<button
onClick={() => toggleCategory(category)}
className="w-full px-6 py-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
>
<div className="flex items-center gap-3">
<h3 className="font-semibold text-gray-800">{category}</h3>
<Badge variant="secondary" className="bg-gray-100 text-gray-600">
{categoryItems.length} 项
</Badge>
</div>
{isExpanded ? (
<ChevronUp className="w-5 h-5 text-gray-400" />
) : (
<ChevronDown className="w-5 h-5 text-gray-400" />
)}
</button>
{/* 分类项目列表 */}
<AnimatePresence>
{isExpanded && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: "auto", opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.3 }}
className="overflow-hidden"
>
<div className="px-4 pb-4 space-y-2">
{categoryItems.map((item, index) => (
<motion.div
key={item.id}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.05 }}
className="rounded-2xl p-4 border-2 transition-all bg-white border-gray-100 hover:border-gray-200"
>
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<h4 className="font-medium text-gray-800">
{item.name}
</h4>
</div>
<button
onClick={() => handleEdit(item.id)}
className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
>
<Edit2 className="w-4 h-4 text-gray-400" />
</button>
</div>
<div className="flex items-end gap-4">
{editingId === item.id ? (
<div className="flex-1 flex items-center gap-2">
<Input
type="text"
defaultValue={item.value}
autoFocus
onKeyDown={(e) => {
if (e.key === "Enter") {
handleSave(
item.id,
e.currentTarget.value
);
}
}}
className="h-10 rounded-xl border-2 border-morandi-200 focus:border-morandi-500"
/>
<Button
onClick={() =>
handleSave(
item.id,
(document.querySelector(`input`) as HTMLInputElement)?.value || item.value
)
}
size="sm"
className="h-10 bg-morandi-sage-400 hover:bg-morandi-sage-500"
>
<Check className="w-4 h-4" />
</Button>
<Button
onClick={() => setEditingId(null)}
size="sm"
variant="outline"
className="h-10"
>
<X className="w-4 h-4" />
</Button>
</div>
) : (
<>
<div className="flex-1">
<div className="flex items-baseline gap-2 mb-1">
<span className="text-2xl font-semibold text-gray-800">
{item.value}
</span>
<span className="text-sm text-gray-500">
{item.unit}
</span>
</div>
<p className="text-xs text-gray-500">
参考范围:{item.referenceRange}
</p>
</div>
</>
)}
</div>
</motion.div>
))}
</div>
</motion.div>
)}
</AnimatePresence>
</motion.div>
);
})}
</div>
{/* 症状勾选 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.5 }}
className="bg-white rounded-3xl shadow-sm p-6"
>
<h3 className="font-semibold text-gray-800 mb-4">
当前身体状况(可选)
</h3>
<p className="text-sm text-gray-600 mb-4">
勾选您目前的症状,帮助 AI 进行更准确的健康评估
</p>
<div className="grid grid-cols-2 gap-3">
{symptomOptions.map((symptom) => (
<label
key={symptom.id}
className={`flex items-center gap-3 p-4 rounded-2xl border-2 cursor-pointer transition-all ${
symptoms.includes(symptom.id)
? "border-morandi-500 bg-morandi-50"
: "border-gray-200 hover:border-gray-300"
}`}
>
<Checkbox
checked={symptoms.includes(symptom.id)}
onCheckedChange={() => handleSymptomToggle(symptom.id)}
className="w-5 h-5"
/>
<div className="flex-1">
<span className="text-2xl mr-2">{symptom.icon}</span>
<span className="text-sm font-medium text-gray-700">
{symptom.label}
</span>
</div>
</label>
))}
</div>
</motion.div>
{/* 提交按钮 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.6 }}
className="sticky bottom-4"
>
<Button
onClick={handleSubmit}
disabled={submitting}
className="w-full h-14 rounded-2xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium shadow-sm"
>
{submitting ? (
<Loader2 className="w-5 h-5 mr-2 animate-spin" />
) : (
<Check className="w-5 h-5 mr-2" />
)}
{submitting ? "提交中..." : "确认并生成 AI 解读"}
</Button>
{submitError && (
<p className="text-red-500 text-sm text-center mt-2">{submitError}</p>
)}
</motion.div>
</div>
</div>
);
}

View File

@@ -0,0 +1,225 @@
import { useNavigate } from "react-router";
import { Card } from "../components/ui/card";
import { Button } from "../components/ui/button";
import {
LogIn,
UserPlus,
Home,
Camera,
FileCheck,
Sparkles,
FileText,
MessageCircle,
Mic,
HeartPulse,
TrendingUp,
Clock,
CalendarDays,
Stethoscope,
Share2,
Users,
Bell,
User,
} from "lucide-react";
export function DevNavigationPage() {
const navigate = useNavigate();
const modules = [
{
title: "模块一:登录与初始化",
pages: [
{
name: "登录页面",
path: "/",
icon: LogIn,
description: "支持微信、手机号、Apple ID登录",
},
{
name: "用户画像页面",
path: "/onboarding",
icon: UserPlus,
description: "收集孕周信息和个人资料",
},
],
},
{
title: "模块二:报告采集与录入",
pages: [
{
name: "首页",
path: "/home",
icon: Home,
description: "报告管理中心,查看孕周信息",
},
{
name: "OCR 拍照页面",
path: "/camera",
icon: Camera,
description: "智能拍照识别检查报告",
},
{
name: "数据校对页面",
path: "/review",
icon: FileCheck,
description: "校对OCR识别结果,补充信息",
},
],
},
{
title: "模块三:AI 解读与互动",
pages: [
{
name: "AI 智能解读",
path: "/analysis/1",
icon: Sparkles,
description: "查看AI生成的报告解读",
},
{
name: "报告详情",
path: "/report/1",
icon: FileText,
description: "查看原始报告完整数据",
},
{
name: "AI 追问对话",
path: "/chat/1",
icon: MessageCircle,
description: "针对报告结果AI追问",
},
{
name: "问诊清单",
path: "/doctor-questions/1",
icon: Stethoscope,
description: "AI生成看医生时的问题清单",
},
],
},
{
title: "模块四:健康建议",
pages: [
{
name: "语音记录",
path: "/voice-record",
icon: Mic,
description: "语音记录症状和感受",
},
],
},
{
title: "模块五:健康档案",
pages: [
{
name: "健康档案",
path: "/health-records",
icon: HeartPulse,
description: "健康数据概览",
},
{
name: "生长曲线",
path: "/growth-curve",
icon: TrendingUp,
description: "胎儿生长发育曲线",
},
{
name: "报告时间轴",
path: "/timeline",
icon: Clock,
description: "检查报告历史时间轴",
},
{
name: "产检日历",
path: "/calendar",
icon: CalendarDays,
description: "产检计划与提醒",
},
],
},
{
title: "模块六:个人中心",
pages: [
{
name: "个人主页",
path: "/profile",
icon: User,
description: "用户资料与设置",
},
{
name: "消息中心",
path: "/notifications",
icon: Bell,
description: "产检提醒与消息通知",
},
{
name: "分享报告",
path: "/share/1",
icon: Share2,
description: "隐私脱敏分享解读结果",
},
{
name: "专家咨询",
path: "/expert-consultation",
icon: Users,
description: "在线问诊专家列表",
},
],
},
];
return (
<div className="min-h-screen bg-morandi-50 p-8">
<div className="max-w-6xl mx-auto">
<div className="text-center mb-8">
<h1 className="text-3xl font-semibold text-gray-800 mb-2">
孕育无忧 - 孕期健康检查报告解读
</h1>
<p className="text-gray-600">开发者导航 - 快速访问所有页面</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{modules.map((module, moduleIndex) => (
<Card
key={moduleIndex}
className="bg-white rounded-2xl p-6 shadow-sm border-0"
>
<h2 className="text-lg font-semibold text-gray-800 mb-4 pb-3 border-b-2 border-gray-100">
{module.title}
</h2>
<div className="space-y-3">
{module.pages.map((page, pageIndex) => (
<Button
key={pageIndex}
onClick={() => navigate(page.path)}
variant="outline"
className="w-full justify-start h-auto p-4 hover:bg-morandi-50 hover:border-morandi-200 transition-all group"
>
<div className="flex items-start gap-3 w-full">
<div className="mt-1">
<page.icon className="w-5 h-5 text-morandi-400 group-hover:text-morandi-500" />
</div>
<div className="flex-1 text-left">
<div className="font-semibold text-gray-800 mb-1">
{page.name}
</div>
<div className="text-xs text-gray-500">
{page.description}
</div>
<div className="text-xs text-morandi-400 mt-1 font-mono">
{page.path}
</div>
</div>
</div>
</Button>
))}
</div>
</Card>
))}
</div>
<div className="mt-6 text-center text-sm text-gray-500">
<p>共 {modules.reduce((sum, m) => sum + m.pages.length, 0)} 个页面 | React + TypeScript + Tailwind CSS</p>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,284 @@
import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router";
import { motion } from "motion/react";
import {
ChevronLeft,
Copy,
Check,
MessageCircle,
Clipboard,
Share2,
Download,
Loader2,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Card } from "../components/ui/card";
import { Badge } from "../components/ui/badge";
import { getDoctorQuestions } from "../services/api";
interface Question {
id: string;
category: string;
question: string;
reason: string;
priority: "high" | "medium" | "low";
}
export function DoctorQuestionsPage() {
const navigate = useNavigate();
const { reportId } = useParams();
const [copiedId, setCopiedId] = useState(null);
const [questions, setQuestions] = useState<Question[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!reportId) return;
getDoctorQuestions(reportId)
.then((data) => {
setQuestions(
data.questions.map((q, i) => ({
id: String(i),
category: q.category,
question: q.question,
reason: q.reason,
priority: (i < 2 ? "high" : i < 4 ? "medium" : "low") as Question["priority"],
}))
);
})
.catch(() => {/* keep empty */})
.finally(() => setLoading(false));
}, [reportId]);
const handleCopy = (text: string, id: string) => {
navigator.clipboard.writeText(text);
setCopiedId(id);
setTimeout(() => setCopiedId(null), 2000);
};
const handleCopyAll = () => {
const allQuestions = questions
.map((q, index) => `${index + 1}. ${q.question}`)
.join("\n\n");
navigator.clipboard.writeText(allQuestions);
setCopiedId("all");
setTimeout(() => setCopiedId(null), 2000);
};
const priorityLabels = {
high: { text: "重要", color: "bg-red-100 text-red-700" },
medium: { text: "建议", color: "bg-morandi-rose-100 text-morandi-rose-400" },
low: { text: "了解", color: "bg-morandi-50 text-morandi-500" },
};
if (loading) {
return (
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
<div className="text-center">
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin mx-auto mb-3" />
<p className="text-sm text-gray-500">正在生成问诊清单...</p>
</div>
</div>
);
}
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => navigate(-1)}
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<ChevronLeft className="w-6 h-6 text-gray-600" />
</button>
<div className="flex items-center gap-2">
<div className="w-10 h-10 bg-morandi-400 rounded-full flex items-center justify-center">
<MessageCircle className="w-5 h-5 text-white" />
</div>
<div>
<h1 className="font-semibold text-gray-800">问诊清单</h1>
<p className="text-xs text-gray-500">
智能生成{questions.length}个问题
</p>
</div>
</div>
</div>
<div className="flex gap-2">
<Button
onClick={handleCopyAll}
variant="outline"
size="sm"
className="rounded-full"
>
{copiedId === "all" ? (
<>
<Check className="w-4 h-4 mr-2" />
已复制
</>
) : (
<>
<Clipboard className="w-4 h-4 mr-2" />
全部复制
</>
)}
</Button>
</div>
</div>
</div>
<div className="mx-auto p-4 space-y-6">
{/* 使用说明 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
>
<Card className="bg-gradient-to-br from-morandi-400 to-morandi-500 border-0 text-white p-6 rounded-3xl shadow-sm">
<h2 className="text-xl font-semibold mb-3">💬 如何使用问诊清单</h2>
<div className="space-y-2 text-sm text-white/90">
<p>✓ 基于您的报告异常项,AI智能生成针对性问题</p>
<p>✓ 点击单个问题可复制,方便向医生提问</p>
<p>✓ 可一键复制全部问题,就诊时查看</p>
<p>✓ 按优先级排序,重要问题优先询问</p>
</div>
</Card>
</motion.div>
{/* 问题列表 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
>
<h2 className="text-lg font-semibold text-gray-800 mb-4">
📋 建议咨询的问题
</h2>
<div className="space-y-4">
{questions.map((question, index) => (
<motion.div
key={question.id}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.2 + index * 0.05 }}
>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0 hover:shadow-md transition-shadow">
<div className="flex items-start gap-4">
<div className="flex-shrink-0 w-8 h-8 bg-morandi-100 text-morandi-500 rounded-full flex items-center justify-center font-semibold text-sm">
{index + 1}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-3">
<Badge
className={`${
priorityLabels[question.priority].color
} hover:bg-current`}
>
{priorityLabels[question.priority].text}
</Badge>
<span className="text-xs text-gray-500">
{question.category}
</span>
</div>
<p className="text-gray-800 leading-relaxed mb-3 font-medium">
{question.question}
</p>
<div className="bg-morandi-slate-50 rounded-xl p-3 mb-3">
<p className="text-sm text-morandi-500">
💡 <strong>为什么问:</strong>
{question.reason}
</p>
</div>
<Button
onClick={() =>
handleCopy(question.question, question.id)
}
size="sm"
variant="outline"
className="w-full"
>
{copiedId === question.id ? (
<>
<Check className="w-4 h-4 mr-2" />
已复制
</>
) : (
<>
<Copy className="w-4 h-4 mr-2" />
复制此问题
</>
)}
</Button>
</div>
</div>
</Card>
</motion.div>
))}
</div>
</motion.div>
{/* 其他建议 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.5 }}
>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
<h3 className="font-semibold text-gray-800 mb-3 flex items-center gap-2">
<MessageCircle className="w-5 h-5 text-morandi-400" />
💡 就诊小贴士
</h3>
<ul className="space-y-2 text-sm text-gray-600">
<li className="flex items-start gap-2">
<span className="flex-shrink-0 w-1.5 h-1.5 bg-morandi-400 rounded-full mt-2"></span>
<span>
问诊时可以拿出手机查看问题清单,避免紧张时忘记要问的内容
</span>
</li>
<li className="flex items-start gap-2">
<span className="flex-shrink-0 w-1.5 h-1.5 bg-morandi-400 rounded-full mt-2"></span>
<span>听从医生建议,记录重要的用药和注意事项</span>
</li>
<li className="flex items-start gap-2">
<span className="flex-shrink-0 w-1.5 h-1.5 bg-morandi-400 rounded-full mt-2"></span>
<span>如医生时间有限,优先询问标记为"重要"的问题</span>
</li>
<li className="flex items-start gap-2">
<span className="flex-shrink-0 w-1.5 h-1.5 bg-morandi-400 rounded-full mt-2"></span>
<span>
就诊后可返回APP查看AI建议,结合医生意见调整生活方式
</span>
</li>
</ul>
</Card>
</motion.div>
{/* 底部操作 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.6 }}
>
<div className="grid grid-cols-2 gap-3">
<Button
variant="outline"
className="h-12"
onClick={() => navigate(`/share/${reportId}`)}
>
<Share2 className="w-4 h-4 mr-2" />
分享清单
</Button>
<Button className="h-12 bg-morandi-400">
<Download className="w-4 h-4 mr-2" />
导出PDF
</Button>
</div>
</motion.div>
</div>
</div>
);
}

View File

@@ -0,0 +1,334 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router";
import { motion } from "motion/react";
import {
ChevronLeft,
UserCheck,
Star,
Clock,
MessageCircle,
Video,
FileText,
Award,
ThumbsUp,
ChevronRight,
Loader2,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Card } from "../components/ui/card";
import { Badge } from "../components/ui/badge";
import { getExperts, type Doctor as DoctorDTO } from "../services/api";
interface Doctor {
id: string;
name: string;
title: string;
hospital: string;
specialty: string;
experience: string;
rating: number;
reviewCount: number;
consultCount: number;
responseTime: string;
price: number;
avatar: string;
tags: string[];
}
export function ExpertConsultationPage() {
const navigate = useNavigate();
const [selectedService, setSelectedService] = useState("text");
const [doctors, setDoctors] = useState<Doctor[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
getExperts()
.then((data) => {
setDoctors(
data.doctors.map((d) => ({
id: d.id,
name: d.name,
title: d.title,
hospital: d.hospital,
specialty: d.specialty,
experience: d.experience,
rating: d.rating,
reviewCount: d.review_count,
consultCount: d.consult_count,
responseTime: d.response_time,
price: d.price?.text || 50,
avatar: "",
tags: d.tags,
}))
);
})
.catch(() => {/* keep empty */})
.finally(() => setLoading(false));
}, []);
const services = [
{
id: "text",
name: "图文咨询",
icon: MessageCircle,
price: 50,
time: "24小时内回复",
description: "上传报告,医生详细解读",
},
{
id: "video",
name: "视频问诊",
icon: Video,
price: 200,
time: "预约时间",
description: "面对面沟通,更加详细",
},
{
id: "urgent",
name: "加急咨询",
icon: Clock,
price: 100,
time: "2小时内回复",
description: "紧急情况,优先处理",
},
];
if (loading) {
return (
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin" />
</div>
);
}
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => navigate(-1)}
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<ChevronLeft className="w-6 h-6 text-gray-600" />
</button>
<div className="flex items-center gap-2">
<div className="w-10 h-10 bg-morandi-400 rounded-full flex items-center justify-center">
<UserCheck className="w-5 h-5 text-white" />
</div>
<div>
<h1 className="font-semibold text-gray-800">专家复核</h1>
<p className="text-xs text-gray-500">专业医生在线解答</p>
</div>
</div>
</div>
</div>
</div>
<div className="mx-auto p-4 space-y-6">
{/* 服务介绍 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
>
<Card className="bg-gradient-to-br from-morandi-400 to-morandi-500 border-0 text-white p-6 rounded-3xl shadow-sm">
<h2 className="text-xl font-semibold mb-3">👨‍⚕️ 为什么需要专家复核</h2>
<div className="space-y-2 text-sm text-white/90">
<p>✓ AI解读仅供参考,复杂情况需专业医生判断</p>
<p>✓ 三甲医院主任医师,20年+临床经验</p>
<p>✓ 一对一解答,针对您的具体情况给出建议</p>
<p>✓ 支持图文、视频多种咨询方式</p>
</div>
</Card>
</motion.div>
{/* 咨询方式选择 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
>
<h2 className="text-lg font-semibold text-gray-800 mb-4">
选择咨询方式
</h2>
<div className="grid grid-cols-3 gap-3">
{services.map((service) => (
<button
key={service.id}
onClick={() => setSelectedService(service.id as any)}
className={`p-4 rounded-2xl transition-all ${
selectedService === service.id
? "bg-morandi-400 text-white shadow-sm scale-105"
: "bg-white text-gray-600 hover:bg-gray-50"
}`}
>
<service.icon
className={`w-8 h-8 mx-auto mb-2 ${
selectedService === service.id
? "text-white"
: "text-morandi-400"
}`}
/>
<div className="font-semibold text-sm mb-1">
{service.name}
</div>
<div
className={`text-xs mb-2 ${
selectedService === service.id
? "text-white/80"
: "text-gray-500"
}`}
>
{service.time}
</div>
<div className="font-semibold">¥{service.price}</div>
</button>
))}
</div>
</motion.div>
{/* 推荐医生 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
>
<h2 className="text-lg font-semibold text-gray-800 mb-4">
🏥 推荐专家
</h2>
<div className="space-y-4">
{doctors.map((doctor, index) => (
<motion.div
key={doctor.id}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.3 + index * 0.05 }}
>
<Card className="bg-white rounded-2xl p-5 shadow-sm hover:shadow-md transition-all border-0">
<div className="flex items-start gap-4 mb-4">
{/* 医生头像 */}
<div className="w-16 h-16 bg-morandi-400 rounded-full flex items-center justify-center text-white text-2xl font-semibold flex-shrink-0">
{doctor.name.charAt(0)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
<h3 className="font-semibold text-gray-800 text-lg">
{doctor.name}
</h3>
<Badge className="bg-morandi-50 text-morandi-500 hover:bg-morandi-50">
{doctor.title}
</Badge>
{doctor.rating >= 4.9 && (
<Award className="w-4 h-4 text-yellow-500" />
)}
</div>
<div className="space-y-1 text-sm text-gray-600 mb-3">
<p>{doctor.hospital} · {doctor.specialty}</p>
<p>{doctor.experience}</p>
</div>
<div className="flex items-center gap-4 text-sm text-gray-500 mb-3">
<div className="flex items-center gap-1">
<Star className="w-4 h-4 text-yellow-500 fill-yellow-500" />
<span className="font-semibold text-gray-800">
{doctor.rating}
</span>
<span>({doctor.reviewCount}评价)</span>
</div>
<div className="flex items-center gap-1">
<ThumbsUp className="w-4 h-4" />
<span>{doctor.consultCount}次咨询</span>
</div>
</div>
<div className="flex flex-wrap gap-2 mb-3">
{doctor.tags.map((tag, i) => (
<span
key={i}
className="px-3 py-1 bg-morandi-50 text-morandi-500 text-xs rounded-full"
>
{tag}
</span>
))}
</div>
<div className="flex items-center gap-2 text-sm">
<Clock className="w-4 h-4 text-gray-400" />
<span className="text-gray-600">
响应时间:{doctor.responseTime}
</span>
</div>
</div>
</div>
<div className="flex items-center justify-between pt-4 border-t border-gray-100">
<div>
<span className="text-gray-500 text-sm mr-2">
咨询费用
</span>
<span className="text-2xl font-semibold text-morandi-500">
¥{doctor.price}
</span>
<span className="text-gray-500 text-sm">/次</span>
</div>
<Button className="bg-morandi-400 hover:bg-morandi-500">
立即咨询
<ChevronRight className="w-4 h-4 ml-1" />
</Button>
</div>
</Card>
</motion.div>
))}
</div>
</motion.div>
{/* 咨询流程 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.5 }}
>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
<h3 className="font-semibold text-gray-800 mb-4">📋 咨询流程</h3>
<div className="space-y-3">
{[
{ step: 1, text: "选择医生和咨询方式" },
{ step: 2, text: "上传检查报告和问题描述" },
{ step: 3, text: "支付咨询费用" },
{ step: 4, text: "医生接单并给出专业建议" },
{ step: 5, text: "可追问3次,获得满意答复" },
].map((item) => (
<div key={item.step} className="flex items-start gap-3">
<div className="flex-shrink-0 w-6 h-6 bg-morandi-100 text-morandi-500 rounded-full flex items-center justify-center text-sm font-semibold">
{item.step}
</div>
<p className="text-gray-700 pt-0.5">{item.text}</p>
</div>
))}
</div>
</Card>
</motion.div>
{/* 温馨提示 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.6 }}
>
<Card className="bg-gradient-to-r from-morandi-rose-100 to-red-50 border-morandi-rose-300 rounded-2xl p-4">
<h3 className="font-semibold text-gray-800 mb-2">⚠️ 重要提示</h3>
<ul className="space-y-1 text-sm text-gray-600">
<li>• 在线咨询仅供参考,不能替代线下就诊</li>
<li>• 如有紧急情况,请立即前往医院就诊</li>
<li>• 咨询记录会保存,可随时查看</li>
<li>• 医生回复后24小时内可免费追问</li>
</ul>
</Card>
</motion.div>
</div>
</div>
);
}

View File

@@ -0,0 +1,624 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router";
import { motion } from "motion/react";
import {
ChevronLeft,
TrendingUp,
Info,
Download,
Share2,
Loader2,
Heart,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Card } from "../components/ui/card";
import { Badge } from "../components/ui/badge";
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
Area,
AreaChart,
} from "recharts";
import { getGrowthCurve } from "../services/api";
import { useUser } from "../context/UserContext";
// 宝宝预期大小数据(按孕周,基于WHO标准)
// 4-19周:身长为头臀长(CRL);20周起:身长为头到脚全身长
const BABY_EXPECTED_DATA: Record<number, { emoji: string; fruit: string; length: string; weight: string; highlight: string }> = {
4: { emoji: "🫘", fruit: "罂粟种子", length: "0.1cm", weight: "<1g", highlight: "心脏开始跳动" },
5: { emoji: "🫘", fruit: "芝麻粒", length: "0.2cm", weight: "<1g", highlight: "神经管开始发育" },
6: { emoji: "🫘", fruit: "小扁豆", length: "0.6cm", weight: "<1g", highlight: "小手小脚在萌芽" },
7: { emoji: "🫐", fruit: "蓝莓", length: "1.3cm", weight: "<1g", highlight: "五官开始形成" },
8: { emoji: "🫐", fruit: "覆盆子", length: "1.6cm", weight: "1g", highlight: "手指脚趾开始分化" },
9: { emoji: "🍇", fruit: "葡萄", length: "2.3cm", weight: "2g", highlight: "可以微微活动了" },
10: { emoji: "🍊", fruit: "金橘", length: "3.1cm", weight: "4g", highlight: "所有器官已初步形成" },
11: { emoji: "🫒", fruit: "无花果", length: "4.1cm", weight: "7g", highlight: "能做出吞咽动作" },
12: { emoji: "🍋", fruit: "青柠", length: "5.4cm", weight: "14g", highlight: "进入稳定的孕中期" },
13: { emoji: "🍋", fruit: "柠檬", length: "7.4cm", weight: "23g", highlight: "指纹开始形成" },
14: { emoji: "🍑", fruit: "桃子", length: "8.7cm", weight: "43g", highlight: "能做出表情了" },
16: { emoji: "🥑", fruit: "牛油果", length: "11.6cm", weight: "100g", highlight: "开始能听到声音" },
18: { emoji: "🫑", fruit: "甜椒", length: "14.2cm", weight: "190g", highlight: "妈妈可能感到胎动了" },
20: { emoji: "🍌", fruit: "香蕉", length: "25.6cm", weight: "300g", highlight: "味觉开始发育" },
22: { emoji: "🥭", fruit: "木瓜", length: "27.8cm", weight: "430g", highlight: "眉毛和眼睫毛长出" },
24: { emoji: "🌽", fruit: "玉米", length: "30cm", weight: "600g", highlight: "肺部开始发育" },
26: { emoji: "🥦", fruit: "菜花", length: "35.6cm", weight: "760g", highlight: "能睁开眼睛了" },
28: { emoji: "🍆", fruit: "茄子", length: "37.6cm", weight: "1000g", highlight: "开始有规律的作息" },
30: { emoji: "🥬", fruit: "卷心菜", length: "39.9cm", weight: "1320g", highlight: "大脑快速发育中" },
32: { emoji: "🥥", fruit: "椰子", length: "42.4cm", weight: "1700g", highlight: "皮下脂肪增多" },
34: { emoji: "🍈", fruit: "哈密瓜", length: "45cm", weight: "2150g", highlight: "肺部接近成熟" },
36: { emoji: "🍈", fruit: "蜜瓜", length: "47.4cm", weight: "2620g", highlight: "头部开始入盆" },
38: { emoji: "🎃", fruit: "南瓜", length: "49.8cm", weight: "3080g", highlight: "各器官发育成熟" },
40: { emoji: "🍉", fruit: "小西瓜", length: "51.2cm", weight: "3460g", highlight: "随时准备来到这个世界" },
};
function getBabyExpectedData(week: number) {
const weeks = Object.keys(BABY_EXPECTED_DATA).map(Number).sort((a, b) => a - b);
let closest = weeks[0];
for (const w of weeks) {
if (w <= week) closest = w;
else break;
}
return BABY_EXPECTED_DATA[closest];
}
// 生成孕周里程碑时间线数据
function getGrowthMilestones(currentWeek: number) {
const milestones = [
{ week: 8, label: "心跳可检测", emoji: "💓" },
{ week: 12, label: "首次B超", emoji: "🔍" },
{ week: 16, label: "开始感知声音", emoji: "👂" },
{ week: 20, label: "大排畸检查", emoji: "🏥" },
{ week: 24, label: "肺部发育", emoji: "🫁" },
{ week: 28, label: "眼睛能睁开", emoji: "👀" },
{ week: 32, label: "快速增重", emoji: "📈" },
{ week: 36, label: "接近足月", emoji: "🎯" },
{ week: 40, label: "预产期到来", emoji: "🎉" },
];
return milestones.map(m => ({ ...m, passed: currentWeek >= m.week }));
}
export function GrowthCurvePage() {
const navigate = useNavigate();
const { user } = useUser();
const currentWeek = user.currentWeek || 0;
const [selectedMetric, setSelectedMetric] = useState("bpd");
const [loading, setLoading] = useState(true);
// Standard reference data (no fake values)
const standardData: Record<string, { name: string; unit: string; description: string; data: { week: number; value?: number; standard: number; lower: number; upper: number }[] }> = {
bpd: {
name: "双顶径 (BPD)",
unit: "mm",
description: "胎儿头部左右两侧之间最宽部位的长度",
data: [
{ week: 12, standard: 20, lower: 18, upper: 22 },
{ week: 16, standard: 35, lower: 32, upper: 38 },
{ week: 20, standard: 47, lower: 43, upper: 51 },
{ week: 24, standard: 60, lower: 56, upper: 64 },
{ week: 28, standard: 71, lower: 67, upper: 75 },
{ week: 32, standard: 81, lower: 77, upper: 85 },
{ week: 36, standard: 89, lower: 85, upper: 93 },
],
},
ac: {
name: "腹围 (AC)",
unit: "mm",
description: "胎儿腹部一周的长度",
data: [
{ week: 12, standard: 60, lower: 54, upper: 66 },
{ week: 16, standard: 102, lower: 94, upper: 110 },
{ week: 20, standard: 148, lower: 138, upper: 158 },
{ week: 24, standard: 192, lower: 180, upper: 204 },
{ week: 28, standard: 235, lower: 221, upper: 249 },
{ week: 32, standard: 279, lower: 263, upper: 295 },
{ week: 36, standard: 318, lower: 300, upper: 336 },
],
},
fl: {
name: "股骨长 (FL)",
unit: "mm",
description: "胎儿大腿骨的长度",
data: [
{ week: 12, standard: 8, lower: 7, upper: 9 },
{ week: 16, standard: 22, lower: 20, upper: 24 },
{ week: 20, standard: 34, lower: 31, upper: 37 },
{ week: 24, standard: 45, lower: 42, upper: 48 },
{ week: 28, standard: 54, lower: 51, upper: 57 },
{ week: 32, standard: 63, lower: 60, upper: 66 },
{ week: 36, standard: 70, lower: 67, upper: 73 },
],
},
};
const [growthData, setGrowthData] = useState(standardData);
useEffect(() => {
getGrowthCurve()
.then((data) => {
if (data.data_points && data.data_points.length > 0) {
// Merge API data points into standard data
const updated = { ...standardData };
for (const metric of ["bpd", "ac", "fl"] as const) {
const apiPoints = data.data_points.filter((p) => p[metric] != null);
if (apiPoints.length > 0) {
updated[metric] = {
...updated[metric],
data: updated[metric].data.map((d) => {
const match = apiPoints.find((p) => p.week === d.week);
return match && match[metric] != null
? { ...d, value: match[metric]! }
: d;
}),
};
}
}
setGrowthData(updated);
}
})
.catch(() => {/* keep standard data */})
.finally(() => setLoading(false));
}, []);
const currentData = growthData[selectedMetric];
// 检查是否有真实数据
const hasRealData = currentData.data.some(d => d.value != null);
// 生成动态评估结果
const generateAssessment = () => {
if (!hasRealData) {
return "暂无生长数据。上传B超报告后,系统会自动记录宝宝的生长数据并生成评估结果。";
}
const realDataPoints = currentData.data.filter(d => d.value != null);
const latestPoint = realDataPoints[realDataPoints.length - 1];
if (!latestPoint) {
return "暂无生长数据。上传B超报告后,系统会自动记录宝宝的生长数据并生成评估结果。";
}
const { value, lower, upper, week, standard } = latestPoint;
const metricName = currentData.name.split(" ")[0];
if (value! >= lower && value! <= upper) {
const deviation = Math.abs(value! - standard);
const deviationPercent = ((deviation / standard) * 100).toFixed(1);
if (deviation < standard * 0.05) {
return `宝宝的${metricName}发育非常好!孕${week}周的测量值为${value}${currentData.unit},与标准值${standard}${currentData.unit}非常接近,在正常范围内(${lower}-${upper}${currentData.unit})。继续保持健康的生活方式,按时产检。`;
} else {
return `宝宝的${metricName}发育良好!孕${week}周的测量值为${value}${currentData.unit},在正常范围内(${lower}-${upper}${currentData.unit}),与标准值${standard}${currentData.unit}相差约${deviationPercent}%。继续保持健康的生活方式,按时产检。`;
}
} else if (value! < lower) {
const gap = lower - value!;
return `宝宝的${metricName}略偏小。孕${week}周的测量值为${value}${currentData.unit},低于正常范围下限(${lower}${currentData.unit})约${gap}${currentData.unit}。建议加强营养摄入,多吃富含蛋白质的食物,并及时咨询产科医生,进行进一步评估。`;
} else {
const gap = value! - upper;
return `宝宝的${metricName}略偏大。孕${week}周的测量值为${value}${currentData.unit},高于正常范围上限(${upper}${currentData.unit})约${gap}${currentData.unit}。建议控制饮食,避免高糖高脂食物,并及时咨询产科医生,进行进一步评估。`;
}
};
const CustomTooltip = ({ active, payload }: any) => {
if (active && payload && payload.length) {
return (
<div className="bg-white p-3 rounded-xl shadow-sm border border-gray-100">
<p className="font-semibold text-gray-800 mb-2">
孕{payload[0].payload.week}周
</p>
<p className="text-sm text-gray-500">
标准值: {payload[0].payload.standard} {currentData.unit}
</p>
<p className="text-xs text-gray-400 mt-1">
正常范围: {payload[0].payload.lower}-{payload[0].payload.upper}{" "}
{currentData.unit}
</p>
</div>
);
}
return null;
};
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => navigate(-1)}
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<ChevronLeft className="w-6 h-6 text-gray-600" />
</button>
<div className="flex items-center gap-2">
<div className="w-10 h-10 bg-gradient-to-br from-morandi-400 to-morandi-400 rounded-full flex items-center justify-center">
<TrendingUp className="w-5 h-5 text-white" />
</div>
<div>
<h1 className="font-semibold text-gray-800">胎儿生长曲线</h1>
<p className="text-xs text-gray-500">基于B超数据自动生成</p>
</div>
</div>
</div>
</div>
</div>
<div className="mx-auto p-4 space-y-6">
{/* 无B超数据时展示宝宝预期大小 */}
{!hasRealData && currentWeek > 0 && (() => {
const babyData = getBabyExpectedData(currentWeek);
const milestones = getGrowthMilestones(currentWeek);
const progress = Math.min(100, Math.max(0, ((currentWeek - 4) / 36) * 100));
if (!babyData) return null;
return (
<>
{/* 宝宝当前大小 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
>
<Card className="bg-white rounded-2xl p-6 shadow-sm border-0 overflow-hidden relative">
<div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-morandi-100 to-transparent rounded-bl-full opacity-60" />
<div className="relative">
<h2 className="font-semibold text-gray-800 mb-4 flex items-center gap-2">
<Heart className="w-5 h-5 text-morandi-rose-400" />
宝宝现在有多大?
</h2>
<div className="text-center py-4">
<motion.div
initial={{ scale: 0.5, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ type: "spring", duration: 0.8 }}
className="text-7xl mb-4"
>
{babyData.emoji}
</motion.div>
<motion.p
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
className="text-lg text-gray-700 font-medium mb-1"
>
孕{currentWeek}周,宝宝像一个<span className="text-morandi-500 font-semibold">{babyData.fruit}</span>
</motion.p>
<p className="text-sm text-gray-400">{babyData.highlight}</p>
</div>
{/* 预期数据 */}
<div className="grid grid-cols-2 gap-3 mt-4">
<div className="bg-morandi-50 rounded-xl p-4 text-center">
<p className="text-xs text-gray-400 mb-1">预期身长</p>
<p className="text-xl font-semibold text-morandi-600">{babyData.length}</p>
</div>
<div className="bg-morandi-50 rounded-xl p-4 text-center">
<p className="text-xs text-gray-400 mb-1">预期体重</p>
<p className="text-xl font-semibold text-morandi-600">{babyData.weight}</p>
</div>
</div>
{/* 孕期进度 */}
<div className="mt-5">
<div className="flex items-center justify-between mb-2">
<span className="text-xs text-gray-400">孕期进度</span>
<span className="text-xs text-morandi-500 font-medium">{Math.round(progress)}%</span>
</div>
<div className="h-2.5 bg-morandi-50 rounded-full overflow-hidden">
<motion.div
className="h-full bg-gradient-to-r from-morandi-300 to-morandi-500 rounded-full"
initial={{ width: 0 }}
animate={{ width: `${progress}%` }}
transition={{ duration: 1.2, ease: "easeOut" }}
/>
</div>
<div className="flex justify-between mt-1">
<span className="text-[10px] text-gray-300">4周</span>
<span className="text-[10px] text-gray-300">40周</span>
</div>
</div>
</div>
</Card>
</motion.div>
{/* 成长里程碑时间线 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.15 }}
>
<Card className="bg-white rounded-2xl p-6 shadow-sm border-0">
<h3 className="font-semibold text-gray-800 mb-4">成长里程碑</h3>
<div className="space-y-0">
{milestones.map((m, i) => (
<div key={m.week} className="flex items-start gap-3">
{/* 时间线连接线 */}
<div className="flex flex-col items-center">
<div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm flex-shrink-0 ${
m.passed
? "bg-morandi-400 text-white"
: currentWeek >= m.week - 2
? "bg-morandi-100 text-morandi-500 ring-2 ring-morandi-300"
: "bg-gray-100 text-gray-400"
}`}>
{m.emoji}
</div>
{i < milestones.length - 1 && (
<div className={`w-0.5 h-6 ${m.passed ? "bg-morandi-300" : "bg-gray-200"}`} />
)}
</div>
<div className="pt-1.5">
<p className={`text-sm font-medium ${m.passed ? "text-gray-700" : "text-gray-400"}`}>
{m.label}
</p>
<p className={`text-xs ${m.passed ? "text-morandi-500" : "text-gray-300"}`}>
孕{m.week}周
</p>
</div>
</div>
))}
</div>
</Card>
</motion.div>
{/* 上传B超提示 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.25 }}
>
<Card className="bg-gradient-to-r from-morandi-sage-50 to-morandi-50 border-morandi-200 rounded-2xl p-4">
<div className="flex items-start gap-3">
<Info className="w-5 h-5 text-morandi-sage-500 mt-0.5 flex-shrink-0" />
<div>
<h3 className="font-semibold text-gray-700 text-sm mb-1">查看精准发育数据</h3>
<p className="text-xs text-gray-500 leading-relaxed mb-3">
上传B超报告后,系统会自动提取胎儿双顶径、腹围、股骨长等数据,生成个性化的生长曲线,让你更直观地了解宝宝发育情况。
</p>
<Button
onClick={() => navigate("/camera")}
className="bg-gradient-to-r from-morandi-400 to-morandi-500"
size="sm"
>
上传B超报告
</Button>
</div>
</div>
</Card>
</motion.div>
</>
);
})()}
{/* 指标选择 - 只在有B超数据时显示 */}
{hasRealData && (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
>
<div className="flex gap-3 overflow-x-auto pb-2">
<button
onClick={() => setSelectedMetric("bpd")}
className={`flex-shrink-0 px-6 py-3 rounded-2xl font-semibold text-sm transition-all ${
selectedMetric === "bpd"
? "bg-gradient-to-r from-morandi-400 to-morandi-400 text-white shadow-sm"
: "bg-white text-gray-600 hover:bg-gray-50"
}`}
>
双顶径
</button>
<button
onClick={() => setSelectedMetric("ac")}
className={`flex-shrink-0 px-6 py-3 rounded-2xl font-semibold text-sm transition-all ${
selectedMetric === "ac"
? "bg-gradient-to-r from-morandi-400 to-morandi-400 text-white shadow-sm"
: "bg-white text-gray-600 hover:bg-gray-50"
}`}
>
腹围
</button>
<button
onClick={() => setSelectedMetric("fl")}
className={`flex-shrink-0 px-6 py-3 rounded-2xl font-semibold text-sm transition-all ${
selectedMetric === "fl"
? "bg-gradient-to-r from-morandi-rose-400 to-morandi-rose-300 text-white shadow-sm"
: "bg-white text-gray-600 hover:bg-gray-50"
}`}
>
股骨长
</button>
</div>
</motion.div>
)}
{/* 有B超数据时显示指标详情、曲线图、数据表格 */}
{hasRealData && (
<>
{/* 指标说明 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
>
<Card className="bg-morandi-slate-50 border-morandi-200 rounded-2xl p-4">
<div className="flex items-start gap-3">
<Info className="w-5 h-5 text-morandi-slate-500 mt-0.5 flex-shrink-0" />
<div>
<h3 className="font-semibold text-gray-800 mb-1">
{currentData.name}
</h3>
<p className="text-sm text-gray-600">
{currentData.description}
</p>
</div>
</div>
</Card>
</motion.div>
{/* 生长曲线图 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
>
<Card className="bg-white rounded-2xl p-6 shadow-sm border-0">
<div className="flex items-center justify-between mb-6">
<h2 className="font-semibold text-gray-800">生长趋势</h2>
<div className="flex items-center gap-4 text-sm">
<div className="flex items-center gap-2">
<div className="w-3 h-3 bg-gray-300 rounded-full"></div>
<span className="text-gray-600">标准值</span>
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 bg-morandi-slate-200 rounded-full"></div>
<span className="text-gray-600">正常范围</span>
</div>
</div>
</div>
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={currentData.data}>
<defs>
<linearGradient id="colorRange" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#93c5fd" stopOpacity={0.3} />
<stop offset="95%" stopColor="#93c5fd" stopOpacity={0.1} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
<XAxis
dataKey="week"
label={{ value: "孕周", position: "insideBottom", offset: -5 }}
stroke="#9ca3af"
/>
<YAxis
label={{
value: `${currentData.unit}`,
angle: -90,
position: "insideLeft",
}}
stroke="#9ca3af"
/>
<Tooltip content={<CustomTooltip />} />
<Area
type="monotone"
dataKey="upper"
stroke="none"
fill="url(#colorRange)"
/>
<Area
type="monotone"
dataKey="lower"
stroke="none"
fill="#ffffff"
/>
<Line
type="monotone"
dataKey="standard"
stroke="#d1d5db"
strokeWidth={2}
dot={false}
strokeDasharray="5 5"
/>
{/* 完全移除实际值线条 */}
</AreaChart>
</ResponsiveContainer>
</Card>
</motion.div>
{/* 数据表格 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
>
<Card className="bg-white rounded-2xl p-6 shadow-sm border-0">
<h3 className="font-semibold text-gray-800 mb-4">详细数据</h3>
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b border-gray-200">
<th className="text-left py-3 text-sm font-semibold text-gray-600">
孕周
</th>
<th className="text-center py-3 text-sm font-semibold text-gray-600">
实际值
</th>
<th className="text-center py-3 text-sm font-semibold text-gray-600">
标准值
</th>
<th className="text-center py-3 text-sm font-semibold text-gray-600">
正常范围
</th>
<th className="text-center py-3 text-sm font-semibold text-gray-600">
状态
</th>
</tr>
</thead>
<tbody>
{currentData.data.map((row, index) => {
const isNormal =
row.value != null && row.value >= row.lower && row.value <= row.upper;
return (
<tr key={index} className="border-b border-gray-100">
<td className="py-3 text-sm text-gray-700">
{row.week}周
</td>
<td className="text-center py-3 text-sm font-semibold text-morandi-500">
{row.value != null ? `${row.value} ${currentData.unit}` : '-'}
</td>
<td className="text-center py-3 text-sm text-gray-600">
{row.standard} {currentData.unit}
</td>
<td className="text-center py-3 text-sm text-gray-500">
{row.lower}-{row.upper} {currentData.unit}
</td>
<td className="text-center py-3">
{row.value != null ? (
<Badge
className={`${
isNormal
? "bg-morandi-sage-100 text-morandi-sage-600"
: "bg-morandi-rose-100 text-morandi-600"
} hover:bg-current`}
>
{isNormal ? "正常" : "关注"}
</Badge>
) : (
<span className="text-gray-400 text-xs">-</span>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</Card>
</motion.div>
{/* 医生建议 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.4 }}
>
<Card className="bg-gradient-to-r from-morandi-sage-100 to-morandi-sage-100 border-morandi-sage-200 rounded-2xl p-4">
<h3 className="font-semibold text-gray-800 mb-2 flex items-center gap-2">
<TrendingUp className="w-5 h-5 text-morandi-sage-500" />
评估结果
</h3>
<p className="text-sm text-gray-700 leading-relaxed">
{generateAssessment()}
</p>
</Card>
</motion.div>
</>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,733 @@
import { useState, useEffect, useMemo } from "react";
import { useNavigate } from "react-router";
import { motion } from "motion/react";
import {
ChevronLeft,
TrendingUp,
Activity,
Search,
FileText,
CheckCircle2,
AlertCircle,
ChevronRight,
Loader2,
FolderOpen,
Camera,
} from "lucide-react";
import {
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Area,
ComposedChart,
} from "recharts";
import { Input } from "../components/ui/input";
import { Card } from "../components/ui/card";
import { Badge } from "../components/ui/badge";
import {
getReportList,
getReportTypeTrends,
type ReportTypeTrend,
} from "../services/api";
interface Report {
id: string;
type: string;
date: string;
status: "normal" | "attention" | "warning";
summary: string;
period: "early" | "mid" | "late";
week: number;
}
export function HealthRecordsPage() {
const navigate = useNavigate();
const [activeTab, setActiveTab] = useState<"trends" | "records">("trends");
const [searchQuery, setSearchQuery] = useState("");
const [reports, setReports] = useState<Report[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
getReportList()
.then((data) => {
setReports(
data.map((item) => {
const week = item.pregnancy_week || 0;
const period = week <= 12 ? "early" : week <= 27 ? "mid" : "late";
const statusMap: Record<string, Report["status"]> = {
normal: "normal",
attention: "attention",
warning: "warning",
};
return {
id: item.id,
type: item.report_type,
date: item.created_at.split("T")[0],
status: statusMap[item.overall_status] || "normal",
summary: item.summary || `共${item.item_count}项指标`,
period: period as Report["period"],
week,
};
})
);
})
.catch(() => {})
.finally(() => setLoading(false));
}, []);
// ─── 按报告类型分组的指标趋势 ───
const [reportTypeTrends, setReportTypeTrends] = useState<ReportTypeTrend[]>([]);
const [trendsLoading, setTrendsLoading] = useState(true);
const [selectedTypeIdx, setSelectedTypeIdx] = useState(0);
const [selectedIndIdx, setSelectedIndIdx] = useState(0);
useEffect(() => {
getReportTypeTrends()
.then((data) => {
setReportTypeTrends(data.report_types);
})
.catch(() => {})
.finally(() => setTrendsLoading(false));
}, []);
const currentType = reportTypeTrends[selectedTypeIdx] || null;
const currentInd = currentType?.indicators[selectedIndIdx] || null;
const trendChartData = useMemo(() => {
if (!currentInd) return [];
return currentInd.points.map((p) => ({
label: p.week > 0 ? `${p.week}周` : p.date.split("T")[0]?.slice(5) || "",
value: p.value,
refLower: currentInd.ref_lower,
refUpper: currentInd.ref_upper,
}));
}, [currentInd]);
// ─── 综合健康摘要:只分析最新一次产检的指标 ───
const healthSummary = useMemo(() => {
// 找到最新产检周数(所有指标中最大的 week)
let latestWeek = 0;
for (const rt of reportTypeTrends) {
for (const ind of rt.indicators) {
for (const p of ind.points) {
if (p.week > latestWeek) latestWeek = p.week;
}
}
}
const stable: string[] = [];
const improving: string[] = [];
const attention: string[] = [];
let latestReportCount = 0;
const countedTypes = new Set<string>();
for (const rt of reportTypeTrends) {
let typeHasLatest = false;
for (const ind of rt.indicators) {
// 只看最新周数的数据点
const latestPt = ind.points.find(p => p.week === latestWeek);
if (!latestPt) continue;
typeHasLatest = true;
const prevPt = ind.points.filter(p => p.week < latestWeek).pop();
const hasRef = ind.ref_lower != null && ind.ref_upper != null;
if (latestPt.status !== "normal") {
attention.push(ind.name);
} else if (prevPt && prevPt.status !== "normal") {
improving.push(ind.name);
} else if (hasRef) {
const range = ind.ref_upper! - ind.ref_lower!;
const margin = range * 0.15;
if (latestPt.value < ind.ref_lower! + margin || latestPt.value > ind.ref_upper! - margin) {
attention.push(ind.name);
} else {
stable.push(ind.name);
}
} else {
stable.push(ind.name);
}
}
if (typeHasLatest && !countedTypes.has(rt.report_type)) {
countedTypes.add(rt.report_type);
latestReportCount++;
}
}
const uniqueStable = [...new Set(stable)];
const uniqueImproving = [...new Set(improving)];
const uniqueAttention = [...new Set(attention)];
const filteredStable = uniqueStable.filter(n => !uniqueAttention.includes(n) && !uniqueImproving.includes(n));
const filteredImproving = uniqueImproving.filter(n => !uniqueAttention.includes(n));
const totalIndicators = filteredStable.length + filteredImproving.length + uniqueAttention.length;
let overallText = "";
let overallLevel: "good" | "ok" | "warn" = "good";
const hasMultipleReports = latestReportCount > 1 || filteredStable.length + filteredImproving.length + uniqueAttention.length > 3;
const prefix = hasMultipleReports ? "本次产检" : "报告显示";
if (uniqueAttention.length === 0) {
overallText = `${prefix}各项指标均在正常范围,整体状况良好`;
overallLevel = "good";
} else if (uniqueAttention.length <= 2) {
overallText = `大部分指标正常,有${uniqueAttention.length}项需要留意`;
overallLevel = "ok";
} else {
overallText = `有${uniqueAttention.length}项指标需要关注,建议咨询医生`;
overallLevel = "warn";
}
return {
stable: filteredStable,
improving: filteredImproving,
attention: uniqueAttention,
overallText,
overallLevel,
latestWeek,
latestReportCount,
totalIndicators,
};
}, [reportTypeTrends]);
const filteredReports = reports.filter((report) => {
const matchesSearch =
report.type.toLowerCase().includes(searchQuery.toLowerCase()) ||
report.summary.toLowerCase().includes(searchQuery.toLowerCase());
return matchesSearch;
});
const groupedReports = filteredReports.reduce((acc, report) => {
const month = report.date.substring(0, 7);
if (!acc[month]) acc[month] = [];
acc[month].push(report);
return acc;
}, {} as Record<string, Report[]>);
const monthNames: Record<string, string> = {};
Object.keys(groupedReports).forEach((month) => {
const [y, m] = month.split("-");
monthNames[month] = `${y}年${parseInt(m)}月`;
});
if (loading) {
return (
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin" />
</div>
);
}
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center gap-3">
<button
onClick={() => navigate(-1)}
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center flex-shrink-0"
>
<ChevronLeft className="w-6 h-6 text-gray-600" />
</button>
<div className="flex items-center gap-2 flex-shrink-0">
<div className="w-10 h-10 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-full flex items-center justify-center">
<Activity className="w-5 h-5 text-white" />
</div>
<div>
<h1 className="font-semibold text-gray-800">健康档案</h1>
<p className="text-xs text-gray-500">共{reports.length}份报告</p>
</div>
</div>
</div>
</div>
<div className="mx-auto px-4 pt-3">
{/* Tab 切换 */}
<div className="flex bg-white rounded-2xl p-1.5 shadow-sm">
<button
onClick={() => setActiveTab("trends")}
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-medium transition-all ${
activeTab === "trends"
? "bg-morandi-400 text-white shadow-sm"
: "text-gray-500 hover:text-gray-700"
}`}
>
<TrendingUp className="w-4 h-4" />
趋势分析
</button>
<button
onClick={() => setActiveTab("records")}
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-medium transition-all ${
activeTab === "records"
? "bg-morandi-400 text-white shadow-sm"
: "text-gray-500 hover:text-gray-700"
}`}
>
<FolderOpen className="w-4 h-4" />
档案记录
</button>
</div>
</div>
<div className="mx-auto p-4 space-y-4">
{/* ═══════════ Tab 1: 趋势分析 ═══════════ */}
{activeTab === "trends" && (
<>
{/* 综合健康摘要 */}
{reportTypeTrends.length > 0 && (
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
{/* 标题 + 产检信息 */}
<div className="flex items-center justify-between mb-4">
<h2 className="font-semibold text-gray-700 flex items-center gap-2 text-base">
<Activity className="w-5 h-5 text-morandi-400" />
健康概览
</h2>
<span className="text-xs text-gray-400 bg-morandi-50 px-2.5 py-1 rounded-full">
{healthSummary.latestWeek > 0 ? `第${healthSummary.latestWeek}周产检 · ` : ""}{healthSummary.latestReportCount}份报告
</span>
</div>
{/* 整体评语 */}
<div className={`rounded-xl px-4 py-3 mb-4 ${
healthSummary.overallLevel === "good"
? "bg-morandi-sage-50"
: healthSummary.overallLevel === "ok"
? "bg-amber-50"
: "bg-red-50"
}`}>
<p className={`text-sm font-medium ${
healthSummary.overallLevel === "good"
? "text-morandi-sage-600"
: healthSummary.overallLevel === "ok"
? "text-amber-600"
: "text-red-600"
}`}>
{healthSummary.overallText}
</p>
</div>
{/* 分类指标 */}
<div className="space-y-2">
{healthSummary.stable.length > 0 && (
<div className="flex items-start gap-2.5 px-1">
<div className="w-1.5 h-1.5 rounded-full bg-morandi-sage-400 mt-1.5 flex-shrink-0" />
<div>
<span className="text-xs font-medium text-gray-600">平稳正常</span>
<span className="text-xs text-gray-400 ml-1.5">{healthSummary.stable.join("、")}</span>
</div>
</div>
)}
{healthSummary.improving.length > 0 && (
<div className="flex items-start gap-2.5 px-1">
<div className="w-1.5 h-1.5 rounded-full bg-blue-400 mt-1.5 flex-shrink-0" />
<div>
<span className="text-xs font-medium text-gray-600">好转向好</span>
<span className="text-xs text-gray-400 ml-1.5">{healthSummary.improving.join("、")}</span>
</div>
</div>
)}
{healthSummary.attention.length > 0 && (
<div className="flex items-start gap-2.5 px-1">
<div className="w-1.5 h-1.5 rounded-full bg-amber-400 mt-1.5 flex-shrink-0" />
<div>
<span className="text-xs font-medium text-gray-600">需要留意</span>
<span className="text-xs text-gray-400 ml-1.5">{healthSummary.attention.join("、")}</span>
</div>
</div>
)}
</div>
</Card>
</motion.div>
)}
{/* 详细指标趋势 */}
{reportTypeTrends.length > 0 && (
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.05 }}
>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
<div className="flex items-center justify-between mb-4">
<h2 className="font-semibold text-gray-700 flex items-center gap-2 text-base">
<TrendingUp className="w-5 h-5 text-morandi-sage-400" />
指标详情
</h2>
</div>
{/* 第一级:报告类型切换 */}
<div className="flex gap-2 mb-3 overflow-x-auto pb-1 -mx-1 px-1">
{reportTypeTrends.map((rt, idx) => (
<button
key={rt.report_type}
onClick={() => { setSelectedTypeIdx(idx); setSelectedIndIdx(0); }}
className={`px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-all flex-shrink-0 ${
selectedTypeIdx === idx
? "bg-morandi-400 text-white"
: "bg-morandi-50 text-gray-500 hover:bg-morandi-100"
}`}
>
{rt.report_type}
<span className="ml-1 opacity-70">({rt.report_count}份)</span>
</button>
))}
</div>
{currentType && (
<>
{/* 第二级:指标切换 */}
<div className="flex gap-2 mb-4 overflow-x-auto pb-1 -mx-1 px-1">
{currentType.indicators.map((ind, idx) => (
<button
key={ind.name}
onClick={() => setSelectedIndIdx(idx)}
className={`px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-all flex-shrink-0 ${
selectedIndIdx === idx
? "bg-morandi-sage-400 text-white"
: "bg-morandi-sage-50 text-gray-500 hover:bg-morandi-sage-100"
}`}
>
{ind.name}
</button>
))}
</div>
{currentInd && (
<>
{/* 图表 */}
<div className="mb-3">
<ResponsiveContainer width="100%" height={200}>
<ComposedChart data={trendChartData}>
<defs>
<linearGradient id="healthTrendRef" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#A8C5A0" stopOpacity={0.2} />
<stop offset="95%" stopColor="#A8C5A0" stopOpacity={0.05} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="#EDE6F2" />
<XAxis dataKey="label" stroke="#B0A8B8" tick={{ fontSize: 11 }} />
<YAxis stroke="#B0A8B8" tick={{ fontSize: 11 }} />
<Tooltip
content={({ active, payload }: any) => {
if (active && payload?.[0]) {
const d = payload[0].payload;
return (
<div className="bg-white p-3 rounded-xl shadow-lg border border-morandi-100">
<p className="font-semibold text-gray-700 text-xs mb-1">{d.label}</p>
<p className="text-xs text-morandi-sage-500">
{currentInd.name}: {d.value} {currentInd.unit}
</p>
{d.refLower != null && d.refUpper != null && (
<p className="text-xs text-gray-400">
参考: {d.refLower}-{d.refUpper} {currentInd.unit}
</p>
)}
</div>
);
}
return null;
}}
/>
{currentInd.ref_upper != null && (
<Area type="monotone" dataKey="refUpper" stroke="none" fill="url(#healthTrendRef)" />
)}
{currentInd.ref_lower != null && (
<Area type="monotone" dataKey="refLower" stroke="none" fill="#ffffff" />
)}
<Line
type="monotone"
dataKey="value"
stroke="#7BA37A"
strokeWidth={2.5}
dot={{ fill: "#7BA37A", r: trendChartData.length === 1 ? 6 : 4, strokeWidth: 2, stroke: "#fff" }}
/>
</ComposedChart>
</ResponsiveContainer>
</div>
{/* 图例 */}
<div className="flex items-center gap-4 mb-3 text-xs flex-wrap">
<div className="flex items-center gap-1.5">
<div className="w-2 h-2 rounded-full bg-[#7BA37A]" />
<span className="text-gray-500">实际值</span>
</div>
{currentInd.ref_lower != null && (
<div className="flex items-center gap-1.5">
<div className="w-2 h-2 bg-morandi-sage-100 rounded-full" />
<span className="text-gray-500">
参考 {currentInd.ref_lower}-{currentInd.ref_upper} {currentInd.unit}
</span>
</div>
)}
</div>
{/* 数据明细 */}
<div className="bg-morandi-50 rounded-xl p-3">
<div className={`grid gap-1 text-xs text-gray-400 mb-2 px-1 ${currentInd.ref_lower != null ? "grid-cols-4" : "grid-cols-3"}`}>
<span>时间</span>
<span className="text-center">实际值</span>
{currentInd.ref_lower != null && (
<span className="text-center">参考值</span>
)}
<span className="text-right">状态</span>
</div>
{currentInd.points.map((p, i) => (
<div key={i} className={`grid gap-1 text-xs px-1 py-1.5 border-t border-morandi-100 ${currentInd.ref_lower != null ? "grid-cols-4" : "grid-cols-3"}`}>
<span className="text-gray-600">
{p.week > 0 ? `第${p.week}周` : p.date.split("T")[0]?.slice(5)}
</span>
<span className={`text-center font-medium ${
p.status === "normal"
? "text-gray-700"
: p.status === "high"
? "text-morandi-rose-500"
: "text-amber-500"
}`}>
{p.value}
</span>
{currentInd.ref_lower != null && (
<span className="text-center text-gray-400">
{currentInd.ref_lower}-{currentInd.ref_upper}
</span>
)}
<span
className={`text-right ${
p.status === "normal"
? "text-morandi-sage-500"
: p.status === "high"
? "text-morandi-rose-500"
: "text-amber-500"
}`}
>
{p.status === "normal" ? "正常" : p.status === "high" ? "偏高" : "偏低"}
</span>
</div>
))}
</div>
</>
)}
</>
)}
</Card>
</motion.div>
)}
{trendsLoading && reportTypeTrends.length === 0 && (
<div className="flex justify-center py-12">
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin" />
</div>
)}
{!trendsLoading && reportTypeTrends.length === 0 && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="text-center py-12"
>
<div className="w-16 h-16 bg-morandi-100 rounded-full flex items-center justify-center mx-auto mb-4">
<TrendingUp className="w-8 h-8 text-morandi-400" />
</div>
<p className="text-sm text-gray-500 mb-1">暂无分析数据</p>
<p className="text-xs text-gray-400 mb-4">上传产检报告后,自动生成健康分析和指标趋势</p>
<button
onClick={() => navigate("/camera")}
className="inline-flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-morandi-400 to-morandi-500 text-white text-sm font-medium rounded-full hover:shadow-md transition-all"
>
<Camera className="w-4 h-4" />
去上传报告
</button>
</motion.div>
)}
</>
)}
{/* ═══════════ Tab 2: 档案记录 ═══════════ */}
{activeTab === "records" && (
<>
{/* 搜索框 */}
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<Input
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="搜索报告..."
className="pl-9 rounded-full border-morandi-100 h-9 text-sm"
/>
</div>
{/* 统计卡片 */}
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
>
<Card className="bg-white rounded-2xl p-4 shadow-sm border-0">
<div className="grid grid-cols-3 gap-4">
<div className="text-center">
<div className="text-2xl font-semibold text-morandi-sage-500 mb-1">
{filteredReports.filter((r) => r.status === "normal").length}
</div>
<div className="text-xs text-gray-500">正常</div>
</div>
<div className="text-center border-l border-r border-gray-100">
<div className="text-2xl font-semibold text-morandi-600 mb-1">
{filteredReports.filter((r) => r.status === "attention").length}
</div>
<div className="text-xs text-gray-500">需关注</div>
</div>
<div className="text-center">
<div className="text-2xl font-semibold text-red-600 mb-1">
{filteredReports.filter((r) => r.status === "warning").length}
</div>
<div className="text-xs text-gray-500">异常</div>
</div>
</div>
</Card>
</motion.div>
{/* 时间轴 */}
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
className="space-y-5"
>
{Object.keys(groupedReports)
.sort()
.reverse()
.map((month) => (
<div key={month}>
<h2 className="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
<div className="w-2 h-2 bg-morandi-400 rounded-full" />
{monthNames[month] || month}
</h2>
<div className="relative pl-6 space-y-3">
<div className="absolute left-1 top-0 bottom-0 w-0.5 bg-morandi-200" />
{groupedReports[month].map((report, index) => (
<motion.div
key={report.id}
initial={{ opacity: 0, x: -16 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.15 + index * 0.04 }}
className="relative"
>
<div
className={`absolute -left-6 top-4 w-3 h-3 rounded-full border-2 border-white ${
report.status === "normal"
? "bg-morandi-sage-400"
: report.status === "attention"
? "bg-morandi-rose-400"
: "bg-red-500"
}`}
/>
<Card
onClick={() => navigate(`/analysis/${report.id}`)}
className="bg-white rounded-2xl p-4 shadow-sm hover:shadow-md transition-all cursor-pointer border-0"
>
<div className="flex items-center gap-3">
<div
className={`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${
report.status === "normal"
? "bg-morandi-sage-100"
: report.status === "attention"
? "bg-morandi-rose-100"
: "bg-red-100"
}`}
>
{report.status === "normal" ? (
<CheckCircle2 className="w-5 h-5 text-morandi-sage-400" />
) : (
<AlertCircle
className={`w-5 h-5 ${
report.status === "attention"
? "text-morandi-rose-400"
: "text-red-500"
}`}
/>
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-0.5">
<h3 className="font-medium text-gray-800 text-sm">
{report.type}
</h3>
<Badge className="bg-morandi-100 text-morandi-500 hover:bg-morandi-100 text-xs">
孕{report.week}周
</Badge>
<Badge
className={`text-xs ${
report.status === "normal"
? "bg-morandi-sage-100 text-morandi-sage-600 hover:bg-morandi-sage-100"
: report.status === "attention"
? "bg-morandi-rose-100 text-morandi-600 hover:bg-morandi-rose-100"
: "bg-red-100 text-red-700 hover:bg-red-100"
}`}
>
{report.status === "normal"
? "正常"
: report.status === "attention"
? "关注"
: "异常"}
</Badge>
</div>
<p className="text-xs text-gray-500 truncate">
{report.summary}
</p>
</div>
<ChevronRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
</div>
</Card>
</motion.div>
))}
</div>
</div>
))}
</motion.div>
{reports.length === 0 && !searchQuery && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="text-center py-12"
>
<div className="w-16 h-16 bg-morandi-100 rounded-full flex items-center justify-center mx-auto mb-4">
<FileText className="w-8 h-8 text-morandi-400" />
</div>
<p className="text-sm text-gray-500 mb-1">暂无检查报告</p>
<p className="text-xs text-gray-400 mb-4">上传产检报告后,这里会自动归档</p>
<button
onClick={() => navigate("/camera")}
className="inline-flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-morandi-400 to-morandi-500 text-white text-sm font-medium rounded-full hover:shadow-md transition-all"
>
<Camera className="w-4 h-4" />
去上传报告
</button>
</motion.div>
)}
{filteredReports.length === 0 && searchQuery && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="text-center py-6"
>
<FileText className="w-12 h-12 text-gray-300 mx-auto mb-3" />
<p className="text-sm text-gray-400">暂无相关报告</p>
</motion.div>
)}
</>
)}
<div className="h-8" />
</div>
</div>
);
}

View File

@@ -0,0 +1,766 @@
import { useState, useEffect, useMemo } from "react";
import { useNavigate } from "react-router";
import { motion } from "motion/react";
import {
Plus,
FileText,
Calendar,
TrendingUp,
ChevronRight,
Heart,
Bell,
User,
Camera,
Info,
Mic,
ListChecks,
Circle,
CheckCircle2,
X,
} from "lucide-react";
import { Card } from "../components/ui/card";
import { Button } from "../components/ui/button";
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Area,
AreaChart,
ComposedChart,
} from "recharts";
import { useUser, getBabySize } from "../context/UserContext";
import { getGrowthCurve, getIndicatorTrends, type IndicatorTrend } from "../services/api";
import { checkupSchedule } from "../data/checkupSchedule";
// 宝宝预期大小数据(按孕周,基于WHO标准)
// 4-19周:身长为头臀长(CRL);20周起:身长为头到脚全身长
const BABY_EXPECTED_DATA: Record<number, { emoji: string; fruit: string; length: string; weight: string; highlight: string }> = {
4: { emoji: "🫘", fruit: "罂粟种子", length: "0.1cm", weight: "<1g", highlight: "心脏开始跳动" },
5: { emoji: "🫘", fruit: "芝麻粒", length: "0.2cm", weight: "<1g", highlight: "神经管开始发育" },
6: { emoji: "🫘", fruit: "小扁豆", length: "0.6cm", weight: "<1g", highlight: "小手小脚在萌芽" },
7: { emoji: "🫐", fruit: "蓝莓", length: "1.3cm", weight: "<1g", highlight: "五官开始形成" },
8: { emoji: "🫐", fruit: "覆盆子", length: "1.6cm", weight: "1g", highlight: "手指脚趾开始分化" },
9: { emoji: "🍇", fruit: "葡萄", length: "2.3cm", weight: "2g", highlight: "可以微微活动了" },
10: { emoji: "🍊", fruit: "金橘", length: "3.1cm", weight: "4g", highlight: "所有器官已初步形成" },
11: { emoji: "🫒", fruit: "无花果", length: "4.1cm", weight: "7g", highlight: "能做出吞咽动作" },
12: { emoji: "🍋", fruit: "青柠", length: "5.4cm", weight: "14g", highlight: "进入稳定的孕中期" },
13: { emoji: "🍋", fruit: "柠檬", length: "7.4cm", weight: "23g", highlight: "指纹开始形成" },
14: { emoji: "🍑", fruit: "桃子", length: "8.7cm", weight: "43g", highlight: "能做出表情了" },
16: { emoji: "🥑", fruit: "牛油果", length: "11.6cm", weight: "100g", highlight: "开始能听到声音" },
18: { emoji: "🫑", fruit: "甜椒", length: "14.2cm", weight: "190g", highlight: "妈妈可能感到胎动了" },
20: { emoji: "🍌", fruit: "香蕉", length: "25.6cm", weight: "300g", highlight: "味觉开始发育" },
22: { emoji: "🥭", fruit: "木瓜", length: "27.8cm", weight: "430g", highlight: "眉毛和眼睫毛长出" },
24: { emoji: "🌽", fruit: "玉米", length: "30cm", weight: "600g", highlight: "肺部开始发育" },
26: { emoji: "🥦", fruit: "菜花", length: "35.6cm", weight: "760g", highlight: "能睁开眼睛了" },
28: { emoji: "🍆", fruit: "茄子", length: "37.6cm", weight: "1000g", highlight: "开始有规律的作息" },
30: { emoji: "🥬", fruit: "卷心菜", length: "39.9cm", weight: "1320g", highlight: "大脑快速发育中" },
32: { emoji: "🥥", fruit: "椰子", length: "42.4cm", weight: "1700g", highlight: "皮下脂肪增多" },
34: { emoji: "🍈", fruit: "哈密瓜", length: "45cm", weight: "2150g", highlight: "肺部接近成熟" },
36: { emoji: "🍈", fruit: "蜜瓜", length: "47.4cm", weight: "2620g", highlight: "头部开始入盆" },
38: { emoji: "🎃", fruit: "南瓜", length: "49.8cm", weight: "3080g", highlight: "各器官发育成熟" },
40: { emoji: "🍉", fruit: "小西瓜", length: "51.2cm", weight: "3460g", highlight: "随时准备来到这个世界" },
};
function getBabyExpectedData(week: number) {
const weeks = Object.keys(BABY_EXPECTED_DATA).map(Number).sort((a, b) => a - b);
let closest = weeks[0];
for (const w of weeks) {
if (w <= week) closest = w;
else break;
}
return BABY_EXPECTED_DATA[closest];
}
// 宝宝预期大小卡片 - 无B超数据时展示
function BabyExpectedSizeCard({ week, onUpload }: { week: number; onUpload: () => void }) {
const data = getBabyExpectedData(week);
if (!data) return null;
// 计算进度百分比 (4-40周)
const progress = Math.min(100, Math.max(0, ((week - 4) / 36) * 100));
return (
<div className="space-y-4">
{/* 宝宝大小展示 */}
<div className="bg-gradient-to-br from-morandi-50 to-morandi-100 rounded-2xl p-5 text-center">
<motion.div
initial={{ scale: 0.8, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ type: "spring", duration: 0.6 }}
className="text-5xl mb-3"
>
{data.emoji}
</motion.div>
<p className="text-sm text-gray-700 font-medium mb-1">
宝宝现在像一个<span className="text-morandi-500 font-semibold">{data.fruit}</span>
</p>
<p className="text-xs text-gray-400">{data.highlight}</p>
</div>
{/* 预期数据 */}
<div className="grid grid-cols-2 gap-3">
<div className="bg-morandi-50 rounded-xl p-3 text-center">
<p className="text-[10px] text-gray-400 mb-1">预期身长</p>
<p className="text-base font-semibold text-morandi-600">{data.length}</p>
</div>
<div className="bg-morandi-50 rounded-xl p-3 text-center">
<p className="text-[10px] text-gray-400 mb-1">预期体重</p>
<p className="text-base font-semibold text-morandi-600">{data.weight}</p>
</div>
</div>
{/* 成长进度条 */}
<div>
<div className="flex items-center justify-between mb-1.5">
<span className="text-[10px] text-gray-400">孕期进度</span>
<span className="text-[10px] text-morandi-500 font-medium">{week}周 / 40周</span>
</div>
<div className="h-2 bg-morandi-50 rounded-full overflow-hidden">
<motion.div
className="h-full bg-gradient-to-r from-morandi-300 to-morandi-400 rounded-full"
initial={{ width: 0 }}
animate={{ width: `${progress}%` }}
transition={{ duration: 1, ease: "easeOut" }}
/>
</div>
</div>
{/* 提示 */}
<div className="bg-morandi-sage-50 rounded-xl p-3">
<div className="flex items-start gap-2">
<Info className="w-4 h-4 text-morandi-sage-400 mt-0.5 flex-shrink-0" />
<div>
<p className="text-xs text-gray-500 leading-relaxed">
上传B超报告后,可查看宝宝实际发育数据与标准值的对比曲线
</p>
<button
onClick={onUpload}
className="text-xs text-morandi-500 font-medium mt-1.5 hover:text-morandi-600"
>
去上传报告 →
</button>
</div>
</div>
</div>
</div>
);
}
export function HomePage() {
const navigate = useNavigate();
const { user } = useUser();
const [selectedMetric, setSelectedMetric] = useState("bpd");
const weekInfo = {
week: user.currentWeek,
day: user.currentDay,
dueDate: user.dueDate || "未设置",
babySize: getBabySize(user.currentWeek),
};
// 计算下次产检信息
const nextCheckup = useMemo(() => {
const currentWeek = user.currentWeek;
if (currentWeek <= 0) return null;
const upcoming = checkupSchedule.find((c) => c.week > currentWeek);
if (!upcoming) return null;
// 通过 lastPeriodDate 或 dueDate 反推末次月经日期
let lmpTime: number | null = null;
if (user.lastPeriodDate) {
lmpTime = new Date(user.lastPeriodDate).getTime();
} else if (user.dueDate) {
// 预产期 = 末次月经 + 280天,反推
lmpTime = new Date(user.dueDate).getTime() - 280 * 24 * 60 * 60 * 1000;
}
if (!lmpTime) {
// 兜底:用当前日期和当前孕周反推
const now = new Date();
const totalDays = currentWeek * 7 + (user.currentDay || 0);
lmpTime = now.getTime() - totalDays * 24 * 60 * 60 * 1000;
}
const checkupDate = new Date(lmpTime + upcoming.week * 7 * 24 * 60 * 60 * 1000);
const now = new Date();
const diffDays = Math.max(0, Math.ceil((checkupDate.getTime() - now.getTime()) / (24 * 60 * 60 * 1000)));
return {
title: upcoming.title,
date: `${checkupDate.getFullYear()}-${String(checkupDate.getMonth() + 1).padStart(2, "0")}-${String(checkupDate.getDate()).padStart(2, "0")}`,
daysLeft: diffDays,
};
}, [user.currentWeek, user.currentDay, user.lastPeriodDate, user.dueDate]);
// 生长曲线数据 - 只包含标准参考范围,不包含假的实际值
const defaultGrowthData: Record<string, { name: string; unit: string; color: string; data: any[] }> = {
bpd: {
name: "双顶径",
unit: "mm",
color: "#8562AB",
data: [
{ week: 12, standard: 20, lower: 18, upper: 22 },
{ week: 16, standard: 35, lower: 32, upper: 38 },
{ week: 20, standard: 47, lower: 43, upper: 51 },
{ week: 24, standard: 60, lower: 56, upper: 64 },
{ week: 28, standard: 71, lower: 67, upper: 75 },
{ week: 32, standard: 81, lower: 77, upper: 85 },
{ week: 36, standard: 89, lower: 85, upper: 93 },
],
},
ac: {
name: "腹围",
unit: "mm",
color: "#A07CC5",
data: [
{ week: 12, standard: 60, lower: 54, upper: 66 },
{ week: 16, standard: 102, lower: 94, upper: 110 },
{ week: 20, standard: 148, lower: 138, upper: 158 },
{ week: 24, standard: 192, lower: 180, upper: 204 },
{ week: 28, standard: 235, lower: 221, upper: 249 },
{ week: 32, standard: 279, lower: 263, upper: 295 },
{ week: 36, standard: 318, lower: 300, upper: 336 },
],
},
fl: {
name: "股骨长",
unit: "mm",
color: "#C48BB0",
data: [
{ week: 12, standard: 8, lower: 7, upper: 9 },
{ week: 16, standard: 22, lower: 20, upper: 24 },
{ week: 20, standard: 34, lower: 31, upper: 37 },
{ week: 24, standard: 45, lower: 42, upper: 48 },
{ week: 28, standard: 54, lower: 51, upper: 57 },
{ week: 32, standard: 63, lower: 60, upper: 66 },
{ week: 36, standard: 70, lower: 67, upper: 73 },
],
},
};
const [growthData, setGrowthData] = useState(defaultGrowthData);
useEffect(() => {
getGrowthCurve()
.then((data) => {
if (data.data_points && data.data_points.length > 0) {
const updated = { ...defaultGrowthData };
// 只添加有真实数据的点
for (const metric of ["bpd", "ac", "fl"] as const) {
const apiPoints = data.data_points.filter((p) => p[metric] != null);
if (apiPoints.length > 0) {
// 合并真实数据点和标准参考范围
const allWeeks = new Set([
...updated[metric].data.map(d => d.week),
...apiPoints.map(p => p.week)
]);
updated[metric] = {
...updated[metric],
data: Array.from(allWeeks)
.sort((a, b) => a - b)
.map((week) => {
const standardPoint = updated[metric].data.find(d => d.week === week);
const realPoint = apiPoints.find(p => p.week === week);
return {
week,
value: realPoint?.[metric] ?? null, // 只有真实数据才有 value
standard: standardPoint?.standard ?? null,
lower: standardPoint?.lower ?? null,
upper: standardPoint?.upper ?? null,
};
}),
};
}
}
setGrowthData(updated);
}
// 如果没有数据,保持 defaultGrowthData(只有标准范围,没有实际值)
})
.catch(() => {/* keep defaults */});
}, []);
const currentData = growthData[selectedMetric];
// 检查是否有真实数据
const hasRealData = currentData.data.some(d => d.value != null);
// ─── 指标趋势分析 ───
const [trendIndicators, setTrendIndicators] = useState<IndicatorTrend[]>([]);
const [selectedTrend, setSelectedTrend] = useState(0);
useEffect(() => {
getIndicatorTrends()
.then((data) => setTrendIndicators(data.indicators))
.catch(() => {});
}, []);
const currentTrend = trendIndicators[selectedTrend] || null;
const trendChartData = useMemo(() => {
if (!currentTrend) return [];
return currentTrend.points.map((p) => ({
week: p.week > 0 ? `${p.week}周` : p.date.split("T")[0]?.slice(5) || "",
value: p.value,
refLower: currentTrend.ref_lower,
refUpper: currentTrend.ref_upper,
}));
}, [currentTrend]);
const CustomTooltip = ({ active, payload }: any) => {
if (active && payload && payload.length) {
return (
<div className="bg-white p-3 rounded-xl shadow-lg border border-morandi-100">
<p className="font-semibold text-gray-700 mb-1 text-xs">
孕{payload[0].payload.week}周
</p>
<p className="text-xs text-morandi-500">
实际: {payload[0].value} {currentData.unit}
</p>
<p className="text-xs text-gray-400">
标准: {payload[0].payload.standard} {currentData.unit}
</p>
</div>
);
}
return null;
};
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white/80 backdrop-blur-sm border-b border-morandi-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-3 flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-9 h-9 bg-gradient-to-br from-morandi-300 to-morandi-400 rounded-full flex items-center justify-center">
<Heart className="w-4 h-4 text-white fill-white" />
</div>
<div>
<h1 className="font-semibold text-gray-700 text-sm">孕育无忧</h1>
</div>
</div>
<div className="flex items-center gap-1">
<button
onClick={() => navigate("/notifications")}
className="w-9 h-9 rounded-full hover:bg-morandi-50 flex items-center justify-center relative"
>
<Bell className="w-4.5 h-4.5 text-gray-400" />
<span className="absolute top-1.5 right-1.5 w-1.5 h-1.5 bg-morandi-rose-400 rounded-full" />
</button>
<button
onClick={() => navigate("/profile")}
className="w-9 h-9 rounded-full hover:bg-morandi-50 flex items-center justify-center"
>
<User className="w-4.5 h-4.5 text-gray-400" />
</button>
</div>
</div>
</div>
<div className="mx-auto p-4 space-y-4">
{/* 孕周卡片 */}
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
>
<Card className="bg-gradient-to-br from-morandi-400 via-morandi-300 to-morandi-rose-300 border-0 text-white px-4 py-3 rounded-2xl shadow-sm">
<div className="flex items-center justify-between">
<div className="flex items-baseline gap-1">
<span className="text-xl font-bold">{weekInfo.week}</span>
<span className="text-xs font-medium text-white/80">周</span>
<span className="text-xl font-bold">{weekInfo.day}</span>
<span className="text-xs font-medium text-white/80">天</span>
</div>
<div className="text-xs text-white/80">
预产期 <span className="font-medium text-white">{weekInfo.dueDate}</span>
</div>
</div>
{nextCheckup && (
<div
className="mt-2 bg-white/15 rounded-lg px-3 py-1.5 flex items-center justify-between cursor-pointer"
onClick={() => navigate("/calendar")}
>
<div className="flex items-center gap-1.5">
<Calendar className="w-3.5 h-3.5 text-white/70" />
<span className="text-[11px] text-white/90">{nextCheckup.title}</span>
<span className="text-[11px] text-white/50">{nextCheckup.date}</span>
</div>
<span className="text-[11px] font-medium text-white/80">{nextCheckup.daysLeft}天后</span>
</div>
)}
</Card>
</motion.div>
{/* 快捷操作 */}
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.05 }}
>
<div className="grid grid-cols-[1.05fr_0.95fr] gap-3">
<button
onClick={() => navigate("/camera")}
className="bg-white rounded-2xl p-4 shadow-sm hover:shadow-md transition-all group text-left min-h-[182px]"
>
<div className="h-full flex flex-col justify-between">
<div className="w-12 h-12 bg-morandi-rose-100 rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform">
<Camera className="w-5 h-5 text-morandi-rose-400" />
</div>
<div>
<div className="font-medium text-gray-700 text-base">AI报告解读</div>
<div className="text-xs text-gray-400 mt-1 leading-relaxed">
拍照上传<br />快速查看解读结果
</div>
</div>
</div>
</button>
<div className="space-y-2.5">
<button
onClick={() => navigate("/calendar")}
className="w-full bg-white rounded-2xl p-3.5 shadow-sm hover:shadow-md transition-all group text-left"
>
<div className="flex items-center gap-3">
<div className="w-9 h-9 bg-morandi-sage-100 rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform flex-shrink-0">
<Calendar className="w-4.5 h-4.5 text-morandi-sage-400" />
</div>
<div className="flex-1 min-w-0">
<div className="font-medium text-gray-700 text-sm">产检日历</div>
<div className="text-[11px] text-gray-400 mt-0.5">产检计划·提醒</div>
</div>
</div>
</button>
<button
onClick={() => navigate("/health-records")}
className="w-full bg-white rounded-2xl p-3.5 shadow-sm hover:shadow-md transition-all group text-left"
>
<div className="flex items-center gap-3">
<div className="w-9 h-9 bg-morandi-100 rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform flex-shrink-0">
<FileText className="w-4.5 h-4.5 text-morandi-500" />
</div>
<div className="flex-1 min-w-0">
<div className="font-medium text-gray-700 text-sm">健康报告</div>
<div className="text-[11px] text-gray-400 mt-0.5">数据分析</div>
</div>
</div>
</button>
<button
onClick={() => navigate("/voice-record")}
className="w-full bg-white rounded-2xl p-3.5 shadow-sm hover:shadow-md transition-all group text-left"
>
<div className="flex items-center gap-3">
<div className="w-9 h-9 bg-morandi-100 rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform flex-shrink-0">
<Mic className="w-4.5 h-4.5 text-morandi-500" />
</div>
<div className="flex-1 min-w-0">
<div className="font-medium text-gray-700 text-sm">语音记录</div>
<div className="text-[11px] text-gray-400 mt-0.5">就诊记录·孕期日记</div>
</div>
</div>
</button>
</div>
</div>
</motion.div>
{/* 宝宝生长趋势 */}
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.15 }}
>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
<div className="flex items-center justify-between mb-4">
<h2 className="font-semibold text-gray-700 flex items-center gap-2 text-base">
<TrendingUp className="w-5 h-5 text-morandi-400" />
宝宝生长趋势
</h2>
<button
onClick={() => navigate("/growth-curve")}
className="text-xs text-morandi-500 hover:text-morandi-600 flex items-center"
>
查看详情
<ChevronRight className="w-3.5 h-3.5 ml-0.5" />
</button>
</div>
{hasRealData ? (
<>
{/* 指标选择 */}
<div className="flex gap-2 mb-4">
{[
{ key: "bpd", label: "双顶径" },
{ key: "ac", label: "腹围" },
{ key: "fl", label: "股骨长" },
].map((m) => (
<button
key={m.key}
onClick={() => setSelectedMetric(m.key)}
className={`px-4 py-1.5 rounded-full text-xs font-medium transition-all ${
selectedMetric === m.key
? "bg-morandi-400 text-white"
: "bg-morandi-50 text-gray-500 hover:bg-morandi-100"
}`}
>
{m.label}
</button>
))}
</div>
{/* 图表 */}
<div className="mb-4">
<ResponsiveContainer width="100%" height={180}>
<ComposedChart data={currentData.data}>
<defs>
<linearGradient id="colorRange" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#C4A8DC" stopOpacity={0.3} />
<stop offset="95%" stopColor="#C4A8DC" stopOpacity={0.05} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="#EDE6F2" />
<XAxis
dataKey="week"
stroke="#B0A8B8"
tick={{ fontSize: 11 }}
/>
<YAxis stroke="#B0A8B8" tick={{ fontSize: 11 }} />
<Tooltip content={<CustomTooltip />} />
<Area
type="monotone"
dataKey="upper"
stroke="none"
fill="url(#colorRange)"
/>
<Area
type="monotone"
dataKey="lower"
stroke="none"
fill="#ffffff"
/>
<Line
type="monotone"
dataKey="standard"
stroke="#C4A8DC"
strokeWidth={2}
dot={false}
strokeDasharray="5 5"
/>
<Line
type="monotone"
dataKey="value"
stroke={currentData.color}
strokeWidth={2.5}
dot={{ fill: currentData.color, r: 3.5 }}
connectNulls={false}
/>
</ComposedChart>
</ResponsiveContainer>
</div>
{/* 图例 */}
<div className="flex items-center gap-4 mb-3 text-xs">
<div className="flex items-center gap-1.5">
<div
className="w-2 h-2 rounded-full"
style={{ backgroundColor: currentData.color }}
/>
<span className="text-gray-500">实际值</span>
</div>
<div className="flex items-center gap-1.5">
<div className="w-2 h-2 bg-morandi-200 rounded-full" />
<span className="text-gray-500">标准值</span>
</div>
<div className="flex items-center gap-1.5">
<div className="w-2 h-2 bg-morandi-100 rounded-full" />
<span className="text-gray-500">正常范围</span>
</div>
</div>
{/* 评估 */}
{(() => {
const realPoints = currentData.data.filter((d: any) => d.value != null);
if (realPoints.length === 0) return null;
const latest = realPoints[realPoints.length - 1];
const val = latest.value!;
const inRange = val >= latest.lower && val <= latest.upper;
const isHigh = val > latest.upper;
const assessBg = inRange ? "bg-morandi-50" : "bg-amber-50";
const assessIcon = inRange ? "text-morandi-sage-400" : "text-amber-500";
const assessText = inRange
? `宝宝的${currentData.name}发育良好,孕${latest.week}周实测${val}${currentData.unit},在正常范围内`
: isHigh
? `宝宝的${currentData.name}孕${latest.week}周实测${val}${currentData.unit},略高于参考上限${latest.upper}${currentData.unit},建议关注`
: `宝宝的${currentData.name}孕${latest.week}周实测${val}${currentData.unit},略低于参考下限${latest.lower}${currentData.unit},建议关注`;
return (
<div className={`${assessBg} rounded-xl p-3`}>
<div className="flex items-start gap-2">
<Info className={`w-4 h-4 ${assessIcon} mt-0.5 flex-shrink-0`} />
<p className="text-xs text-gray-500 leading-relaxed">{assessText}</p>
</div>
</div>
);
})()}
</>
) : (
<BabyExpectedSizeCard week={weekInfo.week} onUpload={() => navigate("/camera")} />
)}
</Card>
</motion.div>
{/* 孕检报告趋势分析 */}
{trendIndicators.length > 0 && (
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
<div className="flex items-center justify-between mb-4">
<h2 className="font-semibold text-gray-700 flex items-center gap-2 text-base">
<TrendingUp className="w-5 h-5 text-morandi-sage-400" />
报告趋势分析
</h2>
<span className="text-xs text-gray-400">{trendIndicators.length}项可对比指标</span>
</div>
{/* 指标选择 - 横向滚动 */}
<div className="flex gap-2 mb-4 overflow-x-auto pb-1 -mx-1 px-1 scrollbar-hide">
{trendIndicators.map((ind, idx) => (
<button
key={ind.name}
onClick={() => setSelectedTrend(idx)}
className={`px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-all flex-shrink-0 ${
selectedTrend === idx
? "bg-morandi-sage-400 text-white"
: "bg-morandi-50 text-gray-500 hover:bg-morandi-100"
}`}
>
{ind.name}
</button>
))}
</div>
{currentTrend && (
<>
{/* 趋势图表 */}
<div className="mb-4">
<ResponsiveContainer width="100%" height={180}>
<ComposedChart data={trendChartData}>
<defs>
<linearGradient id="trendRefRange" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#A8C5A0" stopOpacity={0.2} />
<stop offset="95%" stopColor="#A8C5A0" stopOpacity={0.05} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="#EDE6F2" />
<XAxis dataKey="week" stroke="#B0A8B8" tick={{ fontSize: 11 }} />
<YAxis stroke="#B0A8B8" tick={{ fontSize: 11 }} />
<Tooltip
content={({ active, payload }: any) => {
if (active && payload?.[0]) {
const d = payload[0].payload;
return (
<div className="bg-white p-3 rounded-xl shadow-lg border border-morandi-100">
<p className="font-semibold text-gray-700 text-xs mb-1">{d.week}</p>
<p className="text-xs text-morandi-sage-500">
{currentTrend.name}: {d.value} {currentTrend.unit}
</p>
{d.refLower != null && d.refUpper != null && (
<p className="text-xs text-gray-400">
参考: {d.refLower}-{d.refUpper} {currentTrend.unit}
</p>
)}
</div>
);
}
return null;
}}
/>
{currentTrend.ref_upper != null && (
<Area type="monotone" dataKey="refUpper" stroke="none" fill="url(#trendRefRange)" />
)}
{currentTrend.ref_lower != null && (
<Area type="monotone" dataKey="refLower" stroke="none" fill="#ffffff" />
)}
<Line
type="monotone"
dataKey="value"
stroke="#7BA37A"
strokeWidth={2.5}
dot={{ fill: "#7BA37A", r: 4 }}
/>
</ComposedChart>
</ResponsiveContainer>
</div>
{/* 图例 */}
<div className="flex items-center gap-4 mb-3 text-xs">
<div className="flex items-center gap-1.5">
<div className="w-2 h-2 rounded-full bg-[#7BA37A]" />
<span className="text-gray-500">实际值</span>
</div>
{currentTrend.ref_lower != null && (
<div className="flex items-center gap-1.5">
<div className="w-2 h-2 bg-morandi-sage-100 rounded-full" />
<span className="text-gray-500">
参考范围 {currentTrend.ref_lower}-{currentTrend.ref_upper} {currentTrend.unit}
</span>
</div>
)}
</div>
{/* 数据表格 */}
<div className="bg-morandi-50 rounded-xl p-3">
<div className="grid grid-cols-3 gap-1 text-xs text-gray-400 mb-2 px-1">
<span>时间</span>
<span className="text-center">数值</span>
<span className="text-right">状态</span>
</div>
{currentTrend.points.map((p, i) => (
<div key={i} className="grid grid-cols-3 gap-1 text-xs px-1 py-1.5 border-t border-morandi-100">
<span className="text-gray-600">{p.week > 0 ? `第${p.week}周` : p.date.split("T")[0]?.slice(5)}</span>
<span className="text-center font-medium text-gray-700">
{p.value} {currentTrend.unit}
</span>
<span className={`text-right ${
p.status === "normal" ? "text-morandi-sage-500" :
p.status === "high" ? "text-morandi-rose-500" :
"text-amber-500"
}`}>
{p.status === "normal" ? "正常" : p.status === "high" ? "偏高" : "偏低"}
</span>
</div>
))}
</div>
</>
)}
</Card>
</motion.div>
)}
{/* 底部留白 */}
<div className="h-16" />
</div>
{/* 浮动按钮 */}
<motion.button
onClick={() => navigate("/camera")}
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ delay: 0.3, type: "spring" }}
className="fixed bottom-8 right-8 w-14 h-14 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-full shadow-lg flex items-center justify-center hover:scale-105 transition-transform"
>
<Plus className="w-7 h-7 text-white" />
</motion.button>
</div>
);
}

View File

@@ -0,0 +1,365 @@
import { useState, useEffect, useCallback, useRef } from "react";
import { useNavigate } from "react-router";
import { motion, AnimatePresence } from "motion/react";
import { Heart, Loader2, Phone, ArrowRight, ChevronLeft } from "lucide-react";
import { Button } from "../components/ui/button";
import { useUser } from "../context/UserContext";
import { loginByWechat, loginByDemo, loginByPhone, getToken } from "../services/api";
/** 判断是否在微信小程序 webview 环境 */
function isWechatMiniProgram(): boolean {
const ua = navigator.userAgent.toLowerCase();
return ua.includes("micromessenger") && ua.includes("miniprogram");
}
/** 调用 wx.miniProgram.login 获取 code */
function wxLogin(): Promise<string> {
return new Promise((resolve, reject) => {
const wx = (window as any).wx;
if (!wx?.miniProgram) {
reject(new Error("非小程序环境"));
return;
}
wx.miniProgram.login({
success: (res: any) => {
if (res.code) {
resolve(res.code);
} else {
reject(new Error("获取登录凭证失败"));
}
},
fail: () => reject(new Error("微信登录失败")),
});
});
}
export function LoginPage() {
const navigate = useNavigate();
const { setToken, fetchProfile, user } = useUser();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
const [autoLoginTried, setAutoLoginTried] = useState(false);
// 手机号登录状态
const [showPhoneLogin, setShowPhoneLogin] = useState(false);
const [phoneNumber, setPhoneNumber] = useState("");
const [smsCode, setSmsCode] = useState("");
const [smsSent, setSmsSent] = useState(false);
const [countdown, setCountdown] = useState(0);
const countdownRef = useRef<ReturnType<typeof setInterval> | null>(null);
// 已有 token 且已完成 onboarding,直接跳首页
useEffect(() => {
if (getToken() && user.isOnboarded) {
navigate("/home", { replace: true });
}
}, []);
// 倒计时
useEffect(() => {
if (countdown > 0) {
countdownRef.current = setInterval(() => {
setCountdown((prev) => {
if (prev <= 1) {
if (countdownRef.current) clearInterval(countdownRef.current);
return 0;
}
return prev - 1;
});
}, 1000);
}
return () => {
if (countdownRef.current) clearInterval(countdownRef.current);
};
}, [countdown > 0]);
const handleLoginSuccess = useCallback(
async (res: { access_token: string; is_new_user: boolean }) => {
setToken(res.access_token);
if (res.is_new_user) {
// 新用户 → 走 onboarding 流程
navigate("/onboarding");
} else {
// 老用户 → 拉取资料后直接进首页
await fetchProfile();
navigate("/home", { replace: true });
}
},
[setToken, fetchProfile, navigate]
);
// 小程序环境自动登录
useEffect(() => {
if (autoLoginTried) return;
if (getToken() && user.isOnboarded) return;
if (isWechatMiniProgram()) {
setAutoLoginTried(true);
setIsLoading(true);
wxLogin()
.then((code) => loginByWechat(code))
.then(handleLoginSuccess)
.catch((err) => {
setError(err.message || "自动登录失败");
})
.finally(() => setIsLoading(false));
}
}, [autoLoginTried, user.isOnboarded, handleLoginSuccess]);
// 一键体验(demo)
const handleDemoLogin = async () => {
setError("");
setIsLoading(true);
try {
if (isWechatMiniProgram()) {
const code = await wxLogin();
const res = await loginByWechat(code);
await handleLoginSuccess(res);
} else {
const res = await loginByDemo();
await handleLoginSuccess(res);
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : "登录失败,请重试";
setError(message);
} finally {
setIsLoading(false);
}
};
// 发送验证码
const handleSendSms = () => {
if (phoneNumber.length !== 11) {
setError("请输入正确的11位手机号");
return;
}
setError("");
setSmsSent(true);
setCountdown(60);
};
// 手机号登录
const handlePhoneLogin = async () => {
if (phoneNumber.length !== 11) {
setError("请输入正确的11位手机号");
return;
}
if (smsCode.length < 4) {
setError("请输入验证码");
return;
}
setError("");
setIsLoading(true);
try {
const res = await loginByPhone(phoneNumber, smsCode);
await handleLoginSuccess(res);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : "登录失败,请重试";
setError(message);
} finally {
setIsLoading(false);
}
};
return (
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="w-full"
>
<div className="text-center mb-8">
<motion.div
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ delay: 0.2, type: "spring" }}
className="inline-flex items-center justify-center w-20 h-20 bg-gradient-to-br from-morandi-300 to-morandi-400 rounded-full mb-4"
>
<Heart className="w-10 h-10 text-white fill-white" />
</motion.div>
<h1 className="text-3xl font-semibold bg-gradient-to-r from-morandi-400 to-morandi-500 bg-clip-text text-transparent mb-2">
孕育无忧
</h1>
<p className="text-gray-600">您的专属孕期健康助手</p>
</div>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.3 }}
className="bg-white rounded-3xl shadow-md p-8"
>
<AnimatePresence mode="wait">
{!showPhoneLogin ? (
/* ─── 主登录页 ─── */
<motion.div
key="main"
initial={{ opacity: 0, x: 0 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
className="space-y-4"
>
{/* 错误提示 */}
{error && (
<motion.p
initial={{ opacity: 0, y: -5 }}
animate={{ opacity: 1, y: 0 }}
className="text-sm text-red-500 bg-red-50 px-4 py-2 rounded-xl"
>
{error}
</motion.p>
)}
{/* 手机号登录按钮 */}
<Button
onClick={() => { setError(""); setShowPhoneLogin(true); }}
disabled={isLoading}
className="w-full h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium"
>
<Phone className="w-4 h-4 mr-2" />
手机号登录
</Button>
{/* 分隔线 */}
<div className="flex items-center gap-3">
<div className="flex-1 h-px bg-gray-200" />
<span className="text-xs text-gray-400">或</span>
<div className="flex-1 h-px bg-gray-200" />
</div>
{/* 一键体验 */}
<Button
onClick={handleDemoLogin}
disabled={isLoading}
variant="outline"
className="w-full h-12 rounded-xl border-2 border-morandi-200 text-morandi-500 font-medium hover:bg-morandi-50"
>
{isLoading ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
登录中...
</>
) : isWechatMiniProgram() ? (
"微信一键授权登录"
) : (
"游客体验"
)}
</Button>
<p className="text-xs text-gray-400 text-center">
游客模式数据不保留,建议使用手机号登录
</p>
</motion.div>
) : (
/* ─── 手机号登录表单 ─── */
<motion.div
key="phone"
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
className="space-y-4"
>
{/* 返回 */}
<button
onClick={() => { setShowPhoneLogin(false); setError(""); setSmsSent(false); setSmsCode(""); }}
className="flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 -ml-1 mb-1"
>
<ChevronLeft className="w-4 h-4" />
返回
</button>
<h2 className="text-lg font-semibold text-gray-800">手机号登录</h2>
<p className="text-sm text-gray-500 -mt-2">登录后数据将绑定到您的手机号</p>
{/* 错误提示 */}
{error && (
<motion.p
initial={{ opacity: 0, y: -5 }}
animate={{ opacity: 1, y: 0 }}
className="text-sm text-red-500 bg-red-50 px-4 py-2 rounded-xl"
>
{error}
</motion.p>
)}
{/* 手机号输入 */}
<div className="space-y-1">
<label className="text-sm text-gray-600 font-medium">手机号</label>
<input
type="tel"
maxLength={11}
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value.replace(/\D/g, ""))}
placeholder="请输入11位手机号"
className="w-full h-12 px-4 rounded-xl border-2 border-gray-200 focus:border-morandi-400 outline-none transition-colors text-base"
/>
</div>
{/* 验证码输入 */}
<div className="space-y-1">
<label className="text-sm text-gray-600 font-medium">验证码</label>
<div className="flex gap-3">
<input
type="text"
maxLength={6}
value={smsCode}
onChange={(e) => setSmsCode(e.target.value.replace(/\D/g, ""))}
placeholder="请输入验证码"
className="flex-1 h-12 px-4 rounded-xl border-2 border-gray-200 focus:border-morandi-400 outline-none transition-colors text-base"
/>
<button
onClick={handleSendSms}
disabled={countdown > 0 || phoneNumber.length !== 11}
className={`px-4 h-12 rounded-xl text-sm font-medium whitespace-nowrap transition-all ${
countdown > 0 || phoneNumber.length !== 11
? "bg-gray-100 text-gray-400"
: "bg-morandi-100 text-morandi-500 hover:bg-morandi-200"
}`}
>
{countdown > 0 ? `${countdown}s` : smsSent ? "重新发送" : "获取验证码"}
</button>
</div>
{smsSent && (
<p className="text-xs text-morandi-400 mt-1">
验证码已发送,请输入 123456
</p>
)}
</div>
{/* 登录按钮 */}
<Button
onClick={handlePhoneLogin}
disabled={isLoading || phoneNumber.length !== 11 || smsCode.length < 4}
className="w-full h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium disabled:opacity-50"
>
{isLoading ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
登录中...
</>
) : (
<>
登录
<ArrowRight className="w-4 h-4 ml-2" />
</>
)}
</Button>
</motion.div>
)}
</AnimatePresence>
<p className="text-xs text-gray-500 text-center mt-6">
登录即表示同意
<a href="#" className="text-morandi-400 hover:underline">
用户协议
</a>
和
<a href="#" className="text-morandi-400 hover:underline">
隐私政策
</a>
</p>
</motion.div>
</motion.div>
</div>
);
}

View File

@@ -0,0 +1,462 @@
import { useState } from "react";
import { useNavigate } from "react-router";
import { motion, AnimatePresence } from "motion/react";
import {
ChevronLeft,
Bell,
Clock,
CheckCircle2,
ChevronRight,
Stethoscope,
Baby,
CircleDot,
AlertCircle,
Calendar,
} from "lucide-react";
import { Card } from "../components/ui/card";
import { Badge } from "../components/ui/badge";
import { useUser, calcPregnancyWeek } from "../context/UserContext";
import { checkupSchedule } from "../data/checkupSchedule";
interface Notification {
id: string;
type: "checkup_reminder" | "preparation" | "weekly_tip" | "milestone";
title: string;
content: string;
time: string;
read: boolean;
tags?: string[];
link?: string;
checkupItems?: string[];
checkupPreparations?: string[];
}
function generateNotifications(currentWeek: number, lastPeriodDate: string): Notification[] {
const notifications: Notification[] = [];
// 下次产检提醒(来源于产检日历)
const nextCheckup = checkupSchedule.find((c) => c.week > currentWeek);
if (nextCheckup) {
let dateStr = "";
let daysInfo = "";
if (lastPeriodDate) {
const lmp = new Date(lastPeriodDate);
const checkupDate = new Date(lmp.getTime() + nextCheckup.week * 7 * 24 * 60 * 60 * 1000);
dateStr = checkupDate.toISOString().split("T")[0];
const daysUntil = Math.max(0, Math.ceil((checkupDate.getTime() - Date.now()) / (1000 * 60 * 60 * 24)));
daysInfo = `${dateStr} · 距今${daysUntil}天`;
} else {
daysInfo = `还有${nextCheckup.week - currentWeek}周`;
}
notifications.push({
id: "next-checkup",
type: "checkup_reminder",
title: `下次产检:${nextCheckup.title}`,
content: `孕${nextCheckup.week}周 · ${daysInfo}`,
time: "今天",
read: false,
tags: nextCheckup.preparations.filter(
(p) => p.includes("空腹") || p.includes("憋尿") || p.startsWith("需")
),
checkupItems: nextCheckup.items,
checkupPreparations: nextCheckup.preparations,
});
// 产检项目提醒
notifications.push({
id: "checkup-items",
type: "preparation",
title: `${nextCheckup.title}检查项目`,
content: `共${nextCheckup.items.length}项:${nextCheckup.items.slice(0, 3).join("、")}${nextCheckup.items.length > 3 ? "等" : ""}`,
time: "今天",
read: false,
link: "/calendar",
});
// 特殊注意事项
const specialPreps = nextCheckup.preparations.filter(
(p) => p.includes("空腹") || p.includes("憋尿") || p.includes("携带") || p.includes("预约")
);
if (specialPreps.length > 0) {
notifications.push({
id: "prep-reminder",
type: "preparation",
title: "产检准备提醒",
content: specialPreps.join(";"),
time: "今天",
read: false,
tags: specialPreps.filter((p) => p.includes("空腹") || p.includes("憋尿")),
});
}
}
// 孕周知识推送
notifications.push({
id: "weekly-tip",
type: "weekly_tip",
title: `孕${currentWeek}周知识`,
content: `本周宝宝正在快速发育,请注意补充营养,避免剧烈运动,保持充足睡眠。`,
time: "今天",
read: false,
});
// 孕期里程碑
const milestones: Record<number, string> = {
8: "宝宝的心脏已经开始跳动,四肢也开始发育。记得按时服用叶酸哦~",
12: "宝宝已经有了人的模样,可以做NT检查了。进入相对稳定的孕中期!",
16: "宝宝开始有了听觉,可以和宝宝说说话啦~",
20: "宝宝可以感受到外界的光线了,是做大排畸检查的好时机!",
24: "宝宝体重快速增长,记得做糖耐量检查哦~",
28: "进入孕晚期啦!产检频率要增加了,注意数胎动~",
32: "宝宝头部朝下准备入盆,可以开始准备待产包了!",
36: "宝宝随时可能发动,做好迎接宝宝的准备吧~",
};
const milestoneWeek = Object.keys(milestones).map(Number).find((w) => w === currentWeek);
if (milestoneWeek) {
notifications.push({
id: `milestone-${milestoneWeek}`,
type: "milestone",
title: `孕${milestoneWeek}周里程碑`,
content: `恭喜进入孕${milestoneWeek}周!${milestones[milestoneWeek]}`,
time: "昨天",
read: true,
});
}
// 下下次产检预告
const secondCheckup = checkupSchedule.find((c) => nextCheckup && c.week > nextCheckup.week);
if (secondCheckup) {
notifications.push({
id: "future-checkup",
type: "checkup_reminder",
title: `产检预告:${secondCheckup.title}`,
content: `孕${secondCheckup.week}周 · ${secondCheckup.items.slice(0, 2).join("、")}等`,
time: "3天前",
read: true,
link: "/calendar",
});
}
// 上周知识回顾
if (currentWeek > 1) {
notifications.push({
id: "last-week-tip",
type: "weekly_tip",
title: `孕${currentWeek - 1}周回顾`,
content: "上周的营养建议:多摄入富含蛋白质和铁元素的食物,每日补充0.4mg叶酸。",
time: "一周前",
read: true,
});
}
return notifications;
}
export function NotificationPage() {
const navigate = useNavigate();
const { user } = useUser();
const currentWeek = user.currentWeek || 0;
const [notifications, setNotifications] = useState<Notification[]>(() =>
generateNotifications(currentWeek, user.lastPeriodDate)
);
const [filter, setFilter] = useState<"all" | "unread">("all");
const [expandedId, setExpandedId] = useState<string | null>(null);
const unreadCount = notifications.filter((n) => !n.read && n.type !== "preparation").length;
const filteredNotifications =
filter === "unread"
? notifications.filter((n) => !n.read && n.type !== "preparation")
: notifications.filter((n) => n.type !== "preparation");
const markAsRead = (id: string) => {
setNotifications((prev) =>
prev.map((n) => (n.id === id ? { ...n, read: true } : n))
);
};
const markAllRead = () => {
setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
};
const getIcon = (type: Notification["type"]) => {
switch (type) {
case "checkup_reminder":
return <Stethoscope className="w-5 h-5 text-morandi-500" />;
case "preparation":
return <AlertCircle className="w-5 h-5 text-morandi-rose-400" />;
case "weekly_tip":
return <Baby className="w-5 h-5 text-morandi-400" />;
case "milestone":
return <CircleDot className="w-5 h-5 text-morandi-sage-400" />;
}
};
const getIconBg = (type: Notification["type"]) => {
switch (type) {
case "checkup_reminder":
return "bg-morandi-100";
case "preparation":
return "bg-morandi-rose-100";
case "weekly_tip":
return "bg-morandi-50";
case "milestone":
return "bg-morandi-sage-100";
}
};
const getTypeLabel = (type: Notification["type"]) => {
switch (type) {
case "checkup_reminder":
return "产检提醒";
case "preparation":
return "注意事项";
case "weekly_tip":
return "孕周知识";
case "milestone":
return "孕期里程碑";
}
};
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => navigate(-1)}
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<ChevronLeft className="w-6 h-6 text-gray-600" />
</button>
<div className="flex items-center gap-2">
<div className="w-10 h-10 bg-gradient-to-br from-morandi-300 to-morandi-400 rounded-full flex items-center justify-center">
<Bell className="w-5 h-5 text-white" />
</div>
<div>
<h1 className="font-semibold text-gray-800">消息中心</h1>
<p className="text-xs text-gray-500">
{unreadCount > 0 ? `${unreadCount}条未读消息` : "暂无未读消息"}
</p>
</div>
</div>
</div>
{unreadCount > 0 && (
<button
onClick={markAllRead}
className="text-xs text-morandi-500 hover:text-morandi-600 font-medium"
>
全部已读
</button>
)}
</div>
</div>
<div className="mx-auto p-4 space-y-5">
{/* 筛选按钮 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
>
<div className="flex items-center gap-3">
<h2 className="font-semibold text-gray-800 flex-1">全部消息</h2>
<div className="flex gap-1.5 bg-white rounded-full p-1 shadow-sm">
{(["all", "unread"] as const).map((f) => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-4 py-1.5 rounded-full text-xs font-medium transition-all ${
filter === f
? "bg-morandi-400 text-white"
: "text-gray-500 hover:bg-morandi-50"
}`}
>
{f === "all" ? "全部" : `未读 (${unreadCount})`}
</button>
))}
</div>
</div>
</motion.div>
{/* 消息列表 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.05 }}
className="space-y-3"
>
<AnimatePresence mode="popLayout">
{filteredNotifications.length === 0 ? (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="text-center py-12"
>
<CheckCircle2 className="w-12 h-12 text-morandi-200 mx-auto mb-3" />
<p className="text-gray-400 text-sm">暂无未读消息</p>
</motion.div>
) : (
filteredNotifications.map((notification, index) => (
<motion.div
key={notification.id}
layout
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
transition={{ delay: index * 0.03 }}
>
<Card
className={`rounded-2xl p-4 shadow-sm border-0 cursor-pointer transition-all hover:shadow-md ${
!notification.read
? "bg-white border-l-4 border-l-morandi-400"
: "bg-white opacity-80"
}`}
onClick={() => {
markAsRead(notification.id);
if (expandedId === notification.id) {
setExpandedId(null);
} else {
setExpandedId(notification.id);
}
}}
>
<div className="flex items-start gap-3">
<div
className={`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${getIconBg(
notification.type
)}`}
>
{getIcon(notification.type)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<Badge
className={`text-[10px] px-1.5 py-0 ${
notification.type === "checkup_reminder"
? "bg-morandi-100 text-morandi-600"
: notification.type === "preparation"
? "bg-morandi-rose-100 text-morandi-rose-400"
: notification.type === "milestone"
? "bg-morandi-sage-100 text-morandi-sage-500"
: "bg-morandi-50 text-morandi-400"
} hover:bg-current`}
>
{getTypeLabel(notification.type)}
</Badge>
<span className="text-[10px] text-gray-400 ml-auto flex-shrink-0">
{notification.time}
</span>
{!notification.read && (
<span className="w-2 h-2 bg-morandi-rose-400 rounded-full flex-shrink-0" />
)}
</div>
<h4 className="font-medium text-gray-800 text-sm mb-1 truncate">
{notification.title}
</h4>
<p className="text-xs text-gray-500 leading-relaxed line-clamp-2">
{notification.content}
</p>
{/* 特殊标签 */}
{notification.tags && notification.tags.length > 0 && (
<div className="flex gap-1.5 mt-2 flex-wrap">
{notification.tags.map((tag, i) => (
<span
key={i}
className="inline-flex items-center gap-1 px-2 py-0.5 bg-morandi-rose-100 text-morandi-rose-400 rounded-full text-[10px] font-medium"
>
<AlertCircle className="w-2.5 h-2.5" />
{tag}
</span>
))}
</div>
)}
{/* 展开的详情 */}
<AnimatePresence>
{expandedId === notification.id && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: "auto", opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="overflow-hidden"
>
<div className="mt-3 pt-3 border-t border-gray-100 space-y-3">
{/* 检查项目 */}
{notification.checkupItems && notification.checkupItems.length > 0 && (
<div>
<h5 className="font-semibold text-gray-700 mb-2 text-xs">
检查项目
</h5>
<div className="grid grid-cols-2 gap-2">
{notification.checkupItems.map((item, i) => (
<div
key={i}
className="text-xs text-gray-600 flex items-center gap-2 bg-gray-50 rounded-lg px-2.5 py-1.5"
>
<div className="w-1 h-1 bg-morandi-400 rounded-full flex-shrink-0"></div>
{item}
</div>
))}
</div>
</div>
)}
{/* 注意事项 */}
{notification.checkupPreparations && notification.checkupPreparations.length > 0 && (
<div className="bg-morandi-rose-50 rounded-xl p-3">
<h5 className="font-semibold text-morandi-700 mb-2 text-xs flex items-center gap-1.5">
<AlertCircle className="w-3.5 h-3.5" />
注意事项
</h5>
<ul className="space-y-1">
{notification.checkupPreparations.map((prep, i) => (
<li
key={i}
className="text-xs text-morandi-600 flex items-start gap-2"
>
<span className="w-1 h-1 bg-morandi-rose-400 rounded-full flex-shrink-0 mt-1.5"></span>
<span>{prep}</span>
</li>
))}
</ul>
</div>
)}
</div>
</motion.div>
)}
</AnimatePresence>
</div>
</div>
</Card>
</motion.div>
))
)}
</AnimatePresence>
</motion.div>
{/* 温馨提示 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.15 }}
>
<Card className="bg-morandi-50 border-morandi-100 rounded-2xl p-4">
<div className="flex items-start gap-2.5">
<Bell className="w-4 h-4 text-morandi-400 flex-shrink-0 mt-0.5" />
<div>
<h4 className="font-medium text-gray-700 text-sm mb-1">消息说明</h4>
<p className="text-xs text-gray-500 leading-relaxed">
系统会根据您的孕周和产检计划自动推送提醒,包括产检时间、检查项目和注意事项。产检内容与产检日历同步。
</p>
</div>
</div>
</Card>
</motion.div>
<div className="h-4" />
</div>
</div>
);
}

View File

@@ -0,0 +1,413 @@
import { useState } from "react";
import { useNavigate } from "react-router";
import { motion } from "motion/react";
import { ChevronUp, ChevronDown, Loader2 } from "lucide-react";
import { Input } from "../components/ui/input";
import { useUser, calcPregnancyWeek, calcDueDate } from "../context/UserContext";
import { submitOnboarding } from "../services/api";
type DateMode = "due_date" | "last_period";
type MultiplePregnancy = "单胎" | "双胎" | "三胎+";
type PregnancyCount = 1 | 2 | 3;
const MEDICAL_CONDITIONS = [
"糖尿病 / 妊娠糖尿病史",
"高血压 / 妊娠高血压史",
"甲状腺疾病",
];
export function OnboardingPage() {
const navigate = useNavigate();
const { updateUser } = useUser();
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState("");
// 基本信息
const [dateMode, setDateMode] = useState<DateMode>("due_date");
const [dueDate, setDueDate] = useState("");
const [lastPeriodDate, setLastPeriodDate] = useState("");
// 特殊情况
const [showSpecial, setShowSpecial] = useState(false);
const [age, setAge] = useState("");
const [multiplePregnancy, setMultiplePregnancy] = useState<MultiplePregnancy>("单胎");
const [medicalHistory, setMedicalHistory] = useState<string[]>([]);
const [noMedicalHistory, setNoMedicalHistory] = useState(false);
// 补充信息
const [showExtra, setShowExtra] = useState(false);
const [preWeight, setPreWeight] = useState("");
const [height, setHeight] = useState("");
const [pregnancyCount, setPregnancyCount] = useState<PregnancyCount>(1);
// 计算孕周和预产期(用于显示)
const computedInfo = (() => {
if (dateMode === "last_period" && lastPeriodDate) {
const { weeks, days } = calcPregnancyWeek(lastPeriodDate);
const due = calcDueDate(lastPeriodDate);
if (weeks >= 0 && weeks <= 42) {
return { weeks, days, dueDate: due, valid: true };
}
}
if (dateMode === "due_date" && dueDate) {
// 从预产期反推末次月经:预产期 - 280天
const dueDateObj = new Date(dueDate);
const lmpDate = new Date(dueDateObj.getTime() - 280 * 24 * 60 * 60 * 1000);
const lmpStr = lmpDate.toISOString().split("T")[0];
const { weeks, days } = calcPregnancyWeek(lmpStr);
if (weeks >= 0 && weeks <= 42) {
return { weeks, days, dueDate, lmpDate: lmpStr, valid: true };
}
}
return { weeks: 0, days: 0, dueDate: "", valid: false };
})();
const canSubmit = dateMode === "due_date" ? !!dueDate : !!lastPeriodDate;
const toggleMedicalCondition = (condition: string) => {
setNoMedicalHistory(false);
setMedicalHistory((prev) =>
prev.includes(condition) ? prev.filter((c) => c !== condition) : [...prev, condition]
);
};
const toggleNoMedicalHistory = () => {
setNoMedicalHistory(!noMedicalHistory);
if (!noMedicalHistory) {
setMedicalHistory([]);
}
};
const handleSubmit = async () => {
setError("");
setIsSubmitting(true);
try {
// 确定末次月经日期
let lmpDate = lastPeriodDate;
let dueDateStr = dueDate;
if (dateMode === "due_date" && dueDate) {
const dueDateObj = new Date(dueDate);
lmpDate = new Date(dueDateObj.getTime() - 280 * 24 * 60 * 60 * 1000).toISOString().split("T")[0];
dueDateStr = dueDate;
} else if (dateMode === "last_period" && lastPeriodDate) {
dueDateStr = calcDueDate(lastPeriodDate);
lmpDate = lastPeriodDate;
}
const { weeks, days } = calcPregnancyWeek(lmpDate);
const payload: Record<string, unknown> = {
last_period_date: lmpDate,
due_date: dueDateStr,
pregnancy_week: weeks,
pregnancy_day: days,
multiple_pregnancy: multiplePregnancy,
pregnancy_count: pregnancyCount,
};
if (age) payload.age = parseInt(age);
if (medicalHistory.length > 0) payload.medical_history = medicalHistory;
if (preWeight) payload.pre_pregnancy_weight = parseFloat(preWeight);
if (height) payload.height = parseFloat(height);
await submitOnboarding(payload as Parameters<typeof submitOnboarding>[0]);
updateUser({
lastPeriodDate: lmpDate,
dueDate: dueDateStr,
currentWeek: weeks,
currentDay: days,
age: age ? parseInt(age) : null,
prePregnancyWeight: preWeight ? parseFloat(preWeight) : null,
height: height ? parseFloat(height) : null,
medicalHistory,
isOnboarded: true,
});
navigate("/home");
} catch (err: unknown) {
const message = err instanceof Error ? err.message : "保存失败,请重试";
setError(message);
} finally {
setIsSubmitting(false);
}
};
return (
<div className="min-h-dvh bg-morandi-50">
<div className="px-4 pt-6 pb-32">
{/* 页面标题 */}
<h1 className="text-xl font-bold text-gray-800 mb-1">完善孕期信息</h1>
<p className="text-sm text-gray-400 mb-5">帮助我们更准确地解读您的报告</p>
{/* 基本信息 */}
<section className="mb-4 bg-white rounded-3xl shadow-sm p-5">
<h2 className="text-base font-semibold text-gray-800 mb-4">
基本信息 <span className="text-red-400">*</span>
</h2>
{/* 日期方式切换 */}
<p className="text-sm text-gray-500 mb-2">请选择一种方式</p>
<div className="flex gap-3 mb-4">
<button
onClick={() => setDateMode("due_date")}
className={`flex-1 h-11 rounded-full border-2 text-sm font-medium transition-all ${
dateMode === "due_date"
? "border-morandi-300 text-morandi-500 bg-morandi-50"
: "border-gray-200 text-gray-500 hover:border-gray-300"
}`}
>
我知道预产期
</button>
<button
onClick={() => setDateMode("last_period")}
className={`flex-1 h-11 rounded-full border-2 text-sm font-medium transition-all ${
dateMode === "last_period"
? "border-morandi-300 text-morandi-500 bg-morandi-50"
: "border-gray-200 text-gray-500 hover:border-gray-300"
}`}
>
我知道末次月经
</button>
</div>
{/* 日期输入 */}
{dateMode === "due_date" ? (
<div>
<p className="text-sm text-gray-600 mb-2">预产期</p>
<Input
type="date"
value={dueDate}
onChange={(e) => setDueDate(e.target.value)}
className="h-12 rounded-xl border-2 border-gray-200 focus:border-morandi-200 bg-white"
/>
</div>
) : (
<div>
<p className="text-sm text-gray-600 mb-2">末次月经日期</p>
<Input
type="date"
value={lastPeriodDate}
onChange={(e) => setLastPeriodDate(e.target.value)}
className="h-12 rounded-xl border-2 border-gray-200 focus:border-morandi-200 bg-white"
/>
</div>
)}
{/* 孕周计算结果 */}
{computedInfo.valid && (
<motion.div
initial={{ opacity: 0, y: -8 }}
animate={{ opacity: 1, y: 0 }}
className="mt-3 p-3 bg-morandi-50 rounded-xl"
>
<p className="text-sm text-morandi-400">
当前孕 <span className="font-semibold">{computedInfo.weeks}</span> 周{" "}
<span className="font-semibold">{computedInfo.days}</span> 天
{dateMode === "last_period" && computedInfo.dueDate && (
<span className="ml-2">
· 预产期 {new Date(computedInfo.dueDate).toLocaleDateString("zh-CN")}
</span>
)}
</p>
</motion.div>
)}
</section>
{/* 特殊情况(选填) */}
<section className="mb-4 bg-white rounded-3xl shadow-sm p-5">
<button
onClick={() => setShowSpecial(!showSpecial)}
className={`flex items-center justify-between w-full ${showSpecial ? "mb-4" : ""}`}
>
<h2 className="text-base font-semibold text-gray-800">特殊情况(选填)</h2>
<span className="flex items-center text-xs text-gray-400">
影响解读准确性
{showSpecial ? (
<ChevronUp className="w-4 h-4 ml-1" />
) : (
<ChevronDown className="w-4 h-4 ml-1" />
)}
</span>
</button>
{showSpecial && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
className="space-y-5"
>
{/* 年龄 */}
<div>
<p className="text-sm text-gray-600 mb-2">年龄</p>
<Input
type="number"
placeholder="请输入年龄"
value={age}
onChange={(e) => setAge(e.target.value)}
className="h-12 rounded-xl border-2 border-gray-200 focus:border-morandi-200 bg-white"
/>
<p className="text-xs text-amber-500 mt-2 flex items-start">
<span className="mr-1">💡</span>
35岁以上属于高龄孕妇,某些指标的风险评估会不同
</p>
</div>
{/* 多胎妊娠 */}
<div>
<p className="text-sm text-gray-600 mb-2">是否多胎妊娠?</p>
<div className="flex gap-3">
{(["单胎", "双胎", "三胎+"] as MultiplePregnancy[]).map((opt) => (
<button
key={opt}
onClick={() => setMultiplePregnancy(opt)}
className={`flex-1 h-11 rounded-full border-2 text-sm font-medium transition-all ${
multiplePregnancy === opt
? "border-morandi-300 text-morandi-500 bg-morandi-50"
: "border-gray-200 text-gray-500 hover:border-gray-300"
}`}
>
{opt}
</button>
))}
</div>
</div>
{/* 疾病史 */}
<div>
<p className="text-sm text-gray-600 mb-2">是否有以下疾病史?(可多选)</p>
<div className="space-y-2">
{MEDICAL_CONDITIONS.map((condition) => (
<button
key={condition}
onClick={() => toggleMedicalCondition(condition)}
className={`w-full h-12 px-4 rounded-xl border-2 text-left text-sm font-medium transition-all ${
medicalHistory.includes(condition)
? "border-morandi-300 text-morandi-500 bg-morandi-50"
: "border-gray-200 text-gray-600 hover:border-gray-300 bg-white"
}`}
>
{condition}
</button>
))}
<button
onClick={toggleNoMedicalHistory}
className={`w-full h-12 px-4 rounded-xl border-2 text-left text-sm font-medium transition-all ${
noMedicalHistory
? "border-morandi-300 text-morandi-500 bg-morandi-50"
: "border-gray-200 text-gray-600 hover:border-gray-300 bg-white"
}`}
>
以上都没有 ✓
</button>
</div>
</div>
</motion.div>
)}
</section>
{/* 补充信息(选填) */}
<section className="mb-4 bg-white rounded-3xl shadow-sm p-5">
<button
onClick={() => setShowExtra(!showExtra)}
className={`flex items-center justify-between w-full ${showExtra ? "mb-4" : ""}`}
>
<h2 className="text-base font-semibold text-gray-800">补充信息(选填)</h2>
<span className="flex items-center text-xs text-gray-400">
用于BMI计算
{showExtra ? (
<ChevronUp className="w-4 h-4 ml-1" />
) : (
<ChevronDown className="w-4 h-4 ml-1" />
)}
</span>
</button>
{showExtra && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
className="space-y-5"
>
{/* 孕前体重 */}
<div>
<p className="text-sm text-gray-600 mb-2">孕前体重 (kg)</p>
<Input
type="number"
placeholder="请输入"
value={preWeight}
onChange={(e) => setPreWeight(e.target.value)}
className="h-12 rounded-xl border-2 border-gray-200 focus:border-morandi-200 bg-white"
/>
</div>
{/* 身高 */}
<div>
<p className="text-sm text-gray-600 mb-2">身高 (cm)</p>
<Input
type="number"
placeholder="请输入"
value={height}
onChange={(e) => setHeight(e.target.value)}
className="h-12 rounded-xl border-2 border-gray-200 focus:border-morandi-200 bg-white"
/>
</div>
{/* 第几次怀孕 */}
<div>
<p className="text-sm text-gray-600 mb-2">第几次怀孕</p>
<div className="flex gap-3">
{([1, 2, 3] as PregnancyCount[]).map((count) => (
<button
key={count}
onClick={() => setPregnancyCount(count)}
className={`flex-1 h-11 rounded-full border-2 text-sm font-medium transition-all ${
pregnancyCount === count
? "border-morandi-300 text-morandi-500 bg-morandi-50"
: "border-gray-200 text-gray-500 hover:border-gray-300"
}`}
>
{count === 3 ? "第3次+" : `第${count}次`}
</button>
))}
</div>
</div>
</motion.div>
)}
</section>
</div>
{/* 错误提示 */}
{error && (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="fixed bottom-24 left-4 right-4 mx-auto"
>
<p className="text-sm text-red-500 bg-red-50 px-4 py-3 rounded-xl text-center">
{error}
</p>
</motion.div>
)}
{/* 底部按钮 */}
<div className="fixed bottom-0 left-0 right-0 bg-white/80 backdrop-blur-sm border-t border-gray-100 px-4 py-4 pb-safe z-10">
<div className="max-w-md mx-auto">
<button
onClick={handleSubmit}
disabled={!canSubmit || isSubmitting}
className="w-full h-12 rounded-full bg-gradient-to-r from-morandi-400 to-morandi-500 text-white font-semibold text-base shadow-lg disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center"
>
{isSubmitting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
保存中...
</>
) : (
"完成建档"
)}
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,473 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router";
import { motion } from "motion/react";
import {
ChevronLeft,
User,
Calendar,
Heart,
Phone,
Mail,
MapPin,
Edit2,
Check,
X,
Camera,
Baby,
Activity,
AlertCircle,
Shield,
Bell,
LogOut,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Card } from "../components/ui/card";
import { Badge } from "../components/ui/badge";
import { useUser, getPregnancyStage } from "../context/UserContext";
interface UserInfo {
name: string;
age: number;
phone: string;
email: string;
address: string;
lastPeriod: string;
dueDate: string;
currentWeek: number;
currentDay: number;
height: number;
prePregnancyWeight: number;
currentWeight: number;
bloodType: string;
allergies: string[];
medicalHistory: string[];
emergencyContact: {
name: string;
relation: string;
phone: string;
};
}
export function ProfilePage() {
const navigate = useNavigate();
const { user, updateUserRemote, logout } = useUser();
const [isEditing, setIsEditing] = useState<string | null>(null);
const [userInfo, setUserInfo] = useState<UserInfo>({
name: user.name || "未设置",
age: user.age || 0,
phone: user.phone || "未设置",
email: "",
address: "",
lastPeriod: user.lastPeriodDate || "",
dueDate: user.dueDate || "",
currentWeek: user.currentWeek,
currentDay: user.currentDay,
height: user.height || 0,
prePregnancyWeight: user.prePregnancyWeight || 0,
currentWeight: user.currentWeight || 0,
bloodType: user.bloodType || "未设置",
allergies: user.allergies.length ? user.allergies : ["无"],
medicalHistory: user.medicalHistory.length ? user.medicalHistory : ["无重大病史"],
emergencyContact: {
name: user.emergencyContact.name || "未设置",
relation: user.emergencyContact.relation || "",
phone: user.emergencyContact.phone || "",
},
});
const [editValues, setEditValues] = useState<Partial<UserInfo>>({});
const handleEdit = (field: string) => {
setIsEditing(field);
setEditValues({ [field]: (userInfo as any)[field] });
};
const handleSave = (field: string) => {
const updated = { ...userInfo, ...(editValues as any) };
setUserInfo(updated);
setIsEditing(null);
setEditValues({});
// Sync back to global context + backend
updateUserRemote({
name: updated.name,
age: updated.age,
phone: updated.phone,
lastPeriodDate: updated.lastPeriod,
height: updated.height,
prePregnancyWeight: updated.prePregnancyWeight,
currentWeight: updated.currentWeight,
bloodType: updated.bloodType,
allergies: updated.allergies,
medicalHistory: updated.medicalHistory,
emergencyContact: updated.emergencyContact,
});
};
const handleCancel = () => {
setIsEditing(null);
setEditValues({});
};
const calculateBMI = () => {
const heightInMeters = userInfo.height / 100;
const bmi = userInfo.currentWeight / (heightInMeters * heightInMeters);
return bmi.toFixed(1);
};
const calculateWeightGain = () => {
return (userInfo.currentWeight - userInfo.prePregnancyWeight).toFixed(1);
};
const InfoItem = ({
label,
value,
field,
editable = true,
type = "text",
icon: Icon,
}: {
label: string;
value: string | number;
field: string;
editable?: boolean;
type?: string;
icon?: any;
}) => (
<div className="flex items-center justify-between py-3 border-b border-gray-100 last:border-0">
<div className="flex items-center gap-3">
{Icon && (
<div className="w-8 h-8 bg-morandi-100 rounded-lg flex items-center justify-center">
<Icon className="w-4 h-4 text-morandi-500" />
</div>
)}
<div>
<div className="text-sm text-gray-500">{label}</div>
{isEditing === field ? (
<input
type={type}
value={(editValues as any)[field] ?? value}
onChange={(e) =>
setEditValues({ ...editValues, [field]: e.target.value })
}
className="mt-1 px-2 py-1 border border-morandi-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-morandi-500"
autoFocus
/>
) : (
<div className="font-semibold text-gray-800">{value}</div>
)}
</div>
</div>
{editable && (
<div className="flex items-center gap-2">
{isEditing === field ? (
<>
<button
onClick={() => handleSave(field)}
className="w-8 h-8 bg-morandi-sage-100 rounded-full flex items-center justify-center hover:bg-morandi-sage-200"
>
<Check className="w-4 h-4 text-morandi-sage-500" />
</button>
<button
onClick={handleCancel}
className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center hover:bg-gray-200"
>
<X className="w-4 h-4 text-gray-600" />
</button>
</>
) : (
<button
onClick={() => handleEdit(field)}
className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center hover:bg-gray-200"
>
<Edit2 className="w-4 h-4 text-gray-600" />
</button>
)}
</div>
)}
</div>
);
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => navigate(-1)}
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<ChevronLeft className="w-6 h-6 text-gray-600" />
</button>
<div>
<h1 className="font-semibold text-gray-800">个人中心</h1>
<p className="text-xs text-gray-500">管理您的个人信息</p>
</div>
</div>
</div>
</div>
<div className="mx-auto p-4 space-y-6">
{/* 个人头像卡片 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
>
<Card className="bg-gradient-to-br from-morandi-400 to-morandi-500 border-0 text-white p-6 rounded-3xl shadow-sm">
<div className="flex items-center gap-4">
<div className="relative">
<div className="w-20 h-20 bg-white/20 backdrop-blur-sm rounded-full flex items-center justify-center">
<User className="w-10 h-10 text-white" />
</div>
<button className="absolute bottom-0 right-0 w-6 h-6 bg-white rounded-full flex items-center justify-center shadow-sm">
<Camera className="w-3 h-3 text-morandi-500" />
</button>
</div>
<div className="flex-1">
<h2 className="text-2xl font-semibold mb-1">{userInfo.name}</h2>
<p className="text-white/90 text-sm">
{userInfo.age}岁 · {userInfo.bloodType}
</p>
<p className="text-white/80 text-sm mt-1">
孕{userInfo.currentWeek}周+{userInfo.currentDay}天
</p>
</div>
</div>
</Card>
</motion.div>
{/* 孕期信息 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
>
<h2 className="text-base font-semibold text-gray-800 mb-3 flex items-center gap-2">
<Baby className="w-5 h-5 text-morandi-500" />
孕期信息
</h2>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
<InfoItem
label="末次月经"
value={userInfo.lastPeriod}
field="lastPeriod"
type="date"
icon={Calendar}
/>
<InfoItem
label="预产期"
value={userInfo.dueDate}
field="dueDate"
type="date"
icon={Heart}
/>
<div className="flex items-center justify-between py-3">
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-morandi-100 rounded-lg flex items-center justify-center">
<Activity className="w-4 h-4 text-morandi-500" />
</div>
<div>
<div className="text-sm text-gray-500">当前孕周</div>
<div className="font-semibold text-gray-800">
{userInfo.currentWeek}周+{userInfo.currentDay}天
</div>
</div>
</div>
<Badge className="bg-morandi-100 text-morandi-500 hover:bg-morandi-100">
{getPregnancyStage(userInfo.currentWeek)}
</Badge>
</div>
</Card>
</motion.div>
{/* 健康数据 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
>
<h2 className="text-base font-semibold text-gray-800 mb-3 flex items-center gap-2">
<Activity className="w-5 h-5 text-morandi-slate-500" />
健康数据
</h2>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
<InfoItem
label="身高"
value={`${userInfo.height} cm`}
field="height"
type="number"
/>
<InfoItem
label="孕前体重"
value={`${userInfo.prePregnancyWeight} kg`}
field="prePregnancyWeight"
type="number"
/>
<InfoItem
label="当前体重"
value={`${userInfo.currentWeight} kg`}
field="currentWeight"
type="number"
/>
<div className="grid grid-cols-2 gap-4 mt-4 pt-4 border-t border-gray-100">
<div className="bg-morandi-slate-50 rounded-xl p-3">
<div className="text-xs text-morandi-slate-500 mb-1">当前BMI</div>
<div className="text-2xl font-semibold text-morandi-500">
{calculateBMI()}
</div>
<div className="text-xs text-morandi-slate-500 mt-1">正常范围</div>
</div>
<div className="bg-morandi-sage-100 rounded-xl p-3">
<div className="text-xs text-morandi-sage-500 mb-1">体重增长</div>
<div className="text-2xl font-semibold text-morandi-sage-600">
+{calculateWeightGain()} kg
</div>
<div className="text-xs text-morandi-sage-500 mt-1">符合预期</div>
</div>
</div>
</Card>
</motion.div>
{/* 联系方式 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
>
<h2 className="text-base font-semibold text-gray-800 mb-3 flex items-center gap-2">
<Phone className="w-5 h-5 text-morandi-600" />
联系方式
</h2>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
<InfoItem
label="手机号"
value={userInfo.phone}
field="phone"
icon={Phone}
/>
<InfoItem
label="邮箱"
value={userInfo.email}
field="email"
icon={Mail}
/>
<InfoItem
label="居住地"
value={userInfo.address}
field="address"
icon={MapPin}
/>
</Card>
</motion.div>
{/* 医疗信息 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.4 }}
>
<h2 className="text-base font-semibold text-gray-800 mb-3 flex items-center gap-2">
<AlertCircle className="w-5 h-5 text-red-600" />
医疗信息
</h2>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
<div className="space-y-4">
<div>
<div className="text-sm text-gray-500 mb-2">血型</div>
<Badge className="bg-red-100 text-red-700 hover:bg-red-100">
{userInfo.bloodType}
</Badge>
</div>
<div>
<div className="text-sm text-gray-500 mb-2">药物过敏史</div>
<div className="flex flex-wrap gap-2">
{userInfo.allergies.map((allergy, index) => (
<Badge
key={index}
className="bg-morandi-rose-100 text-morandi-rose-400 hover:bg-morandi-rose-100"
>
{allergy}
</Badge>
))}
<button className="px-3 py-1 border border-dashed border-gray-300 rounded-full text-sm text-gray-500 hover:border-morandi-200 hover:text-morandi-500">
+ 添加
</button>
</div>
</div>
<div>
<div className="text-sm text-gray-500 mb-2">既往病史</div>
<div className="flex flex-wrap gap-2">
{userInfo.medicalHistory.map((history, index) => (
<Badge
key={index}
className="bg-morandi-50 text-morandi-500 hover:bg-morandi-50"
>
{history}
</Badge>
))}
<button className="px-3 py-1 border border-dashed border-gray-300 rounded-full text-sm text-gray-500 hover:border-morandi-200 hover:text-morandi-500">
+ 添加
</button>
</div>
</div>
</div>
</Card>
</motion.div>
{/* 紧急联系人 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.5 }}
>
<h2 className="text-base font-semibold text-gray-800 mb-3 flex items-center gap-2">
<Shield className="w-5 h-5 text-morandi-sage-500" />
紧急联系人
</h2>
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
<div className="space-y-3">
<div className="flex items-center justify-between">
<div>
<div className="text-sm text-gray-500">姓名</div>
<div className="font-semibold text-gray-800">
{userInfo.emergencyContact.name}
</div>
</div>
<Badge className="bg-morandi-sage-100 text-morandi-sage-600 hover:bg-morandi-sage-100">
{userInfo.emergencyContact.relation}
</Badge>
</div>
<div>
<div className="text-sm text-gray-500">联系电话</div>
<div className="font-semibold text-gray-800">
{userInfo.emergencyContact.phone}
</div>
</div>
</div>
</Card>
</motion.div>
{/* 退出登录 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.7 }}
>
<Button
onClick={() => {
logout();
navigate("/");
}}
variant="outline"
className="w-full border-red-200 text-red-600 hover:bg-red-50 hover:text-red-700 hover:border-red-300 rounded-2xl py-6"
>
<LogOut className="w-5 h-5 mr-2" />
退出登录
</Button>
</motion.div>
<div className="h-8"></div>
</div>
</div>
);
}

View File

@@ -0,0 +1,276 @@
import { useNavigate, useParams } from "react-router";
import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "motion/react";
import {
ChevronLeft,
Calendar,
FileText,
Download,
CheckCircle2,
X,
Heart,
Loader2,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Card } from "../components/ui/card";
import { getReport, type ReportResponse } from "../services/api";
export function ReportDetailPage() {
const navigate = useNavigate();
const { reportId } = useParams();
const [showDownloadSheet, setShowDownloadSheet] = useState(false);
const [isDownloading, setIsDownloading] = useState(false);
const [downloadDone, setDownloadDone] = useState(false);
const [report, setReport] = useState<ReportResponse | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!reportId) return;
getReport(reportId)
.then(setReport)
.catch(() => {})
.finally(() => setLoading(false));
}, [reportId]);
const handleDownload = async () => {
if (!report?.image_urls || report.image_urls.length === 0) return;
setIsDownloading(true);
try {
// 下载所有报告图片
for (let i = 0; i < report.image_urls.length; i++) {
const imageUrl = report.image_urls[i];
// 获取图片数据
const response = await fetch(imageUrl);
const blob = await response.blob();
// 创建下载链接
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${report.report_type || '报告'}_${report.created_at?.slice(0, 10) || ''}_${i + 1}.jpg`;
// 触发下载
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// 释放 URL 对象
window.URL.revokeObjectURL(url);
// 多张图片时添加延迟,避免浏览器阻止
if (i < report.image_urls.length - 1) {
await new Promise(resolve => setTimeout(resolve, 300));
}
}
setIsDownloading(false);
setDownloadDone(true);
setTimeout(() => {
setDownloadDone(false);
setShowDownloadSheet(false);
}, 2000);
} catch (error) {
console.error('下载失败:', error);
setIsDownloading(false);
alert('下载失败,请稍后重试');
}
};
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-20">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<button
onClick={() => navigate(-1)}
className="flex items-center text-gray-600 hover:text-gray-900"
>
<ChevronLeft className="w-5 h-5 mr-1" />
返回
</button>
<h1 className="font-semibold text-gray-800">原始报告</h1>
<div className="w-5" />
</div>
</div>
<div className="mx-auto p-4 space-y-6">
{loading ? (
<div className="flex items-center justify-center py-20">
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin" />
</div>
) : !report ? (
<div className="text-center py-20 text-gray-400">报告不存在</div>
) : (
<>
{/* 报告信息 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
>
<Card className="bg-white rounded-3xl shadow-sm p-6">
<div className="flex items-start gap-4">
<div className="w-12 h-12 bg-morandi-100 rounded-2xl flex items-center justify-center">
<FileText className="w-6 h-6 text-morandi-400" />
</div>
<div className="flex-1">
<h2 className="font-semibold text-gray-800 mb-1">
{report.report_type || "检查报告"}
</h2>
<div className="flex items-center gap-3 text-sm text-gray-600">
<div className="flex items-center gap-1">
<Calendar className="w-4 h-4" />
<span>{report.created_at?.slice(0, 10)}</span>
</div>
{report.pregnancy_week && (
<>
<span>·</span>
<span>孕 {report.pregnancy_week}周</span>
</>
)}
</div>
</div>
</div>
</Card>
</motion.div>
{/* 报告图片 */}
{report.image_urls.map((url, idx) => (
<motion.div
key={idx}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 * (idx + 1) }}
>
<Card className="bg-white rounded-3xl shadow-sm overflow-hidden">
<div className="relative">
<img
src={url}
alt={`报告图片 ${idx + 1}`}
className="w-full"
style={{ pointerEvents: 'auto' }}
/>
{/* 长按保存提示 */}
<div className="absolute top-3 left-3 bg-morandi-400/90 backdrop-blur-sm rounded-lg px-3 py-1.5 flex items-center gap-1.5 pointer-events-none">
<Download className="w-3 h-3 text-white" />
<span className="text-xs text-white font-medium">长按图片保存到相册</span>
</div>
{/* 平台水印 */}
<div className="absolute bottom-3 right-3 bg-white/60 backdrop-blur-sm rounded-lg px-2.5 py-1 flex items-center gap-1.5 pointer-events-none">
<Heart className="w-3 h-3 text-morandi-400 fill-morandi-400" />
<span className="text-xs text-morandi-500 font-medium">孕育无忧</span>
</div>
</div>
</Card>
</motion.div>
))}
{/* 提示信息 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
>
<Card className="bg-morandi-50 border border-morandi-200 rounded-2xl p-4">
<div className="flex items-start gap-2">
<Download className="w-4 h-4 text-morandi-400 flex-shrink-0 mt-0.5" />
<div className="text-xs text-gray-600">
<p className="font-medium text-morandi-600 mb-1">保存到相册</p>
<p>长按图片 → 选择"保存图片" → 图片将保存到手机相册</p>
</div>
</div>
</Card>
</motion.div>
</>
)}
</div>
{/* 下载弹窗 */}
<AnimatePresence>
{showDownloadSheet && (
<>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={() => setShowDownloadSheet(false)}
className="fixed inset-0 bg-black/40 z-40"
/>
<motion.div
initial={{ y: "100%" }}
animate={{ y: 0 }}
exit={{ y: "100%" }}
transition={{ type: "spring", damping: 25, stiffness: 300 }}
className="fixed bottom-0 left-0 right-0 bg-white rounded-t-3xl z-50"
>
<div className="mx-auto p-5">
<div className="w-10 h-1 bg-gray-200 rounded-full mx-auto mb-4" />
<div className="flex items-center justify-between mb-5">
<h3 className="font-semibold text-gray-800 text-lg">下载报告</h3>
<button
onClick={() => setShowDownloadSheet(false)}
className="w-8 h-8 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<X className="w-5 h-5 text-gray-400" />
</button>
</div>
{/* 下载预览 */}
<Card className="bg-morandi-50 border-morandi-100 rounded-2xl p-4 mb-4">
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-xl flex items-center justify-center flex-shrink-0">
<FileText className="w-6 h-6 text-white" />
</div>
<div className="flex-1 min-w-0">
<h4 className="font-medium text-gray-800 text-sm">{report?.report_type || "检查报告"}</h4>
<p className="text-xs text-gray-500 mt-0.5">{report?.created_at?.slice(0, 10)}{report?.pregnancy_week ? ` · 孕${report.pregnancy_week}周` : ""}</p>
</div>
<div className="flex items-center gap-1 bg-white rounded-lg px-2 py-1">
<Heart className="w-3 h-3 text-morandi-400 fill-morandi-400" />
<span className="text-xs text-morandi-500 font-medium">孕育无忧</span>
</div>
</div>
</Card>
<p className="text-xs text-gray-400 mb-4">
💡 移动端保存方法:长按图片选择"保存图片"即可保存到相册
</p>
{/* 下载按钮 */}
<Button
onClick={handleDownload}
disabled={isDownloading}
className="w-full h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white mb-3"
>
{isDownloading ? (
<>
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2" />
下载中...
</>
) : downloadDone ? (
<>
<CheckCircle2 className="w-4 h-4 mr-2" />
已下载
</>
) : (
<>
<Download className="w-4 h-4 mr-2" />
下载到本地(电脑端)
</>
)}
</Button>
<p className="text-xs text-center text-gray-400">
或直接长按上方图片保存
</p>
</div>
</motion.div>
</>
)}
</AnimatePresence>
</div>
);
}

View File

@@ -0,0 +1,574 @@
import { useState, useEffect, useRef, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import { motion, AnimatePresence } from "motion/react";
import {
ChevronLeft,
Share2,
CheckCircle2,
AlertCircle,
Info,
Loader2,
Heart,
Baby,
TrendingUp,
Download,
Check,
Image as ImageIcon,
} from "lucide-react";
import { toPng } from "html-to-image";
import { Card } from "../components/ui/card";
import { Badge } from "../components/ui/badge";
import { Button } from "../components/ui/button";
import { generateShareData } from "../services/api";
type SaveStatus = "idle" | "generating" | "success" | "error";
export function SharePage() {
const navigate = useNavigate();
const { reportId } = useParams();
const [loading, setLoading] = useState(true);
const [shareData, setShareData] = useState<any>(null);
const [saveStatus, setSaveStatus] = useState<SaveStatus>("idle");
const [imageUrl, setImageUrl] = useState<string | null>(null);
const cardRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!reportId) return;
generateShareData(reportId)
.then((data) => {
setShareData(data.share_data);
})
.catch(() => {/* keep null */})
.finally(() => setLoading(false));
}, [reportId]);
// 生成长图
const generateImage = useCallback(async (): Promise<string | null> => {
if (!cardRef.current) return null;
try {
// html-to-image: 将 DOM 节点转为 PNG data URL
const dataUrl = await toPng(cardRef.current, {
cacheBust: true,
pixelRatio: 2, // 2x 高清
backgroundColor: "#ffffff",
style: {
// 确保截图时移除圆角阴影的裁切问题
borderRadius: "0",
},
});
return dataUrl;
} catch (err) {
console.error("生成图片失败:", err);
return null;
}
}, []);
// 一键保存到相册 / 下载
const handleSaveImage = useCallback(async () => {
setSaveStatus("generating");
try {
const dataUrl = imageUrl || (await generateImage());
if (!dataUrl) {
setSaveStatus("error");
setTimeout(() => setSaveStatus("idle"), 2000);
return;
}
if (!imageUrl) setImageUrl(dataUrl);
// 尝试使用 Web Share API(移动端可直接分享/保存到相册)
if (navigator.share && navigator.canShare) {
try {
const response = await fetch(dataUrl);
const blob = await response.blob();
const file = new File([blob], `孕育无忧-报告解读-${reportId}.png`, {
type: "image/png",
});
if (navigator.canShare({ files: [file] })) {
await navigator.share({
files: [file],
title: "孕育无忧 · AI 报告解读",
});
setSaveStatus("success");
setTimeout(() => setSaveStatus("idle"), 3000);
return;
}
} catch (shareErr) {
// 用户取消分享或不支持,降级到下载
if ((shareErr as Error).name === "AbortError") {
setSaveStatus("idle");
return;
}
}
}
// 降级方案:触发下载(iOS Safari / Android 浏览器)
const link = document.createElement("a");
link.download = `孕育无忧-报告解读-${reportId}.png`;
link.href = dataUrl;
link.style.display = "none";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
setSaveStatus("success");
setTimeout(() => setSaveStatus("idle"), 3000);
} catch (err) {
console.error("保存失败:", err);
setSaveStatus("error");
setTimeout(() => setSaveStatus("idle"), 2000);
}
}, [imageUrl, generateImage, reportId]);
// 预览:在页面加载数据后自动生成图片预览
useEffect(() => {
if (shareData && cardRef.current && !imageUrl) {
// 延迟一帧确保 DOM 渲染完毕
const timer = setTimeout(async () => {
const url = await generateImage();
if (url) setImageUrl(url);
}, 500);
return () => clearTimeout(timer);
}
}, [shareData, generateImage, imageUrl]);
if (loading || !shareData) {
return (
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
<div className="text-center">
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin mx-auto mb-3" />
<p className="text-sm text-gray-500">正在准备分享内容...</p>
</div>
</div>
);
}
const getStatusColor = (status: string) => {
switch (status) {
case "normal":
return {
bg: "bg-morandi-sage-100",
text: "text-morandi-sage-600",
icon: "text-morandi-sage-400",
};
case "attention":
return {
bg: "bg-morandi-rose-100",
text: "text-morandi-600",
icon: "text-morandi-rose-400",
};
default:
return {
bg: "bg-gray-100",
text: "text-gray-600",
icon: "text-gray-400",
};
}
};
const statusColors = getStatusColor(shareData.overall_status);
const getSaveButtonContent = () => {
switch (saveStatus) {
case "generating":
return (
<>
<Loader2 className="w-5 h-5 animate-spin" />
<span>正在生成图片...</span>
</>
);
case "success":
return (
<>
<Check className="w-5 h-5" />
<span>已保存到相册</span>
</>
);
case "error":
return (
<>
<AlertCircle className="w-5 h-5" />
<span>保存失败,请重试</span>
</>
);
default:
return (
<>
<Download className="w-5 h-5" />
<span>保存图片到相册</span>
</>
);
}
};
return (
<div className="min-h-dvh bg-morandi-50 pb-28">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => navigate(-1)}
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<ChevronLeft className="w-6 h-6 text-gray-600" />
</button>
<div className="flex items-center gap-2">
<div className="w-10 h-10 bg-morandi-400 rounded-full flex items-center justify-center">
<Share2 className="w-5 h-5 text-white" />
</div>
<div>
<h1 className="font-semibold text-gray-800">分享长图</h1>
<p className="text-xs text-gray-500">生成精美报告长图</p>
</div>
</div>
</div>
</div>
</div>
<div className="mx-auto p-4 space-y-5">
{/* 图片预览区域 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
>
{/* 如果已经生成了图片,直接展示图片(可长按保存) */}
{imageUrl ? (
<div className="relative">
<img
src={imageUrl}
alt="分享长图"
className="w-full rounded-3xl shadow-lg"
style={{ userSelect: "none" }}
/>
{/* 长按提示覆盖层 */}
<div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/30 to-transparent rounded-b-3xl px-4 py-3">
<p className="text-white text-xs text-center opacity-80">
💡 长按图片也可直接保存
</p>
</div>
</div>
) : (
<div className="flex items-center justify-center py-16 bg-white rounded-3xl shadow-lg">
<div className="text-center">
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin mx-auto mb-3" />
<p className="text-sm text-gray-500">正在生成长图预览...</p>
</div>
</div>
)}
</motion.div>
{/* 隐藏的 HTML 卡片(用于截图,不展示给用户) */}
<div
style={{
position: "absolute",
left: "-9999px",
top: 0,
width: "375px", // 固定 iPhone 宽度,保证截图一致
}}
>
<div ref={cardRef} style={{ background: "#ffffff", padding: "0" }}>
<ShareCardContent shareData={shareData} getStatusColor={getStatusColor} statusColors={statusColors} />
</div>
</div>
{/* 操作提示 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
>
<Card className="bg-morandi-50 border-morandi-200 rounded-2xl p-4">
<div className="flex items-start gap-3">
<Info className="w-5 h-5 text-morandi-400 flex-shrink-0 mt-0.5" />
<div>
<h4 className="font-semibold text-gray-800 text-sm mb-2">💡 分享说明</h4>
<div className="space-y-1.5">
<p className="text-xs text-gray-600 leading-relaxed">
• 点击下方按钮,一键保存图片到手机相册
</p>
<p className="text-xs text-gray-600 leading-relaxed">
• 也可以长按上方图片直接保存
</p>
<p className="text-xs text-gray-600 leading-relaxed">
• 个人信息已自动脱敏处理,保护您的隐私
</p>
</div>
</div>
</div>
</Card>
</motion.div>
</div>
{/* 底部固定操作栏 */}
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 pb-safe z-10">
<div className="max-w-md mx-auto">
<Button
onClick={handleSaveImage}
disabled={saveStatus === "generating"}
className={`w-full h-14 rounded-2xl text-base font-semibold flex items-center justify-center gap-2 transition-all ${
saveStatus === "success"
? "bg-morandi-sage-400 hover:bg-morandi-sage-500 text-white"
: saveStatus === "error"
? "bg-red-400 hover:bg-red-500 text-white"
: "bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-600 text-white shadow-lg shadow-morandi-300/30"
}`}
>
{getSaveButtonContent()}
</Button>
<p className="text-center text-xs text-gray-400 mt-2">
图片将保存到您的手机相册中
</p>
</div>
</div>
</div>
);
}
/**
* 分享卡片内容组件(纯 HTML/CSS,不使用 motion 动画,用于截图)
* 独立提取,确保截图时样式完整、无动画干扰
*/
function ShareCardContent({
shareData,
getStatusColor,
statusColors,
}: {
shareData: any;
getStatusColor: (status: string) => { bg: string; text: string; icon: string };
statusColors: { bg: string; text: string; icon: string };
}) {
return (
<div style={{ background: "#ffffff", fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif" }}>
<div style={{ padding: "24px", display: "flex", flexDirection: "column", gap: "20px" }}>
{/* 标题区 */}
<div style={{ textAlign: "center", paddingBottom: "20px", borderBottom: "2px solid #f3f4f6" }}>
<div
style={{
display: "inline-flex",
alignItems: "center",
gap: "8px",
padding: "8px 16px",
background: "linear-gradient(135deg, #b8a9c9, #9d8ab5)",
color: "white",
borderRadius: "9999px",
fontSize: "14px",
fontWeight: 600,
marginBottom: "16px",
}}
>
<Heart style={{ width: 16, height: 16, fill: "white", color: "white" }} />
<span>孕育无忧 · AI 智能解读</span>
</div>
<h2
style={{
fontSize: "24px",
fontWeight: 700,
color: "#1f2937",
marginBottom: "8px",
marginTop: "0",
}}
>
{shareData.report_type}
</h2>
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: "12px", fontSize: "14px", color: "#6b7280" }}>
{shareData.pregnancy_week && <span>孕 {shareData.pregnancy_week} 周</span>}
{shareData.user_name && (
<>
<span>·</span>
<span>{shareData.user_name}</span>
</>
)}
</div>
</div>
{/* 整体评估 */}
<div className={`${statusColors.bg} rounded-2xl p-5`}>
<div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "12px" }}>
<div
style={{
width: 48,
height: 48,
background: "rgba(255,255,255,0.5)",
borderRadius: "12px",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Baby className={`w-6 h-6 ${statusColors.icon}`} />
</div>
<div style={{ flex: 1 }}>
<h3 style={{ fontWeight: 700, color: "#1f2937", fontSize: "18px", margin: 0 }}>
整体评估
</h3>
<Badge className={`${statusColors.bg} ${statusColors.text} mt-1`}>
{shareData.overall_status === "normal" ? "一切正常" : "需要关注"}
</Badge>
</div>
</div>
<p className={`text-sm ${statusColors.text} leading-relaxed`} style={{ margin: 0 }}>
{shareData.emotional_summary || shareData.overall_summary}
</p>
</div>
{/* 详细指标 */}
{shareData.categories && shareData.categories.length > 0 && (
<div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
<h3 style={{ fontWeight: 700, color: "#1f2937", fontSize: "18px", display: "flex", alignItems: "center", gap: "8px", margin: 0 }}>
<TrendingUp className="w-5 h-5 text-morandi-400" />
详细指标
</h3>
{shareData.categories.map((category: any, idx: number) => {
const catColors = getStatusColor(category.status);
return (
<div key={idx} className={`${catColors.bg} rounded-2xl p-4`}>
<div style={{ display: "flex", alignItems: "center", gap: "8px", marginBottom: "12px" }}>
<h4 style={{ fontWeight: 600, color: "#1f2937", margin: 0 }}>{category.category}</h4>
<Badge className={`${catColors.bg} ${catColors.text} text-xs`}>
{category.status === "normal" ? "正常" : "需关注"}
</Badge>
</div>
<div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
{category.indicators.map((ind: any, indIdx: number) => (
<div key={indIdx} style={{ background: "rgba(255,255,255,0.7)", borderRadius: "12px", padding: "12px" }}>
<div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: "8px" }}>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 600, color: "#1f2937", fontSize: "14px", marginBottom: "4px" }}>
{ind.name}
{ind.nickname && (
<span style={{ fontSize: "12px", color: "#9ca3af", marginLeft: "8px" }}>({ind.nickname})</span>
)}
</div>
{ind.value && (
<div style={{ fontSize: "18px", fontWeight: 700, color: "#7c6995" }}>
{ind.value} {ind.unit}
</div>
)}
</div>
<Badge className={`text-xs ${
ind.status === "normal"
? "bg-morandi-sage-100 text-morandi-sage-600"
: "bg-morandi-rose-100 text-morandi-rose-600"
}`}>
{ind.status === "normal" ? "正常" : ind.status === "high" ? "偏高" : "偏低"}
</Badge>
</div>
{ind.what_is_it && (
<p style={{ fontSize: "12px", color: "#6b7280", marginBottom: "8px", margin: "0 0 8px 0" }}>
{ind.what_is_it}
</p>
)}
{ind.suggestion && (
<div style={{ background: "#faf7fc", borderRadius: "8px", padding: "8px", marginTop: "8px" }}>
<p style={{ fontSize: "12px", color: "#4b5563", margin: 0 }}>💡 {ind.suggestion}</p>
</div>
)}
</div>
))}
</div>
</div>
);
})}
</div>
)}
{/* 行动建议 */}
{shareData.action_items && shareData.action_items.length > 0 && (
<div>
<h3 style={{ fontWeight: 700, color: "#1f2937", fontSize: "18px", marginBottom: "12px", marginTop: 0 }}>
接下来该做什么?
</h3>
<div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
{shareData.action_items.map((item: any, idx: number) => (
<div
key={idx}
style={{
borderRadius: "12px",
padding: "12px",
background: item.priority === "high" ? "#fce4ec" : "#faf7fc",
}}
>
<div style={{ display: "flex", alignItems: "flex-start", gap: "8px" }}>
<span
style={{
flexShrink: 0,
width: 20,
height: 20,
background: "#b8a9c9",
color: "white",
borderRadius: "50%",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "12px",
fontWeight: 700,
marginTop: "2px",
}}
>
{idx + 1}
</span>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 600, color: "#1f2937", fontSize: "14px", marginBottom: "4px" }}>
{item.title || item.content}
</div>
{item.description && (
<p style={{ fontSize: "12px", color: "#6b7280", margin: 0 }}>{item.description}</p>
)}
</div>
</div>
</div>
))}
</div>
</div>
)}
{/* 温馨提示 */}
{shareData.tips && shareData.tips.length > 0 && (
<div className="bg-morandi-50 rounded-2xl p-4">
<h4 style={{ fontWeight: 600, color: "#1f2937", fontSize: "14px", marginBottom: "8px", display: "flex", alignItems: "center", gap: "8px", marginTop: 0 }}>
<Heart className="w-4 h-4 text-morandi-400" />
温馨提示
</h4>
<ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: "4px" }}>
{shareData.tips.map((tip: string, idx: number) => (
<li key={idx} style={{ fontSize: "12px", color: "#6b7280", display: "flex", alignItems: "flex-start", gap: "8px" }}>
<span style={{ color: "#b8a9c9" }}>•</span>
<span>{tip}</span>
</li>
))}
</ul>
</div>
)}
{/* 底部声明 */}
<div style={{ paddingTop: "20px", borderTop: "2px solid #f3f4f6", textAlign: "center" }}>
<p style={{ fontSize: "12px", color: "#9ca3af", marginBottom: "4px", margin: "0 0 4px 0" }}>
本报告由 AI 生成,仅供参考,不能替代医生诊断
</p>
<p style={{ fontSize: "12px", color: "#9ca3af", marginBottom: "8px", margin: "0 0 8px 0" }}>
如有疑问请及时咨询专业医生
</p>
<div
style={{
display: "inline-flex",
alignItems: "center",
gap: "4px",
fontSize: "11px",
color: "#b8a9c9",
padding: "4px 12px",
background: "#faf7fc",
borderRadius: "9999px",
}}
>
<Heart style={{ width: 12, height: 12, fill: "#b8a9c9", color: "#b8a9c9" }} />
<span>孕育无忧 · yun.tun88.com</span>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,323 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router";
import { motion } from "motion/react";
import {
ChevronLeft,
Search,
Filter,
FileText,
CheckCircle2,
AlertCircle,
ChevronRight,
Loader2,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Card } from "../components/ui/card";
import { Badge } from "../components/ui/badge";
import { getTimeline } from "../services/api";
interface Report {
id: string;
type: string;
date: string;
status: "normal" | "attention" | "warning";
summary: string;
period: "early" | "mid" | "late";
week: number;
}
export function TimelinePage() {
const navigate = useNavigate();
const [searchQuery, setSearchQuery] = useState("");
const [selectedPeriod, setSelectedPeriod] = useState("all");
const [reports, setReports] = useState<Report[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
getTimeline()
.then((data) => {
setReports(
data.reports.map((r) => ({
id: r.id,
type: r.report_type,
date: r.date,
status: (r.status as Report["status"]) || "normal",
summary: r.summary,
period: (r.period as Report["period"]) || "early",
week: r.week,
}))
);
})
.catch(() => {/* keep empty */})
.finally(() => setLoading(false));
}, []);
const filteredReports = reports.filter((report) => {
const matchesSearch =
report.type.toLowerCase().includes(searchQuery.toLowerCase()) ||
report.summary.toLowerCase().includes(searchQuery.toLowerCase());
const matchesPeriod =
selectedPeriod === "all" || report.period === selectedPeriod;
return matchesSearch && matchesPeriod;
});
const periods = [
{ id: "all", name: "全部", weeks: "1-40周" },
{ id: "early", name: "孕早期", weeks: "1-12周" },
{ id: "mid", name: "孕中期", weeks: "13-27周" },
{ id: "late", name: "孕晚期", weeks: "28-40周" },
];
const groupedReports = filteredReports.reduce((acc, report) => {
const month = report.date.substring(0, 7); // "2026-03"
if (!acc[month]) {
acc[month] = [];
}
acc[month].push(report);
return acc;
}, {} as Record<string, Report[]>);
const monthNames: Record<string, string> = {};
Object.keys(groupedReports).forEach((month) => {
const [y, m] = month.split("-");
monthNames[month] = `${y}年${parseInt(m)}月`;
});
if (loading) {
return (
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin" />
</div>
);
}
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => navigate(-1)}
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<ChevronLeft className="w-6 h-6 text-gray-600" />
</button>
<div className="flex items-center gap-2">
<div className="w-10 h-10 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-full flex items-center justify-center">
<FileText className="w-5 h-5 text-white" />
</div>
<div>
<h1 className="font-semibold text-gray-800">报告时间轴</h1>
<p className="text-xs text-gray-500">
共{filteredReports.length}份报告
</p>
</div>
</div>
</div>
{/* 搜索框 */}
<div className="relative">
<Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
<Input
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="搜索报告类型或内容..."
className="pl-12 rounded-full border-gray-200"
/>
</div>
</div>
</div>
<div className="mx-auto p-4 space-y-6">
{/* 孕期筛选 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
>
<div className="flex gap-2 overflow-x-auto pb-2">
{periods.map((period) => (
<button
key={period.id}
onClick={() => setSelectedPeriod(period.id as any)}
className={`flex-shrink-0 px-6 py-3 rounded-2xl font-semibold text-sm transition-all ${
selectedPeriod === period.id
? "bg-gradient-to-r from-morandi-400 to-morandi-400 text-white shadow-sm"
: "bg-white text-gray-600 hover:bg-gray-50"
}`}
>
<div>{period.name}</div>
<div className="text-xs opacity-80">{period.weeks}</div>
</button>
))}
</div>
</motion.div>
{/* 统计卡片 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
>
<Card className="bg-white rounded-2xl p-4 shadow-sm border-0">
<div className="grid grid-cols-3 gap-4">
<div className="text-center">
<div className="text-2xl font-semibold text-morandi-sage-500 mb-1">
{
filteredReports.filter((r) => r.status === "normal").length
}
</div>
<div className="text-xs text-gray-500">正常</div>
</div>
<div className="text-center border-l border-r border-gray-100">
<div className="text-2xl font-semibold text-morandi-600 mb-1">
{
filteredReports.filter((r) => r.status === "attention")
.length
}
</div>
<div className="text-xs text-gray-500">需关注</div>
</div>
<div className="text-center">
<div className="text-2xl font-semibold text-red-600 mb-1">
{
filteredReports.filter((r) => r.status === "warning").length
}
</div>
<div className="text-xs text-gray-500">异常</div>
</div>
</div>
</Card>
</motion.div>
{/* 时间轴 */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
className="space-y-6"
>
{Object.keys(groupedReports)
.sort()
.reverse()
.map((month) => (
<div key={month}>
<h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
<div className="w-2 h-2 bg-morandi-400 rounded-full"></div>
{monthNames[month] || month}
</h2>
<div className="relative pl-6 space-y-4">
{/* 时间线 */}
<div className="absolute left-1 top-0 bottom-0 w-0.5 bg-gradient-to-b from-morandi-200 to-morandi-200"></div>
{groupedReports[month].map((report, index) => (
<motion.div
key={report.id}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.3 + index * 0.05 }}
className="relative"
>
{/* 时间点 */}
<div
className={`absolute -left-6 top-4 w-3 h-3 rounded-full border-2 border-white ${
report.status === "normal"
? "bg-morandi-sage-400"
: report.status === "attention"
? "bg-morandi-rose-400"
: "bg-red-500"
}`}
></div>
<Card
onClick={() => navigate(`/analysis/${report.id}`)}
className="bg-white rounded-2xl p-4 shadow-sm hover:shadow-sm transition-all cursor-pointer border-0"
>
<div className="flex items-center gap-4">
<div
className={`w-12 h-12 rounded-xl flex items-center justify-center ${
report.status === "normal"
? "bg-morandi-sage-100"
: report.status === "attention"
? "bg-morandi-rose-100"
: "bg-red-100"
}`}
>
{report.status === "normal" ? (
<CheckCircle2
className={`w-6 h-6 ${
report.status === "normal"
? "text-morandi-sage-400"
: report.status === "attention"
? "text-morandi-rose-400"
: "text-red-500"
}`}
/>
) : (
<AlertCircle
className={`w-6 h-6 ${
report.status === "attention"
? "text-morandi-rose-400"
: "text-red-500"
}`}
/>
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<h3 className="font-semibold text-gray-800">
{report.type}
</h3>
<Badge className="bg-morandi-100 text-morandi-500 hover:bg-morandi-100 text-xs">
孕{report.week}周
</Badge>
<Badge
className={`text-xs ${
report.status === "normal"
? "bg-morandi-sage-100 text-morandi-sage-600 hover:bg-morandi-sage-100"
: report.status === "attention"
? "bg-morandi-rose-100 text-morandi-600 hover:bg-morandi-rose-100"
: "bg-red-100 text-red-700 hover:bg-red-100"
}`}
>
{report.status === "normal"
? "正常"
: report.status === "attention"
? "关注"
: "异常"}
</Badge>
</div>
<p className="text-sm text-gray-600 truncate">
{report.summary}
</p>
<p className="text-xs text-gray-400 mt-1">
{report.date}
</p>
</div>
<ChevronRight className="w-5 h-5 text-gray-400 flex-shrink-0" />
</div>
</Card>
</motion.div>
))}
</div>
</div>
))}
</motion.div>
{filteredReports.length === 0 && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="text-center py-12"
>
<FileText className="w-16 h-16 text-gray-300 mx-auto mb-4" />
<p className="text-gray-500">暂无相关报告</p>
</motion.div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,840 @@
import { useState, useRef, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import { motion, AnimatePresence } from "motion/react";
import {
ArrowLeft,
Mic,
MicOff,
Square,
Play,
Pause,
Trash2,
Stethoscope,
Smile,
ShieldCheck,
Settings,
RefreshCw,
Pencil,
Check,
} from "lucide-react";
import { Card } from "../components/ui/card";
import { Button } from "../components/ui/button";
type Recording = {
id: string;
name: string;
tag: string;
duration: number;
date: string;
mood: string;
audioUrl?: string;
audioData?: string;
};
type MicPermission = "checking" | "prompt" | "granted" | "denied" | "unsupported" | "insecure";
const TABS = [
{ key: "visit", label: "就诊记录", icon: Stethoscope },
{ key: "mood", label: "孕期心情", icon: Smile },
] as const;
type TabKey = (typeof TABS)[number]["key"];
const STORAGE_KEY = "voice_recordings";
function blobToBase64(blob: Blob): Promise<string> {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.readAsDataURL(blob);
});
}
function base64ToBlobUrl(base64: string): string {
const [header, data] = base64.split(",");
const mime = header.match(/:(.*?);/)?.[1] || "audio/webm";
const binary = atob(data);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return URL.createObjectURL(new Blob([bytes], { type: mime }));
}
export function VoiceRecordPage() {
const navigate = useNavigate();
const [activeTab, setActiveTab] = useState<TabKey>("visit");
const [isRecording, setIsRecording] = useState(false);
const [recordingTime, setRecordingTime] = useState(0);
const [playingId, setPlayingId] = useState<string | null>(null);
const [micPermission, setMicPermission] = useState<MicPermission>("checking");
const [isRequesting, setIsRequesting] = useState(false);
const [deletingId, setDeletingId] = useState<string | null>(null);
const [editingId, setEditingId] = useState<string | null>(null);
const [editingName, setEditingName] = useState("");
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
const chunksRef = useRef<Blob[]>([]);
const audioRef = useRef<HTMLAudioElement | null>(null);
const [recordings, setRecordings] = useState<Recording[]>([]);
const currentTag = TABS.find((t) => t.key === activeTab)!.label;
const filteredRecordings = recordings.filter((r) => r.tag === currentTag);
// ─── 权限检测 ───
const checkPermission = useCallback(async () => {
// 检查是否在安全上下文中(HTTPS 或 localhost)
if (!window.isSecureContext) {
setMicPermission("insecure");
return;
}
// 检查浏览器是否支持
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
setMicPermission("unsupported");
return;
}
try {
// 使用 Permissions API 查询(部分浏览器支持)
if (navigator.permissions && navigator.permissions.query) {
const result = await navigator.permissions.query({ name: "microphone" as PermissionName });
setMicPermission(result.state as MicPermission);
// 监听权限变化(用户在系统设置中更改)
result.onchange = () => {
setMicPermission(result.state as MicPermission);
};
return;
}
} catch {
// Permissions API 不支持 microphone 查询(如 Firefox),fallback
}
// Fallback:尝试实际请求来判断
setMicPermission("prompt");
}, []);
useEffect(() => {
checkPermission();
}, [checkPermission]);
// ─── 从 localStorage 恢复录音 ───
useEffect(() => {
try {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) {
const parsed: Recording[] = JSON.parse(saved);
setRecordings(
parsed.map((r) => ({
...r,
audioUrl: r.audioData ? base64ToBlobUrl(r.audioData) : undefined,
}))
);
}
} catch {
/* ignore */
}
}, []);
// ─── 录音变化时持久化到 localStorage ───
useEffect(() => {
try {
const toSave = recordings.map(({ audioUrl, ...rest }) => rest);
localStorage.setItem(STORAGE_KEY, JSON.stringify(toSave));
} catch {
/* storage full or unavailable */
}
}, [recordings]);
// ─── 请求麦克风权限 ───
const requestPermission = async () => {
setIsRequesting(true);
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
// 拿到权限后立即释放
stream.getTracks().forEach((track) => track.stop());
setMicPermission("granted");
} catch (err: unknown) {
const error = err as DOMException;
if (error.name === "NotAllowedError" || error.name === "PermissionDeniedError") {
setMicPermission("denied");
} else {
setMicPermission("unsupported");
}
} finally {
setIsRequesting(false);
}
};
// ─── 录音功能 ───
const formatTime = (seconds: number) => {
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
};
const startRecording = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const mediaRecorder = new MediaRecorder(stream);
mediaRecorderRef.current = mediaRecorder;
chunksRef.current = [];
mediaRecorder.ondataavailable = (e) => {
if (e.data.size > 0) chunksRef.current.push(e.data);
};
mediaRecorder.start();
setIsRecording(true);
setRecordingTime(0);
timerRef.current = setInterval(() => {
setRecordingTime((prev) => prev + 1);
}, 1000);
} catch {
// 录音时被拒绝,更新权限状态
setMicPermission("denied");
}
};
const stopRecording = () => {
setIsRecording(false);
if (timerRef.current) clearInterval(timerRef.current);
const recorder = mediaRecorderRef.current;
if (recorder && recorder.state !== "inactive") {
const duration = recordingTime;
recorder.onstop = async () => {
const mimeType = recorder.mimeType || "audio/webm";
const blob = new Blob(chunksRef.current, { type: mimeType });
const audioUrl = URL.createObjectURL(blob);
const audioData = await blobToBase64(blob);
recorder.stream.getTracks().forEach((track) => track.stop());
if (duration > 0) {
const moodList = ["😊", "🥰", "😌", "💪", "🤔"];
const now = new Date();
const timeStr = `${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}`;
const dateStr = now.toISOString().split("T")[0];
setRecordings((prev) => {
const count = prev.filter((r) => r.tag === currentTag && r.date === dateStr).length + 1;
return [
{
id: Date.now().toString(),
name: `${currentTag} ${dateStr} ${timeStr}${count > 1 ? ` (${count})` : ""}`,
tag: currentTag,
duration,
date: dateStr,
mood: moodList[Math.floor(Math.random() * moodList.length)],
audioUrl,
audioData,
},
...prev,
];
});
}
};
recorder.stop();
}
setRecordingTime(0);
};
const startRename = (rec: Recording) => {
setEditingId(rec.id);
setEditingName(rec.name);
};
const confirmRename = () => {
if (editingId && editingName.trim()) {
setRecordings((prev) =>
prev.map((r) => (r.id === editingId ? { ...r, name: editingName.trim() } : r))
);
}
setEditingId(null);
setEditingName("");
};
const deleteRecording = (id: string) => {
const rec = recordings.find((r) => r.id === id);
if (rec?.audioUrl) URL.revokeObjectURL(rec.audioUrl);
setRecordings((prev) => prev.filter((r) => r.id !== id));
};
const togglePlay = (id: string) => {
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
if (playingId === id) {
setPlayingId(null);
return;
}
const rec = recordings.find((r) => r.id === id);
if (!rec?.audioUrl) return;
const audio = new Audio(rec.audioUrl);
audioRef.current = audio;
audio.onended = () => {
setPlayingId(null);
audioRef.current = null;
};
audio.play().catch(() => {
setPlayingId(null);
audioRef.current = null;
});
setPlayingId(id);
};
useEffect(() => {
return () => {
if (timerRef.current) clearInterval(timerRef.current);
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
if (mediaRecorderRef.current && mediaRecorderRef.current.state !== "inactive") {
mediaRecorderRef.current.stop();
}
};
}, []);
// ─── 权限引导 UI ───
const renderPermissionGuide = () => {
if (micPermission === "checking") {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="flex flex-col items-center gap-4 py-4"
>
<motion.div
animate={{ rotate: 360 }}
transition={{ duration: 1.5, repeat: Infinity, ease: "linear" }}
>
<RefreshCw className="w-8 h-8 text-morandi-400" />
</motion.div>
<p className="text-sm text-gray-500">正在检查麦克风权限...</p>
</motion.div>
);
}
if (micPermission === "unsupported") {
return (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="flex flex-col items-center gap-4 py-4"
>
<div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center">
<MicOff className="w-8 h-8 text-gray-400" />
</div>
<div className="text-center">
<p className="font-medium text-gray-700 mb-1">浏览器不支持录音</p>
<p className="text-sm text-gray-500 leading-relaxed">
请使用 Safari、Chrome 等现代浏览器访问
</p>
</div>
</motion.div>
);
}
if (micPermission === "insecure") {
const currentUrl = window.location.href;
const httpsUrl = currentUrl.replace(/^http:/, "https:");
return (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="flex flex-col items-center gap-5 py-4"
>
<div className="w-20 h-20 bg-amber-50 rounded-full flex items-center justify-center">
<ShieldCheck className="w-10 h-10 text-amber-500" />
</div>
<div className="text-center">
<p className="font-semibold text-gray-800 mb-2">需要安全连接</p>
<p className="text-sm text-gray-500 leading-relaxed px-2">
麦克风和摄像头功能需要通过 HTTPS 安全连接才能使用,当前页面使用的是不安全的 HTTP 连接
</p>
</div>
<div className="bg-amber-50 rounded-xl p-4 w-full">
<p className="text-sm font-medium text-gray-700 mb-2">解决方法:</p>
<ol className="text-sm text-gray-600 space-y-2">
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-amber-200 text-amber-700 rounded-full flex items-center justify-center text-xs font-semibold">1</span>
<span>将地址栏中的 <strong>http://</strong> 改为 <strong>https://</strong></span>
</li>
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-amber-200 text-amber-700 rounded-full flex items-center justify-center text-xs font-semibold">2</span>
<span>如果浏览器提示证书不安全,点击「继续访问」或「高级」→「继续」</span>
</li>
</ol>
</div>
<Button
onClick={() => { window.location.href = httpsUrl; }}
className="w-full h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium"
>
<ShieldCheck className="w-4 h-4 mr-2" />
切换到 HTTPS 访问
</Button>
</motion.div>
);
}
if (micPermission === "prompt") {
return (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="flex flex-col items-center gap-5 py-4"
>
<div className="w-20 h-20 bg-gradient-to-br from-morandi-100 to-morandi-200 rounded-full flex items-center justify-center">
<Mic className="w-10 h-10 text-morandi-500" />
</div>
<div className="text-center">
<p className="font-semibold text-gray-800 mb-2">需要麦克风权限</p>
<p className="text-sm text-gray-500 leading-relaxed px-4">
录音功能需要访问您的麦克风,点击下方按钮授权后即可开始录音
</p>
</div>
<div className="bg-morandi-50 rounded-xl p-4 w-full">
<div className="flex items-start gap-3">
<ShieldCheck className="w-5 h-5 text-morandi-400 flex-shrink-0 mt-0.5" />
<div>
<p className="text-xs text-gray-600 leading-relaxed">
我们仅在录音时使用麦克风,录音数据保存在您的设备本地,不会上传到服务器
</p>
</div>
</div>
</div>
<Button
onClick={requestPermission}
disabled={isRequesting}
className="w-full h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium"
>
{isRequesting ? (
<>
<motion.div
animate={{ rotate: 360 }}
transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
className="mr-2"
>
<RefreshCw className="w-4 h-4" />
</motion.div>
正在请求权限...
</>
) : (
<>
<Mic className="w-4 h-4 mr-2" />
授权麦克风
</>
)}
</Button>
</motion.div>
);
}
if (micPermission === "denied") {
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
const isAndroid = /Android/.test(navigator.userAgent);
const isWechat = /MicroMessenger/.test(navigator.userAgent);
return (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="flex flex-col items-center gap-5 py-4"
>
<div className="w-20 h-20 bg-red-50 rounded-full flex items-center justify-center">
<MicOff className="w-10 h-10 text-red-400" />
</div>
<div className="text-center">
<p className="font-semibold text-gray-800 mb-2">麦克风权限已被拒绝</p>
<p className="text-sm text-gray-500 leading-relaxed px-2">
请按以下步骤手动开启麦克风权限后,点击"重新检测"
</p>
</div>
<div className="w-full space-y-3">
{isWechat ? (
<div className="bg-morandi-50 rounded-xl p-4">
<p className="text-sm font-medium text-gray-700 mb-2">微信内操作:</p>
<ol className="text-sm text-gray-600 space-y-2">
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">1</span>
<span>点击右上角「...」更多按钮</span>
</li>
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">2</span>
<span>选择「设置」</span>
</li>
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">3</span>
<span>开启「麦克风」权限</span>
</li>
</ol>
</div>
) : isIOS ? (
<div className="bg-morandi-50 rounded-xl p-4">
<p className="text-sm font-medium text-gray-700 mb-2">iOS 设备操作:</p>
<ol className="text-sm text-gray-600 space-y-2">
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">1</span>
<span>打开手机「设置」应用</span>
</li>
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">2</span>
<span>向下滑动找到「Safari浏览器」(或当前浏览器)</span>
</li>
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">3</span>
<span>点击进入,找到「麦克风」并开启</span>
</li>
</ol>
</div>
) : isAndroid ? (
<div className="bg-morandi-50 rounded-xl p-4">
<p className="text-sm font-medium text-gray-700 mb-2">安卓设备操作:</p>
<ol className="text-sm text-gray-600 space-y-2">
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">1</span>
<span>打开手机「设置」→「应用管理」</span>
</li>
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">2</span>
<span>找到当前浏览器应用</span>
</li>
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">3</span>
<span>点击「权限」→ 开启「麦克风」</span>
</li>
</ol>
</div>
) : (
<div className="bg-morandi-50 rounded-xl p-4">
<p className="text-sm font-medium text-gray-700 mb-2">浏览器操作:</p>
<ol className="text-sm text-gray-600 space-y-2">
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">1</span>
<span>点击地址栏左侧的锁形图标或设置图标</span>
</li>
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">2</span>
<span>找到「麦克风」权限设置</span>
</li>
<li className="flex gap-2">
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">3</span>
<span>将其改为「允许」,然后刷新页面</span>
</li>
</ol>
</div>
)}
</div>
<div className="flex gap-3 w-full">
<Button
onClick={() => {
setMicPermission("checking");
checkPermission();
}}
className="flex-1 h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium"
>
<RefreshCw className="w-4 h-4 mr-2" />
重新检测
</Button>
<Button
onClick={requestPermission}
variant="outline"
className="flex-1 h-12 rounded-xl border-2 border-morandi-200 text-morandi-500 font-medium"
>
<Settings className="w-4 h-4 mr-2" />
再次请求
</Button>
</div>
</motion.div>
);
}
return null;
};
// ─── 录音控制区 UI(已授权状态)───
const renderRecorder = () => (
<AnimatePresence mode="wait">
{isRecording ? (
<motion.div
key="recording"
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
className="flex flex-col items-center gap-4"
>
{/* 波形动画 */}
<div className="flex items-center gap-1 h-12">
{Array.from({ length: 24 }).map((_, i) => (
<motion.div
key={i}
className="w-1 bg-morandi-400 rounded-full"
animate={{
height: [6, 14 + Math.random() * 24, 6],
}}
transition={{
duration: 0.6 + Math.random() * 0.4,
repeat: Infinity,
delay: i * 0.05,
}}
/>
))}
</div>
<div className="flex items-center gap-2">
<div className="w-2 h-2 bg-red-400 rounded-full animate-pulse" />
<span className="text-lg font-mono font-semibold text-gray-700">
{formatTime(recordingTime)}
</span>
<span className="text-sm text-gray-400">· {currentTag}</span>
</div>
<button
onClick={stopRecording}
className="w-16 h-16 bg-red-400 hover:bg-red-500 rounded-full flex items-center justify-center shadow-sm shadow-red-200 transition-all hover:scale-105"
>
<Square className="w-6 h-6 text-white fill-white" />
</button>
<span className="text-xs text-gray-400">点击停止录音</span>
</motion.div>
) : (
<motion.div
key="idle"
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
className="flex flex-col items-center gap-4"
>
<p className="text-sm text-gray-500">
{activeTab === "visit"
? "记录就诊过程,方便日后回顾"
: "记录今天的心情和感受"}
</p>
<button
onClick={startRecording}
className="w-16 h-16 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-full flex items-center justify-center shadow-sm transition-all hover:scale-105"
>
<Mic className="w-7 h-7 text-white" />
</button>
<span className="text-xs text-gray-400">点击开始录音</span>
</motion.div>
)}
</AnimatePresence>
);
return (
<div className="min-h-dvh bg-morandi-50">
{/* 顶部导航 */}
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
<div className="mx-auto px-4 py-4 flex items-center gap-3">
<button
onClick={() => navigate(-1)}
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
>
<ArrowLeft className="w-5 h-5 text-gray-600" />
</button>
<h1 className="font-semibold text-gray-800 text-base">语音记录</h1>
</div>
</div>
<div className="mx-auto p-4 space-y-5">
{/* Tab 切换 */}
<div className="flex bg-white rounded-2xl p-1.5 shadow-sm">
{TABS.map((tab) => (
<button
key={tab.key}
onClick={() => {
if (!isRecording) setActiveTab(tab.key);
}}
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-medium transition-all ${
activeTab === tab.key
? "bg-morandi-400 text-white shadow-sm"
: "text-gray-500 hover:text-gray-700"
}`}
>
<tab.icon className="w-4 h-4" />
{tab.label}
</button>
))}
</div>
{/* 录音控制区 */}
<Card className="bg-white rounded-2xl p-6 shadow-md border-0">
<div className="bg-gradient-to-r from-morandi-50 to-morandi-100 rounded-2xl p-5">
{micPermission === "granted" ? renderRecorder() : renderPermissionGuide()}
</div>
</Card>
{/* 录音列表 */}
<div>
<div className="flex items-center justify-between mb-3">
<h2 className="font-semibold text-gray-800">
{currentTag} ({filteredRecordings.length})
</h2>
</div>
{filteredRecordings.length === 0 ? (
<Card className="bg-white rounded-2xl p-8 shadow-md border-0 text-center">
<Mic className="w-10 h-10 text-gray-300 mx-auto mb-3" />
<p className="text-sm text-gray-400">暂无录音,点击上方开始记录</p>
</Card>
) : (
<div className="space-y-3">
{filteredRecordings.map((rec) => (
<motion.div
key={rec.id}
layout
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
>
<Card className="bg-white rounded-2xl p-4 shadow-md border-0 group">
<div className="flex items-center gap-3">
<button
onClick={() => togglePlay(rec.id)}
disabled={!rec.audioUrl}
className="w-11 h-11 rounded-full bg-morandi-100 flex items-center justify-center flex-shrink-0 hover:bg-morandi-200 transition-colors disabled:opacity-50"
>
{playingId === rec.id ? (
<Pause className="w-5 h-5 text-morandi-500" />
) : (
<Play className="w-5 h-5 text-morandi-500 ml-0.5" />
)}
</button>
<div className="flex-1 min-w-0">
{editingId === rec.id ? (
<div className="flex items-center gap-2 mb-1">
<input
autoFocus
value={editingName}
onChange={(e) => setEditingName(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") confirmRename();
if (e.key === "Escape") { setEditingId(null); setEditingName(""); }
}}
onBlur={confirmRename}
className="flex-1 min-w-0 text-sm font-medium text-gray-700 border-b-2 border-morandi-400 outline-none bg-transparent py-0.5"
/>
<button
onMouseDown={(e) => e.preventDefault()}
onClick={confirmRename}
className="p-1 rounded hover:bg-morandi-100"
>
<Check className="w-4 h-4 text-morandi-500" />
</button>
</div>
) : (
<div className="flex items-center gap-2 mb-1">
<span className="text-sm font-medium text-gray-700 truncate">
{rec.name || rec.tag}
</span>
<span className="text-base flex-shrink-0">{rec.mood}</span>
<button
onClick={() => startRename(rec)}
className="p-1 rounded hover:bg-morandi-100 flex-shrink-0"
>
<Pencil className="w-3.5 h-3.5 text-gray-400" />
</button>
</div>
)}
<div className="flex items-center gap-2 text-xs text-gray-400">
<span>{formatTime(rec.duration)}</span>
<span>·</span>
<span>{rec.date}</span>
</div>
{/* 播放波形动画 */}
{playingId === rec.id && (
<div className="flex items-center gap-0.5 mt-2 h-4">
{Array.from({ length: 30 }).map((_, i) => (
<motion.div
key={i}
className="w-1 bg-morandi-300 rounded-full"
animate={{
height: [3, 6 + Math.random() * 10, 3],
}}
transition={{
duration: 0.5 + Math.random() * 0.3,
repeat: Infinity,
delay: i * 0.03,
}}
/>
))}
</div>
)}
</div>
<button
onClick={() => setDeletingId(rec.id)}
className="p-2 rounded-lg hover:bg-red-50 active:bg-red-50 transition-all"
>
<Trash2 className="w-4 h-4 text-gray-400 hover:text-red-400" />
</button>
</div>
</Card>
</motion.div>
))}
</div>
)}
</div>
</div>
{/* 删除确认弹窗 */}
<AnimatePresence>
{deletingId && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-8"
onClick={() => setDeletingId(null)}
>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.9, opacity: 0 }}
onClick={(e) => e.stopPropagation()}
className="bg-white rounded-2xl p-6 w-full max-w-sm shadow-xl"
>
<div className="flex flex-col items-center gap-3 mb-5">
<div className="w-12 h-12 bg-red-50 rounded-full flex items-center justify-center">
<Trash2 className="w-6 h-6 text-red-400" />
</div>
<h3 className="font-semibold text-gray-800">确认删除</h3>
<p className="text-sm text-gray-500 text-center">
删除后无法恢复,确定要删除这条录音吗?
</p>
</div>
<div className="flex gap-3">
<Button
variant="outline"
onClick={() => setDeletingId(null)}
className="flex-1 h-11 rounded-xl"
>
取消
</Button>
<Button
onClick={() => {
deleteRecording(deletingId);
setDeletingId(null);
}}
className="flex-1 h-11 rounded-xl bg-red-400 hover:bg-red-500 text-white"
>
删除
</Button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}

128
frontend/src/app/routes.tsx Normal file
View File

@@ -0,0 +1,128 @@
import { createBrowserRouter, Navigate, Outlet } from "react-router";
import { LoginPage } from "./pages/LoginPage";
import { OnboardingPage } from "./pages/OnboardingPage";
import { HomePage } from "./pages/HomePage";
import { CameraCapturePage } from "./pages/CameraCapturePage";
import { DataVerificationPage } from "./pages/DataVerificationPage";
import { AIAnalysisPage } from "./pages/AIAnalysisPage";
import { ReportDetailPage } from "./pages/ReportDetailPage";
import { DevNavigationPage } from "./pages/DevNavigationPage";
import { AIChatPage } from "./pages/AIChatPage";
import { HealthRecordsPage } from "./pages/HealthRecordsPage";
import { GrowthCurvePage } from "./pages/GrowthCurvePage";
import { TimelinePage } from "./pages/TimelinePage";
import { CalendarPage } from "./pages/CalendarPage";
import { DoctorQuestionsPage } from "./pages/DoctorQuestionsPage";
import { SharePage } from "./pages/SharePage";
import { ExpertConsultationPage } from "./pages/ExpertConsultationPage";
import { ProfilePage } from "./pages/ProfilePage";
import { VoiceRecordPage } from "./pages/VoiceRecordPage";
import { NotificationPage } from "./pages/NotificationPage";
import { MobileLayout } from "./components/MobileLayout";
import { getToken } from "./services/api";
/** 路由守卫:未登录跳转登录页 */
function ProtectedRoute() {
const token = getToken();
const hasProfile = !!localStorage.getItem("pregnancy_user_profile");
if (!token && !hasProfile) {
return <Navigate to="/" replace />;
}
return <Outlet />;
}
export const router = createBrowserRouter([
{
// 全局 H5 移动端布局容器
element: <MobileLayout />,
children: [
// 公开路由
{
path: "/dev",
Component: DevNavigationPage,
},
{
path: "/",
Component: LoginPage,
},
{
path: "/onboarding",
Component: OnboardingPage,
},
// 需要登录的路由
{
element: <ProtectedRoute />,
children: [
{
path: "/home",
Component: HomePage,
},
{
path: "/profile",
Component: ProfilePage,
},
{
path: "/camera",
Component: CameraCapturePage,
},
{
path: "/review",
Component: DataVerificationPage,
},
{
path: "/verify",
Component: DataVerificationPage,
},
{
path: "/analysis/:reportId",
Component: AIAnalysisPage,
},
{
path: "/report/:reportId",
Component: ReportDetailPage,
},
{
path: "/chat/:reportId",
Component: AIChatPage,
},
{
path: "/voice-record",
Component: VoiceRecordPage,
},
{
path: "/health-records",
Component: HealthRecordsPage,
},
{
path: "/growth-curve",
Component: GrowthCurvePage,
},
{
path: "/timeline",
Component: TimelinePage,
},
{
path: "/calendar",
Component: CalendarPage,
},
{
path: "/doctor-questions/:reportId",
Component: DoctorQuestionsPage,
},
{
path: "/share/:reportId",
Component: SharePage,
},
{
path: "/expert-consultation",
Component: ExpertConsultationPage,
},
{
path: "/notifications",
Component: NotificationPage,
},
],
},
],
},
]);

View File

@@ -0,0 +1,510 @@
const TOKEN_KEY = "auth_token";
export function getToken(): string | null {
return localStorage.getItem(TOKEN_KEY);
}
export function setToken(token: string) {
localStorage.setItem(TOKEN_KEY, token);
}
export function clearToken() {
localStorage.removeItem(TOKEN_KEY);
}
async function fetchApi<T>(path: string, options: RequestInit = {}): Promise<T> {
const token = getToken();
const headers: Record<string, string> = {
"Content-Type": "application/json",
...(options.headers as Record<string, string>),
};
if (token) {
headers["Authorization"] = `Bearer ${token}`;
}
const res = await fetch(path, { ...options, headers });
if (res.status === 401) {
clearToken();
window.location.href = "/";
throw new Error("登录已过期,请重新登录");
}
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.detail || `请求失败 (${res.status})`);
}
return res.json();
}
// ─── Auth ───
interface LoginResponse {
access_token: string;
token_type: string;
user_id: string;
is_new_user: boolean;
}
export async function loginByPhone(phone: string, smsCode: string): Promise<LoginResponse> {
return fetchApi<LoginResponse>("/api/auth/phone-login", {
method: "POST",
body: JSON.stringify({ phone, sms_code: smsCode }),
});
}
export async function loginByWechat(code: string): Promise<LoginResponse> {
return fetchApi<LoginResponse>("/api/auth/wechat-login", {
method: "POST",
body: JSON.stringify({ code }),
});
}
export async function loginByDemo(): Promise<LoginResponse> {
return fetchApi<LoginResponse>("/api/auth/demo-login", {
method: "POST",
});
}
// ─── User Profile ───
export interface UserProfileDTO {
id: string;
name: string;
phone: string | null;
age: number | null;
height: number | null;
pre_pregnancy_weight: number | null;
current_weight: number | null;
blood_type: string | null;
allergies: string[];
medical_history: string[];
last_period_date: string | null;
due_date: string | null;
pregnancy_week: number | null;
pregnancy_day: number | null;
emergency_contact: { name: string; relation: string; phone: string } | null;
is_onboarded: boolean;
avatar_url: string | null;
created_at: string;
}
export async function getUserProfile(): Promise<UserProfileDTO> {
return fetchApi<UserProfileDTO>("/api/user/profile");
}
export interface OnboardingData {
name?: string;
age?: number;
last_period_date?: string;
due_date?: string;
pregnancy_week?: number;
pregnancy_day?: number;
multiple_pregnancy?: string;
pregnancy_count?: number;
medical_history?: string[];
height?: number;
pre_pregnancy_weight?: number;
}
export async function submitOnboarding(data: OnboardingData): Promise<UserProfileDTO> {
return fetchApi<UserProfileDTO>("/api/user/onboarding", {
method: "POST",
body: JSON.stringify(data),
});
}
export async function updateUserProfile(data: Record<string, unknown>): Promise<UserProfileDTO> {
return fetchApi<UserProfileDTO>("/api/user/profile", {
method: "PUT",
body: JSON.stringify(data),
});
}
// ─── Report ───
export interface OcrDataItem {
name: string;
value: string;
unit: string;
reference_range: string;
status: "normal" | "high" | "low";
category: string;
}
export interface UploadReportResponse {
report_id: string;
image_url: string;
ocr_result: {
report_type: string;
data_items: OcrDataItem[];
patient_name: string;
};
}
export async function uploadReportImage(file: File): Promise<UploadReportResponse> {
const token = getToken();
const formData = new FormData();
formData.append("file", file);
const headers: Record<string, string> = {};
if (token) headers["Authorization"] = `Bearer ${token}`;
const res = await fetch("/api/report/upload", {
method: "POST",
headers,
body: formData,
});
if (res.status === 401) {
clearToken();
window.location.href = "/";
throw new Error("登录已过期,请重新登录");
}
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.detail || `上传失败 (${res.status})`);
}
return res.json();
}
export interface AddImageResponse {
report_id: string;
image_url: string;
image_count: number;
ocr_result: {
report_type: string;
data_items: OcrDataItem[];
patient_name: string;
};
total_items: number;
}
export async function addImageToReport(reportId: string, file: File): Promise<AddImageResponse> {
const token = getToken();
const formData = new FormData();
formData.append("file", file);
const headers: Record<string, string> = {};
if (token) headers["Authorization"] = `Bearer ${token}`;
const res = await fetch(`/api/report/${reportId}/add-image`, {
method: "POST",
headers,
body: formData,
});
if (res.status === 401) {
clearToken();
window.location.href = "/";
throw new Error("登录已过期,请重新登录");
}
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.detail || `上传失败 (${res.status})`);
}
return res.json();
}
export interface VerifyDataItem {
name: string;
value: string;
unit: string;
reference_range: string;
status: "normal" | "high" | "low";
category: string;
}
export interface ReportVerifyRequest {
data_items: VerifyDataItem[];
symptoms: string[];
notes: string;
report_type?: string;
}
export interface ReportResponse {
id: string;
report_type: string;
pregnancy_week: number | null;
image_urls: string[];
data_items: VerifyDataItem[];
symptoms: string[];
notes: string;
status: string;
overall_status: string;
created_at: string;
}
export async function verifyReport(reportId: string, data: ReportVerifyRequest): Promise<ReportResponse> {
return fetchApi<ReportResponse>(`/api/report/${reportId}/verify`, {
method: "PUT",
body: JSON.stringify(data),
});
}
export interface ReportListItem {
id: string;
report_type: string;
pregnancy_week: number | null;
overall_status: string;
summary: string;
item_count: number;
created_at: string;
}
export async function getReportList(limit = 50): Promise<ReportListItem[]> {
return fetchApi<ReportListItem[]>(`/api/report/list?limit=${limit}`);
}
export async function getReport(reportId: string): Promise<ReportResponse> {
return fetchApi<ReportResponse>(`/api/report/${reportId}`);
}
// ─── Analysis ───
export interface AnalysisResponse {
id: string;
report_id: string;
overall_status: string;
risk_level: string;
overall_summary: string;
emotional_summary: string;
categories: {
category: string;
status: string;
indicators: {
name: string;
nickname: string;
value: string;
unit: string;
reference_range: string;
status: string;
what_is_it: string;
baby_impact: string;
suggestion: string;
follow_up: string;
}[];
}[];
action_items: {
priority: string;
title: string;
description: string;
timeframe: string;
}[];
tips: string[];
created_at: string;
}
export async function generateAnalysis(reportId: string): Promise<AnalysisResponse> {
return fetchApi<AnalysisResponse>(`/api/analysis/${reportId}/generate`, {
method: "POST",
});
}
export async function getAnalysis(reportId: string): Promise<AnalysisResponse> {
return fetchApi<AnalysisResponse>(`/api/analysis/${reportId}`);
}
// ─── Chat ───
export interface ChatMessageResponse {
user_message: { role: string; content: string; timestamp: string };
ai_message: { role: string; content: string; timestamp: string };
}
export interface ChatHistoryResponse {
messages: { role: string; content: string; timestamp: string }[];
quick_questions: string[];
}
export async function sendChatMessage(reportId: string, content: string): Promise<ChatMessageResponse> {
return fetchApi<ChatMessageResponse>(`/api/chat/${reportId}/message`, {
method: "POST",
body: JSON.stringify({ content }),
});
}
export async function getChatHistory(reportId: string): Promise<ChatHistoryResponse> {
return fetchApi<ChatHistoryResponse>(`/api/chat/${reportId}/history`);
}
// ─── Health Records ───
export interface HealthOverviewResponse {
stats: { total: number; normal: number; attention: number; warning: number };
recent_reports: { id: string; report_type: string; overall_status: string; created_at: string }[];
}
export async function getHealthOverview(): Promise<HealthOverviewResponse> {
return fetchApi<HealthOverviewResponse>("/api/health-records/overview");
}
export interface GrowthCurveResponse {
data_points: { week: number; bpd?: number; ac?: number; fl?: number }[];
}
export async function getGrowthCurve(): Promise<GrowthCurveResponse> {
return fetchApi<GrowthCurveResponse>("/api/health-records/growth-curve");
}
export interface TimelineResponse {
reports: {
id: string;
report_type: string;
date: string;
status: string;
summary: string;
period: string;
week: number;
}[];
}
export async function getTimeline(): Promise<TimelineResponse> {
return fetchApi<TimelineResponse>("/api/health-records/timeline");
}
export interface IndicatorTrendPoint {
week: number;
value: number;
date: string;
status: string;
report_type: string;
}
export interface IndicatorTrend {
name: string;
unit: string;
ref_lower: number | null;
ref_upper: number | null;
points: IndicatorTrendPoint[];
}
export interface IndicatorTrendsResponse {
indicators: IndicatorTrend[];
}
export async function getIndicatorTrends(): Promise<IndicatorTrendsResponse> {
return fetchApi<IndicatorTrendsResponse>("/api/health-records/indicator-trends");
}
export interface ReportTypeTrendPoint {
week: number;
value: number;
date: string;
status: string;
}
export interface ReportTypeTrendIndicator {
name: string;
unit: string;
ref_lower: number | null;
ref_upper: number | null;
points: ReportTypeTrendPoint[];
}
export interface ReportTypeTrend {
report_type: string;
report_count: number;
indicators: ReportTypeTrendIndicator[];
}
export interface ReportTypeTrendsResponse {
report_types: ReportTypeTrend[];
}
export async function getReportTypeTrends(): Promise<ReportTypeTrendsResponse> {
return fetchApi<ReportTypeTrendsResponse>("/api/health-records/report-type-trends");
}
// ─── Calendar ───
export interface CheckupItem {
title: string;
week: number;
items: string[];
preparations: string[];
notes: string;
importance: string;
status: string;
report_ids: string[];
}
export interface CheckupPlanResponse {
checkups: CheckupItem[];
next_checkup: CheckupItem | null;
current_week: number;
}
export async function getCheckupPlan(): Promise<CheckupPlanResponse> {
return fetchApi<CheckupPlanResponse>("/api/calendar/plan");
}
export async function completeCheckup(week: number): Promise<{ message: string }> {
return fetchApi<{ message: string }>(`/api/calendar/plan/${week}/complete`, {
method: "PUT",
});
}
// ─── Doctor ───
export interface DoctorQuestionsResponse {
report_id: string;
questions: { category: string; question: string; reason: string }[];
}
export async function getDoctorQuestions(reportId: string): Promise<DoctorQuestionsResponse> {
return fetchApi<DoctorQuestionsResponse>(`/api/doctor/questions/${reportId}`);
}
export interface Doctor {
id: string;
name: string;
title: string;
hospital: string;
specialty: string;
experience: string;
rating: number;
review_count: number;
consult_count: number;
response_time: string;
price: { text: number; video: number; urgent: number };
tags: string[];
}
export async function getExperts(): Promise<{ doctors: Doctor[] }> {
return fetchApi<{ doctors: Doctor[] }>("/api/doctor/experts");
}
export async function getExpertDetail(doctorId: string): Promise<Doctor> {
return fetchApi<Doctor>(`/api/doctor/experts/${doctorId}`);
}
// ─── Share ───
export interface ShareDataResponse {
share_data: {
report_type: string;
pregnancy_week: number | null;
overall_status: string;
emotional_summary: string;
action_items: { priority: string; title: string; description: string; timeframe: string }[];
tips: string[];
user_name: string;
categories?: {
category: string;
status: string;
indicators: { name: string; nickname: string; status: string; what_is_it: string; suggestion: string }[];
}[];
};
}
export async function generateShareData(
reportId: string,
options: { privacy_mode?: boolean; include_details?: boolean } = {}
): Promise<ShareDataResponse> {
return fetchApi<ShareDataResponse>(`/api/share/${reportId}/generate`, {
method: "POST",
body: JSON.stringify({ privacy_mode: true, include_details: false, ...options }),
});
}

7
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,7 @@
import { createRoot } from "react-dom/client";
import App from "./app/App.tsx";
import "./styles/index.css";
createRoot(document.getElementById("root")!).render(<App />);

View File

View File

@@ -0,0 +1,3 @@
@import './fonts.css';
@import './tailwind.css';
@import './theme.css';

View File

@@ -0,0 +1,4 @@
@import 'tailwindcss' source(none);
@source '../**/*.{js,ts,jsx,tsx}';
@import 'tw-animate-css';

View File

@@ -0,0 +1,214 @@
@custom-variant dark (&:is(.dark *));
:root {
--font-size: 16px;
--background: #ffffff;
--foreground: oklch(0.145 0 0);
--card: #ffffff;
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: #A07CC5;
--primary-foreground: #ffffff;
--secondary: #F5F1FA;
--secondary-foreground: #573D78;
--muted: #E9E0F4;
--muted-foreground: #6E4F93;
--accent: #E9E0F4;
--accent-foreground: #573D78;
--destructive: #d4183d;
--destructive-foreground: #ffffff;
--border: rgba(0, 0, 0, 0.1);
--input: transparent;
--input-background: #f8f5fb;
--switch-background: #cbced4;
--font-weight-medium: 500;
--font-weight-normal: 400;
--ring: #A07CC5;
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: #A07CC5;
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.145 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.145 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.985 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.396 0.141 25.723);
--destructive-foreground: oklch(0.637 0.237 25.331);
--border: oklch(0.269 0 0);
--input: oklch(0.269 0 0);
--ring: oklch(0.439 0 0);
--font-weight-medium: 500;
--font-weight-normal: 400;
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(0.269 0 0);
--sidebar-ring: oklch(0.439 0 0);
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-input-background: var(--input-background);
--color-switch-background: var(--switch-background);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
/* 藤萝紫色系 */
--color-morandi-50: #F5F1FA;
--color-morandi-100: #E9E0F4;
--color-morandi-200: #D8CAEB;
--color-morandi-300: #C4A8DC;
--color-morandi-400: #A07CC5;
--color-morandi-500: #8562AB;
--color-morandi-600: #6E4F93;
--color-morandi-700: #573D78;
--color-morandi-rose-100: #F3E8F0;
--color-morandi-rose-300: #D4A8C4;
--color-morandi-rose-400: #C48BB0;
--color-morandi-sage-100: #EDE6F2;
--color-morandi-sage-200: #D8CAEB;
--color-morandi-sage-400: #9B85B5;
--color-morandi-sage-500: #7E679A;
--color-morandi-sage-600: #6B5685;
--color-morandi-sage-700: #574472;
--color-morandi-slate-50: #F0EDF5;
--color-morandi-slate-100: #E5DFF0;
--color-morandi-slate-200: #D0C5E0;
--color-morandi-slate-500: #7B6B9E;
--color-morandi-sand-100: #F0ECE5;
--color-morandi-sand-400: #B8A88E;
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
-webkit-tap-highlight-color: transparent;
-webkit-overflow-scrolling: touch;
overscroll-behavior-y: contain;
}
/* 安全区域底部内边距 */
.pb-safe {
padding-bottom: env(safe-area-inset-bottom, 0px);
}
/**
* Default typography styles for HTML elements (h1-h4, p, label, button, input).
* These are in @layer base, so Tailwind utility classes (like text-sm, text-lg) automatically override them.
*/
html {
font-size: var(--font-size);
}
h1 {
font-size: var(--text-2xl);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
h2 {
font-size: var(--text-xl);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
h3 {
font-size: var(--text-lg);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
h4 {
font-size: var(--text-base);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
label {
font-size: var(--text-base);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
button {
font-size: var(--text-base);
font-weight: var(--font-weight-medium);
line-height: 1.5;
}
input {
font-size: var(--text-base);
font-weight: var(--font-weight-normal);
line-height: 1.5;
}
}

39
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,39 @@
import { defineConfig } from 'vite'
import path from 'path'
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'
import basicSsl from '@vitejs/plugin-basic-ssl'
export default defineConfig({
plugins: [
// The React and Tailwind plugins are both required for Make, even if
// Tailwind is not being actively used – do not remove them
react(),
tailwindcss(),
// basicSsl(), // disabled for cloudflare tunnel compatibility
],
resolve: {
alias: {
// Alias @ to the src directory
'@': path.resolve(__dirname, './src'),
},
},
// File types to support raw imports. Never add .css, .tsx, or .ts files to this.
assetsInclude: ['**/*.svg', '**/*.csv'],
server: {
host: '0.0.0.0',
allowedHosts: ['.trycloudflare.com', '.loca.lt'],
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
},
'/uploads': {
target: 'http://localhost:8000',
changeOrigin: true,
},
},
},
})