Cotton code
540 lines · 20.8 KB · KotlinRaw
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)package com.cottondb.android.ui.settingsimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.safeDrawingPaddingimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.material3.pulltorefresh.PullToRefreshBoximport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.unit.dpimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonMetricsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport com.cottondb.android.settings.devices.ApprovedDeviceimport com.cottondb.android.settings.devices.DeviceCommandimport com.cottondb.android.settings.devices.DeviceListRowimport com.cottondb.android.settings.devices.DeviceWriteStateimport com.cottondb.android.settings.devices.DevicesModelimport com.cottondb.android.settings.devices.DevicesSnapshotimport com.cottondb.android.settings.devices.DevicesStateimport com.cottondb.android.settings.devices.PendingDeviceimport com.cottondb.android.settings.devices.OLD_SERVER_DIGITSimport com.cottondb.android.settings.devices.addDeviceInstructionimport com.cottondb.android.settings.devices.deviceDetailimport com.cottondb.android.settings.devices.deviceListRowsimport com.cottondb.android.settings.devices.deviceStatusimport com.cottondb.android.settings.devices.pairingDigitsForDisplayimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launchimport java.time.Clockimport java.time.Instant/** Settings > Your devices. Device membership writes stay in [DevicesModel]. */@Composablefun DevicesScreen(    model: DevicesModel,    writerScope: CoroutineScope,    databaseName: String?,    onBack: () -> Unit,    onOpenRejectedWrites: (() -> Unit)? = null,    onLeave: (() -> Unit)? = null,    initialPairingId: String? = null,    dataRevision: Long = 0L,    clock: Clock = Clock.systemUTC(),) {    val state by model.state.collectAsState()    val write by model.write.collectAsState()    val readScope = rememberCoroutineScope()    val snapshot = state.snapshot()    var showRemoved by rememberSaveable { mutableStateOf(false) }    var pairingId by rememberSaveable { mutableStateOf(initialPairingId) }    var deviceId by rememberSaveable { mutableStateOf<String?>(null) }    var showAddInstructions by rememberSaveable { mutableStateOf(false) }    var confirmLeave by rememberSaveable { mutableStateOf(false) }    LaunchedEffect(model, dataRevision) {        model.refresh()    }    LaunchedEffect(initialPairingId) {        if (initialPairingId != null) pairingId = initialPairingId    }    Column(        Modifier.fillMaxSize()            .background(CottonPalette.groundMuted)            .safeDrawingPadding(),    ) {        DevicesTopBar(onBack)        Text(            "Every device holds a full copy. Any device already in can let a new one join.",            Modifier.padding(horizontal = CottonMetrics.contentMargin, vertical = 8.dp),            style = CottonTextStyles.preview,            color = CottonPalette.inkSecondary,        )        PullToRefreshBox(            isRefreshing = (state as? DevicesState.Data)?.refreshing == true,            onRefresh = { readScope.launch { model.refresh() } },            modifier = Modifier.weight(1f),        ) {            when {                snapshot != null -> DevicesContent(                    snapshot = snapshot,                    showRemoved = showRemoved,                    readError = (state as? DevicesState.Error)?.message,                    write = write,                    onRefresh = { readScope.launch { model.refresh() } },                    onRetryWrite = { model.retry(writerScope) },                    onOpenPending = { pairingId = it },                    onOpenDevice = { deviceId = it },                    onToggleRemoved = { showRemoved = !showRemoved },                    onAddDevice = { showAddInstructions = true },                    onOpenRejectedWrites = onOpenRejectedWrites,                    onLeave = { confirmLeave = true },                    showLeave = onLeave != null,                    clock = clock,                )                state is DevicesState.Loading -> DevicesMessage("Loading devices…", null, null)                state is DevicesState.Error -> Column {                    DevicesMessage(                        "Devices could not be read",                        (state as DevicesState.Error).message,                        onRefresh = { readScope.launch { model.refresh() } },                    )                    TextButton(onClick = { showAddInstructions = true }) { Text("Add a device") }                    if (onLeave != null) {                        TextButton(onClick = { confirmLeave = true }) { Text("Leave this database on this phone") }                    }                }            }        }    }    val pairing = snapshot?.pending?.firstOrNull { it.pairingId == pairingId }    if (pairing != null) {        PendingDeviceDialog(            row = pairing,            saving = write is DeviceWriteState.Saving,            failure = pairingFailure(write, pairing),            onDismiss = { pairingId = null },            onApprove = { model.approve(pairing, writerScope) },            onDecline = { model.decline(pairing.pairingId, writerScope) },            onRetry = { model.retry(writerScope) },        )    }    val device = snapshot?.approved?.devices?.firstOrNull { it.deviceId == deviceId }    if (device != null) {        DeviceDialog(            device = device,            isThisDevice = device.deviceId == snapshot.approved.thisDevice,            saving = write is DeviceWriteState.Saving,            failure = deviceFailure(write, device),            onDismiss = { deviceId = null },            onRename = { name -> model.rename(device.deviceId, name, writerScope) },            onRevoke = { erase -> model.revoke(device.deviceId, erase, writerScope) },            onRetry = { model.retry(writerScope) },        )    }    if (showAddInstructions) {        AlertDialog(            onDismissRequest = { showAddInstructions = false },            title = { Text("Add a device") },            text = { Text(addDeviceInstruction(databaseName)) },            confirmButton = {                TextButton(onClick = { showAddInstructions = false }) { Text("Done") }            },        )    }    if (confirmLeave && onLeave != null) {        AlertDialog(            onDismissRequest = { confirmLeave = false },            title = { Text("Leave ${databaseName ?: "your database"} on this phone?") },            text = {                Text("This phone stops syncing and forgets the database. Your other devices keep their copies.")            },            confirmButton = {                TextButton(onClick = {                    confirmLeave = false                    onLeave()                }) {                    Text("Leave")                }            },            dismissButton = {                TextButton(onClick = { confirmLeave = false }) { Text("Keep") }            },        )    }    LaunchedEffect(write) {        val command = (write as? DeviceWriteState.Saved)?.command ?: return@LaunchedEffect        when (command) {            is DeviceCommand.Approve -> if (pairingId == command.row.pairingId) pairingId = null            is DeviceCommand.Decline -> if (pairingId == command.pairingId) pairingId = null            is DeviceCommand.Rename -> if (deviceId == command.deviceId) deviceId = null            is DeviceCommand.Revoke -> if (deviceId == command.deviceId) deviceId = null        }        model.acknowledgeSaved()    }}@Composableprivate fun DevicesTopBar(onBack: () -> Unit) {    Column(Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 8.dp)) {        Text(            "Back",            Modifier.clickable(role = Role.Button, onClick = onBack).padding(8.dp),            style = CottonTextStyles.preview,            color = CottonPalette.inkSecondary,        )        Text(            "Your devices",            Modifier.fillMaxWidth().padding(start = 8.dp),            style = CottonTextStyles.pageTitle.copy(fontFamily = CottonFonts.display),            color = CottonPalette.ink,        )    }}@Composableprivate fun DevicesContent(    snapshot: DevicesSnapshot,    showRemoved: Boolean,    readError: String?,    write: DeviceWriteState,    onRefresh: () -> Unit,    onRetryWrite: () -> Unit,    onOpenPending: (String) -> Unit,    onOpenDevice: (String) -> Unit,    onToggleRemoved: () -> Unit,    onAddDevice: () -> Unit,    onOpenRejectedWrites: (() -> Unit)?,    onLeave: () -> Unit,    showLeave: Boolean,    clock: Clock,) {    val rows = deviceListRows(        snapshot = snapshot,        showRemoved = showRemoved,        showRejectedWrites = onOpenRejectedWrites != null,        showLeave = showLeave,    )    LazyColumn(        Modifier.fillMaxSize(),        verticalArrangement = Arrangement.spacedBy(8.dp),    ) {        if (readError != null) {            item { DevicesError(readError, "Try again", onRefresh, "devices-read-error") }        }        if (write is DeviceWriteState.Failure) {            item { DevicesError(write.message, "Retry", onRetryWrite, "devices-write-error") }        }        items(rows, key = { it.key }) { row ->            DeviceRow(                row = row,                onOpenPending = onOpenPending,                onOpenDevice = onOpenDevice,                onToggleRemoved = onToggleRemoved,                onAddDevice = onAddDevice,                onOpenRejectedWrites = onOpenRejectedWrites,                onLeave = onLeave,                clock = clock,            )        }    }}@Composableprivate fun DevicesError(message: String, action: String, onAction: () -> Unit, tag: String) {    Row(        Modifier.fillMaxWidth()            .padding(horizontal = CottonMetrics.contentMargin)            .background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius))            .padding(12.dp)            .semantics { contentDescription = tag },        verticalAlignment = Alignment.CenterVertically,    ) {        Text(message, Modifier.weight(1f), style = CottonTextStyles.caption, color = CottonPalette.statusError)        Text(            action,            Modifier.clickable(role = Role.Button, onClick = onAction).padding(8.dp),            style = CottonTextStyles.preview,            color = CottonPalette.accent,        )    }}@Composableprivate fun DeviceRow(    row: DeviceListRow,    onOpenPending: (String) -> Unit,    onOpenDevice: (String) -> Unit,    onToggleRemoved: () -> Unit,    onAddDevice: () -> Unit,    onOpenRejectedWrites: (() -> Unit)?,    onLeave: () -> Unit,    clock: Clock,) {    val click: () -> Unit    val enabled: Boolean    val label: String    val detail: String?    val state: String?    when (row) {        is DeviceListRow.Pending -> {            click = { onOpenPending(row.device.pairingId) }            enabled = true            label = row.device.name ?: "New device"            detail = deviceDetail(row.device.platform, row.device.appVersion)            state = "approve"        }        is DeviceListRow.Approved -> {            click = { onOpenDevice(row.device.deviceId) }            enabled = !row.isRemoved            label = row.device.name ?: "Unnamed device"            detail = deviceDetail(row.device.platform, row.device.appVersion)            state = deviceStatus(                row.device,                row.isThisDevice,                clock.millis(),                ::parseTimestamp,            )        }        is DeviceListRow.RemovedToggle -> {            click = onToggleRemoved            enabled = true            label = row.label            detail = null            state = null        }        DeviceListRow.AddDevice -> {            click = onAddDevice            enabled = true            label = "Add a device"            detail = null            state = null        }        DeviceListRow.RejectedWrites -> {            click = onOpenRejectedWrites ?: {}            enabled = onOpenRejectedWrites != null            label = "Writes that did not land"            detail = null            state = null        }        DeviceListRow.Leave -> {            click = onLeave            enabled = true            label = "Leave this database on this phone"            detail = null            state = null        }    }    Row(        Modifier.fillMaxWidth()            .padding(horizontal = CottonMetrics.contentMargin)            .background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius))            .clickable(enabled = enabled, role = Role.Button, onClick = click)            .semantics { contentDescription = label }            .padding(14.dp),        verticalAlignment = Alignment.CenterVertically,    ) {        Column(Modifier.weight(1f)) {            Text(                label,                style = CottonTextStyles.body.copy(fontFamily = CottonFonts.display),                color = CottonPalette.ink,            )            detail?.let {                Text(it, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)            }        }        state?.let {            Text(                it,                style = CottonTextStyles.preview,                color = if (it == "approve") CottonPalette.statusError else CottonPalette.inkSecondary,            )        }    }}@Composableprivate fun PendingDeviceDialog(    row: PendingDevice,    saving: Boolean,    failure: String?,    onDismiss: () -> Unit,    onApprove: () -> Unit,    onDecline: () -> Unit,    onRetry: () -> Unit,) {    val digits = pairingDigitsForDisplay(row.digits)    AlertDialog(        onDismissRequest = { if (!saving) onDismiss() },        title = { Text("${row.name ?: "New device"} wants to join") },        text = {            Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {                deviceDetail(row.platform, row.appVersion)?.let { Text(it) }                if (digits == null) {                    Text(OLD_SERVER_DIGITS, color = CottonPalette.statusError)                } else {                    Text("Does it show $digits?")                    Text(digits, style = CottonTextStyles.editorTitle.copy(fontFamily = CottonFonts.type))                }                failure?.let { DialogWriteFailure(it, onRetry) }            }        },        confirmButton = {            TextButton(onClick = onApprove, enabled = digits != null && !saving) {                Text(if (saving) "Approving…" else "Approve")            }        },        dismissButton = {            TextButton(onClick = onDecline, enabled = !saving) { Text("No") }        },    )}@Composableprivate fun DeviceDialog(    device: ApprovedDevice,    isThisDevice: Boolean,    saving: Boolean,    failure: String?,    onDismiss: () -> Unit,    onRename: (String) -> Unit,    onRevoke: (Boolean) -> Unit,    onRetry: () -> Unit,) {    var name by rememberSaveable(device.deviceId) { mutableStateOf(device.name.orEmpty()) }    var erase by rememberSaveable(device.deviceId) { mutableStateOf<Boolean?>(null) }    val trimmedName = name.trim()    val canRename = trimmedName.isNotEmpty() && trimmedName != device.name && !saving    AlertDialog(        onDismissRequest = { if (!saving) onDismiss() },        title = { Text(device.name ?: "Device") },        text = {            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {                OutlinedTextField(                    value = name,                    onValueChange = { name = it.take(80) },                    label = { Text("Device name") },                    singleLine = true,                )                failure?.let { DialogWriteFailure(it, onRetry) }                if (isThisDevice) {                    Text("This is the phone you're using", color = CottonPalette.inkSecondary)                } else if (erase == null) {                    Text(                        "Remove leaves its existing copy alone. Remove and erase asks it to erase itself " +                            "when it next reaches a device.",                    )                    TextButton(onClick = { erase = false }, enabled = !saving) { Text("Remove this device") }                    TextButton(onClick = { erase = true }, enabled = !saving) { Text("Remove and erase") }                } else {                    Text("Remove ${device.name ?: "this device"}?")                    if (erase == true) {                        Text(                            "${device.name ?: "This device"} will erase itself the next time it reaches " +                                "any of your devices. If it never reconnects, this request cannot erase " +                                "its copy.",                            color = CottonPalette.statusError,                        )                    }                    Row {                        TextButton(onClick = { onRevoke(erase == true) }, enabled = !saving) {                            Text(if (erase == true) "Remove and erase" else "Remove")                        }                        TextButton(onClick = { erase = null }, enabled = !saving) { Text("Keep") }                    }                }            }        },        confirmButton = {            TextButton(onClick = { onRename(trimmedName) }, enabled = canRename) {                Text(if (saving) "Saving…" else "Rename")            }        },        dismissButton = {            TextButton(onClick = onDismiss, enabled = !saving) { Text("Done") }        },    )}@Composableprivate fun DevicesMessage(title: String, body: String?, onRefresh: (() -> Unit)?) {    Column(        Modifier.fillMaxWidth().padding(horizontal = CottonMetrics.contentMargin, vertical = 42.dp),        verticalArrangement = Arrangement.spacedBy(8.dp),    ) {        Text(title, style = CottonTextStyles.screenTitle, color = CottonPalette.ink)        body?.let { Text(it, style = CottonTextStyles.preview, color = CottonPalette.inkSecondary) }        onRefresh?.let { TextButton(onClick = it) { Text("Try again") } }    }}private fun DevicesState.snapshot(): DevicesSnapshot? = when (this) {    is DevicesState.Data -> value    is DevicesState.Error -> last    DevicesState.Loading -> null}private fun parseTimestamp(value: String): Long? = runCatching {    Instant.parse(value).toEpochMilli()}.getOrNull()@Composableprivate fun DialogWriteFailure(message: String, onRetry: () -> Unit) {    Row(verticalAlignment = Alignment.CenterVertically) {        Text(message, Modifier.weight(1f), style = CottonTextStyles.caption, color = CottonPalette.statusError)        TextButton(onClick = onRetry) { Text("Retry") }    }}private fun pairingFailure(write: DeviceWriteState, row: PendingDevice): String? {    val failure = write as? DeviceWriteState.Failure ?: return null    return when (val command = failure.command) {        is DeviceCommand.Approve -> if (command.row.pairingId == row.pairingId) failure.message else null        is DeviceCommand.Decline -> if (command.pairingId == row.pairingId) failure.message else null        else -> null    }}private fun deviceFailure(write: DeviceWriteState, device: ApprovedDevice): String? {    val failure = write as? DeviceWriteState.Failure ?: return null    return when (val command = failure.command) {        is DeviceCommand.Rename -> if (command.deviceId == device.deviceId) failure.message else null        is DeviceCommand.Revoke -> if (command.deviceId == device.deviceId) failure.message else null        else -> null    }}