@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) package com.cottondb.android.ui.settings import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement 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.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.OutlinedTextField 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.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberCoroutineScope 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.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import com.cottondb.android.design.CottonFonts import com.cottondb.android.design.CottonMetrics import com.cottondb.android.design.CottonTextStyles import com.cottondb.android.generated.CottonPalette import com.cottondb.android.settings.devices.ApprovedDevice import com.cottondb.android.settings.devices.DeviceCommand import com.cottondb.android.settings.devices.DeviceListRow import com.cottondb.android.settings.devices.DeviceWriteState import com.cottondb.android.settings.devices.DevicesModel import com.cottondb.android.settings.devices.DevicesSnapshot import com.cottondb.android.settings.devices.DevicesState import com.cottondb.android.settings.devices.PendingDevice import com.cottondb.android.settings.devices.OLD_SERVER_DIGITS import com.cottondb.android.settings.devices.addDeviceInstruction import com.cottondb.android.settings.devices.deviceDetail import com.cottondb.android.settings.devices.deviceListRows import com.cottondb.android.settings.devices.deviceStatus import com.cottondb.android.settings.devices.pairingDigitsForDisplay import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import java.time.Clock import java.time.Instant /** Settings > Your devices. Device membership writes stay in [DevicesModel]. */ @Composable fun 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(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() } } @Composable private 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, ) } } @Composable private 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, ) } } } @Composable private 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, ) } } @Composable private 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, ) } } } @Composable private 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") } }, ) } @Composable private 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(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") } }, ) } @Composable private 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() @Composable private 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 } }