From dc23ea53ed74a20e589dbe09b3de2bdb96920974 Mon Sep 17 00:00:00 2001 From: gs Date: Fri, 25 Sep 2026 22:08:37 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../.openspec.yaml | 2 + .../design.md | 67 + .../proposal.md | 65 + .../specs/feeding-modes/spec.md | 39 + .../specs/role-preference-memory/spec.md | 38 + .../tasks.md | 30 + .../.openspec.yaml | 2 + .../memo-checklist-and-focus-timers/design.md | 72 + .../proposal.md | 53 + .../specs/focus-countdown-timers/spec.md | 32 + .../specs/memo-checklist/spec.md | 35 + .../memo-checklist-and-focus-timers/tasks.md | 29 + public/app.js | 1331 ++++++++++++++++- public/index.html | 722 +++++++-- public/style.css | 64 + scripts/migrate_v14.js | 70 + server/app.js | 18 + server/db.js | 95 ++ server/routes/babies.js | 36 +- server/routes/families.js | 40 +- server/routes/memos.js | 206 +++ server/routes/sse.js | 13 + server/routes/summary.js | 5 +- sql/database.sql | 91 +- test_api.js | 137 +- 25 files changed, 3116 insertions(+), 176 deletions(-) create mode 100644 openspec/changes/feeding-modes-and-role-preferences/.openspec.yaml create mode 100644 openspec/changes/feeding-modes-and-role-preferences/design.md create mode 100644 openspec/changes/feeding-modes-and-role-preferences/proposal.md create mode 100644 openspec/changes/feeding-modes-and-role-preferences/specs/feeding-modes/spec.md create mode 100644 openspec/changes/feeding-modes-and-role-preferences/specs/role-preference-memory/spec.md create mode 100644 openspec/changes/feeding-modes-and-role-preferences/tasks.md create mode 100644 openspec/changes/memo-checklist-and-focus-timers/.openspec.yaml create mode 100644 openspec/changes/memo-checklist-and-focus-timers/design.md create mode 100644 openspec/changes/memo-checklist-and-focus-timers/proposal.md create mode 100644 openspec/changes/memo-checklist-and-focus-timers/specs/focus-countdown-timers/spec.md create mode 100644 openspec/changes/memo-checklist-and-focus-timers/specs/memo-checklist/spec.md create mode 100644 openspec/changes/memo-checklist-and-focus-timers/tasks.md create mode 100644 scripts/migrate_v14.js create mode 100644 server/routes/memos.js diff --git a/openspec/changes/feeding-modes-and-role-preferences/.openspec.yaml b/openspec/changes/feeding-modes-and-role-preferences/.openspec.yaml new file mode 100644 index 0000000..75289e4 --- /dev/null +++ b/openspec/changes/feeding-modes-and-role-preferences/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-24 diff --git a/openspec/changes/feeding-modes-and-role-preferences/design.md b/openspec/changes/feeding-modes-and-role-preferences/design.md new file mode 100644 index 0000000..2848645 --- /dev/null +++ b/openspec/changes/feeding-modes-and-role-preferences/design.md @@ -0,0 +1,67 @@ +# Design: 喂奶双模式与角色行为记忆偏好系统 (Feeding Modes & Role Preference Memory) + +## Context + +在新生儿照护系统中,日常打卡需追求“单手、低认知负荷、极速”。当前系统喂奶卡片仅侧重瓶喂(按容量 ml 加减),对高频的母乳亲喂(以起止时间和持续时长为核心)缺乏独立的卡片形态支持。此外,家庭中不同角色(如宝妈偏好亲喂、宝爸/长辈偏好瓶喂)在切换角色时无法自动加载习惯模式,每次均需重复点选。 + +本设计旨在打造一个**以角色为记忆单元、以双模式为核心表现、以档案为配置中枢**的通用行为偏好系统。 + +## Goals / Non-Goals + +**Goals:** +1. **喂奶双模式无缝切换**:喂奶卡片支持「🤱 亲喂」与「🍼 瓶喂」双态,亲喂以开始时刻、结束时刻、持续分钟数和左右侧为核心;瓶喂以 ml 容量为核心。 +2. **角色行为独立记忆 (Per-Role Memory)**:每个看护人角色独立拥有行为偏好配置,切换操作人时自动无感恢复其专属模式。 +3. **档案与全局默认配置**:在宝贝档案中提供全局默认模式与各角色偏好集中管理面板。 +4. **通用行为架构拓展**:将“模式切换 + 默认值预设 + 人工精细修改 + 角色记忆”统一应用到喂奶、睡眠、尿布与自定义打卡中。 +5. **本地缓存与服务端持久化结合**:前端 LocalStorage 实现 0 延迟秒级响应,后端 MySQL 提供多端同步备份。 + +**Non-Goals:** +- 不强制要求亲喂必须使用实时秒级秒表(提供即时一键按预设时长倒推完成,亦支持微调起止点)。 +- 不破坏已有 `activity_record` 的历史数据结构,全面向后兼容。 + +## Decisions + +### 1. 喂奶卡片双态 UI 交互架构 (Dual-State Card Component) +- **选择方案**:在快速打卡界面的「喂奶卡片」内部顶部引入轻量 Segmented Tabs:`[ 🤱 亲喂 (时长) | 🍼 瓶喂 (容量) ]`。 +- **状态驱动渲染**: + - **亲喂状态**:展示当前预设时长(如 `20分钟`)、预估开始/结束时间、左右侧时长快捷选块、`一键完成亲喂 (20m)` 按钮与 `[✏️ 微调时间]` 按钮; + - **瓶喂状态**:展示快捷容量徽章(60/90/120/150ml)、`±10ml` 步进器、奶液类型切换(配方奶/母乳)及 `一键打卡 120ml` 按钮; +- **替代方案考虑**: + - *备选方案 A*:分成两张独立的打卡大卡片(一张亲喂卡片,一张瓶喂卡片)。 + *为何否定*:快速打卡区域空间寸土寸金,并列两张卡片会造成界面冗余,且对同一时间只能发生一种喂奶行为的场景而言不够聚焦。 + +### 2. 看护人角色记忆存储分层设计 (Dual-Layer Preference Storage) +- **选择方案**: + - **L1 本地即时层 (Client LocalStorage)**:键名 `baby_role_preferences`,存储以 `role_name` 为 Key 的偏好映射字典。用户任何模式切换或微调,立即在本地无阻塞写入,并在切换角色时 0ms 瞬间渲染; + - **L2 云端持久层 (Server MySQL)**:在 `family_member` 表追加 `preferences JSON NULL` 字段(并在 `baby_profile` 表追加 `default_config JSON NULL`),通过 RESTful API `PUT /api/families/:familyId/members/:roleName/preferences` 实现多手机端同步。 +- **降级与合并机制**: + `当前卡片显示 = 本地该角色专属记忆 ?? 档案该角色推荐值 ?? 宝贝档案全局默认值 ?? 系统兜底值`。 + +### 3. 亲喂起止时间与数据结构持久化 +- **选择方案**: + - `activity_record.activity_type = 'breastfeed'` + - `start_time`:亲喂开始时间(如一键打卡时,`start_time = now - duration`); + - `end_time`:亲喂结束时间(`now` 或人工指定时间); + - `duration_minutes`:总持续时长(分钟); + - `payload`:JSON 扩展存 `{ leftMinutes: 10, rightMinutes: 10, note: "..." }`; + - 看板 KPI 与作息流中:亲喂以“亲喂 20分钟”呈现,瓶喂以“瓶喂 120ml”呈现。 + +### 4. 通用行为模式向睡眠与尿布拓展 +- **睡眠卡片**:支持切换「☀️ 唤醒结算 (进行中计时)」与「🌙 快捷补录 (预设90分钟)」,并记住各角色习惯; +- **尿布卡片**:支持记忆常用性状(如宝爸常换嘘嘘、宝妈常记录便便与性状),点击直接以该角色常用性状入库。 + +## Risks / Trade-offs + +- **[Risk 1: 多设备并发修改角色偏好可能存在覆盖]** + → **Mitigation**: 偏好属于客户端个性化展示辅助,采用 Last-Write-Wins 策略,且优先尊重当前手机上实际操作者的微调。 +- **[Risk 2: 亲喂时间跨天或手工输入不合理]** + → **Mitigation**: 前端及后端增加时长校验规则(开始时间不得晚于结束时间,单次亲喂时长限制在 1~120 分钟内)。 +- **[Risk 3: 数据库旧数据缺少 preferences 字段]** + → **Mitigation**: 使用 `JSON NULL` 字段,并在服务启动时通过安全 DDL/代码容错处理,未配置时自动回退至默认策略。 + +## Migration Plan + +1. 在 `sql/database.sql` 追加 V1.3.0 变更脚本:为 `family_member` 增加 `preferences JSON`,为 `baby_profile` 增加 `default_config JSON`; +2. 升级后端路由 `records.js`、`families.js`,支持偏好存取及亲喂起止时间计算; +3. 重构前端快速打卡喂奶组件、角色切换事件总线及宝贝档案配置面板; +4. 进行自动化端到端测试与真实浏览器多端验证。 diff --git a/openspec/changes/feeding-modes-and-role-preferences/proposal.md b/openspec/changes/feeding-modes-and-role-preferences/proposal.md new file mode 100644 index 0000000..32db79e --- /dev/null +++ b/openspec/changes/feeding-modes-and-role-preferences/proposal.md @@ -0,0 +1,65 @@ +# Proposal: 喂奶双模式与角色行为记忆偏好系统 (Feeding Modes & Role Preference Memory) + +## Why + +在新生儿日常照料中,喂奶分为两大截然不同的核心场景: +1. **母乳亲喂 (Breastfeeding)**:以**时间**为核心维度(开始时刻、结束时刻、预设持续时长如 15~20 分钟),支持倒计时/正计时或快速录入与人工修改; +2. **奶瓶喂养 (Bottle Feeding)**:以**容量 (ml)** 为核心维度(如 90ml、120ml 配方奶/储奶瓶喂),辅以快速加减量调整。 + +同时,家庭多看护人分工差异显著: +- 宝妈通常以**亲喂**为主; +- 宝爸、爷爷奶奶、外公外婆通常以**瓶喂**为主; +- 不同看护人在记录换尿布、安抚睡眠、做抚触/维D等操作时也具有固定的惯用模式。 + +当前系统缺乏针对亲喂起止时间的精细化配置,且无法记住不同看护人角色的操作偏好。看护人每次切换身份后都需要重新手动选择模式或调整数值,严重增加了夜间或单手抱娃时的记录负担。因此需要建立**喂养双模式**以及**基于看护人角色的行为记忆与配置系统**,并在全行为(喂奶、睡眠、尿布、自定义项)中统一落地。 + +## What Changes + +1. **喂奶双模式与起止时间管理 (Feeding Dual-Mode System)**: + - 快速打卡喂奶卡片支持 **「亲喂」** 与 **「瓶喂」** 一键顶栏 Tab 切换; + - **亲喂模式**: + - 支持记录明确的「开始时间」与「结束时间」; + - 支持在档案/设置中预设默认亲喂时长(例如默认 15 分钟或 20 分钟); + - 点击快速打卡时,可直接按预设时长生成(结束时间 = 开始时间 + 默认时长),亦可在打卡弹窗中人工微调起止时间与时长(左右侧时长); + - 支持计时打卡与即时完成两种方式; + - **瓶喂模式**: + - 以喂奶容量 (ml) 为核心,展示快捷增减量(如 60ml/90ml/120ml/150ml); + - 支持标记奶液类型(配方奶 / 母乳瓶喂)。 + +2. **角色专属偏好记忆系统 (Per-Role Behavioral Preference Memory)**: + - 每个看护人角色(宝妈、宝爸、爷爷、奶奶、外公、外婆、舅舅、舅妈等)拥有**独立的记忆存储**; + - 当用户在顶部切换当前看护人角色时,系统自动切换并加载该角色专属的偏好: + - **喂奶偏好**:当前角色上次/默认选中的是亲喂还是瓶喂、默认喂养容量或默认亲喂时长; + - **睡眠偏好**:默认睡眠记录方式(计时模式 vs 快速推算预设时长如 90 分钟); + - **尿布偏好**:默认尿布性状(仅嘘嘘、仅便便、嘘嘘+便便); + - **自定义项偏好**:常用私人目标与常用数值; + - 支持本地持久化记忆(LocalStorage)+ 服务端同步兜底。 + +3. **家庭/宝贝档案全局默认模式与角色配置 (Configuration in Baby Profile)**: + - 在「👶 宝贝档案」设置专区中,提供「喂养模式与行为默认配置」控制台; + - 可配置宝宝全局默认喂奶模式(亲喂 or 瓶喂)及默认参数; + - 可针对各个看护人角色查看并设定专属推荐模式。 + +4. **全行为统一体验 (Universal Behavior Pattern Alignment)**: + - 将“模式切换 + 默认值预设 + 人工精细修改 + 角色记忆”的设计模式统一推广到睡眠、换尿布、自定义打卡等全行为中。 + +## Capabilities + +### New Capabilities +- `feeding-modes`: 喂养双模式系统(亲喂起止时间/预设时长/人工修改 vs 瓶喂按量)与快速打卡即时切换能力。 +- `role-preference-memory`: 看护人角色行为偏好记忆与配置系统(多角色独立记忆、切换角色自动恢复模式、宝贝档案配置全局与角色默认偏好、全行为统一适配)。 + +### Modified Capabilities + + +## Impact + +- **前端影响** (`public/index.html`, `public/app.js`, `public/style.css`): + - 快速打卡喂奶卡片重构为支持亲喂(起止时间/时长)与瓶喂(毫升)双形态切换; + - 角色切换控制器 (`roleModal` 与全局角色状态) 增加角色偏好加载与存储监听; + - 宝贝档案新增喂奶默认模式与看护人偏好配置面板; + - 流水修改弹窗进一步强化亲喂起止时间与左右侧明细编辑。 +- **后端影响** (`server/routes/records.js`, `server/routes/families.js`, `server/routes/babies.js`, `server/db.js`): + - `activity_record` 对 `breastfeed` 记录的 `start_time`、`end_time` 与 `duration_minutes` 提供完备支持与校验; + - 支持保存与查询角色偏好设置(可存储在 `family_member` 或独立角色偏好配置中)。 +- **兼容性**:100% 向后兼容现有 29 条历史记录与看板聚合逻辑。 diff --git a/openspec/changes/feeding-modes-and-role-preferences/specs/feeding-modes/spec.md b/openspec/changes/feeding-modes-and-role-preferences/specs/feeding-modes/spec.md new file mode 100644 index 0000000..265dff2 --- /dev/null +++ b/openspec/changes/feeding-modes-and-role-preferences/specs/feeding-modes/spec.md @@ -0,0 +1,39 @@ +# Spec Delta: 喂养双模式系统 (Feeding Modes) + +## Purpose + +为新生儿日常记录系统提供亲喂(按起止时间与时长精细记录)与瓶喂(按毫升容量与奶液类型记录)的双形态喂养模式支持,并允许快速打卡即时切换及档案预设默认模式。 + +## ADDED Requirements + +### Requirement: 快速打卡喂养卡片支持亲喂与瓶喂双模式即时切换 +系统 SHALL 在快速打卡主页面的喂奶卡片中提供「亲喂」与「瓶喂」双模式 Tab 切换控件。切换时卡片表单与打卡按钮形态即时变换,且不影响其他行为卡片。 + +#### Scenario: 用户在快速打卡中切换模式 +- **WHEN** 用户点击喂奶卡片顶部的「亲喂」或「瓶喂」切换按钮 +- **THEN** 喂奶卡片界面在 0.1 秒内切换对应形态:选「瓶喂」时展示毫升加减与容量预设;选「亲喂」时展示起止时刻预估、默认时长及计时/即时完成控件 + +### Requirement: 亲喂模式支持起止时间与预设时长打卡 +系统 SHALL 支持记录亲喂的开始时刻 (`start_time`)、结束时刻 (`end_time`) 以及总持续时长 (`duration_minutes`)。系统允许在快速打卡中一键按默认时长自动补全起止时间,并支持在保存前微调或保存后人工修改。 + +#### Scenario: 快速打卡亲喂按预设时长即时记录 +- **WHEN** 用户在亲喂模式下点击一键打卡按钮(预设时长为 20 分钟) +- **THEN** 系统自动以当前时刻为结束时间,倒推 20 分钟作为开始时间,生成一条 activity_type 为 `breastfeed`、duration_minutes 为 20 的打卡流水,并更新看板喂养时间与已逝时间 + +#### Scenario: 用户自定义微调亲喂起止时间 +- **WHEN** 用户点击亲喂卡片中的「微调时间」或进入流水修改该条记录 +- **THEN** 系统弹出时间选择器,允许用户手动调整精确的开始时间、结束时间或左右侧吸吮时长,保存后服务端重新核算该次持续分钟数 + +### Requirement: 瓶喂模式以容量为核心并支持快速微调 +系统 SHALL 支持记录瓶喂的进食容量 (`amountMl`) 与奶液类型 (`formula` 配方奶 或 `breastmilk` 瓶喂母乳),并提供快速步进调整按钮(如 ±10ml、±30ml)及常用量快捷标签。 + +#### Scenario: 快速打卡瓶喂容量调整 +- **WHEN** 用户在瓶喂模式下点击预设容量标签(如 120ml)或步进加减按钮并确认打卡 +- **THEN** 系统即刻记录一条 activity_type 为 `bottle` 的流水,记录 payload 包含 `amountMl: 120`,并即时同步累加至今日看板总奶量 + +### Requirement: 宝贝档案中支持配置喂奶默认模式与默认参数 +系统 SHALL 在「宝贝档案」页面中提供喂养模式配置区,允许家长设置宝宝当前阶段的默认喂养方式(亲喂或瓶喂)、默认亲喂单次目标时长(如 15/20/30 分钟)以及默认瓶喂推荐量(如 90/120/150 ml)。 + +#### Scenario: 家长在档案中更改喂奶默认模式 +- **WHEN** 家长在宝贝档案中将默认喂奶模式更改为「亲喂 (默认 20 分钟)」并保存 +- **THEN** 快速打卡页面在新会话或未指定角色偏好时,默认将喂奶卡片初始化为「亲喂」,且默认时长显示为 20 分钟 diff --git a/openspec/changes/feeding-modes-and-role-preferences/specs/role-preference-memory/spec.md b/openspec/changes/feeding-modes-and-role-preferences/specs/role-preference-memory/spec.md new file mode 100644 index 0000000..97568a4 --- /dev/null +++ b/openspec/changes/feeding-modes-and-role-preferences/specs/role-preference-memory/spec.md @@ -0,0 +1,38 @@ +# Spec Delta: 看护人角色偏好与通用行为记忆系统 (Role Preference Memory) + +## Purpose + +为系统多看护人角色提供专属的行为操作记忆能力,实现切换角色时自动恢复其惯用模式(如宝妈偏好亲喂、宝爸偏好瓶喂),并将模式切换与默认值配置能力统一推广至睡眠、尿布与自定义指标等全行为模块。 + +## ADDED Requirements + +### Requirement: 每个看护人角色拥有独立的专属行为操作记忆 +系统 SHALL 为家庭成员中的每个看护人角色(宝妈、宝爸、爷爷、奶奶、外公、外婆、舅舅、舅妈等)独立存储其行为偏好配置,包括但不限于默认喂奶模式、默认喂奶参数、睡眠记录方式与尿布常用性状。 + +#### Scenario: 宝妈与宝爸具有不同的喂奶偏好记忆 +- **WHEN** 宝妈在快速打卡中切换并使用了「亲喂」,而宝爸切换并使用了「瓶喂 (120ml)」 +- **THEN** 系统分别独立持久化保存宝妈偏好为「亲喂」及宝爸偏好为「瓶喂 (120ml)」,两者互不冲突覆盖 + +### Requirement: 顶部切换角色时即时联动恢复该角色偏好 +系统 SHALL 在用户通过顶部 Header 切换当前操作看护人角色时,自动读取并应用该角色最近记忆或预设的偏好,实时更新快速打卡页面的卡片激活形态。 + +#### Scenario: 切换角色触发卡片状态自动变换 +- **WHEN** 当前角色为「宝妈」(偏好亲喂),用户通过顶部角色弹窗切换为「宝爸」(偏好瓶喂) +- **THEN** 快速打卡页面的喂奶卡片自动在无需用户再次点击的情况下,平滑流转为「瓶喂」模式并加载其上次常用的 120ml 配置;换尿布卡片自动加载宝爸常用项 + +### Requirement: 宝贝档案中支持查看与个性化管理各角色偏好 +系统 SHALL 在「宝贝档案」中提供家庭看护人偏好管理界面,允许管理员(如创建者宝妈)集中查看各家庭成员角色的默认习惯,并支持重置或手动指定推荐默认模式。 + +#### Scenario: 在宝贝档案中为角色指定初始推荐偏好 +- **WHEN** 家长在档案偏好列表中将「奶奶」的喂奶模式预设为「瓶喂 100ml」,将「外婆」预设为「瓶喂 120ml」 +- **THEN** 系统保存设置,当长辈手机或本机切换至对应角色时,初始直接使用该配置 + +### Requirement: 通用行为模式全景推广(睡眠、尿布、自定义项) +系统 SHALL 将「模式切换 + 默认值预设 + 人工精细修改 + 角色记忆」的统一设计原则应用到睡眠、换尿布与自定义打卡全场景中: +- 睡眠:支持快速打卡切换「计时安睡」与「补录已睡时长(默认90分钟)」; +- 换尿布:支持快速打卡记忆常用排泄性状(仅嘘嘘、仅便便、嘘嘘+便便); +- 自定义项:记忆常用私人目标与预设打卡数值。 + +#### Scenario: 睡眠卡片根据角色偏好与状态自动调整 +- **WHEN** 用户在睡眠卡片中选择「快捷补录」模式并设定默认补录 90 分钟 +- **THEN** 系统记忆该角色的睡眠补录偏好,下次该角色操作时默认呈现 90 分钟快捷记录按钮,并允许一键微调起止时刻 diff --git a/openspec/changes/feeding-modes-and-role-preferences/tasks.md b/openspec/changes/feeding-modes-and-role-preferences/tasks.md new file mode 100644 index 0000000..1314999 --- /dev/null +++ b/openspec/changes/feeding-modes-and-role-preferences/tasks.md @@ -0,0 +1,30 @@ +# Tasks: 喂奶双模式与角色行为记忆偏好系统 (Feeding Modes & Role Preference Memory) + +## 1. 数据库与后端服务增强 (Database & Backend Enhancements) + +- [x] 1.1 在 `sql/database.sql` 添加 V1.3.0 变更脚本(为 `family_member` 和 `baby_profile` 增补偏好配置支持),并在 `server/db.js` 添加自动容错保障,通过 Node 运行验证数据库字段。 +- [x] 1.2 在 `server/routes/records.js` 中完善亲喂起止时间 (`start_time`, `end_time`, `duration_minutes`, `payload`) 校验与入库逻辑,确保看板与流水接口精准解析。 +- [x] 1.3 在 `server/routes/families.js` 与 `server/routes/babies.js` 中实现角色偏好与默认配置接口 (`GET/PUT /api/families/:familyId/members/:roleName/preferences` 及宝宝默认配置),通过自动化请求验证读写。 + +## 2. 前端快速打卡喂奶双模式重构 (Frontend Feeding Dual-Mode) + +- [x] 2.1 在 `public/index.html` 中重构喂奶打卡卡片,增加「🤱 亲喂 (时长)」与「🍼 瓶喂 (容量)」分段切换 Tab,构建亲喂起止时间展示、预设时长按钮、微调弹窗及一键打卡按钮。 +- [x] 2.2 在 `public/app.js` 实现亲喂打卡交互逻辑(支持按预设时长倒推开始时间一键打卡、微调起止时刻与左右侧时长、即时同步刷新已逝时间与看板)。 +- [x] 2.3 在 `public/app.js` 保持并优化瓶喂容量快速加减与奶液类型选择,确保双模式切换平滑无闪烁。 + +## 3. 看护人角色偏好记忆系统实现 (Role Preference Memory Engine) + +- [x] 3.1 在 `public/app.js` 实现客户端角色偏好管理器(基于 `localStorage` 的 `baby_role_preferences` 字典并联动云端同步)。 +- [x] 3.2 将角色切换逻辑与偏好引擎绑定:当用户在顶部 Header 切换角色(宝妈、宝爸、爷爷、奶奶等)时,自动瞬间恢复该角色上次使用的喂养模式与参数。 +- [x] 3.3 在快速打卡页面中,用户切换模式或调整数值时自动静默写回当前角色的记忆偏好。 + +## 4. 宝贝档案配置专区与全行为通用推广 (Profile Configuration & Universal Behaviors) + +- [x] 4.1 在 `public/index.html` 与 `public/app.js` 的「👶 宝贝档案」中新增「喂养模式与全行为默认配置」管理控制台,支持修改全局默认模式与查看各角色偏好。 +- [x] 4.2 将模式切换与记忆设计统一推广至睡眠(唤醒计时 vs 预设补录)与尿布(常用排泄性状)及自定义打卡项。 + +## 5. 整体联调与规范验证 (Integration & Validation) + +- [x] 5.1 扩展 `test_api.js`,增加亲喂起止时间打卡与角色偏好接口的端到端自动化测试并执行通过。 +- [x] 5.2 启动本地服务,在浏览器中验证:宝妈切换亲喂记忆、宝爸切换瓶喂记忆、快速打卡即时切换、档案配置生效。 +- [x] 5.3 运行 `openspec validate feeding-modes-and-role-preferences` 确保规范验证通过。 diff --git a/openspec/changes/memo-checklist-and-focus-timers/.openspec.yaml b/openspec/changes/memo-checklist-and-focus-timers/.openspec.yaml new file mode 100644 index 0000000..75289e4 --- /dev/null +++ b/openspec/changes/memo-checklist-and-focus-timers/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-24 diff --git a/openspec/changes/memo-checklist-and-focus-timers/design.md b/openspec/changes/memo-checklist-and-focus-timers/design.md new file mode 100644 index 0000000..778a51e --- /dev/null +++ b/openspec/changes/memo-checklist-and-focus-timers/design.md @@ -0,0 +1,72 @@ +# Design: 家庭备忘待办清单与专注活动倒计时放大模式 (Memo Checklist & Focus Countdown Timers) + +## Context + +新手父母在照料新生儿时具有多任务并发、注意力高度分散的特点。在实际日常中: +1. 家长常需要记录临时性、非结构化的备忘琐事(如体温复测、煮水消毒、换药洗护等); +2. 在进行母乳亲喂、俯趴锻炼或睡眠陪伴时,家长双手抱娃或守护在侧,手机通常摆放在床头或小茶几上,无法看清普通界面的小字,急需一个可放大、抗干扰的专注倒计时模式。 + +本设计旨在打造一个**家庭协同轻备忘系统**以及一个**全局沉浸式多活动专注大视窗 (Focus Mode)**。 + +## Goals / Non-Goals + +**Goals:** +1. **轻量清单待办**:提供简便的备忘录入、完成勾选与清理机制,基于家庭 (`family_id`) 跨端共享。 +2. **多活动精准倒计时引擎**:支持亲喂(分左右侧倒计时)、俯趴锻炼(预设15m)、抚触等时长活动。 +3. **全屏/大视窗沉浸专注模式 (Focus View)**:提供 50px+ 超大字体倒计时、大号触摸操作区(加时、换侧、结算),支持随时最小化至悬浮小窗或恢复全屏。 +4. **计时完成后无缝打卡结算**:倒计时完毕或中途结算,直接自动转换填入并提交 `activity_record`,无需家长再次手动输入时长。 + +**Non-Goals:** +- 不做过于复杂的日程日历与日历 ICS 协议同步(聚焦于家庭日常 1~3 天内的高频轻待办)。 +- 不依赖原生 App 后台服务(纯 Web 环境下使用系统可见的 Web Audio 与轻量持久化计时戳,页面切回自动核准时间差)。 + +## Decisions + +### 1. 专注倒计时状态引擎架构 (Global Active Timer Engine) +- **选择方案**:建立全局单例计时器状态 `state.activeTimer`: + ```javascript + { + activityType: 'breastfeed', // 'breastfeed' | 'tummy' | 'massage' | 'sleep' + title: '母乳亲喂', + targetMinutes: 20, + startTime: Date.now(), + currentSide: 'left', // 'left' | 'right' + leftSeconds: 600, + rightSeconds: 600, + remainingSeconds: 1200, + isRunning: true, + isExpanded: false + } + ``` +- **切后台与断电保护机制**:基于绝对时间戳 `startTimestamp` 与 `Date.now()` 进行核算,即使手机息屏或浏览器降频,重新点亮唤醒时时间依然绝对准确。 + +### 2. 专注全屏大视窗组件 (`#focusModal`) +- **选择方案**:独立遮罩容器,覆盖全屏并采用护眼暗夜/温润深墨绿材质(`bg-stone-900/95`,适合昏暗夜间哺乳): + - 核心展示:巨大环形 SVG 倒计时动效 + 60px 粗体数字 + 醒目操作胶囊(【切换到右侧】、【+5分钟】、【提前完成】、【缩小至卡片】); + - 提示音设计:使用 Web Audio API 原生合成柔和双音节提示音(Bells/Marimba),不依赖外部音频网络文件,100% 离线播放。 + +### 3. 备忘清单数据表与家庭协同设计 +- **选择方案**:新增 `family_memo` 表: + - `id` BIGINT 自增主键; + - `memo_id` VARCHAR(64) 唯一业务ID; + - `family_id` VARCHAR(64) 关联家庭; + - `content` VARCHAR(255) 待办事项内容; + - `due_period` VARCHAR(30) 推荐时段(早晨、下午、睡前、指定时间); + - `is_completed` TINYINT(1) DEFAULT 0; + - `completed_at` DATETIME NULL; + - `created_by` VARCHAR(50) 创建人角色。 +- **接口**:标准 RESTful API `GET/POST/PUT/DELETE /api/memos`。 + +## Risks / Trade-offs + +- **[Risk 1: 手机息屏导致 setInterval 停顿]** + → **Mitigation**: 计时器采用“目标截止绝对时刻 (`targetEndTime = startTime + duration`)”比对,每次 tick 均通过 `Math.max(0, targetEndTime - Date.now())` 实时计算剩余秒数,彻底解决后台暂停漂移问题。 +- **[Risk 2: 亲喂单手哺乳时误触关闭全屏]** + → **Mitigation**: 放大模式中关键操作按键设置防误触尺寸(最小高度 48px),退出全屏按钮置于右上角且二次轻触确认。 + +## Migration Plan + +1. 在 `sql/database.sql` 追加 V1.4.0 变更脚本:创建 `family_memo` 表; +2. 新增服务端路由 `server/routes/memos.js` 并挂载至 `app.js`; +3. 前端实现备忘待办卡片、倒计时引擎与全屏专注放大大视窗; +4. 运行端到端接口验证与多端交互测试。 diff --git a/openspec/changes/memo-checklist-and-focus-timers/proposal.md b/openspec/changes/memo-checklist-and-focus-timers/proposal.md new file mode 100644 index 0000000..423facf --- /dev/null +++ b/openspec/changes/memo-checklist-and-focus-timers/proposal.md @@ -0,0 +1,53 @@ +# Proposal: 家庭备忘待办清单与专注活动倒计时放大模式 (Memo Checklist & Focus Countdown Timers) + +## Why + +在新生儿家庭照护中,父母和家人经常面临两大核心痛点: +1. **繁杂琐事与待办备忘极易遗忘**:例如“下午3点测体温”、“给宝宝喂D3滴剂”、“准备45℃温水”、“周五打第二针乙肝疫苗”、“清洗消毒吸奶器”等。目前系统仅有事后打卡记录,缺乏事前与当天的**备忘待办清单 (Todo Checklist)**,长辈与父母之间容易沟通脱节或遗漏; +2. **有时长的照料动作缺乏陪伴式倒计时与沉浸大屏展示**: + - **母乳亲喂**:单侧通常需喂 10~15 分钟,双侧需轮换,母亲单手抱娃哺乳时急需清晰的**倒计时**与**换侧提醒**; + - **俯趴锻炼 (Tummy Time)**、抚触按摩、盆浴等有时长要求的活动同样需要倒计时指引; + - 手机小屏幕在哺乳或照护时难以看清,急需一个**能够一键放大的「专注全屏/沉浸大卡片模式」**,字号硕大、界面纯粹,方便把手机立在床头或桌上,一眼获知当前进行中的活动进度。 + +## What Changes + +1. **家庭智能备忘待办清单 (Family Memo & Checklist)**: + - 在快速打卡主界面与看板中增设「📝 今日备忘待办 (Memo Checklist)」模块; + - 支持家长手动快速输入待办备忘事项(如任务内容、推荐完成时间、指派或关联人); + - 按照清单清单式推进,支持点击一键勾选完成(已完成划线归档)、取消完成及快速删除; + - 支持家庭多成员协同共享,多手机端同步更新。 + +2. **多活动专注倒计时系统 (Universal Activity Countdown Timers)**: + - **亲喂倒计时 (Breastfeeding Countdown)**: + - 支持设置单次亲喂目标倒计时(如默认 15/20/30 分钟,支持 ±5分钟微调); + - 支持**左右侧乳房切换 (Left/Right Breast Switch)** 分边计时与切换温馨提示; + - 倒计时结束支持柔和提示音与触觉振动,并可直接一键将本次亲喂结算入库; + - **通用计时拓展**:将倒计时推广至俯趴锻炼 (Tummy Time,如 15分钟)、抚触护肤、水浴与自定义计时活动。 + +3. **专注模式全屏/大卡片放大展示 (Focus Large View Mode)**: + - 当任意活动(亲喂、睡眠、俯趴等)处于进行中倒计时或正计时状态时,界面提供「🔍 放大专注」入口; + - 点击后呼出**大字号极简全屏/沉浸式大视窗**: + - 巨大环形进度与清晰倒计时数字(如 `14:28`); + - 醒目标识当前动作(如 `🤱 正在亲喂 (左侧)` 或 `🐢 正在俯趴锻炼`); + - 提供大触控热区按键:【换侧】、【+5分钟】、【提前完成入库】、【暂停/退出全屏】; + - 适配横屏立放与竖屏床头桌面摆放场景。 + +## Capabilities + +### New Capabilities +- `memo-checklist`: 家庭日常备忘待办清单系统(手动输入清单、状态勾选、待办分类、家庭多端同步)。 +- `focus-countdown-timers`: 专注活动倒计时与大屏沉浸放大模式(亲喂分侧倒计时、通用动作计时、全屏/大卡片专注模式、结算自动流水入库)。 + +### Modified Capabilities + + +## Impact + +- **前端架构** (`public/index.html`, `public/app.js`, `public/style.css`): + - 新增全屏专注大视窗组件 (`#focusModal` / `#focusOverlay`); + - 快速打卡喂奶卡片与俯趴卡片集成倒计时控制器与放大按钮; + - 新增备忘清单卡片 (`#memoChecklistCard`) 及输入新增交互。 +- **后端架构** (`server/routes/memos.js`, `server/db.js`, `sql/database.sql`): + - 新建 `family_memo` 备忘数据表,支持基于 `family_id` 的待办增删改查; + - 倒计时结算无缝复用已有 `POST /api/records` 入库流程。 +- **数据库**:无破坏性变更,向后完全兼容。 diff --git a/openspec/changes/memo-checklist-and-focus-timers/specs/focus-countdown-timers/spec.md b/openspec/changes/memo-checklist-and-focus-timers/specs/focus-countdown-timers/spec.md new file mode 100644 index 0000000..69230ba --- /dev/null +++ b/openspec/changes/memo-checklist-and-focus-timers/specs/focus-countdown-timers/spec.md @@ -0,0 +1,32 @@ +# Spec Delta: 专注活动倒计时与放大模式 (Focus Countdown Timers & Large View) + +## Purpose + +为有时长属性的照料动作(如亲喂、俯趴锻炼、抚触等)提供高精度倒计时、左右侧切换提示以及一键放大的全屏沉浸专注模式,满足哺乳与陪伴时的大字号远距阅览需求。 + +## ADDED Requirements + +### Requirement: 亲喂活动支持分侧倒计时与左右轮换 +系统 SHALL 支持为亲喂活动开启目标倒计时(如默认 20 分钟),并在界面清晰呈现剩余分钟秒数与当前喂哺侧别(左侧 / 右侧)。系统支持用户在哺乳中途一键切换喂哺侧,并分别累计左右侧实际吸吮分钟数。 + +#### Scenario: 开启亲喂倒计时并换侧 +- **WHEN** 宝妈点击「开启亲喂倒计时 (20分钟)」,并在喂了 10 分钟后点击「切换到右侧」 +- **THEN** 界面左侧计时停止在 10 分钟,右侧计时自动开始倒计剩余 10 分钟,并清晰标识当前为右侧 + +### Requirement: 通用时长活动统一支持倒计时 +系统 SHALL 为所有具备 duration 属性的日常保健与习惯活动(如俯趴锻炼 Tummy Time、抚触按摩、温水洗浴)提供统一的倒计时触发入口,支持预设推荐时长(如 15 分钟)并在倒计时完毕时提供完成提示。 + +#### Scenario: 开启俯趴锻炼倒计时 +- **WHEN** 用户在俯趴打卡项点击「开始 15 分钟倒计时」 +- **THEN** 系统启动 15 分钟动态倒数,进度条同步按比例缩减,到达 00:00 时发出轻柔提醒并提示用户完成打卡 + +### Requirement: 当前操作倒计时支持放大全屏专注模式 +系统 SHALL 在活动计时进行中提供「🔍 放大专注」入口。点击后以全屏/沉浸式大卡片形式呈现当前活动,展示超大号倒计时数字、环形动态进度、大按钮操作区(暂停/继续、加时、提前完成),屏蔽其他无关界面元素的视觉干扰。 + +#### Scenario: 用户在哺乳或俯趴时放大专注视窗 +- **WHEN** 用户在进行中倒计时界面点击「放大专注」按钮 +- **THEN** 系统弹出覆盖全屏的大字号专注面板,倒计时字号提升至 48px 以上,支持手机横屏与竖屏立放远距清晰可视 + +#### Scenario: 从放大模式直接结算完成打卡 +- **WHEN** 用户在专注全屏模式下点击「完成本次活动并打卡」 +- **THEN** 系统自动采集本次实际发生时长、起止时间与操作人,直接将流水入库并关闭全屏,自动刷新今日看板 diff --git a/openspec/changes/memo-checklist-and-focus-timers/specs/memo-checklist/spec.md b/openspec/changes/memo-checklist-and-focus-timers/specs/memo-checklist/spec.md new file mode 100644 index 0000000..04493f5 --- /dev/null +++ b/openspec/changes/memo-checklist-and-focus-timers/specs/memo-checklist/spec.md @@ -0,0 +1,35 @@ +# Spec Delta: 家庭日常备忘待办清单 (Memo Checklist) + +## Purpose + +为新生儿看护家庭提供事前与日常照料的备忘清单管理能力,支持手动快速添加备忘、勾选完成与删除,并实现全家看护团队多端同步流转。 + +## ADDED Requirements + +### Requirement: 用户可以手动添加备忘待办事项 +系统 SHALL 提供快捷输入界面,允许用户输入备忘标题、选择可选提醒时段(如早晨、下午、睡前)及关联看护人,并保存至当前活跃家庭。 + +#### Scenario: 手动新增备忘事项成功 +- **WHEN** 用户在备忘区域输入「带宝宝去社区医院打疫苗」并点击添加 +- **THEN** 系统立即在备忘列表中新增一条待办事项,状态为未完成,并在 1 秒内持久化存入服务端与本地缓存 + +### Requirement: 按照清单实现勾选与状态切换 +系统 SHALL 支持用户以 Checkbox 形式逐项勾选待办,勾选后视觉展示为已完成(划线或淡出至已完成分组),并支持反悔再次点击取消完成。 + +#### Scenario: 勾选完成某项备忘 +- **WHEN** 用户点击备忘事项「给宝宝补充维D3」左侧的勾选框 +- **THEN** 该项状态变更为已完成,字体呈现完成划线效果,并更新未完成待办计数 + +### Requirement: 备忘清单支持快速清理与删除 +系统 SHALL 允许用户对单条备忘进行左滑/点击垃圾桶删除,或一键清除所有已完成的待办事项。 + +#### Scenario: 删除单条备忘 +- **WHEN** 用户点击某条已失效备忘右侧的删除按钮并确认 +- **THEN** 系统从列表中移除该项,并在数据库中执行软删除或物理删除 + +### Requirement: 家庭看护成员多端共享备忘清单 +系统 SHALL 保证备忘清单基于 `family_id` 维护,任意家庭成员(宝妈、宝爸等)新增或勾选备忘后,其他手机切回或刷新时自动同步呈现最新清单状态。 + +#### Scenario: 跨设备同步待办状态 +- **WHEN** 宝爸在手机上勾选了「已冲洗并消毒奶瓶」 +- **THEN** 宝妈手机在下一次自动刷新或加载看板时,该项同样显示为已完成状态 diff --git a/openspec/changes/memo-checklist-and-focus-timers/tasks.md b/openspec/changes/memo-checklist-and-focus-timers/tasks.md new file mode 100644 index 0000000..0c67864 --- /dev/null +++ b/openspec/changes/memo-checklist-and-focus-timers/tasks.md @@ -0,0 +1,29 @@ +# Tasks: 家庭备忘待办清单与专注活动倒计时放大模式 (Memo Checklist & Focus Countdown Timers) + +## 1. 备忘清单数据库与服务端路由 (Database & Backend Memos) + +- [x] 1.1 在 `sql/database.sql` 追加 V1.4.0 脚本(创建 `family_memo` 表并在 `server/db.js` 完成初始化),通过测试验证表创建与索引配置。 +- [x] 1.2 创建 `server/routes/memos.js` 并挂载至 `server/app.js`,实现 `GET/POST/PUT/DELETE /api/memos` 完整待办 CRUD 接口,通过自动化脚本验证。 + +## 2. 前端家庭备忘待办清单实现 (Frontend Memo Checklist) + +- [x] 2.1 在 `public/index.html` 中增加「📝 今日备忘待办清单」卡片组件(含快速输入框、待办项列表、完成划线与删除操作)。 +- [x] 2.2 在 `public/app.js` 实现备忘清单的增删改查交互、完成状态勾选、计数提示与家庭成员共享同步。 + +## 3. 多活动倒计时核心引擎 (Activity Countdown Engine) + +- [x] 3.1 在 `public/app.js` 封装基于绝对时间戳的单例倒计时引擎(支持防息屏漂移、暂停/继续、加时、倒计时完毕柔和音频提示)。 +- [x] 3.2 在喂奶卡片中实现亲喂倒计时触发器,支持目标时长倒数、左右侧乳房一键切换与分侧时长累计。 +- [x] 3.3 为俯趴锻炼 (Tummy Time) 及其他时长保健活动接入通用倒计时入口。 + +## 4. 全屏沉浸专注大视窗 (Focus Large View Mode) + +- [x] 4.1 在 `public/index.html` 构建全屏沉浸专注大视窗容器(`#focusModal`),包含大号环形进度、50px+ 倒计时字体、左右侧指示及大号操作按钮。 +- [x] 4.2 在 `public/app.js` 实现「🔍 放大专注」与「缩小恢复」双向平滑流转逻辑,确保全屏模式下支持换侧、加时与一键打卡结算入库。 +- [x] 4.3 在 `public/style.css` 补充专注模式的暗夜微光动效、环形进度动画与夜间护眼配色。 + +## 5. 联调测试与规范校验 (Integration & Validation) + +- [x] 5.1 扩展 `test_api.js`,加入备忘待办全生命周期(创建、勾选、删除)与计时入库的自动化测试并验证通过。 +- [x] 5.2 在 Chrome 浏览器中测试亲喂倒计时、放大全屏专注模式、左右换侧、备忘清单勾选并结算打卡。 +- [x] 5.3 运行 `openspec validate memo-checklist-and-focus-timers` 确保规范验证通过。 diff --git a/public/app.js b/public/app.js index 9063e8e..2ebb660 100644 --- a/public/app.js +++ b/public/app.js @@ -19,6 +19,12 @@ const state = { customMetrics: [], careGuides: [], lastBottleMl: parseInt(localStorage.getItem('last_bottle_ml') || '120'), + memos: [], + feedingMode: localStorage.getItem('last_feeding_mode') || 'bottle', + bfTargetDuration: parseInt(localStorage.getItem('bf_target_duration') || '20'), + activeTimer: null, + rolePreferences: JSON.parse(localStorage.getItem('baby_role_preferences') || '{}'), + memoHistoryFilter: { status: 'all', period: 'all', search: '' }, liveTimerInterval: null }; @@ -98,6 +104,7 @@ function openRoleModal() { state.currentOperator = role; localStorage.setItem('caregiver_role', role); updateOperatorDisplay(); + applyRolePreferences(role); closeModal('roleModal'); showToast(`操作人已切换为:【${role}】`); }; @@ -111,8 +118,9 @@ function openRoleModal() { // Initialization // ---------------------------------------------------- document.addEventListener('DOMContentLoaded', async () => { - // Set current operator display + // Set current operator display and apply its preferences updateOperatorDisplay(); + applyRolePreferences(state.currentOperator); const dateInput = document.getElementById('customDatePicker'); if (dateInput) dateInput.value = state.currentDate; @@ -277,6 +285,9 @@ function switchTab(viewId) { if (viewId === 'dashboard' || viewId === 'quick') { loadSummaryData(); } + if (viewId === 'profile') { + renderProfileConfigMenu(); + } } // ---------------------------------------------------- @@ -294,7 +305,19 @@ async function loadFamilies() { localStorage.setItem('selected_family_id', state.currentFamilyId); } updateCurrentFamilyDisplay(); + // Populate role preferences from members if available + const currentFam = state.families.find(f => f.family_id === state.currentFamilyId); + if (currentFam && currentFam.members) { + currentFam.members.forEach(m => { + if (m.preferences && Object.keys(m.preferences).length > 0) { + state.rolePreferences[m.role_name] = { ...(state.rolePreferences[m.role_name] || {}), ...m.preferences }; + } + }); + localStorage.setItem('baby_role_preferences', JSON.stringify(state.rolePreferences)); + } + applyRolePreferences(state.currentOperator); await loadBabies(); + await loadMemos(); } } catch (err) { console.error('Failed to load families:', err); @@ -398,6 +421,7 @@ async function switchFamily(familyId) { const fam = state.families.find(f => f.family_id === familyId); updateCurrentFamilyDisplay(); await loadBabies(); + await loadMemos(); closeModal('familySwitchModal'); showToast(`已切换至家庭:【${fam ? fam.name : ''}】`); } @@ -616,6 +640,7 @@ async function loadBabies() { } updateCurrentBabyDisplay(); renderBabiesList(); + renderProfileConfigMenu(); await loadSummaryData(); } } catch (err) { @@ -725,6 +750,8 @@ function setupSSE() { loadSummaryData(true); } else if (data.type === 'record_deleted' || data.type === 'record_updated') { loadSummaryData(true); + } else if (data.type && data.type.startsWith('memo_')) { + loadMemos(); } } catch (e) {} }; @@ -749,7 +776,7 @@ function renderLiveDashboard(data) { const alertBanner = document.getElementById('feedingAlertBanner'); if (f && f.hasData) { - if (lastFeedTimeEl) lastFeedTimeEl.textContent = `距上次: ${f.elapsedText}`; + if (lastFeedTimeEl) lastFeedTimeEl.textContent = `距上次 ${f.elapsedText ? f.elapsedText.replace(/前$/, '') : '--'}`; if (feedLastSummaryEl) { const typeStr = f.type === 'bottle' ? `${f.amountMl || 0}ml` : '亲喂'; feedLastSummaryEl.textContent = `上次: ${f.time} ${typeStr} (${f.operator || '家人'})`; @@ -772,27 +799,30 @@ function renderLiveDashboard(data) { const sleepToggleActionText = document.getElementById('sleepToggleActionText'); const btnSleepToggle = document.getElementById('btnSleepToggle'); + const btnSleepFocus = document.getElementById('btnSleepFocusExpand'); if (s && s.hasData && s.isSleeping) { + if (btnSleepFocus) btnSleepFocus.classList.remove('hidden'); if (sleepStateTitleEl) { sleepStateTitleEl.textContent = `安睡 ${s.currentDurationText}`; - sleepStateTitleEl.className = 'text-xs font-black text-amber-700 bg-amber-50 border border-amber-200/80 px-2.5 py-1 rounded-xl'; + sleepStateTitleEl.className = 'text-xs font-black text-amber-700 bg-amber-50 border border-amber-200/80 px-2 py-1 rounded-xl whitespace-nowrap inline-block'; } - if (sleepStateDetailEl) sleepStateDetailEl.textContent = '宝宝正在睡眠中 · 骨骼与大脑高速发育'; + if (sleepStateDetailEl) sleepStateDetailEl.textContent = '宝宝正在睡眠中 · 骨骼与大脑发育'; if (sleepToggleIcon) sleepToggleIcon.textContent = '☀️'; - if (sleepToggleActionText) sleepToggleActionText.textContent = `☀️ 宝宝醒了?(点击结算已睡 ${s.currentDurationText})`; + if (sleepToggleActionText) sleepToggleActionText.textContent = `☀️ 宝宝醒了?(结算已睡 ${s.currentDurationText})`; if (btnSleepToggle) { - btnSleepToggle.className = 'w-full bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 active:scale-98 text-white font-extrabold text-xs py-3.5 rounded-2xl shadow-md transition flex items-center justify-center space-x-2'; + btnSleepToggle.className = 'flex-1 bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 active:scale-98 text-white font-extrabold text-xs py-3 rounded-2xl shadow-xs transition flex items-center justify-center space-x-2 whitespace-nowrap'; } } else { + if (btnSleepFocus) btnSleepFocus.classList.add('hidden'); if (sleepStateTitleEl) { - sleepStateTitleEl.textContent = s && s.hasData ? `清醒 ${s.awakeText}` : '清醒中'; - sleepStateTitleEl.className = 'text-xs font-black text-purple-700 bg-purple-50 border border-purple-200/80 px-2.5 py-1 rounded-xl'; + sleepStateTitleEl.textContent = s && s.hasData ? `清醒 ${s.awakeText.replace(/前$/, '')}` : '清醒中'; + sleepStateTitleEl.className = 'text-xs font-black text-purple-700 bg-purple-50 border border-purple-200/80 px-2 py-1 rounded-xl whitespace-nowrap inline-block'; } if (sleepStateDetailEl) sleepStateDetailEl.textContent = '宝宝清醒中 · 精神饱满可互动交流'; if (sleepToggleIcon) sleepToggleIcon.textContent = '😴'; - if (sleepToggleActionText) sleepToggleActionText.textContent = '🌙 宝宝睡下了 (点击开始计时)'; + if (sleepToggleActionText) sleepToggleActionText.textContent = '🌙 宝宝睡下了 (开始计时)'; if (btnSleepToggle) { - btnSleepToggle.className = 'w-full bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 active:scale-98 text-white font-extrabold text-xs py-3.5 rounded-2xl shadow-md transition flex items-center justify-center space-x-2'; + btnSleepToggle.className = 'flex-1 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 active:scale-98 text-white font-extrabold text-xs py-3 rounded-2xl shadow-xs transition flex items-center justify-center space-x-2 whitespace-nowrap'; } } @@ -801,7 +831,7 @@ function renderLiveDashboard(data) { const lastDiaperTimeEl = document.getElementById('lastDiaperTime'); const lastDiaperDetailEl = document.getElementById('lastDiaperDetail'); if (d && d.hasData) { - if (lastDiaperTimeEl) lastDiaperTimeEl.textContent = `距上次: ${d.elapsedText}`; + if (lastDiaperTimeEl) lastDiaperTimeEl.textContent = `距上次 ${d.elapsedText ? d.elapsedText.replace(/前$/, '') : '--'}`; const typeLabel = d.diaperType === 'poop' ? '便便' : (d.diaperType === 'both' ? '尿+便' : '小便'); if (lastDiaperDetailEl) lastDiaperDetailEl.textContent = `上次: ${d.time} ${typeLabel} (${d.operator || '家人'})`; } else { @@ -829,20 +859,45 @@ function renderQuickCustomMetricsGrid() { state.customMetrics.forEach(metric => { const defVal = metric.default_value || '1'; - const card = document.createElement('button'); - card.className = 'bg-slate-50 hover:bg-emerald-50 border border-slate-200 hover:border-emerald-300 rounded-xl p-2.5 flex items-center justify-between active:scale-95 transition text-left shadow-2xs'; - card.onclick = () => quickLogCustomMetric(metric); + const isDuration = metric.type === 'duration' || metric.unit === '分钟' || (metric.name && (metric.name.includes('俯趴') || metric.name.includes('Tummy'))); + const card = document.createElement('div'); + card.className = 'bg-stone-50 hover:bg-emerald-50/80 border border-stone-200 hover:border-emerald-300 rounded-2xl p-2.5 flex items-center justify-between transition text-left shadow-2xs group'; + + const timerBtn = isDuration ? ` + + ` : ''; card.innerHTML = ` -
- ${metric.icon || '⭐'} -
-
${metric.name}
-
默认: ${defVal} ${metric.unit || '次'}
+
+ ${metric.icon || '⭐'} +
+
${metric.name}
+
默认: ${defVal} ${metric.unit || '次'}
- 打卡 +
+ ${timerBtn} + +
`; + + const clickArea = card.querySelector('.metric-click-area'); + const logBtn = card.querySelector('.btn-metric-log'); + const timerEl = card.querySelector('.btn-metric-timer'); + + if (clickArea) clickArea.onclick = () => quickLogCustomMetric(metric); + if (logBtn) logBtn.onclick = () => quickLogCustomMetric(metric); + if (timerEl) { + timerEl.onclick = (e) => { + e.stopPropagation(); + startFocusTimer('custom', parseInt(defVal) || 15); + }; + } + container.appendChild(card); }); } @@ -1634,6 +1689,8 @@ function selectBaby(babyId) { localStorage.setItem('selected_baby_id', babyId); updateCurrentBabyDisplay(); renderBabiesList(); + renderProfileConfigMenu(); + applyRolePreferences(state.currentOperator); loadCustomMetrics(); loadSummaryData(); showToast('已切换至目标宝贝!'); @@ -1816,18 +1873,398 @@ function openCareGuideModal(guideId) { } // ---------------------------------------------------- -// One-Tap Quick Log Handlers +// One-Tap Quick Log Handlers & Role Preferences +// ---------------------------------------------------- +// ---------------------------------------------------- +// Care & Profile Configuration Menu Functions // ---------------------------------------------------- let pendingBottleMl = 120; +function switchConfigSubTab(tab) { + const tabs = ['feeding', 'roles', 'metrics']; + tabs.forEach(t => { + const btn = document.getElementById(`cfgSubTabBtn${t.charAt(0).toUpperCase() + t.slice(1)}`); + const panel = document.getElementById(`cfgSubPanel${t.charAt(0).toUpperCase() + t.slice(1)}`); + if (t === tab) { + if (btn) { + btn.className = 'flex-1 py-1.5 rounded-xl bg-white text-indigo-700 shadow-2xs transition whitespace-nowrap cursor-pointer font-bold'; + } + if (panel) panel.classList.remove('hidden'); + } else { + if (btn) { + btn.className = 'flex-1 py-1.5 rounded-xl text-slate-600 hover:text-slate-900 transition whitespace-nowrap cursor-pointer font-bold'; + } + if (panel) panel.classList.add('hidden'); + } + }); +} + +function renderProfileConfigMenu() { + const baby = state.babies.find(b => b.baby_id === state.currentBabyId); + const babyNameEl = document.getElementById('cfgBabyFeedingName'); + if (babyNameEl) { + babyNameEl.textContent = baby ? baby.name : '未选择宝宝'; + } + + let defConfig = {}; + if (baby && baby.default_config) { + try { + defConfig = typeof baby.default_config === 'string' ? JSON.parse(baby.default_config) : baby.default_config; + } catch (e) { + defConfig = {}; + } + } + + // Populate baby feeding defaults + const mode = defConfig.defaultFeedingMode || 'bottle'; + const modeRadio = document.querySelector(`input[name="cfgDefaultMode"][value="${mode}"]`); + if (modeRadio) modeRadio.checked = true; + + const bottleMl = defConfig.defaultBottleMl || state.lastBottleMl || 120; + const inputBottle = document.getElementById('cfgInputBottleMl'); + const displayBottle = document.getElementById('cfgBottleMlDisplay'); + if (inputBottle) inputBottle.value = bottleMl; + if (displayBottle) displayBottle.textContent = bottleMl; + updateCfgBottleChips(bottleMl); + + const bfMinutes = defConfig.defaultBfMinutes || state.bfTargetDuration || 20; + const inputBf = document.getElementById('cfgInputBfMinutes'); + const displayBf = document.getElementById('cfgBfMinDisplay'); + if (inputBf) inputBf.value = bfMinutes; + if (displayBf) displayBf.textContent = bfMinutes; + updateCfgBfChips(bfMinutes); + + const milkType = defConfig.defaultMilkType || 'formula'; + const milkRadio = document.querySelector(`input[name="cfgDefaultMilkType"][value="${milkType}"]`); + if (milkRadio) milkRadio.checked = true; + + // Populate roles dropdown + populateConfigRolesSelect(); + loadRoleConfigForSelectedRole(); +} + +function updateCfgBottleChips(amount) { + document.querySelectorAll('.cfg-bottle-chip').forEach(chip => { + if (parseInt(chip.textContent.trim()) === parseInt(amount)) { + chip.className = 'cfg-bottle-chip active py-1.5 rounded-xl bg-amber-500 text-white transition cursor-pointer font-bold shadow-2xs'; + } else { + chip.className = 'cfg-bottle-chip py-1.5 rounded-xl bg-slate-100 hover:bg-amber-100 transition cursor-pointer font-bold text-slate-700'; + } + }); +} + +function setCfgBottlePreset(ml) { + const input = document.getElementById('cfgInputBottleMl'); + const display = document.getElementById('cfgBottleMlDisplay'); + if (input) input.value = ml; + if (display) display.textContent = ml; + updateCfgBottleChips(ml); +} + +function onCfgBottleInput(val) { + const display = document.getElementById('cfgBottleMlDisplay'); + if (display) display.textContent = val || 0; + updateCfgBottleChips(val); +} + +function updateCfgBfChips(minutes) { + document.querySelectorAll('.cfg-bf-chip').forEach(chip => { + if (parseInt(chip.textContent.trim()) === parseInt(minutes)) { + chip.className = 'cfg-bf-chip active py-1.5 rounded-xl bg-rose-500 text-white transition cursor-pointer font-bold shadow-2xs'; + } else { + chip.className = 'cfg-bf-chip py-1.5 rounded-xl bg-slate-100 hover:bg-rose-100 transition cursor-pointer font-bold text-slate-700'; + } + }); +} + +function setCfgBfPreset(min) { + const input = document.getElementById('cfgInputBfMinutes'); + const display = document.getElementById('cfgBfMinDisplay'); + if (input) input.value = min; + if (display) display.textContent = min; + updateCfgBfChips(min); +} + +function onCfgBfInput(val) { + const display = document.getElementById('cfgBfMinDisplay'); + if (display) display.textContent = val || 0; + updateCfgBfChips(val); +} + +async function saveBabyFeedingDefaults() { + if (!state.currentBabyId) { + showToast('请先选择或新增宝宝', 'warning'); + return; + } + const mode = document.querySelector('input[name="cfgDefaultMode"]:checked')?.value || 'bottle'; + const bottleMl = parseInt(document.getElementById('cfgInputBottleMl')?.value || '120'); + const bfMinutes = parseInt(document.getElementById('cfgInputBfMinutes')?.value || '20'); + const milkType = document.querySelector('input[name="cfgDefaultMilkType"]:checked')?.value || 'formula'; + + const newDefaults = { + defaultFeedingMode: mode, + defaultBottleMl: bottleMl, + defaultBfMinutes: bfMinutes, + defaultMilkType: milkType + }; + + try { + const res = await fetch(`${API_BASE}/babies/${state.currentBabyId}/defaults`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ defaultConfig: newDefaults }) + }); + const json = await res.json(); + if (json.success) { + showToast('宝宝喂养打卡默认配置已更新!'); + const targetBaby = state.babies.find(b => b.baby_id === state.currentBabyId); + if (targetBaby) { + targetBaby.default_config = newDefaults; + } + applyRolePreferences(state.currentOperator); + } else { + showToast(json.error || '保存失败', 'error'); + } + } catch (err) { + console.error('Failed to save baby defaults:', err); + showToast('网络错误,保存失败', 'error'); + } +} + +function populateConfigRolesSelect() { + const select = document.getElementById('cfgRoleSelect'); + if (!select) return; + + const currentVal = select.value; + const currentFam = state.families.find(f => f.family_id === state.currentFamilyId); + const memberRoles = (currentFam && currentFam.members) ? currentFam.members.map(m => m.role_name) : []; + const defaultRoles = ['宝妈', '宝爸', '月嫂', '外婆', '奶奶', '育儿嫂']; + const allRoles = Array.from(new Set([...memberRoles, ...defaultRoles])); + + select.innerHTML = allRoles.map(role => { + const icon = ROLE_ICONS[role] || '👤'; + return ``; + }).join(''); + + if (currentVal && allRoles.includes(currentVal)) { + select.value = currentVal; + } else if (allRoles.includes(state.currentOperator)) { + select.value = state.currentOperator; + } +} + +function loadRoleConfigForSelectedRole() { + const select = document.getElementById('cfgRoleSelect'); + if (!select) return; + const role = select.value; + const pref = state.rolePreferences[role] || {}; + + const mode = pref.defaultFeedingMode || ''; + const modeRadio = document.querySelector(`input[name="cfgRoleMode"][value="${mode}"]`); + if (modeRadio) modeRadio.checked = true; + + const bottleInput = document.getElementById('cfgRoleBottleMl'); + if (bottleInput) bottleInput.value = pref.defaultBottleMl || ''; + + const bfInput = document.getElementById('cfgRoleBfMinutes'); + if (bfInput) bfInput.value = pref.defaultBfMinutes || ''; +} + +async function saveRolePreferencesFromProfile() { + const select = document.getElementById('cfgRoleSelect'); + if (!select) return; + const role = select.value; + + const mode = document.querySelector('input[name="cfgRoleMode"]:checked')?.value || ''; + const bottleMlStr = document.getElementById('cfgRoleBottleMl')?.value?.trim(); + const bfMinStr = document.getElementById('cfgRoleBfMinutes')?.value?.trim(); + + const pref = {}; + if (mode) pref.defaultFeedingMode = mode; + if (bottleMlStr && !isNaN(parseInt(bottleMlStr))) pref.defaultBottleMl = parseInt(bottleMlStr); + if (bfMinStr && !isNaN(parseInt(bfMinStr))) pref.defaultBfMinutes = parseInt(bfMinStr); + + state.rolePreferences[role] = pref; + localStorage.setItem('baby_role_preferences', JSON.stringify(state.rolePreferences)); + + if (state.currentFamilyId) { + try { + await fetch(`${API_BASE}/families/${state.currentFamilyId}/members/${encodeURIComponent(role)}/preferences`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ preferences: pref }) + }); + } catch (e) { + console.warn('Failed to sync role preference:', e); + } + } + + showToast(`【${role}】专属偏好配置已保存!`); + + if (role === state.currentOperator) { + applyRolePreferences(role); + } +} + +// Apply role preferences when operator changes or baby changes +function applyRolePreferences(roleName) { + const baby = state.babies.find(b => b.baby_id === state.currentBabyId); + let defConfig = {}; + if (baby && baby.default_config) { + try { + defConfig = typeof baby.default_config === 'string' ? JSON.parse(baby.default_config) : baby.default_config; + } catch (e) { + defConfig = {}; + } + } + + const pref = state.rolePreferences[roleName] || {}; + const defaultMode = pref.defaultFeedingMode || defConfig.defaultFeedingMode || (roleName === '宝妈' ? 'breastfeed' : 'bottle'); + const bottleMl = pref.defaultBottleMl || defConfig.defaultBottleMl || state.lastBottleMl || 120; + const bfMinutes = pref.defaultBfMinutes || defConfig.defaultBfMinutes || state.bfTargetDuration || 20; + + setFeedingMode(defaultMode, false); + selectBottleAmount(bottleMl, false); + setBfTargetDuration(bfMinutes, false); + + const btnLast = document.getElementById('btnLastBottleAmount'); + if (btnLast) btnLast.textContent = `${bottleMl}ml`; + const bfDurText = document.getElementById('quickBfDurationText'); + if (bfDurText) bfDurText.textContent = `${bfMinutes}m`; + const bfSecText = document.getElementById('quickBfSecText'); + if (bfSecText) bfSecText.textContent = `${bfMinutes}m`; +} + +// Persist role preference locally and async sync to server +function saveRolePreference(key, value) { + const role = state.currentOperator; + if (!state.rolePreferences[role]) { + state.rolePreferences[role] = {}; + } + state.rolePreferences[role][key] = value; + localStorage.setItem('baby_role_preferences', JSON.stringify(state.rolePreferences)); + + if (state.currentFamilyId) { + fetch(`${API_BASE}/families/${state.currentFamilyId}/members/${encodeURIComponent(role)}/preferences`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ preferences: state.rolePreferences[role] }) + }).catch(e => console.warn('Failed to sync role preference:', e)); + } +} + +// Toggle between Breastfeed and Bottle modes +function setFeedingMode(mode, save = true) { + state.feedingMode = mode; + localStorage.setItem('last_feeding_mode', mode); + + const btnBf = document.getElementById('btnModeBreastfeed'); + const btnBottle = document.getElementById('btnModeBottle'); + const secBottle = document.getElementById('feedBottleSection'); + const secBf = document.getElementById('feedBreastfeedSection'); + const cardIcon = document.getElementById('feedingCardIcon'); + const cardTitle = document.getElementById('feedingCardTitle'); + + if (mode === 'breastfeed') { + if (btnBf) { + btnBf.className = 'flex-1 py-1.5 rounded-lg transition bg-white text-rose-700 shadow-2xs flex items-center justify-center space-x-1 whitespace-nowrap font-bold cursor-pointer'; + } + if (btnBottle) { + btnBottle.className = 'flex-1 py-1.5 rounded-lg transition text-stone-600 bg-transparent flex items-center justify-center space-x-1 whitespace-nowrap font-bold cursor-pointer'; + } + if (secBottle) secBottle.classList.add('hidden'); + if (secBf) secBf.classList.remove('hidden'); + if (cardIcon) cardIcon.textContent = '🤱'; + if (cardTitle) cardTitle.textContent = '亲喂打卡'; + } else { + if (btnBottle) { + btnBottle.className = 'flex-1 py-1.5 rounded-lg transition bg-white text-amber-900 shadow-2xs flex items-center justify-center space-x-1 whitespace-nowrap font-bold cursor-pointer'; + } + if (btnBf) { + btnBf.className = 'flex-1 py-1.5 rounded-lg transition text-stone-600 bg-transparent flex items-center justify-center space-x-1 whitespace-nowrap font-bold cursor-pointer'; + } + if (secBottle) secBottle.classList.remove('hidden'); + if (secBf) secBf.classList.add('hidden'); + if (cardIcon) cardIcon.textContent = '🍼'; + if (cardTitle) cardTitle.textContent = '瓶喂打卡'; + } + + if (save) { + saveRolePreference('defaultFeedingMode', mode); + } +} + +// Select Bottle preset amount (ml) +function selectBottleAmount(amount, save = true) { + state.lastBottleMl = amount; + localStorage.setItem('last_bottle_ml', amount); + + const btnLast = document.getElementById('btnLastBottleAmount'); + if (btnLast) btnLast.textContent = `${amount}ml`; + + if (save) { + saveRolePreference('defaultBottleMl', amount); + } +} + +// Set Breastfeed preset target duration (minutes) +function setBfTargetDuration(minutes, save = true) { + state.bfTargetDuration = minutes; + localStorage.setItem('bf_target_duration', minutes); + + const bfDurText = document.getElementById('quickBfDurationText'); + if (bfDurText) bfDurText.textContent = `${minutes}m`; + const bfSecText = document.getElementById('quickBfSecText'); + if (bfSecText) bfSecText.textContent = `${minutes}m`; + + if (save) { + saveRolePreference('defaultBfMinutes', minutes); + } +} + +// Quick log breastfeed default +async function quickLogBreastfeedDefault() { + const dur = state.bfTargetDuration || 20; + const leftM = Math.round(dur / 2); + const rightM = Math.round(dur / 2); + const now = new Date(); + const startTime = new Date(now.getTime() - dur * 60000); + + const pad = n => String(n).padStart(2, '0'); + const fmtDate = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; + + await createRecord({ + activityType: 'breastfeed', + startTime: fmtDate(startTime), + endTime: fmtDate(now), + durationMinutes: dur, + payload: { + leftMinutes: leftM, + rightMinutes: rightM, + note: `秒记亲喂 (双侧均衡共${dur}m)` + } + }); +} + function quickLogBottleDefault() { + const baby = state.babies.find(b => b.baby_id === state.currentBabyId); + let defConfig = {}; + if (baby && baby.default_config) { + try { + defConfig = typeof baby.default_config === 'string' ? JSON.parse(baby.default_config) : baby.default_config; + } catch (e) { + defConfig = {}; + } + } + const milkType = defConfig.defaultMilkType || 'formula'; + createRecord({ activityType: 'bottle', durationMinutes: 15, payload: { - amountMl: state.lastBottleMl, - milkType: 'formula', - note: '快捷一键打卡' + amountMl: state.lastBottleMl || 120, + milkType, + note: milkType === 'formula' ? '秒记冲调配方奶' : '秒记母乳/冷藏储奶' } }); } @@ -1868,18 +2305,856 @@ async function submitBottleRecord() { }); } +// Manual fine-tune breastfeed start and end time async function handleQuickBreastfeed() { + const durStr = prompt('请输入本次亲喂总时长 (分钟):', state.bfTargetDuration || 20); + if (!durStr) return; + const dur = parseInt(durStr) || 20; + const leftM = Math.round(dur / 2); + const rightM = Math.round(dur / 2); + const now = new Date(); + const startTime = new Date(now.getTime() - dur * 60000); + const pad = n => String(n).padStart(2, '0'); + const fmtDate = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; + await createRecord({ activityType: 'breastfeed', - durationMinutes: 20, + startTime: fmtDate(startTime), + endTime: fmtDate(now), + durationMinutes: dur, payload: { - leftMinutes: 10, - rightMinutes: 10, - note: '双侧亲喂' + leftMinutes: leftM, + rightMinutes: rightM, + note: `手动微调亲喂 (左${leftM}m/右${rightM}m)` } }); } +// ---------------------------------------------------- +// Family Memo Checklist Management +// ---------------------------------------------------- +function focusMemoInput() { + const el = document.getElementById('memoInputContent'); + if (el) el.focus(); +} + +function formatDateTimeShort(dtStr) { + if (!dtStr) return '--'; + const d = new Date(typeof dtStr === 'string' ? dtStr.replace(/-/g, '/') : dtStr); + if (isNaN(d.getTime())) return dtStr; + const pad = n => String(n).padStart(2, '0'); + return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; +} + +async function loadMemos() { + if (!state.currentFamilyId) return; + try { + const res = await fetch(`${API_BASE}/memos?familyId=${state.currentFamilyId}`); + const json = await res.json(); + if (json.success) { + state.memos = json.data || []; + renderMemos(); + renderMemoHistoryList(); + } + } catch (err) { + console.error('Failed to load memos:', err); + } +} + +function renderMemos() { + const container = document.getElementById('memoListContainer'); + const countBadge = document.getElementById('memoCountBadge'); + if (!container) return; + + const memos = state.memos || []; + const pendingCount = memos.filter(m => !m.is_completed).length; + if (countBadge) { + countBadge.textContent = `${pendingCount} 项待办`; + } + + if (memos.length === 0) { + container.innerHTML = ` +
+ 今日暂无家庭备忘,在上方快速添加照料提醒吧 📝 +
+ `; + return; + } + + const periodBadges = { + today: { text: '全天', class: 'bg-stone-100 text-stone-600 border-stone-200' }, + morning: { text: '上午', class: 'bg-amber-50 text-amber-700 border-amber-200' }, + afternoon: { text: '下午', class: 'bg-orange-50 text-orange-700 border-orange-200' }, + evening: { text: '睡前', class: 'bg-indigo-50 text-indigo-700 border-indigo-200' } + }; + + container.innerHTML = memos.map(memo => { + const isCompleted = !!memo.is_completed; + const badge = periodBadges[memo.due_period] || periodBadges.today; + const checkedClass = isCompleted ? 'bg-emerald-500 border-emerald-500 text-white' : 'bg-white border-stone-300 text-transparent'; + const textClass = isCompleted ? 'memo-done-text' : 'font-bold text-stone-800'; + const cardBg = isCompleted ? 'bg-stone-50/70 border-stone-200/50' : 'bg-white border-stone-200 shadow-2xs'; + + return ` +
+
+ + + ${badge.text} + + + ${memo.content} + +
+
+ + ${memo.created_by || '家人'} + + + +
+
+ `; + }).join(''); +} + +// ---------------------------------------------------- +// Historical Memos Modal & Maintenance Engine +// ---------------------------------------------------- +function openMemoHistoryModal() { + state.memoHistoryFilter = { status: 'all', period: 'all', search: '' }; + const searchInput = document.getElementById('memoHistorySearchInput'); + if (searchInput) searchInput.value = ''; + const clearBtn = document.getElementById('btnClearMemoSearch'); + if (clearBtn) clearBtn.classList.add('hidden'); + + // Reset filter buttons + document.querySelectorAll('.memo-status-filter').forEach(btn => { + if (btn.dataset.status === 'all') { + btn.className = 'memo-status-filter active px-2.5 py-1 rounded-lg bg-indigo-600 text-white transition cursor-pointer text-xs'; + } else { + btn.className = 'memo-status-filter px-2.5 py-1 rounded-lg text-slate-600 hover:text-slate-900 transition cursor-pointer text-xs'; + } + }); + + document.querySelectorAll('.memo-period-filter').forEach(btn => { + if (btn.dataset.period === 'all') { + btn.className = 'memo-period-filter active px-2 py-0.5 rounded-lg bg-slate-200 text-slate-800 text-[11px] font-bold cursor-pointer'; + } else { + btn.className = 'memo-period-filter px-2 py-0.5 rounded-lg bg-white border border-slate-200 text-slate-600 text-[11px] hover:bg-slate-100 cursor-pointer'; + } + }); + + renderMemoHistoryList(); + openModal('memoHistoryModal'); +} + +function setMemoStatusFilter(status) { + state.memoHistoryFilter.status = status; + document.querySelectorAll('.memo-status-filter').forEach(btn => { + if (btn.dataset.status === status) { + btn.className = 'memo-status-filter active px-2.5 py-1 rounded-lg bg-indigo-600 text-white transition cursor-pointer text-xs'; + } else { + btn.className = 'memo-status-filter px-2.5 py-1 rounded-lg text-slate-600 hover:text-slate-900 transition cursor-pointer text-xs'; + } + }); + renderMemoHistoryList(); +} + +function setMemoPeriodFilter(period) { + state.memoHistoryFilter.period = period; + document.querySelectorAll('.memo-period-filter').forEach(btn => { + if (btn.dataset.period === period) { + btn.className = 'memo-period-filter active px-2 py-0.5 rounded-lg bg-slate-200 text-slate-800 text-[11px] font-bold cursor-pointer'; + } else { + btn.className = 'memo-period-filter px-2 py-0.5 rounded-lg bg-white border border-slate-200 text-slate-600 text-[11px] hover:bg-slate-100 cursor-pointer'; + } + }); + renderMemoHistoryList(); +} + +function onMemoHistoryFilterChange() { + const input = document.getElementById('memoHistorySearchInput'); + const clearBtn = document.getElementById('btnClearMemoSearch'); + const val = input ? input.value.trim().toLowerCase() : ''; + state.memoHistoryFilter.search = val; + + if (clearBtn) { + if (val) clearBtn.classList.remove('hidden'); + else clearBtn.classList.add('hidden'); + } + + renderMemoHistoryList(); +} + +function clearMemoHistorySearch() { + const input = document.getElementById('memoHistorySearchInput'); + if (input) input.value = ''; + onMemoHistoryFilterChange(); +} + +function renderMemoHistoryList() { + const container = document.getElementById('memoHistoryList'); + if (!container) return; + + const memos = state.memos || []; + const totalCount = memos.length; + const pendingCount = memos.filter(m => !m.is_completed).length; + const completedCount = memos.filter(m => !!m.is_completed).length; + + const totalBadge = document.getElementById('memoHistoryTotalCountBadge'); + if (totalBadge) totalBadge.textContent = `${totalCount} 条记录`; + + const countAll = document.getElementById('memoCountAll'); + if (countAll) countAll.textContent = totalCount; + const countPending = document.getElementById('memoCountPending'); + if (countPending) countPending.textContent = pendingCount; + const countCompleted = document.getElementById('memoCountCompleted'); + if (countCompleted) countCompleted.textContent = completedCount; + + // Filter according to filter state + const { status, period, search } = state.memoHistoryFilter; + const filtered = memos.filter(memo => { + if (status === 'pending' && memo.is_completed) return false; + if (status === 'completed' && !memo.is_completed) return false; + if (period !== 'all' && memo.due_period !== period) return false; + if (search) { + const c = (memo.content || '').toLowerCase(); + const by = (memo.created_by || '').toLowerCase(); + if (!c.includes(search) && !by.includes(search)) return false; + } + return true; + }); + + if (filtered.length === 0) { + container.innerHTML = ` +
+ 📭 +
未找到符合条件的备忘待办记录
+

可以尝试更换筛选条件或在下方直接添加新备忘

+
+ `; + return; + } + + const periodBadges = { + today: { text: '📅 全天', class: 'bg-stone-100 text-stone-600 border-stone-200' }, + morning: { text: '☀️ 上午', class: 'bg-amber-50 text-amber-700 border-amber-200' }, + afternoon: { text: '🌤️ 下午', class: 'bg-orange-50 text-orange-700 border-orange-200' }, + evening: { text: '🌙 睡前', class: 'bg-indigo-50 text-indigo-700 border-indigo-200' } + }; + + container.innerHTML = filtered.map(memo => { + const isCompleted = !!memo.is_completed; + const badge = periodBadges[memo.due_period] || periodBadges.today; + const checkedClass = isCompleted ? 'bg-emerald-500 border-emerald-500 text-white' : 'bg-white border-slate-300 text-transparent'; + const textClass = isCompleted ? 'memo-done-text text-slate-400' : 'font-bold text-slate-800'; + const cardBg = isCompleted ? 'bg-slate-50/70 border-slate-200/60' : 'bg-white border-slate-200 shadow-2xs hover:border-indigo-300'; + const createdTimeStr = formatDateTimeShort(memo.created_at); + const completedTimeStr = memo.completed_at ? ` · ✅ 完成于 ${formatDateTimeShort(memo.completed_at)}` : ''; + + return ` +
+
+ +
+
+ + ${badge.text} + + + ${memo.content} + +
+
+ 👤 ${memo.created_by || '家人'} + · 📅 创建于 ${createdTimeStr} + ${completedTimeStr ? `${completedTimeStr}` : ''} +
+
+
+
+ + +
+
+ `; + }).join(''); +} + +function openEditMemoModal(memoId) { + const memo = state.memos.find(m => m.memo_id === memoId); + if (!memo) return; + + const idInput = document.getElementById('editMemoId'); + const contentInput = document.getElementById('editMemoContentInput'); + const periodSelect = document.getElementById('editMemoPeriodSelect'); + const statusPending = document.getElementById('editMemoStatusPending'); + const statusDone = document.getElementById('editMemoStatusDone'); + + if (idInput) idInput.value = memo.memo_id; + if (contentInput) contentInput.value = memo.content || ''; + if (periodSelect) periodSelect.value = memo.due_period || 'today'; + + if (memo.is_completed) { + if (statusDone) statusDone.checked = true; + } else { + if (statusPending) statusPending.checked = true; + } + + openModal('editMemoModal'); +} + +async function submitEditMemo() { + const memoId = document.getElementById('editMemoId')?.value; + const content = document.getElementById('editMemoContentInput')?.value?.trim(); + const duePeriod = document.getElementById('editMemoPeriodSelect')?.value || 'today'; + const isCompleted = document.querySelector('input[name="editMemoStatus"]:checked')?.value === '1'; + + if (!memoId || !content) { + showToast('待办内容不能为空', 'warning'); + return; + } + + closeModal('editMemoModal'); + + try { + const res = await fetch(`${API_BASE}/memos/${memoId}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + content, + duePeriod, + isCompleted + }) + }); + const json = await res.json(); + if (json.success) { + showToast('备忘修改已保存!'); + await loadMemos(); + } else { + showToast(json.error || '保存失败', 'error'); + } + } catch (err) { + console.error('Failed to update memo:', err); + showToast('网络错误,修改失败', 'error'); + } +} + +async function handleCreateMemoFromHistory(event) { + if (event) event.preventDefault(); + const input = document.getElementById('historyModalInputContent'); + const periodSelect = document.getElementById('historyModalDuePeriod'); + const content = input ? input.value.trim() : ''; + const duePeriod = periodSelect ? periodSelect.value : 'today'; + + if (!content) { + showToast('请输入备忘待办内容', 'warning'); + return; + } + + try { + const res = await fetch(`${API_BASE}/memos`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + familyId: state.currentFamilyId, + babyId: state.currentBabyId, + content, + duePeriod, + operatorName: state.currentOperator + }) + }); + const json = await res.json(); + if (json.success) { + input.value = ''; + showToast('新备忘待办已添加!'); + await loadMemos(); + } else { + showToast(json.error || '添加失败', 'error'); + } + } catch (err) { + showToast('网络错误,添加失败', 'error'); + } +} + +async function clearCompletedMemos() { + const completedMemos = (state.memos || []).filter(m => !!m.is_completed); + if (completedMemos.length === 0) { + showToast('当前没有已完成的备忘事项', 'warning'); + return; + } + + if (!confirm(`确定要清理 ${completedMemos.length} 条已完成的历史备忘吗?清理后无法恢复。`)) { + return; + } + + try { + const res = await fetch(`${API_BASE}/memos/clear-completed`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ familyId: state.currentFamilyId }) + }); + const json = await res.json(); + if (json.success) { + showToast(json.message || '已成功清理已完成历史备忘!'); + state.memos = state.memos.filter(m => !m.is_completed); + renderMemos(); + renderMemoHistoryList(); + } else { + showToast(json.error || '清理失败', 'error'); + } + } catch (err) { + console.error('Failed to clear completed memos:', err); + showToast('网络错误,清理失败', 'error'); + } +} + +async function handleCreateMemo(event) { + if (event) event.preventDefault(); + const input = document.getElementById('memoInputContent'); + const periodSelect = document.getElementById('memoDuePeriod'); + const content = input ? input.value.trim() : ''; + const duePeriod = periodSelect ? periodSelect.value : 'today'; + + if (!content) { + showToast('请输入备忘待办内容', 'warning'); + return; + } + + try { + const res = await fetch(`${API_BASE}/memos`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + familyId: state.currentFamilyId, + babyId: state.currentBabyId, + content, + duePeriod, + operatorName: state.currentOperator + }) + }); + const json = await res.json(); + if (json.success) { + input.value = ''; + showToast('备忘待办已添加!'); + await loadMemos(); + } else { + showToast(json.error || '添加失败', 'error'); + } + } catch (err) { + showToast('网络错误,添加失败', 'error'); + } +} + +async function toggleMemoComplete(memoId, currentStatus) { + const m = state.memos.find(item => item.memo_id === memoId); + if (m) { + m.is_completed = currentStatus ? 0 : 1; + m.completed_at = !currentStatus ? new Date().toISOString() : null; + renderMemos(); + renderMemoHistoryList(); + } + + try { + const res = await fetch(`${API_BASE}/memos/${memoId}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + isCompleted: !currentStatus, + operatorName: state.currentOperator + }) + }); + const json = await res.json(); + if (json.success) { + if (!currentStatus) playChimeSound(); + await loadMemos(); + } else { + showToast(json.error || '更新失败', 'error'); + await loadMemos(); + } + } catch (err) { + await loadMemos(); + } +} + +async function deleteMemo(memoId) { + try { + const res = await fetch(`${API_BASE}/memos/${memoId}`, { + method: 'DELETE' + }); + const json = await res.json(); + if (json.success) { + showToast('备忘待办已删除'); + state.memos = state.memos.filter(item => item.memo_id !== memoId); + renderMemos(); + renderMemoHistoryList(); + } else { + showToast(json.error || '删除失败', 'error'); + } + } catch (err) { + showToast('网络错误', 'error'); + } +} + +// ---------------------------------------------------- +// Focus Countdown Timer Engine +// ---------------------------------------------------- +function playChimeSound() { + try { + const AudioCtx = window.AudioContext || window.webkitAudioContext; + if (!AudioCtx) return; + const ctx = new AudioCtx(); + const osc = ctx.createOscillator(); + const gain = ctx.createGain(); + osc.type = 'sine'; + osc.frequency.setValueAtTime(523.25, ctx.currentTime); // C5 + osc.frequency.exponentialRampToValueAtTime(659.25, ctx.currentTime + 0.25); // E5 + gain.gain.setValueAtTime(0.25, ctx.currentTime); + gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 1.2); + osc.connect(gain); + gain.connect(ctx.destination); + osc.start(ctx.currentTime); + osc.stop(ctx.currentTime + 1.2); + if (navigator.vibrate) navigator.vibrate([150, 80, 150]); + } catch (e) { + console.warn('AudioContext not allowed or not supported:', e); + } +} + +function handleStartBfCountdown() { + startFocusTimer('breastfeed', state.bfTargetDuration); +} + +function startFocusTimer(activityType = 'breastfeed', targetMinutes = 20) { + if (state.activeTimer && state.activeTimer.type === activityType) { + openFocusModal(); + return; + } + if (state.activeTimer && state.activeTimer.timerInterval) { + clearInterval(state.activeTimer.timerInterval); + } + + const now = Date.now(); + state.activeTimer = { + type: activityType, + startTime: now, + targetMinutes: targetMinutes, + currentSide: 'left', + leftSeconds: 0, + rightSeconds: 0, + isPaused: false, + pauseStartTime: null, + totalPausedMs: 0, + lastTickTime: now, + timerInterval: null + }; + + updateFocusModalAppearance(activityType); + state.activeTimer.timerInterval = setInterval(tickFocusTimer, 500); + + const btnBfExpand = document.getElementById('btnBfFocusExpand'); + if (btnBfExpand && activityType === 'breastfeed') btnBfExpand.classList.remove('hidden'); + + renderFocusTimer(); + openFocusModal(); + showToast(`⏱️ ${activityType === 'breastfeed' ? '亲喂' : '睡眠'}倒计时专注已开启!`); +} + +function updateFocusModalAppearance(type) { + const iconEl = document.getElementById('focusActivityIcon'); + const titleEl = document.getElementById('focusActivityTitle'); + const babyBadge = document.getElementById('focusBabyBadge'); + const opTip = document.getElementById('focusOperatorTip'); + const sideStats = document.getElementById('focusBfSideStats'); + const ring = document.getElementById('focusRingCircle'); + + const currentBaby = state.babies.find(b => b.baby_id === state.currentBabyId); + if (babyBadge) babyBadge.textContent = currentBaby ? currentBaby.name : '宝宝'; + if (opTip) opTip.textContent = `当前记录人: ${state.currentOperator} · 保持静心专注`; + + if (type === 'breastfeed') { + if (iconEl) iconEl.textContent = '🤱'; + if (titleEl) titleEl.textContent = '亲喂专注倒计时'; + if (sideStats) sideStats.classList.remove('hidden'); + if (ring) { + ring.setAttribute('stroke', '#F59E0B'); + ring.classList.remove('focus-sleep-glow'); + ring.classList.add('focus-glow-ring'); + } + } else if (type === 'sleep') { + if (iconEl) iconEl.textContent = '😴'; + if (titleEl) titleEl.textContent = '睡眠哄睡专注大屏'; + if (sideStats) sideStats.classList.add('hidden'); + if (ring) { + ring.setAttribute('stroke', '#8B5CF6'); + ring.classList.remove('focus-glow-ring'); + ring.classList.add('focus-sleep-glow'); + } + } else { + if (iconEl) iconEl.textContent = '⏱️'; + if (titleEl) titleEl.textContent = '日常专注倒计时'; + if (sideStats) sideStats.classList.add('hidden'); + } +} + +function tickFocusTimer() { + if (!state.activeTimer) return; + const t = state.activeTimer; + + if (t.isPaused) return; + + const now = Date.now(); + const deltaSec = Math.max(0, (now - t.lastTickTime) / 1000); + t.lastTickTime = now; + + if (t.type === 'breastfeed') { + if (t.currentSide === 'left') { + t.leftSeconds += deltaSec; + } else { + t.rightSeconds += deltaSec; + } + } + + renderFocusTimer(); +} + +function renderFocusTimer() { + if (!state.activeTimer) return; + const t = state.activeTimer; + + const totalTargetSec = t.targetMinutes * 60; + const totalElapsedSec = Math.floor((t.type === 'breastfeed') ? (t.leftSeconds + t.rightSeconds) : Math.max(0, (Date.now() - t.startTime - t.totalPausedMs) / 1000)); + const remainingSec = Math.max(0, totalTargetSec - totalElapsedSec); + + const fmt = (s) => { + const m = Math.floor(s / 60); + const sec = Math.floor(s % 60); + return `${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`; + }; + + const digitsEl = document.getElementById('focusDigitsDisplay'); + const subInfoEl = document.getElementById('focusSubInfo'); + const phaseEl = document.getElementById('focusCurrentPhaseText'); + + if (remainingSec > 0) { + if (digitsEl) digitsEl.textContent = fmt(remainingSec); + } else { + const overtime = totalElapsedSec - totalTargetSec; + if (digitsEl) digitsEl.textContent = `+${fmt(overtime)}`; + if (totalElapsedSec === totalTargetSec) { + playChimeSound(); + } + } + + if (subInfoEl) { + subInfoEl.textContent = `目标: ${t.targetMinutes}分钟 · 已进行: ${fmt(totalElapsedSec)}`; + } + + if (phaseEl) { + if (t.isPaused) { + phaseEl.textContent = '⏸ 计时已暂停'; + phaseEl.className = 'text-xs sm:text-sm font-bold tracking-widest text-stone-400 uppercase mb-1'; + } else if (t.type === 'breastfeed') { + phaseEl.textContent = t.currentSide === 'left' ? '左侧哺乳进行中' : '右侧哺乳进行中'; + phaseEl.className = 'text-xs sm:text-sm font-bold tracking-widest text-amber-300 uppercase mb-1'; + } else { + phaseEl.textContent = '倒计时进行中'; + phaseEl.className = 'text-xs sm:text-sm font-bold tracking-widest text-purple-300 uppercase mb-1'; + } + } + + const ring = document.getElementById('focusRingCircle'); + if (ring) { + const progressRatio = Math.min(1, Math.max(0, remainingSec / totalTargetSec)); + const dashoffset = 754 * (1 - progressRatio); + ring.style.strokeDashoffset = dashoffset; + } + + if (t.type === 'breastfeed') { + const leftTimeEl = document.getElementById('focusLeftTime'); + const rightTimeEl = document.getElementById('focusRightTime'); + const btnLeft = document.getElementById('btnFocusLeftBreast'); + const btnRight = document.getElementById('btnFocusRightBreast'); + + if (leftTimeEl) leftTimeEl.textContent = fmt(t.leftSeconds); + if (rightTimeEl) rightTimeEl.textContent = fmt(t.rightSeconds); + + if (btnLeft && btnRight) { + if (t.currentSide === 'left') { + btnLeft.className = 'px-4 py-2 rounded-2xl bg-amber-500/25 border-2 border-amber-400 text-amber-200 font-bold text-xs flex items-center space-x-2 transition shadow-sm'; + btnRight.className = 'px-4 py-2 rounded-2xl bg-white/5 border border-white/20 text-stone-400 font-bold text-xs flex items-center space-x-2 transition'; + } else { + btnRight.className = 'px-4 py-2 rounded-2xl bg-amber-500/25 border-2 border-amber-400 text-amber-200 font-bold text-xs flex items-center space-x-2 transition shadow-sm'; + btnLeft.className = 'px-4 py-2 rounded-2xl bg-white/5 border border-white/20 text-stone-400 font-bold text-xs flex items-center space-x-2 transition'; + } + } + } + + const floatingDigits = document.getElementById('floatingTimerDigits'); + const floatingTitle = document.getElementById('floatingTimerTitle'); + if (floatingDigits) floatingDigits.textContent = remainingSec > 0 ? fmt(remainingSec) : `+${fmt(totalElapsedSec - totalTargetSec)}`; + if (floatingTitle) { + const sideText = t.type === 'breastfeed' ? `(${t.currentSide === 'left' ? '左侧' : '右侧'})` : ''; + floatingTitle.textContent = `${t.type === 'breastfeed' ? '亲喂' : '睡眠'}中 ${sideText}`; + } +} + +function switchBreastSide(side) { + if (!state.activeTimer) return; + state.activeTimer.currentSide = side; + state.activeTimer.lastTickTime = Date.now(); + renderFocusTimer(); + showToast(`已切换至【${side === 'left' ? '左侧' : '右侧'}】继续计时`); +} + +function toggleBreastSide() { + if (!state.activeTimer) return; + const nextSide = state.activeTimer.currentSide === 'left' ? 'right' : 'left'; + switchBreastSide(nextSide); +} + +function addFocusMinutes(m = 5) { + if (!state.activeTimer) return; + state.activeTimer.targetMinutes += m; + renderFocusTimer(); + showToast(`已延长 ${m} 分钟专注时长`); +} + +function togglePauseFocusTimer() { + if (!state.activeTimer) return; + const t = state.activeTimer; + t.isPaused = !t.isPaused; + + const pauseIcon = document.getElementById('focusPauseIcon'); + const pauseText = document.getElementById('focusPauseText'); + + if (t.isPaused) { + t.pauseStartTime = Date.now(); + if (pauseIcon) pauseIcon.textContent = '▶'; + if (pauseText) pauseText.textContent = '继续'; + showToast('计时已暂停'); + } else { + if (t.pauseStartTime) { + t.totalPausedMs += (Date.now() - t.pauseStartTime); + t.pauseStartTime = null; + } + t.lastTickTime = Date.now(); + if (pauseIcon) pauseIcon.textContent = '⏸'; + if (pauseText) pauseText.textContent = '暂停'; + showToast('计时已继续'); + } + renderFocusTimer(); +} + +async function completeFocusTimerAndRecord() { + if (!state.activeTimer) return; + const t = state.activeTimer; + + if (t.timerInterval) clearInterval(t.timerInterval); + + const totalElapsedSec = Math.floor((t.type === 'breastfeed') ? (t.leftSeconds + t.rightSeconds) : Math.max(0, (Date.now() - t.startTime - t.totalPausedMs) / 1000)); + const durationMinutes = Math.max(1, Math.round(totalElapsedSec / 60)); + + const endTime = new Date(); + const startTime = new Date(endTime.getTime() - durationMinutes * 60000); + + const pad = n => String(n).padStart(2, '0'); + const fmtDate = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; + + let recordData = { + activityType: t.type, + startTime: fmtDate(startTime), + endTime: fmtDate(endTime), + durationMinutes: durationMinutes, + operatorName: state.currentOperator + }; + + if (t.type === 'breastfeed') { + const leftM = Math.max(0, Math.round(t.leftSeconds / 60)); + const rightM = Math.max(0, Math.round(t.rightSeconds / 60)); + recordData.payload = { + leftMinutes: leftM, + rightMinutes: rightM, + note: `倒计时专注完成 (左${leftM}m/右${rightM}m)` + }; + } else if (t.type === 'sleep') { + recordData.payload = { + note: `倒计时睡眠专注打卡` + }; + } + + playChimeSound(); + closeFocusModal(); + + const floatingWidget = document.getElementById('floatingTimerWidget'); + if (floatingWidget) floatingWidget.classList.add('hidden'); + const btnBfExpand = document.getElementById('btnBfFocusExpand'); + if (btnBfExpand) btnBfExpand.classList.add('hidden'); + + state.activeTimer = null; + await createRecord(recordData); +} + +function cancelFocusTimer() { + if (!confirm('确定要放弃并退出本次计时吗?')) return; + if (state.activeTimer && state.activeTimer.timerInterval) { + clearInterval(state.activeTimer.timerInterval); + } + state.activeTimer = null; + closeFocusModal(); + const floatingWidget = document.getElementById('floatingTimerWidget'); + if (floatingWidget) floatingWidget.classList.add('hidden'); + const btnBfExpand = document.getElementById('btnBfFocusExpand'); + if (btnBfExpand) btnBfExpand.classList.add('hidden'); + showToast('本次计时已取消'); +} + +function openFocusModal(activityType) { + if (activityType && (!state.activeTimer || state.activeTimer.type !== activityType)) { + startFocusTimer(activityType); + return; + } + const modal = document.getElementById('focusModal'); + const floatingWidget = document.getElementById('floatingTimerWidget'); + if (modal) modal.classList.remove('hidden'); + if (floatingWidget) floatingWidget.classList.add('hidden'); + if (state.activeTimer) { + updateFocusModalAppearance(state.activeTimer.type); + renderFocusTimer(); + } +} + +function minimizeFocusModal() { + const modal = document.getElementById('focusModal'); + const floatingWidget = document.getElementById('floatingTimerWidget'); + if (modal) modal.classList.add('hidden'); + if (state.activeTimer && floatingWidget) { + floatingWidget.classList.remove('hidden'); + } +} + +function closeFocusModal() { + const modal = document.getElementById('focusModal'); + if (modal) modal.classList.add('hidden'); + if (state.activeTimer) { + const floatingWidget = document.getElementById('floatingTimerWidget'); + if (floatingWidget) floatingWidget.classList.remove('hidden'); + } +} + async function handleQuickDiaper(subType = 'pee') { await createRecord({ activityType: 'diaper', diff --git a/public/index.html b/public/index.html index 5e000e3..8fdc09c 100644 --- a/public/index.html +++ b/public/index.html @@ -25,47 +25,47 @@ - + - -
+ +
-
+
-