Cotton code
305 lines · 12.1 KB · KotlinRaw
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)package com.cottondb.android.ui.captureimport androidx.activity.compose.BackHandlerimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.imePaddingimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingPaddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.rememberimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.shadowimport androidx.compose.ui.focus.FocusRequesterimport androidx.compose.ui.focus.focusRequesterimport 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.capture.CaptureModelimport com.cottondb.android.capture.CaptureStartimport com.cottondb.android.capture.CaptureStateimport com.cottondb.android.capture.foldSegmentimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonMetricsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport kotlinx.coroutines.CoroutineScope/** * Home capture in place: dictation and typing share one retained draft. * * [requestMicrophone] keeps Android's permission prompt in the context of the * control that needs it. The platform voice adapter still guards permission in * case it is revoked after this callback returns. */@Composablefun CaptureOverlay(    model: CaptureModel,    start: CaptureStart,    writerScope: CoroutineScope,    requestMicrophone: (onResult: (Boolean) -> Unit) -> Unit,    onKept: (id: String) -> Unit,    onClose: () -> Unit,) {    val state by model.state.collectAsState()    val focus = remember { FocusRequester() }    var initialStartHandled by rememberSaveable { mutableStateOf(false) }    val beginListening = {        requestMicrophone { granted ->            if (granted) model.start(CaptureStart.Listening) else model.permissionDenied()        }    }    DisposableEffect(model) {        onDispose { model.dispose() }    }    LaunchedEffect(model, start, initialStartHandled) {        if (initialStartHandled) return@LaunchedEffect        initialStartHandled = true        when (start) {            CaptureStart.Listening -> if (                (state as? CaptureState.Error)?.retryable != false &&                state !is CaptureState.Listening &&                state !is CaptureState.Finishing &&                state !is CaptureState.Saving &&                state !is CaptureState.Created            ) beginListening()            CaptureStart.Typing -> {                model.start(CaptureStart.Typing)                focus.requestFocus()            }        }    }    LaunchedEffect(state) {        if (state is CaptureState.Created) onKept((state as CaptureState.Created).id)    }    val busy = state is CaptureState.Finishing || state is CaptureState.Saving    val terminal = (state as? CaptureState.Error)?.retryable == false    val closeWithoutWriting = {        if (!busy) {            model.dispose()            onClose()        }    }    // The overlay owns Back even while a retained operation is settling or saving.    BackHandler(onBack = closeWithoutWriting)    Box(        Modifier.fillMaxSize()            .background(CottonPalette.groundMuted)            .safeDrawingPadding()            .imePadding(),    ) {        Column(Modifier.fillMaxSize()) {            CaptureHeader(                enabled = !busy,                outcomeUncertain = terminal,                onClose = closeWithoutWriting,            )            Spacer(Modifier.weight(1f))            CaptureComposer(                state = state,                focus = focus,                onText = model::edit,                onListen = beginListening,                onStop = { model.stop(writerScope) },                onCapture = { model.submit(writerScope) },            )        }    }    (state as? CaptureState.Error)?.takeIf { it.retryable }?.let { error ->        CaptureError(error.message) {            model.edit(error.draft)        }    }}@Composableprivate fun CaptureHeader(enabled: Boolean, outcomeUncertain: Boolean, onClose: () -> Unit) = Row(    Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 14.dp),    verticalAlignment = Alignment.CenterVertically,) {    Text(        "Capture",        Modifier.weight(1f),        style = CottonTextStyles.pageTitle.copy(fontFamily = CottonFonts.display),        color = CottonPalette.ink,    )    Text(        "Close",        Modifier.clickable(enabled = enabled, role = Role.Button, onClick = onClose)            .semantics { contentDescription = if (outcomeUncertain) "Close capture" else "Close and discard this capture" }            .padding(10.dp),        style = CottonTextStyles.preview,        color = if (enabled) CottonPalette.inkSecondary else CottonPalette.inkTertiary,    )}@Composableprivate fun CaptureComposer(    state: CaptureState,    focus: FocusRequester,    onText: (String) -> Unit,    onListen: () -> Unit,    onStop: () -> Unit,    onCapture: () -> Unit,) {    val draft = state.captureDraft()    val listening = state as? CaptureState.Listening    val finishing = state as? CaptureState.Finishing    val busy = state is CaptureState.Saving || finishing != null    val terminal = (state as? CaptureState.Error)?.retryable == false    val shown = when {        listening != null -> foldSegment(listening.draft, listening.partial)        finishing != null -> finishing.draft        else -> draft    }    val canCapture = !busy && !terminal && shown.trim().isNotEmpty()    Column(        Modifier.fillMaxWidth()            .shadow(4.dp, RoundedCornerShape(CottonMetrics.cardRadius))            .background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius))            .padding(horizontal = CottonMetrics.contentMargin, vertical = 18.dp),        verticalArrangement = Arrangement.spacedBy(14.dp),    ) {        if (terminal) {            Text(                (state as CaptureState.Error).message,                Modifier.semantics { contentDescription = "Capture outcome uncertain" },                style = CottonTextStyles.body,                color = CottonPalette.statusWarning,            )        }        if (listening != null || finishing != null) {            Column(                Modifier.fillMaxWidth().semantics {                    contentDescription = if (finishing != null) {                        "Finishing dictation."                    } else {                        "Listening. Transcript updates as you speak."                    }                },                verticalArrangement = Arrangement.spacedBy(8.dp),            ) {                Text(                    if (finishing != null) "Finishing…" else "Listening",                    style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand),                    color = CottonPalette.statusError,                )                Text(                    shown.ifBlank { "Speak your thought…" },                    style = CottonTextStyles.body,                    color = if (shown.isBlank()) CottonPalette.inkSecondary else CottonPalette.inkBody,                )            }        } else {            OutlinedTextField(                value = draft,                onValueChange = onText,                enabled = !busy,                readOnly = terminal,                modifier = Modifier.fillMaxWidth().focusRequester(focus)                    .semantics { contentDescription = "Anything on your mind?" },                placeholder = { Text("Anything on your mind…") },                textStyle = CottonTextStyles.body,                minLines = 3,                maxLines = 8,            )        }        Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {            when {                listening != null -> {                    Text(                        "Stop",                        Modifier.clickable(role = Role.Button, onClick = onStop).padding(10.dp)                            .semantics { contentDescription = "Stop listening and keep these words" },                        style = CottonTextStyles.body,                        color = CottonPalette.inkSecondary,                    )                    Spacer(Modifier.weight(1f))                    ListeningIndicator()                    Text("Listening", Modifier.padding(start = 8.dp), style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)                }                finishing != null -> {                    Spacer(Modifier.weight(1f))                    Text("Finishing…", style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)                }                else -> {                    Text(                        "Listen",                        Modifier.clickable(enabled = !busy && !terminal, role = Role.Button, onClick = onListen).padding(10.dp)                            .semantics { contentDescription = "Speak a thought" },                        style = CottonTextStyles.body,                        color = if (busy || terminal) CottonPalette.inkTertiary else CottonPalette.accent,                    )                    Spacer(Modifier.weight(1f))                }            }            Text(                when {                    state is CaptureState.Saving -> "Capturing…"                    finishing != null -> "Finishing…"                    else -> "Capture"                },                Modifier.clickable(enabled = canCapture, role = Role.Button, onClick = onCapture)                    .semantics { contentDescription = "Capture this thought" }                    .padding(10.dp),                style = CottonTextStyles.body.copy(fontFamily = CottonFonts.type),                color = if (canCapture) CottonPalette.accent else CottonPalette.inkTertiary,            )        }    }}/** Android dictation exposes text only, so this is an honest state indicator. */@Composableprivate fun ListeningIndicator() = Box(    Modifier.size(8.dp)        .background(CottonPalette.statusError, CircleShape)        .semantics { contentDescription = "Listening" },)@Composableprivate fun CaptureError(message: String, onDismiss: () -> Unit) = AlertDialog(    onDismissRequest = onDismiss,    title = { Text("Couldn’t capture", fontFamily = CottonFonts.display) },    text = { Text(message, maxLines = 4, overflow = TextOverflow.Ellipsis) },    confirmButton = { TextButton(onClick = onDismiss) { Text("Keep editing") } },)private fun CaptureState.captureDraft(): String = when (this) {    is CaptureState.Idle -> draft    is CaptureState.Listening -> draft    is CaptureState.Finishing -> draft    is CaptureState.Saving -> draft    is CaptureState.Error -> draft    is CaptureState.Created -> ""}