Initial commit: HealthCarePregnant project documentation and platform

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
selfrelease
2026-06-18 09:48:05 +08:00
commit eab91174db
301 changed files with 42491 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
node_modules
dist
.env
.env.local
*.log
.git
.DS_Store
Dockerfile
.dockerignore
+16
View File
@@ -0,0 +1,16 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs', 'vite.config.ts'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
},
};
+6
View File
@@ -0,0 +1,6 @@
node_modules
dist
dist-ssr
*.local
.DS_Store
.vite
+12
View File
@@ -0,0 +1,12 @@
# PCM 家属端静态镜像:Vite 构建 → nginx 托管
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:1.27-alpine AS runtime
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
+42
View File
@@ -0,0 +1,42 @@
# PCM 家属端 (family-app · T-8.2)
孕产个案管理平台 **家属端**(轻量移动 Web)。家属在获得授权后了解被照护孕妇的孕期状态、
接收关怀提醒、使用聊天问答。与孕妇端共享暖色低焦虑风格(`../../3-ui-style-PCM.md` §3/§6)。
## 技术栈
Vite + React 18 + TypeScript + react-router-dom。原生 CSS + 共享 Design Tokens。
## 开发
```bash
npm install
npm run dev # http://localhost:5175 /api 代理到后端 (默认 http://localhost:3000)
```
先启动后端:在 `../backend` 执行 `npm run start`
## 功能(T-8.2,对应 PRD §6 家属权限)
| 页面 | 说明 | 映射 |
|------|------|------|
| 登录/注册 | 家属注册须签署知情同意(未签拒绝注册) | NFR-1、T-1.1、REQ-13.2 |
| 绑定 | 通过「关怀码」(孕妇档案编号)绑定被照护孕妇 | 受授权查看(PRD §6)|
| 首页(关怀)| 孕妇状态卡(孕周/分期/风险/预产期/风险因素,**只读**)+ 聊天入口 + 提醒预览 | patient:read |
| 提醒 | 接收并查看关怀提醒列表 | 接收提醒(PRD §6)|
| 聊天 | RAG 问答,强制溯源、无依据提示就医 | knowledge:ask、REQ-7 |
| 我的 | 账号、绑定管理(解绑)、知情同意、退出 | — |
## 权限边界
家属为 **只读 + 接收 + 问答**:可查看获授权孕妇的状态与提醒、使用问答,
**不能**录入/修改孕妇健康数据或处置预警(与后端 RBAC `family: [patient:read, knowledge:ask]` 一致)。
## 绑定说明(MVP
当前通过「关怀码」= 孕妇档案编号绑定(孕妇分享给家属)。
正式的授权链路(孕妇主动授权 / 审批、解除授权回收可见性)列入 V2。
## 迁移到微信小程序
与孕妇端一致,可经 **Taro** 迁移到小程序,复用 Design Token、组件结构与 API 客户端。
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="zh-CN">
<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="theme-color" content="#fff7f3" />
<title>家属关怀</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+20
View File
@@ -0,0 +1,20 @@
# 家属端 nginxSPA 客户端路由回退 + /api 反向代理到后端
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://backend:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
try_files $uri $uri/ /index.html;
}
}
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
{
"name": "pcm-family-app",
"private": true,
"version": "0.1.0",
"type": "module",
"description": "PCM 孕产个案管理平台 · 家属端(轻量移动 Web,了解孕妇状况 + 接收提醒 + 问答)。可经 Taro 移植小程序。",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"lint": "eslint . --ext ts,tsx --max-warnings 0",
"typecheck": "tsc -b --noEmit"
},
"dependencies": {
"lucide-react": "^0.456.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2"
},
"devDependencies": {
"@types/react": "^18.3.11",
"@types/react-dom": "^18.3.0",
"@typescript-eslint/eslint-plugin": "^7.18.0",
"@typescript-eslint/parser": "^7.18.0",
"@vitejs/plugin-react": "^4.3.2",
"eslint": "^8.57.1",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-refresh": "^0.4.12",
"typescript": "^5.5.4",
"vite": "^5.4.8"
}
}
+81
View File
@@ -0,0 +1,81 @@
import { BrowserRouter, Navigate, Outlet, Route, Routes } from 'react-router-dom';
import { AuthProvider, useAuth } from './auth/AuthContext';
import { ToastProvider } from './components/Toast';
import { BottomNav } from './components/BottomNav';
import { LoginPage } from './pages/LoginPage';
import { HomePage } from './pages/HomePage';
import { RemindersPage } from './pages/RemindersPage';
import { ChatPage } from './pages/ChatPage';
import { MePage } from './pages/MePage';
import { OnboardingPage } from './pages/OnboardingPage';
function FullScreenLoading(): JSX.Element {
return (
<div className="app-shell">
<div className="page center" style={{ paddingTop: '40%' }}>
<p className="muted"></p>
</div>
</div>
);
}
function ProtectedLayout(): JSX.Element {
const { user, ready } = useAuth();
if (!ready) return <FullScreenLoading />;
if (!user) return <Navigate to="/login" replace />;
return (
<div className="app-shell">
<Outlet />
<BottomNav />
</div>
);
}
function ProtectedFull(): JSX.Element {
const { user, ready } = useAuth();
if (!ready) return <FullScreenLoading />;
if (!user) return <Navigate to="/login" replace />;
return (
<div className="app-shell">
<Outlet />
</div>
);
}
function PublicOnly({ children }: { children: JSX.Element }): JSX.Element {
const { user, ready } = useAuth();
if (!ready) return <FullScreenLoading />;
if (user) return <Navigate to="/home" replace />;
return children;
}
export function App(): JSX.Element {
return (
<AuthProvider>
<ToastProvider>
<BrowserRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
<Routes>
<Route
path="/login"
element={
<PublicOnly>
<LoginPage />
</PublicOnly>
}
/>
<Route path="/onboarding" element={<OnboardingPage />} />
<Route element={<ProtectedLayout />}>
<Route path="/home" element={<HomePage />} />
<Route path="/reminders" element={<RemindersPage />} />
<Route path="/me" element={<MePage />} />
</Route>
<Route element={<ProtectedFull />}>
<Route path="/chat" element={<ChatPage />} />
</Route>
<Route path="*" element={<Navigate to="/home" replace />} />
</Routes>
</BrowserRouter>
</ToastProvider>
</AuthProvider>
);
}
+78
View File
@@ -0,0 +1,78 @@
// 轻量 fetch 客户端:统一前缀、令牌注入、错误处理。
import type { AuthResult, PatientSummary, QaAnswer, Reminder } from './types';
const API_BASE = (import.meta.env.VITE_API_BASE as string | undefined) ?? '/api';
let authToken: string | null = null;
export function setAuthToken(token: string | null): void {
authToken = token;
}
export class ApiError extends Error {
constructor(
public status: number,
message: string,
) {
super(message);
this.name = 'ApiError';
}
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const headers = new Headers(init?.headers);
headers.set('Content-Type', 'application/json');
if (authToken) {
headers.set('Authorization', `Bearer ${authToken}`);
}
let res: Response;
try {
res = await fetch(`${API_BASE}${path}`, { ...init, headers });
} catch {
throw new ApiError(0, '无法连接服务器,请稍后再试');
}
if (!res.ok) {
let message = `请求失败 (${res.status})`;
try {
const body = (await res.json()) as { message?: string | string[] };
if (body?.message) {
message = Array.isArray(body.message) ? body.message.join('') : body.message;
}
} catch {
// 忽略非 JSON 响应体
}
throw new ApiError(res.status, message);
}
if (res.status === 204) return undefined as T;
return (await res.json()) as T;
}
export const api = {
register: (body: {
username: string;
password: string;
role: 'family';
consent?: boolean;
}): Promise<AuthResult> =>
request('/auth/register', { method: 'POST', body: JSON.stringify(body) }),
login: (username: string, password: string): Promise<AuthResult> =>
request('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) }),
// 家属:受授权查看被照护孕妇(patient:read
getPatient: (id: string): Promise<PatientSummary> => request(`/patients/${id}`),
// 按编号查找(家属凭关怀码/编号绑定)
lookupByNo: (no: string): Promise<PatientSummary> =>
request(`/patients/lookup?${new URLSearchParams({ no }).toString()}`),
// 接收提醒
listReminders: (patientId: string): Promise<Reminder[]> =>
request(`/patients/${patientId}/reminders`),
// 问答(knowledge:ask
ask: (q: string): Promise<QaAnswer> => request(`/ai/ask?${new URLSearchParams({ q }).toString()}`),
};
+73
View File
@@ -0,0 +1,73 @@
// 与后端契约一致的类型(家属端使用部分)。
export type Role = 'patient' | 'family' | 'case_manager' | 'physician' | 'operator' | 'admin';
export type RiskLevel = 'low' | 'medium' | 'high';
export type Trimester = 'first' | 'second' | 'third';
export interface AuthUser {
id: string;
username: string;
role: Role;
consentSigned: boolean;
}
export interface AuthResult {
token: string;
user: AuthUser;
}
export interface PatientSummary {
id: string;
patientNo: string;
name: string;
age: number;
heightCm?: number;
prePregnancyWeightKg?: number;
prePregnancyBmi?: number;
lmp: string;
edd: string;
multipleGestation: boolean;
historyGdm: boolean;
historyPih: boolean;
adversePregnancyHistory: boolean;
chronicConditions: boolean;
initialRiskLevel: RiskLevel;
initialRiskFactors: string[];
createdAt: string;
gestationalWeeks: number;
gestationalDays: number;
trimester: Trimester;
}
export type ReminderType =
| 'exercise'
| 'rest'
| 'water'
| 'medication'
| 'checkup'
| 'measurement';
export interface Reminder {
id: string;
patientId: string;
type: ReminderType;
effectiveType: ReminderType;
message: string;
adjustedForRisk: boolean;
scheduledAt: string;
createdAt: string;
}
export type AuthorityLevel = 'authoritative' | 'reference' | 'self';
export interface KnowledgeCitation {
id: string;
title: string;
source: string;
authority: AuthorityLevel;
}
export interface QaAnswer {
grounded: boolean;
answer: string;
citations: KnowledgeCitation[];
}
@@ -0,0 +1,110 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react';
import { api, setAuthToken } from '../api/client';
import type { AuthUser } from '../api/types';
import { clearSession, loadSession, saveSession, type Session } from './session';
interface AuthContextValue {
user: AuthUser | null;
token: string | null;
boundPatientId: string | null;
ready: boolean;
login: (username: string, password: string) => Promise<void>;
register: (input: { username: string; password: string; consent: boolean }) => Promise<void>;
logout: () => void;
bindPatient: (patientId: string) => void;
unbindPatient: () => void;
}
const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: ReactNode }): JSX.Element {
const [session, setSession] = useState<Session | null>(null);
const [ready, setReady] = useState(false);
useEffect(() => {
const existing = loadSession();
if (existing) {
setAuthToken(existing.token);
setSession(existing);
}
setReady(true);
}, []);
const persist = useCallback((next: Session) => {
setAuthToken(next.token);
saveSession(next);
setSession(next);
}, []);
const login = useCallback(
async (username: string, password: string) => {
const result = await api.login(username, password);
persist({ token: result.token, user: result.user, boundPatientId: null });
},
[persist],
);
const register = useCallback(
async (input: { username: string; password: string; consent: boolean }) => {
const result = await api.register({ ...input, role: 'family' });
persist({ token: result.token, user: result.user, boundPatientId: null });
},
[persist],
);
const logout = useCallback(() => {
setAuthToken(null);
clearSession();
setSession(null);
}, []);
const bindPatient = useCallback((patientId: string) => {
setSession((prev) => {
if (!prev) return prev;
const next = { ...prev, boundPatientId: patientId };
saveSession(next);
return next;
});
}, []);
const unbindPatient = useCallback(() => {
setSession((prev) => {
if (!prev) return prev;
const next = { ...prev, boundPatientId: null };
saveSession(next);
return next;
});
}, []);
const value = useMemo<AuthContextValue>(
() => ({
user: session?.user ?? null,
token: session?.token ?? null,
boundPatientId: session?.boundPatientId ?? null,
ready,
login,
register,
logout,
bindPatient,
unbindPatient,
}),
[session, ready, login, register, logout, bindPatient, unbindPatient],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
// eslint-disable-next-line react-refresh/only-export-components
export function useAuth(): AuthContextValue {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
return ctx;
}
@@ -0,0 +1,27 @@
import type { AuthUser } from '../api/types';
const KEY = 'pcm.family.session';
export interface Session {
token: string;
user: AuthUser;
/** 绑定的被照护孕妇档案 ID(家属受授权查看) */
boundPatientId: string | null;
}
export function loadSession(): Session | null {
try {
const raw = localStorage.getItem(KEY);
return raw ? (JSON.parse(raw) as Session) : null;
} catch {
return null;
}
}
export function saveSession(session: Session): void {
localStorage.setItem(KEY, JSON.stringify(session));
}
export function clearSession(): void {
localStorage.removeItem(KEY);
}
@@ -0,0 +1,58 @@
import { useState } from 'react';
import { api, ApiError } from '../api/client';
import { useAuth } from '../auth/AuthContext';
import { useToast } from './Toast';
/**
* 绑定被照护孕妇(家属受授权查看,PRD §6)。
* MVP:通过"关怀码"(孕妇档案编号)绑定;正式授权链路(孕妇主动授权/审批)列入 V2。
*/
export function BindPatient({ onBound }: { onBound?: () => void }): JSX.Element {
const { bindPatient } = useAuth();
const { show } = useToast();
const [code, setCode] = useState('');
const [checking, setChecking] = useState(false);
async function submit(e: React.FormEvent): Promise<void> {
e.preventDefault();
const value = code.trim();
if (!value) {
show('请输入关怀码');
return;
}
setChecking(true);
try {
// 凭编号(关怀码)解析孕妇档案
const p = await api.lookupByNo(value);
bindPatient(p.id);
show(`已绑定:${p.name}`);
onBound?.();
} catch (err) {
show(err instanceof ApiError ? err.message : '绑定失败,请确认关怀码');
} finally {
setChecking(false);
}
}
return (
<form className="card" onSubmit={submit}>
<h2 className="section-title" style={{ marginTop: 0 }}>
怀
</h2>
<p className="muted" style={{ marginBottom: 16 }}>
怀怀
</p>
<div className="field">
<label>怀</label>
<input
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="如 PCM-000001"
/>
</div>
<button className="btn btn-primary btn-block" type="submit" disabled={checking}>
{checking ? '绑定中…' : '绑定'}
</button>
</form>
);
}
@@ -0,0 +1,44 @@
.bottom-nav {
position: fixed;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 100%;
max-width: var(--max-width);
height: var(--nav-height);
background: var(--color-surface);
border-top: 1px solid var(--color-border);
display: flex;
align-items: stretch;
box-shadow: 0 -2px 12px rgba(214, 158, 138, 0.08);
z-index: 40;
padding-bottom: env(safe-area-inset-bottom);
}
.bottom-nav__item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 2px;
color: var(--color-text-soft);
font-size: var(--font-xs);
}
.bottom-nav__item.is-active {
color: var(--color-primary-strong);
}
.bottom-nav__icon {
font-size: 22px;
line-height: 1;
}
/* SVG 图标对齐 */
.bottom-nav__icon {
display: flex;
align-items: center;
justify-content: center;
height: 24px;
}
@@ -0,0 +1,28 @@
import { NavLink } from 'react-router-dom';
import { Bell, Heart, UserRound, type LucideIcon } from 'lucide-react';
import './BottomNav.css';
const TABS: { to: string; label: string; icon: LucideIcon }[] = [
{ to: '/home', label: '关怀', icon: Heart },
{ to: '/reminders', label: '提醒', icon: Bell },
{ to: '/me', label: '我', icon: UserRound },
];
export function BottomNav(): JSX.Element {
return (
<nav className="bottom-nav">
{TABS.map((t) => (
<NavLink
key={t.to}
to={t.to}
className={({ isActive }) => `bottom-nav__item${isActive ? ' is-active' : ''}`}
>
<span className="bottom-nav__icon" aria-hidden>
<t.icon size={22} strokeWidth={1.75} />
</span>
<span className="bottom-nav__label">{t.label}</span>
</NavLink>
))}
</nav>
);
}
@@ -0,0 +1,30 @@
import { createContext, useCallback, useContext, useState, type ReactNode } from 'react';
interface ToastContextValue {
show: (message: string) => void;
}
const ToastContext = createContext<ToastContextValue | null>(null);
export function ToastProvider({ children }: { children: ReactNode }): JSX.Element {
const [message, setMessage] = useState<string | null>(null);
const show = useCallback((msg: string) => {
setMessage(msg);
window.setTimeout(() => setMessage(null), 2600);
}, []);
return (
<ToastContext.Provider value={{ show }}>
{children}
{message && <div className="toast">{message}</div>}
</ToastContext.Provider>
);
}
// eslint-disable-next-line react-refresh/only-export-components
export function useToast(): ToastContextValue {
const ctx = useContext(ToastContext);
if (!ctx) throw new Error('useToast must be used within ToastProvider');
return ctx;
}
+46
View File
@@ -0,0 +1,46 @@
import type { RiskLevel } from '../api/types';
export function riskLabel(level: RiskLevel): string {
return { low: '低风险', medium: '中风险', high: '高风险' }[level];
}
export function riskBadgeClass(level: RiskLevel): string {
return { low: 'badge-ok', medium: 'badge-warn', high: 'badge-danger' }[level];
}
const REMINDER_LABELS: Record<string, string> = {
exercise: '运动',
rest: '休息',
water: '喝水',
medication: '服药',
checkup: '产检',
measurement: '监测打卡',
};
export function reminderLabel(type: string): string {
return REMINDER_LABELS[type] ?? type;
}
export function trimesterLabel(t: string): string {
return { first: '孕早期', second: '孕中期', third: '孕晚期' }[t] ?? t;
}
export function formatTime(iso: string): string {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return iso;
const pad = (n: number): string => String(n).padStart(2, '0');
return `${d.getMonth() + 1}${d.getDate()}${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
export function formatDate(iso: string): string {
return iso?.slice(0, 10) ?? '';
}
export function greeting(): string {
const h = new Date().getHours();
if (h < 6) return '夜深了';
if (h < 11) return '早上好';
if (h < 14) return '中午好';
if (h < 18) return '下午好';
return '晚上好';
}
@@ -0,0 +1,42 @@
import { useEffect, useRef } from 'react';
interface Options {
/** 轮询间隔(毫秒)。默认 20s。 */
intervalMs?: number;
/** 是否启用。默认 true。 */
enabled?: boolean;
}
/**
* 多端数据一致同步(T-8.5):以单一后端为真源,前端通过
* - 窗口 focus / 标签可见(visibilitychange
* - 可见时定时轮询
* 触发静默刷新,使本端近实时收敛到其他端的改动。
*
* 注:V1 为"拉取式"近实时;实时推送(WebSocket/SSE)列入 V2。
*/
export function useAutoRefresh(refresh: () => void, options?: Options): void {
const intervalMs = options?.intervalMs ?? 20000;
const enabled = options?.enabled ?? true;
const saved = useRef(refresh);
useEffect(() => {
saved.current = refresh;
}, [refresh]);
useEffect(() => {
if (!enabled) return;
const refreshIfVisible = (): void => {
if (document.visibilityState === 'visible') saved.current();
};
const onFocus = (): void => saved.current();
window.addEventListener('focus', onFocus);
document.addEventListener('visibilitychange', refreshIfVisible);
const id = window.setInterval(refreshIfVisible, intervalMs);
return () => {
window.removeEventListener('focus', onFocus);
document.removeEventListener('visibilitychange', refreshIfVisible);
window.clearInterval(id);
};
}, [intervalMs, enabled]);
}
@@ -0,0 +1,39 @@
import { useCallback, useEffect, useState } from 'react';
import { api, ApiError } from '../api/client';
import type { PatientSummary } from '../api/types';
import { useAuth } from '../auth/AuthContext';
interface UsePatientResult {
patient: PatientSummary | null;
loading: boolean;
error: string | null;
reload: () => void;
}
/** 加载家属绑定的被照护孕妇档案。未绑定时 patient 为 null。 */
export function usePatient(): UsePatientResult {
const { boundPatientId } = useAuth();
const [patient, setPatient] = useState<PatientSummary | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const reload = useCallback(() => {
if (!boundPatientId) {
setPatient(null);
return;
}
setLoading(true);
setError(null);
api
.getPatient(boundPatientId)
.then(setPatient)
.catch((err) => setError(err instanceof ApiError ? err.message : '加载孕妇信息失败'))
.finally(() => setLoading(false));
}, [boundPatientId]);
useEffect(() => {
reload();
}, [reload]);
return { patient, loading, error, reload };
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { App } from './App';
import './styles/global.css';
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
@@ -0,0 +1,126 @@
.chat {
display: flex;
flex-direction: column;
height: 100vh;
height: 100dvh;
}
.chat__header {
display: flex;
align-items: center;
gap: var(--space-3);
padding: var(--space-4);
background: var(--color-surface);
border-bottom: 1px solid var(--color-border);
font-weight: 700;
font-size: var(--font-lg);
}
.chat__back {
font-size: 22px;
width: 32px;
color: var(--color-text);
}
.chat__list {
flex: 1;
overflow-y: auto;
padding: var(--space-4);
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.chat__row {
display: flex;
}
.chat__row--user {
justify-content: flex-end;
}
.chat__row--assistant {
justify-content: flex-start;
}
.chat__bubble {
max-width: 82%;
padding: 12px 14px;
border-radius: var(--radius-lg);
font-size: var(--font-md);
line-height: 1.6;
box-shadow: var(--shadow-card);
}
.chat__bubble--user {
background: var(--color-primary);
color: var(--color-text-inverse);
border-bottom-right-radius: 6px;
}
.chat__bubble--assistant {
background: var(--color-surface);
border-bottom-left-radius: 6px;
}
.chat__typing {
color: var(--color-text-soft);
}
.chat__nogrounded {
margin-top: 8px;
padding: 8px 10px;
background: var(--color-warn-soft);
color: var(--color-warn);
border-radius: var(--radius-sm);
font-size: var(--font-sm);
}
.chat__citations {
margin-top: 10px;
padding-top: 10px;
border-top: 1px dashed var(--color-border);
}
.chat__citations-title {
font-size: var(--font-xs);
color: var(--color-text-soft);
margin-bottom: 6px;
}
.chat__citation {
display: flex;
align-items: flex-start;
gap: var(--space-2);
margin-bottom: 6px;
}
.chat__citation-text {
font-size: var(--font-sm);
}
.chat__input {
display: flex;
gap: var(--space-2);
padding: var(--space-3) var(--space-4);
padding-bottom: calc(var(--space-3) + env(safe-area-inset-bottom));
background: var(--color-surface);
border-top: 1px solid var(--color-border);
}
.chat__input input {
flex: 1;
padding: 12px 16px;
border-radius: var(--radius-pill);
border: 1px solid var(--color-border);
background: var(--color-bg);
}
.chat__input input:focus {
outline: none;
border-color: var(--color-primary);
}
/* SVG 图标对齐 */
.chat__back {
display: flex;
align-items: center;
justify-content: center;
}
.chat__nogrounded {
display: flex;
align-items: center;
gap: 6px;
}
.chat__nogrounded svg {
flex-shrink: 0;
}
@@ -0,0 +1,128 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft, AlertTriangle } from 'lucide-react';
import { api, ApiError } from '../api/client';
import type { KnowledgeCitation } from '../api/types';
import './ChatPage.css';
interface Message {
id: string;
role: 'user' | 'assistant';
text: string;
grounded?: boolean;
citations?: KnowledgeCitation[];
}
const AUTHORITY_LABEL: Record<string, string> = {
authoritative: '权威',
reference: '参考',
self: '自建',
};
const WELCOME: Message = {
id: 'welcome',
role: 'assistant',
text: '你好呀~我是孕期助手。作为家属,关于孕期照护、饮食、注意事项,都可以问我。我会附上知识来源,遇到拿不准的会建议及时就医。',
};
export function ChatPage(): JSX.Element {
const navigate = useNavigate();
const [messages, setMessages] = useState<Message[]>([WELCOME]);
const [input, setInput] = useState('');
const [sending, setSending] = useState(false);
const listRef = useRef<HTMLDivElement>(null);
async function send(question: string): Promise<void> {
const q = question.trim();
if (!q || sending) return;
setMessages((prev) => [...prev, { id: `u-${Date.now()}`, role: 'user', text: q }]);
setInput('');
setSending(true);
try {
const answer = await api.ask(q);
setMessages((prev) => [
...prev,
{
id: `a-${Date.now()}`,
role: 'assistant',
text: answer.answer,
grounded: answer.grounded,
citations: answer.citations,
},
]);
} catch (err) {
setMessages((prev) => [
...prev,
{
id: `e-${Date.now()}`,
role: 'assistant',
text: err instanceof ApiError ? err.message : '抱歉,我暂时没能回答,请稍后再试。',
},
]);
} finally {
setSending(false);
}
}
useEffect(() => {
listRef.current?.scrollTo({ top: listRef.current.scrollHeight, behavior: 'smooth' });
}, [messages]);
return (
<div className="chat">
<header className="chat__header">
<button className="chat__back" onClick={() => navigate(-1)} type="button" aria-label="返回">
<ArrowLeft size={22} strokeWidth={1.75} />
</button>
<span></span>
</header>
<div className="chat__list" ref={listRef}>
{messages.map((m) => (
<div key={m.id} className={`chat__row chat__row--${m.role}`}>
<div className={`chat__bubble chat__bubble--${m.role}`}>
<p>{m.text}</p>
{m.role === 'assistant' && m.grounded === false && (
<p className="chat__nogrounded">
<AlertTriangle size={15} strokeWidth={1.9} />
</p>
)}
{m.citations && m.citations.length > 0 && (
<div className="chat__citations">
<p className="chat__citations-title"></p>
{m.citations.map((c) => (
<div key={c.id} className="chat__citation">
<span className="badge badge-ok">{AUTHORITY_LABEL[c.authority] ?? c.authority}</span>
<span className="chat__citation-text">
{c.title}
<span className="muted"> · {c.source}</span>
</span>
</div>
))}
</div>
)}
</div>
</div>
))}
{sending && (
<div className="chat__row chat__row--assistant">
<div className="chat__bubble chat__bubble--assistant chat__typing"></div>
</div>
)}
</div>
<form
className="chat__input"
onSubmit={(e) => {
e.preventDefault();
void send(input);
}}
>
<input value={input} onChange={(e) => setInput(e.target.value)} placeholder="问问孕期助手…" />
<button className="btn btn-primary" type="submit" disabled={sending || !input.trim()}>
</button>
</form>
</div>
);
}
@@ -0,0 +1,196 @@
.home__greet {
margin: var(--space-2) 0 var(--space-4);
}
.home__hello {
font-size: var(--font-xl);
font-weight: 600;
display: inline-flex;
align-items: center;
gap: 6px;
}
.home__hello svg {
color: var(--color-primary-strong);
}
.home__sub {
font-size: var(--font-md);
}
/* ===== 状态卡片 ===== */
.home__status {
margin-bottom: var(--space-5);
border-radius: var(--radius-xl);
}
.home__status-top {
display: flex;
align-items: center;
gap: var(--space-3);
}
.home__avatar {
width: 48px;
height: 48px;
border-radius: 50%;
background: var(--gradient-primary);
display: flex;
align-items: center;
justify-content: center;
color: #fff;
flex-shrink: 0;
box-shadow: 0 4px 12px rgba(244, 143, 177, 0.4);
}
.home__name {
font-size: var(--font-lg);
font-weight: 700;
}
.home__status-top .badge {
margin-left: auto;
}
.home__status-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--space-3);
margin-top: var(--space-4);
padding-top: var(--space-4);
border-top: 1px solid var(--color-border);
}
.home__k {
font-size: var(--font-xs);
margin-bottom: 2px;
}
.home__v {
font-weight: 600;
}
.home__factors {
margin-top: var(--space-3);
padding-top: var(--space-3);
border-top: 1px solid var(--color-border);
}
.home__factor {
margin: 4px 6px 0 0;
}
/* ===== 渐变 Hero ===== */
.home__hero {
position: relative;
width: 100%;
display: flex;
align-items: center;
gap: var(--space-3);
padding: 18px 22px;
border-radius: var(--radius-xl);
background: var(--gradient-hero);
box-shadow: var(--shadow-hero);
color: #fff;
text-align: left;
overflow: hidden;
margin-bottom: var(--space-5);
}
.home__hero-glow {
position: absolute;
inset: 0;
background:
radial-gradient(120px 120px at 88% -10%, rgba(255, 255, 255, 0.45), transparent 70%),
radial-gradient(140px 140px at 10% 120%, rgba(255, 255, 255, 0.22), transparent 70%);
pointer-events: none;
}
.home__hero-body {
position: relative;
flex: 1;
display: flex;
flex-direction: column;
gap: 3px;
}
.home__hero-eyebrow {
display: inline-flex;
align-items: center;
gap: 5px;
font-size: var(--font-xs);
font-weight: 600;
opacity: 0.92;
}
.home__hero-title {
font-size: var(--font-lg);
font-weight: 700;
}
.home__hero-sub {
font-size: var(--font-sm);
opacity: 0.9;
}
.home__hero-cta {
position: relative;
flex-shrink: 0;
width: 42px;
height: 42px;
border-radius: 50%;
background: rgba(255, 255, 255, 0.25);
display: flex;
align-items: center;
justify-content: center;
}
/* ===== 提醒预览(柔彩色调) ===== */
[data-tone='peach'] {
--tone-bg: var(--c-peach);
--tone-ink: var(--c-peach-ink);
}
[data-tone='rose'] {
--tone-bg: var(--c-rose);
--tone-ink: var(--c-rose-ink);
}
[data-tone='mint'] {
--tone-bg: var(--c-mint);
--tone-ink: var(--c-mint-ink);
}
[data-tone='lilac'] {
--tone-bg: var(--c-lilac);
--tone-ink: var(--c-lilac-ink);
}
[data-tone='sky'] {
--tone-bg: var(--c-sky);
--tone-ink: var(--c-sky-ink);
}
.home__rem-head {
display: flex;
align-items: center;
justify-content: space-between;
}
.home__more-link {
color: var(--color-primary-strong);
font-size: var(--font-sm);
font-weight: 600;
display: inline-flex;
align-items: center;
gap: 2px;
}
.home__rem-item {
display: flex;
align-items: center;
gap: var(--space-3);
margin-bottom: var(--space-2);
background: var(--tone-bg, var(--color-surface-soft));
border-radius: var(--radius-lg);
padding: var(--space-3) var(--space-4);
}
.home__rem-chip {
flex-shrink: 0;
width: 36px;
height: 36px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.75);
display: flex;
align-items: center;
justify-content: center;
color: var(--tone-ink, var(--color-primary-strong));
}
.home__rem-type {
font-weight: 700;
}
.home__rem-msg {
font-size: var(--font-sm);
color: var(--color-text-soft);
}
.home__tip {
margin-top: var(--space-5);
font-size: var(--font-xs);
}
@@ -0,0 +1,184 @@
import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
Activity,
Armchair,
ArrowRight,
Bell,
CalendarCheck,
ChevronRight,
Droplet,
Footprints,
HeartPulse,
Pill,
Sparkles,
UserRound,
type LucideIcon,
} from 'lucide-react';
import { api } from '../api/client';
import { useAuth } from '../auth/AuthContext';
import { usePatient } from '../lib/usePatient';
import { useAutoRefresh } from '../lib/useAutoRefresh';
import { BindPatient } from '../components/BindPatient';
import type { Reminder } from '../api/types';
import {
formatDate,
greeting,
reminderLabel,
riskBadgeClass,
riskLabel,
trimesterLabel,
} from '../lib/format';
import './HomePage.css';
const REM: Record<string, { icon: LucideIcon; tone: string }> = {
measurement: { icon: Activity, tone: 'rose' },
water: { icon: Droplet, tone: 'sky' },
exercise: { icon: Footprints, tone: 'mint' },
rest: { icon: Armchair, tone: 'lilac' },
checkup: { icon: CalendarCheck, tone: 'peach' },
medication: { icon: Pill, tone: 'rose' },
};
export function HomePage(): JSX.Element {
const navigate = useNavigate();
const { boundPatientId } = useAuth();
const { patient, loading, reload } = usePatient();
const [reminders, setReminders] = useState<Reminder[]>([]);
const loadReminders = useCallback(() => {
if (!boundPatientId) return;
void api.listReminders(boundPatientId).then((list) => setReminders([...list].reverse()));
}, [boundPatientId]);
useEffect(() => {
loadReminders();
}, [loadReminders]);
// 多端一致:医护更新的状态/提醒近实时反映给家属
useAutoRefresh(() => {
loadReminders();
reload();
});
if (!boundPatientId || (!patient && !loading)) {
return (
<div className="page">
<h1 className="section-title" style={{ marginTop: 0 }}>
</h1>
<BindPatient onBound={reload} />
</div>
);
}
if (!patient) {
return (
<div className="page center" style={{ paddingTop: '30%' }}>
<p className="muted"></p>
</div>
);
}
return (
<div className="page home">
<header className="home__greet">
<p className="home__hello">
{greeting()} <HeartPulse size={20} strokeWidth={1.75} />
</p>
<p className="home__sub muted"> {patient.name} </p>
</header>
{/* 状态卡片 */}
<div className="home__status card">
<div className="home__status-top">
<div className="home__avatar" aria-hidden>
<UserRound size={26} strokeWidth={1.5} />
</div>
<div>
<p className="home__name">{patient.name}</p>
<p className="muted">
{patient.gestationalWeeks} {patient.gestationalDays} ·{' '}
{trimesterLabel(patient.trimester)}
</p>
</div>
<span className={`badge ${riskBadgeClass(patient.initialRiskLevel)}`}>
{riskLabel(patient.initialRiskLevel)}
</span>
</div>
<div className="home__status-grid">
<div>
<p className="muted home__k"></p>
<p className="home__v">{formatDate(patient.edd)}</p>
</div>
<div>
<p className="muted home__k"> BMI</p>
<p className="home__v">
{patient.prePregnancyBmi != null ? patient.prePregnancyBmi.toFixed(1) : '—'}
</p>
</div>
</div>
{patient.initialRiskFactors.length > 0 && (
<div className="home__factors">
<p className="muted home__k"></p>
<div>
{patient.initialRiskFactors.map((f, i) => (
<span key={i} className="badge badge-warn home__factor">
{f}
</span>
))}
</div>
</div>
)}
</div>
{/* 渐变 Hero 聊天主入口 */}
<button className="home__hero" onClick={() => navigate('/chat')} type="button">
<div className="home__hero-glow" aria-hidden />
<div className="home__hero-body">
<span className="home__hero-eyebrow">
<Sparkles size={14} strokeWidth={2} /> AI
</span>
<span className="home__hero-title"></span>
<span className="home__hero-sub"></span>
</div>
<span className="home__hero-cta" aria-hidden>
<ArrowRight size={22} strokeWidth={2.2} />
</span>
</button>
{/* 提醒预览 */}
<div className="home__rem-head">
<h2 className="section-title" style={{ margin: 0 }}>
怀
</h2>
<button className="home__more-link" onClick={() => navigate('/reminders')} type="button">
<ChevronRight size={15} strokeWidth={1.9} />
</button>
</div>
{reminders.length === 0 ? (
<p className="muted"></p>
) : (
reminders.slice(0, 3).map((r) => {
const meta = REM[r.effectiveType] ?? { icon: Bell, tone: 'peach' };
const Icon = meta.icon;
return (
<div key={r.id} className="home__rem-item" data-tone={meta.tone}>
<span className="home__rem-chip">
<Icon size={18} strokeWidth={1.9} />
</span>
<div className="home__rem-text">
<p className="home__rem-type">{reminderLabel(r.effectiveType)}</p>
<p className="home__rem-msg">{r.message}</p>
</div>
</div>
);
})
)}
<p className="home__tip muted center">
</p>
</div>
);
}
@@ -0,0 +1,105 @@
.login {
display: flex;
flex-direction: column;
padding-top: var(--space-6);
}
.login__hero {
text-align: center;
margin-bottom: var(--space-5);
}
.login__logo {
font-size: 56px;
line-height: 1;
}
.login__hero h1 {
font-size: var(--font-xxl);
margin-top: var(--space-2);
}
.login__tabs {
display: flex;
background: var(--color-surface-soft);
border-radius: var(--radius-pill);
padding: 4px;
margin-bottom: var(--space-4);
}
.login__tabs button {
flex: 1;
padding: 10px;
border-radius: var(--radius-pill);
font-weight: 600;
color: var(--color-text-soft);
}
.login__tabs button.is-active {
background: var(--color-surface);
color: var(--color-primary-strong);
box-shadow: var(--shadow-card);
}
.login__consent {
display: flex;
align-items: flex-start;
gap: var(--space-2);
font-size: var(--font-sm);
color: var(--color-text-soft);
margin-bottom: var(--space-4);
}
.login__consent input {
margin-top: 4px;
}
.login__consent a {
color: var(--color-primary-strong);
text-decoration: underline;
}
.login__hint {
margin-top: var(--space-4);
font-size: var(--font-xs);
}
.login__demo-panel {
margin-top: var(--space-4);
padding: var(--space-3) var(--space-4);
border: 1px dashed var(--color-primary-light, #ffd3e0);
background-color: var(--color-surface-soft, #fff5f7);
}
.login__demo-title {
font-size: var(--font-sm);
font-weight: 600;
color: var(--color-primary-strong, #c2185b);
margin-bottom: var(--space-2);
}
.login__demo-buttons {
display: flex;
gap: var(--space-2);
margin-bottom: var(--space-2);
}
.login__demo-buttons .btn {
flex: 1;
padding: 6px 12px;
font-size: var(--font-xs);
border-radius: var(--radius-md, 8px);
}
.login__demo-desc {
font-size: 11px;
line-height: 1.4;
color: var(--color-text-muted, #757575);
}
/* SVG 图标 */
.login__logo {
color: var(--color-primary-strong);
display: flex;
justify-content: center;
}
.login__demo-title {
display: flex;
align-items: center;
gap: 6px;
}
@@ -0,0 +1,145 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { HeartPulse, Lightbulb } from 'lucide-react';
import { useAuth } from '../auth/AuthContext';
import { useToast } from '../components/Toast';
import { ApiError } from '../api/client';
import './LoginPage.css';
type Mode = 'login' | 'register';
export function LoginPage(): JSX.Element {
const { login, register } = useAuth();
const { show } = useToast();
const navigate = useNavigate();
const [mode, setMode] = useState<Mode>('login');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [consent, setConsent] = useState(false);
const [submitting, setSubmitting] = useState(false);
async function handleSubmit(e: React.FormEvent): Promise<void> {
e.preventDefault();
if (!username.trim() || !password) {
show('请填写用户名和密码');
return;
}
if (mode === 'register' && !consent) {
show('请先阅读并签署知情同意');
return;
}
setSubmitting(true);
try {
if (mode === 'login') {
await login(username.trim(), password);
} else {
await register({ username: username.trim(), password, consent });
}
navigate('/home', { replace: true });
} catch (err) {
show(err instanceof ApiError ? err.message : '操作失败,请重试');
} finally {
setSubmitting(false);
}
}
function fillDemoUser(usernameVal: string, passwordVal: string) {
setUsername(usernameVal);
setPassword(passwordVal);
setConsent(true);
}
return (
<div className="app-shell">
<div className="page login">
<div className="login__hero">
<div className="login__logo" aria-hidden>
<HeartPulse size={48} strokeWidth={1.5} />
</div>
<h1>怀</h1>
<p className="muted"></p>
</div>
<div className="login__tabs">
<button
className={mode === 'login' ? 'is-active' : ''}
onClick={() => setMode('login')}
type="button"
>
</button>
<button
className={mode === 'register' ? 'is-active' : ''}
onClick={() => setMode('register')}
type="button"
>
</button>
</div>
<form className="card" onSubmit={handleSubmit}>
<div className="field">
<label></label>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="请输入用户名"
autoComplete="username"
/>
</div>
<div className="field">
<label></label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="请输入密码"
autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
/>
</div>
{mode === 'register' && (
<label className="login__consent">
<input
type="checkbox"
checked={consent}
onChange={(e) => setConsent(e.target.checked)}
/>
<span>
<a href="/onboarding" onClick={(e) => e.stopPropagation()}>
</a>
</span>
</label>
)}
<button className="btn btn-primary btn-block" type="submit" disabled={submitting}>
{submitting ? '请稍候…' : mode === 'login' ? '登录' : '注册并开始'}
</button>
</form>
<div className="login__demo-panel card">
<p className="login__demo-title">
<Lightbulb size={16} strokeWidth={1.75} />
</p>
<div className="login__demo-buttons">
<button
type="button"
className="btn btn-outline btn-sm"
onClick={() => fillDemoUser('test_family_01', '12345678')}
>
01
</button>
</div>
<p className="login__demo-desc muted">
*
</p>
</div>
<p className="muted center login__hint">使</p>
</div>
</div>
);
}
@@ -0,0 +1,85 @@
/* ===== 渐变 Profile Hero ===== */
.me__hero {
position: relative;
display: flex;
align-items: center;
gap: var(--space-4);
padding: var(--space-5);
margin: var(--space-2) 0 var(--space-5);
border-radius: var(--radius-xl);
background: var(--gradient-hero);
box-shadow: var(--shadow-hero);
color: #fff;
overflow: hidden;
}
.me__hero-glow {
position: absolute;
inset: 0;
background:
radial-gradient(130px 130px at 90% -20%, rgba(255, 255, 255, 0.4), transparent 70%),
radial-gradient(150px 150px at 5% 130%, rgba(255, 255, 255, 0.2), transparent 70%);
pointer-events: none;
}
.me__hero-info {
position: relative;
}
.me__hero-meta {
font-size: var(--font-sm);
opacity: 0.92;
margin-top: 2px;
}
.me__avatar {
position: relative;
width: 64px;
height: 64px;
border-radius: 50%;
background: rgba(255, 255, 255, 0.28);
backdrop-filter: blur(4px);
display: flex;
align-items: center;
justify-content: center;
color: #fff;
flex-shrink: 0;
}
.me__name {
font-size: var(--font-xl);
font-weight: 700;
}
.me__bound-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 0;
border-bottom: 1px solid var(--color-border);
}
.me__bound-row:last-of-type {
border-bottom: none;
}
.me__code {
font-family: monospace;
font-size: var(--font-sm);
}
.me__list {
padding: 0;
}
.me__list-item {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
padding: var(--space-4);
border-bottom: 1px solid var(--color-border);
font-size: var(--font-md);
}
.me__list-item:last-child {
border-bottom: none;
}
/* SVG 图标 */
.me__list-right {
display: inline-flex;
align-items: center;
gap: 4px;
}
@@ -0,0 +1,92 @@
import { useNavigate } from 'react-router-dom';
import { ChevronRight, HeartPulse } from 'lucide-react';
import { useAuth } from '../auth/AuthContext';
import { usePatient } from '../lib/usePatient';
import { useToast } from '../components/Toast';
import { BindPatient } from '../components/BindPatient';
import './MePage.css';
export function MePage(): JSX.Element {
const { user, boundPatientId, unbindPatient, logout } = useAuth();
const { patient, loading, reload } = usePatient();
const { show } = useToast();
const navigate = useNavigate();
return (
<div className="page">
<header className="me__hero">
<div className="me__hero-glow" aria-hidden />
<div className="me__avatar" aria-hidden>
<HeartPulse size={34} strokeWidth={1.5} />
</div>
<div className="me__hero-info">
<p className="me__name">{user?.username}</p>
<p className="me__hero-meta">{patient ? ` · 关怀 ${patient.name}` : ''}</p>
</div>
</header>
<h2 className="section-title" style={{ marginTop: 0 }}>
怀
</h2>
{!boundPatientId || (!patient && !loading) ? (
<BindPatient onBound={reload} />
) : (
patient && (
<div className="card me__bound">
<div className="me__bound-row">
<span className="muted"></span>
<span>{patient.name}</span>
</div>
<div className="me__bound-row">
<span className="muted"></span>
<span>
{patient.gestationalWeeks} {patient.gestationalDays}
</span>
</div>
<div className="me__bound-row">
<span className="muted">怀</span>
<span className="me__code">{patient.patientNo}</span>
</div>
<button
className="btn btn-ghost btn-block"
style={{ marginTop: 12 }}
onClick={() => {
unbindPatient();
show('已解除绑定');
}}
type="button"
>
</button>
</div>
)
)}
<h2 className="section-title"></h2>
<div className="card me__list">
<button className="me__list-item" onClick={() => navigate('/onboarding')} type="button">
<span></span>
<span className="me__list-right muted">
{user?.consentSigned ? '已签署' : '查看'}
<ChevronRight size={16} strokeWidth={1.75} />
</span>
</button>
<button className="me__list-item" onClick={() => navigate('/chat')} type="button">
<span></span>
<span className="me__list-right muted">
<ChevronRight size={16} strokeWidth={1.75} />
</span>
</button>
</div>
<button
className="btn btn-ghost btn-block"
style={{ marginTop: 24 }}
onClick={logout}
type="button"
>
退
</button>
</div>
);
}
@@ -0,0 +1,39 @@
import { useNavigate } from 'react-router-dom';
import { ArrowLeft } from 'lucide-react';
export function OnboardingPage(): JSX.Element {
const navigate = useNavigate();
return (
<div className="app-shell">
<div className="page">
<button className="btn btn-ghost" onClick={() => navigate(-1)} type="button">
<ArrowLeft size={18} strokeWidth={1.75} />
</button>
<h1 className="section-title"></h1>
<div className="card" style={{ lineHeight: 1.8 }}>
<p>
使怀怀便
</p>
<p style={{ marginTop: 12 }}></p>
<ul style={{ paddingLeft: 20, marginTop: 8 }}>
<li></li>
<li>访</li>
<li>怀</li>
<li></li>
</ul>
<p style={{ marginTop: 12 }} className="muted">
</p>
</div>
<button
className="btn btn-primary btn-block"
style={{ marginTop: 16 }}
onClick={() => navigate(-1)}
type="button"
>
</button>
</div>
</div>
);
}
@@ -0,0 +1,37 @@
.rem-card {
display: flex;
align-items: center;
gap: var(--space-3);
background: var(--color-surface);
border-radius: var(--radius-lg);
padding: var(--space-4);
margin-bottom: var(--space-3);
box-shadow: var(--shadow-card);
}
.rem-card__icon {
font-size: 28px;
}
.rem-card__body {
flex: 1;
}
.rem-card__title {
font-weight: 700;
display: flex;
align-items: center;
gap: var(--space-2);
}
.rem-card__msg {
font-size: var(--font-sm);
margin-top: 2px;
}
.rem-card__time {
font-size: var(--font-xs);
margin-top: 4px;
}
/* SVG 图标 */
.rem-card__icon {
display: flex;
align-items: center;
color: var(--color-primary-strong);
}
@@ -0,0 +1,96 @@
import { useCallback, useEffect, useState } from 'react';
import {
Activity,
Armchair,
Bell,
CalendarCheck,
Droplet,
Footprints,
Pill,
type LucideIcon,
} from 'lucide-react';
import { api, ApiError } from '../api/client';
import { useAuth } from '../auth/AuthContext';
import { usePatient } from '../lib/usePatient';
import { useAutoRefresh } from '../lib/useAutoRefresh';
import { BindPatient } from '../components/BindPatient';
import type { Reminder } from '../api/types';
import { formatTime, reminderLabel } from '../lib/format';
import './RemindersPage.css';
const TYPE_ICON: Record<string, LucideIcon> = {
measurement: Activity,
water: Droplet,
exercise: Footprints,
rest: Armchair,
checkup: CalendarCheck,
medication: Pill,
};
export function RemindersPage(): JSX.Element {
const { boundPatientId } = useAuth();
const { patient, loading, reload } = usePatient();
const [reminders, setReminders] = useState<Reminder[]>([]);
const [err, setErr] = useState<string | null>(null);
const load = useCallback(() => {
if (!boundPatientId) return;
api
.listReminders(boundPatientId)
.then((list) => setReminders([...list].reverse()))
.catch((e) => setErr(e instanceof ApiError ? e.message : '加载提醒失败'));
}, [boundPatientId]);
useEffect(() => {
load();
}, [load]);
// 多端一致:管理师下发提醒近实时出现
useAutoRefresh(load);
if (!boundPatientId || (!patient && !loading)) {
return (
<div className="page">
<h1 className="section-title" style={{ marginTop: 0 }}>
</h1>
<BindPatient onBound={reload} />
</div>
);
}
return (
<div className="page">
<h1 className="section-title" style={{ marginTop: 0 }}>
怀
</h1>
<p className="muted" style={{ marginBottom: 'var(--space-4)' }}>
{patient ? `${patient.name} 的孕期提醒,方便你协助陪伴。` : ''}
</p>
{err && <p className="muted">{err}</p>}
{reminders.length === 0 ? (
<p className="muted"></p>
) : (
reminders.map((r) => {
const Icon = TYPE_ICON[r.effectiveType] ?? Bell;
return (
<div key={r.id} className="rem-card">
<span className="rem-card__icon">
<Icon size={26} strokeWidth={1.75} />
</span>
<div className="rem-card__body">
<p className="rem-card__title">
{reminderLabel(r.effectiveType)}
{r.adjustedForRisk && <span className="badge badge-warn"></span>}
</p>
<p className="rem-card__msg muted">{r.message}</p>
<p className="rem-card__time muted">{formatTime(r.scheduledAt)}</p>
</div>
</div>
);
})
)}
</div>
);
}
@@ -0,0 +1,187 @@
@import './tokens.css';
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html,
body,
#root {
height: 100%;
}
body {
font-family: 'Yuanti SC', 'YuanTi SC', '圆体-简', 'PingFang SC', 'Hiragino Sans GB',
'Microsoft YaHei', system-ui, -apple-system, sans-serif;
color: var(--color-text);
background: var(--color-bg);
line-height: 1.65;
font-weight: 400;
letter-spacing: 0.2px;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
button {
font-family: inherit;
cursor: pointer;
border: none;
background: none;
color: inherit;
}
input,
select,
textarea {
font-family: inherit;
font-size: var(--font-md);
}
a {
color: inherit;
text-decoration: none;
}
.app-shell {
max-width: var(--max-width);
margin: 0 auto;
min-height: 100%;
background: var(--color-bg);
position: relative;
display: flex;
flex-direction: column;
}
.page {
flex: 1;
padding: var(--space-4);
padding-bottom: calc(var(--nav-height) + var(--space-5));
}
.card {
background: var(--color-surface);
border-radius: var(--radius-lg);
padding: var(--space-4);
box-shadow: var(--shadow-card);
}
.card-soft {
background: var(--color-surface-soft);
border-radius: var(--radius-lg);
padding: var(--space-4);
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--space-2);
padding: 12px 18px;
border-radius: var(--radius-pill);
font-size: var(--font-md);
font-weight: 600;
transition: transform 0.08s ease, opacity 0.2s ease;
}
.btn:active {
transform: scale(0.97);
}
.btn-primary {
background: var(--color-primary);
color: var(--color-text-inverse);
}
.btn-block {
width: 100%;
}
.btn-ghost {
background: var(--color-surface);
color: var(--color-primary-strong);
border: 1px solid var(--color-border);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.field {
margin-bottom: var(--space-4);
}
.field label {
display: block;
font-size: var(--font-sm);
color: var(--color-text-soft);
margin-bottom: var(--space-2);
}
.field input,
.field select {
width: 100%;
padding: 12px 14px;
border-radius: var(--radius-md);
border: 1px solid var(--color-border);
background: var(--color-surface);
}
.field input:focus,
.field select:focus {
outline: none;
border-color: var(--color-primary);
}
.muted {
color: var(--color-text-soft);
}
.section-title {
font-size: var(--font-lg);
font-weight: 600;
margin: var(--space-5) 0 var(--space-3);
}
.center {
text-align: center;
}
.badge {
display: inline-flex;
align-items: center;
padding: 2px 10px;
border-radius: var(--radius-pill);
font-size: var(--font-xs);
font-weight: 600;
}
.badge-ok {
background: var(--color-ok-soft);
color: var(--color-ok);
}
.badge-warn {
background: var(--color-warn-soft);
color: var(--color-warn);
}
.badge-danger {
background: var(--color-danger-soft);
color: var(--color-danger);
}
.toast {
position: fixed;
bottom: calc(var(--nav-height) + 16px);
left: 50%;
transform: translateX(-50%);
background: rgba(74, 64, 57, 0.92);
color: #fff;
padding: 10px 18px;
border-radius: var(--radius-pill);
font-size: var(--font-sm);
z-index: 50;
max-width: 90%;
}
.check-row {
display: flex;
align-items: center;
gap: var(--space-2);
padding: 10px 0;
font-size: var(--font-md);
}
.check-row input {
width: 18px;
height: 18px;
}
@@ -0,0 +1,74 @@
/*
* PCM Design Tokens · 家属端(与孕妇端共享暖色低焦虑风)
* 依据 3-ui-style-PCM.md §3/§6(孕妇/家属端为主)。
*/
:root {
--color-bg: #fff7f3;
--color-surface: #ffffff;
--color-surface-soft: #fff1ea;
--color-primary: #f48fb1;
--color-primary-strong: #ec6f9e;
--color-primary-soft: #ffe4ee;
--color-accent: #7fc8a9;
--color-accent-soft: #e3f5ec;
--color-calm: #8ec5e8;
--color-ok: #5bb98c;
--color-ok-soft: #e3f5ec;
--color-warn: #e8a13a;
--color-warn-soft: #fbf0db;
--color-danger: #e3725b;
--color-danger-soft: #fbe3dd;
--color-text: #4a4039;
--color-text-soft: #8a7e76;
--color-text-inverse: #ffffff;
--color-border: #f1e4dc;
--radius-sm: 10px;
--radius-md: 16px;
--radius-lg: 22px;
--radius-pill: 999px;
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-5: 24px;
--space-6: 32px;
--font-xs: 12px;
--font-sm: 14px;
--font-md: 16px;
--font-lg: 19px;
--font-xl: 24px;
--font-xxl: 30px;
--shadow-soft: 0 6px 20px rgba(214, 158, 138, 0.16);
--shadow-card: 0 2px 12px rgba(214, 158, 138, 0.1);
/* 炫酷暖色:渐变与柔和彩色卡(保持暖、稳,不刺眼) */
--radius-xl: 26px;
--gradient-hero: linear-gradient(135deg, #ff9e7a 0%, #ff7ba6 52%, #f368a6 100%);
--gradient-primary: linear-gradient(135deg, #ffb38a 0%, #f48fb1 100%);
--gradient-soft: linear-gradient(135deg, #ffe9d9 0%, #ffd9e6 100%);
--shadow-hero: 0 14px 30px rgba(243, 104, 166, 0.28);
/* 暖系柔彩卡背景 + 对应图标色 */
--c-peach: #fff0e4;
--c-peach-ink: #e07a45;
--c-rose: #ffe4ee;
--c-rose-ink: #db5e8e;
--c-honey: #fff4d6;
--c-honey-ink: #c2901f;
--c-mint: #e6f4ec;
--c-mint-ink: #3fa777;
--c-lilac: #f1e9fb;
--c-lilac-ink: #9a6fc9;
--c-sky: #e6f1fb;
--c-sky-ink: #5b91c4;
--nav-height: 64px;
--max-width: 480px;
}
+9
View File
@@ -0,0 +1,9 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
@@ -0,0 +1 @@
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/client.ts","./src/api/types.ts","./src/auth/authcontext.tsx","./src/auth/session.ts","./src/components/bindpatient.tsx","./src/components/bottomnav.tsx","./src/components/toast.tsx","./src/lib/format.ts","./src/lib/useautorefresh.ts","./src/lib/usepatient.ts","./src/pages/chatpage.tsx","./src/pages/homepage.tsx","./src/pages/loginpage.tsx","./src/pages/mepage.tsx","./src/pages/onboardingpage.tsx","./src/pages/reminderspage.tsx"],"version":"5.9.3"}
+4
View File
@@ -0,0 +1,4 @@
{
"files": [],
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
}
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"strict": true
},
"include": ["vite.config.ts"]
}
@@ -0,0 +1 @@
{"root":["./vite.config.ts"],"version":"5.9.3"}
+16
View File
@@ -0,0 +1,16 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// 家属端开发服务器:将 /api 代理到本地 NestJS 后端(默认 3000)。
export default defineConfig({
plugins: [react()],
server: {
port: 5175,
proxy: {
'/api': {
target: process.env.PCM_API_TARGET ?? 'http://localhost:3000',
changeOrigin: true,
},
},
},
});