Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f33732b79d | ||
|
|
289706d1fc | ||
|
|
1eb351b0dd | ||
|
|
1734f8e646 |
@@ -0,0 +1,123 @@
|
||||
# Agent Note: 六屏与浮窗按设计系统重排
|
||||
|
||||
Status: implemented
|
||||
|
||||
## Problem
|
||||
|
||||
`lpt-android/.agents/roles/design-system.md` 登记了 8 条现状偏差,到今天一条没消化,界面仍是「M3 默认模板只换了主色」的样子:主色是 `#1F6FEB` 蓝、深色只覆盖 4 个槽位、任务条目与页面区块同为灰 `Card`、任务页顶栏并排四个等权 `TextButton`、`labelSmall`(11sp)承担会话号与时间戳、空态与错误态共用一条分支、间距散在 9 个档位。真机截图(1080×2400,`f5269dcc`)可见全部问题。
|
||||
|
||||
浮窗虽然没有上面这些问题,但仍有自己的一批小偏离:状态行与「轻触收起」用 11sp(低于 12sp 下限)、胶囊内指示点 5dp(登记值 4dp)、面板顶部内边距 10dp(不在五档内)、按钮水波纹是方角(`RippleDrawable` 传了 `mask = null`,圆角背景外侧不裁切)、碎片输入页用 placeholder 代替 label(`ui-review-checklist.md` 明确禁止)。
|
||||
|
||||
## Decision
|
||||
|
||||
一次改完六个 Compose 页面与浮窗,全部取值以 `.agents/roles/design-system.md` 为准,新增取值当场登记回该文件。目标态线框在 `docs/diagrams/android-ui/`(8 份 `.svg` + 生成脚本),构图经用户确认。
|
||||
|
||||
### 颜色(浅色 / 深色)
|
||||
|
||||
| 语义 | 浅色 | 深色 | 实测对比度 |
|
||||
|---|---|---|---|
|
||||
| 页底 | `#F7FBF8` | `#111A16` | 深色主文字 15.06:1 |
|
||||
| 面(区块、条目) | `#FFFFFF` | `#1B2A23` | 16.11:1 / 12.71:1 |
|
||||
| 输入框底、内嵌块 | `#F1F6F3` | `#22332B` | 深色次要字 7.50:1 |
|
||||
| primary / onPrimary | `#237556` / `#FFFFFF` | `#7FD8B4` / `#111A16` | 5.60:1 / 10.47:1 |
|
||||
| primaryContainer / on | `#EEF9F3` / `#237556` | `#17332A` / `#7FD8B4` | 5.19:1 / 8.02:1 |
|
||||
| tertiaryContainer / on(到时、暂停提醒条) | `#FFF8E1` / `#856404` | `#3A3220` / `#FFD08A` | 5.17:1 / 11.00:1 |
|
||||
| onSurfaceVariant | `#4B6156` | `#B3C7BD` | 6.40:1 / 9.99:1 |
|
||||
| outline(图标、强描边) | `#6B7F75` | `#7C9186` | 4.27:1 / 5.28:1 |
|
||||
| outlineVariant(1dp 分组描边) | `#C6D6CD` | `#33453D` | 1.5:1,仅分隔,不表达状态 |
|
||||
| error / errorContainer / on | `#B62324` / `#FDECEA` / `#B62324` | `#F85149` / `#3A1F1F` / `#FF8A80` | 5.64:1 / 4.49:1→用 `#FF8A80` 取 6.59:1 |
|
||||
|
||||
### 间距、字号、圆角
|
||||
|
||||
- 间距只用 4 / 8 / 12 / 16 / 24;屏幕水平边距 16(登录页 24 是已登记例外)。
|
||||
- 字号只用 28 / 22 / 16 / 14 / 12,以及会话页计时 44(唯一自造字号,等宽 + 粗体)。`labelSmall`(11sp)全仓停用。
|
||||
- 圆角:条目 8、区块 12、浮窗拉起的输入页 18。
|
||||
|
||||
### 容器语法
|
||||
|
||||
- 页面区块 = `Surface`(`shapes.medium`,`surface` 实底,无描边、无阴影)。
|
||||
- 列表条目 = `Surface`(`shapes.small` + `BorderStroke(1.dp, outlineVariant)`)。
|
||||
- 不用 `Card` 兼职两种层级。
|
||||
|
||||
### 各屏结构(与线框一致)
|
||||
|
||||
| 屏 | 首屏留下 | 删掉 |
|
||||
|---|---|---|
|
||||
| `TaskListScreen` | 标题 + 唯一动作「设置」;进行中会话块(`primaryContainer`,整块可点、不带箭头);搜索框(任务 ≥6 才出现,只描一条边);任务条目(点条目先弹确认) | 「已登录:xxx」、「共 N 个任务」、「刷新」「权限」「退出登录」、条目箭头 |
|
||||
| `SessionScreen` | 返回 + 任务名(`titleMedium`);倒计时小字、44sp 计时、有效学习时间;「暂停/继续」实底、「结束学习」描边各占一行;「显示悬浮窗」文字入口;预期块(已填 = 文本 +「修改」);碎片块(输入 + 最近 3 条 +「查看全部」) | 「状态:进行中」、「已暂停 · 」前缀、底部「正在与服务器同步…」、「误操作结束(零数据 / …)」长串 |
|
||||
| `ReportsScreen` | 日期 + 会话号 + 会话摘要,其余三段收进「展开全文」;「查看本次碎片」降为次要色;「加载更多」 | 每条重复的「学习报告」标题、绿色章节标签、11sp 时间戳 |
|
||||
| `SettingsScreen` | 权限段(标题 + 为什么 + 右侧状态/「去开启」)、MIUI 额外设置(收起)、服务器地址(当前值 +「修改」)、「退出登录」 | 任务页顶栏的权限与退出入口、与权限页重复的整段说明 |
|
||||
| `PermissionScreen`(首启) | 复用同一套权限行,标题「能不能跨应用计时,取决于这三项」,底部「已完成,去学习任务」,右上「稍后」 | 页面级说明段(理由挪进每行) |
|
||||
| `LoginScreen` | 标题、账号、密码、全宽「登录」、「修改 API 地址」 | 副标题、页脚「LPT」、写死域名的那行提示 |
|
||||
| `OverlayView` | 三件事不变(倒计时、记一条碎片、暂停/继续) | 11sp 文案、5dp 点、10dp 内边距、方角水波纹 |
|
||||
|
||||
### 动作命名(四处同名)
|
||||
|
||||
| 动作 | 按钮 | 加载中 | 成功提示 |
|
||||
|---|---|---|---|
|
||||
| 记一条碎片 | 记碎片 | 记碎片… | 已记碎片 |
|
||||
| 结束 | 结束学习 | 结束中… | 已结束学习 |
|
||||
| 暂停 / 继续 | 暂停 / 继续 | — | 已暂停 / 已继续学习 |
|
||||
|
||||
会话页的「误操作结束」放页面最底一行文字入口,点开二次确认;浮窗不加任何入口。确认语以浅底块展示、右侧「复制」,按下变「已复制」,用户长按输入框粘贴即可。
|
||||
|
||||
### 第二轮评审后的修订(2026-11-20)
|
||||
|
||||
独立评审第一轮 7/10、三条 P1;按清单修完后落地了这些决定:
|
||||
|
||||
| 问题 | 改法 | 为什么不是另一种改法 |
|
||||
|---|---|---|
|
||||
| 报告不是结论先行、空卡还露「展开全文」 | 首行取「预期达成判断」,没写就退到会话摘要、再退到本次预期;三者全空才写「这次会话没有留下文字记录」,此时 `hasMore` 为假、不渲染「展开全文」 | 不给「未填写预期达成判断」当结论:每张卡都挂一句「未填写」等于没有结论,还把缺失当成内容展示 |
|
||||
| 报告卡首行挤着会话号与日期 | 去掉会话号,只留日期 | 会话号是排障用的,学习者扫列表时只会被一串十六进制打断;日期足够定位,真要查库里也有 |
|
||||
| 任务页没有唯一主操作、两行等权文字按钮 | 「开始学习」改为主色文字并靠右(整条仍可点),「报告」降为 `bodySmall` 灰色 `TextButton` 靠左;动作行上方留 `Dimens.Group` | 不新增第二颗实底按钮:一屏里实底只该有一个,两个都是实底就谁都不像主操作 |
|
||||
| 优先级在 200% 下与任务名挤行 | 优先级移到任务名同一行右侧、等宽小字 | 不删数字:它是排序依据,删掉用户就不知道为什么这条排在前面 |
|
||||
| Snackbar 是全屏最亮的一块并盖住动作 | 改 `surfaceContainerHigh` 底 + `onSurface` 字 + `shapes.small`,左右留 `Dimens.Screen` | 不用默认 `inverseSurface`:深色下它比白色卡片还亮,提示条成了视觉焦点 |
|
||||
| 搜索框占着次级视觉最强位 | 去实心底,只留 1dp `outlineVariant` 边框,高度 40dp | 不做「点开才出现」的折叠搜索:任务 ≥6 时搜索本来就是常用入口,藏起来要多一次点击 |
|
||||
| 浮窗两个动作一实一虚(记碎片实底、暂停描边) | 两个都改 `BUTTON` 底 + 1dp 描边 + `TEXT` 字,`MINT` 只留给倒计时;删掉「轻触收起」提示文字 | 浮窗不设主操作,且放不下第二个手势说明;收起只保留点把手 + 无障碍描述 |
|
||||
| 200% 字体下碎片输入的 label 被按钮挤成两行 | `fontScale ≥ 1.5` 时输入占满一行、按钮另起一行右对齐 | 不给 label 换短词:短词会和按钮「记碎片」重复,与上一轮「label 不重复标题」的结论冲突 |
|
||||
|
||||
第二轮评审的其余 P2 也在这一轮落地:有进行中会话时点任务直接弹「先结束这次学习」(只给「回到会话」,不再连弹两个框);「显示悬浮窗」点完弹「悬浮窗已显示」;误操作结束因记过碎片而灰掉时写明「请用『结束学习』」;搜索框高 40→48dp;确认语块补 1dp 描边(`surfaceVariant` 与弹窗底几乎同色);会话页底部留双倍 `Dimens.Block` 给 snackbar 让位;报告首行标出角色(预期达成判断 / 会话摘要 / 本次预期),展开区不再重贴首行那段;浮窗按钮去掉「+」前缀与页面同名。浮窗两个动作维持同一行——规则里写的「各占一行」改成「同一行、同权重」:面板只有 224dp 宽,纵向多一行会多遮 48dp 内容。
|
||||
|
||||
任务条目的落地动作另加一道确认(`pendingTask` + `AlertDialog`):整条可点是给手好按,但一步就进会话开始计时,误触代价不小。确认框正文写「开始后进入会话页,悬浮窗开始计时;学完在会话页结束」,无数据副作用,连点只在 `starting` 时禁用。
|
||||
|
||||
### 实现顺序
|
||||
|
||||
1. 取值与共用件:`ui/theme/Theme.kt` 两个色板补全、新增 `ui/theme/Dimens.kt`、新增 `ui/components/`(页头、区块、条目、空态、行内错误)。
|
||||
2. 任务页 + 设置页 + 权限段 + `MainActivity` 导航(`MainActivity` 只有一个写者)。
|
||||
3. 会话页 + 报告页 + 登录页。
|
||||
4. 浮窗 + 碎片输入页 + `SessionController` 文案。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **只换主色,不动结构与文案**:最强论据是改动面小、几乎不可能回归。否决:登记偏差里有 5 条是结构问题(顶栏四按钮、容器不分级、空错同分支、间距散档、11sp 正文),只换色等于把「M3 默认模板」的骨架留到一个更亮的绿色上。
|
||||
- **保留蓝色主色**:最强论据是蓝色在深色下更好对比、且已有用户习惯。否决:同一产品两端不该有两个品牌色,`lpt-fe` 用的是 `#237556`;而且 `#1F6FEB` 正是 M3 模板的默认落点,保留它等于承认禁用清单里「只改主色」那条。
|
||||
- **深色继续只覆盖 4 个槽位**:最强论据是深色用得少。否决:M3 未覆盖的槽位会退回默认紫灰(真机截图里页底就是 `#1C1B1F`),与绿色主色拼在一起像两个产品。
|
||||
- **浮窗收起态显示 `mm:ss`**:最强论据是「浮窗展示倒计时」写在 `AGENTS.md` 里,收起后看不到时间等于这条没兑现。否决:收起态只露出 24dp 把手(已登记例外),12sp 的 `12:34` 约 30dp,放不下;把把手放宽会重新变成常态遮挡。本轮只做取值对齐,收起态仍是一点一箭头,倒计时在展开后与前台通知里可见。
|
||||
- **报告页保留四段全展开**:最强论据是不用第二次点击。否决:一屏只放得下一次半的学习记录,回看时要先滚过大量正文才能找到想读的那次。
|
||||
|
||||
## 验证结果
|
||||
|
||||
已做到:
|
||||
|
||||
- `./gradlew --offline :app:assembleDebug :app:testDebugUnitTest :app:lintDebug` 三条全绿,单元测试 22 条 0 失败,lint 0 error / 25 warning(存量基线,无新增)。
|
||||
- 取值收敛实测:`labelSmall` 0 处、`Card(` 0 处、`Color(0x…)` 只出现在 `ui/theme/Theme.kt`、`Spacer(0.dp)` 0 处。
|
||||
- 独立评审两轮:第一轮 7/10(3 条 P1),第二轮 8/10(无 P1,9 条 P2 中 7 条当场修掉,2 条按下述取舍保留)。第二轮结论「方向成立、无阻断项」。
|
||||
- 真机截图(`f5269dcc`,1080×2400):任务页默认 / 200% 字体 / 点任务确认框 / 有会话时的冲突框;报告页列表与展开;会话页默认与 200% 字体;误操作结束弹窗(含复制确认语);碎片写入后的提示条;悬浮窗展开态与叠在第三方桌面上的收起态;设置页(浅色,含权限段两种状态);深色与浅色两套主题。
|
||||
|
||||
未取证,老实记着:
|
||||
|
||||
- **加载骨架屏**:断网启动是秒失败(直接进错误态,这是正确行为),有网时秒开,`screencap` 有约 1 秒延迟,录屏抓帧也没逮到只有骨架的一帧。
|
||||
- **真·零任务空态**:现有账号有 5 条任务,只能取到「搜索无匹配」那种空态;同一套 `LptEmptyState`,但不是零数据分支。
|
||||
- **130% 字体、横屏**:本轮只验了 100% 与 200% 两端,130% 与横屏未单独截图。
|
||||
- **首启权限引导页**:MIUI 上 `appops set SYSTEM_ALERT_WINDOW deny/ignore`、`pm revoke` 都撤不掉悬浮窗权限,取不到首启态;该页与设置页权限段是同一组件,后者已截。
|
||||
- **登录页**:退出登录会销毁会话且手上没有可用的测试口令,没截。
|
||||
|
||||
本轮不做:新建任务入口、报告第四段(按归属分组的碎片)、浮窗信息架构变更。
|
||||
|
||||
## Consequences
|
||||
|
||||
- **下拉刷新依赖 M3 的 `PullToRefreshBox`**:Compose BOM `2026.03.01` 里它可能仍是实验 API。若不可用,退化为「列表顶部一行刷新文字入口」,并在这里补记。
|
||||
- **200% 字体**:任务名与描述在 360dp 宽下会换行到三行,条目高度变大;线框只画了 100%。真机验证若出现截断,按 `design-principles.md` 的降级顺序处理,不缩字号。
|
||||
- **`MainActivity` 只有一个写者**:任务页与设置页都要改导航,必须同属一个改动单元,否则并行写同一文件会互相覆盖。
|
||||
- **复制确认语降低了「停下来读一遍」的门槛**:一键复制 + 粘贴把这道确认变成两次点击。这是用户明确要求的取舍(手打十二个汉字更容易出错),复制只写剪贴板、不代填不代提交;若将来要收紧,先去掉复制而不是加提示。
|
||||
- **浮窗是经典 View**:不读 `MaterialTheme`,颜色仍走 `OverlayView` 的 companion object 常量;本轮只改字号、间距与圆角水波纹,不改窗口标志与拖拽逻辑。
|
||||
@@ -0,0 +1,52 @@
|
||||
# Agent Note: Android 补齐主操作位置、按钮样子与命名规矩
|
||||
|
||||
Status: implemented
|
||||
|
||||
## Problem
|
||||
|
||||
`lpt-fe` 补完设计规则(位置、状态、降级、命名)后,把同一套对照逐条拿到 Android 上核了一遍。结论是六项缺、五项不必搬。
|
||||
|
||||
缺的六项,都是「规则写了方向,但没给可照着做的样子」:
|
||||
|
||||
1. **写码前没有计划环节**:`design-principles.md` 只有一张「哪个屏的主操作是什么」的表,没有「主操作放在屏幕哪个位置」。于是顶栏四个等权 `TextButton`(权限 / 设置 / 刷新 / 退出登录)这种写法只能靠事后评审发现。
|
||||
2. **按钮只有类型,没有样子**:主操作是 `Button`、次级是 `OutlinedButton`,但按下、键盘聚焦、禁用、加载中四种状态没有任何规定。Compose 里去掉 `indication` 一行就能把水波纹和焦点高亮一起删掉,没人拦。
|
||||
3. **主操作没有「让位顺序」**:系统字体放大到 200% 时按钮文字会挤出容器,规则里只有「不截断」这个结果,没说先改什么、最后不许改什么。
|
||||
4. **命名只有一句原则**:「按钮说清按下去会发生什么」拦不住「确定」这类写法,也没有规定按钮、加载中、成功提示、撤销四处要同名。
|
||||
5. **图标按钮没有规矩**:`contentDescription` 有了,但 `Tooltip`、48dp 命中区、什么时候才允许只用图标,都没有。
|
||||
6. **自检清单 60 多条,没有轻量档**:改一个按钮的位置也要过整份清单,实际上没人会走。
|
||||
|
||||
不必搬的五项:断点与视口矩阵(Android 已有 360dp 小屏、130%/200% 字号、分屏与可折叠、横屏四条,比 web 的断点更贴设备)、颜色字面量门禁(`Color(0x…)` 只在 `Theme.kt` 出现)、旧名治理(Kotlin 里「残片」0 处,35 处都写的是「碎片」)、悬停的触屏等价(Android 根本没有悬停)、`responsive.md` 整份文件(「空间不够怎么办」已在上面第 3 条局部解决)。
|
||||
|
||||
## Decision
|
||||
|
||||
在 `.agents/roles/` 的四份规则里补条款,不新增文件,也不从 `lpt-fe` 复制正文——沿用 `2026-11-19-android-ui-rules.md` 定的「两仓各自持有、只在同源意图处互相引用路径」。
|
||||
|
||||
| 文件 | 改了什么 |
|
||||
|---|---|
|
||||
| `design-principles.md` | 新增「动手前:一页设计计划」(新页面 ≤12 行、中等改动 3–5 行);新增「主操作的位置」对照表(列表 / 会话 / 阅读 / 弹窗 / 空态 / 浮窗六种场景,含 `confirmButton` 在右、`dismissButton` 在左);新增「主操作不因字号放大让位」与五步降级顺序;文案即设计补命名配方(动词 + 宾语、四处同名、六个禁用词、破坏性写后果、术语正式名);评审触发改三档 |
|
||||
| `design-system.md` | 按钮补五种样子的对照表(常态 / 按下 / 键盘聚焦 / 禁用 / 加载中,三类按钮各一列);补图标按钮规矩(`contentDescription` + `Tooltip` + 48dp);新增「动效」一节(只动 alpha 与 offset、200ms 量级、关掉系统动画后仍可用) |
|
||||
| `code-standards.md` | 文案段改为指向命名规矩并补术语;视觉实现补一条「不许 `indication = null` 把按下与焦点反馈一起删掉」 |
|
||||
| `ui-review-checklist.md` | 开头加「快检 10 条」(改主操作位置或名字、加图标按钮、改顶栏或底部按钮区时必过);字号 200% 那条补「空间不够按降级顺序退,不缩主操作字号」;交付前补快检结论一行 |
|
||||
| `AGENTS.md`(本仓与 meta) | 索引描述改为「写码前设计计划与页面结构取舍」「快检与交付自检」 |
|
||||
|
||||
浮窗是经典 View,不读 `MaterialTheme`:按钮样子表与动效条款只对 Compose 页面上生效,`design-system.md` 顶部的「适用范围」已经写明这条边界,没有为浮窗另造一套按钮状态。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **把 `lpt-fe` 的 `responsive.md` 整份搬到 Android** — 最强论据是两端「空间不够怎么办」口径统一,评审时不用记两套。否决:那份文件的核心是 768/1024/1280 三档断点与七档视口,Android 一条都用不上(设备宽度靠 `WindowSizeClass` 与真机矩阵解决),搬过来只有「先改布局再改字号」一句有效,已单独写进主操作让位那条。
|
||||
- **抽到 meta 做跨端母规则** — 最强论据是同一件事只写一次。否决理由与上一篇笔记相同:抽掉实现锚点(`Button` / `TextButton` / `.el-button` / `dp` / `sp`)后母规则只剩口号,两端都验证不了。
|
||||
- **加 lint 脚本查色值与字号字面量** — 最强论据是把纪律变成退出码,与 `lpt-fe` 的 `lint:ui` 对齐。否决:Android 侧代码本来就干净(`Color(0x…)` 只在主题文件、`fontSize` 只有已登记的一处例外),现有 `./gradlew :app:lintDebug` 已覆盖大部分;先上脚本等于给零违规的地方装门,收益抵不上多一处要维护的检查。
|
||||
- **只更新 `ui-review-checklist.md`,不动规则文件** — 最强论据是清单本来就是执行面,改一处足够。否决:清单只说「查什么」,说不出「应该是什么样」。按钮五种样子与主操作的位置必须写进取值文件,否则每次自检都要重新讨论标准。
|
||||
- **给顶栏那四个等权按钮现在就补一条新规矩** — 最强论据是以此为例推动整改。否决:该偏差已在 `design-system.md` 与上一篇笔记的偏差表里登记(#4),规则再写一遍就成第二个版本;本次只补「位置该在哪」,不重复「现状哪里不对」。
|
||||
|
||||
## Consequences
|
||||
|
||||
- **收益**:主操作的位置、名字、五种样子在 Android 侧各有一处定义,新页面照着填即可;字体放大到 200% 有明确的先后顺序,「缩小字号换空间」从默认做法变成禁止项;改按钮相关的东西有一个 10 条的轻量档,不必每次走完整清单。
|
||||
- **代价与已知上限**:规则仍与代码有两处不一致——顶栏四个等权 `TextButton`(偏差 #4)与 `labelSmall` 11sp 承担正文(偏差 #5),继续按 `design-system.md` 的偏差表逐条消化,本次没有新增待改代码项。按钮状态表对浮窗不适用,浮窗的按钮状态仍由 `OverlayView` 自己的常量决定。
|
||||
- **风险**:主操作位置表绑定的是当前四个屏(列表 / 会话 / 阅读 / 浮窗)。新增第五个屏时要先回来加一行,否则会有人把「表里没有」理解成「随便放」。
|
||||
|
||||
## Verification
|
||||
|
||||
- 四份规则文件在 `lpt-android/.agents/roles/`,`AGENTS.md` 与 meta `AGENTS.md` 的索引描述已同步;没有新增文件,所以索引路径未变。
|
||||
- `node .agents/scripts/verify-notes.ts lpt-android` 通过。
|
||||
- 规则里的取值可与代码对核:弹窗确认按钮在右(`SessionScreen.kt:503,569` 的 `dismissButton` 都在 `confirmButton` 之后声明)、点击区 48dp、字号下限 12sp、小屏 360dp 与字号 200% 四条与 `ui-review-checklist.md` 原有条目一致。
|
||||
@@ -0,0 +1,77 @@
|
||||
# Agent Note: Android 端界面规则的落位与色彩口径
|
||||
|
||||
Status: implemented
|
||||
|
||||
## Problem
|
||||
|
||||
`lpt-fe` 有一套界面规则(`design-principles` / `design-system` / `code-standards` / `ui-review-checklist` / `testing` + `ui-review` 技能),`lpt-android` 一份都没有。结果是 Android 侧的界面取值全靠当次改动的直觉:
|
||||
|
||||
- 主色是 M3 默认蓝 `#1F6FEB`,与 lpt-fe 的品牌绿 `#237556` 不是同一个产品;
|
||||
- 列表条目与页面区块都用 M3 默认 `Card`,两条层级无法区分;
|
||||
- 顶栏四个动作(权限 / 设置 / 刷新 / 退出登录)都是一排等权 `TextButton`;
|
||||
- 辅助文字用 `labelSmall`(11sp)写会话号与时间戳;
|
||||
- `LptRepository` 把后端 `message` 直接交给 UI,用户可能看到接口原文;
|
||||
- 间距档位散在 `4/6/8/10/12/14/16/20/24`,还出现 `Spacer(0.dp)` 这种噪声。
|
||||
|
||||
改界面的 agent 没有共同基准,评审也没有可执行的清单与取证方式。
|
||||
|
||||
## Decision
|
||||
|
||||
Android 端持有一套自己的界面规则,与 `lpt-fe` 同源但换锚点:
|
||||
|
||||
- 规则落在 `lpt-android/.agents/roles/`,共 5 份:`design-system.md`(取值)、`design-principles.md`(结构取舍与禁用清单)、`code-standards.md`(Compose 写法与请求层)、`ui-review-checklist.md`(交付自检)、`testing.md`(测试分层与真机矩阵)。
|
||||
- 技能落在 `lpt-android/.agents/skills/ui-review/`,取图走真机 `adb exec-out screencap`,因为浮窗叠在第三方 App 之上这一状态在 App 内无法复现。
|
||||
- 品牌主色**目标值**是 `#237556`,与 `lpt-fe` 同源。`ui/theme/Theme.kt` 现状仍是 `#1F6FEB`,作为偏差登记在 `design-system.md`,本轮不动代码。
|
||||
- 浮窗保留独立深色板(`service/OverlayView.kt` 的 `companion object` 常量),不跟随系统深浅色、不复用 App 页面 token。
|
||||
- 两个仓库的规则各自持有,**不抽 meta 母规则**;只在「同源意图」处互相引用路径。
|
||||
|
||||
`design-system.md` 是取值的唯一来源,`Theme.kt` 落地时引用它而不复制一份自己的表。
|
||||
|
||||
## 为什么是这 5 份,不是 FE 的 6 份
|
||||
|
||||
FE 多出的 `style-conventions.md` 是 web 的杂物抽屉(链接虚线、`Study.vue` 每页 20 条、`MindMapViewer` 的四种模式)。Android 没有对应物,杂项约定已经在 `lpt-android/AGENTS.md` 的「必须遵守的约定」里,再抄一份只会产生第二个版本。
|
||||
|
||||
## 为什么统一到绿,而不是保留蓝
|
||||
|
||||
- 同一个产品在两个端不该有两个品牌色。用户从浏览器换到手机,看到的应该是同一套调性。
|
||||
- `#1F6FEB` 是 M3 模板最典型的主色取值,保留它等于承认「组件库默认只改主色」,正是 `design-principles.md` 禁用清单里的一条。
|
||||
- 绿色族已有现成对比度基线:`#237556` 白底 5.60:1 可做正文与实底白字;`#2F8F68` 只有 4.00:1,不能做正文。浮窗强调色 `MINT #80E6C1` 与品牌绿同色相(实测均约 157°),统一品牌色后浮窗不需要换色。
|
||||
|
||||
## 为什么浮窗不跟随系统深浅色
|
||||
|
||||
浮窗常驻在任意第三方 App 之上,背景不可控。跟随系统意味着同一个常驻元素会在白天变浅、夜里变深,而它周围的背景并不跟着变;反过来,固定深色板自带不透明底与 8:1 以上的文字对比度(`TEXT` 14.55:1、`SECONDARY` 8.12:1、`MINT` 9.30:1),在任何下层 App 上都成立。代价是浮窗无法与 App 页面观感完全一致,这是刻意接受的。
|
||||
|
||||
## 现状偏差(整改时逐条消化)
|
||||
|
||||
| # | 偏差 | 影响 | 验收 |
|
||||
|---|---|---|---|
|
||||
| 1 | `Theme.kt` 主色 `#1F6FEB` | 与品牌色冲突 | `colorScheme.primary` 指向 `#237556`,页面无蓝色强调 |
|
||||
| 2 | 深色模式只覆盖 4 个槽位 | 深色下对比度不受控 | 按 `design-system.md` 登记的深色值补全,正文 ≥4.5:1 |
|
||||
| 3 | 条目与区块同为默认 `Card` | 层级不可分 | 条目与区块用两套容器语法 |
|
||||
| 4 | 顶栏四个等权 `TextButton` | 主操作不突出 | 低频动作收进入口,主操作 ≤1 |
|
||||
| 5 | `labelSmall`(11sp)承担正文信息 | 小字不可读 | 辅助信息改用 `bodySmall`(12sp) |
|
||||
| 6 | `LptRepository` 直出后端 message | 用户看到技术信息 | 仓库层收敛为「原因 + 怎么修」 |
|
||||
| 7 | 空态与错误态同一分支 | 失败被当成空数据 | 两态分开,错误态给重试 |
|
||||
| 8 | 间距档位未收敛 | 分组感弱 | 只用 `4/8/12/16/24` 与 `Spacer` 有意义的取值 |
|
||||
|
||||
## Verification
|
||||
|
||||
- `./gradlew :app:assembleDebug`、`:app:testDebugUnitTest`、`:app:lintDebug` 全部成功;单测 22 条通过(`SessionControllerTest` 15、`CountdownAlertTest` 7);lint 基线为 0 error / 30 warnings(依赖版本、`UseKtx`、`BatteryLife` 等既有项)。
|
||||
- `node .agents/scripts/verify-notes.ts lpt-android` 通过。
|
||||
- 真机取图链路已验证:`adb exec-out screencap -p` → `ffmpeg -q:v 4`,单张 1080×2400 截图压到约 110KB。
|
||||
- meta `AGENTS.md` 的子仓库索引与 `lpt-android/AGENTS.md` 的「规则与技能位置」指向的路径全部真实存在。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **照搬 FE 的 6 份规则。** 最强理由是维护成本最低,一处改动两端受益。否决原因:FE 规则的锚点全是 web(`.surface-card`、`el-*`、768/900 断点、`hover`、`useElapsedSeconds`),搬到 Compose 上无法验证,最终剩下的只有「保持简洁」这类拦不住任何人的话。
|
||||
- **抽到 meta 做跨端母规则,两仓引用。** 最强理由是同源意图只需要写一次。否决原因:抽掉实现锚点后母规则必然退化成口号;真正跨端的纪律(提交规范、图示优先、业务名词收敛)已经在 meta `.agents/roles/`,界面规则反而是端内最强的锚点。
|
||||
- **保留蓝色作为 Android 品牌色。** 最强理由是现有页面已按蓝色验收过,改动面为零。否决原因:两个端两个品牌色违背一个产品一套色的前提,且蓝色是 M3 模板默认值,等于没有做过设计决策。
|
||||
- **规则里只写「待定」,不写目标值。** 最强理由是避免文档与代码不一致。否决原因:没有目标值就没有验收标准,也拦不住新代码继续写蓝色。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 收益:改界面的 agent 有一处可查的取值与判据;新页面不必重新发明间距、字号与容器层级;评审有可执行的清单与真机取证流程。
|
||||
- 收益:偏差被写成表,后续整改有明确验收,不必每次重新讨论「到底该不该改」。
|
||||
- 代价:目标值与代码现状会有一段时间不一致。这期间必须靠偏差表逐条消化;任何一次「顺手改成蓝的」都会让规则失信,因此新代码一律按目标值写。
|
||||
- 代价:真机评审依赖一台连着的设备(当前 `f5269dcc`,Android 12)。没有设备时只能在交付说明里标注「未验证」,比 web 端起本地服务麻烦。
|
||||
- 风险:取值在两处存在(`design-system.md` 与 `Theme.kt`),可能漂移。缓解方式是把 `design-system.md` 定为唯一来源,`Theme.kt` 只做落地,不允许在页面里另写一套。
|
||||
@@ -0,0 +1,82 @@
|
||||
# Android 代码标准
|
||||
|
||||
- **功能**:约束 Compose 代码结构、视觉实现取值、无障碍、文案、时间数字格式与请求层的写法,保证界面代码可预测、取值不漂移、错误文案只有一处来源。
|
||||
- **何时用**:新增或修改 Composable、页面、主题、请求封装时;评审 Android 代码改动时。界面取值的「是什么」见 `.agents/roles/design-system.md`,这里只讲「怎么写」。
|
||||
- **适用范围**:App 页面(Compose)为主;浮窗(经典 View,`service/OverlayView.kt`)适用其中的视觉实现、无障碍与文案条目,Compose 专属条目对它不适用。
|
||||
|
||||
## 规则
|
||||
|
||||
### Compose 结构
|
||||
|
||||
- **状态提升,会话状态只读不存。** 页面从 `SessionController.State` 读当前会话,不在 Composable 里维护会话副本;动作通过传入的 lambda 回传,`SessionController` 是唯一写入点(`AGENTS.md`)。
|
||||
- **`rememberSaveable` 只用于用户输入草稿**,且必须带上状态归属键,否则同一个 Composable 换到另一个会话会串味:`rememberSaveable(state.sessionNum) { mutableStateOf("") }`(`SessionScreen.kt` 现状写法,照此办理)。
|
||||
- **`LazyColumn` 的 `items` 必须带 `key`**:用业务号(`it.taskNum` / `it.id`),不用下标;现状两处列表都已带,新增的照做。
|
||||
- **副作用只入 `LaunchedEffect` / `DisposableEffect`。** 不在 Composable 体内直接发请求、直接改外部状态或起定时器;键变化才重跑。计时不走 tick 累加(`AGENTS.md`)。
|
||||
- **Composable 内不发请求**,只调用传入的回调;请求与状态改动的中间层是 `SessionController` / `AppContainer`。
|
||||
- **空态与错误态分开渲染**:`loading && empty`、`error`、`empty` 三条分支各自成形,不用一个分支兼纳失败与空(现状 `TaskListScreen` 的 `tasks.isEmpty() && !loading` 兼纳两者,待整改)。
|
||||
- **参数顺序**:`modifier` 放第一个可选参数;回调参数命名 `onXxx`;一屏一个 `Screen` 根 Composable,内部拆私有的 `XxxSection`。
|
||||
- **不做无消费者的参数**:Composable 的入参只保留真正被用的,废弃的 `onXxx` 回调一并删掉。
|
||||
|
||||
### 视觉实现
|
||||
|
||||
- 不写颜色字面量(禁 `Color(0x…)`),一律 `MaterialTheme.colorScheme.*`;浮窗例外,取值集中在 `OverlayView` 的 companion object 常量。
|
||||
- 不写尺寸常量:间距只用 `.agents/roles/design-system.md` 登记的五档,不出现档外值,也不写 `Spacer(Modifier.height(0.dp))`。
|
||||
- 形状走 `MaterialTheme.shapes`;`FragmentInputActivity` 的 `RoundedCornerShape(18.dp)` 是唯一已登记例外,不再新增。
|
||||
- 文字只用 M3 六个角色(`design-system.md`);不写 `fontSize = …sp`,唯一例外是会话页计时数字。
|
||||
- 进度指示必须 `Modifier.size(...)`,不用 `Modifier.height(...)`(`AGENTS.md`:非方形画布会让旋转中心偏移、圆环被压扁)。
|
||||
- 需要背景对比或分组时用 `Surface` / `Card` 的语义容器,不手画边框与阴影值。
|
||||
- 不许为了「看上去干净」去掉 M3 的按下水波纹与焦点高亮(`indication = null`):这等于把按下反馈和键盘焦点一起删掉;要换就整体换成一套保留反馈的写法。
|
||||
|
||||
取值从哪来,一张表说清:
|
||||
|
||||
| 要写的东西 | 取处 |
|
||||
|---|---|
|
||||
| 颜色 | `MaterialTheme.colorScheme.*`(浮窗:`OverlayView` 常量) |
|
||||
| 字号/字重 | `MaterialTheme.typography.*` |
|
||||
| 圆角 | `MaterialTheme.shapes.*`(浮窗:`GradientDrawable` 的 `cornerRadius`) |
|
||||
| 边距/间隙/图标尺寸 | `.agents/roles/design-system.md` 登记档位,写 `dp` 常量 |
|
||||
| 时长与倒计时文本 | `util/Format.kt` |
|
||||
|
||||
### 无障碍
|
||||
|
||||
- 非文字控件必须有 `contentDescription`,写清「是什么 + 点了会怎样」;浮窗已经做到(「学习计时,点按收起,拖动调整位置」「记一条知识碎片」),Compose 侧新增图标按钮照此补。
|
||||
- 可点区域 ≥48dp;视觉小的控件靠 `Modifier.minimumInteractiveComponentSize()` 或外扩 padding 撑起命中区。
|
||||
- 已知例外:浮窗收起时露出的 24dp 把手小于 48dp,是「不挡下层 App」的既有取舍,标注为已知例外,不要再缩小,也不要为它单独加规则。
|
||||
- 系统字体放大到 200% 不截断、不重叠:不用固定高度容器装文字,不用 `maxLines` 一刀切,长文案允许换行。
|
||||
- 状态不只靠颜色:除颜色外配文字或形态差别(`design-system.md`)。
|
||||
|
||||
### 文案
|
||||
|
||||
- **不显示接口原始 message。** 现状 `LptRepository.kt:7` 的注释写着「把后端的 message 直接带给 UI」,与实际期望相反,登记为待整改:用户看到的必须是「原因 + 怎么修」,技术细节留日志。
|
||||
- 加载/处理中文案以 `…`(省略号字符)结尾,不用 `...`;现状「保存中…」「记录中…」「刷新中…」「同步中…」已合规,保持。
|
||||
- 按钮说清按下去会发生什么(「结束学习」而不是「提交」),同一动作全流程同名。完整的命名规矩(动词 + 宾语、四处同名、六个禁用词、破坏性按钮写后果)见 `.agents/roles/design-principles.md` 的「文案即设计」,这里不重复。
|
||||
- 名词用术语表的正式名:`知识碎片`(行内可写「碎片」),不写旧名「残片」,也不自造同义词。
|
||||
- 错误文案不道歉、不含糊;空态文案给下一步动作。
|
||||
- 文案目前硬编码在 Kotlin 里(`res/values/strings.xml` 只有 `app_name`),新增文案沿用现状,不做迁移;要迁移时单独定路线。
|
||||
|
||||
错误文案的尺度(示例,不是固定文案):
|
||||
|
||||
| 场合 | 不这样写 | 这样写 |
|
||||
|---|---|---|
|
||||
| 保存预期失败 | 直接把后端 message 贴上去 | 「预期保存失败:网络断开,检查网络后重试」 |
|
||||
| 记碎片连点 | 静默丢第二条 | 按钮文案变「记录中…」且禁用 |
|
||||
| 会话冲突 | 「操作失败」 | 「有一个未结束的会话,先去继续或结束它」 |
|
||||
|
||||
### 时间与数字
|
||||
|
||||
- 时长、倒计时、日期时间只走 `util/Format.kt` 的 `formatDuration` / `formatCountdown` / `formatDateTime`;禁止在页面里用 `SimpleDateFormat` 或字符串拼接再造一份。
|
||||
- 倒计时用 `formatCountdown`(向上取整,到零才显示 `00:00`),显示值来自 `State.effectiveSeconds(nowMs)`,页面不自己起定时器。
|
||||
- 需要上下比较的数字用等宽字形。
|
||||
|
||||
### 请求层
|
||||
|
||||
- 唯一网络出口是 `LptRepository`(`code != 200 → ApiException`);页面与浮窗都不直接调 Retrofit,`LptApi` 只定义接口。
|
||||
- 新增接口的错误文案在仓库层收敛成一句用户可读的话,不在各页面各写一套映射。
|
||||
- 写操作的「在途」标记加在中间层(`SessionController` / `AppContainer`),并把按钮 `enabled` 绑到该标记;成功才清输入,失败保留输入(`AGENTS.md`)。
|
||||
- 对接后端前先看部署环境的 OpenAPI(`AGENTS.md`),不按源码假设字段。
|
||||
|
||||
### 提交前检查
|
||||
|
||||
- 界面改动按 `.agents/roles/ui-review-checklist.md` 逐项自检;新页面或整页改版走 `.agents/skills/ui-review/`。
|
||||
- 测试与命令见 `.agents/roles/testing.md`,这里不重复。
|
||||
- 提交信息按 `AGENTS.md` 的提交规范:简短中文,`类型: 简述`。
|
||||
@@ -0,0 +1,119 @@
|
||||
# Android 设计原则
|
||||
|
||||
- **功能**:规定写代码前的设计计划、App 页面的信息架构与视觉层级取舍、主操作放在哪,给出浮窗加控件的判据,并列出「模型默认做法」禁用清单,保证每屏只服务一个主任务、主操作只有一个且位置固定、浮窗不变成常驻干扰。
|
||||
- **何时用**:新增页面或重构页面结构时;决定某块内容放主区还是收起时;决定主操作叫什么名字、放在哪时;想往浮窗加按钮或面板时;评审界面层级时。出现新页面或整页改版,须同时走 `.agents/skills/ui-review/`(见「独立评审」)。
|
||||
- **适用范围**:App 页面与浮窗两者;「浮窗专有判据」一节只对悬浮窗生效。
|
||||
|
||||
## 规则
|
||||
|
||||
### 动手前:一页设计计划
|
||||
|
||||
- **新页面或整页改版**:写代码之前先交不超过 12 行的计划,写清七件事——这一屏给谁用、他来这一屏要干成什么、主操作叫什么名字放在哪、首屏留哪些块删哪些块、颜色字号间距各取哪一档、一句话记忆点(用户靠什么记住这一屏)、验收设备与字号(见 `testing.md` 的真机矩阵)。计划没通过不开工。
|
||||
- **中等改动**(新增一个按钮、挪动主操作位置、加一块内容):3–5 行写清「加什么、放哪、为什么放这、删掉什么腾位置」,跟第一条回复一起给。
|
||||
- **计划在前,评审在后**:计划管写代码之前的方向,`.agents/skills/ui-review/` 管写完之后看真机画面,两者不能互相替代。跳过计划直接动手,最常见的错是「先在顶栏排一摞文字按钮,再回头找理由」。
|
||||
|
||||
### 页面信息架构
|
||||
|
||||
- **一屏一个主角。** 每屏先回答「用户来这一屏是看什么、做什么」,让那件事占最大面积与最强对比;其余信息靠更小的字号、更轻的字重、更低的对比退到后面。同一屏不让两种强调同时抢注意力。
|
||||
|
||||
当前三个高频屏的落点:
|
||||
|
||||
| 屏 | 主角 | 主操作(≤1) | 收起或降级 |
|
||||
|---|---|---|---|
|
||||
| 会话页 `SessionScreen` | 计时 | 暂停/继续 | 结束(次级)、误操作结束(低频,收在弹窗) |
|
||||
| 任务页 `TaskListScreen` | 任务列表 | 开始学习(点条目先弹确认,确认框里才是真按钮) | 报告入口(行内次要)、刷新(下拉或空态里的动作)、权限/设置/退出登录(进设置页) |
|
||||
| 报告页 `ReportsScreen` | 本次报告结论 | 无(阅读页,返回交给系统返回键与顶栏返回) | 三段内容的后续段落(渐进披露) |
|
||||
|
||||
- **内容先行,页面不自述。** 首屏就是内容本身,不放「这个页面是干什么的」说明段落;页面标题已说清的事不再补副标题;操作提示放在控件附近(输入框 label、按钮文案),不放页面顶部当导语。
|
||||
- **主操作每屏 ≤1。** 会话页的主操作是「暂停/继续」,「结束」降为次级(描边或文字按钮,不与主操作同权重、不同颜色强度并排)。
|
||||
- **整条可点的列表项,落地动作要确认。** 任务条目整条可点是为了好按,但一步就进会话、开始计时,误触代价不小:点条目只弹确认(正文写清「开始后进入会话页、悬浮窗开始计时」),确认框里才有真按钮。只读的入口(如「报告」)不需要这道确认。
|
||||
- **主操作的位置按场景查表**,不要每次重新发明:
|
||||
|
||||
| 场景 | 主操作 | 次级操作 | 危险操作 |
|
||||
|---|---|---|---|
|
||||
| 列表页(`TaskListScreen`) | 列表块上方或空态里的「开始学习」,不用悬浮按钮(FAB) | 行内 `TextButton`(如「报告」) | 不在列表出现,收进会话页 |
|
||||
| 会话页(`SessionScreen`) | 计时区下方的「暂停/继续」 | 「结束学习」用 `OutlinedButton` | 「误操作结束」收在底部的文字入口 + 二次确认 |
|
||||
| 阅读页(`ReportsScreen`) | 无(返回交给系统返回键与顶栏返回) | — | — |
|
||||
| 弹窗 | `confirmButton` 在右 | `dismissButton`「取消」在左 | 默认不放 |
|
||||
| 空态 | 空态里唯一的主操作 | — | — |
|
||||
| 浮窗 | 不设主操作:两个动作(记一条知识碎片、暂停/继续)平级、同一行、同权重,不加第三个 | 收起(胶囊把手) | 无(浮窗不做危险操作) |
|
||||
|
||||
- **主操作不因字号放大或文案变长让位。** 空间不够时按这个顺序退:①允许换行 ②缩短文案但不改名 ③次要操作收进设置页或菜单 ④次要操作改图标 + `Tooltip` ⑤主操作占满一行。**禁止**:把主操作字号改小、把点击区压到 48dp 以下、把它藏进菜单或二级页。「空间不够就先缩小字号」是最常见的默认做法,也是这条存在的理由。
|
||||
- **低频操作收起。** 权限、设置、退出登录这类一次配好的动作收进设置页或菜单,不在顶栏平铺成一排等权按钮。现状任务页顶栏「权限 / 设置 / 刷新 / 退出登录」四个等权文字按钮是典型反例。
|
||||
- **渐进披露。** 复杂或低频的信息默认收起,用户需要时展开:每条报告的第一句就是「预期达成判断」,展开后依次是「本次预期 → 会话摘要 → 自由总结」,先给结论再给记录;没有后续内容时不出「展开全文」这种空动作。碎片列表默认只露最近几条,剩下的靠滚动或「查看全部」。
|
||||
- **待办与汇总各成一块。** 需要用户处理的内容(未结束的会话、待填预期)独立成块并给出条数;纯指标(总时长、碎片数)另成一块,不与待办混排。
|
||||
|
||||
#### 已登记的例外
|
||||
|
||||
两处有意不讲一般规则,不当作遗漏:
|
||||
|
||||
- **会话页顶栏用任务名当标题(`titleMedium`)**,不用 22sp 的 `titleLarge` 页标题。任务名逐屏变化,它本身就是这一屏的标题;`PageHeader(titleStyle = MaterialTheme.typography.titleMedium, subtitle = 会话号)` 实现,页面标题角色仍是一屏一个,只是这一屏由任务名担任。
|
||||
- **任务页搜索框在任务 ≥6 个时才出现**。少于 6 个一屏内就能扫完,搜索是纯负担;不到 6 个直接给列表,不渲染禁用态的搜索框。
|
||||
|
||||
### 浮窗专有判据
|
||||
|
||||
浮窗常驻在别人 App 之上,每多一个控件都是常态干扰。加控件前先回答三问,任一答「否」就不加:
|
||||
|
||||
| 问题 | 判据 |
|
||||
|---|---|
|
||||
| 是否手机之外无法替代的场景必需? | 必须离开 App 才能做,且 App 里做不了 |
|
||||
| 是否值得常驻在别人 App 之上? | 用户每次看到它都会付出注意力成本 |
|
||||
| 能否改到 App 页面里完成? | 能就不做进浮窗 |
|
||||
|
||||
- 浮窗只做三件事:展示倒计时、记一条碎片、暂停/继续——正文见 `AGENTS.md`,这里不重复。
|
||||
- 浮窗不做文本输入(会拉起 `FragmentInputActivity`),也不放二级面板、历史、报告入口。
|
||||
|
||||
### 视觉层级
|
||||
|
||||
- **间距表达分组。** 同一种关系用同一档间距,不用同一档表达两种关系:
|
||||
|
||||
| 关系 | 取哪一档 |
|
||||
|---|---|
|
||||
| 同一条目内的相邻行 | 紧凑 |
|
||||
| 卡片内相邻元素 | 组内 |
|
||||
| 区块内子块 | 小节 |
|
||||
| 区块之间、列表条目之间 | 组间 |
|
||||
| 页面主要区块之间 | 区块间 |
|
||||
|
||||
各档的具体取值只在 `.agents/roles/design-system.md` 登记,这里只讲关系。先用对齐和留白立结构,再考虑容器与分隔线。
|
||||
- **先对齐留白,再容器。** 需要分组时才加容器;页面、区块、条目、条目说明不要一层层套。现状任务页条目与区块都用默认 `Card`,靠容器而不是留白分区,是待整改的写法。
|
||||
- **一屏一个滚动轴。** 长内容用滚动容器本身承载,不让卡片、内嵌列表各自带滚动。
|
||||
- **禁止嵌套滚动。** 竖向滚动容器里不再嵌竖向滚动容器;横向例外只用于确有并列关系的一排内容,且不抢竖向手势。
|
||||
|
||||
### 模型默认做法禁用清单
|
||||
|
||||
以下是生成界面的默认倾向,不是经过判断的选择;除非能说出**来自本产品的理由**,一律不用:
|
||||
|
||||
- 套 `Card` 当边框:为了分组给每块内容都加一层 `Card`。
|
||||
- 每条配一个强调色:列表里逐条换色、逐条加重描边或阴影。
|
||||
- emoji 当图标,或混用 emoji 与图形图标。
|
||||
- 全站统一的淡入/上移动画,或给每个元素都加入场动效。
|
||||
- 空泛文案:「了解更多」「立即开始」「丝滑」「无缝」。
|
||||
- M3 默认样子只改主色:其余槽位、形状、字号全用默认,换了主色也认不出是哪个产品。
|
||||
- 大号数字 + 渐变强调色当指标呈现的默认答案。
|
||||
- `TextButton` 铺满顶栏:把并列的低频动作做成一行等权文字按钮。
|
||||
- `›` 与整卡可点含义重叠:同一行既整卡可点又带箭头提示进入,两种点击含义叠在一起。
|
||||
|
||||
### 文案即设计
|
||||
|
||||
- **状态靠形态表达。** 进行中 / 已暂停 / 到点用计时数值、按钮文案和形态差别体现,不加「(暂停中)」「· 进行中」这类小眉标复述当前状态。
|
||||
- **错误 = 原因 + 怎么修。** 「保存失败:网络断开,检查网络后重试」而不是「操作失败」。不道歉、不含糊。
|
||||
- **空态给下一步动作。** 空态只写一句事实 + 一个可执行入口(「还没有学习任务」+「去新建」),不给情绪、不给插画。
|
||||
- **说明文字不是规则。** 「请先填写学习预期」这类导语拦不住任何人;要拦就做成控件(不可关闭的弹窗),不要靠一句说明。
|
||||
- **按钮名字用「动词 + 宾语」**:2–6 个字,说清按下去会发生什么(「结束学习」「记一条知识碎片」)。不带「点击」「请」「立即」「一键」,不带标点与括号(加载态的 `…` 除外)。
|
||||
- **同一动作四处同名**:按钮写什么,加载中就用哪个动词(「结束中…」),成功 snackbar 写「已 + 同一动词」(「已结束」),撤销(若有)写「撤销 + 同一动词」。四处不换词。
|
||||
- **破坏性按钮写后果,不写「确定」**:写「结束这次会话」而不是「确定」;确认框正文说明这一步会失去什么(「未结束的会话会按误操作处理」)。
|
||||
- **要打字的确认框,确认语必须可复制。** 「误操作结束」要求手打一整句才能提交,手打是这条流程最容易出错的一步:确认语以浅底块展示,右侧一个「复制」,按下变「已复制」,用户长按输入框粘贴即可。复制只写剪贴板,不代填、不代提交。
|
||||
- **五个词不进按钮**:确定、提交、开始、了解更多、高级。(「继续」不在列:会话页的主操作就叫「暂停/继续」,恢复某件事本身就是它的含义。)
|
||||
- **名词用术语表的正式名**:`lpt-docs/docs/concepts/README.md` 定性为「知识碎片」的就写「知识碎片」(行内短标签可写「碎片」),不写旧名「残片」,也不自造同义词。
|
||||
|
||||
### 独立评审
|
||||
|
||||
- **第一档(独立评审)**:新页面,或整页改版(整页重构、视觉语言变更、新增信息区块)——交付前必须走 `.agents/skills/ui-review/`:取图 → 派无上下文的独立评审者 → 按清单修 → 下一轮逐条核对,评审结论写进交付说明。
|
||||
- **第二档(快检 10 条)**:改主操作的位置或名字、加图标按钮、改底部或顶栏的按钮区,这三类不触发独立评审,但必须过 `.agents/roles/ui-review-checklist.md` 开头的快检 10 条,并在交付说明里写一行结论。
|
||||
- **第三档(自检)**:小改动、局部低风险调整不走技能,按 `.agents/roles/ui-review-checklist.md` 完整清单自检即可;没做独立评审的,明确写出来。
|
||||
|
||||
### 设计系统锚点
|
||||
|
||||
- 调性、颜色、间距、圆角、文字角色、组件语法的**当前取值**只在 `.agents/roles/design-system.md` 登记;新增取值先在那里登记,再落 `ui/theme/Theme.kt`(浮窗落在 `service/OverlayView.kt` 的常量)。
|
||||
- 组件里禁止写颜色与尺寸字面量,见 `.agents/roles/code-standards.md`。
|
||||
@@ -0,0 +1,185 @@
|
||||
# Android 设计系统
|
||||
|
||||
- **功能**:记录 LPT Android 客户端的调性、颜色、间距、圆角、文字角色与组件语法,作为新增界面与界面评审的共同取值基准。
|
||||
- **何时用**:写新页面或新控件之前;需要决定字号、间距、圆角、颜色取哪一档的时候;评审界面是否偏离现有规范时;与 `.agents/roles/design-principles.md` 配套使用。
|
||||
- **适用范围**:App 页面与浮窗两者通用;标注「浮窗」的条目只对悬浮窗生效(浮窗是经典 View,不读 `MaterialTheme`)。
|
||||
|
||||
## 规则
|
||||
|
||||
### 调性五刻度
|
||||
|
||||
依据:手机上使用的单次几分钟的学习记录工具,中文界面,多数时间只有倒计时和一两条碎片。
|
||||
|
||||
| 刻度 | 取值 | 依据 |
|
||||
|---|---|---|
|
||||
| 能量 | 偏安静 | 一次几分钟,打开就要能立刻离开,不喧闹 |
|
||||
| 完成度 | 偏精致(公差小) | 天天打开,粗糙边缘会持续被看到 |
|
||||
| 密度 | 中等 | 一屏要看清「在学什么 + 还剩多久 + 记了什么」 |
|
||||
| 分量 | 中等偏轻 | 字重两级、色块面积克制,浮窗更是压倒性地轻 |
|
||||
| 严肃度 | 中性偏稳重 | 学习记录,不玩梗、不用插画与 emoji 当图标 |
|
||||
|
||||
一句话北极星:**「手机上、单次几分钟内的记录工具」——一眼看清现在在做什么、还剩多久,记一条就退出。**
|
||||
|
||||
### 颜色
|
||||
|
||||
#### App 浅色
|
||||
|
||||
| 语义 | 取值 | 对比度 | 槽位 / 用在哪 |
|
||||
|---|---|---|---|
|
||||
| 页面底 + 主文字 | `#F7FBF8` / `#16241C` | 15.43:1 | `background` / `onBackground`、`onSurface` |
|
||||
| 面(区块、条目) | `#FFFFFF` | 16.11:1(配 `#16241C`) | `surface`、`surfaceContainerLow` / `surfaceContainerLowest` |
|
||||
| 面内浅一档 | `#F4F8F5` | — | `surfaceContainerHigh`:面内再分组时用,不单独承载正文 |
|
||||
| 输入框底、内嵌块 | `#F1F6F3` | 6.11:1(配 `#4B6156`) | `surfaceVariant`、`surfaceContainer` / `surfaceContainerHighest` |
|
||||
| 主色(实底 + 白字) | `#237556` / `#FFFFFF` | 5.60:1 | `primary` / `onPrimary`、`secondary` / `onSecondary`:主操作实底按钮 |
|
||||
| 主色文字 | `#237556` | 5.36:1(页底)、5.19:1(浅底) | 需要突出的文字、`onPrimaryContainer` / `onSecondaryContainer` |
|
||||
| 浅色强调底 + 深字 | `#EEF9F3` / `#237556` | 5.19:1 | `primaryContainer` / `secondaryContainer`:状态块、选中态、进行中会话块 |
|
||||
| 次要文字 | `#4B6156` | 6.40:1(页底)、6.68:1(面) | `onSurfaceVariant`:meta、时间戳、说明 |
|
||||
| 描边 / 图形强调 | `#6B7F75` | 4.09:1(页底)、4.27:1(面) | `outline`:图标、输入框等强描边,**不写正文** |
|
||||
| 分组描边 | `#C6D6CD` | 1.45:1(页底)、1.51:1(面) | `outlineVariant`:1dp 条目描边,只做分隔 |
|
||||
| 错误文字 | `#B62324` / `#FFFFFF` | 6.45:1 | `error` / `onError`:错误提示 |
|
||||
| 错误底 + 字 | `#FDECEA` / `#B62324` | 5.64:1 | `errorContainer` / `onErrorContainer`:行内错误条 |
|
||||
| 提醒块底 + 字 | `#FFF8E1` / `#856404` | 5.17:1 | `tertiaryContainer` / `onTertiaryContainer`:到时 / 暂停提醒条 |
|
||||
|
||||
#### App 深色
|
||||
|
||||
| 语义 | 取值 | 对比度 | 槽位 / 用在哪 |
|
||||
|---|---|---|---|
|
||||
| 页面底 + 主文字 | `#111A16` / `#E4EFE9` | 15.06:1 | `background` / `onBackground`、`onSurface` |
|
||||
| 面(区块、条目) | `#1B2A23` / `#E4EFE9` | 12.71:1 | `surface`、`surfaceContainer` / `surfaceContainerLow` |
|
||||
| 最深一块(贴页底) | `#111A16` | — | `surfaceContainerLowest` |
|
||||
| 输入框底、内嵌块 | `#22332B` | 7.50:1(配 `#B3C7BD`) | `surfaceVariant`、`surfaceContainerHigh` / `surfaceContainerHighest` |
|
||||
| 主色 / 深色底 | `#7FD8B4` / `#111A16` | 10.47:1 | `primary` / `onPrimary`、`secondary` / `onSecondary`、实底上的深色文字 |
|
||||
| 主色浅底 + 亮字 | `#17332A` / `#7FD8B4` | 8.02:1 | `primaryContainer` / `secondaryContainer` 与各自的 `on*` |
|
||||
| 次要文字 | `#B3C7BD` | 9.99:1(页底)、7.50:1(输入框底) | `onSurfaceVariant`:meta、时间戳、说明 |
|
||||
| 描边 / 图形强调 | `#7C9186` | 5.28:1(页底) | `outline`:图标、强描边,**不写正文** |
|
||||
| 分组描边 | `#33453D` | 1.74:1(页底)、1.47:1(面) | `outlineVariant`:1dp 条目描边,只做分隔 |
|
||||
| 错误文字 | `#F85149` / `#111A16` | 5.29:1 | `error` / `onError` |
|
||||
| 错误底 + 字 | `#3A1F1F` / `#FF8A80` | 6.59:1 | `errorContainer` / `onErrorContainer`:行内错误条 |
|
||||
| 提醒块底 + 字 | `#3A3220` / `#FFD08A` | 8.84:1 | `tertiaryContainer` / `onTertiaryContainer`:到时 / 暂停提醒条 |
|
||||
|
||||
深色值按「同色相提高明度」派生,不是把浅色值反相;两套色板同槽位一一对应,不允许哪个槽位留 M3 默认值。
|
||||
|
||||
#### 浮窗独立深色板
|
||||
|
||||
浮窗常驻在别人 App 之上,因此不跟随系统深浅色,必须自带对比度。取值在 `service/OverlayView.kt` 的 companion object 常量里,不走 `MaterialTheme`。
|
||||
|
||||
| 常量 | 值 | 对比度 | 用途 |
|
||||
|---|---|---|---|
|
||||
| `SURFACE` | `#F51A242B`(96% alpha) | — | 面板底 |
|
||||
| `BUTTON` | `#2B3941` | — | 次要按钮底 |
|
||||
| `BORDER` | `#40515A` | — | 1dp 描边 |
|
||||
| `TEXT` | `#F1F7F5` | 14.55:1(对 `#1A242B`) | 主文字 |
|
||||
| `SECONDARY` | `#ADBDBF` | 8.12:1 | 次要文字 |
|
||||
| `MINT` | `#80E6C1` | 9.30:1 | 倒计时与强调(与品牌绿同色相,提亮适配深底) |
|
||||
| `AMBER` | `#FFD08A` | 11.00:1 | 到时 / 暂停提示 |
|
||||
|
||||
#### 色板落地位置
|
||||
|
||||
| 项 | 内容 |
|
||||
|---|---|
|
||||
| 落地处 | `ui/theme/Theme.kt` 的 `LightColors` / `DarkColors`;浅深各 27 个槽位显式给值 |
|
||||
| 主色 | 浅 `#237556`(5.60:1 配白字)、深 `#7FD8B4`(10.47:1 配 `#111A16`),与 `lpt-fe` 品牌绿同源 |
|
||||
| 深色 | 同色相提高明度派生,页底 / 面 / 输入框底 / 描边 / 错误底全部显式给值,不再退回 M3 默认紫灰 |
|
||||
| 组件侧 | 只取 `MaterialTheme.colorScheme.*`;颜色字面量只允许出现在 `Theme.kt` 与 `service/OverlayView.kt` |
|
||||
| 主题形状与字号 | 不覆盖:M3 默认 `small` = 8dp、`medium` = 12dp 正好对上两级容器 |
|
||||
|
||||
#### 颜色规则
|
||||
|
||||
- 组件里禁止写 `Color(0x…)` 字面量,一律 `MaterialTheme.colorScheme.*`;新增语义先来本节登记,再改 `Theme.kt`。
|
||||
- 语义色按「浅底 + 深字」成对使用:标签、状态块用 `#EEF9F3` 底配 `#237556` 字,不用实底压深字。
|
||||
- `outline`(浅 `#6B7F75` 4.09:1 / 深 `#7C9186` 5.28:1)只用于描边、图标、图形,**不得用于正文**;浅底上的文字要用登记过对比度的组合(如 `#EEF9F3` 上的 `#237556`、`#FFF8E1` 上的 `#856404`)。
|
||||
- **1dp 分组描边不参与非文字 3:1 门限**:`outlineVariant` 只做分隔,不表达状态,所以不拿它当「看得见的边」去承载选中 / 错误 / 禁用;状态差别必须另有文字或形态。
|
||||
- **页底与面同色,差别只有 1 档明度**(浅 `#F7FBF8` / `#FFFFFF`、深 `#111A16` / `#1B2A23`):分组靠 1dp 描边与留白,不靠底色对比;不要为了「看得出卡片」把面调深、调亮或加阴影。
|
||||
- 状态不只靠颜色:错误、到时、暂停都要同时有文字或形态差别。
|
||||
- 深色按同色相提高明度派生;不为深色另造一套色相。
|
||||
|
||||
### 间距
|
||||
|
||||
以 4dp 为基数,只用这五档关系,外加一档屏幕边距;六个取值集中在 `ui/theme/Dimens.kt` 的 `Dimens` 对象,组件只取这里,不写档外 dp:
|
||||
|
||||
| 档 | `Dimens` 成员 | 值 | 用在哪 |
|
||||
|---|---|---|---|
|
||||
| 紧凑 | `Compact` | 4dp | 同一条目内相邻行、图标与文字之间 |
|
||||
| 组内 | `Inner` | 8dp | 卡片内相邻元素 |
|
||||
| 小节 | `Section` | 12dp | 区块内子块之间、列表条目内边距、页头上下 |
|
||||
| 组间 | `Group` | 16dp | 区块之间、列表条目之间、区块内边距 |
|
||||
| 区块间 | `Block` | 24dp | 页面主要区块之间、页面首尾留白 |
|
||||
| 屏边 | `Screen` | 16dp | 页面左右边距,页头与页面内容对齐 |
|
||||
|
||||
现状偏差登记(逐屏收敛到 `Dimens`,改到时不再保留档外值):
|
||||
|
||||
- 屏幕级水平边距取 `Dimens.Screen`(16dp,6 个页面一致);`LoginScreen.kt:48` 的 24dp 是登录页主视觉例外,保留为特例。
|
||||
- 卡片内边距现状 14dp(7 处)/ 20dp(计时卡片)/ 12dp(`FragmentInputActivity`)→ 含表单的区块 `Dimens.Group`,纯展示条目 `Dimens.Section`,计时卡片归入 `Dimens.Group`。
|
||||
- 区块间距现状混用 `spacedBy(12)`(3 处)/ `spacedBy(10)`(3 处)/ `spacedBy(8)`(1 处)→ 按上表取 `Dimens` 成员,10dp 不再使用。
|
||||
- `Spacer.height` 档外取值 2(1 处)、6(5 处)、10(8 处)、20(1 处);另有 3 处 `Spacer(Modifier.height(0.dp))` 属噪声写法,删掉。
|
||||
|
||||
### 圆角
|
||||
|
||||
| 档 | 值 | 用在哪 |
|
||||
|---|---|---|
|
||||
| 行内 | 4dp | 标签、行内小控件 |
|
||||
| 条目 | 8dp | 列表条目(`LptListItem` 用 `shapes.small`) |
|
||||
| 区块 | 12dp | 页面区块(`LptSection` 用 `shapes.medium`) |
|
||||
| 独立容器 | 18dp | 浮窗拉起的输入页 `Surface`(`FragmentInputActivity.kt` 现状,登记保留) |
|
||||
|
||||
浮窗(经典 View,单列,不走 `MaterialTheme.shapes`):面板展开 22dp、收起胶囊 24dp、按钮 14dp、内部点 4dp。
|
||||
|
||||
浮窗的两个动作(记碎片、暂停/继续)同权重、同一行:都是 `BUTTON` 底 + 1dp `BORDER` 描边 + `TEXT` 字,不设主操作;`MINT` 只留给倒计时与状态行,`AMBER` 只给到时与暂停。收起只有一个手势(点按把手),不再写「轻触收起」这类与箭头冲突的提示。
|
||||
|
||||
- 嵌套圆角内层 ≤ 外层;同一页里同层级元素用同一档。
|
||||
- 形状统一走 `MaterialTheme.shapes`;18dp 是唯一已登记的例外,不再新增。
|
||||
|
||||
### 文字
|
||||
|
||||
M3 默认 Typography。内容排版只用这六个角色(按钮与标签文字用 `labelMedium`,属组件内部排版,不算第七个内容角色):
|
||||
|
||||
| 角色 | 槽位 | 字号 | 用在哪 |
|
||||
|---|---|---|---|
|
||||
| 页面主视觉 | `headlineMedium` | 28sp | 仅登录页标题 |
|
||||
| 页面标题 | `titleLarge` | 22sp | 每页一个 |
|
||||
| 区块标题 | `titleMedium` | 16sp | 页面内模块标题 |
|
||||
| 卡片内标题 | `titleSmall` | 14sp | 条目名称 |
|
||||
| 正文 | `bodyMedium` | 14sp | 内容、说明 |
|
||||
| 辅助 | `bodySmall` | 12sp | 时间戳、会话号、meta |
|
||||
|
||||
- `labelSmall`(11sp)**停用**:低于 12sp 下限;会话号、时间戳这类要读的小字用 `bodySmall`(12sp),全仓不再出现 `labelSmall`。
|
||||
- `labelMedium`(12sp)留给按钮与标签文字,不写正文。
|
||||
- 计时数字 44sp + `FontFamily.Monospace` + `Bold`(`SessionScreen.kt:151`)是**唯一自造字号**,不新增第二处。
|
||||
- 需要上下比较的数字用等宽字形(现状优先级 `%.2f` 走比例字形,属待整改)。
|
||||
- 不靠加粗表达强调;一屏内字重层级最多两级。
|
||||
|
||||
### 组件语法
|
||||
|
||||
- **按钮**:主操作 `Button`;次级 `OutlinedButton`;`TextButton` 只能用于低权重动作(行内入口、空态里的次要动作),不铺满顶栏。顶部只留一个动作,其余收进设置页。**主操作放在哪,查 `.agents/roles/design-principles.md` 的「主操作的位置」对照表。**
|
||||
- **每个按钮五种样子都要有**,不许只做常态和禁用(触屏没有悬停):
|
||||
|
||||
| 样子 | 主操作 `Button` | 次级 `OutlinedButton` | 低权重 `TextButton` | 备注 |
|
||||
|---|---|---|---|---|
|
||||
| 常态 | `primary` 实底 + `onPrimary` 字 | 描边 + `primary` 字 | 无底 + `primary` 字 | — |
|
||||
| 按下 | M3 水波纹 | 同左 | 同左 | 不许 `indication = null` 把水波纹去掉 |
|
||||
| 键盘 / 手柄聚焦 | 默认焦点高亮 | 同左 | 同左 | 接键盘、电视盒子、投屏时靠它 |
|
||||
| 禁用 | `disabledContainerColor` / `disabledContentColor` | 同左 | 同左 | 尺寸不变、文案不变 |
|
||||
| 加载中 | 保留原文案 + 转圈,宽度不跳 | 同左 | 同左 | `enabled = false` + 在途标记(防连点见 `AGENTS.md`) |
|
||||
|
||||
- **图标按钮**(`IconButton`):必须同时有 `contentDescription`(写「是什么 + 点了会怎样」)和 `Tooltip`(长按与鼠标悬停都能出);点击区 ≥48dp,视觉小就用 `Modifier.minimumInteractiveComponentSize()` 撑起命中区。
|
||||
- **页头**(`PageHeader`,`ui/components/PageHeader.kt`):一屏一个;左右边距 `Dimens.Screen`、上下 `Dimens.Section`;标题与副标题纵向排(间距 `Dimens.Compact`);返回用 `TextButton`(可点区 ≥48dp);右侧 `action` 只放一个动作。页头标题角色默认 `titleLarge`;会话页把任务名当标题(`titleMedium`)是已登记例外,见 `design-principles.md`。
|
||||
- **容器分两级,同一页里同层级条目必须用同一套**(两个组件都在 `ui/components/Surfaces.kt`):
|
||||
- **页面区块**:`LptSection`,`MaterialTheme.shapes.medium`(12dp 圆角)+ `surface` 实底 + 内边距 `Dimens.Group`,无描边、无阴影,只用于页面级的独立区块。
|
||||
- **列表条目**:`LptListItem`,`MaterialTheme.shapes.small`(8dp 圆角)+ `BorderStroke(1.dp, outlineVariant)` + 内边距 `Dimens.Section`,无阴影,不套 `Card`;整条可点时传 `onClick`(走 `Surface` 的点击重载,水波纹被圆角裁切)。
|
||||
- 不用 `Card` 兼职两种层级:分区只用上面这两个组件,同一页不混用。
|
||||
- **`AlertDialog`**:用于不可撤销动作,必须二次确认,确认按钮文案写清后果而不是「确定」。「误操作结束」现有的确认语(说明该动作会放弃这次会话)可作正面例子。
|
||||
- **`Snackbar`**(`MainActivity.AppRoot` 的 `SnackbarHost`):底用 `surfaceContainerHigh`、字用 `onSurface`、圆角 `shapes.small`,左右留 `Dimens.Screen`、底部留 `Dimens.Inner`;常规 3–5 秒,失败用 `long`;不抢焦点、不挡当前操作;同文案 1.5 秒内去重(现有实现,正向例子)。不使用 M3 默认的 `inverseSurface`——深色下它会变成整屏最亮的一块。
|
||||
- **进度指示**:一律 `Modifier.size(...)`,见 `AGENTS.md`。
|
||||
- **空态与错误态**(`ui/components/States.kt`):空态用 `LptEmptyState`(一句事实 + 可选提示 + 一个可执行入口,不画插画、不用 emoji),错误用 `LptInlineError`(`errorContainer` 底 + 原因 + 重试),两者不共用同一分支;`loading && empty`、`error`、`empty` 三条分支各自成形。
|
||||
|
||||
### 动效
|
||||
|
||||
- 只动透明度与位移(`alpha` / `offset`),不动尺寸;时长取 `200ms` 量级,用 `tween` 默认缓动,不为单个页面另造曲线。
|
||||
- 不做全站统一的淡入 / 上移动画;一屏最多一两处动效用来表达因果。
|
||||
- 系统关掉动画(开发者选项里动画缩放设为 0)时界面必须照常可用:动效是实现方式,不是状态载体。
|
||||
|
||||
### 不要什么
|
||||
|
||||
- 不新增第 6 档字号、第 5 档圆角——需要时先改本节,再改代码。
|
||||
- 不为单个页面另造一套色板;一致性来自这套语义色与排版,不来自换主色。
|
||||
- 浮窗不得引入第二套强调色:`MINT` 是唯一强调色,`AMBER` 只承担到时与暂停提示。
|
||||
@@ -0,0 +1,68 @@
|
||||
# Android 测试规范
|
||||
|
||||
- **功能**:规定 Android 侧的测试分层现状、可测性约束、真机验证矩阵与提交前命令,明确「逻辑下沉到状态机与工具函数」是可视层不写测试的前提。
|
||||
- **何时用**:新增或修改会话状态机、计时、请求层、工具函数时;新增或修改界面、浮窗行为时;提交前跑检查时。
|
||||
- **适用范围**:App 页面与浮窗两者;分层只到 JVM 单测,界面与浮窗行为靠真机验证矩阵覆盖。
|
||||
|
||||
## 规则
|
||||
|
||||
### 分层现状
|
||||
|
||||
| 层 | 位置 | 现状 |
|
||||
|---|---|---|
|
||||
| JVM 单测 | `app/src/test/java/com/catshark/lpt/{session,service}/` | 仅 `SessionControllerTest`、`CountdownAlertTest` 两份(JUnit4 + kotlinx-coroutines-test) |
|
||||
| instrumentation / Robolectric / Compose UI 测试 | — | 未引入 |
|
||||
| ktlint / detekt | — | 未配置;只有 AGP 自带的 `:app:lintDebug` |
|
||||
|
||||
- 分层是现状,不是终点;要加一层先单独定路线(见「覆盖率与引入新工具」)。
|
||||
- 单测必须直接测真实代码:用 `SessionController` 与 `util/Format.kt` 本身断言,不把逻辑抄一份到测试里再自测。
|
||||
|
||||
### 可测性约束
|
||||
|
||||
- **状态机与计时必须能在 JVM 断言。** 时间一律从参数进来(`nowMs`),不直接读 `SystemClock` 再算:`SessionController.State.effectiveSeconds(nowMs = …)` 与 `CountdownAlert` 的现有测试就是这么写的,新增逻辑照此留出时间入口。
|
||||
- 协程用 `runTest`,不 `Thread.sleep`、不靠真实延时等结果。
|
||||
- 网络用 `LptApi` 的假实现(`SessionControllerTest` 用委托 + 覆盖方法),不为此额外引入 mock 框架,也不让单测打真机网络。
|
||||
- **界面层不写测试的前提**是逻辑都下沉到 `SessionController` 与 `util/`:页面只做「读状态 + 转发动作 + 排版」,这样界面改动不需要测试,也不会漏测。
|
||||
- 需要断言的界面行为(例如「连点只发一次请求」)在状态机里断言,不在界面层补:`repeatedStartSendsOnlyOneRequest` 是现成范例。
|
||||
|
||||
### 现有测试盖了什么
|
||||
|
||||
| 测试 | 条数 | 覆盖 |
|
||||
|---|---|---|
|
||||
| `SessionControllerTest` | 15 | 冲突检查失败不开会话、冲突只给已有会话、对账失败保持未解析且可重试、详情失败不当成空、确认无会话才清本地、连点只发一次、迟到响应被丢弃、结束等碎片写入且失败保留会话、业务错误不当成空、取消向上传播、碎片请求被拒也回调、缺失预期≠预期请求失败、计时基准取详情而非开始响应、零指针不默认成 25 分钟、旧 UI tick 不减时间 |
|
||||
| `CountdownAlertTest` | 7 | 单调锚点且到零停、暂停不递减、无倒计时不算到期、只在真正截止显示零、到期只提醒一次且重启与对账不重复、下一段可再提醒而已结束会话不提醒、恢复时已结束的会话只提醒一次且不自动结束 |
|
||||
|
||||
改状态机或倒计时时先看这两张表:没提到的新行为就是缺用例。
|
||||
|
||||
### 真机验证矩阵
|
||||
|
||||
界面与浮窗行为没有自动化覆盖,改动涉及哪行就手动走哪行(dev 包,`adb devices` 确认机型与版本):
|
||||
|
||||
| 场景 | 怎么验 | 期望 |
|
||||
|---|---|---|
|
||||
| 会话生命周期 | 开始 → 学几分钟 → 结束 | 时长与服务端口径一致,报告可打开 |
|
||||
| 暂停 / 继续 | 暂停 1 分钟再继续 | 暂停期间计时不动,继续后接上原基准 |
|
||||
| 记碎片 | 浮窗记一条、App 内记一条 | 两条都落库,输入框成功才清空 |
|
||||
| 结束与误操作结束 | 各走一次,取消一次 | 取消不改状态;确认后状态与通知同步 |
|
||||
| 浮窗跨 App 常驻 | 切到浏览器/微信/桌面 | 浮窗仍在,不挡对方主操作区 |
|
||||
| 拖动与吸附 | 拖到左、右、上、下边缘 | 吸附最近侧,8 秒后自动收起 |
|
||||
| 到时提醒 | 把预期时间设成 1 分钟 | 到点提醒一次,不重复、不自动结束 |
|
||||
| 权限撤销 | 系统设置里关掉悬浮窗权限再回 App | 不崩,能给降级与重新授权入口 |
|
||||
| 进程被杀 | 清后台后重新打开 | 会话状态与服务端口径一致 |
|
||||
| 断网 | 关网后开始/记碎片/结束 | 有明确错误文案,恢复网络后可重试 |
|
||||
|
||||
### 提交前检查
|
||||
|
||||
```bash
|
||||
./gradlew :app:assembleDebug :app:testDebugUnitTest :app:lintDebug
|
||||
```
|
||||
|
||||
- 三条全绿才算可交付;只跑其中一条时在交付说明里写清跑了哪条。
|
||||
- 需要 `JAVA_HOME` / `ANDROID_HOME`,见 `README.md`。
|
||||
|
||||
### 覆盖率与引入新工具
|
||||
|
||||
- **不设覆盖率阈值**:现有两份单测覆盖的是状态机与倒计时这类真正会错的地方,凑覆盖率没有意义。
|
||||
- 但**新增状态机分支必须带用例**:`State` 新增字段、`startOrContinue` 新增分支、`CountdownAlert` 新增触发条件,都要在 `SessionControllerTest` / `CountdownAlertTest` 里补一条能失败的断言。
|
||||
- 引入 Robolectric / instrumentation / Compose UI 测试 / ktlint / detekt **必须先单独定路线**(为什么加、跑在哪、CI 怎么接),不得在业务改动里顺手加依赖或加插件。
|
||||
- 界面改动的自检项见 `.agents/roles/ui-review-checklist.md`,这里不重复。
|
||||
@@ -0,0 +1,99 @@
|
||||
# Android 界面交付自检清单
|
||||
|
||||
- **功能**:交付 Android 界面前逐项自检的清单,先一份 10 条快检、再一份完整清单,覆盖状态完整性、交互反馈、按钮状态与命名、无障碍、布局滚动、内容承载、表单与浮窗专项,避免出现空/错态缺失、连点重复提交、主操作被挤掉、浮窗盖住操作等真机上才会暴露的问题。
|
||||
- **何时用**:改完任何有可见界面变化的代码、准备交付前;改主操作的位置或名字、加图标按钮时至少过快检 10 条;评审 Android 界面改动时;手动回归真机前。
|
||||
- **适用范围**:App 页面与浮窗两者;「浮窗专项」一节只对悬浮窗生效,其余每项标注「浮窗」的部分一并检查。
|
||||
|
||||
## 规则
|
||||
|
||||
### 快检 10 条(每次可见改动都过一遍)
|
||||
|
||||
改主操作的位置或名字、加图标按钮、改顶栏或底部的按钮区时,至少过这 10 条;下面那份完整清单留给新页面与整页改版。
|
||||
|
||||
- [ ] 主操作只一个,位置符合 `.agents/roles/design-principles.md` 的「主操作的位置」对照表;没因字号放大或文案变长被缩小、隐藏、塞进菜单。
|
||||
- [ ] 按钮名字是「动词 + 宾语」,按钮 / 加载中 / 成功 snackbar / 撤销四处用同一个动词。
|
||||
- [ ] 按钮五种样子齐:常态、按下、键盘聚焦、禁用、加载中(取值见 `design-system.md`);加载中文案保留、宽度不跳。
|
||||
- [ ] 图标按钮有 `contentDescription` 和 `Tooltip`,可点区 ≥48dp。
|
||||
- [ ] 错误与空数据分开,错误给原因 + 重试,重试真的重发。
|
||||
- [ ] 连点防护:在途标记加在中间层,按钮 `enabled` 绑到它。
|
||||
- [ ] 系统字体 200% 下不截断、不重叠,按钮文字不挤出容器;**不靠缩小字号换空间**。
|
||||
- [ ] 键盘弹出时输入框与保存按钮都可见(`imePadding`)。
|
||||
- [ ] 文字对比 ≥4.5:1,只用 `design-system.md` 登记过的组合。
|
||||
- [ ] 界面用「知识碎片」(行内可写「碎片」),不出现旧名「残片」。
|
||||
|
||||
> 每条自检要能拿出依据:真机截图、`adb` 命令输出或单测断言。只打勾不算过。
|
||||
|
||||
### 状态完整性(每处都要有)
|
||||
|
||||
- [ ] **五态齐备**:空 / 稀疏 / 密集 / 加载 / 错误。
|
||||
- [ ] **错误与空数据分开**:不用同一个分支兜住失败与空。`loading && empty`、`error`、`empty` 三条分支各自成形:空态用 `LptEmptyState`(一句事实 + 一个入口),错误用 `LptInlineError`(原因 + 重试),不让「列表为空」一条分支兼顾两者。
|
||||
- [ ] 空态给下一步动作(一句事实 + 一个可执行入口),错误态给原因 + 重试。
|
||||
- [ ] **加载不闪**:快响应不出现一闪而过的 spinner;重试前先重置失败状态。
|
||||
- [ ] **失败可恢复**:失败后能重试且重试真的重新发请求,不是只清一个布尔。
|
||||
- [ ] **「还不知道」不当成空**:对账是异步的,`State.resolved == false` 时看到的空是未知,不能据此显示「没有会话」或停服务(`AGENTS.md`)。
|
||||
- [ ] **冲突态单独成形**:`State.conflict` 只给「前往继续 / 取消」,不给「直接开始」。
|
||||
- [ ] 静稀两态都看过:只有 1 条内容时不显得突兀,长到两屏时滚动位置合理。
|
||||
|
||||
### 交互与反馈
|
||||
|
||||
- [ ] 可点元素看得出可点;不可点的内容不带可点暗示。
|
||||
- [ ] **Snackbar 3–5 秒自动消失,不抢焦点**,不挡当前正在操作的控件;同文案去重已有实现(`MainActivity` 的 1.5 秒去重,正向例子),新动作复用它而不是自己弹。
|
||||
- [ ] **破坏性操作二次确认**:结束会话、误操作结束都要 `AlertDialog` 确认,确认按钮文案写清后果。
|
||||
- [ ] **连点防护**:「在途」标记加在中间层,按钮 `enabled` 绑到该标记,文案可改「保存中…」(`AGENTS.md`)。
|
||||
- [ ] **成功才清输入,失败保留输入**。
|
||||
- [ ] 状态变化时点击区域不变大变小,也不挤动旁边布局。
|
||||
- [ ] 深色模式下逐屏看一眼对比度与阴影(浅深两套色板已按 `design-system.md` 落地,直接按登记值核对)。
|
||||
- [ ] 页面往返(页面 → 弹窗 → 返回)后草稿还在,不丢用户已经输入的内容。
|
||||
|
||||
### 无障碍
|
||||
|
||||
- [ ] 文字对比 ≥4.5:1,非文字(图标、描边、图形)≥3:1;取值只用 `design-system.md` 登记过的组合。
|
||||
- [ ] **描边门限口径**:1dp 分组描边(`outlineVariant`,浅 `#C6D6CD` / 深 `#33453D`)只做分隔、不表达状态,不参与非文字 3:1 门限;选中 / 错误 / 禁用必须另有文字或形态,不靠描边深浅。
|
||||
- [ ] 可点区域 ≥48dp;浮窗露出 24dp 把手是已登记的已知例外,不再缩小。
|
||||
- [ ] 非文字控件有 `contentDescription`(浮窗已做),Compose 侧新增图标按钮必须补。
|
||||
- [ ] 系统字体 130% 与 200% 下不截断、不重叠、按钮文字不挤出容器;空间不够时按 `design-principles.md` 的降级顺序(换行 → 缩文案 → 收次要 → 改图标),不缩主操作字号。
|
||||
- [ ] 状态不只靠颜色:暂停、到时、错误都有文字或形态差别。
|
||||
- [ ] TalkBack 走一遍主流程:能听到「是什么 + 点了会怎样」。
|
||||
|
||||
### 布局与滚动
|
||||
|
||||
- [ ] `Modifier.safeDrawingPadding()` 与 `Modifier.imePadding()` 包住可交互区,键盘弹出时输入框与保存按钮都可见(`MainActivity`、`FragmentInputActivity` 现状写法)。
|
||||
- [ ] 横屏下内容不被裁切,不出现横向滚动。
|
||||
- [ ] 小屏 360dp 宽下不溢出:长按钮文案、长任务名、四个中文数字并排都试过。
|
||||
- [ ] 分屏与可折叠设备下窗口尺寸变化不崩不重叠。
|
||||
- [ ] 一屏只有一个滚动轴,不嵌套滚动。
|
||||
- [ ] 自定义手势(浮窗拖动、边缘滑动)不与系统返回手势抢,不靠边缘区做主要交互。
|
||||
|
||||
### 内容承载
|
||||
|
||||
- [ ] 长文本换行或省略,省略时保留看全文的入口。
|
||||
- [ ] 任务名、碎片正文、预期文本三种长内容都试过极端长度(一两百字)。
|
||||
- [ ] 需要上下比较的数字用等宽字形(计时已用 `FontFamily.Monospace`)。
|
||||
- [ ] 日期与时长只用 `util/Format.kt` 的 `formatDateTime` / `formatDuration`,格式一致。
|
||||
- [ ] 中文标点用 `…` 而不是 `...`;数字与单位不拆行。
|
||||
|
||||
### 表单
|
||||
|
||||
- [ ] 每个输入有可见 label,不用 placeholder 代替 label;placeholder 只放示例值。
|
||||
- [ ] `KeyboardOptions` 选对键盘类型(数字、句子首字母大写),不一律默认。
|
||||
- [ ] 错误就近字段显示,并说明怎么修。
|
||||
- [ ] 不预先禁用提交按钮,不阻止粘贴;校验在输入之后。
|
||||
- [ ] 不可关闭的必填弹窗(如学习预期)只能填或走误操作结束。
|
||||
|
||||
### 浮窗专项
|
||||
|
||||
- [ ] 叠加在第三方 App 与桌面上都不挡对方的主操作区;收起态只占一条胶囊。
|
||||
- [ ] 不被系统栏、手势区、刘海与挖孔裁切;换一个 App 与横屏各看一眼。
|
||||
- [ ] 展开后 **8 秒**无操作自动收起(`AUTO_COLLAPSE_MS`),拖动过程中不收起。
|
||||
- [ ] 拖动后吸附到最近一侧并记住位置,重启后位置恢复。
|
||||
- [ ] 悬浮窗权限被撤销时不崩、不闪退,能降级成通知提示并引导重新授权。
|
||||
- [ ] 进程被杀后回到 App,浮窗与会话状态一致(会话还在就重新显示,不在就不显示)。
|
||||
- [ ] 通知权限被关闭时的降级路径可用:浮窗与 App 内状态仍能反映真实会话。
|
||||
- [ ] 浮窗里不做文本输入,需要输入时拉起 `FragmentInputActivity`。
|
||||
|
||||
### 交付前
|
||||
|
||||
- [ ] `./gradlew :app:assembleDebug :app:testDebugUnitTest :app:lintDebug` 三条全绿。
|
||||
- [ ] 真机走一遍改动涉及的路径(不只看预览或截图)。
|
||||
- [ ] 新页面或整页改版已走 `.agents/skills/ui-review/` 并写评审结论;没做的明确写出来。
|
||||
- [ ] 改主操作位置或名字、加图标按钮的改动:过完快检 10 条,并在交付说明里写一行结论。
|
||||
@@ -0,0 +1,165 @@
|
||||
---
|
||||
name: ui-review
|
||||
description: 对 lpt-android 的新页面或大范围界面改动做独立视觉评审:用已连真机通过 adb 截图取证、派无历史上下文的评审者按固定评分锚点打分并输出「问题 / 提升 / 保留」,主 agent 修完再截图核对一轮。当用户新增页面、重构页面结构、改版视觉语言、调悬浮窗外观、或说「页面难看 / 重新设计一下 / 评审下这个界面」时使用。触发词:评审界面、UI 评审、页面难看、重新设计、视觉评审、设计走查、新页面、改版、悬浮窗难看。
|
||||
metadata:
|
||||
short-description: Android 新页面与大改动的真机独立视觉评审
|
||||
---
|
||||
|
||||
# Android 界面独立评审
|
||||
|
||||
针对 `lpt-android` 的**新页面**或**大范围界面改动**(整页重构、视觉语言变更、新增信息区块、悬浮窗改版)走一遍:真机取证 → 独立评审 → 修正 → 复核。
|
||||
|
||||
与 `lpt-fe` 的同名技能同源意图——同一套流程与打分锚点,但取证方式与评审锚点是移动端的:画面来自真机 adb 截图,锚点换成触达尺寸、系统字体缩放、单手可达、系统栏与手势区,以及常驻悬浮窗的侵扰成本。两个仓库各自维护,不互相复制正文。
|
||||
|
||||
## 适用范围
|
||||
|
||||
- 只在 `lpt-android` 仓库内使用;`lpt-fe` / `lpt-ai` / `lpt-docs` 不适用。
|
||||
- 规则依据是本仓库 `.agents/roles/design-principles.md`(含禁用清单)、`.agents/roles/design-system.md`(现状规范)、`.agents/roles/ui-review-checklist.md`(交付自检)。评审时把 `design-system.md` 作为「现状规范」交给评审者,不让它凭空想象理想风格。
|
||||
- 小改动、局部低风险调整(改一句文案、调一个间距、补一条错误提示)不走本技能,按 `ui-review-checklist.md` 自检即可;只改主操作的位置或名字、加图标按钮时,过那份清单开头的快检 10 条就够。
|
||||
- 本技能只规定怎么取证、怎么派评审、按什么顺序修;代码改动与浮窗约束仍以 `AGENTS.md` 为准。
|
||||
|
||||
## 工作区约定
|
||||
|
||||
| 用途 | 路径 |
|
||||
|------|------|
|
||||
| 本技能 | `lpt-android/.agents/skills/ui-review/` |
|
||||
| 设计原则(禁用清单) | `lpt-android/.agents/roles/design-principles.md` |
|
||||
| 设计系统(现状规范) | `lpt-android/.agents/roles/design-system.md` |
|
||||
| 交付自检清单 | `lpt-android/.agents/roles/ui-review-checklist.md` |
|
||||
| 证据存放 | 本次任务的工作目录或 `/tmp`;**截图与评审记录不进仓库** |
|
||||
|
||||
登记在案的现状偏差(评审时按「现状」陈述,不能当成已修好):品牌主色目标 `#237556`、`Theme.kt` 的 primary 仍为 `#1F6FEB`;`labelSmall`(11sp)仍用在会话号与时间戳;`TextButton` 被当成通用动作入口;`Card` 同时充当区块与列表条目。
|
||||
|
||||
## Step 1 确认范围
|
||||
|
||||
| 项 | 说明 |
|
||||
|---|---|
|
||||
| 改动类型 | 全新页面 / 整页重构 / 视觉语言变更 / 局部新增区块 / 悬浮窗改版 |
|
||||
| 涉及页面 | 具体 `*Screen.kt` 或 `service/OverlayView.kt`,以及它当前的状态 |
|
||||
| 不可动的东西 | M3 组件依赖与 `Theme.kt` 的槽位结构、悬浮窗「只做三件事」的边界、分支与发布规则(`dev`/`master` 只差 `DEFAULT_BASE_URL`) |
|
||||
| 用户最常做的事 | 决定「一屏一个主角」是谁(列表页是「开始学习」,会话页是倒计时) |
|
||||
| 验收重点 | 这次最想让用户看到什么变化 |
|
||||
| 设计计划 | 写码前那份不超过 12 行的计划(主操作叫什么、放哪、删了什么),作为评审的对照基准;没写就先补,再送评审 |
|
||||
|
||||
缺一项就问,不要猜。存量页面润色时**不探索新风格**,只对齐 `design-system.md` 的现状规范。
|
||||
|
||||
## Step 2 取证(真机)
|
||||
|
||||
先有画面再评审;不用静态推断代替截图。
|
||||
|
||||
1. 确认设备:`adb devices` 的 device 行**有且仅有一个**。多于一台时后续命令统一加 `-s <serial>`;出现 `offline` / `unauthorized` 先解决,不要带着两台设备截图。
|
||||
当前设备:serial `f5269dcc`、Android 12、1080×2400 @440dpi、包名 `com.catshark.lpt`。设备换了要在交付说明里写清新设备。
|
||||
2. 截图与转码(固定两条;转 JPEG 是必须的,评审者拿到的是 jpg):
|
||||
```bash
|
||||
adb exec-out screencap -p > /tmp/lpt-<状态>.png
|
||||
ffmpeg -y -loglevel error -i /tmp/lpt-<状态>.png -vf scale=720:-1 -q:v 4 /tmp/lpt-<状态>.jpg
|
||||
```
|
||||
实测 244KB → 112KB;要看清小字时用 `scale=1080:-1`。
|
||||
3. 状态矩阵,除默认态外都要覆盖:
|
||||
|
||||
| 状态 | 怎么造 | 看什么 |
|
||||
|---|---|---|
|
||||
| 默认(有数据) | 启动 `com.catshark.lpt/.MainActivity`,列表有内容 | 主操作是否唯一、条目与区块有无层级差 |
|
||||
| 空 | 清空任务,走 `tasks.isEmpty() && !loading` 分支 | 空态是否只有一句文字加一个按钮 |
|
||||
| 加载中 | 冷启动或刷新瞬间连拍 | 有骨架还是只有居中 spinner |
|
||||
| 错误 | 断网或停掉后端再刷新 | 错误行能否恢复;文案是否直接暴露接口 message |
|
||||
| 横屏 | 见下「横屏」 | 是否压扁或裁切,计时与按钮是否仍在屏内 |
|
||||
| 系统字体 130% / 200% | 见下「字体缩放」 | 文字截断、按钮换行、顶栏挤爆 |
|
||||
| 深色 | `adb shell cmd uimode night yes` | `Theme.kt` 只覆盖少数槽位,看是否露出 M3 默认蓝紫 |
|
||||
| 浮窗叠在第三方 App 之上 | 见下「浮窗状态」 | 常驻侵扰、可读性、是否只有三件事 |
|
||||
| 权限被拒 | 见下「权限被拒」 | 引导页是否说清「为什么需要」,被拒后还能否进会话页 |
|
||||
|
||||
4. 字体缩放:设值 → 冷启动 → 截图 → 复原。
|
||||
```bash
|
||||
adb shell settings put system font_scale 1.3
|
||||
adb shell am force-stop com.catshark.lpt
|
||||
adb shell am start -n com.catshark.lpt/.MainActivity
|
||||
```
|
||||
200% 时把 `1.3` 换成 `2.0` 再跑同样的三步;每档截完都要复原:
|
||||
`adb shell settings delete system font_scale`。
|
||||
5. 横屏:锁竖屏后转 90° 截图,再复原。
|
||||
```bash
|
||||
adb shell settings put system accelerometer_rotation 0
|
||||
adb shell settings put system user_rotation 1
|
||||
```
|
||||
复原:`adb shell settings put system user_rotation 0` 与 `adb shell settings put system accelerometer_rotation 1`。
|
||||
6. 浮窗状态:进会话页点「显示 / 恢复悬浮窗」→ `adb shell input keyevent KEYCODE_HOME` → 打开任一第三方 App(例如 `adb shell am start -a android.settings.SETTINGS`)→ 截图。同时截浮窗展开态与收起态。
|
||||
7. 权限被拒:`adb shell appops set com.catshark.lpt SYSTEM_ALERT_WINDOW deny` → 启动 App 截权限引导页 → `... allow` 复原。
|
||||
8. 取证结束统一复原,别把设备留在 200% 字体、横屏或深色上:`adb shell cmd uimode night auto`。
|
||||
9. 抓不到的页面(需要登录态、需要真实会话、系统托管的权限弹窗)显式标「未验证」,不当它是合格。
|
||||
10. 自己先做一次三秒测试:打开 720 宽 jpg 看三秒,写下「像哪一类产品」「第一眼看到的是什么」两句;明显不合格的先改再送评审。
|
||||
|
||||
## Step 3 派独立评审者
|
||||
|
||||
- 用 `subagent` 派一个**没有历史上下文**的子代理;一次只派一个,不要多个评审者。
|
||||
- 交给它的材料只有:**截图 + 任务与约束 + `design-system.md` 的现状规范 + 下面的提示词模板**。
|
||||
- **不给**代码、不给制作过程、不给你的实现说明——评审只看画面,避免被实现细节带偏。
|
||||
- 没有可派子代理的环境时,按同一模板自查,并在交付说明里写明「未独立评审」。
|
||||
|
||||
### 评审提示词模板
|
||||
|
||||
```text
|
||||
你是这次界面改动的独立视觉评审者,没有参与制作。只根据我给的截图、任务描述和现状设计规范评审。
|
||||
|
||||
任务:[这次改动要解决什么、给谁用、主任务是什么]
|
||||
约束:[不可动的品牌主色/字体/M3 组件/悬浮窗三件事边界;目标设备与分辨率]
|
||||
现状规范:[.agents/roles/design-system.md 的全文]
|
||||
截图:[文件路径与每个文件对应的状态、设备分辨率与字体缩放档]
|
||||
|
||||
评审要求(按顺序做,看不清就写明"未验证",不要猜):
|
||||
0. 三秒测试:把首屏缩到 720 宽看三秒,写出两句:它像哪一类产品;第一眼看到的是什么,这个东西换到别的产品上是否同样成立。
|
||||
1. 品类与标杆:指出这属于什么品类(移动学习 / 计时类 App),该品类的优秀产品首屏怎么做;现有画面哪里违背了品类共识,是有意为之还是套了默认模板。
|
||||
2. 默认做法检查:逐条对照设计规范里的禁用清单,指出画面上仍在的项;特别点名 M3 默认模板感(默认灰 Card、全宽描边输入框、等权文字按钮顶栏、灰 Card 既当区块又当条目)。
|
||||
3. 状态检查:空 / 稀疏 / 密集 / 加载 / 错误五态是否都有合理呈现;错误态能否恢复。
|
||||
4. 层级与减法:哪块在抢注意力、哪块该更安静;点名可直接删掉的文字、面板与装饰。
|
||||
5. 可读性:触达目标是否≥48dp、130% 与 200% 系统字体下是否读得全、文字对比度、数字是否等宽、单手可达区域、内容是否避开系统栏与手势区。
|
||||
6. 浮窗专项(截图里有浮窗时必答):它常驻在其他 App 之上,侵扰成本是否可接受、同屏信息是否读得清、是否仍然只有「倒计时 / 记一条碎片 / 暂停继续」三件事。
|
||||
|
||||
输出格式(先问题,后提升):
|
||||
- 问题:只写会阻断任务、读不清、或明显是默认模板的,按影响从大到小,最多 5 条。每条写「位置 + 观察到的现象 + 影响 + 修完应该达到什么结果」。
|
||||
- 提升:精致度 / 设计感 / 动效三项都要表态,最多 5 条,某项确实没有差距就写"没有"和依据。
|
||||
- 保留:一两处修改时不能磨掉的做法。
|
||||
- 打分:[新页面或改版才打分,存量润色不打分,只列客观修正建议]
|
||||
|
||||
打分锚点(拿不准取低一档):
|
||||
10 挑不出可观察缺陷,至少一处是品类里没见过的好做法
|
||||
9 主流程、异常状态、细节都成立,提升只剩小处
|
||||
8 方向鲜明、主流程走得通、没有阻断或数据丢失;若干中等问题
|
||||
7 方向成立,但有一处会让用户丢数据/走错/卡住,或首屏仍是明显默认模板
|
||||
5-6 能看出方向,但骨架是默认模板,或主流程多处卡住
|
||||
1-4 主任务走不通,或画面有重叠、裁切、看不清这类基本错误
|
||||
|
||||
不要修改任何文件,不要替我定构图,只给诊断与目标。
|
||||
```
|
||||
|
||||
## Step 4 按结果修正
|
||||
|
||||
- 问题按评审给出的顺序修,从影响最大的开始。
|
||||
- 首条是「重做:……」时(分数落在 6 分及以下、骨架仍是默认模板),**回到 `.agents/roles/design-principles.md` 的「页面信息架构」重排结构**,不要在被否定的骨架上做局部修饰。
|
||||
- 只做减法与结构修正,不靠加功能、加数据量来换真实感;要求新增任何元素时,同一条里写明为它腾位置删掉什么。
|
||||
- 浮窗相关改动先对 `AGENTS.md` 的三件事边界与窗口标志约束,越界的建议直接退回。
|
||||
- 修完按 `.agents/roles/ui-review-checklist.md` 自检一遍。
|
||||
|
||||
## Step 5 复核
|
||||
|
||||
- 用 Step 2 同一套状态与字体档重新截图,再派一次评审者,**逐条核对上一轮清单**:修掉了几条、有没有引入新问题。
|
||||
- 最多两轮。第二轮仍有 6 分及以下的问题,停下来找用户确认方向,不要继续自己改。
|
||||
- 风格开始漂移、意见反复时,保留最合适的版本并说明取舍。
|
||||
|
||||
## Step 6 交付说明
|
||||
|
||||
回复里必须包含:
|
||||
|
||||
1. 什么改动、为什么这么改(对应哪条设计原则);
|
||||
2. 做了哪些动效;
|
||||
3. 评审轮次与结果:打分制写每轮分数;未独立评审要写明;
|
||||
4. 删掉了哪些文字与装饰;
|
||||
5. 未完成与非界面问题(环境、接口、真机不可达)各一行,不排查。
|
||||
|
||||
## 禁止事项
|
||||
|
||||
- 不截图就派评审,或拿静态推断当画面证据。
|
||||
- 把代码给评审者,或让评审者看制作过程。
|
||||
- 把截图、评审记录提交进仓库。
|
||||
- 在被判定「重做」的骨架上继续做局部修饰。
|
||||
- 用模拟器分辨率冒充真机结果,或换了设备却不写明设备型号与分辨率。
|
||||
@@ -169,13 +169,25 @@ jobs:
|
||||
echo "release id=$RID"
|
||||
|
||||
# 2) 同名附件先删,保证下载链接稳定
|
||||
# Gitea 的附件删除路径带 release id:DELETE /releases/{release_id}/assets/{asset_id}
|
||||
# (曾经缺了 /{release_id} 这一段,线上返回 404,构建 19 分钟成功后整条流水线判失败)
|
||||
ASSETS_JSON="$(mktemp)"
|
||||
curl -fsS "${AUTH[@]}" "$API/releases/$RID/assets" -o "$ASSETS_JSON"
|
||||
for NAME in "$ASSET" "${ASSET}.sha256"; do
|
||||
AID="$(cat "$ASSETS_JSON" | asset_id "$NAME")"
|
||||
if [ -n "$AID" ]; then
|
||||
echo "删除旧附件 $NAME (id=$AID)"
|
||||
curl -fsS "${AUTH[@]}" -X DELETE "$API/releases/assets/$AID" > /dev/null
|
||||
CODE="$(curl -sS -o /dev/null -w '%{http_code}' "${AUTH[@]}" \
|
||||
-X DELETE "$API/releases/$RID/assets/$AID")"
|
||||
case "$CODE" in
|
||||
200|204) echo "OK: 已删除 $NAME" ;;
|
||||
404) echo "跳过:$NAME 已不存在(HTTP 404)" ;;
|
||||
*)
|
||||
echo "ERROR: 删除 $NAME 失败,HTTP $CODE(期望 200/204)"
|
||||
echo " 路径:$API/releases/$RID/assets/$AID"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
done
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ local.properties
|
||||
.idea/
|
||||
*.iml
|
||||
captures/
|
||||
artifacts/qa/
|
||||
|
||||
# 系统
|
||||
.DS_Store
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
## 规则与技能位置
|
||||
|
||||
- 通用规则(跨仓库):meta 仓库 `.agents/roles/`(提交规范见其中的 `commit-convention.md`)。
|
||||
- 本仓库暂无专属 `roles/` 与 `skills/`;出现 Android 专属约定时再建。
|
||||
- 命名:业务概念的英文名以 `lpt-docs/docs/concepts/README.md` 术语表为准,模型类与字段由它派生(规则见 meta `.agents/roles/business-terminology.md`)。
|
||||
- 本仓库专属规则(`.agents/roles/`):`design-principles.md` 写码前设计计划与页面结构取舍 · `design-system.md` 颜色间距圆角文字与按钮状态取值 · `code-standards.md` Compose 写法与请求层 · `ui-review-checklist.md` 快检与交付自检 · `testing.md` 测试分层与真机验证矩阵。
|
||||
- 本仓库专属技能(`.agents/skills/`):`ui-review` 新页面或整页改版的真机截图评审。
|
||||
|
||||
## 技术栈
|
||||
|
||||
@@ -24,6 +26,7 @@
|
||||
| `session/` | `SessionController` 是会话状态机唯一入口;UI 与服务都只读它的 `StateFlow` |
|
||||
| `service/` | 前台服务与悬浮窗;不承载业务逻辑,只渲染状态并转发动作 |
|
||||
| `ui/` | Compose 页面(含 `ReportsScreen`);不直接调 Retrofit,只调 `SessionController` / `AppContainer` |
|
||||
| `.agents/` | 本仓库专属规则与技能;界面取值与判据只在这里登记一次 |
|
||||
|
||||
## 必须遵守的约定
|
||||
|
||||
|
||||
@@ -8,7 +8,11 @@ LPT 的学习计时原本只能在电脑浏览器里进行;而真实的学习
|
||||
|
||||
- 浮窗常驻在其他 App 之上,学习计时不因切走而中断。
|
||||
- 不抢输入法焦点、不挡住下层 App 的触摸(`FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL`)。
|
||||
- 12 秒无操作自动收成贴边小胶囊,点一下恢复;常态 80% 不透明,收起后约 60%。
|
||||
- 默认收纳到屏幕左右侧,仅露出 24dp 的状态把手,点按展开为完整计时 +「记碎片 / 暂停或继续」面板。
|
||||
- 侧边把手与面板都可拖动,松手吸附最近一侧并记住位置;8 秒无操作自动收入边缘,横竖屏切换重新校正边界。
|
||||
- 深色面板搭配薄荷绿倒计时,暂停或到时用暖色提示;写请求在途时禁用操作。
|
||||
- 倒计时基于详情接口 `pointerPosition`(毫秒)与 `lastStartTime` 对锚,到零停在 `00:00`;累计有效学习时间继续在 App 和通知里展示。
|
||||
- 到时自动展开浮窗并发送一次「学习到时提醒」通知(声音/振动遵循系统设置),不自动暂停或结束;同一运行分段对账或进程恢复不重复提醒。通知权限被关闭时仍有浮窗文字提示。
|
||||
- 可在浮窗里直接记一条知识碎片(拉起轻量输入弹窗)。
|
||||
|
||||
浮窗的职责被刻意压到最小:**只展示倒计时、记碎片、暂停/继续**。其余动作(结束会话、写报告、改预期、看历史)都在 App 页面内完成。
|
||||
@@ -19,7 +23,7 @@ LPT 的学习计时原本只能在电脑浏览器里进行;而真实的学习
|
||||
|------|------|
|
||||
| 登录 | `POST /login` 拿 token,DataStore 持久化,OkHttp 拦截器注入 `satoken` 请求头;服务端返回 401 时自动退出登录并在登录页说明原因 |
|
||||
| 权限引导 | 悬浮窗权限 / 通知权限 / 电池优化白名单 / MIUI 自启动与后台弹出 |
|
||||
| 任务列表 | `GET /tasks`,每个任务带「报告」入口;有进行中的会话时顶部带「回到会话」入口 |
|
||||
| 任务列表 | `GET /tasks`,支持本地搜索、刷新及加载失败重试,每个任务带「报告」入口;有进行中的会话时顶部带「回到会话」入口 |
|
||||
| 操作反馈 | 保存预期、保存 API 地址、开始/暂停/结束、记碎片等动作都有 snackbar 提示(成功短、失败长);所有发请求的按钮在途时禁用,防连点重复提交 |
|
||||
| 学习会话 | 开始/继续、暂停、结束、误操作结束(零数据)、学习预期(必填)、知识碎片、结束报告三段 |
|
||||
| 会话冲突出口 | 开始新任务前先查其他任务上的未结束会话;有冲突时只给「前往继续 / 取消」,结束与误操作结束必须回到那个会话的页面里自己做 |
|
||||
@@ -91,7 +95,7 @@ gradle :app:assembleDebug
|
||||
## 关键实现决定
|
||||
|
||||
- **计时口径**:显示值 = 服务端 `effectiveTime`(基准)+ 以 `SystemClock.elapsedRealtime()` 为锚点的增量。**不用 tick 累加**,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时用服务端 `lastStartTime` 重新对锚。
|
||||
- **窗口必须带 `FLAG_LAYOUT_NO_LIMITS`**:否则 WindowManager 会把越界位置夹回屏幕内,半隐藏会失效(实测 `mAttrs x=-651` 但 `mFrame` 仍是 `[0,...]`)。
|
||||
- **浮窗边界**:保留 `FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL | FLAG_LAYOUT_NO_LIMITS`;增加 `FLAG_LAYOUT_IN_SCREEN`,用系统栏与刘海 Insets 计算安全范围,避免 MIUI 的状态栏偏移让底部浮窗越界。收起状态只显示状态点与展开箭头,计时在展开后完整显示。
|
||||
- **浮窗内不做文本输入**:App 不在前台时,系统不允许后台窗口弹软键盘——实测浮窗的 `EditText` 能拿到输入连接(`mServedView=EditText`),但 IME 窗口 `mViewVisibility=0x8`(GONE)。因此「记碎片」改为拉起 `FragmentInputActivity`(带 `SYSTEM_ALERT_WINDOW` 的 App 有后台启动 Activity 豁免),并给它独立 `taskAffinity`,保存后回到用户原本在用的 App。
|
||||
- **服务自恢复**:App 启动时 `GET /study-sessions/active` 对账,恢复未结束的会话;只要状态里有活跃会话就拉起前台服务,权限是后来才授予的也会每秒兜底重试 `overlay.show()`。进程被系统拉起时(`START_STICKY`)服务自己会补一次对账,**只有「对过账且确实没有会话」才停服务**,否则会先自杀而没人再拉起来。
|
||||
- **浮窗职责固定为三件事**:展示倒计时、记一条碎片、暂停/继续。结束、写报告、改预期、看历史都必须在 App 页面内完成(详见 `AGENTS.md`)。
|
||||
@@ -129,5 +133,8 @@ app/src/main/java/com/catshark/lpt/
|
||||
- 浮窗依赖悬浮窗权限;进程被杀后靠 `START_STICKY` + 启动时对账恢复。实测 **MIUI(Android 12)不会重启被杀的进程**:进程没了浮窗就没了,需要用户打开一次 App 才恢复(打开后的对账是可靠的)。
|
||||
- 国内 OEM 的省电策略可能杀掉前台服务,需要用户手动白名单。
|
||||
- 报告第四部分「按归属分组的碎片」由复习模块实时聚合,本客户端按仓库边界不访问复习端点,报告页只列本次会话产生的碎片。
|
||||
- 没有自动化测试;`.gitea/workflows/build.yml` 只构建不跑测试。
|
||||
- **全屏视频输入**:碎片输入使用非 floating 的透明 Activity,按系统栏和 IME Insets 调整可用区域。横屏键盘弹出时收紧标题、将保存/取消放在顶栏,编辑框内部滚动,避免固定高度对话框裁切输入内容。
|
||||
- **弱网恢复与输入保护**:冲突查询失败时阻止开始;恢复失败保留未知状态并提供重试;退出登录取消会话请求。结束失败保留报告弹窗内容,AI 草稿晚到时由用户确认后采用。
|
||||
- **验证**:`gradle :app:testDebugUnitTest :app:assembleDebug :app:lintDebug`。JVM 回归覆盖会话冲突、恢复失败、取消、重复提交与写入互斥;真机截图保存在本地忽略目录 `artifacts/qa/`。
|
||||
- 构建流水线目前只构建 APK,尚未集成测试步骤。
|
||||
- 学习录音(系统混音采集)未做,属于二期。
|
||||
|
||||
@@ -66,5 +66,8 @@ dependencies {
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2")
|
||||
|
||||
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
|
||||
@@ -35,7 +36,8 @@
|
||||
android:launchMode="singleTop"
|
||||
android:noHistory="true"
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/Theme.LPT.InputDialog" />
|
||||
android:theme="@style/Theme.LPT.InputDialog"
|
||||
android:windowSoftInputMode="stateAlwaysVisible|adjustResize" />
|
||||
|
||||
<service
|
||||
android:name=".service.StudySessionService"
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.provider.Settings
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -11,12 +12,15 @@ import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Snackbar
|
||||
import androidx.compose.material3.SnackbarDuration
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
@@ -44,7 +48,9 @@ import com.catshark.lpt.ui.ReportsScreen
|
||||
import com.catshark.lpt.ui.SessionScreen
|
||||
import com.catshark.lpt.ui.SettingsScreen
|
||||
import com.catshark.lpt.ui.TaskListScreen
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
import com.catshark.lpt.ui.theme.LptTheme
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
@@ -89,7 +95,6 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
|
||||
val ready by container.ready.collectAsState()
|
||||
val loggedIn by container.loggedIn.collectAsState()
|
||||
val username by container.username.collectAsState()
|
||||
val baseUrl by container.baseUrl.collectAsState()
|
||||
val sessionState by container.session.state.collectAsState()
|
||||
val authNotice by container.authNotice.collectAsState()
|
||||
@@ -99,6 +104,7 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
var tasks by remember { mutableStateOf<List<TaskItem>>(emptyList()) }
|
||||
var tasksLoading by remember { mutableStateOf(false) }
|
||||
var tasksError by remember { mutableStateOf<String?>(null) }
|
||||
var tasksJob by remember { mutableStateOf<Job?>(null) }
|
||||
var reportTask by remember { mutableStateOf<TaskItem?>(null) }
|
||||
|
||||
// 保存/开始/结束这类动作必须给出即时反馈,不能只靠页面底部的静态文案
|
||||
@@ -120,16 +126,15 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
}
|
||||
|
||||
fun refreshTasks() {
|
||||
if (tasksLoading || !container.loggedIn.value) return
|
||||
tasksLoading = true
|
||||
tasksError = null
|
||||
scope.launch {
|
||||
tasksJob = scope.launch {
|
||||
try {
|
||||
container.repository.tasks()
|
||||
.onSuccess {
|
||||
tasks = it
|
||||
tasksLoading = false
|
||||
}
|
||||
.onFailure {
|
||||
tasksError = it.message ?: "加载任务失败"
|
||||
.onSuccess { tasks = it }
|
||||
.onFailure { tasksError = it.message ?: "加载任务失败" }
|
||||
} finally {
|
||||
tasksLoading = false
|
||||
}
|
||||
}
|
||||
@@ -140,6 +145,9 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
refreshTasks()
|
||||
if (!Settings.canDrawOverlays(context)) screen = Screen.Permissions
|
||||
} else {
|
||||
tasksJob?.cancel()
|
||||
tasksLoading = false
|
||||
tasksError = null
|
||||
tasks = emptyList()
|
||||
screen = Screen.Tasks
|
||||
}
|
||||
@@ -174,16 +182,11 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
}
|
||||
}
|
||||
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
// 不在会话页时,会话层的失败也要让用户看到(用正常布局占位,不遮住下面的标题)
|
||||
if (screen != Screen.Session) {
|
||||
sessionState.error?.let { message ->
|
||||
ErrorBar(message = message, onDismiss = { container.session.consumeError() })
|
||||
}
|
||||
BackHandler(enabled = loggedIn && screen != Screen.Tasks) {
|
||||
if (!sessionState.expectationRequired) screen = Screen.Tasks
|
||||
}
|
||||
|
||||
Box(modifier = Modifier.weight(1f)) {
|
||||
Box(modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding()) {
|
||||
when {
|
||||
!ready -> LoadingScreen()
|
||||
|
||||
@@ -199,11 +202,11 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
tasks = tasks,
|
||||
loading = tasksLoading,
|
||||
error = tasksError,
|
||||
username = username,
|
||||
onRefresh = { refreshTasks() },
|
||||
onStart = { task ->
|
||||
container.session.startOrContinue(task.taskNum) {
|
||||
StudySessionService.start(context)
|
||||
screen = Screen.Session
|
||||
}
|
||||
},
|
||||
onOpenReports = { task ->
|
||||
@@ -211,14 +214,9 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
screen = Screen.Reports
|
||||
},
|
||||
hasActiveSession = sessionState.hasSession,
|
||||
starting = sessionState.busy,
|
||||
starting = sessionState.writing,
|
||||
onOpenSession = { screen = Screen.Session },
|
||||
onOpenSettings = { screen = Screen.Settings },
|
||||
onOpenPermissions = { screen = Screen.Permissions },
|
||||
onLogout = {
|
||||
StudySessionService.stop(context)
|
||||
container.logout()
|
||||
},
|
||||
)
|
||||
|
||||
Screen.Session -> SessionScreen(
|
||||
@@ -246,8 +244,13 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
},
|
||||
onSaveExpectation = { text, onResult -> container.session.saveExpectation(text, onResult) },
|
||||
onAddFragment = { text, onResult -> container.session.addFragment(text, onResult) },
|
||||
onShowOverlay = { StudySessionService.showOverlay(context) },
|
||||
// 浮窗已经在上层时这一步不会有任何视觉变化,用一句提示交代「按了、它已经在」
|
||||
onShowOverlay = {
|
||||
StudySessionService.showOverlay(context)
|
||||
toast("悬浮窗已显示")
|
||||
},
|
||||
onGenerateDraft = { container.session.generateReportDraft() },
|
||||
onRetrySync = { container.session.reconcile() },
|
||||
onBack = { screen = Screen.Tasks },
|
||||
)
|
||||
|
||||
@@ -283,8 +286,6 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 会话-05:别的任务上还有未结束会话时,只能先去把它处理完
|
||||
sessionState.conflict?.let {
|
||||
@@ -301,11 +302,22 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
)
|
||||
}
|
||||
|
||||
// 提示条走登记过的深底语义色,别用 M3 默认反色(深色下会变成整屏最亮的一块)
|
||||
SnackbarHost(
|
||||
hostState = snackbarHostState,
|
||||
modifier = Modifier.align(Alignment.BottomCenter),
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.padding(horizontal = Dimens.Screen, vertical = Dimens.Inner),
|
||||
) { data ->
|
||||
Snackbar(
|
||||
snackbarData = data,
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
actionColor = MaterialTheme.colorScheme.primary,
|
||||
shape = MaterialTheme.shapes.small,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -333,7 +345,7 @@ private fun SessionConflictDialog(
|
||||
)
|
||||
Text(
|
||||
conflict.sessionNum,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
if (conflict.autoConverged) {
|
||||
@@ -351,7 +363,7 @@ private fun SessionConflictDialog(
|
||||
)
|
||||
if (busy) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(modifier = Modifier.padding(end = 8.dp), strokeWidth = 2.dp)
|
||||
CircularProgressIndicator(modifier = Modifier.padding(end = Dimens.Inner).size(18.dp), strokeWidth = 2.dp)
|
||||
Text("正在打开那个会话…", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
@@ -361,7 +373,7 @@ private fun SessionConflictDialog(
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(Dimens.Inner)) {
|
||||
Button(
|
||||
onClick = onContinue,
|
||||
enabled = !busy,
|
||||
@@ -377,33 +389,9 @@ private fun SessionConflictDialog(
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ErrorBar(message: String, onDismiss: () -> Unit) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.errorContainer,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(12.dp),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
message,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = onDismiss) { Text("关闭") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LoadingScreen() {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
CircularProgressIndicator(modifier = Modifier.size(40.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.catshark.lpt.data
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import retrofit2.HttpException
|
||||
|
||||
@@ -9,11 +10,13 @@ class ApiException(message: String) : Exception(message)
|
||||
/**
|
||||
* 学习会话仓库:把 Retrofit 调用包成 Result,并把 `code != 200` 转成 ApiException。
|
||||
*/
|
||||
class LptRepository(private val apiClient: ApiClient) {
|
||||
class LptRepository(private val apiProvider: () -> LptApi) {
|
||||
|
||||
private val api get() = apiClient.api
|
||||
constructor(apiClient: ApiClient) : this({ apiClient.api })
|
||||
|
||||
private inline fun <T> envelope(env: ApiEnvelope<T>, action: String): T {
|
||||
private val api get() = apiProvider()
|
||||
|
||||
private fun <T> envelope(env: ApiEnvelope<T>, action: String): T {
|
||||
if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "${action}失败")
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return env.data as T
|
||||
@@ -29,6 +32,8 @@ class LptRepository(private val apiClient: ApiClient) {
|
||||
private fun <T> Result<T>.friendly(action: String? = null): Result<T> {
|
||||
val error = exceptionOrNull()
|
||||
return when {
|
||||
error is CancellationException -> throw error
|
||||
|
||||
error is HttpException -> {
|
||||
val detail = "HTTP ${error.code()}"
|
||||
val message = if (action != null) {
|
||||
@@ -77,7 +82,9 @@ class LptRepository(private val apiClient: ApiClient) {
|
||||
}
|
||||
|
||||
suspend fun getExpectation(sessionNum: String): Result<String> = call {
|
||||
api.getExpectation(sessionNum).takeIf { it.code == 200 }?.data?.description.orEmpty()
|
||||
val env = api.getExpectation(sessionNum)
|
||||
if (env.code != 200) throw ApiException(env.message ?: "获取学习预期失败")
|
||||
env.data?.description.orEmpty()
|
||||
}
|
||||
|
||||
suspend fun putExpectation(sessionNum: String, description: String): Result<Unit> = call {
|
||||
@@ -124,7 +131,7 @@ class LptRepository(private val apiClient: ApiClient) {
|
||||
}
|
||||
|
||||
suspend fun fragments(sessionNum: String): Result<List<FragmentItem>> = call {
|
||||
api.fragmentsBySession(sessionNum).takeIf { it.code == 200 }?.data.orEmpty()
|
||||
envelope(api.fragmentsBySession(sessionNum), "获取知识碎片").orEmpty()
|
||||
}
|
||||
|
||||
/** 依次任务的历史报告(按会话生成,分页) */
|
||||
@@ -134,7 +141,7 @@ class LptRepository(private val apiClient: ApiClient) {
|
||||
|
||||
/** 本次会话的全部碎片原文 */
|
||||
suspend fun allFragments(sessionNum: String): Result<List<String>> = runCatching {
|
||||
api.allFragments(sessionNum).takeIf { it.code == 200 }?.data.orEmpty()
|
||||
envelope(api.allFragments(sessionNum), "查看本次碎片").orEmpty()
|
||||
}.friendly("查看本次碎片")
|
||||
|
||||
/**
|
||||
|
||||
@@ -54,7 +54,8 @@ data class SessionDetail(
|
||||
val effectiveTime: Double = 0.0,
|
||||
val effectivenessRatio: Double = 0.0,
|
||||
val sessionState: String = "",
|
||||
val pointerPosition: Double = 0.0,
|
||||
/** 本段开始时的剩余毫秒;缺失不同于已经归零。 */
|
||||
val pointerPosition: Double? = null,
|
||||
val systemMessage: String? = null,
|
||||
val autoConverged: Boolean = false,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.catshark.lpt.service
|
||||
|
||||
import com.catshark.lpt.session.SessionController
|
||||
|
||||
/** 纯判定:暂停、无倒计时、已提醒的同一分段均不重复触发。 */
|
||||
internal fun countdownAlertKey(state: SessionController.State, nowMs: Long, lastAlertKey: String?): String? {
|
||||
if (state.status != SessionController.Status.ONGOING || state.remainingMs(nowMs) != 0L) return null
|
||||
return state.countdownKey?.takeUnless { it == lastAlertKey }
|
||||
}
|
||||
@@ -3,336 +3,370 @@ package com.catshark.lpt.service
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.Rect
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.graphics.drawable.RippleDrawable
|
||||
import android.content.res.ColorStateList
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.text.TextUtils
|
||||
import android.view.Gravity
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.WindowInsets
|
||||
import android.view.WindowManager
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import com.catshark.lpt.session.SessionController
|
||||
import com.catshark.lpt.util.formatDuration
|
||||
import com.catshark.lpt.util.formatCountdown
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* 系统级悬浮窗(经典 View 实现)。
|
||||
*
|
||||
* 职责被刻意压到最小——浮窗只做三件事:
|
||||
* 1. 展示倒计时;
|
||||
* 2. 记一条知识碎片(拉起 FragmentInputActivity,浮窗内不做文本输入);
|
||||
* 3. 暂停 / 继续计时。
|
||||
*
|
||||
* 其余动作(改预期、结束会话、写报告、看历史)一律在 App 页面内完成,不要往浮窗里加。
|
||||
*
|
||||
* 两种形态:
|
||||
* - 常态条:`● 12:34 + 暂停`,FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL,不抢焦点、浮窗外触摸透传。
|
||||
* - 半隐藏:只剩一个「● 计时」小胶囊,贴边并部分滑出屏幕;点一下恢复。12 秒无操作自动进入。
|
||||
*
|
||||
* 窗口带 FLAG_LAYOUT_NO_LIMITS,否则 WindowManager 会把越界位置夹回屏幕内(半隐藏会失效)。
|
||||
*
|
||||
* 碎片输入不在这里做:App 不在前台时系统不允许后台窗口弹软键盘,
|
||||
* 所以「+」回调给 Service,由它拉起 FragmentInputActivity。
|
||||
*/
|
||||
/** 经典 View 浮窗:贴边计时胶囊 + 展开面板,仅提供记碎片与暂停/继续。 */
|
||||
class OverlayView(private val context: Context) {
|
||||
|
||||
private val wm = context.getSystemService(WindowManager::class.java)
|
||||
|
||||
private val preferences = context.getSharedPreferences("study_overlay", Context.MODE_PRIVATE)
|
||||
private var root: LinearLayout? = null
|
||||
private var params: WindowManager.LayoutParams? = null
|
||||
private var shown = false
|
||||
private var halfHidden = false
|
||||
private var compact = true
|
||||
private var dockRight = preferences.getBoolean("dock_right", true)
|
||||
private var verticalFraction = preferences.getFloat("vertical_fraction", 0.25f)
|
||||
private var dragging = false
|
||||
private var lastState: SessionController.State? = null
|
||||
|
||||
private lateinit var barRow: LinearLayout
|
||||
private lateinit var dotView: View
|
||||
private lateinit var panel: LinearLayout
|
||||
private lateinit var capsule: LinearLayout
|
||||
private lateinit var statusView: TextView
|
||||
private lateinit var timeView: TextView
|
||||
private lateinit var compactTime: TextView
|
||||
private lateinit var compactDot: View
|
||||
private lateinit var fragmentView: TextView
|
||||
private lateinit var toggleView: TextView
|
||||
private lateinit var compactRow: LinearLayout
|
||||
private lateinit var compactDot: View
|
||||
private lateinit var compactTime: TextView
|
||||
|
||||
var onTogglePause: (() -> Unit)? = null
|
||||
var onRequestFragmentInput: (() -> Unit)? = null
|
||||
val isShown: Boolean get() = root != null
|
||||
|
||||
val isShown: Boolean get() = shown
|
||||
|
||||
private val autoHideTask = Runnable {
|
||||
if (shown && !halfHidden) setHalfHidden(true)
|
||||
}
|
||||
|
||||
private fun dp(value: Int): Int = (value * context.resources.displayMetrics.density).toInt()
|
||||
|
||||
private fun rounded(color: Int, radiusDp: Int): GradientDrawable = GradientDrawable().apply {
|
||||
private val collapseTask = Runnable { if (!dragging) setCompact(true) }
|
||||
private fun dp(value: Int) = (value * context.resources.displayMetrics.density).toInt()
|
||||
private fun background(color: Int, radius: Int, border: Boolean = false) = GradientDrawable().apply {
|
||||
setColor(color)
|
||||
cornerRadius = dp(radiusDp).toFloat()
|
||||
}
|
||||
|
||||
private fun pill(label: String, bg: Int, textColor: Int = Color.WHITE): TextView = TextView(context).apply {
|
||||
text = label
|
||||
textSize = 13f
|
||||
setTextColor(textColor)
|
||||
gravity = Gravity.CENTER
|
||||
background = rounded(bg, 10)
|
||||
setPadding(dp(12), dp(6), dp(12), dp(6))
|
||||
isClickable = true
|
||||
isFocusable = false
|
||||
cornerRadius = dp(radius).toFloat()
|
||||
if (border) setStroke(dp(1), BORDER)
|
||||
}
|
||||
|
||||
fun show() {
|
||||
if (shown) return
|
||||
if (!Settings.canDrawOverlays(context)) return
|
||||
if (isShown || !Settings.canDrawOverlays(context)) return
|
||||
compact = true
|
||||
val view = buildRoot()
|
||||
val p = createParams()
|
||||
val layout = WindowManager.LayoutParams(
|
||||
dp(COMPACT_WIDTH), WindowManager.LayoutParams.WRAP_CONTENT,
|
||||
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
|
||||
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
|
||||
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
|
||||
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
|
||||
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
|
||||
PixelFormat.TRANSLUCENT,
|
||||
).apply {
|
||||
gravity = Gravity.TOP or Gravity.LEFT
|
||||
// 坐标使用完整屏幕,边界与系统栏由 screenBounds 统一处理。
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) setFitInsetsTypes(0)
|
||||
title = "LPT 学习悬浮窗"
|
||||
}
|
||||
root = view
|
||||
params = p
|
||||
runCatching { wm.addView(view, p) }.onFailure {
|
||||
params = layout
|
||||
applyMode()
|
||||
position(view, layout)
|
||||
try {
|
||||
wm.addView(view, layout)
|
||||
} catch (_: RuntimeException) {
|
||||
root = null
|
||||
params = null
|
||||
return
|
||||
}
|
||||
shown = true
|
||||
scheduleAutoHide()
|
||||
}
|
||||
|
||||
/** 彻底移除(仅在会话结束/服务停止时调用) */
|
||||
fun hide() {
|
||||
if (!shown) return
|
||||
cancelAutoHide()
|
||||
root?.let { runCatching { wm.removeView(it) } }
|
||||
val view = root ?: return
|
||||
view.removeCallbacks(collapseTask)
|
||||
view.animate().cancel()
|
||||
runCatching { wm.removeView(view) }
|
||||
root = null
|
||||
params = null
|
||||
shown = false
|
||||
dragging = false
|
||||
}
|
||||
|
||||
/** 恢复/重建浮窗(App 内「显示悬浮窗」入口) */
|
||||
fun restore() {
|
||||
if (!shown) {
|
||||
show()
|
||||
return
|
||||
}
|
||||
if (halfHidden) setHalfHidden(false)
|
||||
scheduleAutoHide()
|
||||
setCompact(false)
|
||||
}
|
||||
|
||||
fun render(state: SessionController.State) {
|
||||
lastState = state
|
||||
if (!shown) return
|
||||
if (!isShown) return
|
||||
val ongoing = state.status == SessionController.Status.ONGOING
|
||||
val text = formatDuration(state.effectiveSeconds())
|
||||
|
||||
timeView.text = text
|
||||
compactTime.text = text
|
||||
dotView.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4)
|
||||
compactDot.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4)
|
||||
val remaining = state.remainingMs()
|
||||
val due = remaining == 0L
|
||||
val accent = if (due || !ongoing) AMBER else MINT
|
||||
val duration = formatCountdown(remaining)
|
||||
timeView.text = duration
|
||||
compactTime.text = if (dockRight) "‹" else "›"
|
||||
compactTime.setTextColor(accent)
|
||||
compactDot.background = background(accent, 4)
|
||||
statusView.text = when {
|
||||
state.writing -> "正在同步…"
|
||||
state.syncError != null -> "同步失败 · 请打开 App"
|
||||
due -> "时间到 · 请注意休息"
|
||||
remaining == null -> "倒计时待同步"
|
||||
ongoing -> "本轮剩余时间"
|
||||
else -> "倒计时已暂停"
|
||||
}
|
||||
statusView.setTextColor(accent)
|
||||
toggleView.text = if (ongoing) "暂停" else "继续"
|
||||
toggleView.background = rounded(if (ongoing) COLOR_ACTION else COLOR_RESUME, 10)
|
||||
|
||||
barRow.visibility = if (halfHidden) View.GONE else View.VISIBLE
|
||||
compactRow.visibility = if (halfHidden) View.VISIBLE else View.GONE
|
||||
toggleView.contentDescription = if (ongoing) "暂停学习" else "继续学习"
|
||||
toggleView.isEnabled = !state.writing && state.hasSession
|
||||
fragmentView.isEnabled = !state.writing && state.hasSession
|
||||
toggleView.alpha = if (toggleView.isEnabled) 1f else 0.45f
|
||||
fragmentView.alpha = if (fragmentView.isEnabled) 1f else 0.45f
|
||||
capsule.contentDescription = "${if (due) "时间到" else if (ongoing) "学习倒计时" else "已暂停"},$duration,侧边收纳,点按展开,拖动调整位置"
|
||||
}
|
||||
|
||||
// ---- 半隐藏 / 自动隐藏 ----
|
||||
|
||||
fun setHalfHidden(hidden: Boolean) {
|
||||
/** 横竖屏、屏幕尺寸变化后仍保持贴边,按相对高度重新定位。 */
|
||||
fun reposition() {
|
||||
val view = root ?: return
|
||||
val p = params ?: return
|
||||
halfHidden = hidden
|
||||
// 常态整条 80% 不透明;收起后再压一档,整体约 60%
|
||||
view.alpha = if (hidden) 0.75f else 1f
|
||||
lastState?.let { render(it) }
|
||||
|
||||
val screenWidth = context.resources.displayMetrics.widthPixels
|
||||
// 等布局完成拿到新宽度后再贴边
|
||||
view.post {
|
||||
val width = view.width.takeIf { it > 0 } ?: dp(220)
|
||||
if (hidden) {
|
||||
val toRight = (p.x + width / 2) > screenWidth / 2
|
||||
// 收向最近的屏幕边缘,只留约七成在屏幕内
|
||||
p.x = if (toRight) screenWidth - (width * 0.7).toInt() else -(width * 0.3).toInt()
|
||||
} else {
|
||||
p.x = (screenWidth - width - dp(12)).coerceIn(dp(0), (screenWidth - width).coerceAtLeast(0))
|
||||
scheduleAutoHide()
|
||||
}
|
||||
runCatching { wm.updateViewLayout(view, p) }
|
||||
}
|
||||
val layout = params ?: return
|
||||
position(view, layout)
|
||||
updateLayout()
|
||||
}
|
||||
|
||||
private fun scheduleAutoHide() {
|
||||
root?.removeCallbacks(autoHideTask)
|
||||
if (!halfHidden) root?.postDelayed(autoHideTask, AUTO_HIDE_DELAY_MS)
|
||||
private fun setCompact(value: Boolean) {
|
||||
val view = root ?: return
|
||||
compact = value
|
||||
applyMode()
|
||||
reposition()
|
||||
view.animate().cancel()
|
||||
view.alpha = 1f
|
||||
scheduleCollapse()
|
||||
}
|
||||
|
||||
private fun cancelAutoHide() {
|
||||
root?.removeCallbacks(autoHideTask)
|
||||
private fun applyMode() {
|
||||
val view = root ?: return
|
||||
panel.visibility = if (compact) View.GONE else View.VISIBLE
|
||||
capsule.visibility = if (compact) View.VISIBLE else View.GONE
|
||||
view.background = background(SURFACE, if (compact) 24 else 22, border = true)
|
||||
params?.width = dp(if (compact) COMPACT_WIDTH else PANEL_WIDTH)
|
||||
// 收入屏幕一半,只在屏内露出 24dp 的把手;计时在展开后完整显示。
|
||||
capsule.setPadding(if (dockRight) 0 else dp(EDGE_HIDDEN_WIDTH), 0,
|
||||
if (dockRight) dp(EDGE_HIDDEN_WIDTH) else 0, 0)
|
||||
lastState?.let(::render)
|
||||
}
|
||||
|
||||
private fun baseFlags(): Int =
|
||||
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
|
||||
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
|
||||
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
|
||||
private fun scheduleCollapse() {
|
||||
root?.removeCallbacks(collapseTask)
|
||||
if (!compact) root?.postDelayed(collapseTask, AUTO_COLLAPSE_MS)
|
||||
}
|
||||
|
||||
private fun label(size: Float, color: Int) = TextView(context).apply {
|
||||
textSize = size
|
||||
setTextColor(color)
|
||||
includeFontPadding = false
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
maxLines = 1
|
||||
}
|
||||
|
||||
/** 两个动作同权重:浮窗不设主操作,强调只留给倒计时(见 design-principles「浮窗」行)。 */
|
||||
private fun action(text: String) = label(14f, TEXT).apply {
|
||||
this.text = text
|
||||
gravity = Gravity.CENTER
|
||||
typeface = Typeface.DEFAULT_BOLD
|
||||
// mask 与背景同为圆角形状,按下水波纹才会被 14dp 圆角裁切,不溢到面板上。
|
||||
background = RippleDrawable(
|
||||
ColorStateList.valueOf(0x3367E8C4),
|
||||
background(BUTTON, 14, border = true),
|
||||
background(BUTTON, 14, border = true),
|
||||
)
|
||||
isClickable = true
|
||||
isFocusable = false
|
||||
layoutParams = LinearLayout.LayoutParams(0, dp(48), 1f)
|
||||
}
|
||||
|
||||
private fun buildRoot(): LinearLayout {
|
||||
val container = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
background = rounded(COLOR_BG, 16)
|
||||
setPadding(dp(12), dp(10), dp(12), dp(10))
|
||||
elevation = dp(10).toFloat()
|
||||
elevation = dp(6).toFloat()
|
||||
}
|
||||
|
||||
// ---- 常态条:● 计时 + 暂停/继续 ----
|
||||
barRow = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
}
|
||||
dotView = View(context).apply {
|
||||
background = rounded(COLOR_ONGOING, 4)
|
||||
layoutParams = LinearLayout.LayoutParams(dp(8), dp(8))
|
||||
}
|
||||
timeView = TextView(context).apply {
|
||||
setTextColor(Color.WHITE)
|
||||
textSize = 17f
|
||||
typeface = Typeface.MONOSPACE
|
||||
maxLines = 1
|
||||
ellipsize = TextUtils.TruncateAt.END
|
||||
setPadding(dp(8), 0, dp(10), 0)
|
||||
}
|
||||
fragmentView = pill("+", COLOR_NEUTRAL).apply {
|
||||
contentDescription = "记一条知识碎片"
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
).apply { marginEnd = dp(6) }
|
||||
}
|
||||
toggleView = pill("暂停", COLOR_ACTION)
|
||||
|
||||
barRow.addView(dotView)
|
||||
barRow.addView(timeView)
|
||||
barRow.addView(fragmentView)
|
||||
barRow.addView(toggleView)
|
||||
container.addView(barRow)
|
||||
|
||||
// ---- 半隐藏小胶囊:● 计时 ----
|
||||
compactRow = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
visibility = View.GONE
|
||||
setPadding(dp(4), dp(2), dp(4), dp(2))
|
||||
capsule = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
gravity = Gravity.CENTER
|
||||
minimumHeight = dp(56)
|
||||
isClickable = true
|
||||
}
|
||||
compactDot = View(context).apply {
|
||||
background = rounded(COLOR_ONGOING, 4)
|
||||
layoutParams = LinearLayout.LayoutParams(dp(8), dp(8))
|
||||
background = background(MINT, 4)
|
||||
layoutParams = LinearLayout.LayoutParams(dp(4), dp(4))
|
||||
}
|
||||
compactTime = TextView(context).apply {
|
||||
setTextColor(Color.WHITE)
|
||||
textSize = 15f
|
||||
typeface = Typeface.MONOSPACE
|
||||
setPadding(dp(6), 0, dp(4), 0)
|
||||
compactTime = label(22f, MINT).apply {
|
||||
gravity = Gravity.CENTER
|
||||
text = "‹"
|
||||
}
|
||||
compactRow.addView(compactDot)
|
||||
compactRow.addView(compactTime)
|
||||
compactRow.setOnClickListener { setHalfHidden(false) }
|
||||
container.addView(compactRow)
|
||||
capsule.addView(compactDot)
|
||||
capsule.addView(compactTime)
|
||||
capsule.setOnClickListener { setCompact(false) }
|
||||
// 侧边把手的拖动不能被系统「返回」手势抢走;只排除把手自身的小区域。
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
capsule.addOnLayoutChangeListener { view, _, _, _, _, _, _, _, _ ->
|
||||
view.systemGestureExclusionRects = listOf(Rect(0, 0, view.width, view.height))
|
||||
}
|
||||
}
|
||||
attachDrag(capsule)
|
||||
container.addView(capsule)
|
||||
|
||||
fragmentView.setOnClickListener {
|
||||
scheduleAutoHide()
|
||||
// 输入弹窗要占屏幕,先把浮窗收成小胶囊,避免遮挡
|
||||
setHalfHidden(true)
|
||||
panel = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setPadding(dp(12), dp(12), dp(12), dp(12))
|
||||
}
|
||||
val handle = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setPadding(dp(4), dp(4), dp(4), dp(12))
|
||||
isClickable = true
|
||||
contentDescription = "学习计时,点按收起,拖动调整位置"
|
||||
}
|
||||
val heading = LinearLayout(context).apply { gravity = Gravity.CENTER_VERTICAL }
|
||||
statusView = label(12f, MINT).apply { text = "专注学习中" }
|
||||
heading.addView(statusView, LinearLayout.LayoutParams(0, dp(24), 1f))
|
||||
timeView = label(30f, TEXT).apply {
|
||||
text = "00:00"
|
||||
typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
|
||||
setPadding(0, dp(2), 0, 0)
|
||||
}
|
||||
handle.addView(heading)
|
||||
handle.addView(timeView)
|
||||
handle.setOnClickListener { setCompact(true) }
|
||||
attachDrag(handle)
|
||||
panel.addView(handle)
|
||||
val actions = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL }
|
||||
fragmentView = action("记碎片").apply {
|
||||
contentDescription = "记一条知识碎片"
|
||||
setOnClickListener {
|
||||
setCompact(true)
|
||||
onRequestFragmentInput?.invoke()
|
||||
}
|
||||
toggleView.setOnClickListener {
|
||||
scheduleAutoHide()
|
||||
}
|
||||
toggleView = action("暂停").apply {
|
||||
setOnClickListener {
|
||||
scheduleCollapse()
|
||||
onTogglePause?.invoke()
|
||||
}
|
||||
|
||||
attachDrag(barRow)
|
||||
}
|
||||
actions.addView(fragmentView)
|
||||
actions.addView(View(context), LinearLayout.LayoutParams(dp(8), 1))
|
||||
actions.addView(toggleView)
|
||||
panel.addView(actions)
|
||||
container.addView(panel)
|
||||
return container
|
||||
}
|
||||
|
||||
/** 拖动移动;未移动的单击 = 切换半隐藏/恢复 */
|
||||
private fun attachDrag(handle: View) {
|
||||
var startX = 0
|
||||
var startY = 0
|
||||
var downRawX = 0f
|
||||
var downRawY = 0f
|
||||
var moved = false
|
||||
handle.setOnTouchListener { _, event ->
|
||||
val p = params ?: return@setOnTouchListener false
|
||||
when (event.action) {
|
||||
var downX = 0f
|
||||
var downY = 0f
|
||||
val slop = ViewConfiguration.get(context).scaledTouchSlop
|
||||
handle.setOnTouchListener { touched, event ->
|
||||
val layout = params ?: return@setOnTouchListener false
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
startX = p.x
|
||||
startY = p.y
|
||||
downRawX = event.rawX
|
||||
downRawY = event.rawY
|
||||
moved = false
|
||||
cancelAutoHide()
|
||||
startX = layout.x
|
||||
startY = layout.y
|
||||
downX = event.rawX
|
||||
downY = event.rawY
|
||||
dragging = false
|
||||
root?.removeCallbacks(collapseTask)
|
||||
true
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val dx = (event.rawX - downRawX).toInt()
|
||||
val dy = (event.rawY - downRawY).toInt()
|
||||
if (abs(dx) > dp(4) || abs(dy) > dp(4)) {
|
||||
moved = true
|
||||
val view = root
|
||||
val width = view?.width ?: dp(200)
|
||||
val height = view?.height ?: dp(60)
|
||||
val screenWidth = context.resources.displayMetrics.widthPixels
|
||||
val screenHeight = context.resources.displayMetrics.heightPixels
|
||||
p.x = (startX + dx).coerceIn(dp(0), (screenWidth - width).coerceAtLeast(dp(0)))
|
||||
p.y = (startY + dy).coerceIn(dp(0), (screenHeight - height).coerceAtLeast(dp(0)))
|
||||
view?.let { runCatching { wm.updateViewLayout(it, p) } }
|
||||
val dx = (event.rawX - downX).toInt()
|
||||
val dy = (event.rawY - downY).toInt()
|
||||
if (dragging || abs(dx) > slop || abs(dy) > slop) {
|
||||
dragging = true
|
||||
val bounds = screenBounds()
|
||||
layout.x = (startX + dx).coerceIn(bounds.left, (bounds.right - layout.width).coerceAtLeast(bounds.left))
|
||||
val maxY = (bounds.bottom - (root?.height ?: dp(48))).coerceAtLeast(bounds.top)
|
||||
layout.y = (startY + dy).coerceIn(bounds.top, maxY)
|
||||
updateLayout()
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
if (moved) {
|
||||
scheduleAutoHide()
|
||||
} else {
|
||||
setHalfHidden(!halfHidden)
|
||||
MotionEvent.ACTION_UP -> {
|
||||
if (dragging) savePosition() else touched.performClick()
|
||||
dragging = false
|
||||
scheduleCollapse()
|
||||
true
|
||||
}
|
||||
MotionEvent.ACTION_CANCEL -> {
|
||||
// 系统取消手势不应被当作点击展开/收起。
|
||||
if (dragging) savePosition()
|
||||
dragging = false
|
||||
scheduleCollapse()
|
||||
true
|
||||
}
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createParams(): WindowManager.LayoutParams {
|
||||
val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
WindowManager.LayoutParams.TYPE_PHONE
|
||||
private fun savePosition() {
|
||||
val layout = params ?: return
|
||||
val bounds = screenBounds()
|
||||
dockRight = layout.x + layout.width / 2 > bounds.centerX()
|
||||
val available = (bounds.height() - (root?.height ?: dp(48))).coerceAtLeast(1)
|
||||
verticalFraction = ((layout.y - bounds.top).toFloat() / available).coerceIn(0f, 1f)
|
||||
preferences.edit().putBoolean("dock_right", dockRight)
|
||||
.putFloat("vertical_fraction", verticalFraction).apply()
|
||||
applyMode()
|
||||
reposition()
|
||||
}
|
||||
return WindowManager.LayoutParams(
|
||||
WindowManager.LayoutParams.WRAP_CONTENT,
|
||||
WindowManager.LayoutParams.WRAP_CONTENT,
|
||||
type,
|
||||
baseFlags(),
|
||||
PixelFormat.TRANSLUCENT,
|
||||
).apply {
|
||||
gravity = Gravity.TOP or Gravity.START
|
||||
x = dp(12)
|
||||
y = dp(160)
|
||||
|
||||
private fun position(view: View, layout: WindowManager.LayoutParams) {
|
||||
val bounds = screenBounds()
|
||||
layout.width = dp(if (compact) COMPACT_WIDTH else PANEL_WIDTH).coerceAtMost(bounds.width())
|
||||
view.measure(View.MeasureSpec.makeMeasureSpec(layout.width, View.MeasureSpec.EXACTLY),
|
||||
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
|
||||
val hidden = if (compact) dp(EDGE_HIDDEN_WIDTH) else 0
|
||||
layout.x = if (dockRight) bounds.right - layout.width + hidden else bounds.left - hidden
|
||||
layout.y = bounds.top + ((bounds.height() - view.measuredHeight).coerceAtLeast(0) * verticalFraction).toInt()
|
||||
}
|
||||
|
||||
private fun updateLayout() {
|
||||
val view = root ?: return
|
||||
val layout = params ?: return
|
||||
runCatching { wm.updateViewLayout(view, layout) }
|
||||
}
|
||||
|
||||
private fun screenBounds(): Rect {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
val metrics = wm.currentWindowMetrics
|
||||
val insets = metrics.windowInsets.getInsetsIgnoringVisibility(
|
||||
WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout(),
|
||||
)
|
||||
val edgeMargin = if (compact) 0 else dp(6)
|
||||
return Rect(insets.left + edgeMargin, insets.top + dp(8),
|
||||
metrics.bounds.width() - insets.right - edgeMargin, metrics.bounds.height() - insets.bottom - dp(8))
|
||||
}
|
||||
val metrics = context.resources.displayMetrics
|
||||
val edgeMargin = if (compact) 0 else dp(6)
|
||||
return Rect(edgeMargin, dp(32), metrics.widthPixels - edgeMargin, metrics.heightPixels - dp(48))
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val AUTO_HIDE_DELAY_MS = 12_000L
|
||||
|
||||
private const val COLOR_BG = 0xCC1B1F27.toInt()
|
||||
private const val COLOR_ONGOING = 0xFF34D399.toInt()
|
||||
private const val COLOR_PAUSED = 0xFFF59E0B.toInt()
|
||||
private const val COLOR_ACTION = 0xFF1F6FEB.toInt()
|
||||
private const val COLOR_RESUME = 0xFF238636.toInt()
|
||||
private const val COLOR_NEUTRAL = 0xFF30363D.toInt()
|
||||
private const val COMPACT_WIDTH = 48
|
||||
private const val EDGE_HIDDEN_WIDTH = 24
|
||||
private const val PANEL_WIDTH = 224
|
||||
private const val AUTO_COLLAPSE_MS = 8_000L
|
||||
private const val SURFACE = 0xF51A242B.toInt()
|
||||
private const val BUTTON = 0xFF2B3941.toInt()
|
||||
private const val BORDER = 0xFF40515A.toInt()
|
||||
private const val TEXT = 0xFFF1F7F5.toInt()
|
||||
private const val SECONDARY = 0xFFADBDBF.toInt()
|
||||
private const val MINT = 0xFF80E6C1.toInt()
|
||||
private const val AMBER = 0xFFFFD08A.toInt()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,11 @@ import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import android.os.IBinder
|
||||
import android.provider.Settings
|
||||
import androidx.core.app.NotificationCompat
|
||||
@@ -16,6 +18,7 @@ import androidx.core.app.ServiceCompat
|
||||
import com.catshark.lpt.MainActivity
|
||||
import com.catshark.lpt.R
|
||||
import com.catshark.lpt.session.SessionController
|
||||
import com.catshark.lpt.util.formatCountdown
|
||||
import com.catshark.lpt.util.formatDuration
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -33,6 +36,8 @@ class StudySessionService : Service() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private lateinit var overlay: OverlayView
|
||||
private lateinit var controller: SessionController
|
||||
private val alertPreferences by lazy { getSharedPreferences("countdown_alert", MODE_PRIVATE) }
|
||||
private var lastAlertKey: String? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
@@ -43,6 +48,7 @@ class StudySessionService : Service() {
|
||||
onRequestFragmentInput = { openFragmentInput() }
|
||||
}
|
||||
createChannel()
|
||||
lastAlertKey = alertPreferences.getString("last_key", null)
|
||||
|
||||
// 状态变化:更新通知 / 悬浮窗。
|
||||
// 只有「已经与服务端对过账且确实没有会话」才能停服务——进程被系统拉起时
|
||||
@@ -51,7 +57,10 @@ class StudySessionService : Service() {
|
||||
controller.state.collect { state ->
|
||||
if (!state.hasSession) {
|
||||
overlay.hide()
|
||||
if (state.resolved) stopSelf()
|
||||
if (state.resolved) {
|
||||
getSystemService(NotificationManager::class.java).cancel(ALERT_NOTIFICATION_ID)
|
||||
stopSelf()
|
||||
}
|
||||
return@collect
|
||||
}
|
||||
ensureForeground(state)
|
||||
@@ -74,6 +83,7 @@ class StudySessionService : Service() {
|
||||
}
|
||||
overlay.render(state)
|
||||
notify(buildNotification(state))
|
||||
checkCountdown(state)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,6 +104,11 @@ class StudySessionService : Service() {
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
overlay.reposition()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
overlay.hide()
|
||||
scope.coroutineContext[kotlinx.coroutines.Job]?.cancel()
|
||||
@@ -147,6 +162,28 @@ class StudySessionService : Service() {
|
||||
manager.notify(NOTIFICATION_ID, notification)
|
||||
}
|
||||
|
||||
private fun checkCountdown(state: SessionController.State) {
|
||||
val key = countdownAlertKey(state, SystemClock.elapsedRealtime(), lastAlertKey) ?: return
|
||||
lastAlertKey = key
|
||||
alertPreferences.edit().putString("last_key", key).apply()
|
||||
// 即使系统通知被静音或禁止,仍展示可见的浮窗提示,不抢焦点。
|
||||
overlay.restore()
|
||||
overlay.render(state)
|
||||
val notification = NotificationCompat.Builder(this, ALERT_CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle("本轮学习时间到")
|
||||
.setContentText("${state.taskName ?: "学习会话"}:请暂停休息,会话不会自动结束")
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setCategory(NotificationCompat.CATEGORY_REMINDER)
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(PendingIntent.getActivity(this, 3,
|
||||
Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT))
|
||||
.addAction(0, "暂停", servicePendingIntent(ACTION_PAUSE, 1))
|
||||
.build()
|
||||
runCatching { getSystemService(NotificationManager::class.java).notify(ALERT_NOTIFICATION_ID, notification) }
|
||||
}
|
||||
|
||||
private fun buildNotification(state: SessionController.State): Notification {
|
||||
val ongoing = state.status == SessionController.Status.ONGOING
|
||||
val toggleLabel = if (ongoing) "暂停" else "继续"
|
||||
@@ -164,7 +201,7 @@ class StudySessionService : Service() {
|
||||
return NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(state.taskName ?: "学习会话")
|
||||
.setContentText("${if (ongoing) "进行中" else "已暂停"} · 有效 ${formatDuration(state.effectiveSeconds())}")
|
||||
.setContentText("${if (state.remainingMs() == 0L) "时间到" else if (ongoing) "倒计时" else "已暂停"} ${formatCountdown(state.remainingMs())} · 有效 ${formatDuration(state.effectiveSeconds())}")
|
||||
.setContentIntent(contentIntent)
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
@@ -204,6 +241,12 @@ class StudySessionService : Service() {
|
||||
|
||||
private fun createChannel() {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
val alertChannel = NotificationChannel(ALERT_CHANNEL_ID, "学习到时提醒", NotificationManager.IMPORTANCE_HIGH).apply {
|
||||
description = "倒计时结束时提醒一次;声音和振动遵循系统设置"
|
||||
enableVibration(true)
|
||||
setShowBadge(true)
|
||||
}
|
||||
manager.createNotificationChannel(alertChannel)
|
||||
if (manager.getNotificationChannel(CHANNEL_ID) != null) return
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
@@ -219,6 +262,8 @@ class StudySessionService : Service() {
|
||||
companion object {
|
||||
const val CHANNEL_ID = "study_session"
|
||||
const val NOTIFICATION_ID = 1001
|
||||
const val ALERT_CHANNEL_ID = "study_countdown_alert"
|
||||
const val ALERT_NOTIFICATION_ID = 1002
|
||||
|
||||
const val ACTION_PAUSE = "com.catshark.lpt.action.PAUSE"
|
||||
const val ACTION_RESUME = "com.catshark.lpt.action.RESUME"
|
||||
|
||||
@@ -6,6 +6,9 @@ import com.catshark.lpt.data.LptRepository
|
||||
import com.catshark.lpt.data.ReportSections
|
||||
import com.catshark.lpt.data.SessionDetail
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancelChildren
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
@@ -22,12 +25,15 @@ import java.time.LocalDateTime
|
||||
* 不使用 tick 累加,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时以服务端时间戳重新对锚。
|
||||
*
|
||||
* 会话-05:开始任务前先看别的任务上有没有未结束会话,有就进 [State.conflict],
|
||||
* 由 UI 给出「前往继续 / 结束它并开始新任务 / 放弃它」三个出口。
|
||||
* 由 UI 给出「前往继续 / 取消」两个出口。
|
||||
*/
|
||||
class SessionController(
|
||||
private val repo: LptRepository,
|
||||
private val scope: CoroutineScope,
|
||||
scope: CoroutineScope,
|
||||
private val realtimeMs: () -> Long = { SystemClock.elapsedRealtime() },
|
||||
) {
|
||||
private val scope = CoroutineScope(scope.coroutineContext + SupervisorJob(scope.coroutineContext[Job]))
|
||||
private var draftJob: Job? = null
|
||||
|
||||
enum class Status { NONE, ONGOING, PAUSED, ENDED }
|
||||
|
||||
@@ -49,6 +55,9 @@ class SessionController(
|
||||
val status: Status = Status.NONE,
|
||||
val baseEffectiveSeconds: Double = 0.0,
|
||||
val anchorRealtimeMs: Long = 0L,
|
||||
val countdownBaseMs: Long? = null,
|
||||
/** 同一次运行分段在对账、进程恢复后保持相同标识,用于去重提醒。 */
|
||||
val countdownKey: String? = null,
|
||||
val expectation: String = "",
|
||||
/** 学习预期是否已经从服务端取回过(没取回前不要弹必填弹窗) */
|
||||
val expectationLoaded: Boolean = false,
|
||||
@@ -60,7 +69,10 @@ class SessionController(
|
||||
val busy: Boolean = false,
|
||||
/** 是否已经与服务端对过账:前台服务据此判断「真没有会话」还是「还不知道」 */
|
||||
val resolved: Boolean = false,
|
||||
val reconciling: Boolean = false,
|
||||
val syncError: String? = null,
|
||||
val error: String? = null,
|
||||
val endError: String? = null,
|
||||
val notice: String? = null,
|
||||
val conflict: Conflict? = null,
|
||||
val conflictBusy: Boolean = false,
|
||||
@@ -71,6 +83,9 @@ class SessionController(
|
||||
val draftSeconds: Int = 0,
|
||||
val draftError: String? = null,
|
||||
) {
|
||||
val writing: Boolean
|
||||
get() = busy || expectationSaving || fragmentAdding || conflictBusy || reconciling
|
||||
|
||||
val hasSession: Boolean
|
||||
get() = status == Status.ONGOING || status == Status.PAUSED
|
||||
|
||||
@@ -78,9 +93,14 @@ class SessionController(
|
||||
val expectationRequired: Boolean
|
||||
get() = hasSession && expectationLoaded && expectation.isBlank()
|
||||
|
||||
fun remainingMs(nowMs: Long = SystemClock.elapsedRealtime()): Long? = countdownBaseMs?.let {
|
||||
val elapsed = if (status == Status.ONGOING) (nowMs - anchorRealtimeMs).coerceAtLeast(0) else 0L
|
||||
(it - elapsed).coerceAtLeast(0)
|
||||
}
|
||||
|
||||
fun effectiveSeconds(nowMs: Long = SystemClock.elapsedRealtime()): Double =
|
||||
if (status == Status.ONGOING) {
|
||||
baseEffectiveSeconds + (nowMs - anchorRealtimeMs) / 1000.0
|
||||
baseEffectiveSeconds + (nowMs - anchorRealtimeMs).coerceAtLeast(0) / 1000.0
|
||||
} else {
|
||||
baseEffectiveSeconds
|
||||
}
|
||||
@@ -95,7 +115,9 @@ class SessionController(
|
||||
|
||||
fun consumeNotice() = _state.update { it.copy(notice = null) }
|
||||
|
||||
fun dismissConflict() = _state.update { it.copy(conflict = null, conflictError = null) }
|
||||
fun dismissConflict() {
|
||||
if (!_state.value.conflictBusy) _state.update { it.copy(conflict = null, conflictError = null) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始或恢复某任务的学习会话;成功后回调(UI 用它拉起前台服务)。
|
||||
@@ -103,7 +125,7 @@ class SessionController(
|
||||
* 先查其他任务上有没有未结束会话:有则只更新 [State.conflict],不开始新会话。
|
||||
*/
|
||||
fun startOrContinue(taskNum: String, onSuccess: () -> Unit = {}) {
|
||||
if (_state.value.busy) return
|
||||
if (_state.value.writing) return
|
||||
_state.update { it.copy(busy = true, error = null, conflict = null, conflictError = null) }
|
||||
scope.launch {
|
||||
val active = repo.activeSession(excludeTaskNum = taskNum)
|
||||
@@ -125,8 +147,8 @@ class SessionController(
|
||||
return@launch
|
||||
}
|
||||
if (active.isFailure) {
|
||||
// 查不到不等于没有:提示一句再照常开始,不把用户堵在列表页
|
||||
_state.update { it.copy(notice = "未能确认是否存在未结束会话,已按没有冲突处理") }
|
||||
_state.update { it.copy(busy = false, error = "无法确认未结束会话:${active.exceptionOrNull()?.message ?: "请稍后重试"}") }
|
||||
return@launch
|
||||
}
|
||||
startTask(taskNum, onSuccess)
|
||||
}
|
||||
@@ -138,7 +160,7 @@ class SessionController(
|
||||
*/
|
||||
fun continueConflict(onSessionReady: () -> Unit = {}) {
|
||||
val conflict = _state.value.conflict ?: return
|
||||
if (_state.value.conflictBusy) return
|
||||
if (_state.value.writing) return
|
||||
_state.update { it.copy(conflictBusy = true, conflictError = null) }
|
||||
scope.launch {
|
||||
repo.sessionDetail(conflict.sessionNum)
|
||||
@@ -149,10 +171,10 @@ class SessionController(
|
||||
taskNum = conflict.taskNum,
|
||||
taskName = conflict.taskName ?: it.taskName,
|
||||
conflict = null,
|
||||
conflictBusy = false,
|
||||
)
|
||||
}
|
||||
loadAuxiliary(conflict.sessionNum)
|
||||
_state.update { it.copy(conflictBusy = false) }
|
||||
onSessionReady()
|
||||
}
|
||||
.onFailure { failConflict(it) }
|
||||
@@ -161,11 +183,14 @@ class SessionController(
|
||||
|
||||
fun pause() {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (_state.value.busy) return
|
||||
if (_state.value.writing || _state.value.status != Status.ONGOING) return
|
||||
_state.update { it.copy(busy = true) }
|
||||
scope.launch {
|
||||
repo.pauseSession(num)
|
||||
.onSuccess { refreshDetail(num) }
|
||||
.onSuccess {
|
||||
_state.update { it.copy(notice = "学习已暂停") }
|
||||
refreshDetail(num)
|
||||
}
|
||||
.onFailure { e -> _state.update { it.copy(error = e.message ?: "暂停失败") } }
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
@@ -173,11 +198,14 @@ class SessionController(
|
||||
|
||||
fun resume() {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (_state.value.busy) return
|
||||
if (_state.value.writing || _state.value.status != Status.PAUSED) return
|
||||
_state.update { it.copy(busy = true) }
|
||||
scope.launch {
|
||||
repo.continueSession(num)
|
||||
.onSuccess { refreshDetail(num) }
|
||||
.onSuccess {
|
||||
_state.update { it.copy(notice = "已继续学习") }
|
||||
refreshDetail(num)
|
||||
}
|
||||
.onFailure { e -> _state.update { it.copy(error = e.message ?: "继续失败") } }
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
@@ -187,11 +215,19 @@ class SessionController(
|
||||
* 保存学习预期。在途时再点直接返回,并在成功时回调;失败文案走 State.error(由页面弹提示)。
|
||||
*/
|
||||
fun saveExpectation(text: String, onResult: (String?) -> Unit = {}) {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (_state.value.expectationSaving) return
|
||||
val num = _state.value.sessionNum
|
||||
if (num == null || !_state.value.hasSession) {
|
||||
onResult("当前没有可保存预期的学习会话")
|
||||
return
|
||||
}
|
||||
if (_state.value.writing) {
|
||||
onResult("正在同步会话,请稍后重试")
|
||||
return
|
||||
}
|
||||
val value = text.trim()
|
||||
if (value.isBlank()) {
|
||||
_state.update { it.copy(error = "学习预期不可为空") }
|
||||
onResult("学习预期不可为空")
|
||||
return
|
||||
}
|
||||
_state.update { it.copy(expectationSaving = true) }
|
||||
@@ -217,17 +253,28 @@ class SessionController(
|
||||
* onResult 给 null 表示已写入,UI 可以据此清空输入框(失败时保留输入)。
|
||||
*/
|
||||
fun addFragment(content: String, onResult: (String?) -> Unit = {}) {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
val num = _state.value.sessionNum
|
||||
if (num == null || !_state.value.hasSession) {
|
||||
onResult("当前没有可记录碎片的学习会话")
|
||||
return
|
||||
}
|
||||
val value = content.trim()
|
||||
if (value.isBlank()) return
|
||||
if (_state.value.fragmentAdding) return
|
||||
if (value.isBlank()) {
|
||||
onResult("碎片内容不能为空")
|
||||
return
|
||||
}
|
||||
if (_state.value.writing) {
|
||||
onResult("正在同步会话,请稍后重试")
|
||||
return
|
||||
}
|
||||
_state.update { it.copy(fragmentAdding = true) }
|
||||
scope.launch {
|
||||
repo.createFragment(num, value)
|
||||
.onSuccess {
|
||||
repo.fragments(num).onSuccess { list ->
|
||||
_state.update { it.copy(fragments = list, notice = "已记录一条碎片") }
|
||||
}
|
||||
_state.update { it.copy(notice = "已记碎片") }
|
||||
repo.fragments(num)
|
||||
.onSuccess { list -> _state.update { it.copy(fragments = list) } }
|
||||
.onFailure { e -> _state.update { it.copy(syncError = "碎片列表刷新失败:${e.message}", error = "碎片已保存,但列表刷新失败:${e.message}") } }
|
||||
onResult(null)
|
||||
}
|
||||
.onFailure { e ->
|
||||
@@ -241,23 +288,23 @@ class SessionController(
|
||||
|
||||
fun end(sections: ReportSections, onDone: () -> Unit = {}) {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (_state.value.busy) return
|
||||
_state.update { it.copy(busy = true) }
|
||||
if (_state.value.writing || !_state.value.hasSession) return
|
||||
_state.update { it.copy(busy = true, endError = null) }
|
||||
scope.launch {
|
||||
repo.endSession(num, sections)
|
||||
.onSuccess { message ->
|
||||
_state.value = idle(notice = message ?: "学习会话已结束")
|
||||
_state.value = idle(notice = message ?: "已结束学习")
|
||||
onDone()
|
||||
}
|
||||
.onFailure { e ->
|
||||
_state.update { it.copy(busy = false, error = e.message ?: "结束学习会话失败") }
|
||||
_state.update { it.copy(busy = false, endError = e.message ?: "结束学习会话失败", error = e.message ?: "结束学习会话失败") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun abort(confirmation: String, onDone: () -> Unit = {}) {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (_state.value.busy) return
|
||||
if (_state.value.writing || !_state.value.hasSession) return
|
||||
_state.update { it.copy(busy = true) }
|
||||
scope.launch {
|
||||
repo.abortSession(num, confirmation)
|
||||
@@ -277,14 +324,14 @@ class SessionController(
|
||||
*/
|
||||
fun generateReportDraft() {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (_state.value.draftLoading) return
|
||||
if (_state.value.draftLoading || _state.value.writing || !_state.value.hasSession) return
|
||||
if (_state.value.fragments.isEmpty()) {
|
||||
_state.update { it.copy(draftError = "这次学习还没有知识碎片,暂无可聚合的内容") }
|
||||
return
|
||||
}
|
||||
_state.update { it.copy(draftLoading = true, draftSeconds = 0, draftError = null) }
|
||||
scope.launch {
|
||||
val ticker = scope.launch {
|
||||
draftJob = scope.launch {
|
||||
val ticker = launch {
|
||||
while (_state.value.draftLoading) {
|
||||
delay(1_000)
|
||||
_state.update { it.copy(draftSeconds = it.draftSeconds + 1) }
|
||||
@@ -312,33 +359,32 @@ class SessionController(
|
||||
|
||||
/** App 启动/登录后与服务端对账:把未结束的会话恢复出来 */
|
||||
fun reconcile() {
|
||||
if (reconciling) return
|
||||
if (reconciling || _state.value.writing) return
|
||||
reconciling = true
|
||||
_state.update { it.copy(reconciling = true, syncError = null) }
|
||||
scope.launch {
|
||||
try {
|
||||
repo.activeSession()
|
||||
.onSuccess { active ->
|
||||
if (active == null || active.sessionNum.isBlank()) {
|
||||
_state.update { it.copy(status = if (it.hasSession) it.status else Status.NONE) }
|
||||
return@onSuccess
|
||||
val active = repo.activeSession().getOrThrow()
|
||||
if (active == null) {
|
||||
_state.value = idle()
|
||||
return@launch
|
||||
}
|
||||
// 详情接口的 taskName 为 null,先用 active 里的任务信息兜底
|
||||
val detail = repo.sessionDetail(active.sessionNum).getOrThrow()
|
||||
applyDetail(detail)
|
||||
_state.update {
|
||||
it.copy(
|
||||
sessionNum = active.sessionNum,
|
||||
taskNum = active.taskNum.ifBlank { it.taskNum },
|
||||
taskName = active.taskName ?: it.taskName,
|
||||
)
|
||||
}
|
||||
refreshDetail(active.sessionNum)
|
||||
loadAuxiliary(active.sessionNum)
|
||||
}
|
||||
.onFailure { e ->
|
||||
_state.update { it.copy(error = e.message ?: "恢复会话状态失败") }
|
||||
}
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(resolved = false, syncError = e.message ?: "恢复会话状态失败", error = e.message ?: "恢复会话状态失败") }
|
||||
} finally {
|
||||
reconciling = false
|
||||
_state.update { it.copy(resolved = true) }
|
||||
_state.update { it.copy(reconciling = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -351,7 +397,11 @@ class SessionController(
|
||||
/** 未登录时没有会话可查,直接标记为已知状态,避免服务一直等 */
|
||||
fun markResolved() = _state.update { it.copy(resolved = true) }
|
||||
|
||||
fun clear() = _state.update { State(resolved = true) }
|
||||
fun clear() {
|
||||
scope.coroutineContext.cancelChildren()
|
||||
reconciling = false
|
||||
_state.value = State(resolved = true)
|
||||
}
|
||||
|
||||
// ---- 内部 ----
|
||||
|
||||
@@ -359,18 +409,27 @@ class SessionController(
|
||||
private suspend fun startTask(taskNum: String, onSessionReady: () -> Unit, note: String? = null) {
|
||||
repo.startOrContinue(taskNum)
|
||||
.onSuccess { detail ->
|
||||
applyDetail(detail)
|
||||
// 开始接口的 pointer 已扣时,详情接口才是本段基准,不能直接复用。
|
||||
val authoritative = repo.sessionDetail(detail.sessionNum)
|
||||
if (authoritative.isFailure) {
|
||||
applyDetail(detail.copy(pointerPosition = null))
|
||||
_state.update { it.copy(busy = false, syncError = "倒计时校准失败,请重新同步", error = "会话已开始,但倒计时校准失败,请重新同步") }
|
||||
onSessionReady()
|
||||
return@onSuccess
|
||||
}
|
||||
val current = authoritative.getOrThrow()
|
||||
applyDetail(current.copy(taskName = current.taskName ?: detail.taskName, taskNum = current.taskNum ?: detail.taskNum))
|
||||
_state.update {
|
||||
it.copy(
|
||||
busy = false,
|
||||
conflict = null,
|
||||
conflictBusy = false,
|
||||
conflictError = null,
|
||||
expectationLoaded = false,
|
||||
notice = note ?: it.notice,
|
||||
notice = note ?: it.notice ?: "已进入学习会话",
|
||||
)
|
||||
}
|
||||
loadAuxiliary(detail.sessionNum)
|
||||
_state.update { it.copy(busy = false) }
|
||||
onSessionReady()
|
||||
}
|
||||
.onFailure { e ->
|
||||
@@ -391,19 +450,24 @@ class SessionController(
|
||||
}
|
||||
}
|
||||
|
||||
private fun idle(notice: String? = null) = State(notice = notice, resolved = true)
|
||||
private fun idle(notice: String? = null): State {
|
||||
draftJob?.cancel()
|
||||
return State(notice = notice, resolved = true)
|
||||
}
|
||||
|
||||
private suspend fun refreshDetail(sessionNum: String) {
|
||||
repo.sessionDetail(sessionNum).onSuccess { applyDetail(it) }
|
||||
repo.sessionDetail(sessionNum)
|
||||
.onSuccess { applyDetail(it) }
|
||||
.onFailure { e -> _state.update { it.copy(resolved = false, syncError = e.message, error = "会话状态同步失败:${e.message}") } }
|
||||
}
|
||||
|
||||
private suspend fun loadAuxiliary(sessionNum: String) {
|
||||
repo.getExpectation(sessionNum).onSuccess { text ->
|
||||
_state.update { it.copy(expectation = text, expectationLoaded = true) }
|
||||
}
|
||||
repo.fragments(sessionNum).onSuccess { list ->
|
||||
_state.update { it.copy(fragments = list) }
|
||||
}
|
||||
repo.getExpectation(sessionNum)
|
||||
.onSuccess { text -> _state.update { it.copy(expectation = text, expectationLoaded = true) } }
|
||||
.onFailure { e -> _state.update { it.copy(syncError = "学习预期加载失败:${e.message}", error = "学习预期加载失败:${e.message}") } }
|
||||
repo.fragments(sessionNum)
|
||||
.onSuccess { list -> _state.update { it.copy(fragments = list) } }
|
||||
.onFailure { e -> _state.update { it.copy(syncError = "碎片加载失败:${e.message}", error = "碎片加载失败:${e.message}") } }
|
||||
}
|
||||
|
||||
private fun applyDetail(detail: SessionDetail) {
|
||||
@@ -414,32 +478,41 @@ class SessionController(
|
||||
else -> Status.NONE
|
||||
}
|
||||
val anchor = if (status == Status.ONGOING) {
|
||||
SystemClock.elapsedRealtime() - secondsSince(detail.lastStartTime) * 1000L
|
||||
realtimeMs() - millisSince(detail.lastStartTime)
|
||||
} else {
|
||||
SystemClock.elapsedRealtime()
|
||||
realtimeMs()
|
||||
}
|
||||
// 会话-04:被服务端自动收敛过的会话,把服务端文案原样告诉用户
|
||||
val converged = detail.systemMessage?.takeIf { it.isNotBlank() }
|
||||
?: if (detail.autoConverged) "上一次学习疑似忘记结束,已自动截止,本次只计入一个番茄钟的有效学习时间" else null
|
||||
val previous = _state.value
|
||||
if (previous.sessionNum != detail.sessionNum) {
|
||||
draftJob?.cancel()
|
||||
_state.value = State(busy = previous.busy, conflictBusy = previous.conflictBusy, reconciling = previous.reconciling)
|
||||
}
|
||||
_state.update {
|
||||
it.copy(
|
||||
resolved = true,
|
||||
syncError = null,
|
||||
sessionNum = detail.sessionNum.ifBlank { it.sessionNum },
|
||||
taskNum = detail.taskNum ?: it.taskNum,
|
||||
taskName = detail.taskName ?: it.taskName,
|
||||
status = status,
|
||||
baseEffectiveSeconds = detail.effectiveTime,
|
||||
anchorRealtimeMs = anchor,
|
||||
countdownBaseMs = detail.pointerPosition?.takeIf { value -> value.isFinite() }?.toLong()?.coerceAtLeast(0),
|
||||
countdownKey = detail.lastStartTime?.let { start -> "${detail.sessionNum}|$start" },
|
||||
error = null,
|
||||
notice = converged ?: it.notice,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun secondsSince(iso: String?): Long {
|
||||
private fun millisSince(iso: String?): Long {
|
||||
if (iso.isNullOrBlank()) return 0
|
||||
return runCatching {
|
||||
val start = LocalDateTime.parse(iso)
|
||||
Duration.between(start, LocalDateTime.now()).seconds.coerceAtLeast(0)
|
||||
Duration.between(start, LocalDateTime.now()).toMillis().coerceAtLeast(0)
|
||||
}.getOrDefault(0)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,53 +3,39 @@ package com.catshark.lpt.ui
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.core.view.WindowCompat
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.catshark.lpt.LptApp
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
import com.catshark.lpt.ui.theme.LptTheme
|
||||
|
||||
/**
|
||||
* 从悬浮窗拉起的一条碎片输入弹窗。
|
||||
*
|
||||
* 之所以不复用悬浮窗内输入:App 不在前台时,系统不允许后台窗口弹软键盘
|
||||
* (实测浮窗的 EditText 能拿到输入连接,但 IME 窗口 mViewVisibility=GONE)。
|
||||
* 带 SYSTEM_ALERT_WINDOW 的 App 有后台启动 Activity 的豁免,所以这里用 Activity 输入。
|
||||
*/
|
||||
/** 透明 Activity 承载输入,键盘只影响本页,不在系统浮窗内请求焦点。 */
|
||||
class FragmentInputActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
WindowCompat.setDecorFitsSystemWindows(window, false)
|
||||
setContent {
|
||||
LptTheme {
|
||||
val controller = (application as LptApp).container.session
|
||||
val state by controller.state.collectAsStateWithLifecycle()
|
||||
FragmentInputDialog(
|
||||
sessionNum = (application as LptApp).container.session.state.value.sessionNum,
|
||||
onSubmit = { text, onResult ->
|
||||
(application as LptApp).container.session.addFragment(text, onResult)
|
||||
},
|
||||
sessionNum = state.sessionNum.takeIf { state.hasSession },
|
||||
busy = state.writing,
|
||||
onSubmit = controller::addFragment,
|
||||
onDismiss = { finish() },
|
||||
)
|
||||
}
|
||||
@@ -60,76 +46,78 @@ class FragmentInputActivity : ComponentActivity() {
|
||||
@Composable
|
||||
private fun FragmentInputDialog(
|
||||
sessionNum: String?,
|
||||
busy: Boolean,
|
||||
onSubmit: (String, (String?) -> Unit) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var text by remember { mutableStateOf("") }
|
||||
// 提交期间禁用按钮:这里多发一次就是两条重复碎片
|
||||
var text by rememberSaveable { mutableStateOf("") }
|
||||
var submitting by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
val context = LocalContext.current
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
|
||||
LaunchedEffect(Unit) { focusRequester.requestFocus() }
|
||||
LaunchedEffect(Unit) {
|
||||
focusRequester.requestFocus()
|
||||
keyboard?.show()
|
||||
}
|
||||
|
||||
// 高度由 IME 实际可用空间决定,横屏不再使用固定高度的 floating Dialog。
|
||||
BoxWithConstraints(
|
||||
Modifier.fillMaxSize().safeDrawingPadding().imePadding().padding(8.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
val compactHeight = maxHeight < 240.dp
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(20.dp),
|
||||
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth().heightIn(max = maxHeight),
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = 6.dp,
|
||||
shadowElevation = 12.dp,
|
||||
) {
|
||||
Column(modifier = Modifier.padding(18.dp)) {
|
||||
Text("记一条知识碎片", style = MaterialTheme.typography.titleMedium)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Column(Modifier.padding(horizontal = Dimens.Group, vertical = if (compactHeight) Dimens.Compact else Dimens.Group)) {
|
||||
// 横屏把操作放在顶栏,永远不让保存/取消掉到键盘下面。
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("记一条知识碎片", style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f))
|
||||
TextButton(onClick = onDismiss, enabled = !submitting) { Text("取消") }
|
||||
Button(
|
||||
onClick = {
|
||||
if (submitting || busy) return@Button
|
||||
submitting = true
|
||||
error = null
|
||||
onSubmit(text.trim()) { message ->
|
||||
submitting = false
|
||||
if (message == null) onDismiss() else error = message
|
||||
}
|
||||
},
|
||||
enabled = !submitting && !busy && text.isNotBlank() && sessionNum != null,
|
||||
) { Text(if (submitting) "记碎片…" else "记碎片") }
|
||||
}
|
||||
if (!compactHeight) {
|
||||
Text(
|
||||
sessionNum?.let { "归属会话:$it" } ?: "当前没有进行中的会话",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
// 使用内部滚动的编辑框;空间紧张时只需容纳一行,光标行仍可见。
|
||||
OutlinedTextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
label = { Text("这条碎片记了什么?") },
|
||||
minLines = 2,
|
||||
maxLines = 4,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
enabled = !submitting,
|
||||
label = { Text("记下这次学到的") },
|
||||
placeholder = { Text("例:PagedAttention 把 KV cache 按页切") },
|
||||
minLines = if (compactHeight) 1 else 3,
|
||||
maxLines = if (compactHeight) 2 else 6,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.Sentences,
|
||||
imeAction = ImeAction.Default,
|
||||
),
|
||||
isError = error != null,
|
||||
modifier = Modifier.fillMaxWidth().weight(1f, fill = false).focusRequester(focusRequester),
|
||||
)
|
||||
Spacer(Modifier.height(14.dp))
|
||||
if (error != null) {
|
||||
Text(error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = onDismiss, enabled = !submitting) { Text("取消") }
|
||||
Spacer(Modifier.height(0.dp))
|
||||
Button(
|
||||
onClick = {
|
||||
if (submitting) return@Button
|
||||
submitting = true
|
||||
error = null
|
||||
// 写入成功才关弹窗;失败保留输入并提示,避免碎片静默丢失
|
||||
onSubmit(text.trim()) { message ->
|
||||
if (message == null) {
|
||||
onDismiss()
|
||||
} else {
|
||||
submitting = false
|
||||
error = message
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = !submitting && text.isNotBlank() && sessionNum != null,
|
||||
modifier = Modifier.padding(start = 8.dp),
|
||||
) { Text(if (submitting) "保存中…" else "保存") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,10 @@ import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
@@ -22,11 +24,11 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
|
||||
@Composable
|
||||
fun LoginScreen(
|
||||
@@ -45,17 +47,12 @@ fun LoginScreen(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(24.dp),
|
||||
// 登录页的 24dp 水平边距是 design-system.md 已登记的主视觉例外
|
||||
.padding(horizontal = Dimens.Block, vertical = Dimens.Block),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text("LPT 学习", style = MaterialTheme.typography.headlineMedium)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"移动端学习会话 · 悬浮窗计时",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Spacer(Modifier.height(Dimens.Group))
|
||||
|
||||
if (notice != null) {
|
||||
// 一直留到下次登录成功:否则用户回到登录页时已经看不到原因了
|
||||
@@ -64,7 +61,7 @@ fun LoginScreen(
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
@@ -74,7 +71,7 @@ fun LoginScreen(
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Spacer(Modifier.height(Dimens.Section))
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
@@ -85,25 +82,16 @@ fun LoginScreen(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
if (showAdvanced) {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
OutlinedTextField(
|
||||
value = baseUrl,
|
||||
onValueChange = { baseUrl = it },
|
||||
label = { Text("API 地址") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
TextButton(onClick = { showAdvanced = true }) { Text("高级:修改 API 地址") }
|
||||
}
|
||||
|
||||
if (error != null) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
Text(
|
||||
error!!,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Spacer(Modifier.height(Dimens.Group))
|
||||
Button(
|
||||
onClick = {
|
||||
if (loading) return@Button
|
||||
@@ -115,7 +103,9 @@ fun LoginScreen(
|
||||
}
|
||||
},
|
||||
enabled = !loading && username.isNotBlank() && password.isNotBlank(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 48.dp),
|
||||
) {
|
||||
if (loading) {
|
||||
CircularProgressIndicator(
|
||||
@@ -123,23 +113,25 @@ fun LoginScreen(
|
||||
strokeWidth = 2.dp,
|
||||
color = MaterialTheme.colorScheme.onPrimary,
|
||||
)
|
||||
Spacer(Modifier.width(Dimens.Inner))
|
||||
}
|
||||
Text(if (loading) "登录中…" else "登录")
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
if (showAdvanced) {
|
||||
OutlinedTextField(
|
||||
value = baseUrl,
|
||||
onValueChange = { baseUrl = it },
|
||||
label = { Text("API 地址") },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
Text("登录")
|
||||
TextButton(onClick = { showAdvanced = true }, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("修改 API 地址")
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"提示:dev 环境默认 https://lpt-dev.cat-shark.xyz/api",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"LPT",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,216 +1,53 @@
|
||||
package com.catshark.lpt.ui
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import com.catshark.lpt.ui.components.LptSection
|
||||
import com.catshark.lpt.ui.components.PageHeader
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
|
||||
/**
|
||||
* 首启权限页:只放「三项授权 + MIUI 额外设置」,理由写进每一行,不再有页面级说明段。
|
||||
* 右上「稍后」与底部「已完成,去学习任务」都只是回到任务页——权限随时能在设置页补。
|
||||
*/
|
||||
@Composable
|
||||
fun PermissionScreen(onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var refreshKey by remember { mutableIntStateOf(0) }
|
||||
|
||||
// 从系统设置页返回时自动刷新权限状态
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) refreshKey++
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
|
||||
val overlayGranted = remember(refreshKey) { Settings.canDrawOverlays(context) }
|
||||
val batteryIgnored = remember(refreshKey) { isIgnoringBatteryOptimizations(context) }
|
||||
val notificationGranted = remember(refreshKey) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) ==
|
||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
PageHeader(
|
||||
title = "权限与后台",
|
||||
backLabel = "‹ 任务",
|
||||
onBack = onBack,
|
||||
action = { TextButton(onClick = onBack) { Text("稍后") } },
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.weight(1f)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
.padding(horizontal = Dimens.Screen),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Block),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("权限与后台", style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))
|
||||
TextButton(onClick = onBack) { Text("返回") }
|
||||
LptSection {
|
||||
PermissionSection(title = "能不能跨应用计时,取决于这三项")
|
||||
}
|
||||
Text(
|
||||
"悬浮窗是核心功能:没有悬浮窗权限,跨应用计时就不成立。MIUI 还需要额外放行后台。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
PermissionCard(
|
||||
title = "悬浮窗权限(必须)",
|
||||
description = "允许 LPT 在其他应用之上显示学习计时浮窗。",
|
||||
granted = overlayGranted,
|
||||
actionLabel = "去开启",
|
||||
onAction = { openOverlaySettings(context) },
|
||||
)
|
||||
|
||||
PermissionCard(
|
||||
title = "通知权限",
|
||||
description = "前台服务需要一条常驻通知;Android 13+ 需要授权。",
|
||||
granted = notificationGranted,
|
||||
actionLabel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) "去开启" else "无需(本机低于 13)",
|
||||
onAction = { openAppNotificationSettings(context) },
|
||||
)
|
||||
|
||||
PermissionCard(
|
||||
title = "电池优化白名单",
|
||||
description = "避免长时间学习时被系统冻结计时。",
|
||||
granted = batteryIgnored,
|
||||
actionLabel = "去设置",
|
||||
onAction = { requestIgnoreBatteryOptimizations(context) },
|
||||
)
|
||||
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
Text("小米 / MIUI 额外设置", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"MIUI 会限制后台启动与后台弹窗,需要手动放行「自启动」和「其他权限 → 后台弹出界面」,并把省电策略设为「无限制」。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = { openMiuiAutostart(context) }) { Text("自启动管理") }
|
||||
OutlinedButton(onClick = { openAppDetailSettings(context) }) { Text("应用详情") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Button(onClick = onBack, modifier = Modifier.fillMaxWidth()) { Text("完成") }
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PermissionCard(
|
||||
title: String,
|
||||
description: String,
|
||||
granted: Boolean,
|
||||
actionLabel: String,
|
||||
onAction: () -> Unit,
|
||||
) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(title, style = MaterialTheme.typography.titleSmall, modifier = Modifier.weight(1f))
|
||||
Text(
|
||||
if (granted) "已授权" else "未授权",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = if (granted) MaterialTheme.colorScheme.secondary else MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
description,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
if (!granted) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Button(onClick = onAction) { Text(actionLabel) }
|
||||
MiuiSection()
|
||||
}
|
||||
Button(
|
||||
onClick = onBack,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = Dimens.Screen, vertical = Dimens.Group),
|
||||
) {
|
||||
Text("已完成,去学习任务")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun openOverlaySettings(context: Context) {
|
||||
val intent = Intent(
|
||||
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
|
||||
Uri.parse("package:${context.packageName}"),
|
||||
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
.onFailure { runCatching { context.startActivity(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)) } }
|
||||
}
|
||||
|
||||
private fun openAppNotificationSettings(context: Context) {
|
||||
val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
.onFailure { openAppDetailSettings(context) }
|
||||
}
|
||||
|
||||
private fun openAppDetailSettings(context: Context) {
|
||||
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
|
||||
.setData(Uri.parse("package:${context.packageName}"))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
}
|
||||
|
||||
private fun requestIgnoreBatteryOptimizations(context: Context) {
|
||||
val intent = Intent(
|
||||
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
|
||||
Uri.parse("package:${context.packageName}"),
|
||||
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
.onFailure { runCatching { context.startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) } }
|
||||
}
|
||||
|
||||
private fun openMiuiAutostart(context: Context) {
|
||||
val candidates = listOf(
|
||||
ComponentName(
|
||||
"com.miui.securitycenter",
|
||||
"com.miui.permcenter.autostart.AutoStartManagementActivity",
|
||||
),
|
||||
ComponentName(
|
||||
"com.miui.securitycenter",
|
||||
"com.miui.powercenter.PowerSettings",
|
||||
),
|
||||
)
|
||||
for (component in candidates) {
|
||||
val intent = Intent().setComponent(component).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (runCatching { context.startActivity(intent) }.isSuccess) return
|
||||
}
|
||||
openAppDetailSettings(context)
|
||||
}
|
||||
|
||||
private fun isIgnoringBatteryOptimizations(context: Context): Boolean {
|
||||
val powerManager = context.getSystemService(PowerManager::class.java) ?: return false
|
||||
return powerManager.isIgnoringBatteryOptimizations(context.packageName)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
/**
|
||||
* 权限段:设置页与首启权限页共用同一份检测、状态展示与跳转,避免两处各写一套。
|
||||
*/
|
||||
package com.catshark.lpt.ui
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import com.catshark.lpt.ui.components.LptSection
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
|
||||
/**
|
||||
* 三条与跨应用计时相关的授权:悬浮窗、通知、电池优化白名单。
|
||||
* 从系统设置页返回时靠 `ON_RESUME` 重新检测,`title` 由调用方按场景给(设置页写「权限」,首启页写理由)。
|
||||
*/
|
||||
@Composable
|
||||
fun PermissionSection(
|
||||
modifier: Modifier = Modifier,
|
||||
title: String = "权限",
|
||||
showTitle: Boolean = true,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var refreshKey by remember { mutableIntStateOf(0) }
|
||||
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) refreshKey++
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
|
||||
val overlayGranted = remember(refreshKey) { Settings.canDrawOverlays(context) }
|
||||
val notificationGranted = remember(refreshKey) { isNotificationGranted(context) }
|
||||
val batteryIgnored = remember(refreshKey) { isIgnoringBatteryOptimizations(context) }
|
||||
|
||||
Column(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Section),
|
||||
) {
|
||||
if (showTitle) {
|
||||
Text(title, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
PermissionRow(
|
||||
title = "悬浮窗权限",
|
||||
description = "在其他应用之上显示计时浮窗",
|
||||
granted = overlayGranted,
|
||||
onOpen = { openOverlaySettings(context) },
|
||||
)
|
||||
PermissionRow(
|
||||
title = "通知权限",
|
||||
description = "前台服务要有一条常驻通知",
|
||||
granted = notificationGranted,
|
||||
onOpen = { openAppNotificationSettings(context) },
|
||||
)
|
||||
PermissionRow(
|
||||
title = "电池优化白名单",
|
||||
description = "长时间学习时不被系统冻结计时",
|
||||
granted = batteryIgnored,
|
||||
onOpen = { requestIgnoreBatteryOptimizations(context) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 小米 / MIUI 额外设置:低频,默认收起成一行,需要时展开。 */
|
||||
@Composable
|
||||
fun MiuiSection(modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
|
||||
LptSection(modifier = modifier) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"小米 / MIUI 额外设置",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = { expanded = !expanded }) {
|
||||
Text(
|
||||
if (expanded) "收起" else "展开",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (expanded) {
|
||||
Column(
|
||||
modifier = Modifier.padding(top = Dimens.Section),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Section),
|
||||
) {
|
||||
Text(
|
||||
"MIUI 会限制后台启动与后台弹窗:放行「自启动」和「其他权限 → 后台弹出界面」," +
|
||||
"并把省电策略设为「无限制」。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(Dimens.Inner)) {
|
||||
OutlinedButton(onClick = { openMiuiAutostart(context) }) { Text("自启动管理") }
|
||||
OutlinedButton(onClick = { openAppDetailSettings(context) }) { Text("应用详情") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 一行一条权限:左边「是什么 + 为什么」,右边「现在什么状态 + 未授权时怎么开」。 */
|
||||
@Composable
|
||||
private fun PermissionRow(
|
||||
title: String,
|
||||
description: String,
|
||||
granted: Boolean,
|
||||
onOpen: () -> Unit,
|
||||
) {
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Compact),
|
||||
) {
|
||||
Text(title, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
description,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Column(horizontalAlignment = Alignment.End) {
|
||||
Text(
|
||||
if (granted) "已授权" else "未授权",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = if (granted) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.error
|
||||
},
|
||||
)
|
||||
if (!granted) {
|
||||
TextButton(onClick = onOpen) {
|
||||
Text("去开启", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun isNotificationGranted(context: Context): Boolean =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) ==
|
||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
} else {
|
||||
true
|
||||
}
|
||||
|
||||
private fun isIgnoringBatteryOptimizations(context: Context): Boolean {
|
||||
val powerManager = context.getSystemService(PowerManager::class.java) ?: return false
|
||||
return powerManager.isIgnoringBatteryOptimizations(context.packageName)
|
||||
}
|
||||
|
||||
private fun openOverlaySettings(context: Context) {
|
||||
val intent = Intent(
|
||||
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
|
||||
Uri.parse("package:${context.packageName}"),
|
||||
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
.onFailure { runCatching { context.startActivity(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)) } }
|
||||
}
|
||||
|
||||
private fun openAppNotificationSettings(context: Context) {
|
||||
val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
.onFailure { openAppDetailSettings(context) }
|
||||
}
|
||||
|
||||
private fun openAppDetailSettings(context: Context) {
|
||||
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
|
||||
.setData(Uri.parse("package:${context.packageName}"))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
}
|
||||
|
||||
private fun requestIgnoreBatteryOptimizations(context: Context) {
|
||||
val intent = Intent(
|
||||
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
|
||||
Uri.parse("package:${context.packageName}"),
|
||||
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
.onFailure { runCatching { context.startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) } }
|
||||
}
|
||||
|
||||
private fun openMiuiAutostart(context: Context) {
|
||||
val candidates = listOf(
|
||||
ComponentName(
|
||||
"com.miui.securitycenter",
|
||||
"com.miui.permcenter.autostart.AutoStartManagementActivity",
|
||||
),
|
||||
ComponentName(
|
||||
"com.miui.securitycenter",
|
||||
"com.miui.powercenter.PowerSettings",
|
||||
),
|
||||
)
|
||||
for (component in candidates) {
|
||||
val intent = Intent().setComponent(component).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (runCatching { context.startActivity(intent) }.isSuccess) return
|
||||
}
|
||||
openAppDetailSettings(context)
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.catshark.lpt.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -11,9 +10,10 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
@@ -28,15 +28,21 @@ import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.catshark.lpt.data.ReportPage
|
||||
import com.catshark.lpt.data.StudyReport
|
||||
import com.catshark.lpt.ui.components.LptEmptyState
|
||||
import com.catshark.lpt.ui.components.LptInlineError
|
||||
import com.catshark.lpt.ui.components.LptListItem
|
||||
import com.catshark.lpt.ui.components.PageHeader
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
import com.catshark.lpt.util.formatDateTime
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* 某任务的历史学习报告:三段文本 + 该会话的学习预期 + 本次会话的碎片原文。
|
||||
* 某任务的历史学习报告:首屏只给「哪次会话 + 会话摘要」,三段内容与碎片原文按需展开。
|
||||
*
|
||||
* 报告第四部分「按归属分组的碎片」由复习模块实时聚合(review 前缀的端点),
|
||||
* 本客户端按边界不访问它,所以这里只列本次会话产生的碎片。
|
||||
@@ -78,64 +84,65 @@ fun ReportsScreen(
|
||||
}
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = onBack) { Text("‹ 任务") }
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("学习报告", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||
Text(
|
||||
taskName,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
PageHeader(
|
||||
title = "学习报告",
|
||||
subtitle = taskName,
|
||||
backLabel = "‹ 任务",
|
||||
onBack = onBack,
|
||||
action = {
|
||||
if (loading) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
if (loading) CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||
}
|
||||
|
||||
if (error != null) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
error!!,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
val errorMessage = error
|
||||
when {
|
||||
errorMessage != null && reports.isEmpty() -> LptInlineError(
|
||||
title = "学习报告没加载出来",
|
||||
detail = errorMessage,
|
||||
retryLabel = "重新加载",
|
||||
onRetry = { load(if (page == 0) 1 else page) },
|
||||
modifier = Modifier.padding(horizontal = Dimens.Screen, vertical = Dimens.Group),
|
||||
)
|
||||
|
||||
reports.isEmpty() && !loading -> LptEmptyState(
|
||||
title = "这个任务还没有学习报告",
|
||||
modifier = Modifier.weight(1f),
|
||||
actionLabel = "刷新",
|
||||
onAction = { load(1) },
|
||||
)
|
||||
TextButton(onClick = { load(if (page == 0) 1 else page) }) { Text("重试") }
|
||||
}
|
||||
}
|
||||
|
||||
if (reports.isEmpty() && !loading && error == null) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text("这个任务还没有学习报告", style = MaterialTheme.typography.bodyLarge)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(onClick = { load(1) }) { Text("刷新") }
|
||||
}
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
else -> LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
contentPadding = PaddingValues(horizontal = Dimens.Screen, vertical = Dimens.Group),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Group),
|
||||
) {
|
||||
if (errorMessage != null) {
|
||||
item {
|
||||
LptInlineError(
|
||||
title = "后面几页没加载出来",
|
||||
detail = errorMessage,
|
||||
retryLabel = "重新加载",
|
||||
onRetry = { load(page + 1) },
|
||||
)
|
||||
}
|
||||
}
|
||||
items(reports, key = { it.id }) { report ->
|
||||
ReportCard(report = report, onLoadFragments = onLoadFragments)
|
||||
ReportItem(report = report, onLoadFragments = onLoadFragments)
|
||||
}
|
||||
if (reports.size < total) {
|
||||
item {
|
||||
TextButton(onClick = { load(page + 1) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(if (loading) "加载中…" else "加载更多(${reports.size}/$total)")
|
||||
TextButton(
|
||||
onClick = { load(page + 1) },
|
||||
enabled = !loading,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
if (loading) "加载中…" else "加载更多(${reports.size}/$total)",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,63 +151,114 @@ fun ReportsScreen(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ReportCard(
|
||||
private fun ReportItem(
|
||||
report: StudyReport,
|
||||
onLoadFragments: suspend (String) -> Result<List<String>>,
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
var fragments by remember { mutableStateOf<List<String>?>(null) }
|
||||
var fragmentError by remember { mutableStateOf<String?>(null) }
|
||||
var sectionsExpanded by remember(report.id) { mutableStateOf(false) }
|
||||
var fragmentsShown by remember(report.id) { mutableStateOf(false) }
|
||||
var fragments by remember(report.id) { mutableStateOf<List<String>?>(null) }
|
||||
var fragmentError by remember(report.id) { mutableStateOf<String?>(null) }
|
||||
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"学习报告",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
formatDateTime(report.createdTime),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
"会话 ${report.sessionNum}",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
if (!report.sessionExpectation.isNullOrBlank()) {
|
||||
Section("本次预期", report.sessionExpectation)
|
||||
}
|
||||
Section("会话摘要", report.sessionSummary)
|
||||
Section("预期达成判断", report.expectationVerdict)
|
||||
Section("自由总结", report.freeSummary)
|
||||
|
||||
TextButton(
|
||||
onClick = {
|
||||
expanded = !expanded
|
||||
if (expanded && fragments == null && fragmentError == null) {
|
||||
fun loadFragments() {
|
||||
if (fragmentError != null) fragmentError = null
|
||||
scope.launch {
|
||||
onLoadFragments(report.sessionNum)
|
||||
.onSuccess { fragments = it }
|
||||
.onFailure { fragmentError = it.message ?: "加载碎片失败" }
|
||||
}
|
||||
}
|
||||
},
|
||||
) { Text(if (expanded) "收起本次碎片" else "查看本次碎片") }
|
||||
|
||||
if (expanded) {
|
||||
val list = fragments
|
||||
when {
|
||||
fragmentError != null -> Text(
|
||||
fragmentError!!,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
LptListItem {
|
||||
// 会话号是排障用的,学习者扫列表时只会被一串十六进制打断;留着日期就够定位
|
||||
Text(
|
||||
formatDateTime(report.createdTime),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
// 结论先行:第一句取「预期达成判断」,没写判断就退到会话摘要、再退到本次预期;
|
||||
// 三者都空才说「没有文字记录」——否则会一边说没记录一边还挂着「展开全文」
|
||||
val verdict = report.expectationVerdict?.takeIf { it.isNotBlank() }
|
||||
val summaryLead = report.sessionSummary?.takeIf { it.isNotBlank() }
|
||||
val expectationLead = report.sessionExpectation?.takeIf { it.isNotBlank() }
|
||||
val lead = verdict ?: summaryLead ?: expectationLead
|
||||
// 首行可能是判断、摘要或预期:不标出是哪一种,扫列表时「部分达成…」和「review state」看着一样
|
||||
val leadLabel = when {
|
||||
verdict != null -> "预期达成判断"
|
||||
summaryLead != null -> "会话摘要"
|
||||
expectationLead != null -> "本次预期"
|
||||
else -> null
|
||||
}
|
||||
if (leadLabel != null) {
|
||||
Text(
|
||||
leadLabel,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
lead ?: "这次会话没有留下文字记录",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (lead != null) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = if (sectionsExpanded) Int.MAX_VALUE else 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
|
||||
if (sectionsExpanded) {
|
||||
// 首行已经贴过的那段不再重贴一遍
|
||||
ReportSection("本次预期", expectationLead.takeIf { it != lead })
|
||||
ReportSection("会话摘要", summaryLead.takeIf { it != lead })
|
||||
ReportSection("自由总结", report.freeSummary)
|
||||
}
|
||||
|
||||
val hasMore = listOf(
|
||||
report.sessionExpectation,
|
||||
report.sessionSummary,
|
||||
report.freeSummary,
|
||||
).any { !it.isNullOrBlank() }
|
||||
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
if (hasMore) {
|
||||
TextButton(
|
||||
onClick = { sectionsExpanded = !sectionsExpanded },
|
||||
colors = ButtonDefaults.textButtonColors(
|
||||
contentColor = MaterialTheme.colorScheme.primary,
|
||||
),
|
||||
) {
|
||||
Text(
|
||||
if (sectionsExpanded) "收起全文" else "展开全文",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
TextButton(
|
||||
onClick = {
|
||||
fragmentsShown = !fragmentsShown
|
||||
if (fragmentsShown && fragments == null && fragmentError == null) loadFragments()
|
||||
},
|
||||
colors = ButtonDefaults.textButtonColors(
|
||||
contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
) {
|
||||
Text(
|
||||
if (fragmentsShown) "收起本次碎片" else "查看本次碎片",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (fragmentsShown) {
|
||||
val list = fragments
|
||||
val failure = fragmentError
|
||||
when {
|
||||
failure != null -> LptInlineError(
|
||||
title = "碎片没加载出来",
|
||||
detail = failure,
|
||||
retryLabel = "重新加载",
|
||||
onRetry = { loadFragments() },
|
||||
)
|
||||
|
||||
list == null -> Text(
|
||||
@@ -216,35 +274,36 @@ private fun ReportCard(
|
||||
)
|
||||
|
||||
else -> list.forEachIndexed { index, content ->
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"${index + 1}.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.width(Dimens.Compact))
|
||||
Text(
|
||||
content,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(start = 6.dp),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 三段报告正文:标签 bodySmall 退后,正文 bodyMedium 在前,空值写「(未填写)」 */
|
||||
@Composable
|
||||
private fun Section(label: String, value: String?) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
private fun ReportSection(label: String, value: String?) {
|
||||
Spacer(Modifier.height(Dimens.Section))
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Spacer(Modifier.height(Dimens.Compact))
|
||||
if (value.isNullOrBlank()) {
|
||||
Text(
|
||||
"(未填写)",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.catshark.lpt.ui
|
||||
|
||||
import android.os.SystemClock
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -8,17 +9,20 @@ import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -27,20 +31,33 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.catshark.lpt.data.ReportSections
|
||||
import com.catshark.lpt.session.SessionController
|
||||
import com.catshark.lpt.ui.components.LptInlineError
|
||||
import com.catshark.lpt.ui.components.LptSection
|
||||
import com.catshark.lpt.ui.components.PageHeader
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
import com.catshark.lpt.util.formatCountdown
|
||||
import com.catshark.lpt.util.formatDuration
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
private val MISOPERATION_PHRASE = SessionController.MISOPERATION_PHRASE
|
||||
|
||||
/** 知识碎片默认只露最近几条,其余靠「查看全部」展开(不做嵌套滚动) */
|
||||
private const val FRAGMENT_PREVIEW_COUNT = 3
|
||||
|
||||
@Composable
|
||||
fun SessionScreen(
|
||||
state: SessionController.State,
|
||||
@@ -53,6 +70,7 @@ fun SessionScreen(
|
||||
onAddFragment: (String, (String?) -> Unit) -> Unit,
|
||||
onShowOverlay: () -> Unit,
|
||||
onGenerateDraft: () -> Unit,
|
||||
onRetrySync: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
var nowMs by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }
|
||||
@@ -63,14 +81,19 @@ fun SessionScreen(
|
||||
}
|
||||
}
|
||||
val seconds = state.effectiveSeconds(nowMs)
|
||||
val remainingMs = state.remainingMs(nowMs)
|
||||
val ongoing = state.status == SessionController.Status.ONGOING
|
||||
val due = remainingMs == 0L
|
||||
|
||||
var expectationDraft by remember { mutableStateOf(state.expectation) }
|
||||
var expectationDraft by rememberSaveable(state.sessionNum) { mutableStateOf(state.expectation) }
|
||||
var expectationEditing by rememberSaveable(state.sessionNum) { mutableStateOf(false) }
|
||||
LaunchedEffect(state.expectation) { expectationDraft = state.expectation }
|
||||
|
||||
var fragmentDraft by remember { mutableStateOf("") }
|
||||
var showEnd by remember { mutableStateOf(false) }
|
||||
var showAbort by remember { mutableStateOf(false) }
|
||||
var fragmentDraft by rememberSaveable(state.sessionNum) { mutableStateOf("") }
|
||||
var allFragmentsShown by rememberSaveable(state.sessionNum) { mutableStateOf(false) }
|
||||
var fragmentBlankHint by rememberSaveable(state.sessionNum) { mutableStateOf(false) }
|
||||
var showEnd by rememberSaveable(state.sessionNum) { mutableStateOf(false) }
|
||||
var showAbort by rememberSaveable(state.sessionNum) { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(openEndDialog) {
|
||||
if (openEndDialog) {
|
||||
@@ -79,103 +102,153 @@ fun SessionScreen(
|
||||
}
|
||||
}
|
||||
|
||||
val controlsEnabled = !state.writing && state.expectationLoaded && state.syncError == null
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
PageHeader(
|
||||
// 任务名逐屏变化,它本身就是这一屏的标题(例外见 design-principles.md)
|
||||
title = state.taskName ?: "学习会话",
|
||||
titleStyle = MaterialTheme.typography.titleMedium,
|
||||
backLabel = "‹ 任务",
|
||||
// 预期还没填时不允许离开:会话必须有预期才能算正式开始
|
||||
TextButton(onClick = onBack, enabled = !state.expectationRequired) { Text("‹ 任务") }
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
state.taskName ?: "学习会话",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Text(
|
||||
state.sessionNum ?: "",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (state.busy) CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||
onBack = if (state.expectationRequired) null else onBack,
|
||||
action = {
|
||||
if (state.busy) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
// 底部多留一条提示条的高度:snackbar 是覆盖层,压住「误操作结束」时点不到
|
||||
.padding(
|
||||
start = Dimens.Screen,
|
||||
end = Dimens.Screen,
|
||||
top = Dimens.Group,
|
||||
bottom = Dimens.Block + Dimens.Block,
|
||||
),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Block),
|
||||
) {
|
||||
if (state.syncError != null) {
|
||||
LptInlineError(
|
||||
title = "和服务器没同步上",
|
||||
detail = state.syncError,
|
||||
retryLabel = "重新同步",
|
||||
onRetry = onRetrySync,
|
||||
)
|
||||
}
|
||||
|
||||
if (due) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.small,
|
||||
color = MaterialTheme.colorScheme.tertiaryContainer,
|
||||
) {
|
||||
// 计时卡片
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(20.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.padding(Dimens.Section),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Compact),
|
||||
) {
|
||||
Text(
|
||||
if (ongoing) "有效学习时间" else "已暂停 · 有效学习时间",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
"本轮时间已到,先暂停休息",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onTertiaryContainer,
|
||||
)
|
||||
Text(
|
||||
"会话不会自己结束",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onTertiaryContainer,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 计时是这一屏的主角:一个数字占最大对比,其余信息退到两侧小字
|
||||
LptSection {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Inner),
|
||||
) {
|
||||
Text(
|
||||
"本轮还剩 ${formatCountdown(remainingMs)}",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = if (due) {
|
||||
MaterialTheme.colorScheme.onTertiaryContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
formatDuration(seconds),
|
||||
fontSize = 44.sp,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = if (ongoing) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
color = if (ongoing) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"状态:${statusLabel(state.status)}",
|
||||
"有效学习时间",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 控制按钮
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Inner),
|
||||
) {
|
||||
Button(
|
||||
onClick = onTogglePause,
|
||||
enabled = !state.busy,
|
||||
modifier = Modifier.weight(1f),
|
||||
enabled = controlsEnabled,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 48.dp),
|
||||
) {
|
||||
Text(if (ongoing) "暂停" else "继续")
|
||||
}
|
||||
Button(
|
||||
OutlinedButton(
|
||||
onClick = { showEnd = true },
|
||||
enabled = !state.busy,
|
||||
modifier = Modifier.weight(1f),
|
||||
enabled = controlsEnabled,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 48.dp),
|
||||
) {
|
||||
Text("结束")
|
||||
Text("结束学习")
|
||||
}
|
||||
TextButton(onClick = onShowOverlay, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("显示悬浮窗")
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = { showAbort = true },
|
||||
enabled = !state.busy && state.fragments.isEmpty(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(if (state.fragments.isEmpty()) "误操作结束(零数据)" else "误操作结束(已产生碎片,不可用)")
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = onShowOverlay,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text("显示 / 恢复悬浮窗")
|
||||
}
|
||||
|
||||
// 学习预期
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
Text("本次学习预期", style = MaterialTheme.typography.titleSmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
LptSection {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"学习预期",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (state.expectation.isNotBlank() && !expectationEditing) {
|
||||
TextButton(onClick = { expectationEditing = true }, enabled = !state.writing) {
|
||||
Text("修改")
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
val expectationText = state.expectation
|
||||
if (expectationText.isNotBlank() && !expectationEditing) {
|
||||
Text(expectationText, style = MaterialTheme.typography.bodyMedium)
|
||||
} else {
|
||||
OutlinedTextField(
|
||||
value = expectationDraft,
|
||||
onValueChange = { expectationDraft = it },
|
||||
@@ -183,72 +256,148 @@ fun SessionScreen(
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
|
||||
if (state.expectationSaving) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||
Spacer(Modifier.height(0.dp))
|
||||
}
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
Button(
|
||||
onClick = { onSaveExpectation(expectationDraft) {} },
|
||||
enabled = !state.expectationSaving && expectationDraft.isNotBlank(),
|
||||
) { Text(if (state.expectationSaving) "保存中…" else "保存预期") }
|
||||
onClick = {
|
||||
onSaveExpectation(expectationDraft) { error ->
|
||||
// 成功才收起输入态;失败保留用户写的内容
|
||||
if (error == null) expectationEditing = false
|
||||
}
|
||||
},
|
||||
enabled = !state.writing && state.expectationLoaded && expectationDraft.isNotBlank(),
|
||||
modifier = Modifier.align(Alignment.End),
|
||||
) {
|
||||
Text(if (state.expectationSaving) "保存中…" else "保存预期")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 碎片
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
Text("知识碎片(${state.fragments.size})", style = MaterialTheme.typography.titleSmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
LptSection {
|
||||
Text(
|
||||
"知识碎片(${state.fragments.size})",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
val fragmentField = @Composable { fieldModifier: Modifier ->
|
||||
OutlinedTextField(
|
||||
value = fragmentDraft,
|
||||
onValueChange = { fragmentDraft = it },
|
||||
label = { Text("记一条…") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.height(0.dp))
|
||||
TextButton(
|
||||
onClick = {
|
||||
// 成功后清空输入;失败保留,避免手写的碎片白丢
|
||||
onAddFragment(fragmentDraft) { error -> if (error == null) fragmentDraft = "" }
|
||||
onValueChange = {
|
||||
fragmentDraft = it
|
||||
if (it.isNotBlank()) fragmentBlankHint = false
|
||||
},
|
||||
enabled = fragmentDraft.isNotBlank() && !state.fragmentAdding,
|
||||
) { Text(if (state.fragmentAdding) "记录中…" else "记录") }
|
||||
label = { Text("记下这次学到的") },
|
||||
placeholder = { Text("例:PagedAttention 把 KV cache 按页切") },
|
||||
singleLine = true,
|
||||
isError = fragmentBlankHint,
|
||||
modifier = fieldModifier,
|
||||
)
|
||||
}
|
||||
state.fragments.forEachIndexed { index, fragment ->
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row {
|
||||
// 常态就可点:空输入点了给一句提示,而不是先做一个死按钮
|
||||
val submitFragment = @Composable { modifier: Modifier ->
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
if (fragmentDraft.isBlank()) {
|
||||
fragmentBlankHint = true
|
||||
return@OutlinedButton
|
||||
}
|
||||
// 成功后清空输入;失败保留,避免手写的碎片白丢
|
||||
val submitted = fragmentDraft
|
||||
onAddFragment(submitted) { error ->
|
||||
if (error == null && fragmentDraft == submitted) fragmentDraft = ""
|
||||
else if (error != null) fragmentBlankHint = false
|
||||
}
|
||||
},
|
||||
enabled = !state.writing && !state.fragmentAdding,
|
||||
modifier = modifier,
|
||||
) {
|
||||
Text(if (state.fragmentAdding) "记碎片…" else "记碎片")
|
||||
}
|
||||
}
|
||||
if (LocalDensity.current.fontScale >= 1.5f) {
|
||||
// 大字体下 label 会被按钮挤成两行,改为上下排:输入占满一行,按钮右对齐
|
||||
fragmentField(Modifier.fillMaxWidth())
|
||||
Spacer(Modifier.height(Dimens.Compact))
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
submitFragment(Modifier)
|
||||
}
|
||||
} else {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
fragmentField(Modifier.weight(1f))
|
||||
Spacer(Modifier.width(Dimens.Inner))
|
||||
submitFragment(Modifier)
|
||||
}
|
||||
}
|
||||
if (fragmentBlankHint) {
|
||||
Text(
|
||||
"${index + 1}.",
|
||||
"先写一条再记",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
val visibleFragments =
|
||||
if (allFragmentsShown) state.fragments else state.fragments.takeLast(FRAGMENT_PREVIEW_COUNT)
|
||||
val firstNumber = state.fragments.size - visibleFragments.size + 1
|
||||
visibleFragments.forEachIndexed { index, fragment ->
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"${firstNumber + index}.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(0.dp))
|
||||
Spacer(Modifier.width(Dimens.Compact))
|
||||
Text(
|
||||
fragment.content,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(start = 6.dp),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (state.fragments.size > FRAGMENT_PREVIEW_COUNT) {
|
||||
TextButton(
|
||||
onClick = { allFragmentsShown = !allFragmentsShown },
|
||||
modifier = Modifier.align(Alignment.CenterHorizontally),
|
||||
) {
|
||||
Text(
|
||||
if (allFragmentsShown) "收起" else "查看全部 ${state.fragments.size} 条",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (state.busy) {
|
||||
Text("正在与服务器同步…", style = MaterialTheme.typography.bodySmall)
|
||||
// 误操作结束是低频动作:页面最底一行文字入口 + 二次确认。
|
||||
// 记过碎片的会话不走这条路(碎片会一起删掉),灰掉的同时把原因写出来
|
||||
val abortBlockedByFragments = state.fragments.isNotEmpty()
|
||||
TextButton(
|
||||
onClick = { showAbort = true },
|
||||
enabled = !state.writing && state.syncError == null && !abortBlockedByFragments,
|
||||
colors = ButtonDefaults.textButtonColors(
|
||||
contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text("误操作结束", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
if (abortBlockedByFragments) {
|
||||
Text(
|
||||
"记过碎片的会话不能按误操作结束,请用「结束学习」",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
|
||||
// 会话必须有预期才能正式开始:未填预期时用不可关闭的弹窗挡住
|
||||
if (state.expectationRequired) {
|
||||
ExpectationGateDialog(
|
||||
busy = state.busy,
|
||||
busy = state.writing,
|
||||
saving = state.expectationSaving,
|
||||
error = state.error,
|
||||
onSave = { text -> onSaveExpectation(text) {} },
|
||||
@@ -259,23 +408,17 @@ fun SessionScreen(
|
||||
if (showEnd) {
|
||||
EndSessionDialog(
|
||||
state = state,
|
||||
onDismiss = { showEnd = false },
|
||||
onConfirm = { sections ->
|
||||
showEnd = false
|
||||
onEnd(sections)
|
||||
},
|
||||
onDismiss = { if (!state.writing) showEnd = false },
|
||||
onConfirm = onEnd,
|
||||
onGenerateDraft = onGenerateDraft,
|
||||
)
|
||||
}
|
||||
|
||||
if (showAbort) {
|
||||
AbortSessionDialog(
|
||||
busy = state.busy,
|
||||
onDismiss = { showAbort = false },
|
||||
onConfirm = { phrase ->
|
||||
showAbort = false
|
||||
onAbort(phrase)
|
||||
},
|
||||
busy = state.writing,
|
||||
onDismiss = { if (!state.writing) showAbort = false },
|
||||
onConfirm = onAbort,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -307,9 +450,9 @@ private fun ExpectationGateDialog(
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text("请输入确认语:$MISOPERATION_PHRASE", style = MaterialTheme.typography.bodySmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Spacer(Modifier.height(Dimens.Section))
|
||||
MisoperationPhrase(MISOPERATION_PHRASE)
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
OutlinedTextField(
|
||||
value = phrase,
|
||||
onValueChange = { phrase = it },
|
||||
@@ -323,7 +466,7 @@ private fun ExpectationGateDialog(
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Spacer(Modifier.height(Dimens.Section))
|
||||
OutlinedTextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
@@ -332,8 +475,12 @@ private fun ExpectationGateDialog(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
if (error != null) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(error, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
Text(
|
||||
error,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -343,7 +490,7 @@ private fun ExpectationGateDialog(
|
||||
Button(
|
||||
onClick = { onAbort(phrase) },
|
||||
enabled = !busy && phrase.trim() == MISOPERATION_PHRASE,
|
||||
) { Text("确认放弃") }
|
||||
) { Text("放弃这次会话") }
|
||||
} else {
|
||||
Button(
|
||||
onClick = { onSave(text) },
|
||||
@@ -372,9 +519,11 @@ private fun EndSessionDialog(
|
||||
onConfirm: (ReportSections) -> Unit,
|
||||
onGenerateDraft: () -> Unit,
|
||||
) {
|
||||
var summary by remember { mutableStateOf("") }
|
||||
var verdict by remember { mutableStateOf("") }
|
||||
var free by remember { mutableStateOf("") }
|
||||
var summary by rememberSaveable(state.sessionNum) { mutableStateOf("") }
|
||||
var verdict by rememberSaveable(state.sessionNum) { mutableStateOf("") }
|
||||
var free by rememberSaveable(state.sessionNum) { mutableStateOf("") }
|
||||
var edited by rememberSaveable(state.sessionNum) { mutableStateOf(false) }
|
||||
var draftAvailable by remember { mutableStateOf(false) }
|
||||
var confirmRegenerate by remember { mutableStateOf(false) }
|
||||
val hasFragments = state.fragments.isNotEmpty()
|
||||
|
||||
@@ -384,12 +533,20 @@ private fun EndSessionDialog(
|
||||
// 已经有缓存草稿时直接用它,不要为了重开弹窗再化一次 AI
|
||||
if (currentSections().allBlank && hasFragments && state.draft == null) onGenerateDraft()
|
||||
}
|
||||
// 草稿是整段覆盖的:它就是这次生成的编辑起点
|
||||
LaunchedEffect(state.draft) {
|
||||
fun applyDraft() {
|
||||
state.draft?.let {
|
||||
summary = it.sessionSummary
|
||||
verdict = it.expectationVerdict
|
||||
free = it.freeSummary
|
||||
edited = false
|
||||
draftAvailable = false
|
||||
}
|
||||
}
|
||||
|
||||
// 用户开始手写后,迟到的草稿必须由用户选择采用。
|
||||
LaunchedEffect(state.draft) {
|
||||
if (state.draft != null) {
|
||||
if (edited) draftAvailable = true else applyDraft()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -403,51 +560,73 @@ private fun EndSessionDialog(
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
if (state.draftLoading) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||
state.endError?.let {
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
Text(
|
||||
" AI 正在根据 ${state.fragments.size} 条碎片生成草稿,已等待 ${state.draftSeconds} 秒",
|
||||
it,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
if (state.draftLoading) {
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||
Spacer(Modifier.width(Dimens.Inner))
|
||||
Text(
|
||||
"AI 正在根据 ${state.fragments.size} 条碎片生成草稿,已等待 ${state.draftSeconds} 秒",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
state.draftError?.let {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
Text(
|
||||
it,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Spacer(Modifier.height(Dimens.Section))
|
||||
OutlinedTextField(
|
||||
value = summary,
|
||||
onValueChange = { summary = it },
|
||||
onValueChange = { summary = it; edited = true },
|
||||
enabled = !state.writing,
|
||||
label = { Text("会话摘要(这次实际学了什么)") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Spacer(Modifier.height(Dimens.Section))
|
||||
OutlinedTextField(
|
||||
value = verdict,
|
||||
onValueChange = { verdict = it },
|
||||
onValueChange = { verdict = it; edited = true },
|
||||
enabled = !state.writing,
|
||||
label = { Text("预期达成判断") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Spacer(Modifier.height(Dimens.Section))
|
||||
OutlinedTextField(
|
||||
value = free,
|
||||
onValueChange = { free = it },
|
||||
onValueChange = { free = it; edited = true },
|
||||
enabled = !state.writing,
|
||||
label = { Text("自由总结") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
if (draftAvailable) {
|
||||
Text("新草稿已就绪,已保留你的手写内容。", style = MaterialTheme.typography.bodySmall)
|
||||
TextButton(onClick = { confirmRegenerate = true }, enabled = !state.writing) {
|
||||
Text("查看并采用 AI 草稿")
|
||||
}
|
||||
}
|
||||
TextButton(
|
||||
onClick = {
|
||||
// 用户已经写过内容时先确认,避免手滑覆盖
|
||||
if (currentSections().allBlank) onGenerateDraft() else confirmRegenerate = true
|
||||
},
|
||||
enabled = !state.draftLoading && hasFragments,
|
||||
enabled = !state.draftLoading && !state.writing && hasFragments && !draftAvailable,
|
||||
) { Text("AI 重新生成") }
|
||||
}
|
||||
},
|
||||
@@ -455,8 +634,8 @@ private fun EndSessionDialog(
|
||||
Button(
|
||||
onClick = { onConfirm(currentSections()) },
|
||||
// 草稿只是编辑起点:正在生成时也允许直接手写结束
|
||||
enabled = !state.busy,
|
||||
) { Text("确认结束") }
|
||||
enabled = !state.writing,
|
||||
) { Text(if (state.busy) "结束中…" else "结束学习") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
|
||||
)
|
||||
@@ -465,12 +644,22 @@ private fun EndSessionDialog(
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmRegenerate = false },
|
||||
title = { Text("重新生成学习总结") },
|
||||
text = { Text("会用新草稿覆盖当前三段内容(包括你已经编辑的部分),确定继续吗?") },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text("会用草稿覆盖当前三段内容,包括你已经编辑的部分,覆盖后无法恢复。")
|
||||
if (draftAvailable) Text(state.draft?.asLegacyContent().orEmpty())
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Button(onClick = {
|
||||
confirmRegenerate = false
|
||||
if (draftAvailable) {
|
||||
applyDraft()
|
||||
} else {
|
||||
edited = false
|
||||
onGenerateDraft()
|
||||
}) { Text("重新生成") }
|
||||
}
|
||||
}) { Text(if (draftAvailable) "采用草稿" else "重新生成") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { confirmRegenerate = false }) { Text("取消") }
|
||||
@@ -479,6 +668,54 @@ private fun EndSessionDialog(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 误操作结束的确认语:原文放在浅底块里,右侧「复制」直接写进剪贴板,
|
||||
* 用户长按输入框粘贴即可。手打十二个汉字是这条流程最容易出错的一步。
|
||||
*/
|
||||
@Composable
|
||||
private fun MisoperationPhrase(phrase: String) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
var copied by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(copied) {
|
||||
if (copied) {
|
||||
delay(2_000)
|
||||
copied = false
|
||||
}
|
||||
}
|
||||
Text(
|
||||
"输入下面这句话确认",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.border(1.dp, MaterialTheme.colorScheme.outlineVariant, MaterialTheme.shapes.small),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = MaterialTheme.shapes.small,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = Dimens.Section, vertical = Dimens.Inner),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
phrase,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(
|
||||
onClick = {
|
||||
clipboard.setText(AnnotatedString(phrase))
|
||||
copied = true
|
||||
},
|
||||
) {
|
||||
Text(if (copied) "已复制" else "复制", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AbortSessionDialog(
|
||||
busy: Boolean,
|
||||
@@ -496,9 +733,9 @@ private fun AbortSessionDialog(
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text("请输入确认语:$MISOPERATION_PHRASE", style = MaterialTheme.typography.bodySmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Spacer(Modifier.height(Dimens.Section))
|
||||
MisoperationPhrase(MISOPERATION_PHRASE)
|
||||
Spacer(Modifier.height(Dimens.Inner))
|
||||
OutlinedTextField(
|
||||
value = phrase,
|
||||
onValueChange = { phrase = it },
|
||||
@@ -512,15 +749,8 @@ private fun AbortSessionDialog(
|
||||
Button(
|
||||
onClick = { onConfirm(phrase) },
|
||||
enabled = !busy && phrase.trim() == MISOPERATION_PHRASE,
|
||||
) { Text("确认放弃") }
|
||||
) { Text("放弃这次会话") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
private fun statusLabel(status: SessionController.Status): String = when (status) {
|
||||
SessionController.Status.ONGOING -> "进行中"
|
||||
SessionController.Status.PAUSED -> "已暂停"
|
||||
SessionController.Status.ENDED -> "已结束"
|
||||
SessionController.Status.NONE -> "无"
|
||||
}
|
||||
|
||||
@@ -3,11 +3,11 @@ package com.catshark.lpt.ui
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
@@ -20,8 +20,15 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import com.catshark.lpt.ui.components.LptSection
|
||||
import com.catshark.lpt.ui.components.PageHeader
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
|
||||
/**
|
||||
* 设置页:权限段、MIUI 额外设置(默认收起)、服务器地址(点「修改」就地展开)、退出登录。
|
||||
* 任务页顶栏原先的「权限」「退出登录」两个平级入口都收到这里。
|
||||
*/
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
baseUrl: String,
|
||||
@@ -29,21 +36,55 @@ fun SettingsScreen(
|
||||
onLogout: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
var editing by remember { mutableStateOf(false) }
|
||||
var draft by remember { mutableStateOf(baseUrl) }
|
||||
// 保存期间禁用按钮:地址写入是异步的,不加标记会被连点重复提交
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
PageHeader(title = "设置", backLabel = "‹ 任务", onBack = onBack)
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
.weight(1f)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = Dimens.Screen),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Block),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("设置", style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))
|
||||
TextButton(onClick = onBack) { Text("返回") }
|
||||
LptSection {
|
||||
PermissionSection()
|
||||
}
|
||||
|
||||
MiuiSection()
|
||||
|
||||
LptSection {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"服务器地址",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(
|
||||
onClick = {
|
||||
if (!editing) draft = baseUrl
|
||||
editing = !editing
|
||||
},
|
||||
enabled = !saving,
|
||||
) {
|
||||
Text("修改", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
baseUrl,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
modifier = Modifier.padding(top = Dimens.Inner),
|
||||
)
|
||||
if (editing) {
|
||||
Column(
|
||||
modifier = Modifier.padding(top = Dimens.Section),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Section),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = draft,
|
||||
onValueChange = { draft = it },
|
||||
@@ -52,7 +93,7 @@ fun SettingsScreen(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Text(
|
||||
"例如 https://lpt-dev.cat-shark.xyz/api",
|
||||
"换环境时改这里,改完重新登录",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -60,16 +101,30 @@ fun SettingsScreen(
|
||||
onClick = {
|
||||
if (!saving) {
|
||||
saving = true
|
||||
onSave(draft.trim()) { saving = false }
|
||||
// 成功才收起输入框,失败保留输入让用户改
|
||||
onSave(draft.trim()) { error ->
|
||||
saving = false
|
||||
if (error == null) editing = false
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = !saving,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text(if (saving) "保存中…" else "保存") }
|
||||
) {
|
||||
Text(if (saving) "保存中…" else "保存地址")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(onClick = onLogout, modifier = Modifier.fillMaxWidth()) {
|
||||
TextButton(
|
||||
onClick = onLogout,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = Dimens.Group),
|
||||
) {
|
||||
Text("退出登录", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
package com.catshark.lpt.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
@@ -12,24 +13,46 @@ import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.catshark.lpt.data.TaskItem
|
||||
import com.catshark.lpt.ui.components.LptEmptyState
|
||||
import com.catshark.lpt.ui.components.LptInlineError
|
||||
import com.catshark.lpt.ui.components.LptListItem
|
||||
import com.catshark.lpt.ui.components.PageHeader
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
|
||||
/**
|
||||
* 任务页:顶栏只留「设置」,进行中会话独立成块,任务条目整条可点即「开始学习」。
|
||||
* 权限、退出登录都收进设置页,这里不再各放一个平级文字按钮。
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun TaskListScreen(
|
||||
tasks: List<TaskItem>,
|
||||
loading: Boolean,
|
||||
error: String?,
|
||||
username: String?,
|
||||
onRefresh: () -> Unit,
|
||||
onStart: (TaskItem) -> Unit,
|
||||
onOpenReports: (TaskItem) -> Unit,
|
||||
@@ -37,141 +60,320 @@ fun TaskListScreen(
|
||||
starting: Boolean,
|
||||
onOpenSession: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onOpenPermissions: () -> Unit,
|
||||
onLogout: () -> Unit,
|
||||
) {
|
||||
var query by rememberSaveable { mutableStateOf("") }
|
||||
// 点任务先确认再开始:整条可点是给手滑留的坑,一步开会话太容易误触
|
||||
var pendingTask by remember { mutableStateOf<TaskItem?>(null) }
|
||||
var sessionConflict by remember { mutableStateOf(false) }
|
||||
val keyword = query.trim()
|
||||
val visibleTasks = if (keyword.isBlank()) {
|
||||
tasks
|
||||
} else {
|
||||
tasks.filter {
|
||||
it.taskName.contains(keyword, ignoreCase = true) ||
|
||||
it.taskDescription.orEmpty().contains(keyword, ignoreCase = true)
|
||||
}
|
||||
}
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
PageHeader(
|
||||
title = "学习任务",
|
||||
action = { TextButton(onClick = onOpenSettings) { Text("设置") } },
|
||||
)
|
||||
PullToRefreshBox(
|
||||
isRefreshing = loading && tasks.isNotEmpty(),
|
||||
onRefresh = onRefresh,
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("学习任务", style = MaterialTheme.typography.titleLarge)
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(horizontal = Dimens.Screen, vertical = Dimens.Group),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Group),
|
||||
) {
|
||||
if (hasActiveSession) {
|
||||
item(key = "active-session") { ActiveSessionBlock(onOpenSession = onOpenSession) }
|
||||
}
|
||||
// 搜索框只在任务多到一屏扫不完时出现(例外登记在 design-principles.md)
|
||||
if (tasks.size >= SEARCH_THRESHOLD) {
|
||||
item(key = "search") { TaskSearchField(query = query, onQueryChange = { query = it }) }
|
||||
}
|
||||
when {
|
||||
// 加载态:三条骨架,不与空态共用分支
|
||||
loading && tasks.isEmpty() -> items(SKELETON_COUNT) { TaskSkeletonItem() }
|
||||
|
||||
// 失败态:列表本来就是空的,给原因 + 重新加载
|
||||
error != null && tasks.isEmpty() -> item(key = "error") {
|
||||
LptInlineError(
|
||||
title = "任务列表没加载出来",
|
||||
detail = error,
|
||||
retryLabel = "重新加载",
|
||||
onRetry = onRefresh,
|
||||
)
|
||||
}
|
||||
|
||||
// 空态:不是失败,只是还没有任务
|
||||
tasks.isEmpty() -> item(key = "empty") {
|
||||
LptEmptyState(
|
||||
title = "还没有学习任务",
|
||||
modifier = Modifier.fillParentMaxHeight(),
|
||||
hint = "任务在网页端新建,建好后回来刷新",
|
||||
actionLabel = "刷新列表",
|
||||
onAction = onRefresh,
|
||||
)
|
||||
}
|
||||
|
||||
visibleTasks.isEmpty() -> item(key = "no-match") {
|
||||
LptEmptyState(
|
||||
title = "没有匹配的任务",
|
||||
modifier = Modifier.fillParentMaxHeight(),
|
||||
hint = "换个关键词,或清空搜索",
|
||||
actionLabel = "清空搜索",
|
||||
onAction = { query = "" },
|
||||
)
|
||||
}
|
||||
|
||||
else -> {
|
||||
// 有数据但刷新失败:错误条只占一行,不顶掉已有列表
|
||||
if (error != null) {
|
||||
item(key = "stale-error") {
|
||||
LptInlineError(
|
||||
title = "任务列表没能刷新",
|
||||
detail = error,
|
||||
retryLabel = "重新加载",
|
||||
onRetry = onRefresh,
|
||||
)
|
||||
}
|
||||
}
|
||||
items(visibleTasks, key = { it.taskNum }) { task ->
|
||||
TaskRow(
|
||||
task = task,
|
||||
starting = starting,
|
||||
onSelect = {
|
||||
// 已有进行中的会话时不让开新的:一次操作只弹一个框,直接给「回到会话」
|
||||
if (hasActiveSession) sessionConflict = true else pendingTask = task
|
||||
},
|
||||
onOpenReports = { onOpenReports(task) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sessionConflict) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { sessionConflict = false },
|
||||
title = { Text("先结束这次学习") },
|
||||
text = {
|
||||
Text(
|
||||
username?.let { "已登录:$it" } ?: "",
|
||||
"有一次学习正在进行。结束它之后才能开始新的会话。",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
Button(onClick = { sessionConflict = false; onOpenSession() }) { Text("回到会话") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { sessionConflict = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pendingTask?.let { task ->
|
||||
AlertDialog(
|
||||
// 申请进行中不让点外面关掉,避免「点了确认又点外面」这种半开状态
|
||||
onDismissRequest = { if (!starting) pendingTask = null },
|
||||
title = { Text("开始这次学习?") },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(Dimens.Inner)) {
|
||||
Text(task.taskName, style = MaterialTheme.typography.titleSmall)
|
||||
if (!task.taskDescription.isNullOrBlank()) {
|
||||
Text(
|
||||
task.taskDescription,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
TextButton(onClick = onOpenPermissions) { Text("权限") }
|
||||
TextButton(onClick = onOpenSettings) { Text("设置") }
|
||||
Text(
|
||||
"点「开始学习」后进入会话页,悬浮窗开始计时。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = { onStart(task) },
|
||||
enabled = !starting,
|
||||
) {
|
||||
Text(if (starting) "开始中…" else "开始学习")
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { pendingTask = null }, enabled = !starting) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hasActiveSession) {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp)
|
||||
.clickable { onOpenSession() },
|
||||
/** 进行中的会话独立成块:整块可点回会话,不带箭头(箭头与整块可点是重复的两个点击暗示)。 */
|
||||
@Composable
|
||||
private fun ActiveSessionBlock(onOpenSession: () -> Unit) {
|
||||
Surface(
|
||||
onClick = onOpenSession,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
color = MaterialTheme.colorScheme.primaryContainer,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
modifier = Modifier.padding(horizontal = Dimens.Group, vertical = Dimens.Section),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
"有一次学习正在进行",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"回到会话 ›",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
"回到会话",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (error != null) {
|
||||
Row(
|
||||
/**
|
||||
* 紧凑搜索框:40dp 高、`surfaceVariant` 底、无描边。
|
||||
* 放大镜图标需要 `material-icons-core`(本工程没有该依赖),所以只留左侧内边距,
|
||||
* 无障碍名称由 `semantics` 补——`BasicTextField` 的 placeholder 不进无障碍名称。
|
||||
*/
|
||||
@Composable
|
||||
private fun TaskSearchField(query: String, onQueryChange: (String) -> Unit) {
|
||||
// 搜索是列表的附属工具,不做成实心块:只描一条边,视线先落在任务上
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
.height(SEARCH_FIELD_HEIGHT)
|
||||
.border(1.dp, MaterialTheme.colorScheme.outlineVariant, MaterialTheme.shapes.small),
|
||||
) {
|
||||
BasicTextField(
|
||||
value = query,
|
||||
onValueChange = onQueryChange,
|
||||
singleLine = true,
|
||||
textStyle = MaterialTheme.typography.bodyMedium.copy(
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = Dimens.Group)
|
||||
.semantics { contentDescription = "搜索任务名称或描述" },
|
||||
decorationBox = { innerTextField ->
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.CenterStart) {
|
||||
if (query.isEmpty()) {
|
||||
Text(
|
||||
error,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
"搜索任务",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
TextButton(onClick = onRefresh) { Text("重试") }
|
||||
}
|
||||
innerTextField()
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading && tasks.isEmpty()) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
if (tasks.isEmpty() && !loading) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text("还没有学习任务", style = MaterialTheme.typography.bodyLarge)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(onClick = onRefresh) { Text("刷新") }
|
||||
}
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
/** 加载骨架:形状与真实条目同档(`shapes.small`),内三根圆角条用 `outlineVariant`。 */
|
||||
@Composable
|
||||
private fun TaskSkeletonItem() {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth().height(SKELETON_HEIGHT),
|
||||
shape = MaterialTheme.shapes.small,
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
) {
|
||||
items(tasks, key = { it.taskNum }) { task ->
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
// 开始会话是网络请求:在途时禁用,防连点重复提交
|
||||
.clickable(enabled = !starting) { onStart(task) },
|
||||
Column(
|
||||
modifier = Modifier.padding(Dimens.Group),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Section),
|
||||
) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
SkeletonBar(widthFraction = 0.55f, barHeight = Dimens.Section)
|
||||
SkeletonBar(widthFraction = 0.8f, barHeight = Dimens.Inner)
|
||||
SkeletonBar(widthFraction = 0.3f, barHeight = Dimens.Inner)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SkeletonBar(widthFraction: Float, barHeight: Dp) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(widthFraction).height(barHeight),
|
||||
shape = MaterialTheme.shapes.extraSmall,
|
||||
color = MaterialTheme.colorScheme.outlineVariant,
|
||||
) {}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TaskRow(
|
||||
task: TaskItem,
|
||||
starting: Boolean,
|
||||
onSelect: () -> Unit,
|
||||
onOpenReports: () -> Unit,
|
||||
) {
|
||||
// 点整条只负责选中,真正的开始交给页面上的确认弹窗;在途时整条与行内入口一起禁用
|
||||
LptListItem(onClick = onSelect, enabled = !starting) {
|
||||
// 任务名与优先级同一行:优先级是数据的注脚,不占动作那一行
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
task.taskName,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
"优先级 %.2f".format(task.taskPriority),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
)
|
||||
}
|
||||
if (!task.taskDescription.isNullOrBlank()) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
task.taskDescription,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
modifier = Modifier.padding(top = Dimens.Compact),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
// 动作行只留一个主操作在右、一个低权重入口在左,中间留空,200% 字体下也不会和数字挤成一行
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = Dimens.Group),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = onOpenReports, enabled = !starting) {
|
||||
Text(
|
||||
"优先级 %.2f".format(task.taskPriority),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
"报告",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
TextButton(onClick = { onOpenReports(task) }, enabled = !starting) { Text("报告") }
|
||||
Text(
|
||||
if (starting) "开始中…" else "开始学习 ›",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
if (starting) "开始中…" else "开始学习",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
TextButton(onClick = onLogout, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("退出登录", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/** 任务少于一屏扫得完时不渲染搜索框 */
|
||||
private const val SEARCH_THRESHOLD = 6
|
||||
private const val SKELETON_COUNT = 3
|
||||
private val SEARCH_FIELD_HEIGHT = 48.dp
|
||||
private val SKELETON_HEIGHT = 104.dp
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* 页面顶栏:返回与标题同一行(标题可换行),副标题单独一行;右侧最多一个动作。
|
||||
*/
|
||||
package com.catshark.lpt.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.minimumInteractiveComponentSize
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
|
||||
/**
|
||||
* 一屏一个页头:`backLabel` 与 `onBack` 同时给了才出现返回按钮,`action` 只放一个动作。
|
||||
* 会话页用 `titleStyle = MaterialTheme.typography.titleMedium` 让任务名当标题(例外见 design-principles.md)。
|
||||
*
|
||||
* 标题换行时返回按钮仍与标题第一行对齐:返回与标题在同一行,副标题另起一行,
|
||||
* 这样 200% 字体下不会出现「返回居中挂在三行标题的中间」。
|
||||
*/
|
||||
@Composable
|
||||
fun PageHeader(
|
||||
title: String,
|
||||
modifier: Modifier = Modifier,
|
||||
subtitle: String? = null,
|
||||
titleStyle: TextStyle = MaterialTheme.typography.titleLarge,
|
||||
backLabel: String? = null,
|
||||
onBack: (() -> Unit)? = null,
|
||||
action: (@Composable () -> Unit)? = null,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = Dimens.Screen, vertical = Dimens.Section),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Compact),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (backLabel != null && onBack != null) {
|
||||
TextButton(
|
||||
onClick = onBack,
|
||||
modifier = Modifier.minimumInteractiveComponentSize(),
|
||||
contentPadding = PaddingValues(horizontal = Dimens.Inner, vertical = Dimens.Inner),
|
||||
) {
|
||||
Text(backLabel, style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
title,
|
||||
style = titleStyle,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (action != null) {
|
||||
action()
|
||||
}
|
||||
}
|
||||
if (subtitle != null) {
|
||||
Text(
|
||||
subtitle,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* 页面状态件:`LptEmptyState` 空态(一句事实 + 可选提示 + 可选动作),`LptInlineError` 行内错误(原因 + 重试)。
|
||||
*/
|
||||
package com.catshark.lpt.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
|
||||
/**
|
||||
* 空态:不画插画、不用 emoji;在给定高度的容器里垂直居中,高度由调用方(如 `Modifier.weight(1f)`)决定。
|
||||
*/
|
||||
@Composable
|
||||
fun LptEmptyState(
|
||||
title: String,
|
||||
modifier: Modifier = Modifier,
|
||||
hint: String? = null,
|
||||
actionLabel: String? = null,
|
||||
onAction: (() -> Unit)? = null,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = Dimens.Screen, vertical = Dimens.Block),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Inner, Alignment.CenterVertically),
|
||||
) {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
if (hint != null) {
|
||||
Text(
|
||||
hint,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
if (actionLabel != null && onAction != null) {
|
||||
OutlinedButton(onClick = onAction) {
|
||||
Text(actionLabel, style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 行内错误条:`errorContainer` 底 + 原因 + 右侧重试;重试没给 `onRetry` 时不显示按钮。
|
||||
*/
|
||||
@Composable
|
||||
fun LptInlineError(
|
||||
title: String,
|
||||
modifier: Modifier = Modifier,
|
||||
detail: String? = null,
|
||||
retryLabel: String = "重试",
|
||||
onRetry: (() -> Unit)? = null,
|
||||
) {
|
||||
Surface(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.small,
|
||||
color = MaterialTheme.colorScheme.errorContainer,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(Dimens.Section),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
verticalArrangement = Arrangement.spacedBy(Dimens.Compact),
|
||||
) {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
)
|
||||
if (detail != null) {
|
||||
Text(
|
||||
detail,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (onRetry != null) {
|
||||
TextButton(
|
||||
onClick = onRetry,
|
||||
colors = ButtonDefaults.textButtonColors(
|
||||
contentColor = MaterialTheme.colorScheme.onErrorContainer,
|
||||
),
|
||||
) {
|
||||
Text(retryLabel, style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* 页面容器两级:`LptSection` 页面区块(12dp 圆角、`surface` 实底、无描边无阴影),`LptListItem` 列表条目(8dp 圆角 + 1dp `outlineVariant` 描边)。
|
||||
*/
|
||||
package com.catshark.lpt.ui.components
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.catshark.lpt.ui.theme.Dimens
|
||||
|
||||
/**
|
||||
* 页面级独立区块:同一页里的区块都用它,不套 `Card`。
|
||||
*/
|
||||
@Composable
|
||||
fun LptSection(
|
||||
modifier: Modifier = Modifier,
|
||||
contentPadding: PaddingValues = PaddingValues(Dimens.Group),
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
) {
|
||||
SectionBody(contentPadding, content)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表条目:与 `LptSection` 差一级(小圆角 + 1dp 分组描边),`onClick` 为空时不可点。
|
||||
*/
|
||||
@Composable
|
||||
fun LptListItem(
|
||||
modifier: Modifier = Modifier,
|
||||
onClick: (() -> Unit)? = null,
|
||||
enabled: Boolean = true,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
val shape = MaterialTheme.shapes.small
|
||||
val color = MaterialTheme.colorScheme.surface
|
||||
val border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant)
|
||||
if (onClick != null) {
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
enabled = enabled,
|
||||
shape = shape,
|
||||
color = color,
|
||||
border = border,
|
||||
) {
|
||||
SectionBody(PaddingValues(Dimens.Section), content)
|
||||
}
|
||||
} else {
|
||||
Surface(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
shape = shape,
|
||||
color = color,
|
||||
border = border,
|
||||
) {
|
||||
SectionBody(PaddingValues(Dimens.Section), content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionBody(
|
||||
contentPadding: PaddingValues,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
Column(modifier = Modifier.padding(contentPadding), content = content)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* 间距六档(登记在 `.agents/roles/design-system.md`):组件里的边距与间隙只取这里,不写档外 dp。
|
||||
*/
|
||||
package com.catshark.lpt.ui.theme
|
||||
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
object Dimens {
|
||||
val Compact = 4.dp
|
||||
val Inner = 8.dp
|
||||
val Section = 12.dp
|
||||
val Group = 16.dp
|
||||
val Block = 24.dp
|
||||
val Screen = 16.dp
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
/**
|
||||
* 主题:浅色与深色两套完整色板(取值登记在 `.agents/roles/design-system.md`),`LptTheme` 跟随系统深浅色。
|
||||
*/
|
||||
package com.catshark.lpt.ui.theme
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
@@ -8,17 +11,63 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
private val LightColors = lightColorScheme(
|
||||
primary = Color(0xFF1F6FEB),
|
||||
onPrimary = Color.White,
|
||||
secondary = Color(0xFF238636),
|
||||
primary = Color(0xFF237556),
|
||||
onPrimary = Color(0xFFFFFFFF),
|
||||
primaryContainer = Color(0xFFEEF9F3),
|
||||
onPrimaryContainer = Color(0xFF237556),
|
||||
secondary = Color(0xFF237556),
|
||||
onSecondary = Color(0xFFFFFFFF),
|
||||
secondaryContainer = Color(0xFFEEF9F3),
|
||||
onSecondaryContainer = Color(0xFF237556),
|
||||
tertiaryContainer = Color(0xFFFFF8E1),
|
||||
onTertiaryContainer = Color(0xFF856404),
|
||||
background = Color(0xFFF7FBF8),
|
||||
onBackground = Color(0xFF16241C),
|
||||
surface = Color(0xFFFFFFFF),
|
||||
onSurface = Color(0xFF16241C),
|
||||
surfaceVariant = Color(0xFFF1F6F3),
|
||||
onSurfaceVariant = Color(0xFF4B6156),
|
||||
surfaceContainer = Color(0xFFF1F6F3),
|
||||
surfaceContainerLow = Color(0xFFFFFFFF),
|
||||
surfaceContainerLowest = Color(0xFFFFFFFF),
|
||||
surfaceContainerHigh = Color(0xFFF4F8F5),
|
||||
surfaceContainerHighest = Color(0xFFF1F6F3),
|
||||
outline = Color(0xFF6B7F75),
|
||||
outlineVariant = Color(0xFFC6D6CD),
|
||||
error = Color(0xFFB62324),
|
||||
onError = Color(0xFFFFFFFF),
|
||||
errorContainer = Color(0xFFFDECEA),
|
||||
onErrorContainer = Color(0xFFB62324),
|
||||
)
|
||||
|
||||
private val DarkColors = darkColorScheme(
|
||||
primary = Color(0xFF6EA8FE),
|
||||
onPrimary = Color(0xFF0B1220),
|
||||
secondary = Color(0xFF3FB950),
|
||||
primary = Color(0xFF7FD8B4),
|
||||
onPrimary = Color(0xFF111A16),
|
||||
primaryContainer = Color(0xFF17332A),
|
||||
onPrimaryContainer = Color(0xFF7FD8B4),
|
||||
secondary = Color(0xFF7FD8B4),
|
||||
onSecondary = Color(0xFF111A16),
|
||||
secondaryContainer = Color(0xFF17332A),
|
||||
onSecondaryContainer = Color(0xFF7FD8B4),
|
||||
tertiaryContainer = Color(0xFF3A3220),
|
||||
onTertiaryContainer = Color(0xFFFFD08A),
|
||||
background = Color(0xFF111A16),
|
||||
onBackground = Color(0xFFE4EFE9),
|
||||
surface = Color(0xFF1B2A23),
|
||||
onSurface = Color(0xFFE4EFE9),
|
||||
surfaceVariant = Color(0xFF22332B),
|
||||
onSurfaceVariant = Color(0xFFB3C7BD),
|
||||
surfaceContainer = Color(0xFF1B2A23),
|
||||
surfaceContainerLow = Color(0xFF1B2A23),
|
||||
surfaceContainerLowest = Color(0xFF111A16),
|
||||
surfaceContainerHigh = Color(0xFF22332B),
|
||||
surfaceContainerHighest = Color(0xFF22332B),
|
||||
outline = Color(0xFF7C9186),
|
||||
outlineVariant = Color(0xFF33453D),
|
||||
error = Color(0xFFF85149),
|
||||
onError = Color(0xFF111A16),
|
||||
errorContainer = Color(0xFF3A1F1F),
|
||||
onErrorContainer = Color(0xFFFF8A80),
|
||||
)
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.catshark.lpt.util
|
||||
|
||||
import kotlin.math.ceil
|
||||
import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
@@ -12,6 +13,10 @@ fun formatDuration(seconds: Double): String {
|
||||
return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%02d:%02d".format(m, s)
|
||||
}
|
||||
|
||||
/** 倒计时向上取整:不足一秒仍显示 00:01,实际到零才显示 00:00。 */
|
||||
fun formatCountdown(remainingMs: Long?): String =
|
||||
remainingMs?.let { formatDuration(ceil(it.coerceAtLeast(0) / 1000.0)) } ?: "--:--"
|
||||
|
||||
private val DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
|
||||
|
||||
/** 服务端返回的 LocalDateTime 字符串(无时区),解析失败时原样展示 */
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
<resources>
|
||||
<style name="Theme.LPT" parent="android:Theme.Material.Light.NoActionBar" />
|
||||
|
||||
<!-- 悬浮窗拉起的碎片输入弹窗:悬浮小窗 + 键盘 -->
|
||||
<style name="Theme.LPT.InputDialog" parent="android:Theme.Material.Light.Dialog">
|
||||
<!-- 透明全屏承载页:非 floating,键盘缩放后的高度交给 Compose 自适应。 -->
|
||||
<style name="Theme.LPT.InputDialog" parent="android:Theme.Material.Light.NoActionBar">
|
||||
<item name="android:windowIsFloating">false</item>
|
||||
<item name="android:windowBackground">@android:color/transparent</item>
|
||||
<item name="android:windowIsTranslucent">true</item>
|
||||
<item name="android:windowNoTitle">true</item>
|
||||
<item name="android:backgroundDimEnabled">true</item>
|
||||
<item name="android:windowSoftInputMode">stateVisible|adjustResize</item>
|
||||
<item name="android:windowSoftInputMode">stateAlwaysVisible|adjustResize</item>
|
||||
<item name="android:colorBackgroundCacheHint">@null</item>
|
||||
</style>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.catshark.lpt.service
|
||||
|
||||
import com.catshark.lpt.session.SessionController
|
||||
import com.catshark.lpt.util.formatCountdown
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class CountdownAlertTest {
|
||||
private fun running(ms: Long = 1500L) = SessionController.State(
|
||||
sessionNum = "s1", status = SessionController.Status.ONGOING,
|
||||
countdownBaseMs = ms, anchorRealtimeMs = 1000L, countdownKey = "s1|start1",
|
||||
)
|
||||
|
||||
@Test fun countdownUsesMonotonicAnchorAndStopsAtZero() {
|
||||
val state = running()
|
||||
assertEquals(1500L, state.remainingMs(1000L))
|
||||
assertEquals(500L, state.remainingMs(2000L))
|
||||
assertEquals(0L, state.remainingMs(2500L))
|
||||
assertEquals(0L, state.remainingMs(20000L))
|
||||
assertEquals(1500L, state.remainingMs(500L))
|
||||
}
|
||||
|
||||
@Test fun pausedCountdownDoesNotDecrease() {
|
||||
val state = running().copy(status = SessionController.Status.PAUSED)
|
||||
assertEquals(1500L, state.remainingMs(100000L))
|
||||
assertNull(countdownAlertKey(state.copy(countdownBaseMs = 0L), 100000L, null))
|
||||
}
|
||||
|
||||
@Test fun missingCountdownIsNotAnExpiredTimer() {
|
||||
val state = running().copy(countdownBaseMs = null)
|
||||
assertNull(state.remainingMs(100000L))
|
||||
assertNull(countdownAlertKey(state, 100000L, null))
|
||||
assertEquals("--:--", formatCountdown(null))
|
||||
}
|
||||
|
||||
@Test fun countdownOnlyDisplaysZeroAtActualDeadline() {
|
||||
assertEquals("00:01", formatCountdown(1))
|
||||
assertEquals("00:01", formatCountdown(999))
|
||||
assertEquals("00:02", formatCountdown(1001))
|
||||
assertEquals("00:00", formatCountdown(0))
|
||||
assertEquals("25:00", formatCountdown(1500000))
|
||||
}
|
||||
|
||||
@Test fun expiryEmitsOnceAndSurvivesReconciliationOrRestart() {
|
||||
val state = running()
|
||||
assertNull(countdownAlertKey(state, 2499L, null))
|
||||
val persistedKey = countdownAlertKey(state, 2500L, null)
|
||||
assertEquals("s1|start1", persistedKey)
|
||||
assertNull(countdownAlertKey(state, 5000L, persistedKey))
|
||||
// 进程恢复只重新对锚,不改变后端分段标识。
|
||||
val restored = state.copy(anchorRealtimeMs = 500L)
|
||||
assertNull(countdownAlertKey(restored, 5000L, persistedKey))
|
||||
}
|
||||
|
||||
@Test fun nextSegmentCanAlertButEndedSessionCannot() {
|
||||
val state = running().copy(countdownKey = "s1|start2")
|
||||
assertEquals("s1|start2", countdownAlertKey(state, 3000L, "s1|start1"))
|
||||
assertNull(countdownAlertKey(state.copy(status = SessionController.Status.ENDED), 3000L, null))
|
||||
}
|
||||
|
||||
@Test fun expiredSessionOnRecoveryAlertsOnceWithoutEndingSession() {
|
||||
val state = running(0L)
|
||||
assertEquals("s1|start1", countdownAlertKey(state, 1000L, null))
|
||||
assertEquals(SessionController.Status.ONGOING, state.status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package com.catshark.lpt.session
|
||||
|
||||
import com.catshark.lpt.data.*
|
||||
import java.lang.reflect.Proxy
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
private fun unusedApi(): LptApi = Proxy.newProxyInstance(
|
||||
LptApi::class.java.classLoader, arrayOf(LptApi::class.java),
|
||||
) { _, method, _ -> error("Unexpected API call: ${method.name}") } as LptApi
|
||||
|
||||
private class SessionApi : LptApi by unusedApi() {
|
||||
var active: suspend () -> ApiEnvelope<ActiveSession> = { ApiEnvelope(200) }
|
||||
var detail: suspend () -> ApiEnvelope<SessionDetail> = {
|
||||
ApiEnvelope(200, data = SessionDetail(sessionNum = "s1", taskNum = "t1", sessionState = "PAUSED"))
|
||||
}
|
||||
var expectation: ApiEnvelope<Expectation> = ApiEnvelope(200, data = Expectation("learn"))
|
||||
var fragmentResponse: ApiEnvelope<List<FragmentItem>> = ApiEnvelope(200, data = emptyList())
|
||||
var startResponse: ApiEnvelope<SessionDetail>? = null
|
||||
var starts = 0
|
||||
var endings = 0
|
||||
var add: suspend () -> ApiEnvelope<kotlinx.serialization.json.JsonElement> = { ApiEnvelope(200) }
|
||||
override suspend fun activeSession(excludeTaskNum: String?) = active()
|
||||
override suspend fun sessionDetail(sessionNum: String) = detail()
|
||||
override suspend fun startOrContinue(taskNum: String): ApiEnvelope<SessionDetail> {
|
||||
starts++
|
||||
return startResponse ?: detail()
|
||||
}
|
||||
override suspend fun getExpectation(sessionNum: String) = expectation
|
||||
override suspend fun fragmentsBySession(sessionNum: String) = fragmentResponse
|
||||
override suspend fun createFragment(body: CreateFragmentRequest) = add()
|
||||
override suspend fun endSession(sessionNum: String, body: EndSessionRequest): ApiEnvelope<kotlinx.serialization.json.JsonElement> {
|
||||
endings++
|
||||
return ApiEnvelope(500, "save failed")
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class SessionControllerTest {
|
||||
@Test fun failedConflictCheckNeverStartsSession() = runTest {
|
||||
val api = SessionApi().apply { active = { ApiEnvelope(500, "offline") } }
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
controller.startOrContinue("t1")
|
||||
runCurrent()
|
||||
assertEquals(0, api.starts)
|
||||
assertFalse(controller.state.value.busy)
|
||||
assertTrue(controller.state.value.error!!.contains("offline"))
|
||||
}
|
||||
|
||||
@Test fun conflictOnlyOffersExistingSession() = runTest {
|
||||
val api = SessionApi().apply { active = { ApiEnvelope(200, data = ActiveSession("t2", "s2")) } }
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
controller.startOrContinue("t1")
|
||||
runCurrent()
|
||||
assertEquals(0, api.starts)
|
||||
assertEquals("s2", controller.state.value.conflict?.sessionNum)
|
||||
}
|
||||
|
||||
@Test fun failedReconcileStaysUnresolvedAndCanRetry() = runTest {
|
||||
val api = SessionApi().apply { active = { ApiEnvelope(500, "offline") } }
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
controller.reconcile()
|
||||
runCurrent()
|
||||
assertFalse(controller.state.value.resolved)
|
||||
assertFalse(controller.state.value.reconciling)
|
||||
api.active = { ApiEnvelope(200) }
|
||||
controller.reconcile()
|
||||
runCurrent()
|
||||
assertTrue(controller.state.value.resolved)
|
||||
assertNull(controller.state.value.syncError)
|
||||
}
|
||||
|
||||
@Test fun failedDetailDoesNotConfirmEmptyState() = runTest {
|
||||
val api = SessionApi().apply {
|
||||
active = { ApiEnvelope(200, data = ActiveSession("t1", "s1")) }
|
||||
detail = { ApiEnvelope(500, "detail failed") }
|
||||
}
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
controller.reconcile()
|
||||
runCurrent()
|
||||
assertFalse(controller.state.value.resolved)
|
||||
assertFalse(controller.state.value.hasSession)
|
||||
}
|
||||
|
||||
@Test fun confirmedNoSessionClearsStaleLocalSession() = runTest {
|
||||
val api = SessionApi()
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
controller.startOrContinue("t1")
|
||||
runCurrent()
|
||||
assertTrue(controller.state.value.hasSession)
|
||||
controller.reconcile()
|
||||
runCurrent()
|
||||
assertFalse(controller.state.value.hasSession)
|
||||
assertTrue(controller.state.value.resolved)
|
||||
}
|
||||
|
||||
@Test fun clearCancelsLateResponses() = runTest {
|
||||
val response = CompletableDeferred<ApiEnvelope<ActiveSession>>()
|
||||
val api = SessionApi().apply { active = { response.await() } }
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
controller.reconcile()
|
||||
runCurrent()
|
||||
controller.clear()
|
||||
response.complete(ApiEnvelope(200, data = ActiveSession("t1", "s1")))
|
||||
runCurrent()
|
||||
assertFalse(controller.state.value.hasSession)
|
||||
assertNull(controller.state.value.sessionNum)
|
||||
assertNull(controller.state.value.error)
|
||||
}
|
||||
|
||||
@Test fun repeatedStartSendsOnlyOneRequest() = runTest {
|
||||
val response = CompletableDeferred<ApiEnvelope<ActiveSession>>()
|
||||
val api = SessionApi().apply { active = { response.await() } }
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
controller.startOrContinue("t1")
|
||||
controller.startOrContinue("t1")
|
||||
runCurrent()
|
||||
response.complete(ApiEnvelope(200))
|
||||
runCurrent()
|
||||
assertEquals(1, api.starts)
|
||||
}
|
||||
|
||||
@Test fun endingWaitsForFragmentWriteAndFailedEndKeepsSession() = runTest {
|
||||
val response = CompletableDeferred<ApiEnvelope<kotlinx.serialization.json.JsonElement>>()
|
||||
val api = SessionApi().apply { add = { response.await() } }
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
controller.startOrContinue("t1")
|
||||
runCurrent()
|
||||
controller.addFragment("note")
|
||||
controller.end(ReportSections.EMPTY)
|
||||
runCurrent()
|
||||
assertEquals(0, api.endings)
|
||||
response.complete(ApiEnvelope(200))
|
||||
runCurrent()
|
||||
controller.end(ReportSections.EMPTY)
|
||||
runCurrent()
|
||||
assertEquals(1, api.endings)
|
||||
assertTrue(controller.state.value.hasSession)
|
||||
assertFalse(controller.state.value.busy)
|
||||
assertEquals("save failed", controller.state.value.error)
|
||||
assertEquals("save failed", controller.state.value.endError)
|
||||
controller.consumeError()
|
||||
assertEquals("save failed", controller.state.value.endError)
|
||||
}
|
||||
|
||||
@Test fun businessErrorsNeverBecomeEmptyAuxiliaryData() = runTest {
|
||||
val api = SessionApi().apply {
|
||||
expectation = ApiEnvelope(500, "expectation failed")
|
||||
fragmentResponse = ApiEnvelope(500, "fragments failed")
|
||||
}
|
||||
val repository = LptRepository { api }
|
||||
assertTrue(repository.getExpectation("s1").isFailure)
|
||||
assertTrue(repository.fragments("s1").isFailure)
|
||||
val controller = SessionController(repository, backgroundScope) { 1000L }
|
||||
controller.startOrContinue("t1")
|
||||
runCurrent()
|
||||
assertFalse(controller.state.value.expectationLoaded)
|
||||
assertNotNull(controller.state.value.syncError)
|
||||
}
|
||||
|
||||
@Test fun cancellationPropagatesOutOfRepository() = runTest {
|
||||
val api = SessionApi().apply { active = { throw CancellationException("cancelled") } }
|
||||
try {
|
||||
LptRepository { api }.activeSession()
|
||||
fail("Cancellation must propagate")
|
||||
} catch (_: CancellationException) {
|
||||
// Expected: callers must not apply a cancelled response to UI state.
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun rejectedFragmentRequestAlwaysCompletesCallback() = runTest {
|
||||
val response = CompletableDeferred<ApiEnvelope<ActiveSession>>()
|
||||
val api = SessionApi().apply { active = { response.await() } }
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
var message: String? = null
|
||||
controller.addFragment("note") { message = it }
|
||||
assertNotNull(message)
|
||||
api.active = { ApiEnvelope(200) }
|
||||
controller.startOrContinue("t1")
|
||||
runCurrent()
|
||||
api.active = { response.await() }
|
||||
controller.reconcile()
|
||||
runCurrent()
|
||||
message = null
|
||||
controller.addFragment("note") { message = it }
|
||||
assertNotNull(message)
|
||||
controller.clear()
|
||||
}
|
||||
|
||||
@Test fun missingExpectationIsDifferentFromFailedExpectation() = runTest {
|
||||
val api = SessionApi().apply { expectation = ApiEnvelope(200) }
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
controller.startOrContinue("t1")
|
||||
runCurrent()
|
||||
assertTrue(controller.state.value.expectationLoaded)
|
||||
assertTrue(controller.state.value.expectationRequired)
|
||||
}
|
||||
|
||||
@Test fun startUsesDetailCountdownBaselineInsteadOfDeductedStartResponse() = runTest {
|
||||
val api = SessionApi().apply {
|
||||
startResponse = ApiEnvelope(200, data = SessionDetail(sessionNum = "s1", sessionState = "PAUSED", pointerPosition = 500.0))
|
||||
detail = { ApiEnvelope(200, data = SessionDetail(
|
||||
sessionNum = "s1", taskNum = "t1", sessionState = "PAUSED",
|
||||
pointerPosition = 123456.0, lastStartTime = "2026-11-14T10:00:00",
|
||||
)) }
|
||||
}
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
controller.startOrContinue("t1")
|
||||
runCurrent()
|
||||
assertEquals(123456L, controller.state.value.remainingMs(100000L))
|
||||
assertEquals("s1|2026-11-14T10:00:00", controller.state.value.countdownKey)
|
||||
}
|
||||
|
||||
@Test fun zeroPointerRemainsZeroInsteadOfDefaultingToTwentyFiveMinutes() = runTest {
|
||||
val api = SessionApi().apply {
|
||||
detail = { ApiEnvelope(200, data = SessionDetail(
|
||||
sessionNum = "s1", sessionState = "PAUSED", pointerPosition = 0.0,
|
||||
)) }
|
||||
}
|
||||
val controller = SessionController(LptRepository { api }, backgroundScope) { 1000L }
|
||||
controller.startOrContinue("t1")
|
||||
runCurrent()
|
||||
assertEquals(0L, controller.state.value.remainingMs(1000L))
|
||||
}
|
||||
|
||||
@Test fun timerNeverSubtractsForOlderUiTick() {
|
||||
val state = SessionController.State(
|
||||
status = SessionController.Status.ONGOING,
|
||||
baseEffectiveSeconds = 12.0,
|
||||
anchorRealtimeMs = 2000L,
|
||||
)
|
||||
assertEquals(12.0, state.effectiveSeconds(1000L), 0.0)
|
||||
assertEquals(14.0, state.effectiveSeconds(4000L), 0.0)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user