Cotton code
288 lines · 14.6 KB · KotlinRaw
@file:OptIn(    androidx.compose.material3.ExperimentalMaterial3Api::class,    androidx.compose.foundation.layout.ExperimentalLayoutApi::class,)package com.cottondb.android.ui.dayimport android.app.TimePickerDialogimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.FlowRowimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.FilterChipimport androidx.compose.material3.ModalBottomSheetimport androidx.compose.material3.rememberModalBottomSheetStateimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Switchimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.roleimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.cottondb.android.day.alarms.Alarmimport com.cottondb.android.day.alarms.AlarmEditorModelimport com.cottondb.android.day.alarms.AlarmEditorStateimport com.cottondb.android.day.alarms.AlarmEditorSuccessimport com.cottondb.android.day.alarms.AlarmMutationimport com.cottondb.android.day.alarms.AlarmsReadimport com.cottondb.android.day.alarms.AlarmsRepositoryimport com.cottondb.android.day.alarms.AlarmsStateimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonMetricsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport com.cottondb.android.ui.day.todos.PaperGroundimport com.cottondb.android.ui.day.todos.TodoFailureimport com.cottondb.android.ui.day.todos.TodoLoadingPaperimport com.cottondb.android.ui.day.todos.TodoNoticeimport com.cottondb.android.ui.day.todos.TodoTopBarimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchprivate val AlarmPaperShape = RoundedCornerShape(CottonMetrics.cardRadius)/** * Durable alarm intent editor. This screen does not promise ringing or delivery: * Android scheduling and permission state are intentionally a later integration. */@Composablefun AlarmsScreen(    repository: AlarmsRepository,    writerScope: CoroutineScope,    editorFor: (key: String, initial: Alarm?) -> AlarmEditorModel,    dataRevision: Long,    onBack: () -> Unit,    permissions: @Composable () -> Unit = {},) {    val state by repository.state.collectAsState()    val uiScope = rememberCoroutineScope()    var creating by rememberSaveable { mutableStateOf(false) }    var creationNonce by rememberSaveable { mutableStateOf(0) }    var openedId by rememberSaveable { mutableStateOf<String?>(null) }    val read = state.readOrNull()    LaunchedEffect(repository, dataRevision) { repository.refresh() }    PaperGround {        Column(Modifier.fillMaxSize()) {            TodoTopBar(                title = "Alarms",                onBack = onBack,                onRefresh = { uiScope.launch { repository.refresh() } },                onAdd = { creationNonce += 1; creating = true },            )            permissions()            when {                state is AlarmsState.Loading && read == null -> TodoLoadingPaper()                read == null -> TodoFailure((state as AlarmsState.Error).message) { uiScope.launch { repository.refresh() } }                else -> AlarmList(                    read = read,                    warning = (state as? AlarmsState.Error)?.message,                    onRetry = { uiScope.launch { repository.refresh() } },                    editorFor = editorFor,                    writerScope = writerScope,                    onOpen = { openedId = it.id },                    onNew = { creationNonce += 1; creating = true },                )            }        }    }    if (creating) {        val editor = remember("alarm:new:$creationNonce") { editorFor("alarm:new:$creationNonce", null) }        AlarmEditorSheet(editor, writerScope, title = "New alarm", onDismiss = { creating = false })        val editorState by editor.state.collectAsState()        LaunchedEffect(editorState) {            if ((editorState as? AlarmEditorState.Editing)?.success is AlarmEditorSuccess.Created) {                creating = false                editor.acknowledgeSuccess()            }        }    }    openedId?.let { id ->        val alarm = read?.alarms?.firstOrNull { it.id == id }        if (alarm == null) LaunchedEffect(id, read) { openedId = null }        else {            val editor = remember("alarm:$id") { editorFor("alarm:$id", alarm) }            LaunchedEffect(alarm) { editor.adopt(alarm) }            AlarmEditorSheet(editor, writerScope, title = "Edit alarm", onDismiss = { openedId = null })            val editorState by editor.state.collectAsState()            LaunchedEffect(editorState) {                when (editorState) {                    is AlarmEditorState.Deleted -> openedId = null                    is AlarmEditorState.Editing -> if ((editorState as AlarmEditorState.Editing).success is AlarmEditorSuccess.Updated) {                        openedId = null                        editor.acknowledgeSuccess()                    }                    is AlarmEditorState.Saving -> Unit                }            }        }    }}private fun AlarmsState.readOrNull(): AlarmsRead? = when (this) {    is AlarmsState.Data -> read    is AlarmsState.Error -> last    AlarmsState.Loading -> null}@Composableprivate fun AlarmList(    read: AlarmsRead,    warning: String?,    onRetry: () -> Unit,    editorFor: (String, Alarm?) -> AlarmEditorModel,    writerScope: CoroutineScope,    onOpen: (Alarm) -> Unit,    onNew: () -> Unit,) = LazyColumn(    modifier = Modifier.fillMaxSize(),    contentPadding = PaddingValues(CottonMetrics.contentMargin, 14.dp, CottonMetrics.contentMargin, 100.dp),    verticalArrangement = Arrangement.spacedBy(12.dp),) {    warning?.let { item { TodoNotice(it) } }    if (warning != null) item { Text("Try again", Modifier.clickable(onClick = onRetry), style = CottonTextStyles.caption, color = CottonPalette.accent) }    if (read.alarms.isEmpty()) item { AlarmEmpty(onNew) }    items(read.alarms, key = Alarm::id) { alarm ->        val editor = remember("alarm:${alarm.id}") { editorFor("alarm:${alarm.id}", alarm) }        LaunchedEffect(alarm) { editor.adopt(alarm) }        AlarmCard(alarm, editor, writerScope, onOpen = {            editor.acknowledgeSuccess()            onOpen(alarm)        })    }}@Composableprivate fun AlarmEmpty(onNew: () -> Unit) = Column(    Modifier.fillMaxWidth().padding(top = 56.dp),    horizontalAlignment = Alignment.CenterHorizontally,) {    Text("No alarms yet.", style = CottonTextStyles.body.copy(fontFamily = CottonFonts.serif), color = CottonPalette.ink)    Text("New alarm", Modifier.padding(top = 10.dp).clickable(onClick = onNew), style = CottonTextStyles.caption, color = CottonPalette.accent)}@Composableprivate fun AlarmCard(alarm: Alarm, editor: AlarmEditorModel, writerScope: CoroutineScope, onOpen: () -> Unit) {    val state by editor.state.collectAsState()    val busy = state is AlarmEditorState.Saving    Row(        modifier = Modifier.fillMaxWidth().background(CottonPalette.groundElevated, AlarmPaperShape)            .clickable(enabled = !busy, onClick = onOpen).padding(18.dp),        verticalAlignment = Alignment.CenterVertically,    ) {        Column(Modifier.weight(1f)) {            Text(alarmClock(alarm.hour, alarm.minute), style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.type), color = if (alarm.enabled) CottonPalette.ink else CottonPalette.inkSecondary)            Text(alarm.label.trim().ifBlank { "Alarm" }, Modifier.padding(top = 4.dp), maxLines = 1, overflow = TextOverflow.Ellipsis, style = CottonTextStyles.body.copy(fontFamily = CottonFonts.serif), color = if (alarm.enabled) CottonPalette.ink else CottonPalette.inkSecondary)            Text(repeatLabel(alarm.repeatDays), Modifier.padding(top = 3.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)            (state as? AlarmEditorState.Editing)?.error?.let { Text(it, Modifier.padding(top = 4.dp), style = CottonTextStyles.caption, color = CottonPalette.statusError) }        }        Spacer(Modifier.width(12.dp))        Switch(            checked = alarm.enabled,            enabled = !busy,            onCheckedChange = { editor.setEnabled(it, writerScope) },            modifier = Modifier.semantics { role = Role.Switch; contentDescription = "${if (alarm.enabled) "Turn off" else "Turn on"} ${alarm.label.trim().ifBlank { "alarm" }}" },        )    }}@Composableprivate fun AlarmEditorSheet(editor: AlarmEditorModel, writerScope: CoroutineScope, title: String, onDismiss: () -> Unit) {    val state by editor.state.collectAsState()    val editing = state as? AlarmEditorState.Editing    val draft = when (state) {        is AlarmEditorState.Editing -> (state as AlarmEditorState.Editing).draft        is AlarmEditorState.Saving -> (state as AlarmEditorState.Saving).draft        is AlarmEditorState.Deleted -> return    }    val saving = state is AlarmEditorState.Saving    val context = LocalContext.current    ModalBottomSheet(        onDismissRequest = { if (!saving) onDismiss() },        sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),        containerColor = CottonPalette.ground,    ) {        LazyColumn(Modifier.fillMaxWidth().padding(CottonMetrics.contentMargin), verticalArrangement = Arrangement.spacedBy(14.dp)) {            item { Text(title, style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink) }            item {                TextButton(enabled = !saving, onClick = {                    TimePickerDialog(context, { _, hour, minute -> editor.setDraft(draft.copy(hour = hour, minute = minute)) }, draft.hour, draft.minute, false).show()                }) { Text("Time: ${alarmClock(draft.hour, draft.minute)}") }            }            item { OutlinedTextField(value = draft.label, onValueChange = { if (it.length <= 120) editor.setDraft(draft.copy(label = it)) }, modifier = Modifier.fillMaxWidth(), enabled = !saving, label = { Text("Name") }, placeholder = { Text("Alarm") }, textStyle = CottonTextStyles.body.copy(fontFamily = CottonFonts.serif)) }            item {                Text("Repeats", style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkSecondary)                FlowRow(Modifier.padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(5.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {                    (1..7).forEach { day -> FilterChip(selected = day in draft.repeatDays, onClick = {                        val next = if (day in draft.repeatDays) draft.repeatDays - day else draft.repeatDays + day                        editor.setDraft(draft.copy(repeatDays = next.sorted()))                    }, enabled = !saving, label = { Text(weekdayShort(day)) }) }                }                Text(if (draft.repeatDays.isEmpty()) "Once" else repeatLabel(draft.repeatDays), Modifier.padding(top = 6.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)            }            item {                Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {                    Column(Modifier.weight(1f)) {                        Text("Sound", style = CottonTextStyles.body, color = CottonPalette.ink)                        Text(if (draft.sound) "Makes a noise." else "Arrives silently — it still lights the screen and vibrates.", style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)                    }                    Switch(checked = draft.sound, enabled = !saving, onCheckedChange = { editor.setDraft(draft.copy(sound = it)) })                }            }            editing?.error?.let { error -> item { Text(error, style = CottonTextStyles.caption, color = CottonPalette.statusError) } }            item {                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(18.dp)) {                    TextButton(enabled = !saving, onClick = { editor.save(writerScope) }) { Text(if (saving) "Saving…" else "Save") }                    if (title == "Edit alarm") TextButton(enabled = !saving, onClick = { editor.delete(writerScope) }) { Text("Delete alarm", color = CottonPalette.statusError) }                }            }        }    }}@Composableprivate fun AlarmNotice(message: String, dismiss: () -> Unit) = AlertDialog(onDismissRequest = dismiss, title = { Text("Couldn’t save", fontFamily = CottonFonts.display) }, text = { Text(message) }, confirmButton = { TextButton(onClick = dismiss) { Text("OK") } })private fun alarmClock(hour: Int, minute: Int): String {    val displayHour = when (hour % 12) { 0 -> 12; else -> hour % 12 }    return "$displayHour:${minute.toString().padStart(2, '0')} ${if (hour >= 12) "pm" else "am"}"}private fun weekdayShort(day: Int): String = listOf("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[day - 1]private fun repeatLabel(raw: List<Int>): String {    val days = raw.filter { it in 1..7 }.distinct().sorted()    if (days.isEmpty()) return "Once"    if (days.size == 7) return "Every day"    if (days.size >= 3 && days.last() - days.first() == days.size - 1) return "${weekdayShort(days.first())}–${weekdayShort(days.last())}"    return days.joinToString(" ", transform = ::weekdayShort)}