Modern Apps git

← Modern-Apps.git

email: add-account form is a route (#nav)

Commit
dd8d05af365fc2a9ce774a09ddd08ee736e50e63
Author
Vayun Mathur <[email protected]>
When
2026-11-16 21:32 UTC (19 days ago)
Parents
a3f5686
Replace AddAccountScreen's selectedProviderId picker-to-form swap
and its hand-rolled BackHandler with a pushed destination:
Route.AddAccountForm(providerId) carries the picked provider, the
picker stays Route.AddAccount, and Back from the form is a plain
stack pop to the picker.

The Outlook OAuth and app-password forms move verbatim into the new
AddAccountFormScreen; an unknown provider id (a stale restored
destination) pops straight back. The two destinations are registered
by a shared addAccountEntries helper used by both the main graph and
the first-run gate in MainContent, which now hosts them on a
gate-local stack (the gate previously rendered the combined screen
outside any navigation); the gate picker keeps its no-back
presentation, and saving there still relies on the accounts flow to
swap the gate for the main graph.

Tests: AddAccountScreenTest and AddAccountSubmitTest now host the
real destinations on a NavBackStack via MainNavigation and assert
the push (Route.AddAccountForm(gmail) on top after picking) and the
pop back to the picker; the screenshot preview renders the picker
with its new callback.

Verified on devvm21958 (no push):
- ./gradlew :email:compileDevKotlin :email:testDevUnitTest — green

Diff

email/src/main/java/com/vayunmathur/email/Navigation.kt
diff --git a/email/src/main/java/com/vayunmathur/email/Navigation.kt b/email/src/main/java/com/vayunmathur/email/Navigation.ktindex a899eb9606..8545ba44a5 100644--- a/email/src/main/java/com/vayunmathur/email/Navigation.kt+++ b/email/src/main/java/com/vayunmathur/email/Navigation.kt@@ -8,6 +8,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.email.platform.EmailViewModel import com.vayunmathur.email.platform.IntentState+import com.vayunmathur.email.ui.AddAccountFormScreen import com.vayunmathur.email.ui.AddAccountScreen import com.vayunmathur.email.ui.ComposerScreen import com.vayunmathur.email.ui.DraftsScreen@@ -168,9 +169,7 @@ private fun EntryProviderScope<Route>.miscEntries(         entry<Route.Outbox>(metadata = ListDetailPage()) {             OutboxScreen(viewModel = viewModel, onBack = { backStack.pop() })         }-        entry<Route.AddAccount>(metadata = ListDetailPage()) {-            AddAccountScreen(onBack = { backStack.pop() }, onAccountAdded = { backStack.pop() })-        }+        addAccountEntries(backStack, onAccountAdded = { backStack.pop() })         entry<Route.Settings>(metadata = ListDetailPage()) {             SettingsScreen(viewModel = viewModel, onBack = { backStack.pop() })         }@@ -191,3 +190,34 @@ private fun EntryProviderScope<Route>.miscEntries(             )         }     }++/**+ * The add-account destinations, shared by the main graph and the+ * first-run gate in `MainContent` (which hosts them on its own stack+ * before any account exists to navigate with).+ *+ * Picking a provider pushes [Route.AddAccountForm] carrying the provider+ * id; Back from the form is the stack pop back to the picker, and+ * [onAccountAdded] decides where a saved account goes next (pop in the+ * main graph, nothing at the gate — the accounts flow swaps the gate for+ * the graph on its own).+ */+internal fun EntryProviderScope<Route>.addAccountEntries(+    backStack: NavBackStack<Route>,+    onPickBack: (() -> Unit)? = { backStack.pop() },+    onAccountAdded: () -> Unit,+) {+    entry<Route.AddAccount>(metadata = ListDetailPage()) {+        AddAccountScreen(+            onBack = onPickBack,+            onPickProvider = { providerId -> backStack.add(Route.AddAccountForm(providerId)) },+        )+    }+    entry<Route.AddAccountForm>(metadata = ListDetailPage()) { route ->+        AddAccountFormScreen(+            providerId = route.providerId,+            onBack = { backStack.pop() },+            onAccountAdded = onAccountAdded,+        )+    }+}
email/src/main/java/com/vayunmathur/email/Route.kt
diff --git a/email/src/main/java/com/vayunmathur/email/Route.kt b/email/src/main/java/com/vayunmathur/email/Route.ktindex 0fdbcca588..e2e285b094 100644--- a/email/src/main/java/com/vayunmathur/email/Route.kt+++ b/email/src/main/java/com/vayunmathur/email/Route.kt@@ -29,9 +29,12 @@ sealed interface Route : NavKey {     /** Destination showing saved drafts. */     object Drafts : Route     @Serializable-    /** Destination for adding a new mail account. */+    /** Destination for adding a new mail account (the provider picker). */     object AddAccount : Route     @Serializable+    /** Destination for the account form of the provider picked on [AddAccount]. */+    data class AddAccountForm(val providerId: String) : Route+    @Serializable     /** Destination showing email settings. */     object Settings : Route     @Serializable
email/src/main/java/com/vayunmathur/email/ui/AddAccountFormScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/AddAccountFormScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/AddAccountFormScreen.ktnew file mode 100644index 0000000000..8e54903239--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/ui/AddAccountFormScreen.kt@@ -0,0 +1,291 @@+package com.vayunmathur.email.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+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.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.foundation.verticalScroll+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.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.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.input.PasswordVisualTransformation+import androidx.compose.ui.unit.dp+import com.vayunmathur.email.R+import com.vayunmathur.email.data.OutlookOAuth+import com.vayunmathur.email.data.PROVIDER_CUSTOM+import com.vayunmathur.email.data.PROVIDER_OUTLOOK+import com.vayunmathur.email.data.PROVIDER_PRESETS+import com.vayunmathur.email.data.ProviderPreset+import com.vayunmathur.email.platform.ServerConfig+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Checkbox+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.ElevatedCard+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.AppMessages+import kotlinx.coroutines.launch++/**+ * Add-account form for one provider (`Route.AddAccountForm(providerId)`):+ * Outlook OAuth for Outlook, app password for the rest. Pushed by the+ * provider picker, so Back is a plain stack pop to the picker. An unknown+ * provider id (a stale restored destination) pops straight back.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun AddAccountFormScreen(+    providerId: String,+    onBack: (() -> Unit)?,+    onAccountAdded: () -> Unit,+) {+    val selectedProvider = PROVIDER_PRESETS.firstOrNull { it.id == providerId }+    if (selectedProvider == null) {+        LaunchedEffect(providerId) { onBack?.invoke() }+        return+    }+    AppScaffold(+        title = selectedProvider.displayName,+        navigationIcon = {+            if (onBack != null) { IconNavigation(onBack) }+        },+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        Box(Modifier.padding(padding).fillMaxSize()) {+            if (selectedProvider.id == PROVIDER_OUTLOOK) {+                OutlookOAuthForm(+                    preset = selectedProvider,+                    onAccountAdded = onAccountAdded,+                )+            } else {+                PasswordForm(+                    preset = selectedProvider,+                    onAccountAdded = onAccountAdded,+                )+            }+        }+    }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun OutlookOAuthForm(+    preset: ProviderPreset,+    onAccountAdded: () -> Unit,+) {+    val context = LocalContext.current+    val scope = rememberCoroutineScope()+    val accountAddedMsg = stringResource(R.string.account_added)+    var emailHint by rememberSaveable { mutableStateOf("") }+    var useAppPassword by rememberSaveable { mutableStateOf(false) }+    var appPassword by rememberSaveable { mutableStateOf("") }+    var appPasswordVisible by rememberSaveable { mutableStateOf(false) }+    var working by remember { mutableStateOf(false) }+    var error by remember { mutableStateOf<String?>(null) }++    Column(+        Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),+        verticalArrangement = Arrangement.spacedBy(16.dp),+    ) {+        ElevatedCard(Modifier.fillMaxWidth()) {+            Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {+                Text(stringResource(R.string.sign_in_with, preset.displayName), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)+                preset.instructions.forEach { line -> Text("• $line", style = MaterialTheme.typography.bodySmall) }+                Spacer(Modifier.height(4.dp))+                Text("Client: ${com.vayunmathur.email.BuildConfig.OUTLOOK_OAUTH_CLIENT_ID.take(12)}… Redirect: com.vayunmathur.email://oauth", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+            }+        }++        OutlinedTextField(+            value = emailHint,+            onValueChange = { emailHint = it.trim() },+            label = { Text(stringResource(R.string.email_address_optional)) },+            placeholder = { Text("Optional — pre-fills Microsoft login") },+            singleLine = true,+            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),+            modifier = Modifier.fillMaxWidth(),+        )++        Button(+            onClick = { OutlookOAuth.start(context, emailHint) },+            modifier = Modifier.fillMaxWidth(),+        ) {+            Text(stringResource(R.string.sign_in_with, preset.displayName))+        }++        HorizontalDivider()++        Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clickable { useAppPassword = !useAppPassword }) {+            Checkbox(checked = useAppPassword, onCheckedChange = { useAppPassword = it })+            Text(stringResource(R.string.use_app_password_instead), style = MaterialTheme.typography.bodyMedium)+        }++        if (useAppPassword) {+            OutlinedTextField(+                value = appPassword,+                onValueChange = { appPassword = it },+                label = { Text(stringResource(R.string.app_password)) },+                singleLine = true,+                visualTransformation = if (appPasswordVisible) androidx.compose.ui.text.input.VisualTransformation.None else PasswordVisualTransformation(),+                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),+                trailingIcon = {+                    TextButton(onClick = { appPasswordVisible = !appPasswordVisible }) {+                        Text(if (appPasswordVisible) stringResource(R.string.hide) else stringResource(R.string.show))+                    }+                },+                modifier = Modifier.fillMaxWidth(),+            )++            if (error != null) {+                Text(error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)+            }++            Button(+                enabled = !working && emailHint.isNotBlank() && appPassword.isNotBlank(),+                onClick = {+                    error = null; working = true+                    scope.launch {+                        val result = testAndPersistAccount(+                            context = context,+                            providerId = preset.id,+                            email = emailHint,+                            username = "",+                            password = appPassword,+                            imap = preset.imap ?: ServerConfig("outlook.office365.com", 993, true),+                            smtp = preset.smtp ?: ServerConfig("smtp-mail.outlook.com", 587, false),+                        )+                        working = false+                        if (result == null) {+                            AppMessages.show(accountAddedMsg); onAccountAdded()+                        } else error = result+                    }+                },+                modifier = Modifier.fillMaxWidth(),+            ) {+                if (working) {+                    CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)+                    Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.testing_connection))+                } else Text(stringResource(R.string.test_connection_and_save))+            }+        }++        preset.appPasswordHelpUrl?.let { url ->+            TextButton(onClick = { openUrl(context, url) }) { Text(stringResource(R.string.open_app_password_help, preset.displayName)) }+        }+    }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun PasswordForm(+    preset: ProviderPreset,+    onAccountAdded: () -> Unit,+) {+    val context = LocalContext.current+    val scope = rememberCoroutineScope()+    val accountAddedMsg = stringResource(R.string.account_added)++    var email by rememberSaveable { mutableStateOf("") }+    var useDifferentUsername by rememberSaveable { mutableStateOf(false) }+    var username by rememberSaveable { mutableStateOf("") }+    var password by rememberSaveable { mutableStateOf("") }+    var passwordVisible by rememberSaveable { mutableStateOf(false) }++    var imapHost by rememberSaveable { mutableStateOf(preset.imap?.host ?: "") }+    var imapPort by rememberSaveable { mutableStateOf((preset.imap?.port ?: 993).toString()) }+    var imapUseSsl by rememberSaveable { mutableStateOf(preset.imap?.useSsl ?: true) }+    var smtpHost by rememberSaveable { mutableStateOf(preset.smtp?.host ?: "") }+    var smtpPort by rememberSaveable { mutableStateOf((preset.smtp?.port ?: 465).toString()) }+    var smtpUseSsl by rememberSaveable { mutableStateOf(preset.smtp?.useSsl ?: true) }++    var working by remember { mutableStateOf(false) }+    var error by remember { mutableStateOf<String?>(null) }++    Column(+        Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),+        verticalArrangement = Arrangement.spacedBy(12.dp),+    ) {+        if (preset.instructions.isNotEmpty()) { InstructionsCard(preset = preset) }++        OutlinedTextField(value = email, onValueChange = { email = it.trim() }, label = { Text(stringResource(R.string.email_address)) }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email), modifier = Modifier.fillMaxWidth())+        if (preset.id == PROVIDER_CUSTOM) {+            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clickable { useDifferentUsername = !useDifferentUsername }) {+                Checkbox(checked = useDifferentUsername, onCheckedChange = { useDifferentUsername = it })+                Text(stringResource(R.string.username_is_not_my_email), style = MaterialTheme.typography.bodyMedium)+            }+            if (useDifferentUsername) {+                OutlinedTextField(value = username, onValueChange = { username = it.trim() }, label = { Text(stringResource(R.string.username)) }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Ascii), modifier = Modifier.fillMaxWidth())+            }+        }+        OutlinedTextField(+            value = password,+            onValueChange = { password = it },+            label = { Text(if (preset.id == PROVIDER_CUSTOM) stringResource(R.string.password) else stringResource(R.string.app_password)) },+            singleLine = true,+            visualTransformation = if (passwordVisible) androidx.compose.ui.text.input.VisualTransformation.None else PasswordVisualTransformation(),+            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),+            trailingIcon = {+                TextButton(onClick = { passwordVisible = !passwordVisible }) { Text(if (passwordVisible) stringResource(R.string.hide) else stringResource(R.string.show)) }+            },+            modifier = Modifier.fillMaxWidth(),+        )++        if (preset.id == PROVIDER_CUSTOM) {+            Text(stringResource(R.string.imap_incoming), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)+            AddAccountSection(host = imapHost, onHostChange = { imapHost = it.trim() }, port = imapPort, onPortChange = { imapPort = it.filter(Char::isDigit) }, useSsl = imapUseSsl, onSslChange = { imapUseSsl = it })+            Text(stringResource(R.string.smtp_outgoing), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)+            AddAccountSection(host = smtpHost, onHostChange = { smtpHost = it.trim() }, port = smtpPort, onPortChange = { smtpPort = it.filter(Char::isDigit) }, useSsl = smtpUseSsl, onSslChange = { smtpUseSsl = it })+        }++        if (error != null) {+            Text(error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)+        }++        Button(+            enabled = !working && email.isNotBlank() && password.isNotBlank() && (preset.id != PROVIDER_CUSTOM || (imapHost.isNotBlank() && smtpHost.isNotBlank() && imapPort.isNotBlank() && smtpPort.isNotBlank())),+            onClick = {+                error = null; working = true+                scope.launch {+                    val imap = preset.imap ?: ServerConfig(imapHost, imapPort.toIntOrNull() ?: 993, imapUseSsl)+                    val smtp = preset.smtp ?: ServerConfig(smtpHost, smtpPort.toIntOrNull() ?: 465, smtpUseSsl)+                    val result = testAndPersistAccount(context = context, providerId = preset.id, email = email, username = if (useDifferentUsername) username else "", password = password, imap = imap, smtp = smtp)+                    working = false+                    if (result == null) { AppMessages.show(accountAddedMsg); onAccountAdded() } else error = result+                }+            },+            modifier = Modifier.fillMaxWidth(),+        ) {+            if (working) {+                CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.testing_connection))+            } else Text(stringResource(R.string.test_connection_and_save))+        }+    }+}
email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.ktindex e4dcbc8cc6..e51bee6285 100644--- a/email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/AddAccountScreen.kt@@ -1,107 +1,50 @@ package com.vayunmathur.email.ui -import androidx.compose.foundation.clickable-import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column-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.padding-import androidx.compose.foundation.layout.size-import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.rememberCoroutineScope-import androidx.compose.runtime.saveable.rememberSaveable-import androidx.compose.runtime.setValue import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.Checkbox-import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.ElevatedCard import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.appBarScrollBehavior-import com.vayunmathur.library.util.AppMessages-import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource-import androidx.compose.ui.text.font.FontWeight-import androidx.compose.ui.text.input.KeyboardType-import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import com.vayunmathur.email.R-import com.vayunmathur.email.data.EmailAccount-import com.vayunmathur.email.platform.EmailManager-import com.vayunmathur.email.platform.ServerConfig-import com.vayunmathur.email.data.CredentialCrypto-import com.vayunmathur.email.data.EmailRepository-import com.vayunmathur.email.data.EmailSyncWorker-import com.vayunmathur.email.data.ImapIdleService-import com.vayunmathur.email.data.OutlookOAuth import com.vayunmathur.email.data.PROVIDER_CUSTOM import com.vayunmathur.email.data.PROVIDER_OUTLOOK import com.vayunmathur.email.data.PROVIDER_PRESETS import com.vayunmathur.email.data.ProviderPreset-import com.vayunmathur.library.ui.IconNavigation-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext  /**- * Add-account flow: OAuth for Outlook (Microsoft), app password for others.- * Raw IMAP/SMTP via [com.vayunmathur.email.imap]/[com.vayunmathur.email.smtp].+ * Add-account provider picker (`Route.AddAccount`): picking a provider+ * pushes `Route.AddAccountForm(providerId)`, so Back from the form is a+ * plain stack pop to this picker — no in-screen step state or hand-rolled+ * BackHandler. The forms themselves live in [AddAccountFormScreen].  */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun AddAccountScreen(     onBack: (() -> Unit)?,-    onAccountAdded: () -> Unit,+    onPickProvider: (String) -> Unit, ) {-    var selectedProviderId by rememberSaveable { mutableStateOf<String?>(null) }-    val selectedProvider = selectedProviderId?.let { id -> PROVIDER_PRESETS.firstOrNull { it.id == id } }--    androidx.activity.compose.BackHandler(enabled = selectedProvider != null) { selectedProviderId = null }-     AppScaffold(-        title = if (selectedProvider == null) stringResource(R.string.add_account) else selectedProvider.displayName,+        title = stringResource(R.string.add_account),         navigationIcon = {-            val backTarget: (() -> Unit)? = when {-                selectedProvider != null -> ({ selectedProviderId = null })-                else -> onBack-            }-            if (backTarget != null) { IconNavigation(backTarget) }+            if (onBack != null) { IconNavigation(onBack) }         },         scrollBehavior = appBarScrollBehavior(),     ) { padding ->         Box(Modifier.padding(padding).fillMaxSize()) {-            if (selectedProvider == null) {-                ProviderPicker(onPick = { selectedProviderId = it.id })-            } else if (selectedProvider.id == PROVIDER_OUTLOOK) {-                OutlookOAuthForm(-                    preset = selectedProvider,-                    onAccountAdded = onAccountAdded,-                )-            } else {-                PasswordForm(-                    preset = selectedProvider,-                    onAccountAdded = onAccountAdded,-                )-            }+            ProviderPicker(onPick = { onPickProvider(it.id) })         }     } }@@ -130,198 +73,3 @@ private fun ProviderPicker(onPick: (ProviderPreset) -> Unit) {         }     } }--@OptIn(ExperimentalMaterial3Api::class)-@Composable-private fun OutlookOAuthForm(-    preset: ProviderPreset,-    onAccountAdded: () -> Unit,-) {-    val context = LocalContext.current-    val scope = rememberCoroutineScope()-    val accountAddedMsg = stringResource(R.string.account_added)-    var emailHint by rememberSaveable { mutableStateOf("") }-    var useAppPassword by rememberSaveable { mutableStateOf(false) }-    var appPassword by rememberSaveable { mutableStateOf("") }-    var appPasswordVisible by rememberSaveable { mutableStateOf(false) }-    var working by remember { mutableStateOf(false) }-    var error by remember { mutableStateOf<String?>(null) }--    Column(-        Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),-        verticalArrangement = Arrangement.spacedBy(16.dp),-    ) {-        ElevatedCard(Modifier.fillMaxWidth()) {-            Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {-                Text(stringResource(R.string.sign_in_with, preset.displayName), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)-                preset.instructions.forEach { line -> Text("• $line", style = MaterialTheme.typography.bodySmall) }-                Spacer(Modifier.height(4.dp))-                Text("Client: ${com.vayunmathur.email.BuildConfig.OUTLOOK_OAUTH_CLIENT_ID.take(12)}… Redirect: com.vayunmathur.email://oauth", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)-            }-        }--        OutlinedTextField(-            value = emailHint,-            onValueChange = { emailHint = it.trim() },-            label = { Text(stringResource(R.string.email_address_optional)) },-            placeholder = { Text("Optional — pre-fills Microsoft login") },-            singleLine = true,-            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),-            modifier = Modifier.fillMaxWidth(),-        )--        Button(-            onClick = { OutlookOAuth.start(context, emailHint) },-            modifier = Modifier.fillMaxWidth(),-        ) {-            Text(stringResource(R.string.sign_in_with, preset.displayName))-        }--        HorizontalDivider()--        Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clickable { useAppPassword = !useAppPassword }) {-            Checkbox(checked = useAppPassword, onCheckedChange = { useAppPassword = it })-            Text(stringResource(R.string.use_app_password_instead), style = MaterialTheme.typography.bodyMedium)-        }--        if (useAppPassword) {-            OutlinedTextField(-                value = appPassword,-                onValueChange = { appPassword = it },-                label = { Text(stringResource(R.string.app_password)) },-                singleLine = true,-                visualTransformation = if (appPasswordVisible) androidx.compose.ui.text.input.VisualTransformation.None else PasswordVisualTransformation(),-                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),-                trailingIcon = {-                    TextButton(onClick = { appPasswordVisible = !appPasswordVisible }) {-                        Text(if (appPasswordVisible) stringResource(R.string.hide) else stringResource(R.string.show))-                    }-                },-                modifier = Modifier.fillMaxWidth(),-            )--            if (error != null) {-                Text(error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)-            }--            Button(-                enabled = !working && emailHint.isNotBlank() && appPassword.isNotBlank(),-                onClick = {-                    error = null; working = true-                    scope.launch {-                        val result = testAndPersistAccount(-                            context = context,-                            providerId = preset.id,-                            email = emailHint,-                            username = "",-                            password = appPassword,-                            imap = preset.imap ?: ServerConfig("outlook.office365.com", 993, true),-                            smtp = preset.smtp ?: ServerConfig("smtp-mail.outlook.com", 587, false),-                        )-                        working = false-                        if (result == null) {-                            AppMessages.show(accountAddedMsg); onAccountAdded()-                        } else error = result-                    }-                },-                modifier = Modifier.fillMaxWidth(),-            ) {-                if (working) {-                    CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)-                    Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.testing_connection))-                } else Text(stringResource(R.string.test_connection_and_save))-            }-        }--        preset.appPasswordHelpUrl?.let { url ->-            TextButton(onClick = { openUrl(context, url) }) { Text(stringResource(R.string.open_app_password_help, preset.displayName)) }-        }-    }-}--@OptIn(ExperimentalMaterial3Api::class)-@Composable-private fun PasswordForm(-    preset: ProviderPreset,-    onAccountAdded: () -> Unit,-) {-    val context = LocalContext.current-    val scope = rememberCoroutineScope()-    val accountAddedMsg = stringResource(R.string.account_added)--    var email by rememberSaveable { mutableStateOf("") }-    var useDifferentUsername by rememberSaveable { mutableStateOf(false) }-    var username by rememberSaveable { mutableStateOf("") }-    var password by rememberSaveable { mutableStateOf("") }-    var passwordVisible by rememberSaveable { mutableStateOf(false) }--    var imapHost by rememberSaveable { mutableStateOf(preset.imap?.host ?: "") }-    var imapPort by rememberSaveable { mutableStateOf((preset.imap?.port ?: 993).toString()) }-    var imapUseSsl by rememberSaveable { mutableStateOf(preset.imap?.useSsl ?: true) }-    var smtpHost by rememberSaveable { mutableStateOf(preset.smtp?.host ?: "") }-    var smtpPort by rememberSaveable { mutableStateOf((preset.smtp?.port ?: 465).toString()) }-    var smtpUseSsl by rememberSaveable { mutableStateOf(preset.smtp?.useSsl ?: true) }--    var working by remember { mutableStateOf(false) }-    var error by remember { mutableStateOf<String?>(null) }--    Column(-        Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),-        verticalArrangement = Arrangement.spacedBy(12.dp),-    ) {-        if (preset.instructions.isNotEmpty()) { InstructionsCard(preset = preset) }--        OutlinedTextField(value = email, onValueChange = { email = it.trim() }, label = { Text(stringResource(R.string.email_address)) }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email), modifier = Modifier.fillMaxWidth())-        if (preset.id == PROVIDER_CUSTOM) {-            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clickable { useDifferentUsername = !useDifferentUsername }) {-                Checkbox(checked = useDifferentUsername, onCheckedChange = { useDifferentUsername = it })-                Text(stringResource(R.string.username_is_not_my_email), style = MaterialTheme.typography.bodyMedium)-            }-            if (useDifferentUsername) {-                OutlinedTextField(value = username, onValueChange = { username = it.trim() }, label = { Text(stringResource(R.string.username)) }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Ascii), modifier = Modifier.fillMaxWidth())-            }-        }-        OutlinedTextField(-            value = password,-            onValueChange = { password = it },-            label = { Text(if (preset.id == PROVIDER_CUSTOM) stringResource(R.string.password) else stringResource(R.string.app_password)) },-            singleLine = true,-            visualTransformation = if (passwordVisible) androidx.compose.ui.text.input.VisualTransformation.None else PasswordVisualTransformation(),-            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),-            trailingIcon = {-                TextButton(onClick = { passwordVisible = !passwordVisible }) { Text(if (passwordVisible) stringResource(R.string.hide) else stringResource(R.string.show)) }-            },-            modifier = Modifier.fillMaxWidth(),-        )--        if (preset.id == PROVIDER_CUSTOM) {-            Text(stringResource(R.string.imap_incoming), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)-            AddAccountSection(host = imapHost, onHostChange = { imapHost = it.trim() }, port = imapPort, onPortChange = { imapPort = it.filter(Char::isDigit) }, useSsl = imapUseSsl, onSslChange = { imapUseSsl = it })-            Text(stringResource(R.string.smtp_outgoing), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)-            AddAccountSection(host = smtpHost, onHostChange = { smtpHost = it.trim() }, port = smtpPort, onPortChange = { smtpPort = it.filter(Char::isDigit) }, useSsl = smtpUseSsl, onSslChange = { smtpUseSsl = it })-        }--        if (error != null) {-            Text(error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)-        }--        Button(-            enabled = !working && email.isNotBlank() && password.isNotBlank() && (preset.id != PROVIDER_CUSTOM || (imapHost.isNotBlank() && smtpHost.isNotBlank() && imapPort.isNotBlank() && smtpPort.isNotBlank())),-            onClick = {-                error = null; working = true-                scope.launch {-                    val imap = preset.imap ?: ServerConfig(imapHost, imapPort.toIntOrNull() ?: 993, imapUseSsl)-                    val smtp = preset.smtp ?: ServerConfig(smtpHost, smtpPort.toIntOrNull() ?: 465, smtpUseSsl)-                    val result = testAndPersistAccount(context = context, providerId = preset.id, email = email, username = if (useDifferentUsername) username else "", password = password, imap = imap, smtp = smtp)-                    working = false-                    if (result == null) { AppMessages.show(accountAddedMsg); onAccountAdded() } else error = result-                }-            },-            modifier = Modifier.fillMaxWidth(),-        ) {-            if (working) {-                CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.testing_connection))-            } else Text(stringResource(R.string.test_connection_and_save))-        }-    }-}
email/src/main/java/com/vayunmathur/email/ui/MainContent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/MainContent.kt b/email/src/main/java/com/vayunmathur/email/ui/MainContent.ktindex 3c90b47027..6b7f1bb5eb 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MainContent.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MainContent.kt@@ -5,8 +5,11 @@ import androidx.compose.runtime.getValue import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.email.Navigation import com.vayunmathur.email.Route+import com.vayunmathur.email.addAccountEntries import com.vayunmathur.email.platform.EmailViewModel import com.vayunmathur.email.platform.IntentState+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack  @Composable fun MainContent(viewModel: EmailViewModel) {@@ -15,10 +18,16 @@ fun MainContent(viewModel: EmailViewModel) {     val isEmlViewer = navigationRoute is Route.EmlViewer      if (accounts.isEmpty() && !isEmlViewer) {-        AddAccountScreen(-            onBack = null,-            onAccountAdded = {},-        )+        // First-run gate: no account yet, so there is no main graph to+        // push the add-account form onto. Host the same two destinations+        // on a gate-local stack instead; saving an account fills+        // `accounts` and swaps this for the main Navigation, so the+        // form's onAccountAdded has nothing to do here. The picker is+        // the gate root and keeps its no-back presentation.+        val gateStack = rememberNavBackStack<Route>(Route.AddAccount)+        MainNavigation(gateStack) {+            addAccountEntries(gateStack, onPickBack = null, onAccountAdded = {})+        }     } else {         Navigation(viewModel = viewModel)     }
email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt
diff --git a/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt b/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.ktindex 7a9effb037..ea91748f96 100644--- a/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt+++ b/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt@@ -102,7 +102,7 @@ class MetadataPreviews {     @Composable     fun Preview4AddAccount() {         DynamicTheme(darkTheme = true) {-            AddAccountScreen(onBack = {}, onAccountAdded = {})+            AddAccountScreen(onBack = {}, onPickProvider = {})         }     } 
email/src/test/java/com/vayunmathur/email/ui/AddAccountScreenTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/ui/AddAccountScreenTest.kt b/email/src/test/java/com/vayunmathur/email/ui/AddAccountScreenTest.ktindex dc5b7be64c..25d2d55c44 100644--- a/email/src/test/java/com/vayunmathur/email/ui/AddAccountScreenTest.kt+++ b/email/src/test/java/com/vayunmathur/email/ui/AddAccountScreenTest.kt@@ -6,6 +6,11 @@ import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollTo import androidx.compose.ui.test.performTextInput+import com.vayunmathur.email.Route+import com.vayunmathur.email.addAccountEntries+import com.vayunmathur.email.data.PROVIDER_GMAIL+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavBackStack import kotlin.test.Test import kotlin.test.assertEquals import org.junit.Rule@@ -14,8 +19,9 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config  /**- * Drives the real [AddAccountScreen] through provider picking and form- * validation. Picking a provider never touches the network (connection+ * Drives the real add-account destinations through provider picking and+ * form validation: picking a provider pushes [Route.AddAccountForm] and+ * Back pops to the picker. Picking never touches the network (connection  * testing only starts on the save button), so these render for real.  *  * A miswired picker strands new users with no way to add an account; a@@ -29,9 +35,18 @@ class AddAccountScreenTest {     @get:Rule     val composeRule = createComposeRule() +    /** Hosts the picker+form destinations on a real stack, as Navigation does. */+    private fun composeAddAccount(onAccountAdded: () -> Unit = {}): NavBackStack<Route> {+        val stack = NavBackStack(arrayOf<Route>(Route.AddAccount))+        composeRule.setContent {+            MainNavigation(stack) { addAccountEntries(stack, onAccountAdded = onAccountAdded) }+        }+        return stack+    }+     @Test     fun `provider list shows every preset`() {-        composeRule.setContent { AddAccountScreen(onBack = {}, onAccountAdded = {}) }+        composeAddAccount()         composeRule.onNodeWithText("Gmail").assertIsDisplayed()         composeRule.onNodeWithText("Outlook / Microsoft 365", substring = true).performScrollTo()         composeRule.onNodeWithText("Outlook / Microsoft 365", substring = true).assertIsDisplayed()@@ -42,18 +57,19 @@ class AddAccountScreenTest {     @Test     fun `picking gmail opens the app-password form`() {         var added = 0-        composeRule.setContent { AddAccountScreen(onBack = {}, onAccountAdded = { added++ }) }+        val stack = composeAddAccount { added++ }         composeRule.onNodeWithText("Gmail").performClick()         composeRule.waitForIdle()         // Gmail's instructions mention the app-passwords page.         composeRule.onNodeWithText("apppasswords", substring = true, ignoreCase = true).performScrollTo()         composeRule.onNodeWithText("apppasswords", substring = true, ignoreCase = true).assertIsDisplayed()+        assertEquals(Route.AddAccountForm(PROVIDER_GMAIL), stack.backStack.last())         assertEquals(0, added)     }      @Test     fun `picking outlook opens the oauth form`() {-        composeRule.setContent { AddAccountScreen(onBack = {}, onAccountAdded = {}) }+        composeAddAccount()         composeRule.onNodeWithText("Outlook / Microsoft 365", substring = true).performScrollTo()         composeRule.onNodeWithText("Outlook / Microsoft 365", substring = true).performClick()         composeRule.waitForIdle()@@ -63,18 +79,21 @@ class AddAccountScreenTest {      @Test     fun `back from a provider returns to the picker`() {-        var backs = 0-        composeRule.setContent { AddAccountScreen(onBack = { backs++ }, onAccountAdded = {}) }+        val stack = composeAddAccount()         composeRule.onNodeWithText("Gmail").performClick()         composeRule.waitForIdle()-        // Provider form is showing (help link); the picker back wasn't consumed.+        // Provider form is showing (help link) over the picker destination.         composeRule.onNodeWithText("Open Gmail app-password help", substring = true).assertExists()-        assertEquals(0, backs)+        assertEquals(Route.AddAccountForm(PROVIDER_GMAIL), stack.backStack.last())+        composeRule.runOnUiThread { stack.pop() }+        composeRule.waitForIdle()+        assertEquals(listOf<Route>(Route.AddAccount), stack.backStack)+        composeRule.onNodeWithText("Gmail").assertIsDisplayed()     }      @Test     fun `gmail form accepts input and toggles password visibility`() {-        composeRule.setContent { AddAccountScreen(onBack = {}, onAccountAdded = {}) }+        composeAddAccount()         composeRule.onNodeWithText("Gmail").performClick()         composeRule.waitForIdle()         composeRule.onNodeWithText("Email address").performScrollTo()@@ -92,7 +111,7 @@ class AddAccountScreenTest {      @Test     fun `custom form reveals username field when toggled`() {-        composeRule.setContent { AddAccountScreen(onBack = {}, onAccountAdded = {}) }+        composeAddAccount()         composeRule.onNodeWithText("Other (IMAP / SMTP)", substring = true).performScrollTo()         composeRule.onNodeWithText("Other (IMAP / SMTP)", substring = true).performClick()         composeRule.waitForIdle()@@ -106,7 +125,7 @@ class AddAccountScreenTest {      @Test     fun `outlook form reveals app password fields when toggled`() {-        composeRule.setContent { AddAccountScreen(onBack = {}, onAccountAdded = {}) }+        composeAddAccount()         composeRule.onNodeWithText("Outlook / Microsoft 365", substring = true).performScrollTo()         composeRule.onNodeWithText("Outlook / Microsoft 365", substring = true).performClick()         composeRule.waitForIdle()@@ -121,7 +140,7 @@ class AddAccountScreenTest {      @Test     fun `custom provider shows manual server fields`() {-        composeRule.setContent { AddAccountScreen(onBack = {}, onAccountAdded = {}) }+        composeAddAccount()         composeRule.onNodeWithText("Other (IMAP / SMTP)", substring = true).performScrollTo()         composeRule.onNodeWithText("Other (IMAP / SMTP)", substring = true).performClick()         composeRule.waitForIdle()
email/src/test/java/com/vayunmathur/email/ui/AddAccountSubmitTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/ui/AddAccountSubmitTest.kt b/email/src/test/java/com/vayunmathur/email/ui/AddAccountSubmitTest.ktindex e49e3bdd83..a51302e466 100644--- a/email/src/test/java/com/vayunmathur/email/ui/AddAccountSubmitTest.kt+++ b/email/src/test/java/com/vayunmathur/email/ui/AddAccountSubmitTest.kt@@ -16,6 +16,10 @@ import androidx.test.core.app.ApplicationProvider import androidx.work.Configuration import androidx.work.WorkManager import com.vayunmathur.email.FakeAndroidKeyStore+import com.vayunmathur.email.Route+import com.vayunmathur.email.addAccountEntries+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.email.data.CredentialCrypto import com.vayunmathur.email.data.EmailDatabase import com.vayunmathur.email.data.EmailRepository@@ -35,7 +39,7 @@ import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config  /**- * [AddAccountScreen] submit flows: the custom-provider form must test+ * Add-account submit flows: the custom-provider form must test  * the entered server before saving (a saved-but-dead account is worse  * than an error), persist the account with the password encrypted, and  * fire onAccountAdded; the Outlook form's sign-in button must start@@ -48,6 +52,15 @@ class AddAccountSubmitTest {     @get:Rule     val composeRule = createComposeRule() +    /** Hosts the picker+form destinations on a real stack, as Navigation does. */+    private fun composeAddAccount(onAccountAdded: () -> Unit = {}): NavBackStack<Route> {+        val stack = NavBackStack(arrayOf<Route>(Route.AddAccount))+        composeRule.setContent {+            MainNavigation(stack) { addAccountEntries(stack, onAccountAdded = onAccountAdded) }+        }+        return stack+    }+     private val context get() = ApplicationProvider.getApplicationContext<Application>()     private lateinit var db: EmailDatabase     private lateinit var server: FakeImapServer@@ -93,7 +106,7 @@ class AddAccountSubmitTest {     @Test     fun `custom form tests the fake server and saves the account`() {         var added = 0-        composeRule.setContent { AddAccountScreen(onBack = {}, onAccountAdded = { added++ }) }+        composeAddAccount { added++ }         composeRule.onNodeWithText("Other (IMAP / SMTP)", substring = true).performScrollTo()         composeRule.onNodeWithText("Other (IMAP / SMTP)", substring = true).performClick()         composeRule.waitForIdle()@@ -128,7 +141,7 @@ class AddAccountSubmitTest {      @Test     fun `outlook sign-in stores the pkce session and launches microsoft`() {-        composeRule.setContent { AddAccountScreen(onBack = {}, onAccountAdded = {}) }+        composeAddAccount()         composeRule.onNodeWithText("Outlook / Microsoft 365", substring = true).performScrollTo()         composeRule.onNodeWithText("Outlook / Microsoft 365", substring = true).performClick()         composeRule.waitForIdle()
email/src/test/java/com/vayunmathur/email/ui/ComposerAndAccountW5Test.kt
diff --git a/email/src/test/java/com/vayunmathur/email/ui/ComposerAndAccountW5Test.kt b/email/src/test/java/com/vayunmathur/email/ui/ComposerAndAccountW5Test.ktindex c6e0878959..722129e761 100644--- a/email/src/test/java/com/vayunmathur/email/ui/ComposerAndAccountW5Test.kt+++ b/email/src/test/java/com/vayunmathur/email/ui/ComposerAndAccountW5Test.kt@@ -120,7 +120,7 @@ class ComposerAndAccountW5Test {     @Test     fun addAccountScreenShowsOAuthAndPasswordPaths() {         rule.setContent {-            AddAccountScreen(onBack = {}, onAccountAdded = {})+            AddAccountScreen(onBack = {}, onPickProvider = {})         }         rule.waitForIdle()         assertTrue(