package com.cottondb.android.ui.boot import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope 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.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Text 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.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.cottondb.android.boot.BootRefusal import com.cottondb.android.boot.BootState import com.cottondb.android.boot.JoinState import com.cottondb.android.design.ConstellationMark import com.cottondb.android.design.CottonFonts import com.cottondb.android.design.CottonMetrics import com.cottondb.android.design.CottonTextStyles import com.cottondb.android.generated.CottonPalette as GeneratedPalette /** * The app-root boot surface. It has no core dependency: the root collects the * two models and supplies every command, keeping one owner for native events. */ @Composable fun CottonBootGate( boot: BootState, join: JoinState, showJoin: Boolean, deviceName: String, appVersion: String, onShowJoin: () -> Unit, onStartLocal: (deviceName: String, appVersion: String) -> Unit, onJoin: (server: String, name: String, appVersion: String) -> Unit, onCancelJoin: () -> Unit, onRetry: () -> Unit, onSetName: (String) -> Unit, onErase: () -> Unit, onLeave: () -> Unit, readyContent: @Composable () -> Unit, modifier: Modifier = Modifier, ) { when (boot) { BootState.Waiting -> SplashWait(modifier) BootState.Start -> if (showJoin) { JoinScreen(join, appVersion, onJoin, onCancelJoin, onSetName, modifier) } else { StartScreen(deviceName, appVersion, onStartLocal, onShowJoin, modifier) } is BootState.Refused -> if (showJoin) { JoinScreen(join, appVersion, onJoin, onCancelJoin, onSetName, modifier) } else { RefusalScreen(boot.refusal, onRetry, onShowJoin, onErase, onLeave, modifier) } BootState.Opening -> ProgressPaper( title = "Still opening your database", body = "This takes a moment when the app was closed suddenly — Cotton is folding in the last changes you made. It will open by itself.", modifier = modifier, ) BootState.Bootstrapping -> ProgressPaper( title = "Downloading your database", body = "Your Cotton database is copying to this phone. This happens once, and it can take a few minutes on a big database — don't close the app.", modifier = modifier, ) is BootState.Error -> ErrorPaper(boot.message, onRetry, modifier) is BootState.Ready -> readyContent() } } @Composable private fun SplashWait(modifier: Modifier) { Box( modifier = modifier.fillMaxSize().background(GeneratedPalette.groundMuted), contentAlignment = Alignment.Center, ) { Column(horizontalAlignment = Alignment.CenterHorizontally) { ConstellationMark(Modifier.width(74.dp).height(106.dp)) Spacer(Modifier.height(20.dp)) CircularProgressIndicator( color = GeneratedPalette.inkTertiary, strokeWidth = CottonMetrics.hairline, modifier = Modifier.width(22.dp).height(22.dp), ) } } } @Composable private fun StartScreen( deviceName: String, appVersion: String, onStartLocal: (String, String) -> Unit, onShowJoin: () -> Unit, modifier: Modifier, ) = BootFrame(modifier) { Masthead() PaperSheet { Text( "Your life, in a database you own. It lives on your devices and nowhere else.", style = CottonTextStyles.body, color = GeneratedPalette.inkBody, ) Spacer(Modifier.height(18.dp)) InkPill("Start a new database", "Start a new database") { onStartLocal(deviceName, appVersion) } Spacer(Modifier.height(14.dp)) PaperLine() QuietAction("Join my database", "Join my database", onShowJoin) Text( "Already have Cotton on a Mac or a phone? Join.", modifier = Modifier.padding(top = 14.dp), fontFamily = CottonFonts.hand, fontSize = 19.sp, color = GeneratedPalette.inkSecondary, ) } } @Composable private fun JoinScreen( state: JoinState, appVersion: String, onJoin: (String, String, String) -> Unit, onCancel: () -> Unit, onSetName: (String) -> Unit, modifier: Modifier, ) = BootFrame(modifier) { Masthead() PaperSheet { when (state) { is JoinState.Form -> { JoinForm(state, appVersion, onJoin) Spacer(Modifier.height(14.dp)) PaperLine() QuietAction("Back", "Back", onCancel) } is JoinState.Pending -> PendingApproval(state, onCancel) JoinState.Opening -> OpeningJoin() is JoinState.Joined -> if (state.needsName) NameForm(state.error, onSetName) else OpeningJoin() } } } @Composable private fun JoinForm( state: JoinState.Form, appVersion: String, onJoin: (String, String, String) -> Unit, ) { var server by remember { mutableStateOf(state.server) } var name by remember { mutableStateOf(state.name) } var localError by remember { mutableStateOf(null) } val nameFocus = remember { FocusRequester() } val focus = LocalFocusManager.current LaunchedEffect(state.server, state.name, state.busy) { if (!state.busy) { server = state.server name = state.name } } fun submit() { if (server.trim().isEmpty()) { localError = "That's not a name or an address — type the short name your other device shows, or its full https:// address" } else if (name.trim().isEmpty()) { localError = "Give this phone a name" } else { localError = null focus.clearFocus() onJoin(server.trim(), name.trim(), appVersion) } } Text("Join your Cotton", style = CottonTextStyles.screenTitle, color = GeneratedPalette.ink) Spacer(Modifier.height(10.dp)) Text( "Type the name your other device shows. Open Cotton there — the name is on its Settings, under Your devices. An address works too, if your database has no internet name.", style = CottonTextStyles.preview, color = GeneratedPalette.inkBody, ) Spacer(Modifier.height(18.dp)) RuledField( label = "The name your other device shows", value = server, onValueChange = { server = it }, hint = "such as home — or a full https:// address", keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.None, imeAction = ImeAction.Next), onImeAction = { nameFocus.requestFocus() }, ) Spacer(Modifier.height(14.dp)) RuledField( label = "This phone's name", value = name, onValueChange = { name = it }, focusRequester = nameFocus, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences, imeAction = ImeAction.Done), onImeAction = ::submit, ) val error = localError ?: state.error Spacer(Modifier.height(18.dp)) Row(verticalAlignment = Alignment.CenterVertically) { if (error != null) Text(error, Modifier.weight(1f), style = CottonTextStyles.preview, color = GeneratedPalette.statusError) else if (state.busy) Text("Joining…", Modifier.weight(1f), fontFamily = CottonFonts.hand, fontSize = 20.sp, color = GeneratedPalette.ink) else Spacer(Modifier.weight(1f)) CircleAction(if (state.busy) "Joining…" else "Join", enabled = !state.busy, ::submit) } } @Composable private fun PendingApproval(state: JoinState.Pending, onCancel: () -> Unit) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Text("Asking ${state.server?.ifBlank { null } ?: "your other device"}", style = CottonTextStyles.screenTitle, color = GeneratedPalette.ink) Spacer(Modifier.height(18.dp)) Text( state.digits, modifier = Modifier.semantics { contentDescription = "Server digits ${state.digits}" } .clip(RoundedCornerShape(12.dp)).background(GeneratedPalette.groundElevated).border(CottonMetrics.hairline, GeneratedPalette.hairline, RoundedCornerShape(12.dp)).padding(horizontal = 18.dp, vertical = 12.dp), fontFamily = CottonFonts.type, fontSize = 30.sp, color = GeneratedPalette.ink, ) Spacer(Modifier.height(18.dp)) Text( "Approve this phone on any of your devices. It will ask if the phone shows these numbers.", style = CottonTextStyles.body, color = GeneratedPalette.inkBody, ) Spacer(Modifier.height(18.dp)) PaperLine() QuietAction("Cancel", "Cancel joining", onCancel) } } @Composable private fun OpeningJoin() = Column(horizontalAlignment = Alignment.CenterHorizontally) { CircularProgressIndicator(color = GeneratedPalette.ink, strokeWidth = CottonMetrics.hairline) Spacer(Modifier.height(16.dp)) Text("Bringing your records together…", fontFamily = CottonFonts.hand, fontSize = 20.sp, color = GeneratedPalette.ink) } @Composable private fun NameForm(error: String?, onSetName: (String) -> Unit) { var name by remember { mutableStateOf("") } Text("What should we call you?", style = CottonTextStyles.screenTitle, color = GeneratedPalette.ink) Spacer(Modifier.height(10.dp)) Text("Just how things read back to you. Change it any time.", style = CottonTextStyles.preview, color = GeneratedPalette.inkBody) Spacer(Modifier.height(18.dp)) RuledField("", name, { name = it }, placeholder = "Enter name", keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), onImeAction = { onSetName(name) }) if (error != null) { Spacer(Modifier.height(10.dp)) Text(error, style = CottonTextStyles.preview, color = GeneratedPalette.statusError) } Spacer(Modifier.height(18.dp)) InkPill("Continue", "Continue") { onSetName(name) } } @Composable private fun RefusalScreen( refusal: BootRefusal, onRetry: () -> Unit, onJoin: () -> Unit, onErase: () -> Unit, onLeave: () -> Unit, modifier: Modifier, ) = BootFrame(modifier) { PaperSheet { Text(refusalReason(refusal.code).uppercase(), style = CottonTextStyles.sectionLabel, color = GeneratedPalette.statusError) Spacer(Modifier.height(10.dp)) Text(refusalTitle(refusal.code), style = CottonTextStyles.screenTitle, color = GeneratedPalette.ink) Spacer(Modifier.height(10.dp)) PaperLine(GeneratedPalette.statusError) Spacer(Modifier.height(10.dp)) Text(refusal.sentence ?: refusalBody(refusal.code), style = CottonTextStyles.preview, color = GeneratedPalette.inkBody) Spacer(Modifier.height(20.dp)) InkPill("Try again", "Try again", onRetry) if (refusal.code == "device_revoked") { Spacer(Modifier.height(12.dp)) PaperLine() QuietAction("Keep my copy", "Keep my copy", onJoin) QuietAction("Erase Cotton from this phone", "Erase Cotton from this phone", onErase, GeneratedPalette.statusError) } else if (refusal.code == "scope_refused") { Spacer(Modifier.height(12.dp)) PaperLine() QuietAction("Leave this database", "Leave this database", onLeave, GeneratedPalette.statusError) } } } @Composable private fun ProgressPaper(title: String, body: String, modifier: Modifier) = BootFrame(modifier) { PaperSheet { CircularProgressIndicator(color = GeneratedPalette.inkTertiary, strokeWidth = CottonMetrics.hairline) Spacer(Modifier.height(16.dp)) Text(title, style = CottonTextStyles.screenTitle, color = GeneratedPalette.ink) Spacer(Modifier.height(10.dp)) PaperLine() Spacer(Modifier.height(10.dp)) Text(body, style = CottonTextStyles.preview, color = GeneratedPalette.inkBody) } } @Composable private fun ErrorPaper(message: String, onRetry: () -> Unit, modifier: Modifier) = BootFrame(modifier) { PaperSheet { Text("Something went wrong", style = CottonTextStyles.screenTitle, color = GeneratedPalette.ink) Spacer(Modifier.height(10.dp)) Text(message, style = CottonTextStyles.caption, color = GeneratedPalette.inkTertiary) Spacer(Modifier.height(18.dp)) InkPill("Try again", "Try again", onRetry) } } @Composable private fun BootFrame(modifier: Modifier, content: @Composable ColumnScope.() -> Unit) { Column( modifier = modifier.fillMaxSize().background(GeneratedPalette.groundMuted).statusBarsPadding().navigationBarsPadding() .verticalScroll(rememberScrollState()).padding(horizontal = CottonMetrics.settingsMargin, vertical = 24.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { content() } } @Composable private fun Masthead() { Spacer(Modifier.height(24.dp)) ConstellationMark(Modifier.width(74.dp).height(106.dp)) Spacer(Modifier.height(14.dp)) Text("Cotton", fontFamily = CottonFonts.display, fontSize = 34.sp, color = GeneratedPalette.ink) Spacer(Modifier.height(24.dp)) } @Composable private fun PaperSheet(content: @Composable ColumnScope.() -> Unit) { Column( modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(CottonMetrics.cardRadius)).background(GeneratedPalette.ground) .border(CottonMetrics.hairline, GeneratedPalette.hairline, RoundedCornerShape(CottonMetrics.cardRadius)).padding(24.dp), content = content, ) } @Composable private fun InkPill(label: String, description: String, action: () -> Unit) { Text( label, modifier = Modifier.clip(RoundedCornerShape(30.dp)).background(GeneratedPalette.ink).clickable(onClick = action) .semantics { contentDescription = description }.padding(horizontal = 22.dp, vertical = 14.dp), fontFamily = CottonFonts.type, fontSize = 16.sp, color = GeneratedPalette.ground, ) } @Composable private fun CircleAction(label: String, enabled: Boolean, action: () -> Unit) { Text( "→", modifier = Modifier.clip(CircleShape).background(if (enabled) GeneratedPalette.ink else GeneratedPalette.inkTertiary) .clickable(enabled = enabled, onClick = action).semantics { contentDescription = label }.padding(horizontal = 17.dp, vertical = 13.dp), fontSize = 20.sp, color = GeneratedPalette.ground, ) } @Composable private fun QuietAction(label: String, description: String, action: () -> Unit, color: Color = GeneratedPalette.ink) { Row(modifier = Modifier.fillMaxWidth().clickable(onClick = action).semantics { contentDescription = description }.padding(vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) { Text(label, Modifier.weight(1f), fontFamily = CottonFonts.type, fontSize = 15.sp, color = color) Text("→", fontSize = 16.sp, color = color) } } @Composable private fun PaperLine(color: Color = GeneratedPalette.hairline) = HorizontalDivider(thickness = CottonMetrics.hairline, color = color) @Composable private fun RuledField( label: String, value: String, onValueChange: (String) -> Unit, hint: String? = null, placeholder: String? = null, focusRequester: FocusRequester? = null, keyboardOptions: KeyboardOptions, onImeAction: () -> Unit, ) { if (label.isNotEmpty()) Text(label, fontFamily = CottonFonts.typeItalic, fontSize = 13.sp, color = GeneratedPalette.inkSecondary) BasicTextField( value = value, onValueChange = onValueChange, modifier = Modifier.fillMaxWidth().then(if (focusRequester != null) Modifier.focusRequester(focusRequester) else Modifier).padding(vertical = 7.dp), textStyle = TextStyle(fontFamily = CottonFonts.type, fontSize = 17.sp, color = GeneratedPalette.ink), keyboardOptions = keyboardOptions, keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { onImeAction() }, onNext = { onImeAction() }), decorationBox = { inner -> if (value.isEmpty() && placeholder != null) Text(placeholder, fontFamily = CottonFonts.type, fontSize = 17.sp, color = GeneratedPalette.inkTertiary); inner() }, ) PaperLine() if (hint != null) Text(hint, Modifier.padding(top = 4.dp), fontFamily = CottonFonts.typeItalic, fontSize = 12.sp, color = GeneratedPalette.inkSecondary) } private fun refusalReason(code: String): String = when (code) { "device_not_approved" -> "Not approved" "device_revoked" -> "Removed from your server" "device_bad_signature" -> "Key not accepted" "device_key_unreadable", "no_device_key" -> "Key unreadable" "device_clock" -> "Clock out of step" "rate_limited" -> "Paused by your server" "snapshot_stalled" -> "No data for a minute" "upgrade_required" -> "This build is out of date" else -> "Could not open" } private fun refusalTitle(code: String): String = when (code) { "device_not_approved" -> "This phone isn't approved yet" "device_revoked" -> "This phone was removed" "device_bad_signature" -> "Your server didn't recognise this phone" "device_clock" -> "Check the clock" "upgrade_required" -> "Update Cotton to keep syncing" else -> "We couldn't open your Cotton" } private fun refusalBody(code: String): String = when (code) { "device_not_approved" -> "Your server only opens for devices you've approved. Join again, then say yes on any device that's already in." "device_revoked" -> "Someone removed this phone from your server. The copy on this phone is untouched — keep it and join again when you're ready, or erase Cotton from this phone." "device_bad_signature" -> "Your server didn't accept this phone's signature — it hasn't approved this phone's key for that address. Join again from your Mac to pair it afresh." "device_clock" -> "This phone's clock or your Mac's is off by more than two minutes, so the server can't tell a fresh request from an old one. Fix the time and try again." "upgrade_required" -> "This build is older than your data. Update Cotton, then try again." else -> "Your data is safe — we just couldn't reach it. Try again in a moment." }