feat: 六个页面按新规则重构,接入深色取值
This commit is contained in:
@@ -8,6 +8,7 @@ local.properties
|
||||
.idea/
|
||||
*.iml
|
||||
captures/
|
||||
artifacts/qa/
|
||||
|
||||
# 系统
|
||||
.DS_Store
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,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