From 6b579a3533810473265eb0a4928eb7e8a9a4fe2e Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Mon, 3 Aug 2026 23:03:27 +0200 Subject: [PATCH 01/24] feat(onboarding): add module --- feature/onboarding/build.gradle.kts | 10 ++++++++++ .../feature/onboarding/di/FeatureOnboardingModule.kt | 10 ++++++++++ settings.gradle.kts | 1 + 3 files changed, 21 insertions(+) create mode 100644 feature/onboarding/build.gradle.kts create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/di/FeatureOnboardingModule.kt diff --git a/feature/onboarding/build.gradle.kts b/feature/onboarding/build.gradle.kts new file mode 100644 index 000000000..ed698fe18 --- /dev/null +++ b/feature/onboarding/build.gradle.kts @@ -0,0 +1,10 @@ +plugins { + alias(libs.plugins.keygo.android.compose) +} + +android { + namespace = "de.davis.keygo.feature.onboarding" +} + +dependencies { +} diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/di/FeatureOnboardingModule.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/di/FeatureOnboardingModule.kt new file mode 100644 index 000000000..8e9c1eee0 --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/di/FeatureOnboardingModule.kt @@ -0,0 +1,10 @@ +package de.davis.keygo.feature.onboarding.di + +import org.koin.core.annotation.ComponentScan +import org.koin.core.annotation.Configuration +import org.koin.core.annotation.Module + +@Module +@Configuration +@ComponentScan("de.davis.keygo.feature.onboarding") +object FeatureOnboardingModule diff --git a/settings.gradle.kts b/settings.gradle.kts index 29d162c2d..c7e735f27 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -50,3 +50,4 @@ include(":feature:autofill") include(":feature:credit-card") include(":feature:settings") include(":feature:backup") +include(":feature:onboarding") From 4fc1e5768a77fc6a757effa12307d72fd223b892 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Tue, 4 Aug 2026 18:04:46 +0200 Subject: [PATCH 02/24] feat(onboarding): add prototypes --- app/build.gradle.kts | 1 + .../component/BackupFileChooser.kt | 2 +- feature/onboarding/build.gradle.kts | 3 + feature/onboarding/consumer-rules.pro | 0 .../presentation/EnableAutofillContent.kt | 155 +++++++++++++++++ .../presentation/EnableBiometricsContent.kt | 68 ++++++++ .../presentation/ImportVaultContent.kt | 68 ++++++++ .../presentation/MainPasswordContent.kt | 136 +++++++++++++++ .../presentation/OnboardingScreen.kt | 27 +++ .../onboarding/presentation/WelcomeContent.kt | 61 +++++++ .../component/OnboardingScaffold.kt | 163 ++++++++++++++++++ .../src/main/res/values/strings.xml | 34 ++++ 12 files changed, 717 insertions(+), 1 deletion(-) create mode 100644 feature/onboarding/consumer-rules.pro create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/component/OnboardingScaffold.kt create mode 100644 feature/onboarding/src/main/res/values/strings.xml diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 0e8648d4d..521beac26 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -118,6 +118,7 @@ dependencies { implementation(projects.feature.autofill) implementation(projects.feature.settings) implementation(projects.feature.backup) + implementation(projects.feature.onboarding) implementation(projects.migration.createAccess) implementation(projects.migration.legacyData) diff --git a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/component/BackupFileChooser.kt b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/component/BackupFileChooser.kt index f0a3142c1..8c40e1300 100644 --- a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/component/BackupFileChooser.kt +++ b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/component/BackupFileChooser.kt @@ -33,7 +33,7 @@ import de.davis.keygo.feature.backup.R import de.davis.keygo.feature.backup.domain.model.BackupDestination @Composable -internal fun BackupFileChooser( +fun BackupFileChooser( destination: BackupDestination?, onChoose: () -> Unit, chooserIcon: ImageVector, diff --git a/feature/onboarding/build.gradle.kts b/feature/onboarding/build.gradle.kts index ed698fe18..c1e825675 100644 --- a/feature/onboarding/build.gradle.kts +++ b/feature/onboarding/build.gradle.kts @@ -7,4 +7,7 @@ android { } dependencies { + implementation(projects.core.ui) + implementation(projects.core.item) + implementation(projects.feature.backup) } diff --git a/feature/onboarding/consumer-rules.pro b/feature/onboarding/consumer-rules.pro new file mode 100644 index 000000000..e69de29bb diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt new file mode 100644 index 000000000..6c0310d26 --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt @@ -0,0 +1,155 @@ +package de.davis.keygo.feature.onboarding.presentation + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AutoFixHigh +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItemDefaults +import androidx.compose.material3.MaterialShapes +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SegmentedListItem +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.toShape +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import de.davis.keygo.feature.onboarding.R +import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffold +import de.davis.keygo.feature.onboarding.presentation.component.SmallIconContainer + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +internal fun EnableAutofillContent( + onOpenSettings: () -> Unit, + onDone: () -> Unit, +) { + OnboardingScaffold( + iconContainer = { + SmallIconContainer( + shape = MaterialShapes.Cookie7Sided.toShape() + ) { + Icon( + imageVector = Icons.Default.AutoFixHigh, + contentDescription = null + ) + } + }, + title = stringResource(R.string.autofill_title), + description = stringResource(R.string.autofill_subtitle), + buttonText = stringResource(R.string.open_settings), + onButtonClicked = onOpenSettings, + optionalAction = { + TextButton( + onClick = onDone, + modifier = Modifier.fillMaxWidth(), + ) { + Text(text = stringResource(R.string.finish_setup)) + } + }, + ) { + Column( + verticalArrangement = Arrangement.spacedBy(ListItemDefaults.SegmentedGap) + ) { + SegmentedListItem( + shapes = ListItemDefaults.segmentedShapes(0, 3), + leadingContent = { + NumberBadge( + number = 1, + containerColor = MaterialTheme.colorScheme.primary, + contentColor = MaterialTheme.colorScheme.onPrimary + ) + }, + supportingContent = { + Text(text = stringResource(R.string.autofill_open_settings_support)) + } + ) { + Text(text = stringResource(R.string.autofill_open_settings)) + } + + SegmentedListItem( + shapes = ListItemDefaults.segmentedShapes(1, 3), + leadingContent = { + NumberBadge( + number = 2, + containerColor = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer + ) + }, + supportingContent = { + Text(text = stringResource(R.string.autofill_choose_keygo_support)) + } + ) { + Text(text = stringResource(R.string.autofill_choose_keygo)) + } + + SegmentedListItem( + shapes = ListItemDefaults.segmentedShapes(2, 3), + leadingContent = { + NumberBadge( + number = 3, + containerColor = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer + ) + }, + supportingContent = { + Text(text = stringResource(R.string.autofill_chrome_support)) + } + ) { + Text(text = stringResource(R.string.autofill_chrome)) + } + } + } +} + +@Composable +internal fun NumberBadge( + number: Int, + containerColor: Color, + contentColor: Color, + modifier: Modifier = Modifier, + size: Dp = 40.dp, +) { + Box( + modifier = modifier + .size(size) + .clip(CircleShape) + .background(containerColor), + contentAlignment = Alignment.Center, + ) { + Text( + text = number.toString(), + color = contentColor, + style = MaterialTheme.typography.headlineSmallEmphasized, + ) + } +} + + +@Preview +@Composable +private fun EnableAutofillContentPreview() { + MaterialTheme { + Surface(modifier = Modifier.fillMaxSize()) { + EnableAutofillContent( + onOpenSettings = {}, + onDone = {} + ) + } + } +} \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt new file mode 100644 index 000000000..2c1805fdc --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt @@ -0,0 +1,68 @@ +package de.davis.keygo.feature.onboarding.presentation + +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Fingerprint +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialShapes +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.toShape +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import de.davis.keygo.feature.onboarding.R +import de.davis.keygo.feature.onboarding.presentation.component.LargeIconContainer +import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffold + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +internal fun EnableBiometricsContent( + onContinue: () -> Unit +) { + OnboardingScaffold( + iconContainer = { + LargeIconContainer( + shape = MaterialShapes.Square.toShape() + ) { + Icon( + imageVector = Icons.Default.Fingerprint, + contentDescription = null + ) + } + }, + title = stringResource(R.string.biometrics_title), + description = stringResource(R.string.biometrics_subtitle), + buttonText = stringResource(R.string.enable_biometrics), + onButtonClicked = onContinue, + optionalAction = { + TextButton( + onClick = {}, + modifier = Modifier.fillMaxWidth(), + ) { + Text(text = stringResource(R.string.skip_for_now)) + } + }, + contentHorizontalAlignment = Alignment.CenterHorizontally + ) { + // No content for Enable Biometrics + } +} + +@Preview +@Composable +private fun EnableBiometricsContentPreview() { + MaterialTheme { + Surface(modifier = Modifier.fillMaxSize()) { + EnableBiometricsContent( + onContinue = {} + ) + } + } +} \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt new file mode 100644 index 000000000..fc01b861f --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt @@ -0,0 +1,68 @@ +package de.davis.keygo.feature.onboarding.presentation + +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.FileOpen +import androidx.compose.material.icons.filled.ImportExport +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialShapes +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.toShape +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import de.davis.keygo.feature.backup.presentation.component.BackupFileChooser +import de.davis.keygo.feature.onboarding.R +import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffold +import de.davis.keygo.feature.onboarding.presentation.component.SmallIconContainer +import de.davis.keygo.feature.backup.R as BackupR + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +internal fun ImportVaultContent( + onContinue: () -> Unit +) { + OnboardingScaffold( + iconContainer = { + SmallIconContainer( + shape = MaterialShapes.Pentagon.toShape() + ) { + Icon( + imageVector = Icons.Default.ImportExport, + contentDescription = null + ) + } + }, + title = stringResource(R.string.import_title), + description = stringResource(R.string.import_subtitle), + buttonText = stringResource(R.string.skip_for_now), + buttonOutlined = true, + onButtonClicked = onContinue, + ) { + BackupFileChooser( + destination = null, + onChoose = {}, + chooserIcon = Icons.Default.FileOpen, + chooserTitle = stringResource(BackupR.string.destination_choose_title), + chooserSubtitle = stringResource(BackupR.string.destination_choose_subtitle), + chooserAction = stringResource(BackupR.string.destination_choose_action), + changeLabel = stringResource(BackupR.string.destination_filename_label), + fileNameLabel = "TODO", // TODO + ) + } +} + +@Preview +@Composable +private fun ImportVaultContentPreview() { + MaterialTheme { + Surface(modifier = Modifier.fillMaxSize()) { + ImportVaultContent( + onContinue = {} + ) + } + } +} \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt new file mode 100644 index 000000000..7c9803c17 --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt @@ -0,0 +1,136 @@ +package de.davis.keygo.feature.onboarding.presentation + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.SharedTransitionLayout +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.input.TextObfuscationMode +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Password +import androidx.compose.material.icons.filled.Shield +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialShapes +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedSecureTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.toShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +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.focus.onFocusChanged +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import de.davis.keygo.core.item.domain.model.PasswordScore +import de.davis.keygo.core.item.presentation.StrengthIndicator +import de.davis.keygo.core.ui.components.VisibilityButton +import de.davis.keygo.feature.onboarding.R +import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffold +import de.davis.keygo.feature.onboarding.presentation.component.SmallIconContainer + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +internal fun MainPasswordContent( + onContinue: () -> Unit +) { + OnboardingScaffold( + iconContainer = { + SmallIconContainer( + shape = MaterialShapes.Diamond.toShape() + ) { + Icon( + imageVector = Icons.Default.Password, + contentDescription = null + ) + } + }, + title = stringResource(R.string.main_password_title), + description = stringResource(R.string.main_password_subtitle), + buttonText = stringResource(R.string.continue_text), + onButtonClicked = onContinue, + info = { + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + imageVector = Icons.Default.Shield, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + + Text( + text = stringResource(R.string.main_password_info), + style = MaterialTheme.typography.bodySmall, + ) + } + } + ) { + var forceCompact by rememberSaveable { mutableStateOf(false) } + var passwordHidden by remember { mutableStateOf(true) } + OutlinedSecureTextField( + state = passwordState, + modifier = Modifier + .fillMaxWidth() + .onFocusChanged { + forceCompact = !it.hasFocus + }, + label = { Text(text = stringResource(R.string.main_password_label)) }, + textObfuscationMode = if (passwordHidden) TextObfuscationMode.RevealLastTyped + else TextObfuscationMode.Visible, + trailingIcon = { + VisibilityButton( + isHidden = passwordHidden, + onClick = { passwordHidden = !passwordHidden } + ) + } + ) + + StrengthIndicator( + passwordScore = PasswordScore.Moderate, + forceCompact = forceCompact, + ) + + var confirmPasswordHidden by remember { mutableStateOf(true) } + OutlinedSecureTextField( + state = passwordState, + modifier = Modifier.fillMaxWidth(), + label = { Text(text = stringResource(R.string.confirm_main_password_label)) }, + textObfuscationMode = if (confirmPasswordHidden) TextObfuscationMode.RevealLastTyped + else TextObfuscationMode.Visible, + trailingIcon = { + VisibilityButton( + isHidden = confirmPasswordHidden, + onClick = { confirmPasswordHidden = !confirmPasswordHidden } + ) + } + ) + } +} + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Preview +@Composable +private fun MainPasswordContentPreview() { + MaterialTheme { + Surface(modifier = Modifier.fillMaxSize()) { + SharedTransitionLayout { + AnimatedVisibility(visible = true) { + MainPasswordContent( + onContinue = {} + ) + } + } + } + } +} \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt new file mode 100644 index 000000000..d4cd6dd93 --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -0,0 +1,27 @@ +package de.davis.keygo.feature.onboarding.presentation + +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +fun OnboardingScreen() { + +} + +@Preview +@Composable +private fun OnboardingScreenPreview() { + MaterialTheme { + Surface( + modifier = Modifier.fillMaxSize(), + ) { + OnboardingScreen() + } + } +} \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt new file mode 100644 index 000000000..f25c6e746 --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt @@ -0,0 +1,61 @@ +package de.davis.keygo.feature.onboarding.presentation + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.SharedTransitionLayout +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialShapes +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.toShape +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import de.davis.keygo.feature.onboarding.R +import de.davis.keygo.feature.onboarding.presentation.component.LargeIconContainer +import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffold +import de.davis.keygo.core.ui.R as CoreUiR + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +internal fun WelcomeContent(onContinue: () -> Unit) { + OnboardingScaffold( + iconContainer = { + LargeIconContainer( + shape = MaterialShapes.Arrow.toShape() + ) { + Icon( + painter = painterResource(CoreUiR.drawable.ic_launcher_monochrome), + contentDescription = null + ) + } + }, + title = stringResource(R.string.welcome_title), + description = stringResource(R.string.welcome_subtitle), + buttonText = stringResource(R.string.get_started), + onButtonClicked = onContinue, + contentHorizontalAlignment = Alignment.CenterHorizontally + ) { + // No content for Welcome + } +} + +@Preview +@Composable +private fun WelcomeContentPreview() { + MaterialTheme { + Surface(modifier = Modifier.fillMaxSize()) { + SharedTransitionLayout { + AnimatedVisibility(visible = true) { + WelcomeContent( + onContinue = {} + ) + } + } + } + } +} \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/component/OnboardingScaffold.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/component/OnboardingScaffold.kt new file mode 100644 index 000000000..d446f50df --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/component/OnboardingScaffold.kt @@ -0,0 +1,163 @@ +package de.davis.keygo.feature.onboarding.presentation.component + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.requiredSize +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.sizeIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp + +@Composable +internal fun SmallIconContainer( + shape: Shape, + modifier: Modifier = Modifier, + content: @Composable BoxScope.() -> Unit +) { + Surface( + modifier = modifier + .size(100.dp) + .aspectRatio(1f), + shape = shape, + color = MaterialTheme.colorScheme.primary, + ) { + Box( + modifier = Modifier.requiredSize(48.dp), + contentAlignment = Alignment.Center, + propagateMinConstraints = true, + content = content, + ) + } +} + +@Composable +internal fun LargeIconContainer( + shape: Shape, + modifier: Modifier = Modifier, + content: @Composable BoxScope.() -> Unit +) { + Surface( + modifier = modifier + .size(250.dp) + .aspectRatio(1f), + shape = shape, + color = MaterialTheme.colorScheme.primary, + ) { + Box( + modifier = Modifier.requiredSize(175.dp), + contentAlignment = Alignment.Center, + propagateMinConstraints = true, + content = content, + ) + } +} + +private fun arrangementFor(horizontal: Alignment.Horizontal) = when (horizontal) { + Alignment.CenterHorizontally -> Arrangement.spacedBy(8.dp, Alignment.CenterVertically) + else -> Arrangement.spacedBy(8.dp) +} + +private fun textAlignFor(horizontal: Alignment.Horizontal) = when (horizontal) { + Alignment.CenterHorizontally -> TextAlign.Center + else -> null +} + +@Composable +internal fun OnboardingScaffold( + iconContainer: @Composable () -> Unit, + title: String, + description: String, + buttonText: String, + onButtonClicked: () -> Unit, + buttonOutlined: Boolean = false, + contentHorizontalAlignment: Alignment.Horizontal = Alignment.Start, + info: (@Composable () -> Unit)? = null, + optionalAction: (@Composable () -> Unit)? = null, + content: @Composable () -> Unit, +) { + val contentHeight = ButtonDefaults.LargeContainerHeight + Column( + modifier = Modifier + .fillMaxSize() + .padding(16.dp) + ) { + Column( + modifier = Modifier + .weight(1f) + .verticalScroll(rememberScrollState()), + verticalArrangement = arrangementFor(contentHorizontalAlignment), + horizontalAlignment = contentHorizontalAlignment, + ) { + iconContainer() + + Text( + text = title, + style = MaterialTheme.typography.headlineLargeEmphasized, + modifier = Modifier.fillMaxWidth(), + textAlign = textAlignFor(contentHorizontalAlignment), + ) + + Text( + text = description, + style = MaterialTheme.typography.bodyLarge, + modifier = Modifier.fillMaxWidth(if (contentHorizontalAlignment == Alignment.CenterHorizontally) 0.75f else 1f), + textAlign = textAlignFor(contentHorizontalAlignment), + ) + + content() + } + + Column( + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + info?.invoke() + optionalAction?.invoke() + + if (buttonOutlined) + OutlinedButton( + onClick = onButtonClicked, + shapes = ButtonDefaults.shapesFor(contentHeight), + modifier = Modifier + .sizeIn(minHeight = contentHeight) + .fillMaxWidth(), + contentPadding = ButtonDefaults.contentPaddingFor(contentHeight) + ) { + Text( + text = buttonText, + style = ButtonDefaults.textStyleFor(contentHeight), + ) + } + else Button( + onClick = onButtonClicked, + shapes = ButtonDefaults.shapesFor(contentHeight), + modifier = Modifier + .sizeIn(minHeight = contentHeight) + .fillMaxWidth(), + contentPadding = ButtonDefaults.contentPaddingFor(contentHeight) + ) { + Text( + text = buttonText, + style = ButtonDefaults.textStyleFor(contentHeight), + ) + } + } + } +} \ No newline at end of file diff --git a/feature/onboarding/src/main/res/values/strings.xml b/feature/onboarding/src/main/res/values/strings.xml new file mode 100644 index 000000000..b5e4f3c2c --- /dev/null +++ b/feature/onboarding/src/main/res/values/strings.xml @@ -0,0 +1,34 @@ + + + Get Started + Continue + Skip for now + Enable Biometrics + Open settings + Finish setup + + + Own your credentials, own your privacy. + KeyGo encrypts everything locally. No servers, no cloud, no tracking. Just you and your data. + + Set your main password + This password will encrypt your vaults. KeyGo never stores this password. Make it secure. + If you forget your password, no one can recover your vaults. It will be cryptographically impossible. + Main password + Confirm main password + + Bring your passwords + Imports are encrypted locally and always on-device. Select a file to get started. + + Unlock with a touch + Use your fingerprint to open KeyGo. Your master password stays as backup. + + Set KeyGo as your autofill provider + With this feature KeyGo will offer you stored passwords whenever you are in a login screen. You can always change this setting later in your device settings. + Open system settings + Open your device settings + Choose KeyGo + Select KeyGo as your autofill provider & confirm + Apply to Chrome + Open Chrome settings & enable 3rd party autofill providers + \ No newline at end of file From f10240847799b1de758f08f86c612cf5a0c57504 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Wed, 5 Aug 2026 17:12:14 +0200 Subject: [PATCH 03/24] refactor(core): move UI field error state --- .../davis/keygo/core/ui/model/UiFieldError.kt | 22 ++++++++ core/ui/src/main/res/values/strings.xml | 4 ++ .../feature/auth/presentation/AuthContent.kt | 28 +++------- .../auth/presentation/AuthViewModel.kt | 18 +++---- .../auth/presentation/model/AuthState.kt | 13 ++--- .../presentation/model/UIPasswordError.kt | 8 --- feature/auth/src/main/res/values/strings.xml | 3 -- .../presentation/EnableBiometricsContent.kt | 6 ++- .../changepassword/ChangePasswordScreen.kt | 45 +++++++--------- .../changepassword/ChangePasswordState.kt | 14 ++--- .../changepassword/ChangePasswordViewModel.kt | 17 +++--- .../settings/src/main/res/values/strings.xml | 3 -- .../ChangePasswordViewModelTest.kt | 53 ++++++++++--------- 13 files changed, 113 insertions(+), 121 deletions(-) create mode 100644 core/ui/src/main/kotlin/de/davis/keygo/core/ui/model/UiFieldError.kt delete mode 100644 feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/UIPasswordError.kt diff --git a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/model/UiFieldError.kt b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/model/UiFieldError.kt new file mode 100644 index 000000000..b816f97d6 --- /dev/null +++ b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/model/UiFieldError.kt @@ -0,0 +1,22 @@ +package de.davis.keygo.core.ui.model + +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import de.davis.keygo.core.ui.R + +sealed interface UiFieldError { + + data object Incorrect : UiFieldError + data object Mismatch : UiFieldError + data object Empty : UiFieldError +} + +val UiFieldError.error: String + @Composable + get() = stringResource( + when (this) { + is UiFieldError.Incorrect -> R.string.incorrect_password + is UiFieldError.Mismatch -> R.string.password_does_not_match + is UiFieldError.Empty -> R.string.blank_password + } + ) \ No newline at end of file diff --git a/core/ui/src/main/res/values/strings.xml b/core/ui/src/main/res/values/strings.xml index ec096d5ec..42fd502cf 100644 --- a/core/ui/src/main/res/values/strings.xml +++ b/core/ui/src/main/res/values/strings.xml @@ -14,5 +14,9 @@ Hide password + You must set a password + Password is incorrect + Password does not match + Add \ No newline at end of file diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt index e8bf893a4..89c53980c 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt @@ -51,11 +51,11 @@ import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import de.davis.keygo.core.item.presentation.StrengthIndicator import de.davis.keygo.core.ui.components.VisibilityButton +import de.davis.keygo.core.ui.model.error import de.davis.keygo.core.ui.theme.KeyGoTheme import de.davis.keygo.feature.auth.R import de.davis.keygo.feature.auth.presentation.model.AuthState import de.davis.keygo.feature.auth.presentation.model.AuthUIEvent -import de.davis.keygo.feature.auth.presentation.model.UIPasswordError import de.davis.keygo.core.item.R as CoreItemR @OptIn(ExperimentalMaterial3ExpressiveApi::class) @@ -135,16 +135,9 @@ private fun InteractableAuthContent( label = { Text(text = stringResource(CoreItemR.string.password)) }, - isError = passwordError !is UIPasswordError.None, - supportingText = when (passwordError) { - is UIPasswordError.None -> null - is UIPasswordError.Incorrect -> { - { Text(stringResource(R.string.incorrect_password)) } - } - - else -> { - { Text(stringResource(R.string.blank_password)) } - } + isError = passwordError != null, + supportingText = passwordError?.let { + { Text(it.error) } }, textObfuscationMode = when { passwordHidden -> TextObfuscationMode.RevealLastTyped @@ -171,16 +164,9 @@ private fun InteractableAuthContent( label = { Text(text = stringResource(R.string.confirm_password)) }, - isError = confirmPasswordError !is UIPasswordError.None, - supportingText = when (confirmPasswordError) { - is UIPasswordError.None -> null - is UIPasswordError.Incorrect -> { - { Text(stringResource(R.string.password_does_not_match)) } - } - - else -> { - { Text(stringResource(R.string.blank_password)) } - } + isError = confirmPasswordError != null, + supportingText = confirmPasswordError?.let { + { Text(it.error) } }, textObfuscationMode = when { confirmPasswordHidden -> TextObfuscationMode.RevealLastTyped diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt index a25da324d..d9b259fda 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt @@ -11,6 +11,7 @@ import de.davis.keygo.core.identity.domain.usecase.CreateAccessUseCase import de.davis.keygo.core.identity.domain.usecase.UnlockWithPasswordUseCase import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository +import de.davis.keygo.core.ui.model.UiFieldError import de.davis.keygo.core.util.Result import de.davis.keygo.core.util.asResult import de.davis.keygo.core.util.onFailure @@ -18,7 +19,6 @@ import de.davis.keygo.core.util.onSuccess import de.davis.keygo.feature.auth.presentation.model.AuthState import de.davis.keygo.feature.auth.presentation.model.AuthUIEvent import de.davis.keygo.feature.auth.presentation.model.BiometricRequest -import de.davis.keygo.feature.auth.presentation.model.UIPasswordError import de.davis.keygo.migration.create_access.domain.usecase.ClearMainPasswordUseCase import de.davis.keygo.migration.create_access.domain.usecase.HasMainPasswordUseCase import de.davis.keygo.migration.create_access.domain.usecase.ValidateMainPasswordUseCase @@ -125,7 +125,7 @@ internal class AuthViewModel( _uiState.update { if (it !is AuthState.CreateAccess) return@update it - it.copy(passwordError = UIPasswordError.None) + it.copy(passwordError = null) } } .flowOn(Dispatchers.Default) @@ -143,7 +143,7 @@ internal class AuthViewModel( _uiState.update { if (it !is AuthState.CreateAccess) return@update it - it.copy(confirmPasswordError = UIPasswordError.None) + it.copy(confirmPasswordError = null) } } .flowOn(Dispatchers.Default) @@ -182,7 +182,7 @@ internal class AuthViewModel( unlockWithPassword( password = password ).handleAuthenticationResult { - copyDefaultState(passwordError = UIPasswordError.Incorrect) + copyDefaultState(passwordError = UiFieldError.Incorrect) } } } @@ -193,7 +193,7 @@ internal class AuthViewModel( .onFailure { _uiState.update { if (it !is AuthState.Interactable) return@update it - it.copyDefaultState(passwordError = UIPasswordError.Incorrect) + it.copyDefaultState(passwordError = UiFieldError.Incorrect) } }.onSuccess { clearMainPasswordUseCase() @@ -204,20 +204,20 @@ internal class AuthViewModel( is AuthState.CreateAccess -> { val errorFreeState = state.copy( - passwordError = UIPasswordError.None, - confirmPasswordError = UIPasswordError.None + passwordError = null, + confirmPasswordError = null ) if (password.isBlank()) { _uiState.update { - errorFreeState.copy(passwordError = UIPasswordError.Empty) + errorFreeState.copy(passwordError = UiFieldError.Empty) } return } val confirmedPassword = confirmPasswordTextFieldState.text.toString() if (password != confirmedPassword) { _uiState.update { - errorFreeState.copy(confirmPasswordError = UIPasswordError.Incorrect) + errorFreeState.copy(confirmPasswordError = UiFieldError.Incorrect) } return } diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt index e67983940..0e582c34e 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt @@ -2,6 +2,7 @@ package de.davis.keygo.feature.auth.presentation.model import androidx.compose.foundation.text.input.TextFieldState import de.davis.keygo.core.item.domain.model.PasswordScore +import de.davis.keygo.core.ui.model.UiFieldError sealed interface AuthState { @@ -9,13 +10,13 @@ sealed interface AuthState { sealed interface Interactable : AuthState { val passwordTextFieldState: TextFieldState - val passwordError: UIPasswordError + val passwordError: UiFieldError? val loading: Boolean fun copyDefaultState( loading: Boolean = this.loading, passwordTextFieldState: TextFieldState = this.passwordTextFieldState, - passwordError: UIPasswordError = this.passwordError, + passwordError: UiFieldError? = this.passwordError, ): Interactable = when (this) { is Login -> copy( loading = loading, @@ -39,7 +40,7 @@ sealed interface AuthState { data class Login( override val passwordTextFieldState: TextFieldState, - override val passwordError: UIPasswordError = UIPasswordError.None, + override val passwordError: UiFieldError? = null, override val loading: Boolean = false, val biometricAuthenticationAvailable: Boolean = false, ) : Interactable @@ -67,7 +68,7 @@ sealed interface AuthState { data class Migrating( override val passwordTextFieldState: TextFieldState, - override val passwordError: UIPasswordError = UIPasswordError.None, + override val passwordError: UiFieldError? = null, override val loading: Boolean = false, override val biometricsAvailable: Boolean = false, override val useBiometrics: Boolean = true, @@ -76,12 +77,12 @@ sealed interface AuthState { data class CreateAccess( override val passwordTextFieldState: TextFieldState, - override val passwordError: UIPasswordError = UIPasswordError.None, + override val passwordError: UiFieldError? = null, override val loading: Boolean = false, override val biometricsAvailable: Boolean = false, override val useBiometrics: Boolean = true, val confirmPasswordTextFieldState: TextFieldState = TextFieldState(), - val confirmPasswordError: UIPasswordError = UIPasswordError.None, + val confirmPasswordError: UiFieldError? = null, val passwordScore: PasswordScore = PasswordScore.None, ) : BiometricAuthState } diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/UIPasswordError.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/UIPasswordError.kt deleted file mode 100644 index fed1e821b..000000000 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/UIPasswordError.kt +++ /dev/null @@ -1,8 +0,0 @@ -package de.davis.keygo.feature.auth.presentation.model - -sealed interface UIPasswordError { - - data object Incorrect : UIPasswordError - data object Empty : UIPasswordError - data object None : UIPasswordError -} \ No newline at end of file diff --git a/feature/auth/src/main/res/values/strings.xml b/feature/auth/src/main/res/values/strings.xml index d8b7bc9ae..e731ab442 100644 --- a/feature/auth/src/main/res/values/strings.xml +++ b/feature/auth/src/main/res/values/strings.xml @@ -1,9 +1,6 @@ Confirm Password - You must set a password - Password is incorrect! - Password does not match Authenticate Unlock %s Create your access diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt index 2c1805fdc..4c1b1f19c 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt @@ -24,7 +24,8 @@ import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffo @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable internal fun EnableBiometricsContent( - onContinue: () -> Unit + onSkip: () -> Unit, + onContinue: () -> Unit, ) { OnboardingScaffold( iconContainer = { @@ -43,7 +44,7 @@ internal fun EnableBiometricsContent( onButtonClicked = onContinue, optionalAction = { TextButton( - onClick = {}, + onClick = onSkip, modifier = Modifier.fillMaxWidth(), ) { Text(text = stringResource(R.string.skip_for_now)) @@ -61,6 +62,7 @@ private fun EnableBiometricsContentPreview() { MaterialTheme { Surface(modifier = Modifier.fillMaxSize()) { EnableBiometricsContent( + onSkip = {}, onContinue = {} ) } diff --git a/feature/settings/src/main/kotlin/de/davis/keygo/feature/settings/presentation/changepassword/ChangePasswordScreen.kt b/feature/settings/src/main/kotlin/de/davis/keygo/feature/settings/presentation/changepassword/ChangePasswordScreen.kt index 2d52c41af..6cd146b81 100644 --- a/feature/settings/src/main/kotlin/de/davis/keygo/feature/settings/presentation/changepassword/ChangePasswordScreen.kt +++ b/feature/settings/src/main/kotlin/de/davis/keygo/feature/settings/presentation/changepassword/ChangePasswordScreen.kt @@ -50,6 +50,8 @@ import de.davis.keygo.core.security.domain.model.CiphertextData import de.davis.keygo.core.security.domain.model.KeyId import de.davis.keygo.core.security.presentation.rememberBiometricCryptoController import de.davis.keygo.core.ui.components.VisibilityButton +import de.davis.keygo.core.ui.model.UiFieldError +import de.davis.keygo.core.ui.model.error import de.davis.keygo.core.util.domain.model.snackbar.SnackbarMessage import de.davis.keygo.core.util.presentation.ObserveAsEvents import de.davis.keygo.core.util.presentation.UIText.Companion.ResourceString @@ -73,6 +75,7 @@ internal fun ChangePasswordScreen(onUp: () -> Unit) { ChangePasswordEvent.GenericError -> snackbarManager.sendMessage( SnackbarMessage(message = ResourceString(R.string.change_password_failed)), ) + ChangePasswordEvent.LaunchBiometricPrompt -> { val ciphertext = state.biometricCiphertext ?: return@ObserveAsEvents scope.launch { @@ -156,8 +159,10 @@ internal fun ChangePasswordContent( forceCompact = !it.isFocused }, label = { Text(stringResource(R.string.new_password)) }, - isError = state.newPasswordError !is FieldError.None, - supportingText = supportingTextFor(state.newPasswordError), + isError = state.newPasswordError != null, + supportingText = state.newPasswordError?.let { + { Text(text = it.error) } + }, textObfuscationMode = obfuscation(newHidden), trailingIcon = { VisibilityButton( @@ -178,8 +183,10 @@ internal fun ChangePasswordContent( state = state.confirmPassword, modifier = Modifier.fillMaxWidth(), label = { Text(stringResource(R.string.confirm_password)) }, - isError = state.confirmPasswordError !is FieldError.None, - supportingText = supportingTextFor(state.confirmPasswordError), + isError = state.confirmPasswordError != null, + supportingText = state.confirmPasswordError?.let { + { Text(text = it.error) } + }, textObfuscationMode = obfuscation(confirmHidden), trailingIcon = { VisibilityButton( @@ -243,26 +250,10 @@ internal fun ChangePasswordContent( private fun obfuscation(hidden: Boolean): TextObfuscationMode = if (hidden) TextObfuscationMode.RevealLastTyped else TextObfuscationMode.Visible -@Composable -private fun supportingTextFor(error: FieldError): (@Composable () -> Unit)? = when (error) { - FieldError.None -> null - FieldError.Empty -> { - { Text(stringResource(R.string.password_blank)) } - } - - FieldError.Incorrect -> { - { Text(stringResource(R.string.incorrect_password)) } - } - - FieldError.Mismatch -> { - { Text(stringResource(R.string.passwords_do_not_match)) } - } -} - @Composable private fun CurrentPasswordField( state: TextFieldState, - error: FieldError, + error: UiFieldError?, modifier: Modifier = Modifier, ) { var hidden by rememberSaveable { mutableStateOf(true) } @@ -270,8 +261,10 @@ private fun CurrentPasswordField( state = state, modifier = modifier.fillMaxWidth(), label = { Text(stringResource(R.string.current_password)) }, - isError = error !is FieldError.None, - supportingText = supportingTextFor(error), + isError = error != null, + supportingText = error?.let { + { Text(text = it.error) } + }, textObfuscationMode = obfuscation(hidden), trailingIcon = { VisibilityButton(isHidden = hidden, onClick = { hidden = !hidden }) @@ -288,9 +281,9 @@ private class ChangePasswordStateProvider : PreviewParameterProvider - _state.update { it.copy(currentPasswordError = FieldError.Incorrect) } + _state.update { it.copy(currentPasswordError = UiFieldError.Incorrect) } else -> _event.trySend(ChangePasswordEvent.GenericError) } diff --git a/feature/settings/src/main/res/values/strings.xml b/feature/settings/src/main/res/values/strings.xml index c0201c5a7..988a3d157 100644 --- a/feature/settings/src/main/res/values/strings.xml +++ b/feature/settings/src/main/res/values/strings.xml @@ -28,9 +28,6 @@ Change password You\'ll confirm with your fingerprint Enter your current password - Password must not be blank - Incorrect password - Passwords do not match Password changed Could not change password diff --git a/feature/settings/src/test/kotlin/de/davis/keygo/feature/settings/presentation/changepassword/ChangePasswordViewModelTest.kt b/feature/settings/src/test/kotlin/de/davis/keygo/feature/settings/presentation/changepassword/ChangePasswordViewModelTest.kt index 7b8d78232..0d57050f4 100644 --- a/feature/settings/src/test/kotlin/de/davis/keygo/feature/settings/presentation/changepassword/ChangePasswordViewModelTest.kt +++ b/feature/settings/src/test/kotlin/de/davis/keygo/feature/settings/presentation/changepassword/ChangePasswordViewModelTest.kt @@ -9,6 +9,7 @@ import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.security.crypto.FakeBiometricAvailabilityRepository import de.davis.keygo.core.security.domain.model.BiometricAuthError +import de.davis.keygo.core.ui.model.UiFieldError import de.davis.keygo.core.util.Result import de.davis.keygo.rust.FakeKeyDeriver import de.davis.keygo.rust.FakeKeyWrapper @@ -93,7 +94,7 @@ class ChangePasswordViewModelTest { vm.submitWithPassword() advanceUntilIdle() - assertEquals(FieldError.Empty, vm.state.value.newPasswordError) + assertEquals(UiFieldError.Empty, vm.state.value.newPasswordError) } @Test @@ -106,7 +107,7 @@ class ChangePasswordViewModelTest { vm.submitWithPassword() advanceUntilIdle() - assertEquals(FieldError.Mismatch, vm.state.value.confirmPasswordError) + assertEquals(UiFieldError.Mismatch, vm.state.value.confirmPasswordError) } @Test @@ -120,8 +121,8 @@ class ChangePasswordViewModelTest { // Await rather than advanceUntilIdle: key derivation hops to Dispatchers.Default, // which the test scheduler cannot see. - vm.state.first { it.currentPasswordError != FieldError.None } - assertEquals(FieldError.Incorrect, vm.state.value.currentPasswordError) + vm.state.first { it.currentPasswordError != null } + assertEquals(UiFieldError.Incorrect, vm.state.value.currentPasswordError) } @Test @@ -162,12 +163,13 @@ class ChangePasswordViewModelTest { vm.onSubmit() advanceUntilIdle() - assertEquals(FieldError.Empty, vm.state.value.newPasswordError) + assertEquals(UiFieldError.Empty, vm.state.value.newPasswordError) } @Test fun `onSubmit without biometric and valid passwords emits Success`() = runTest(dispatcher) { - val vm = viewModel() // setUp seeds an account with no biometric ARK; availability defaults false + val vm = + viewModel() // setUp seeds an account with no biometric ARK; availability defaults false vm.state.value.currentPassword.edit { append("old") } vm.state.value.newPassword.edit { append("brand-new") } vm.state.value.confirmPassword.edit { append("brand-new") } @@ -190,28 +192,29 @@ class ChangePasswordViewModelTest { vm.onSubmit() advanceUntilIdle() - assertEquals(FieldError.Mismatch, vm.state.value.confirmPasswordError) + assertEquals(UiFieldError.Mismatch, vm.state.value.confirmPasswordError) } @Test - fun `dismissReauthDialog hides dialog and clears current password error`() = runTest(dispatcher) { - enableBiometric() - val vm = viewModel() - advanceUntilIdle() - vm.onBiometricResult(Result.Failure(BiometricAuthError.Declined)) // opens the dialog - vm.state.value.newPassword.edit { append("brand-new") } - vm.state.value.confirmPassword.edit { append("brand-new") } - vm.state.value.currentPassword.edit { append("wrong") } - vm.submitWithPassword() - // Await rather than advanceUntilIdle: key derivation hops to Dispatchers.Default, - // which the test scheduler cannot see. The Incorrect error below is load-bearing. - vm.state.first { it.currentPasswordError == FieldError.Incorrect } + fun `dismissReauthDialog hides dialog and clears current password error`() = + runTest(dispatcher) { + enableBiometric() + val vm = viewModel() + advanceUntilIdle() + vm.onBiometricResult(Result.Failure(BiometricAuthError.Declined)) // opens the dialog + vm.state.value.newPassword.edit { append("brand-new") } + vm.state.value.confirmPassword.edit { append("brand-new") } + vm.state.value.currentPassword.edit { append("wrong") } + vm.submitWithPassword() + // Await rather than advanceUntilIdle: key derivation hops to Dispatchers.Default, + // which the test scheduler cannot see. The Incorrect error below is load-bearing. + vm.state.first { it.currentPasswordError == UiFieldError.Incorrect } - vm.dismissReauthDialog() + vm.dismissReauthDialog() - assertEquals(false, vm.state.value.showReauthDialog) - assertEquals(FieldError.None, vm.state.value.currentPasswordError) - } + assertEquals(false, vm.state.value.showReauthDialog) + assertEquals(null, vm.state.value.currentPasswordError) + } @Test fun `dialog confirm with wrong current password keeps dialog open with Incorrect error`() = @@ -228,8 +231,8 @@ class ChangePasswordViewModelTest { // Await rather than advanceUntilIdle: key derivation hops to Dispatchers.Default, // which the test scheduler cannot see. - vm.state.first { it.currentPasswordError != FieldError.None } - assertEquals(FieldError.Incorrect, vm.state.value.currentPasswordError) + vm.state.first { it.currentPasswordError != null } + assertEquals(UiFieldError.Incorrect, vm.state.value.currentPasswordError) assertEquals(true, vm.state.value.showReauthDialog) } From ddc7e85327ee2da2467cfc6a00b9c0f3338fc188 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Wed, 5 Aug 2026 17:40:23 +0200 Subject: [PATCH 04/24] feat(onboarding): wire vm --- .../presentation/EnableAutofillContent.kt | 22 +-- .../presentation/EnableBiometricsContent.kt | 23 +-- .../presentation/ImportVaultContent.kt | 11 +- .../presentation/MainPasswordContent.kt | 30 ++-- .../presentation/OnboardingScreen.kt | 115 ++++++++++++++ .../presentation/OnboardingViewModel.kt | 148 ++++++++++++++++++ .../onboarding/presentation/WelcomeContent.kt | 2 - .../component/OnboardingScaffold.kt | 49 +----- .../presentation/model/OnboardingStep.kt | 19 +++ .../presentation/model/OnboardingUiState.kt | 22 +++ 10 files changed, 333 insertions(+), 108 deletions(-) create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt index 6c0310d26..f51c998bf 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt @@ -5,7 +5,6 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons @@ -18,7 +17,6 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SegmentedListItem import androidx.compose.material3.Surface import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.material3.toShape import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment @@ -35,10 +33,7 @@ import de.davis.keygo.feature.onboarding.presentation.component.SmallIconContain @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -internal fun EnableAutofillContent( - onOpenSettings: () -> Unit, - onDone: () -> Unit, -) { +internal fun EnableAutofillContent() { OnboardingScaffold( iconContainer = { SmallIconContainer( @@ -52,16 +47,6 @@ internal fun EnableAutofillContent( }, title = stringResource(R.string.autofill_title), description = stringResource(R.string.autofill_subtitle), - buttonText = stringResource(R.string.open_settings), - onButtonClicked = onOpenSettings, - optionalAction = { - TextButton( - onClick = onDone, - modifier = Modifier.fillMaxWidth(), - ) { - Text(text = stringResource(R.string.finish_setup)) - } - }, ) { Column( verticalArrangement = Arrangement.spacedBy(ListItemDefaults.SegmentedGap) @@ -146,10 +131,7 @@ internal fun NumberBadge( private fun EnableAutofillContentPreview() { MaterialTheme { Surface(modifier = Modifier.fillMaxSize()) { - EnableAutofillContent( - onOpenSettings = {}, - onDone = {} - ) + EnableAutofillContent() } } } \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt index 4c1b1f19c..9810dad19 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableBiometricsContent.kt @@ -1,7 +1,6 @@ package de.davis.keygo.feature.onboarding.presentation import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Fingerprint import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi @@ -9,8 +8,6 @@ import androidx.compose.material3.Icon import androidx.compose.material3.MaterialShapes import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton import androidx.compose.material3.toShape import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment @@ -23,10 +20,7 @@ import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffo @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -internal fun EnableBiometricsContent( - onSkip: () -> Unit, - onContinue: () -> Unit, -) { +internal fun EnableBiometricsContent() { OnboardingScaffold( iconContainer = { LargeIconContainer( @@ -40,16 +34,6 @@ internal fun EnableBiometricsContent( }, title = stringResource(R.string.biometrics_title), description = stringResource(R.string.biometrics_subtitle), - buttonText = stringResource(R.string.enable_biometrics), - onButtonClicked = onContinue, - optionalAction = { - TextButton( - onClick = onSkip, - modifier = Modifier.fillMaxWidth(), - ) { - Text(text = stringResource(R.string.skip_for_now)) - } - }, contentHorizontalAlignment = Alignment.CenterHorizontally ) { // No content for Enable Biometrics @@ -61,10 +45,7 @@ internal fun EnableBiometricsContent( private fun EnableBiometricsContentPreview() { MaterialTheme { Surface(modifier = Modifier.fillMaxSize()) { - EnableBiometricsContent( - onSkip = {}, - onContinue = {} - ) + EnableBiometricsContent() } } } \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt index fc01b861f..94e8f96e3 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt @@ -22,9 +22,7 @@ import de.davis.keygo.feature.backup.R as BackupR @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -internal fun ImportVaultContent( - onContinue: () -> Unit -) { +internal fun ImportVaultContent() { OnboardingScaffold( iconContainer = { SmallIconContainer( @@ -38,9 +36,6 @@ internal fun ImportVaultContent( }, title = stringResource(R.string.import_title), description = stringResource(R.string.import_subtitle), - buttonText = stringResource(R.string.skip_for_now), - buttonOutlined = true, - onButtonClicked = onContinue, ) { BackupFileChooser( destination = null, @@ -60,9 +55,7 @@ internal fun ImportVaultContent( private fun ImportVaultContentPreview() { MaterialTheme { Surface(modifier = Modifier.fillMaxSize()) { - ImportVaultContent( - onContinue = {} - ) + ImportVaultContent() } } } \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt index 7c9803c17..59e269d05 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt @@ -34,14 +34,16 @@ import androidx.compose.ui.unit.dp import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.item.presentation.StrengthIndicator import de.davis.keygo.core.ui.components.VisibilityButton +import de.davis.keygo.core.ui.model.error import de.davis.keygo.feature.onboarding.R import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffold import de.davis.keygo.feature.onboarding.presentation.component.SmallIconContainer +import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable internal fun MainPasswordContent( - onContinue: () -> Unit + state: OnboardingUiState.SetMainPassword, ) { OnboardingScaffold( iconContainer = { @@ -56,8 +58,6 @@ internal fun MainPasswordContent( }, title = stringResource(R.string.main_password_title), description = stringResource(R.string.main_password_subtitle), - buttonText = stringResource(R.string.continue_text), - onButtonClicked = onContinue, info = { Row( horizontalArrangement = Arrangement.spacedBy(8.dp), @@ -79,7 +79,7 @@ internal fun MainPasswordContent( var forceCompact by rememberSaveable { mutableStateOf(false) } var passwordHidden by remember { mutableStateOf(true) } OutlinedSecureTextField( - state = passwordState, + state = state.passwordTextFieldState, modifier = Modifier .fillMaxWidth() .onFocusChanged { @@ -93,17 +93,21 @@ internal fun MainPasswordContent( isHidden = passwordHidden, onClick = { passwordHidden = !passwordHidden } ) - } + }, + isError = state.passwordError != null, + supportingText = state.passwordError?.let { + { Text(text = it.error) } + }, ) StrengthIndicator( - passwordScore = PasswordScore.Moderate, + passwordScore = state.passwordScore, forceCompact = forceCompact, ) var confirmPasswordHidden by remember { mutableStateOf(true) } OutlinedSecureTextField( - state = passwordState, + state = state.confirmPasswordTextFieldState, modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(R.string.confirm_main_password_label)) }, textObfuscationMode = if (confirmPasswordHidden) TextObfuscationMode.RevealLastTyped @@ -113,7 +117,11 @@ internal fun MainPasswordContent( isHidden = confirmPasswordHidden, onClick = { confirmPasswordHidden = !confirmPasswordHidden } ) - } + }, + isError = state.confirmPasswordError != null, + supportingText = state.confirmPasswordError?.let { + { Text(text = it.error) } + }, ) } } @@ -127,7 +135,11 @@ private fun MainPasswordContentPreview() { SharedTransitionLayout { AnimatedVisibility(visible = true) { MainPasswordContent( - onContinue = {} + state = OnboardingUiState.SetMainPassword( + passwordTextFieldState = remember { TextFieldState() }, + confirmPasswordTextFieldState = remember { TextFieldState() }, + passwordScore = PasswordScore.Moderate + ), ) } } diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index d4cd6dd93..f3dfafac3 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -1,19 +1,134 @@ package de.davis.keygo.feature.onboarding.presentation +import androidx.compose.animation.AnimatedContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.sizeIn +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.davis.keygo.feature.onboarding.R +import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState +import org.koin.androidx.compose.koinViewModel @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable fun OnboardingScreen() { + val viewModel = koinViewModel() + val state by viewModel.state.collectAsStateWithLifecycle() + val contentHeight = ButtonDefaults.LargeContainerHeight + Scaffold( + modifier = Modifier + .fillMaxSize() + .padding(16.dp), + bottomBar = { + Column( + verticalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.padding(top = 8.dp) + ) { + state.optionalActionText?.let { + TextButton( + onClick = viewModel::onNextStep, + modifier = Modifier.fillMaxWidth(), + ) { + Text(text = it) + } + } + + if (state.isOutlinedButonCandidate()) + OutlinedButton( + onClick = viewModel::onNextStep, + shapes = ButtonDefaults.shapesFor(contentHeight), + modifier = Modifier + .sizeIn(minHeight = contentHeight) + .fillMaxWidth(), + contentPadding = ButtonDefaults.contentPaddingFor(contentHeight) + ) { + Text( + text = state.buttonText, + style = ButtonDefaults.textStyleFor(contentHeight), + ) + } + else Button( + onClick = viewModel::onNextStep, + shapes = ButtonDefaults.shapesFor(contentHeight), + modifier = Modifier + .sizeIn(minHeight = contentHeight) + .fillMaxWidth(), + contentPadding = ButtonDefaults.contentPaddingFor(contentHeight) + ) { + Text( + text = state.buttonText, + style = ButtonDefaults.textStyleFor(contentHeight), + ) + } + } + } + ) { innerPadding -> + Box( + modifier = Modifier.padding(innerPadding) + ) { + AnimatedContent(state, contentKey = { it::class }) { state -> + when (state) { + OnboardingUiState.Welcome -> WelcomeContent( + onContinue = viewModel::onNextStep + ) + + is OnboardingUiState.SetMainPassword -> MainPasswordContent(state = state) + + OnboardingUiState.EnableBiometrics -> EnableBiometricsContent() + OnboardingUiState.ImportData -> ImportVaultContent() + OnboardingUiState.EnableAutofill -> EnableAutofillContent() + } + } + } + } } +private val OnboardingUiState.buttonText: String + @Composable + get() = stringResource( + when (this) { + OnboardingUiState.Welcome -> R.string.get_started + is OnboardingUiState.SetMainPassword -> R.string.continue_text + OnboardingUiState.EnableBiometrics -> R.string.enable_biometrics + OnboardingUiState.ImportData -> R.string.skip_for_now + OnboardingUiState.EnableAutofill -> R.string.open_settings + } + ) + + +private val OnboardingUiState.optionalActionText: String? + @Composable + get() = when (this) { + OnboardingUiState.Welcome, + OnboardingUiState.ImportData, + is OnboardingUiState.SetMainPassword -> null + + OnboardingUiState.EnableBiometrics -> R.string.skip_for_now + OnboardingUiState.EnableAutofill -> R.string.finish_setup + }?.let { stringResource(it) } + +private fun OnboardingUiState.isOutlinedButonCandidate() = this is OnboardingUiState.ImportData + @Preview @Composable private fun OnboardingScreenPreview() { diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt new file mode 100644 index 000000000..97016decc --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -0,0 +1,148 @@ +package de.davis.keygo.feature.onboarding.presentation + +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.runtime.snapshotFlow +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator +import de.davis.keygo.core.item.domain.model.PasswordScore +import de.davis.keygo.core.ui.model.UiFieldError +import de.davis.keygo.feature.onboarding.presentation.model.OnboardingStep +import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.debounce +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.mapLatest +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.onStart +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update +import org.koin.core.annotation.KoinViewModel +import kotlin.time.Duration.Companion.milliseconds + +@KoinViewModel +internal class OnboardingViewModel( + private val passwordStrengthEstimator: PasswordStrengthEstimator +) : ViewModel() { + + private val passwordTextFieldState = TextFieldState() + private val confirmPasswordTextFieldState = TextFieldState() + + private val _mainPasswordState = MutableStateFlow( + OnboardingUiState.SetMainPassword( + passwordTextFieldState = passwordTextFieldState, + confirmPasswordTextFieldState = confirmPasswordTextFieldState, + passwordScore = PasswordScore.None + ) + ) + + private val _enableBiometricsState = MutableStateFlow( + OnboardingUiState.EnableBiometrics + ) + + private val _importDataState = MutableStateFlow( + OnboardingUiState.ImportData + ) + + private val _enableAutofillState = MutableStateFlow( + OnboardingUiState.EnableAutofill + ) + + private val _step = MutableStateFlow(OnboardingStep.Welcome) + + @OptIn(ExperimentalCoroutinesApi::class) + val state = _step.flatMapLatest { + when (it) { + OnboardingStep.Welcome -> flowOf(OnboardingUiState.Welcome) + OnboardingStep.SetMainPassword -> _mainPasswordState + OnboardingStep.EnableBiometrics -> _enableBiometricsState + OnboardingStep.ImportExistingData -> _importDataState + OnboardingStep.EnableAutofillService -> _enableAutofillState + } + }.onStart { + observePasswordStrength() + observePasswordError() + }.stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5_000), + initialValue = OnboardingUiState.Welcome + ) + + @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) + private fun observePasswordStrength() { + snapshotFlow { passwordTextFieldState.text } + .debounce(150.milliseconds) + .mapLatest { passwordStrengthEstimator(it.toString()) } + .distinctUntilChanged() + .onEach { score -> + _mainPasswordState.update { + it.copy(passwordScore = score) + } + } + .flowOn(Dispatchers.Default) + .launchIn(viewModelScope) + } + + @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) + private fun observePasswordError() { + combine( + snapshotFlow { passwordTextFieldState.text }, + snapshotFlow { confirmPasswordTextFieldState.text } + ) { pwd, confirmation -> + pwd.trim() to (pwd == confirmation) + }.debounce(150.milliseconds) + .distinctUntilChanged() + .onEach { (password, isEqual) -> + if (password.isNotBlank()) { + _mainPasswordState.update { + it.copy(passwordError = null) + } + } + + if (isEqual) { + _mainPasswordState.update { + it.copy(confirmPasswordError = null) + } + } + } + .launchIn(viewModelScope) + } + + fun onNextStep() { + val currentStep = _step.value + if (currentStep == OnboardingStep.SetMainPassword) { + val password = passwordTextFieldState.text.toString() + val confirmPassword = confirmPasswordTextFieldState.text.toString() + + if (password.isBlank()) { + _mainPasswordState.update { + it.copy(passwordError = UiFieldError.Empty) + } + return + } + + if (password != confirmPassword) { + _mainPasswordState.update { + it.copy(confirmPasswordError = UiFieldError.Mismatch) + } + return + } + } + + val nextStep = currentStep.nextStep() ?: return finishUp() + _step.update { nextStep } + } + + private fun finishUp() { + + } +} \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt index f25c6e746..d5ade4faa 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt @@ -36,8 +36,6 @@ internal fun WelcomeContent(onContinue: () -> Unit) { }, title = stringResource(R.string.welcome_title), description = stringResource(R.string.welcome_subtitle), - buttonText = stringResource(R.string.get_started), - onButtonClicked = onContinue, contentHorizontalAlignment = Alignment.CenterHorizontally ) { // No content for Welcome diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/component/OnboardingScaffold.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/component/OnboardingScaffold.kt index d446f50df..af730f97c 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/component/OnboardingScaffold.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/component/OnboardingScaffold.kt @@ -7,16 +7,11 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -85,19 +80,12 @@ internal fun OnboardingScaffold( iconContainer: @Composable () -> Unit, title: String, description: String, - buttonText: String, - onButtonClicked: () -> Unit, - buttonOutlined: Boolean = false, contentHorizontalAlignment: Alignment.Horizontal = Alignment.Start, info: (@Composable () -> Unit)? = null, - optionalAction: (@Composable () -> Unit)? = null, content: @Composable () -> Unit, ) { - val contentHeight = ButtonDefaults.LargeContainerHeight Column( - modifier = Modifier - .fillMaxSize() - .padding(16.dp) + modifier = Modifier.fillMaxSize() ) { Column( modifier = Modifier @@ -125,39 +113,6 @@ internal fun OnboardingScaffold( content() } - Column( - verticalArrangement = Arrangement.spacedBy(8.dp) - ) { - info?.invoke() - optionalAction?.invoke() - - if (buttonOutlined) - OutlinedButton( - onClick = onButtonClicked, - shapes = ButtonDefaults.shapesFor(contentHeight), - modifier = Modifier - .sizeIn(minHeight = contentHeight) - .fillMaxWidth(), - contentPadding = ButtonDefaults.contentPaddingFor(contentHeight) - ) { - Text( - text = buttonText, - style = ButtonDefaults.textStyleFor(contentHeight), - ) - } - else Button( - onClick = onButtonClicked, - shapes = ButtonDefaults.shapesFor(contentHeight), - modifier = Modifier - .sizeIn(minHeight = contentHeight) - .fillMaxWidth(), - contentPadding = ButtonDefaults.contentPaddingFor(contentHeight) - ) { - Text( - text = buttonText, - style = ButtonDefaults.textStyleFor(contentHeight), - ) - } - } + info?.invoke() } } \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt new file mode 100644 index 000000000..734dfced7 --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt @@ -0,0 +1,19 @@ +package de.davis.keygo.feature.onboarding.presentation.model + +internal enum class OnboardingStep { + Welcome, + SetMainPassword, + EnableBiometrics, + ImportExistingData, + EnableAutofillService; + + fun nextStep(): OnboardingStep? { + return when (this) { + Welcome -> SetMainPassword + SetMainPassword -> EnableBiometrics + EnableBiometrics -> ImportExistingData + ImportExistingData -> EnableAutofillService + EnableAutofillService -> null + } + } +} \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt new file mode 100644 index 000000000..deee4ffe2 --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt @@ -0,0 +1,22 @@ +package de.davis.keygo.feature.onboarding.presentation.model + +import androidx.compose.foundation.text.input.TextFieldState +import de.davis.keygo.core.item.domain.model.PasswordScore +import de.davis.keygo.core.ui.model.UiFieldError + +internal sealed interface OnboardingUiState { + + data object Welcome : OnboardingUiState + + data class SetMainPassword( + val passwordTextFieldState: TextFieldState, + val confirmPasswordTextFieldState: TextFieldState, + val passwordScore: PasswordScore, + val passwordError: UiFieldError? = null, + val confirmPasswordError: UiFieldError? = null, + ) : OnboardingUiState + + data object EnableBiometrics : OnboardingUiState + data object ImportData : OnboardingUiState + data object EnableAutofill : OnboardingUiState +} From 0a46da05da31d27f7f282ff9f1b8a26778cdc029 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Wed, 5 Aug 2026 20:35:03 +0200 Subject: [PATCH 05/24] feat(onboarding): skip steps if not needed --- .../kotlin/de/davis/keygo/app/di/AppModule.kt | 2 ++ .../keygo/app/presentation/AppViewModel.kt | 15 ++++++++ .../keygo/app/presentation/MainActivity.kt | 25 ++++++++++++- feature/onboarding/build.gradle.kts | 6 ++++ .../presentation/OnboardingGraph.kt | 36 +++++++++++++++++++ .../presentation/OnboardingScreen.kt | 6 ++-- .../presentation/OnboardingViewModel.kt | 32 ++++++++++++++++- .../presentation/model/OnboardingStep.kt | 11 ++---- 8 files changed, 121 insertions(+), 12 deletions(-) create mode 100644 app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingGraph.kt diff --git a/app/src/main/kotlin/de/davis/keygo/app/di/AppModule.kt b/app/src/main/kotlin/de/davis/keygo/app/di/AppModule.kt index 218a6e699..3ad2db030 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/di/AppModule.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/di/AppModule.kt @@ -1,6 +1,7 @@ package de.davis.keygo.app.di import de.davis.keygo.dashboard.di.DashboardModule +import org.koin.core.annotation.ComponentScan import org.koin.core.annotation.Configuration import org.koin.core.annotation.Module @@ -9,6 +10,7 @@ import org.koin.core.annotation.Module DashboardModule::class, ] ) +@ComponentScan("de.davis.keygo.app") @Configuration object AppModule diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt new file mode 100644 index 000000000..ed8f2f053 --- /dev/null +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt @@ -0,0 +1,15 @@ +package de.davis.keygo.app.presentation + +import androidx.lifecycle.ViewModel +import de.davis.keygo.core.identity.domain.repository.AccountRepository +import de.davis.keygo.migration.create_access.domain.usecase.HasMainPasswordUseCase +import org.koin.core.annotation.KoinViewModel + +@KoinViewModel +internal class AppViewModel( + private val hasV1Password: HasMainPasswordUseCase, + private val accountRepository: AccountRepository +) : ViewModel() { + + suspend fun hasValidAccount() = accountRepository.getOrNull() != null && !hasV1Password() +} \ No newline at end of file diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt index 0552f4cd1..575184ce6 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt @@ -14,6 +14,7 @@ import androidx.compose.material3.adaptive.navigation.rememberListDetailPaneScaf import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier @@ -42,10 +43,13 @@ import de.davis.keygo.feature.auth.presentation.AuthRoute import de.davis.keygo.feature.auth.presentation.authGraph import de.davis.keygo.feature.backup.presentation.BackupHubRoute import de.davis.keygo.feature.backup.presentation.backupGraph +import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute +import de.davis.keygo.feature.onboarding.presentation.onboardingGraph import de.davis.keygo.feature.settings.presentation.ChangePasswordRoute import de.davis.keygo.feature.settings.presentation.settingsGraph import de.davis.keygo.item.dialog.SelectItemContent import kotlinx.coroutines.launch +import org.koin.androidx.compose.koinViewModel import org.koin.compose.koinInject class MainActivity : FragmentActivity() { @@ -94,6 +98,13 @@ private fun App() { val scope = rememberCoroutineScope() + val viewModel = koinViewModel() + val hasAccess by produceState(null) { + value = viewModel.hasValidAccount() + } + + if (hasAccess == null) return // TODO: Add this to splash screen + KeyGoNavigationWrapper( currentDestination = currentDestination, navigateToTopLevelDestination = { @@ -125,7 +136,7 @@ private fun App() { ) { NavHost( navController = navController, - startDestination = AuthRoute(), + startDestination = if (hasAccess == true) AuthRoute() else OnboardingRoute(), ) { authGraph( onSuccess = { totpUri -> @@ -139,6 +150,18 @@ private fun App() { } ) + onboardingGraph( + onSuccess = { totpUri -> + val dest = totpUri?.let { + RouteDestination.Home.Root(it) + } ?: RouteDestination.TopLevelAppGraph + + navController.navigate(dest) { + popUpTo { inclusive = true } + } + } + ) + navigation( startDestination = RouteDestination.Home.NavGraph ) { diff --git a/feature/onboarding/build.gradle.kts b/feature/onboarding/build.gradle.kts index c1e825675..20a6c0a61 100644 --- a/feature/onboarding/build.gradle.kts +++ b/feature/onboarding/build.gradle.kts @@ -1,5 +1,6 @@ plugins { alias(libs.plugins.keygo.android.compose) + alias(libs.plugins.kotlin.serialization) } android { @@ -9,5 +10,10 @@ android { dependencies { implementation(projects.core.ui) implementation(projects.core.item) + implementation(projects.core.identity) implementation(projects.feature.backup) + implementation(projects.feature.autofill) + implementation(projects.migration.createAccess) + + implementation(libs.androidx.navigation.compose) } diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingGraph.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingGraph.kt new file mode 100644 index 000000000..391df6771 --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingGraph.kt @@ -0,0 +1,36 @@ +package de.davis.keygo.feature.onboarding.presentation + +import androidx.navigation.NavGraphBuilder +import androidx.navigation.compose.composable +import androidx.navigation.navDeepLink +import androidx.navigation.toRoute +import de.davis.keygo.core.ui.RouteDestination +import kotlinx.serialization.Serializable + + +fun NavGraphBuilder.onboardingGraph(onSuccess: (String?) -> Unit) { + composable( + deepLinks = listOf( + navDeepLink(basePath = "otpauth://totp") { + uriPattern = "otpauth://totp/{totpInfo}?{queries}" + } + ) + ) { s -> + OnboardingScreen( + onSuccess = { + onSuccess(s.toRoute().uri) + } + ) + } +} + +@Serializable +data class OnboardingRoute( + val totpInfo: String? = null, + val queries: String? = null, +) : RouteDestination { + val uri + get() = if (!totpInfo.isNullOrBlank() && !queries.isNullOrBlank()) + "otpauth://totp/$totpInfo?$queries" + else null +} \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index f3dfafac3..b416061a8 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -30,7 +30,7 @@ import org.koin.androidx.compose.koinViewModel @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -fun OnboardingScreen() { +fun OnboardingScreen(onSuccess: () -> Unit) { val viewModel = koinViewModel() val state by viewModel.state.collectAsStateWithLifecycle() @@ -136,7 +136,9 @@ private fun OnboardingScreenPreview() { Surface( modifier = Modifier.fillMaxSize(), ) { - OnboardingScreen() + OnboardingScreen( + onSuccess = {} + ) } } } \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index 97016decc..78cb143b7 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -4,11 +4,16 @@ import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import de.davis.keygo.core.identity.domain.repository.AccountRepository import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator import de.davis.keygo.core.item.domain.model.PasswordScore +import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository import de.davis.keygo.core.ui.model.UiFieldError +import de.davis.keygo.feature.autofill.domain.repository.AutofillServiceRepository +import de.davis.keygo.feature.autofill.domain.repository.ChromeAutofillRepository import de.davis.keygo.feature.onboarding.presentation.model.OnboardingStep import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState +import de.davis.keygo.migration.create_access.domain.usecase.HasMainPasswordUseCase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview @@ -26,14 +31,39 @@ import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch import org.koin.core.annotation.KoinViewModel import kotlin.time.Duration.Companion.milliseconds @KoinViewModel internal class OnboardingViewModel( + private val biometricAvailabilityRepository: BiometricAvailabilityRepository, + private val hasV1Password: HasMainPasswordUseCase, + private val accountRepository: AccountRepository, + private val autofillServiceRepository: AutofillServiceRepository, + private val chromeAutofillRepository: ChromeAutofillRepository, + private val passwordStrengthEstimator: PasswordStrengthEstimator ) : ViewModel() { + private val stepsToSkip = MutableStateFlow>(emptySet()) + + init { + calculateStepsToSkip() + } + + private fun calculateStepsToSkip() { + viewModelScope.launch { + val skipSteps = buildSet { + if (!biometricAvailabilityRepository.availability()) add(OnboardingStep.EnableBiometrics) + if (accountRepository.getOrNull() != null || hasV1Password()) add(OnboardingStep.ImportExistingData) + if (autofillServiceRepository.isEnabled() && chromeAutofillRepository.isAutofillEnabled()) + add(OnboardingStep.EnableAutofillService) + } + stepsToSkip.update { skipSteps } + } + } + private val passwordTextFieldState = TextFieldState() private val confirmPasswordTextFieldState = TextFieldState() @@ -138,7 +168,7 @@ internal class OnboardingViewModel( } } - val nextStep = currentStep.nextStep() ?: return finishUp() + val nextStep = currentStep.nextStep(stepsToSkip.value) ?: return finishUp() _step.update { nextStep } } diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt index 734dfced7..3ba6f4956 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt @@ -7,13 +7,8 @@ internal enum class OnboardingStep { ImportExistingData, EnableAutofillService; - fun nextStep(): OnboardingStep? { - return when (this) { - Welcome -> SetMainPassword - SetMainPassword -> EnableBiometrics - EnableBiometrics -> ImportExistingData - ImportExistingData -> EnableAutofillService - EnableAutofillService -> null - } + fun nextStep(skip: Set): OnboardingStep? { + val pool = OnboardingStep.entries.filterNot { it in skip } + return pool.getOrNull(pool.indexOf(this) + 1) } } \ No newline at end of file From cff16f52f8532257667a4933c5871d50da274f5a Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Wed, 5 Aug 2026 22:37:23 +0200 Subject: [PATCH 06/24] feat(onboarding): wire up access creation --- .../presentation/MainPasswordContent.kt | 8 ++ .../presentation/OnboardingScreen.kt | 58 ++++++++----- .../presentation/OnboardingViewModel.kt | 84 +++++++++++++++---- 3 files changed, 116 insertions(+), 34 deletions(-) diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt index 59e269d05..266b444c9 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/MainPasswordContent.kt @@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.foundation.text.input.TextObfuscationMode import androidx.compose.material.icons.Icons @@ -29,6 +30,8 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import de.davis.keygo.core.item.domain.model.PasswordScore @@ -98,6 +101,11 @@ internal fun MainPasswordContent( supportingText = state.passwordError?.let { { Text(text = it.error) } }, + keyboardOptions = KeyboardOptions( + imeAction = ImeAction.Next, + autoCorrectEnabled = false, + keyboardType = KeyboardType.Password + ) ) StrengthIndicator( diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index b416061a8..df9a63852 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -1,5 +1,6 @@ package de.davis.keygo.feature.onboarding.presentation +import android.util.Log import androidx.compose.animation.AnimatedContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -8,32 +9,54 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.sizeIn +import androidx.compose.material3.BasicAlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.ContainedLoadingIndicator +import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Scaffold -import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource -import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.davis.keygo.core.security.domain.model.CryptographicMode +import de.davis.keygo.core.security.domain.model.KeyId +import de.davis.keygo.core.security.presentation.rememberBiometricCryptoController +import de.davis.keygo.core.util.onFailure +import de.davis.keygo.core.util.onSuccess +import de.davis.keygo.core.util.presentation.ObserveAsEvents import de.davis.keygo.feature.onboarding.R import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState import org.koin.androidx.compose.koinViewModel -@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) @Composable fun OnboardingScreen(onSuccess: () -> Unit) { val viewModel = koinViewModel() val state by viewModel.state.collectAsStateWithLifecycle() + val loading by viewModel.loading.collectAsStateWithLifecycle() + + val biometricCryptoController = rememberBiometricCryptoController() + ObserveAsEvents(viewModel.biometricFlow) { + biometricCryptoController.requestCipher( + keyId = KeyId.BiometricVaultKek, + mode = CryptographicMode.Wrap + ).onSuccess { + viewModel.performCreateAccess(it) + }.onFailure { + Log.e("OnboardingScreen", "Failed to create cipher for biometric access: $it") + // TODO: show error + } + } + val contentHeight = ButtonDefaults.LargeContainerHeight Scaffold( modifier = Modifier @@ -46,7 +69,7 @@ fun OnboardingScreen(onSuccess: () -> Unit) { ) { state.optionalActionText?.let { TextButton( - onClick = viewModel::onNextStep, + onClick = viewModel::onSkip, modifier = Modifier.fillMaxWidth(), ) { Text(text = it) @@ -101,6 +124,17 @@ fun OnboardingScreen(onSuccess: () -> Unit) { } } } + + if (loading) + BasicAlertDialog( + onDismissRequest = {} + ) { + Box( + contentAlignment = Alignment.Center + ) { + ContainedLoadingIndicator() + } + } } private val OnboardingUiState.buttonText: String @@ -128,17 +162,3 @@ private val OnboardingUiState.optionalActionText: String? }?.let { stringResource(it) } private fun OnboardingUiState.isOutlinedButonCandidate() = this is OnboardingUiState.ImportData - -@Preview -@Composable -private fun OnboardingScreenPreview() { - MaterialTheme { - Surface( - modifier = Modifier.fillMaxSize(), - ) { - OnboardingScreen( - onSuccess = {} - ) - } - } -} \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index 78cb143b7..d81bdbf58 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -5,10 +5,12 @@ import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import de.davis.keygo.core.identity.domain.repository.AccountRepository +import de.davis.keygo.core.identity.domain.usecase.CreateAccessUseCase import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository import de.davis.keygo.core.ui.model.UiFieldError +import de.davis.keygo.core.util.onSuccess import de.davis.keygo.feature.autofill.domain.repository.AutofillServiceRepository import de.davis.keygo.feature.autofill.domain.repository.ChromeAutofillRepository import de.davis.keygo.feature.onboarding.presentation.model.OnboardingStep @@ -17,8 +19,10 @@ import de.davis.keygo.migration.create_access.domain.usecase.HasMainPasswordUseC import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged @@ -29,10 +33,12 @@ import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.onStart +import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.koin.core.annotation.KoinViewModel +import javax.crypto.Cipher import kotlin.time.Duration.Companion.milliseconds @KoinViewModel @@ -43,7 +49,8 @@ internal class OnboardingViewModel( private val autofillServiceRepository: AutofillServiceRepository, private val chromeAutofillRepository: ChromeAutofillRepository, - private val passwordStrengthEstimator: PasswordStrengthEstimator + private val passwordStrengthEstimator: PasswordStrengthEstimator, + private val createAccess: CreateAccessUseCase, ) : ViewModel() { private val stepsToSkip = MutableStateFlow>(emptySet()) @@ -87,6 +94,13 @@ internal class OnboardingViewModel( OnboardingUiState.EnableAutofill ) + + private val biometricChannel = Channel() + val biometricFlow = biometricChannel.receiveAsFlow() + + private val _loading = MutableStateFlow(false) + val loading = _loading.asStateFlow() + private val _step = MutableStateFlow(OnboardingStep.Welcome) @OptIn(ExperimentalCoroutinesApi::class) @@ -148,31 +162,71 @@ internal class OnboardingViewModel( } fun onNextStep() { - val currentStep = _step.value - if (currentStep == OnboardingStep.SetMainPassword) { - val password = passwordTextFieldState.text.toString() - val confirmPassword = confirmPasswordTextFieldState.text.toString() + when (_step.value) { + OnboardingStep.SetMainPassword -> { + val password = passwordTextFieldState.text.toString() + val confirmPassword = confirmPasswordTextFieldState.text.toString() - if (password.isBlank()) { - _mainPasswordState.update { - it.copy(passwordError = UiFieldError.Empty) + if (password.isBlank()) { + _mainPasswordState.update { + it.copy(passwordError = UiFieldError.Empty) + } + return } - return + + if (password != confirmPassword) { + _mainPasswordState.update { + it.copy(confirmPasswordError = UiFieldError.Mismatch) + } + return + } + + if (OnboardingStep.EnableBiometrics in stepsToSkip.value) performCreateAccess() } - if (password != confirmPassword) { - _mainPasswordState.update { - it.copy(confirmPasswordError = UiFieldError.Mismatch) + OnboardingStep.EnableBiometrics -> { + biometricChannel.trySend(Unit) + return // wait for biometric result before proceeding to next step + } + + else -> {} + } + + internalSkip() + } + + fun performCreateAccess(cipher: Cipher? = null) { + viewModelScope.launch { + loading { + createAccess( + password = passwordTextFieldState.text.toString(), + biometricCipher = cipher + ).onSuccess { + internalSkip() } - return } } + } - val nextStep = currentStep.nextStep(stepsToSkip.value) ?: return finishUp() + fun onSkip() { + if (_step.value == OnboardingStep.EnableBiometrics) return performCreateAccess() + + internalSkip() + } + + private fun internalSkip() { + val nextStep = _step.value.nextStep(stepsToSkip.value) ?: return finishUp() _step.update { nextStep } } private fun finishUp() { } -} \ No newline at end of file + + private suspend fun loading(block: suspend () -> R): R { + _loading.update { true } + return block().also { + _loading.update { false } + } + } +} From 75c43c682cd9937cd637ec96140cb801c8ab24ee Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Thu, 6 Aug 2026 22:30:58 +0200 Subject: [PATCH 07/24] feat(onboarding): show different message for migration --- .../onboarding/presentation/OnboardingScreen.kt | 7 ++++--- .../presentation/OnboardingViewModel.kt | 17 +++++++++++++---- .../onboarding/presentation/WelcomeContent.kt | 8 +++++--- .../presentation/model/OnboardingUiState.kt | 2 +- .../onboarding/src/main/res/values/strings.xml | 3 +++ 5 files changed, 26 insertions(+), 11 deletions(-) diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index df9a63852..f45f7ab68 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -111,7 +111,8 @@ fun OnboardingScreen(onSuccess: () -> Unit) { ) { AnimatedContent(state, contentKey = { it::class }) { state -> when (state) { - OnboardingUiState.Welcome -> WelcomeContent( + is OnboardingUiState.Welcome -> WelcomeContent( + state = state, onContinue = viewModel::onNextStep ) @@ -141,7 +142,7 @@ private val OnboardingUiState.buttonText: String @Composable get() = stringResource( when (this) { - OnboardingUiState.Welcome -> R.string.get_started + is OnboardingUiState.Welcome -> if (migrating) R.string.migrate else R.string.get_started is OnboardingUiState.SetMainPassword -> R.string.continue_text OnboardingUiState.EnableBiometrics -> R.string.enable_biometrics OnboardingUiState.ImportData -> R.string.skip_for_now @@ -153,7 +154,7 @@ private val OnboardingUiState.buttonText: String private val OnboardingUiState.optionalActionText: String? @Composable get() = when (this) { - OnboardingUiState.Welcome, + is OnboardingUiState.Welcome, OnboardingUiState.ImportData, is OnboardingUiState.SetMainPassword -> null diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index d81bdbf58..40c16530d 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -27,7 +27,6 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flatMapLatest -import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.mapLatest @@ -54,6 +53,7 @@ internal class OnboardingViewModel( ) : ViewModel() { private val stepsToSkip = MutableStateFlow>(emptySet()) + private val isMigrating = MutableStateFlow(false) init { calculateStepsToSkip() @@ -61,13 +61,17 @@ internal class OnboardingViewModel( private fun calculateStepsToSkip() { viewModelScope.launch { + val hasAccount = accountRepository.getOrNull() != null + val hasLegacyPassword = hasV1Password() + val skipSteps = buildSet { if (!biometricAvailabilityRepository.availability()) add(OnboardingStep.EnableBiometrics) - if (accountRepository.getOrNull() != null || hasV1Password()) add(OnboardingStep.ImportExistingData) + if (hasAccount || hasLegacyPassword) add(OnboardingStep.ImportExistingData) if (autofillServiceRepository.isEnabled() && chromeAutofillRepository.isAutofillEnabled()) add(OnboardingStep.EnableAutofillService) } stepsToSkip.update { skipSteps } + isMigrating.update { hasLegacyPassword && !hasAccount } } } @@ -106,7 +110,12 @@ internal class OnboardingViewModel( @OptIn(ExperimentalCoroutinesApi::class) val state = _step.flatMapLatest { when (it) { - OnboardingStep.Welcome -> flowOf(OnboardingUiState.Welcome) + OnboardingStep.Welcome -> isMigrating.mapLatest { migrating -> + OnboardingUiState.Welcome( + migrating + ) + } + OnboardingStep.SetMainPassword -> _mainPasswordState OnboardingStep.EnableBiometrics -> _enableBiometricsState OnboardingStep.ImportExistingData -> _importDataState @@ -118,7 +127,7 @@ internal class OnboardingViewModel( }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), - initialValue = OnboardingUiState.Welcome + initialValue = OnboardingUiState.Welcome() ) @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt index d5ade4faa..8f69759c1 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt @@ -18,11 +18,12 @@ import androidx.compose.ui.tooling.preview.Preview import de.davis.keygo.feature.onboarding.R import de.davis.keygo.feature.onboarding.presentation.component.LargeIconContainer import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffold +import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState import de.davis.keygo.core.ui.R as CoreUiR @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -internal fun WelcomeContent(onContinue: () -> Unit) { +internal fun WelcomeContent(state: OnboardingUiState.Welcome, onContinue: () -> Unit) { OnboardingScaffold( iconContainer = { LargeIconContainer( @@ -34,8 +35,8 @@ internal fun WelcomeContent(onContinue: () -> Unit) { ) } }, - title = stringResource(R.string.welcome_title), - description = stringResource(R.string.welcome_subtitle), + title = stringResource(if (state.migrating) R.string.welcome_migrating_title else R.string.welcome_title), + description = stringResource(if (state.migrating) R.string.welcome_migrating_subtitle else R.string.welcome_subtitle), contentHorizontalAlignment = Alignment.CenterHorizontally ) { // No content for Welcome @@ -50,6 +51,7 @@ private fun WelcomeContentPreview() { SharedTransitionLayout { AnimatedVisibility(visible = true) { WelcomeContent( + state = OnboardingUiState.Welcome(), onContinue = {} ) } diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt index deee4ffe2..536d2ec98 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt @@ -6,7 +6,7 @@ import de.davis.keygo.core.ui.model.UiFieldError internal sealed interface OnboardingUiState { - data object Welcome : OnboardingUiState + data class Welcome(val migrating: Boolean = false) : OnboardingUiState data class SetMainPassword( val passwordTextFieldState: TextFieldState, diff --git a/feature/onboarding/src/main/res/values/strings.xml b/feature/onboarding/src/main/res/values/strings.xml index b5e4f3c2c..962ef8031 100644 --- a/feature/onboarding/src/main/res/values/strings.xml +++ b/feature/onboarding/src/main/res/values/strings.xml @@ -1,6 +1,7 @@ Get Started + Migrate Continue Skip for now Enable Biometrics @@ -10,6 +11,8 @@ Own your credentials, own your privacy. KeyGo encrypts everything locally. No servers, no cloud, no tracking. Just you and your data. + Welcome back. + You already have a KeyGo vault on this device. Let\'s finish setting up your account. Set your main password This password will encrypt your vaults. KeyGo never stores this password. Make it secure. From c6f8fe6bcc3a438a4e82852dc92baec17c830d88 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Fri, 7 Aug 2026 22:21:43 +0200 Subject: [PATCH 08/24] feat(onboarding): wire up autofill setup --- .../ChromeAutofillRepositoryImpl.kt | 58 ++++-- .../repository/ChromeAutofillRepository.kt | 11 +- .../autofill/FakeChromeAutofillRepository.kt | 8 +- feature/onboarding/build.gradle.kts | 4 + .../presentation/EnableAutofillContent.kt | 125 +++++++------ .../presentation/OnboardingScreen.kt | 54 +++++- .../presentation/OnboardingViewModel.kt | 59 +++++- .../presentation/model/AutofillSetup.kt | 43 +++++ .../presentation/model/OnboardingUiState.kt | 21 ++- .../src/main/res/values/strings.xml | 2 +- .../presentation/model/AutofillSetupTest.kt | 168 ++++++++++++++++++ 11 files changed, 466 insertions(+), 87 deletions(-) create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/AutofillSetup.kt create mode 100644 feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/AutofillSetupTest.kt diff --git a/feature/autofill/src/main/kotlin/de/davis/keygo/feature/autofill/data/repository/ChromeAutofillRepositoryImpl.kt b/feature/autofill/src/main/kotlin/de/davis/keygo/feature/autofill/data/repository/ChromeAutofillRepositoryImpl.kt index 901f21d07..a656c23d2 100644 --- a/feature/autofill/src/main/kotlin/de/davis/keygo/feature/autofill/data/repository/ChromeAutofillRepositoryImpl.kt +++ b/feature/autofill/src/main/kotlin/de/davis/keygo/feature/autofill/data/repository/ChromeAutofillRepositoryImpl.kt @@ -3,8 +3,12 @@ package de.davis.keygo.feature.autofill.data.repository import android.content.ContentResolver import android.content.Context import android.content.Intent +import android.database.Cursor import android.net.Uri +import android.util.Log import de.davis.keygo.feature.autofill.domain.repository.ChromeAutofillRepository +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import org.koin.core.annotation.Single @Single @@ -12,26 +16,40 @@ internal class ChromeAutofillRepositoryImpl( private val context: Context, ) : ChromeAutofillRepository { - override fun isAutofillEnabled(): Boolean { - val uri = Uri.Builder() + private val thirdPartyModeUri: Uri + get() = Uri.Builder() .scheme(ContentResolver.SCHEME_CONTENT) .authority(CHROME_CHANNEL_PACKAGE + CONTENT_PROVIDER_NAME) .path(THIRD_PARTY_MODE_ACTIONS_URI_PATH) .build() - return context.contentResolver.query( - uri, - arrayOf(THIRD_PARTY_MODE_COLUMN), - null, - null, - null, - )?.use { - if (!it.moveToFirst()) return false - - val thirdPartyModeState = it.getInt(it.getColumnIndexOrThrow(THIRD_PARTY_MODE_COLUMN)) - thirdPartyModeState == 1 // 1 means third-party autofill is enabled. - } == true - } + private suspend fun useQueryThirdPartyMode(block: (Cursor) -> R): R? = + withContext(Dispatchers.IO) { + try { + context.contentResolver.query( + thirdPartyModeUri, + arrayOf(THIRD_PARTY_MODE_COLUMN), + null, + null, + null, + )?.use(block) + } catch (e: RuntimeException) { + // A provider that answers for the authority but refuses the read is + // indistinguishable, for our purposes, from no provider at all. + Log.w(TAG, "Failed to query Chrome's third party autofill mode provider", e) + null + } + } + + override suspend fun isAvailable(): Boolean = useQueryThirdPartyMode { true } == true + + override suspend fun isAutofillEnabled(): Boolean = useQueryThirdPartyMode { cursor -> + if (!cursor.moveToFirst()) return@useQueryThirdPartyMode false + + val thirdPartyModeState = + cursor.getInt(cursor.getColumnIndexOrThrow(THIRD_PARTY_MODE_COLUMN)) + thirdPartyModeState == 1 // 1 means third-party autofill is enabled. + } == true override fun openChromeAutofillSettings() { val intent = Intent(Intent.ACTION_APPLICATION_PREFERENCES).apply { @@ -46,9 +64,11 @@ internal class ChromeAutofillRepositoryImpl( } private companion object { - private val CHROME_CHANNEL_PACKAGE = "com.android.chrome" // Chrome Stable. - private val CONTENT_PROVIDER_NAME = ".AutofillThirdPartyModeContentProvider" - private val THIRD_PARTY_MODE_COLUMN = "autofill_third_party_state" - private val THIRD_PARTY_MODE_ACTIONS_URI_PATH = "autofill_third_party_mode" + private const val TAG = "ChromeAutofillRepositoryImpl" + + private const val CHROME_CHANNEL_PACKAGE = "com.android.chrome" + private const val CONTENT_PROVIDER_NAME = ".AutofillThirdPartyModeContentProvider" + private const val THIRD_PARTY_MODE_COLUMN = "autofill_third_party_state" + private const val THIRD_PARTY_MODE_ACTIONS_URI_PATH = "autofill_third_party_mode" } } \ No newline at end of file diff --git a/feature/autofill/src/main/kotlin/de/davis/keygo/feature/autofill/domain/repository/ChromeAutofillRepository.kt b/feature/autofill/src/main/kotlin/de/davis/keygo/feature/autofill/domain/repository/ChromeAutofillRepository.kt index 8ad5d0322..20f853bf1 100644 --- a/feature/autofill/src/main/kotlin/de/davis/keygo/feature/autofill/domain/repository/ChromeAutofillRepository.kt +++ b/feature/autofill/src/main/kotlin/de/davis/keygo/feature/autofill/domain/repository/ChromeAutofillRepository.kt @@ -2,7 +2,14 @@ package de.davis.keygo.feature.autofill.domain.repository interface ChromeAutofillRepository { - fun isAutofillEnabled(): Boolean + /** + * Whether Chrome is installed and exposes third party autofill mode. Callers that offer to open + * Chrome's settings should check this first: without the provider there is nothing to read and + * nothing for the user to turn on. + */ + suspend fun isAvailable(): Boolean + + suspend fun isAutofillEnabled(): Boolean fun openChromeAutofillSettings() -} \ No newline at end of file +} diff --git a/feature/autofill/src/testFixtures/kotlin/de/davis/keygo/core/feature/autofill/FakeChromeAutofillRepository.kt b/feature/autofill/src/testFixtures/kotlin/de/davis/keygo/core/feature/autofill/FakeChromeAutofillRepository.kt index 9d6474263..4d8d95ab0 100644 --- a/feature/autofill/src/testFixtures/kotlin/de/davis/keygo/core/feature/autofill/FakeChromeAutofillRepository.kt +++ b/feature/autofill/src/testFixtures/kotlin/de/davis/keygo/core/feature/autofill/FakeChromeAutofillRepository.kt @@ -4,11 +4,17 @@ import de.davis.keygo.feature.autofill.domain.repository.ChromeAutofillRepositor class FakeChromeAutofillRepository : ChromeAutofillRepository { + // Chrome is present and exposes third party autofill mode. Flip it to model a device with no + // Chrome, where the enabled read can never come back true. + var available: Boolean = true + var enabled: Boolean = false var openCalled: Boolean = false - override fun isAutofillEnabled(): Boolean = enabled + override suspend fun isAvailable(): Boolean = available + + override suspend fun isAutofillEnabled(): Boolean = available && enabled override fun openChromeAutofillSettings() { openCalled = true diff --git a/feature/onboarding/build.gradle.kts b/feature/onboarding/build.gradle.kts index 20a6c0a61..98ffcb9ba 100644 --- a/feature/onboarding/build.gradle.kts +++ b/feature/onboarding/build.gradle.kts @@ -5,6 +5,10 @@ plugins { android { namespace = "de.davis.keygo.feature.onboarding" + + defaultConfig { + missingDimensionStrategy("store", "playStore") + } } dependencies { diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt index f51c998bf..226f560b9 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/EnableAutofillContent.kt @@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AutoFixHigh +import androidx.compose.material.icons.filled.Check import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.ListItemDefaults @@ -22,7 +23,6 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp @@ -30,10 +30,16 @@ import androidx.compose.ui.unit.dp import de.davis.keygo.feature.onboarding.R import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffold import de.davis.keygo.feature.onboarding.presentation.component.SmallIconContainer +import de.davis.keygo.feature.onboarding.presentation.model.AutofillSetupStatus +import de.davis.keygo.feature.onboarding.presentation.model.AutofillSetupStep +import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState +import de.davis.keygo.feature.onboarding.presentation.model.setupSteps @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -internal fun EnableAutofillContent() { +internal fun EnableAutofillContent(state: OnboardingUiState.EnableAutofill) { + val steps = state.setupSteps() + OnboardingScaffold( iconContainer = { SmallIconContainer( @@ -51,65 +57,42 @@ internal fun EnableAutofillContent() { Column( verticalArrangement = Arrangement.spacedBy(ListItemDefaults.SegmentedGap) ) { - SegmentedListItem( - shapes = ListItemDefaults.segmentedShapes(0, 3), - leadingContent = { - NumberBadge( - number = 1, - containerColor = MaterialTheme.colorScheme.primary, - contentColor = MaterialTheme.colorScheme.onPrimary - ) - }, - supportingContent = { - Text(text = stringResource(R.string.autofill_open_settings_support)) + steps.forEachIndexed { index, (step, status) -> + SegmentedListItem( + shapes = ListItemDefaults.segmentedShapes(index, steps.size), + leadingContent = { + StepBadge( + number = index + 1, + status = status, + ) + }, + supportingContent = { + Text(text = stringResource(step.supportingRes)) + } + ) { + Text(text = stringResource(step.titleRes)) } - ) { - Text(text = stringResource(R.string.autofill_open_settings)) - } - - SegmentedListItem( - shapes = ListItemDefaults.segmentedShapes(1, 3), - leadingContent = { - NumberBadge( - number = 2, - containerColor = MaterialTheme.colorScheme.primaryContainer, - contentColor = MaterialTheme.colorScheme.onPrimaryContainer - ) - }, - supportingContent = { - Text(text = stringResource(R.string.autofill_choose_keygo_support)) - } - ) { - Text(text = stringResource(R.string.autofill_choose_keygo)) - } - - SegmentedListItem( - shapes = ListItemDefaults.segmentedShapes(2, 3), - leadingContent = { - NumberBadge( - number = 3, - containerColor = MaterialTheme.colorScheme.primaryContainer, - contentColor = MaterialTheme.colorScheme.onPrimaryContainer - ) - }, - supportingContent = { - Text(text = stringResource(R.string.autofill_chrome_support)) - } - ) { - Text(text = stringResource(R.string.autofill_chrome)) } } } } @Composable -internal fun NumberBadge( +internal fun StepBadge( number: Int, - containerColor: Color, - contentColor: Color, + status: AutofillSetupStatus, modifier: Modifier = Modifier, size: Dp = 40.dp, ) { + val containerColor = when (status) { + AutofillSetupStatus.Current -> MaterialTheme.colorScheme.primary + else -> MaterialTheme.colorScheme.primaryContainer + } + val contentColor = when (status) { + AutofillSetupStatus.Current -> MaterialTheme.colorScheme.onPrimary + else -> MaterialTheme.colorScheme.onPrimaryContainer + } + Box( modifier = modifier .size(size) @@ -117,7 +100,13 @@ internal fun NumberBadge( .background(containerColor), contentAlignment = Alignment.Center, ) { - Text( + if (status == AutofillSetupStatus.Done) + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + tint = contentColor, + ) + else Text( text = number.toString(), color = contentColor, style = MaterialTheme.typography.headlineSmallEmphasized, @@ -125,13 +114,43 @@ internal fun NumberBadge( } } +private val AutofillSetupStep.titleRes + get() = when (this) { + AutofillSetupStep.OpenSystemSettings -> R.string.autofill_open_settings + AutofillSetupStep.ChooseKeyGo -> R.string.autofill_choose_keygo + AutofillSetupStep.EnableInChrome -> R.string.autofill_chrome + } + +private val AutofillSetupStep.supportingRes + get() = when (this) { + AutofillSetupStep.OpenSystemSettings -> R.string.autofill_open_settings_support + AutofillSetupStep.ChooseKeyGo -> R.string.autofill_choose_keygo_support + AutofillSetupStep.EnableInChrome -> R.string.autofill_chrome_support + } @Preview @Composable private fun EnableAutofillContentPreview() { MaterialTheme { Surface(modifier = Modifier.fillMaxSize()) { - EnableAutofillContent() + EnableAutofillContent( + state = OnboardingUiState.EnableAutofill(chromeAvailable = true) + ) } } -} \ No newline at end of file +} + +@Preview +@Composable +private fun EnableAutofillContentChromePendingPreview() { + MaterialTheme { + Surface(modifier = Modifier.fillMaxSize()) { + EnableAutofillContent( + state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = true, + chromeAvailable = true, + ) + ) + } + } +} diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index f45f7ab68..87846ccbd 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -1,6 +1,11 @@ package de.davis.keygo.feature.onboarding.presentation +import android.content.ActivityNotFoundException +import android.content.Intent +import android.provider.Settings import android.util.Log +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -23,8 +28,11 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue 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.unit.dp +import androidx.core.net.toUri +import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.davis.keygo.core.security.domain.model.CryptographicMode import de.davis.keygo.core.security.domain.model.KeyId @@ -33,9 +41,12 @@ import de.davis.keygo.core.util.onFailure import de.davis.keygo.core.util.onSuccess import de.davis.keygo.core.util.presentation.ObserveAsEvents import de.davis.keygo.feature.onboarding.R +import de.davis.keygo.feature.onboarding.presentation.model.AutofillSetupAction import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState import org.koin.androidx.compose.koinViewModel +private const val TAG = "OnboardingScreen" + @OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) @Composable fun OnboardingScreen(onSuccess: () -> Unit) { @@ -57,6 +68,38 @@ fun OnboardingScreen(onSuccess: () -> Unit) { } } + ObserveAsEvents(viewModel.finishedFlow) { + onSuccess() + } + + val context = LocalContext.current + val autofillPickerLauncher = + rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {} + + ObserveAsEvents(viewModel.autofillPickerFlow) { + try { + autofillPickerLauncher.launch( + Intent(Settings.ACTION_REQUEST_SET_AUTOFILL_SERVICE).apply { + data = "package:${context.packageName}".toUri() + } + ) + } catch (e: ActivityNotFoundException) { + // Some AOSP builds, Android TV, and a few OEM ROMs have nothing that resolves this + // intent. The user still has the "Finish setup" button to move past the step, so + // failing quietly here is acceptable as long as it stays diagnosable. + Log.w(TAG, "No activity found to handle the system autofill picker", e) + } + } + + // The picker reports nothing back and Chrome's hand off is not a result flow at all, so the + // resume read is what actually learns the new state. Keying on the step also refreshes on + // arrival, and keeps Chrome's cross process query off every other step's resume. + val onAutofillStep = state is OnboardingUiState.EnableAutofill + LifecycleResumeEffect(onAutofillStep) { + if (onAutofillStep) viewModel.refreshAutofillState() + onPauseOrDispose {} + } + val contentHeight = ButtonDefaults.LargeContainerHeight Scaffold( modifier = Modifier @@ -120,7 +163,7 @@ fun OnboardingScreen(onSuccess: () -> Unit) { OnboardingUiState.EnableBiometrics -> EnableBiometricsContent() OnboardingUiState.ImportData -> ImportVaultContent() - OnboardingUiState.EnableAutofill -> EnableAutofillContent() + is OnboardingUiState.EnableAutofill -> EnableAutofillContent(state = state) } } } @@ -146,7 +189,11 @@ private val OnboardingUiState.buttonText: String is OnboardingUiState.SetMainPassword -> R.string.continue_text OnboardingUiState.EnableBiometrics -> R.string.enable_biometrics OnboardingUiState.ImportData -> R.string.skip_for_now - OnboardingUiState.EnableAutofill -> R.string.open_settings + is OnboardingUiState.EnableAutofill -> when (nextAction) { + AutofillSetupAction.OpenSystemSettings -> R.string.autofill_open_settings + AutofillSetupAction.OpenChromeSettings -> R.string.autofill_enable_in_chrome + AutofillSetupAction.Finish -> R.string.finish_setup + } } ) @@ -159,7 +206,8 @@ private val OnboardingUiState.optionalActionText: String? is OnboardingUiState.SetMainPassword -> null OnboardingUiState.EnableBiometrics -> R.string.skip_for_now - OnboardingUiState.EnableAutofill -> R.string.finish_setup + is OnboardingUiState.EnableAutofill -> + R.string.finish_setup.takeIf { nextAction != AutofillSetupAction.Finish } }?.let { stringResource(it) } private fun OnboardingUiState.isOutlinedButonCandidate() = this is OnboardingUiState.ImportData diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index 40c16530d..29d15f889 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -13,6 +13,7 @@ import de.davis.keygo.core.ui.model.UiFieldError import de.davis.keygo.core.util.onSuccess import de.davis.keygo.feature.autofill.domain.repository.AutofillServiceRepository import de.davis.keygo.feature.autofill.domain.repository.ChromeAutofillRepository +import de.davis.keygo.feature.onboarding.presentation.model.AutofillSetupAction import de.davis.keygo.feature.onboarding.presentation.model.OnboardingStep import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState import de.davis.keygo.migration.create_access.domain.usecase.HasMainPasswordUseCase @@ -55,19 +56,19 @@ internal class OnboardingViewModel( private val stepsToSkip = MutableStateFlow>(emptySet()) private val isMigrating = MutableStateFlow(false) - init { - calculateStepsToSkip() - } - private fun calculateStepsToSkip() { viewModelScope.launch { val hasAccount = accountRepository.getOrNull() != null val hasLegacyPassword = hasV1Password() + val autofill = readAutofillState() + _enableAutofillState.update { autofill } val skipSteps = buildSet { if (!biometricAvailabilityRepository.availability()) add(OnboardingStep.EnableBiometrics) if (hasAccount || hasLegacyPassword) add(OnboardingStep.ImportExistingData) - if (autofillServiceRepository.isEnabled() && chromeAutofillRepository.isAutofillEnabled()) + // Not "both enabled": on a device with no Chrome the Chrome read is false forever, + // which would keep offering a step that has nothing left to do. + if (autofill.nextAction == AutofillSetupAction.Finish) add(OnboardingStep.EnableAutofillService) } stepsToSkip.update { skipSteps } @@ -75,6 +76,22 @@ internal class OnboardingViewModel( } } + private suspend fun readAutofillState(): OnboardingUiState.EnableAutofill { + val chromeAvailable = chromeAutofillRepository.isAvailable() + return OnboardingUiState.EnableAutofill( + systemAutofillEnabled = autofillServiceRepository.isEnabled(), + chromeAvailable = chromeAvailable, + chromeAutofillEnabled = chromeAvailable && chromeAutofillRepository.isAutofillEnabled(), + ) + } + + fun refreshAutofillState() { + viewModelScope.launch { + val autofill = readAutofillState() + _enableAutofillState.update { autofill } + } + } + private val passwordTextFieldState = TextFieldState() private val confirmPasswordTextFieldState = TextFieldState() @@ -95,13 +112,26 @@ internal class OnboardingViewModel( ) private val _enableAutofillState = MutableStateFlow( - OnboardingUiState.EnableAutofill + OnboardingUiState.EnableAutofill() ) + // Declared after every property calculateStepsToSkip() touches. init runs in declaration + // order, and viewModelScope is Main.immediate, so on the main thread this launch body starts + // executing synchronously; if it ran before _enableAutofillState above it would read a + // not-yet-initialized property. + init { + calculateStepsToSkip() + } private val biometricChannel = Channel() val biometricFlow = biometricChannel.receiveAsFlow() + private val autofillPickerChannel = Channel(Channel.BUFFERED) + val autofillPickerFlow = autofillPickerChannel.receiveAsFlow() + + private val finishedChannel = Channel(Channel.BUFFERED) + val finishedFlow = finishedChannel.receiveAsFlow() + private val _loading = MutableStateFlow(false) val loading = _loading.asStateFlow() @@ -198,6 +228,21 @@ internal class OnboardingViewModel( return // wait for biometric result before proceeding to next step } + OnboardingStep.EnableAutofillService -> when (_enableAutofillState.value.nextAction) { + AutofillSetupAction.OpenSystemSettings -> { + autofillPickerChannel.trySend(Unit) + return // wait for the user to come back from the system picker + } + + AutofillSetupAction.OpenChromeSettings -> { + chromeAutofillRepository.openChromeAutofillSettings() + return // wait for the user to come back from Chrome + } + + // Nothing left to set up, fall through to the step advance below. + AutofillSetupAction.Finish -> {} + } + else -> {} } @@ -229,7 +274,7 @@ internal class OnboardingViewModel( } private fun finishUp() { - + finishedChannel.trySend(Unit) } private suspend fun loading(block: suspend () -> R): R { diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/AutofillSetup.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/AutofillSetup.kt new file mode 100644 index 000000000..8c768a0b8 --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/AutofillSetup.kt @@ -0,0 +1,43 @@ +package de.davis.keygo.feature.onboarding.presentation.model + +/** What the primary button on the autofill step does next. */ +internal enum class AutofillSetupAction { + OpenSystemSettings, + OpenChromeSettings, + Finish, +} + +/** One row of the instruction list on the autofill step. */ +internal enum class AutofillSetupStep { + OpenSystemSettings, + ChooseKeyGo, + EnableInChrome, +} + +internal enum class AutofillSetupStatus { + Done, + Current, + Upcoming, +} + +/** + * The rows to render, in order. Opening the picker and picking KeyGo are a single act for the user, + * so both follow the system service flag and flip to done together. The Chrome row is dropped + * entirely when there is no Chrome to act on. + */ +internal fun OnboardingUiState.EnableAutofill.setupSteps(): List> { + val steps = listOfNotNull( + AutofillSetupStep.OpenSystemSettings to systemAutofillEnabled, + AutofillSetupStep.ChooseKeyGo to systemAutofillEnabled, + (AutofillSetupStep.EnableInChrome to chromeAutofillEnabled).takeIf { chromeAvailable }, + ) + + val currentIndex = steps.indexOfFirst { (_, done) -> !done } + return steps.mapIndexed { index, (step, done) -> + step to when { + done -> AutofillSetupStatus.Done + index == currentIndex -> AutofillSetupStatus.Current + else -> AutofillSetupStatus.Upcoming + } + } +} diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt index 536d2ec98..cfec53963 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt @@ -18,5 +18,24 @@ internal sealed interface OnboardingUiState { data object EnableBiometrics : OnboardingUiState data object ImportData : OnboardingUiState - data object EnableAutofill : OnboardingUiState + + data class EnableAutofill( + val systemAutofillEnabled: Boolean = false, + val chromeAvailable: Boolean = false, + val chromeAutofillEnabled: Boolean = false, + ) : OnboardingUiState { + + /** + * Single source of truth for the primary button: the ViewModel reads it to decide what to + * do, the screen reads it to decide what to say. Driven by state rather than a counter, so + * a device that already has Chrome on but KeyGo unselected still starts at the picker and + * then goes straight to done. + */ + val nextAction: AutofillSetupAction + get() = when { + !systemAutofillEnabled -> AutofillSetupAction.OpenSystemSettings + chromeAvailable && !chromeAutofillEnabled -> AutofillSetupAction.OpenChromeSettings + else -> AutofillSetupAction.Finish + } + } } diff --git a/feature/onboarding/src/main/res/values/strings.xml b/feature/onboarding/src/main/res/values/strings.xml index 962ef8031..488f88125 100644 --- a/feature/onboarding/src/main/res/values/strings.xml +++ b/feature/onboarding/src/main/res/values/strings.xml @@ -5,7 +5,6 @@ Continue Skip for now Enable Biometrics - Open settings Finish setup @@ -34,4 +33,5 @@ Select KeyGo as your autofill provider & confirm Apply to Chrome Open Chrome settings & enable 3rd party autofill providers + Enable in Chrome \ No newline at end of file diff --git a/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/AutofillSetupTest.kt b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/AutofillSetupTest.kt new file mode 100644 index 000000000..aa6020efe --- /dev/null +++ b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/AutofillSetupTest.kt @@ -0,0 +1,168 @@ +package de.davis.keygo.feature.onboarding.presentation.model + +import kotlin.test.Test +import kotlin.test.assertEquals + +class AutofillSetupTest { + + @Test + fun `next action opens system settings while KeyGo is not the autofill service`() { + val state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = false, + chromeAvailable = true, + chromeAutofillEnabled = false, + ) + + assertEquals(AutofillSetupAction.OpenSystemSettings, state.nextAction) + } + + @Test + fun `next action opens system settings even when chrome is already on`() { + val state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = false, + chromeAvailable = true, + chromeAutofillEnabled = true, + ) + + assertEquals(AutofillSetupAction.OpenSystemSettings, state.nextAction) + } + + @Test + fun `next action opens chrome settings once the system service is set`() { + val state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = true, + chromeAvailable = true, + chromeAutofillEnabled = false, + ) + + assertEquals(AutofillSetupAction.OpenChromeSettings, state.nextAction) + } + + @Test + fun `next action finishes when both are enabled`() { + val state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = true, + chromeAvailable = true, + chromeAutofillEnabled = true, + ) + + assertEquals(AutofillSetupAction.Finish, state.nextAction) + } + + @Test + fun `next action finishes when the system service is set and chrome is unavailable`() { + val state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = true, + chromeAvailable = false, + chromeAutofillEnabled = false, + ) + + assertEquals(AutofillSetupAction.Finish, state.nextAction) + } + + @Test + fun `setup steps start with the first row current and the rest upcoming`() { + val state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = false, + chromeAvailable = true, + chromeAutofillEnabled = false, + ) + + assertEquals( + listOf( + AutofillSetupStep.OpenSystemSettings to AutofillSetupStatus.Current, + AutofillSetupStep.ChooseKeyGo to AutofillSetupStatus.Upcoming, + AutofillSetupStep.EnableInChrome to AutofillSetupStatus.Upcoming, + ), + state.setupSteps(), + ) + } + + @Test + fun `setup steps mark both system rows done together and chrome current`() { + val state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = true, + chromeAvailable = true, + chromeAutofillEnabled = false, + ) + + assertEquals( + listOf( + AutofillSetupStep.OpenSystemSettings to AutofillSetupStatus.Done, + AutofillSetupStep.ChooseKeyGo to AutofillSetupStatus.Done, + AutofillSetupStep.EnableInChrome to AutofillSetupStatus.Current, + ), + state.setupSteps(), + ) + } + + @Test + fun `setup steps omit the chrome row when chrome is unavailable`() { + val state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = false, + chromeAvailable = false, + chromeAutofillEnabled = false, + ) + + assertEquals( + listOf( + AutofillSetupStep.OpenSystemSettings to AutofillSetupStatus.Current, + AutofillSetupStep.ChooseKeyGo to AutofillSetupStatus.Upcoming, + ), + state.setupSteps(), + ) + } + + @Test + fun `setup steps mark every row done once both are enabled`() { + val state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = true, + chromeAvailable = true, + chromeAutofillEnabled = true, + ) + + assertEquals( + listOf( + AutofillSetupStep.OpenSystemSettings to AutofillSetupStatus.Done, + AutofillSetupStep.ChooseKeyGo to AutofillSetupStatus.Done, + AutofillSetupStep.EnableInChrome to AutofillSetupStatus.Done, + ), + state.setupSteps(), + ) + } + + @Test + fun `setup steps show chrome already done while the system rows are still pending`() { + val state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = false, + chromeAvailable = true, + chromeAutofillEnabled = true, + ) + + assertEquals( + listOf( + AutofillSetupStep.OpenSystemSettings to AutofillSetupStatus.Current, + AutofillSetupStep.ChooseKeyGo to AutofillSetupStatus.Upcoming, + AutofillSetupStep.EnableInChrome to AutofillSetupStatus.Done, + ), + state.setupSteps(), + ) + } + + @Test + fun `setup steps have no current row when only the chrome row is missing`() { + val state = OnboardingUiState.EnableAutofill( + systemAutofillEnabled = true, + chromeAvailable = false, + chromeAutofillEnabled = false, + ) + + assertEquals( + listOf( + AutofillSetupStep.OpenSystemSettings to AutofillSetupStatus.Done, + AutofillSetupStep.ChooseKeyGo to AutofillSetupStatus.Done, + ), + state.setupSteps(), + ) + } +} From bbeed27c4566f687a33f93b32663c4d99edad476 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 8 Aug 2026 01:36:17 +0200 Subject: [PATCH 09/24] fix(onboarding): coroutine leak --- .../presentation/OnboardingViewModel.kt | 97 +++++++------------ 1 file changed, 33 insertions(+), 64 deletions(-) diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index 29d15f889..5546f67db 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -7,7 +7,6 @@ import androidx.lifecycle.viewModelScope import de.davis.keygo.core.identity.domain.repository.AccountRepository import de.davis.keygo.core.identity.domain.usecase.CreateAccessUseCase import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator -import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository import de.davis.keygo.core.ui.model.UiFieldError import de.davis.keygo.core.util.onSuccess @@ -29,10 +28,7 @@ import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOn -import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.mapLatest -import kotlinx.coroutines.flow.onEach -import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update @@ -95,14 +91,6 @@ internal class OnboardingViewModel( private val passwordTextFieldState = TextFieldState() private val confirmPasswordTextFieldState = TextFieldState() - private val _mainPasswordState = MutableStateFlow( - OnboardingUiState.SetMainPassword( - passwordTextFieldState = passwordTextFieldState, - confirmPasswordTextFieldState = confirmPasswordTextFieldState, - passwordScore = PasswordScore.None - ) - ) - private val _enableBiometricsState = MutableStateFlow( OnboardingUiState.EnableBiometrics ) @@ -135,15 +123,43 @@ internal class OnboardingViewModel( private val _loading = MutableStateFlow(false) val loading = _loading.asStateFlow() + private val _passwordError = MutableStateFlow(null) + private val _confirmPasswordError = MutableStateFlow(null) + + @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) + private val passwordScoreFlow = snapshotFlow { passwordTextFieldState.text } + .debounce(150.milliseconds) + .mapLatest { passwordStrengthEstimator(it.toString()) } + .distinctUntilChanged() + .flowOn(Dispatchers.Default) + + private val _mainPasswordState = combine( + snapshotFlow { passwordTextFieldState.text }, + snapshotFlow { confirmPasswordTextFieldState.text }, + passwordScoreFlow, + _passwordError, + _confirmPasswordError + ) { pwd, confirm, score, manualPwdError, manualConfirmError -> + // Automatically clear manual errors if the user has fixed them by typing + val resolvedPwdError = if (pwd.isNotBlank()) null else manualPwdError + val resolvedConfirmError = if (pwd == confirm) null else manualConfirmError + + OnboardingUiState.SetMainPassword( + passwordTextFieldState = passwordTextFieldState, + confirmPasswordTextFieldState = confirmPasswordTextFieldState, + passwordScore = score, + passwordError = resolvedPwdError, + confirmPasswordError = resolvedConfirmError + ) + } + private val _step = MutableStateFlow(OnboardingStep.Welcome) @OptIn(ExperimentalCoroutinesApi::class) val state = _step.flatMapLatest { when (it) { OnboardingStep.Welcome -> isMigrating.mapLatest { migrating -> - OnboardingUiState.Welcome( - migrating - ) + OnboardingUiState.Welcome(migrating) } OnboardingStep.SetMainPassword -> _mainPasswordState @@ -151,55 +167,12 @@ internal class OnboardingViewModel( OnboardingStep.ImportExistingData -> _importDataState OnboardingStep.EnableAutofillService -> _enableAutofillState } - }.onStart { - observePasswordStrength() - observePasswordError() }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = OnboardingUiState.Welcome() ) - @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) - private fun observePasswordStrength() { - snapshotFlow { passwordTextFieldState.text } - .debounce(150.milliseconds) - .mapLatest { passwordStrengthEstimator(it.toString()) } - .distinctUntilChanged() - .onEach { score -> - _mainPasswordState.update { - it.copy(passwordScore = score) - } - } - .flowOn(Dispatchers.Default) - .launchIn(viewModelScope) - } - - @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) - private fun observePasswordError() { - combine( - snapshotFlow { passwordTextFieldState.text }, - snapshotFlow { confirmPasswordTextFieldState.text } - ) { pwd, confirmation -> - pwd.trim() to (pwd == confirmation) - }.debounce(150.milliseconds) - .distinctUntilChanged() - .onEach { (password, isEqual) -> - if (password.isNotBlank()) { - _mainPasswordState.update { - it.copy(passwordError = null) - } - } - - if (isEqual) { - _mainPasswordState.update { - it.copy(confirmPasswordError = null) - } - } - } - .launchIn(viewModelScope) - } - fun onNextStep() { when (_step.value) { OnboardingStep.SetMainPassword -> { @@ -207,16 +180,12 @@ internal class OnboardingViewModel( val confirmPassword = confirmPasswordTextFieldState.text.toString() if (password.isBlank()) { - _mainPasswordState.update { - it.copy(passwordError = UiFieldError.Empty) - } + _passwordError.update { UiFieldError.Empty } return } if (password != confirmPassword) { - _mainPasswordState.update { - it.copy(confirmPasswordError = UiFieldError.Mismatch) - } + _confirmPasswordError.update { UiFieldError.Mismatch } return } From 1bcca09e019275904a0d43b5750b37a39bba39af Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 8 Aug 2026 21:42:10 +0200 Subject: [PATCH 10/24] feat(onboarding): wire up import data --- .../feature/backup/domain/model/FileFormat.kt | 12 ++ .../backup/domain/model/ImportError.kt | 1 + .../component/BackupFileChooser.kt | 8 +- .../presentation/import/ImportFilePicker.kt | 24 +++ .../presentation/import/ImportPhaseContent.kt | 1 + .../import/ImportWizardContent.kt | 4 +- .../presentation/import/ImportWizardScreen.kt | 63 ++++-- .../import/ImportWizardViewModel.kt | 131 ++++++++++-- .../import/model/ImportWizardEvent.kt | 3 + .../import/model/ImportWizardStep.kt | 34 +++- .../import/model/ImportWizardUiState.kt | 45 ++--- .../backup/src/main/res/values/strings.xml | 1 + .../import/ImportWizardViewModelTest.kt | 189 ++++++++++++++++++ .../import/model/ImportWizardStepTest.kt | 87 +++++++- .../import/model/ImportWizardUiStateTest.kt | 33 +++ .../data/FakeBackupDestinationResolver.kt | 15 +- .../presentation/ImportVaultContent.kt | 23 +-- .../presentation/OnboardingScreen.kt | 48 ++++- .../presentation/OnboardingViewModel.kt | 18 +- .../presentation/model/OnboardingUiState.kt | 8 +- .../presentation/model/OnboardingStepTest.kt | 35 ++++ 21 files changed, 694 insertions(+), 89 deletions(-) create mode 100644 feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportFilePicker.kt create mode 100644 feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepTest.kt diff --git a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/domain/model/FileFormat.kt b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/domain/model/FileFormat.kt index bfed18ce4..66f22f16e 100644 --- a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/domain/model/FileFormat.kt +++ b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/domain/model/FileFormat.kt @@ -9,4 +9,16 @@ enum class FileFormat(val mimeType: String, val extension: String) { val encrypted: Boolean get() = this == JSON + + companion object { + + /** + * The format [fileName] implies, or null when KeyGo has no importer for it. The extension + * decides, not the MIME type: content providers routinely report the wrong type for a CSV, + * so the file picker cannot filter tightly enough to keep an unsupported file out. + */ + fun fromFileName(fileName: String?): FileFormat? = fileName?.let { name -> + entries.firstOrNull { name.endsWith(".${it.extension}", ignoreCase = true) } + } + } } \ No newline at end of file diff --git a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/domain/model/ImportError.kt b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/domain/model/ImportError.kt index 7bf4d1490..51fc86831 100644 --- a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/domain/model/ImportError.kt +++ b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/domain/model/ImportError.kt @@ -6,6 +6,7 @@ sealed interface ImportError { data object SessionLocked : ImportError data object FileUnreadable : ImportError data object EmptyFile : ImportError + data object UnsupportedFormat : ImportError data object WrongCredential : ImportError data object PassphraseRequired : ImportError data class ParseFailed(val cause: BackupException) : ImportError diff --git a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/component/BackupFileChooser.kt b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/component/BackupFileChooser.kt index 8c40e1300..8cb0d8884 100644 --- a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/component/BackupFileChooser.kt +++ b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/component/BackupFileChooser.kt @@ -45,7 +45,7 @@ fun BackupFileChooser( modifier: Modifier = Modifier, ) { when (destination) { - null -> ChooserCard( + null -> BackupFileChooserCard( icon = chooserIcon, title = chooserTitle, subtitle = chooserSubtitle, @@ -64,8 +64,12 @@ fun BackupFileChooser( } } +/** + * The empty state of [BackupFileChooser], exposed on its own for hosts that never show a selected + * file because picking one immediately hands off somewhere else. + */ @Composable -private fun ChooserCard( +fun BackupFileChooserCard( icon: ImageVector, title: String, subtitle: String, diff --git a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportFilePicker.kt b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportFilePicker.kt new file mode 100644 index 000000000..792c2a0f2 --- /dev/null +++ b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportFilePicker.kt @@ -0,0 +1,24 @@ +package de.davis.keygo.feature.backup.presentation.import + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import de.davis.keygo.feature.backup.domain.model.BackupDestinationUri +import de.davis.keygo.feature.backup.domain.model.FileFormat + +private val ImportFileMimeTypes = (FileFormat.entries.map { it.mimeType } + "*/*").toTypedArray() + +fun interface FilePickerAction { + fun launch() +} + +@Composable +fun rememberImportFilePicker(onPicked: (BackupDestinationUri) -> Unit): FilePickerAction { + val launcher = rememberLauncherForActivityResult( + ActivityResultContracts.OpenDocument(), + ) { uri -> + uri?.let { onPicked(BackupDestinationUri(it.toString())) } + } + return remember(launcher) { FilePickerAction { launcher.launch(ImportFileMimeTypes) } } +} diff --git a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportPhaseContent.kt b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportPhaseContent.kt index 81fe3871b..b9ba8bfc6 100644 --- a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportPhaseContent.kt +++ b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportPhaseContent.kt @@ -203,6 +203,7 @@ internal fun ImportErrorContent( val message = when (error) { ImportError.FileUnreadable -> stringResource(R.string.import_error_file_unreadable) ImportError.EmptyFile -> stringResource(R.string.import_error_empty) + ImportError.UnsupportedFormat -> stringResource(R.string.import_error_unsupported) ImportError.NothingImported -> stringResource(R.string.import_error_nothing) ImportError.SessionLocked -> stringResource(R.string.import_error_session_locked) is ImportError.ParseFailed -> stringResource(R.string.import_error_parse) diff --git a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardContent.kt b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardContent.kt index 1dfa586d5..434f8830a 100644 --- a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardContent.kt +++ b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardContent.kt @@ -37,6 +37,7 @@ internal fun ImportWizardContent( state: ImportWizardUiState, onEvent: (ImportWizardUiEvent) -> Unit, navigateUp: () -> Unit, + onFinished: () -> Unit = navigateUp, ) { AnimatedContent( targetState = state.progress, @@ -46,7 +47,7 @@ internal fun ImportWizardContent( when (progress) { is ImportProgress.Succeeded -> ImportResultContent( summary = progress.summary, - onDone = navigateUp, + onDone = onFinished, ) is ImportProgress.Failed -> ImportErrorContent( @@ -176,6 +177,7 @@ private class ImportWizardUiStateProvider : PreviewParameterProvider Unit) { +fun ImportWizardScreen( + navigateUp: () -> Unit, + preselectedFile: BackupDestinationUri? = null, + onFinished: () -> Unit = navigateUp, +) { val viewModel = koinViewModel() val state by viewModel.state.collectAsStateWithLifecycle() - val filePicker = rememberLauncherForActivityResult( - ActivityResultContracts.OpenDocument(), - ) { uri -> - viewModel.onFilePicked(uri?.let { BackupDestinationUri(it.toString()) }) - } + val chooseFile = rememberImportFilePicker(viewModel::onFilePicked) ObserveAsEvents(flow = viewModel.event) { when (it) { - ImportWizardEvent.PickFile -> filePicker.launch( - arrayOf("application/json", "text/csv", "*/*"), - ) + ImportWizardEvent.PickFile -> chooseFile.launch() + + ImportWizardEvent.Exit -> navigateUp() } } + LaunchedEffect(preselectedFile) { + if (preselectedFile != null) viewModel.seedFile(preselectedFile) + } + + // seedFile lands on the next composition, so for one frame the state still says the wizard owns + // file selection. Showing the reading phase for that frame keeps the chooser in one place. + val displayState = if (preselectedFile != null && !state.fileChosenByHost) + state.copy(progress = ImportProgress.Reading) + else state + + // While a host owns the file, the wizard is the only thing that may answer back: it has no back + // stack of its own to fall through to, and an unhandled press would finish the host's Activity + // mid import. So this stays enabled for every phase and swallows the press where back is inert, + // rather than letting the host compensate with a no-op handler of its own. Wizard's + // PredictiveBackHandler is composed deeper and still wins wherever it is enabled. + BackHandler(enabled = preselectedFile != null) { + if (displayState.backEnabled) viewModel.onEvent(ImportWizardUiEvent.Back) + } + + // Wizard's own toolbar arrow calls navigateUp directly on the first step it renders, bypassing + // onBack(). A seeded wizard needs that arrow on the same path as the back gesture above, or + // tapping it would leave a running import and the seed in place instead of tearing them down. + val onBackToHost: () -> Unit = { viewModel.onEvent(ImportWizardUiEvent.Back) } + ImportWizardContent( - state = state, + state = displayState, onEvent = viewModel::onEvent, - navigateUp = navigateUp, + navigateUp = if (preselectedFile != null) onBackToHost else navigateUp, + onFinished = onFinished, ) } diff --git a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardViewModel.kt b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardViewModel.kt index ec58a1193..60b2b0469 100644 --- a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardViewModel.kt +++ b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardViewModel.kt @@ -1,10 +1,12 @@ package de.davis.keygo.feature.backup.presentation.import import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.input.clearText import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import de.davis.keygo.core.item.domain.model.Vault import de.davis.keygo.core.item.domain.model.getIdOrNull import de.davis.keygo.core.util.fold import de.davis.keygo.feature.backup.domain.BackupDestinationResolver @@ -22,6 +24,7 @@ import de.davis.keygo.feature.backup.presentation.import.model.ImportWizardEvent import de.davis.keygo.feature.backup.presentation.import.model.ImportWizardStep import de.davis.keygo.feature.backup.presentation.import.model.ImportWizardUiEvent import de.davis.keygo.feature.backup.presentation.import.model.ImportWizardUiState +import de.davis.keygo.feature.backup.presentation.import.model.previousStep import de.davis.keygo.feature.backup.presentation.import.model.toMappingRows import de.davis.keygo.feature.vault.domain.usecase.ObserveVaultsAndSelectionUseCase import de.davisalessandro.keygo.rust.ColumnMapping @@ -60,7 +63,9 @@ internal class ImportWizardViewModel( private var importJob: Job? = null private var analysisJob: Job? = null + private var seedJob: Job? = null private var vaultStepSeeded = false + private var seededUri: BackupDestinationUri? = null init { snapshotFlow { passphraseState.text.toString() } @@ -121,6 +126,37 @@ internal class ImportWizardViewModel( } } + /** + * Enters the wizard on a file the host picked, so that choosing a file stays one action in one + * place. The file step is skipped and the lane resumes at the first question the wizard still + * has, which is the column mapping for a CSV and nothing at all for a JSON that imports cleanly. + * + * Idempotent per file. The screen seeds from a [androidx.compose.runtime.LaunchedEffect], which + * restarts on a configuration change, and re-running the import there would throw away the + * mapping the user was in the middle of. + */ + fun seedFile(uri: BackupDestinationUri) { + if (seededUri == uri) return + seededUri = uri + + cancelInFlightWork() + _state.update { + it.cleared().copy( + uri = uri, + fileChosenByHost = true, + // Held until the lane below decides where the user lands, so the wizard never + // flashes the file step its host already owns. + progress = ImportProgress.Reading, + ) + } + + seedJob = viewModelScope.launch { + val destination = backupDestinationResolver.resolve(uri) + _state.update { it.copy(backupDestination = destination) } + onContinue() + } + } + private fun onContinue() = when (_state.value.step) { ImportWizardStep.SelectFile -> onSelectFileContinue() ImportWizardStep.MapColumns -> validateMapping() @@ -131,7 +167,12 @@ internal class ImportWizardViewModel( private fun onSelectFileContinue() = when (_state.value.format) { FileFormat.CSV -> runAnalysis() FileFormat.JSON -> startImport(passphrase = null) - null -> Unit + + // Reachable because the picker has to offer the wildcard type: providers routinely report + // the wrong MIME type for a .csv, so the filter cannot be tight enough to keep a .txt out. + null -> _state.update { + it.copy(progress = ImportProgress.Failed(ImportError.UnsupportedFormat)) + } } private fun runAnalysis() { @@ -151,6 +192,7 @@ internal class ImportWizardViewModel( columns = analysis.toMappingRows(), step = ImportWizardStep.MapColumns, duplicateTypes = emptySet(), + progress = null, ) } @@ -249,26 +291,83 @@ internal class ImportWizardViewModel( else -> _state.update { it.copy(progress = ImportProgress.Failed(error)) } } - private fun back() = _state.update { - when { - it.progress is ImportProgress.Failed -> it.copy( - progress = null, - step = ImportWizardStep.SelectFile, - passphraseError = false, - ) + private fun back() { + val current = _state.value + + // A failure restarts from the file. When the host picked it there is no file step to + // restart from, so the wizard hands control back instead. + if (current.progress is ImportProgress.Failed) { + if (current.fileChosenByHost) return exit() + + return _state.update { + it.copy( + progress = null, + step = ImportWizardStep.SelectFile, + passphraseError = false, + ) + } + } - it.step == ImportWizardStep.SelectVault -> it.copy(step = ImportWizardStep.MapColumns) + val previous = current.step.previousStep(current.fileChosenByHost) + if (previous == null) { + if (current.fileChosenByHost) exit() + return + } - it.step == ImportWizardStep.MapColumns -> it.copy( - step = ImportWizardStep.SelectFile, - columns = emptyList(), + // duplicateTypes can only be set on MapColumns (validateMapping refuses to advance while + // duplicates remain) and passphraseError only on ProvidePassphrase, so clearing both + // unconditionally is the same as clearing them per step. Only the columns are conditional. + _state.update { + it.copy( + step = previous, + columns = if (current.step == ImportWizardStep.MapColumns) emptyList() + else it.columns, duplicateTypes = emptySet(), + passphraseError = false, ) + } + } - it.step == ImportWizardStep.ProvidePassphrase -> - it.copy(step = ImportWizardStep.SelectFile, passphraseError = false) + /** + * Hands control back to whoever opened the wizard, stops any work still in flight, and resets + * the UI state to what a fresh wizard looks like. + * + * The reset matters because this ViewModel is scoped to the host's back stack entry, so it + * outlives the visit: without it, the previous file's screen (its error, or its column mapping) + * would render again for the gap between handing control back and the host seeding a new file. + */ + private fun exit() { + cancelInFlightWork() + seededUri = null + _state.update { it.cleared() } + _event.trySend(ImportWizardEvent.Exit) + } - else -> it - } + private fun cancelInFlightWork() { + importJob?.cancel() + analysisJob?.cancel() + seedJob?.cancel() + vaultStepSeeded = false + passphraseState.clearText() + newVaultNameState.clearText() } + + /** + * What a fresh wizard looks like. `vaults` and `contextVaultId` are owned by the observe flow + * rather than by a visit, so they survive; the text field states are held by this ViewModel and + * are cleared by [cancelInFlightWork]. + */ + private fun ImportWizardUiState.cleared() = copy( + step = ImportWizardStep.SelectFile, + fileChosenByHost = false, + uri = null, + backupDestination = null, + progress = null, + columns = emptyList(), + duplicateTypes = emptySet(), + passphraseError = false, + creatingNewVault = false, + selectedVaultId = null, + newVaultIcon = Vault.Icon.Default, + ) } diff --git a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardEvent.kt b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardEvent.kt index 05b080a98..7d6362be7 100644 --- a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardEvent.kt +++ b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardEvent.kt @@ -2,4 +2,7 @@ package de.davis.keygo.feature.backup.presentation.import.model internal sealed interface ImportWizardEvent { data object PickFile : ImportWizardEvent + + /** The wizard has nothing left to go back to and hands control to whoever opened it. */ + data object Exit : ImportWizardEvent } diff --git a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardStep.kt b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardStep.kt index 335891ba3..a989c5575 100644 --- a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardStep.kt +++ b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardStep.kt @@ -18,8 +18,34 @@ private val JsonLane = listOf( ImportWizardStep.ProvidePassphrase, ) -/** The steps walked so far on [step]'s lane, so the wizard can draw its progress. */ -internal fun importStepsFor(step: ImportWizardStep): List { - val lane = if (step == ImportWizardStep.ProvidePassphrase) JsonLane else CsvLane - return lane.subList(0, lane.indexOf(step) + 1) +/** + * The whole lane [step] sits on, which is the single place the step order lives. + * + * [includeFileStep] is false when the host picked the file before the wizard opened. That step + * never renders then, so it is not part of the walk at all. + */ +private fun laneFor(step: ImportWizardStep, includeFileStep: Boolean): List { + val full = if (step == ImportWizardStep.ProvidePassphrase) JsonLane else CsvLane + return if (includeFileStep) full else full - ImportWizardStep.SelectFile } + +/** + * The steps walked so far on [step]'s lane, so the wizard can draw its progress. Dropping the file + * step would otherwise leave the indicator permanently one dot ahead of the user. + */ +internal fun importStepsFor( + step: ImportWizardStep, + includeFileStep: Boolean = true, +): List = laneFor(step, includeFileStep) + .let { it.subList(0, it.indexOf(step) + 1) } + +/** + * The step back from this one, or null when there is nothing left inside the wizard to go back to. + * + * [fileChosenByHost] collapses the file step: the host owns it, so backing out of the first step + * the wizard actually renders means leaving the wizard rather than walking to + * [ImportWizardStep.SelectFile]. + */ +internal fun ImportWizardStep.previousStep(fileChosenByHost: Boolean): ImportWizardStep? = + laneFor(this, includeFileStep = !fileChosenByHost) + .let { it.getOrNull(it.indexOf(this) - 1) } diff --git a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardUiState.kt b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardUiState.kt index 4f076ee6b..182a2e6b7 100644 --- a/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardUiState.kt +++ b/feature/backup/src/main/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardUiState.kt @@ -19,6 +19,8 @@ internal data class ImportWizardUiState( val backupDestination: BackupDestination? = null, val uri: BackupDestinationUri? = null, val step: ImportWizardStep = ImportWizardStep.SelectFile, + /** True when the file was picked before the wizard opened, for example by onboarding. */ + val fileChosenByHost: Boolean = false, val passphraseValid: Boolean = false, val passphraseError: Boolean = false, val progress: ImportProgress? = null, @@ -32,36 +34,31 @@ internal data class ImportWizardUiState( /** The vault the user is currently working in; seeds the destination choice. */ val contextVaultId: VaultId? = null, ) { - val format: FileFormat? = backupDestination?.fileName?.let { name -> - when { - name.endsWith(".${FileFormat.JSON.extension}", ignoreCase = true) -> FileFormat.JSON - name.endsWith(".${FileFormat.CSV.extension}", ignoreCase = true) -> FileFormat.CSV - else -> null - } - } + val format: FileFormat? + get() = FileFormat.fromFileName(backupDestination?.fileName) + + val steps: List + get() = importStepsFor(step, includeFileStep = !fileChosenByHost) - val steps: List = importStepsFor(step) + val suggestedVaultName: String + get() = backupDestination?.fileName?.substringBeforeLast('.').orEmpty() - /** `passwords.csv` -> `passwords`. Distinct per import, unlike the parser's `CSV Import`. */ - val suggestedVaultName: String = - backupDestination?.fileName?.substringBeforeLast('.').orEmpty() + val canContinue: Boolean + get() = when (step) { + ImportWizardStep.SelectFile -> backupDestination != null + ImportWizardStep.MapColumns -> columns.any { it.selectedType != null } + ImportWizardStep.SelectVault -> + if (creatingNewVault) newVaultNameValid else selectedVaultId != null - val canContinue: Boolean = when (step) { - ImportWizardStep.SelectFile -> backupDestination != null - ImportWizardStep.MapColumns -> columns.any { it.selectedType != null } - ImportWizardStep.SelectVault -> - if (creatingNewVault) newVaultNameValid else selectedVaultId != null + ImportWizardStep.ProvidePassphrase -> passphraseValid + } - ImportWizardStep.ProvidePassphrase -> passphraseValid - } + val showContinueButton: Boolean + get() = progress == null - val showContinueButton: Boolean = progress == null + val backEnabled: Boolean + get() = progress == null || progress is ImportProgress.Failed - /** - * A function rather than a computed property: the new-vault name lives in a [TextFieldState], - * and a `val` would capture whatever it held when this state object was built rather than what - * the user has typed since. - */ fun resolveTarget(newVaultName: String): ImportTarget? = if (creatingNewVault) newVaultName.trim().takeIf(String::isNotBlank) ?.let { ImportTarget.New(it, newVaultIcon) } diff --git a/feature/backup/src/main/res/values/strings.xml b/feature/backup/src/main/res/values/strings.xml index a58f2a147..b3c207ff9 100644 --- a/feature/backup/src/main/res/values/strings.xml +++ b/feature/backup/src/main/res/values/strings.xml @@ -100,6 +100,7 @@ Back Couldn\'t read the selected file. The selected file is empty. + KeyGo imports .json and .csv files. Pick a file with one of those extensions. There was nothing to import in this backup. This file isn\'t a valid KeyGo backup. Your vault is locked. Unlock it and try again. diff --git a/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardViewModelTest.kt b/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardViewModelTest.kt index 64826f8b3..bd7f559dc 100644 --- a/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardViewModelTest.kt +++ b/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/ImportWizardViewModelTest.kt @@ -36,12 +36,14 @@ import de.davisalessandro.keygo.rust.CsvImportResult import de.davisalessandro.keygo.rust.FieldConfidence import de.davisalessandro.keygo.rust.ImportReport import de.davisalessandro.keygo.rust.JsonEncryption +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import kotlin.test.AfterTest @@ -115,6 +117,12 @@ class ImportWizardViewModelTest { fileName = "keygo.csv", ) + private fun textDestination() = BackupDestination( + provider = BackupDestination.Provider.OnDevice, + displayPath = "Internal storage/Backups", + fileName = "notes.txt", + ) + private fun csvAnalysis() = CsvAnalysis( columns = listOf( CsvColumn(0u, "name", listOf("Email")), @@ -246,6 +254,21 @@ class ImportWizardViewModelTest { assertTrue(csv.importCalls.isEmpty()) // not imported yet } + @Test + fun `Continue on an unsupported file reports the format error`() = runTest { + // The picker offers the wildcard MIME type, so a provider can hand back a .txt. + val viewModel = viewModel(FakeBackupDestinationResolver(result = textDestination())) + viewModel.onFilePicked(BackupDestinationUri("content://doc/notes.txt")) + advanceUntilIdle() + + viewModel.onEvent(ImportWizardUiEvent.Continue) + + assertEquals( + ImportProgress.Failed(ImportError.UnsupportedFormat), + viewModel.state.value.progress, + ) + } + @Test fun `ChangeColumnType updates the selected type`() = runTest { fileStore.contents = "name,secret\nEmail,s3cr3t\n" @@ -565,4 +588,170 @@ class ImportWizardViewModelTest { assertEquals(ImportWizardStep.SelectFile, viewModel.state.value.step) } + + @Test + fun `seeding a CSV skips the file step and lands on the mapping`() = runTest { + fileStore.contents = "name,secret\nEmail,s3cr3t\n" + csv.analyzeResult = csvAnalysis() + val viewModel = viewModel(FakeBackupDestinationResolver(result = csvDestination())) + + viewModel.seedFile(BackupDestinationUri("content://doc/keygo.csv")) + val state = viewModel.state.first { it.step == ImportWizardStep.MapColumns } + + assertTrue(state.fileChosenByHost) + assertNull(state.progress) + assertEquals(listOf(ImportWizardStep.MapColumns), state.steps) + } + + @Test + fun `seeding an ARK sealed JSON imports without asking anything`() = runTest { + json.inspectResult = JsonEncryption.ARK + fileStore.contents = """{"vaults":[]}""" + json.importResult = Backup(listOf(backupVault("Imported", listOf(login("Email"))))) + val viewModel = viewModel(FakeBackupDestinationResolver(result = jsonDestination())) + + viewModel.seedFile(BackupDestinationUri("content://doc/keygo.json")) + val state = viewModel.state.first { it.progress is ImportProgress.Succeeded } + + assertEquals(1, assertIs(state.progress).summary.imported) + } + + @Test + fun `seeding the same file again does not restart the import`() = runTest { + fileStore.contents = "name,secret\nEmail,s3cr3t\n" + csv.analyzeResult = csvAnalysis() + val uri = BackupDestinationUri("content://doc/keygo.csv") + val viewModel = viewModel(FakeBackupDestinationResolver(result = csvDestination())) + viewModel.seedFile(uri) + viewModel.state.first { it.step == ImportWizardStep.MapColumns } + viewModel.onEvent(ImportWizardUiEvent.ChangeColumnType(1, CsvColumnType.Username)) + + viewModel.seedFile(uri) + advanceUntilIdle() + + // A configuration change re-runs the seeding effect. The mapping in progress has to survive. + assertEquals(ImportWizardStep.MapColumns, viewModel.state.value.step) + assertEquals(CsvColumnType.Username, viewModel.state.value.columns[1].selectedType) + } + + @Test + fun `back from the first seeded step hands control to the host`() = runTest { + fileStore.contents = "name,secret\nEmail,s3cr3t\n" + csv.analyzeResult = csvAnalysis() + val viewModel = viewModel(FakeBackupDestinationResolver(result = csvDestination())) + viewModel.seedFile(BackupDestinationUri("content://doc/keygo.csv")) + viewModel.state.first { it.step == ImportWizardStep.MapColumns } + + viewModel.onEvent(ImportWizardUiEvent.Back) + + assertEquals(ImportWizardEvent.Exit, viewModel.event.first()) + } + + @Test + fun `the same file can be seeded again after handing control back`() = runTest { + fileStore.contents = "name,secret\nEmail,s3cr3t\n" + csv.analyzeResult = csvAnalysis() + val uri = BackupDestinationUri("content://doc/keygo.csv") + val viewModel = viewModel(FakeBackupDestinationResolver(result = csvDestination())) + viewModel.seedFile(uri) + viewModel.state.first { it.step == ImportWizardStep.MapColumns } + // Edit the mapping so a no-op second seed and a real one are distinguishable: a real one + // re-analyzes the file and throws this edit away, a no-op leaves it exactly as it is. + viewModel.onEvent(ImportWizardUiEvent.ChangeColumnType(1, CsvColumnType.Username)) + viewModel.onEvent(ImportWizardUiEvent.Back) + viewModel.event.first() + + viewModel.seedFile(uri) + val state = viewModel.state.first { it.step == ImportWizardStep.MapColumns } + + // Back hands control back, and exit() resets the step to SelectFile, so arriving at + // MapColumns again already means a second seed ran. The analyzer count and the mapping + // reverting to its freshly suggested value instead of the edit above pin down that it + // re-read the file rather than restoring a step. + assertEquals(2, csv.analyzeCalls.size) + assertEquals(CsvColumnType.Password, state.columns[1].selectedType) + } + + @Test + fun `seeding a file KeyGo cannot read reports the format`() = runTest { + val viewModel = viewModel(FakeBackupDestinationResolver(result = textDestination())) + + viewModel.seedFile(BackupDestinationUri("content://doc/notes.txt")) + val state = viewModel.state.first { it.progress is ImportProgress.Failed } + + assertEquals(ImportProgress.Failed(ImportError.UnsupportedFormat), state.progress) + } + + @Test + fun `exiting after an unsupported file error resets the wizard to a fresh state`() = runTest { + val viewModel = viewModel(FakeBackupDestinationResolver(result = textDestination())) + viewModel.seedFile(BackupDestinationUri("content://doc/notes.txt")) + viewModel.state.first { it.progress is ImportProgress.Failed } + + viewModel.onEvent(ImportWizardUiEvent.Back) + viewModel.event.first() + + // This ViewModel is scoped to the host's back stack entry, so it outlives the visit. The + // gap between handing control back and the host seeding a new file is exactly what a second + // entry into the wizard would render if exit() left the dismissed error behind. + val state = viewModel.state.value + assertNull(state.progress) + assertEquals(ImportWizardStep.SelectFile, state.step) + assertFalse(state.fileChosenByHost) + assertNull(state.backupDestination) + assertNull(state.uri) + } + + @Test + fun `seeding a different file after backing out of a mapping does not carry over the old file's state`() = + runTest { + fileStore.contents = "name,secret\nEmail,s3cr3t\n" + csv.analyzeResult = csvAnalysis() + val resolver = FakeBackupDestinationResolver(result = csvDestination()) + val viewModel = viewModel(resolver) + viewModel.seedFile(BackupDestinationUri("content://doc/keygo.csv")) + viewModel.state.first { it.step == ImportWizardStep.MapColumns } + + viewModel.onEvent(ImportWizardUiEvent.Back) + viewModel.event.first() + + // Same gap as above, but from a mapping rather than an error: the previous file's + // column names are the tell if exit() left them behind. + val handedBackState = viewModel.state.value + assertEquals(ImportWizardStep.SelectFile, handedBackState.step) + assertEquals(emptyList(), handedBackState.columns) + assertFalse(handedBackState.fileChosenByHost) + + resolver.result = jsonDestination() + json.inspectResult = JsonEncryption.ARK + fileStore.contents = """{"vaults":[]}""" + json.importResult = Backup(listOf(backupVault("Imported", listOf(login("Email"))))) + viewModel.seedFile(BackupDestinationUri("content://doc/keygo.json")) + val finalState = viewModel.state.first { it.progress is ImportProgress.Succeeded } + + assertEquals(1, assertIs(finalState.progress).summary.imported) + assertEquals(emptyList(), finalState.columns) + } + + @Test + fun `seedFile resolves the destination without a concurrent state write re-running it`() = runTest { + val gate = CompletableDeferred() + val resolver = FakeBackupDestinationResolver(result = textDestination(), gate = gate) + val viewModel = viewModel(resolver) + + viewModel.seedFile(BackupDestinationUri("content://doc/notes.txt")) + // seedFile's coroutine has called resolve() and is now parked on the gate, mid-CAS-lambda. + runCurrent() + + // A state write that lands while that lambda is still suspended: this is the same window + // the passphraseState.clearText() collector writes into in the real flow. If resolve() were + // still called from inside _state.update, the CAS retry this forces would call it again. + env.vaultRepo.seed(testVault(name = "Personal")) + runCurrent() + + gate.complete(Unit) + viewModel.state.first { it.backupDestination != null } + + assertEquals(listOf(BackupDestinationUri("content://doc/notes.txt")), resolver.calls) + } } diff --git a/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardStepTest.kt b/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardStepTest.kt index cf491f46e..448ea54d0 100644 --- a/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardStepTest.kt +++ b/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardStepTest.kt @@ -2,11 +2,12 @@ package de.davis.keygo.feature.backup.presentation.import.model import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertNull class ImportWizardStepTest { @Test - fun `SelectFile shows a single step`() { + fun `the file step alone is the whole lane when the wizard owns it`() { assertEquals( listOf(ImportWizardStep.SelectFile), importStepsFor(ImportWizardStep.SelectFile), @@ -14,15 +15,15 @@ class ImportWizardStepTest { } @Test - fun `ProvidePassphrase reveals the passphrase step`() { + fun `csv lane walks the file step first`() { assertEquals( - listOf(ImportWizardStep.SelectFile, ImportWizardStep.ProvidePassphrase), - importStepsFor(ImportWizardStep.ProvidePassphrase), + listOf(ImportWizardStep.SelectFile, ImportWizardStep.MapColumns), + importStepsFor(ImportWizardStep.MapColumns), ) } @Test - fun `SelectVault reveals the file, mapping and vault steps`() { + fun `csv lane walks all three steps by the time it reaches select vault`() { assertEquals( listOf( ImportWizardStep.SelectFile, @@ -32,4 +33,80 @@ class ImportWizardStepTest { importStepsFor(ImportWizardStep.SelectVault), ) } + + @Test + fun `json lane walks the file step first`() { + assertEquals( + listOf(ImportWizardStep.SelectFile, ImportWizardStep.ProvidePassphrase), + importStepsFor(ImportWizardStep.ProvidePassphrase), + ) + } + + @Test + fun `csv lane drops the file step when the host owns it`() { + assertEquals( + listOf(ImportWizardStep.MapColumns, ImportWizardStep.SelectVault), + importStepsFor(ImportWizardStep.SelectVault, includeFileStep = false), + ) + } + + @Test + fun `json lane drops the file step when the host owns it`() { + assertEquals( + listOf(ImportWizardStep.ProvidePassphrase), + importStepsFor(ImportWizardStep.ProvidePassphrase, includeFileStep = false), + ) + } + + @Test + fun `a host owned lane standing on the file step has walked nothing`() { + assertEquals( + emptyList(), + importStepsFor(ImportWizardStep.SelectFile, includeFileStep = false), + ) + } + + @Test + fun `map columns goes back to the file step when the wizard owns it`() { + assertEquals( + ImportWizardStep.SelectFile, + ImportWizardStep.MapColumns.previousStep(fileChosenByHost = false), + ) + } + + @Test + fun `map columns hands back to the host when the host owns the file`() { + assertNull(ImportWizardStep.MapColumns.previousStep(fileChosenByHost = true)) + } + + @Test + fun `provide passphrase goes back to the file step when the wizard owns it`() { + assertEquals( + ImportWizardStep.SelectFile, + ImportWizardStep.ProvidePassphrase.previousStep(fileChosenByHost = false), + ) + } + + @Test + fun `provide passphrase hands back to the host when the host owns the file`() { + assertNull(ImportWizardStep.ProvidePassphrase.previousStep(fileChosenByHost = true)) + } + + @Test + fun `select vault always goes back to map columns`() { + assertEquals( + ImportWizardStep.MapColumns, + ImportWizardStep.SelectVault.previousStep(fileChosenByHost = true), + ) + assertEquals( + ImportWizardStep.MapColumns, + ImportWizardStep.SelectVault.previousStep(fileChosenByHost = false), + ) + } + + @Test + fun `the file step has nothing to go back to`() { + assertNull(ImportWizardStep.SelectFile.previousStep(fileChosenByHost = false)) + } + } diff --git a/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardUiStateTest.kt b/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardUiStateTest.kt index c3a1df867..79795cd72 100644 --- a/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardUiStateTest.kt +++ b/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/presentation/import/model/ImportWizardUiStateTest.kt @@ -3,6 +3,9 @@ package de.davis.keygo.feature.backup.presentation.import.model import de.davis.keygo.core.item.domain.alias.newVaultId import de.davis.keygo.core.item.domain.model.Vault import de.davis.keygo.feature.backup.domain.model.BackupDestination +import de.davis.keygo.feature.backup.domain.model.ImportError +import de.davis.keygo.feature.backup.domain.model.ImportProgress +import de.davis.keygo.feature.backup.domain.model.ImportSummary import de.davis.keygo.feature.backup.domain.model.ImportTarget import kotlin.test.Test import kotlin.test.assertEquals @@ -106,4 +109,34 @@ class ImportWizardUiStateTest { assertEquals("my.passwords.backup", state.suggestedVaultName) } + + @Test + fun `back is live while the user is still answering questions`() { + assertTrue(ImportWizardUiState(progress = null).backEnabled) + } + + @Test + fun `back is live after a failure`() { + val progress = ImportProgress.Failed(ImportError.NothingImported) + + assertTrue(ImportWizardUiState(progress = progress).backEnabled) + } + + @Test + fun `back is inert while the import runs`() { + assertFalse(ImportWizardUiState(progress = ImportProgress.Reading).backEnabled) + assertFalse(ImportWizardUiState(progress = ImportProgress.Parsing).backEnabled) + assertFalse( + ImportWizardUiState( + progress = ImportProgress.Running(processed = 1, total = 10), + ).backEnabled, + ) + } + + @Test + fun `back is inert on the summary`() { + val summary = ImportSummary(imported = 1, skipped = 0, failed = 0, vaultsCreated = 1) + + assertFalse(ImportWizardUiState(progress = ImportProgress.Succeeded(summary)).backEnabled) + } } diff --git a/feature/backup/src/testFixtures/kotlin/de/davis/keygo/feature/backup/data/FakeBackupDestinationResolver.kt b/feature/backup/src/testFixtures/kotlin/de/davis/keygo/feature/backup/data/FakeBackupDestinationResolver.kt index 7cae396c4..9a7812430 100644 --- a/feature/backup/src/testFixtures/kotlin/de/davis/keygo/feature/backup/data/FakeBackupDestinationResolver.kt +++ b/feature/backup/src/testFixtures/kotlin/de/davis/keygo/feature/backup/data/FakeBackupDestinationResolver.kt @@ -1,25 +1,36 @@ package de.davis.keygo.feature.backup.data +import de.davis.keygo.feature.backup.FakeBackupScheduler import de.davis.keygo.feature.backup.domain.BackupDestinationResolver import de.davis.keygo.feature.backup.domain.model.BackupDestination import de.davis.keygo.feature.backup.domain.model.BackupDestinationUri +import kotlinx.coroutines.CompletableDeferred +/** + * Records every resolution and hands back [result]. Pass [gate] to park inside [resolve] until the + * test completes it - mirroring [FakeBackupScheduler] - so a test can hold a resolution open and + * observe whether anything re-enters it. + */ class FakeBackupDestinationResolver( var result: BackupDestination = BackupDestination( provider = BackupDestination.Provider.OnDevice, displayPath = "Internal storage/Backups", ), + private val gate: CompletableDeferred? = null, ) : BackupDestinationResolver { - var lastUri: BackupDestinationUri? = null + val calls = mutableListOf() + + val lastUri: BackupDestinationUri? get() = calls.lastOrNull() var lastCachedName: String? = null override suspend fun resolve( uri: BackupDestinationUri, cachedName: String?, ): BackupDestination { - lastUri = uri + calls += uri lastCachedName = cachedName + gate?.await() return result } } diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt index 94e8f96e3..324da115c 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/ImportVaultContent.kt @@ -14,7 +14,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview -import de.davis.keygo.feature.backup.presentation.component.BackupFileChooser +import de.davis.keygo.feature.backup.presentation.component.BackupFileChooserCard import de.davis.keygo.feature.onboarding.R import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffold import de.davis.keygo.feature.onboarding.presentation.component.SmallIconContainer @@ -22,7 +22,7 @@ import de.davis.keygo.feature.backup.R as BackupR @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -internal fun ImportVaultContent() { +internal fun ImportVaultContent(onChooseFile: () -> Unit) { OnboardingScaffold( iconContainer = { SmallIconContainer( @@ -37,15 +37,12 @@ internal fun ImportVaultContent() { title = stringResource(R.string.import_title), description = stringResource(R.string.import_subtitle), ) { - BackupFileChooser( - destination = null, - onChoose = {}, - chooserIcon = Icons.Default.FileOpen, - chooserTitle = stringResource(BackupR.string.destination_choose_title), - chooserSubtitle = stringResource(BackupR.string.destination_choose_subtitle), - chooserAction = stringResource(BackupR.string.destination_choose_action), - changeLabel = stringResource(BackupR.string.destination_filename_label), - fileNameLabel = "TODO", // TODO + BackupFileChooserCard( + icon = Icons.Default.FileOpen, + title = stringResource(BackupR.string.import_choose_title), + subtitle = stringResource(BackupR.string.import_choose_subtitle), + action = stringResource(BackupR.string.import_choose_action), + onChoose = onChooseFile, ) } } @@ -55,7 +52,7 @@ internal fun ImportVaultContent() { private fun ImportVaultContentPreview() { MaterialTheme { Surface(modifier = Modifier.fillMaxSize()) { - ImportVaultContent() + ImportVaultContent(onChooseFile = {}) } } -} \ No newline at end of file +} diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index 87846ccbd..3e1127bf1 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -40,6 +40,8 @@ import de.davis.keygo.core.security.presentation.rememberBiometricCryptoControll import de.davis.keygo.core.util.onFailure import de.davis.keygo.core.util.onSuccess import de.davis.keygo.core.util.presentation.ObserveAsEvents +import de.davis.keygo.feature.backup.presentation.import.ImportWizardScreen +import de.davis.keygo.feature.backup.presentation.import.rememberImportFilePicker import de.davis.keygo.feature.onboarding.R import de.davis.keygo.feature.onboarding.presentation.model.AutofillSetupAction import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState @@ -100,6 +102,35 @@ fun OnboardingScreen(onSuccess: () -> Unit) { onPauseOrDispose {} } + val chooseImportFile = rememberImportFilePicker(viewModel::onImportFileChosen) + + // The wizard brings its own Scaffold, top bar, step indicator and continue button, so it + // replaces the step chrome rather than rendering inside it. It also owns back for every one of + // its phases while it holds a preselected file, so onboarding adds no handler of its own. + val importFile = (state as? OnboardingUiState.ImportData)?.fileUri + if (importFile != null) ImportWizardScreen( + preselectedFile = importFile, + navigateUp = viewModel::onImportCancelled, + onFinished = viewModel::onImportFinished, + ) + else OnboardingSteps( + state = state, + loading = loading, + onNextStep = viewModel::onNextStep, + onSkip = viewModel::onSkip, + onChooseImportFile = chooseImportFile::launch, + ) +} + +@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) +@Composable +private fun OnboardingSteps( + state: OnboardingUiState, + loading: Boolean, + onNextStep: () -> Unit, + onSkip: () -> Unit, + onChooseImportFile: () -> Unit, +) { val contentHeight = ButtonDefaults.LargeContainerHeight Scaffold( modifier = Modifier @@ -112,7 +143,7 @@ fun OnboardingScreen(onSuccess: () -> Unit) { ) { state.optionalActionText?.let { TextButton( - onClick = viewModel::onSkip, + onClick = onSkip, modifier = Modifier.fillMaxWidth(), ) { Text(text = it) @@ -121,7 +152,7 @@ fun OnboardingScreen(onSuccess: () -> Unit) { if (state.isOutlinedButonCandidate()) OutlinedButton( - onClick = viewModel::onNextStep, + onClick = onNextStep, shapes = ButtonDefaults.shapesFor(contentHeight), modifier = Modifier .sizeIn(minHeight = contentHeight) @@ -134,7 +165,7 @@ fun OnboardingScreen(onSuccess: () -> Unit) { ) } else Button( - onClick = viewModel::onNextStep, + onClick = onNextStep, shapes = ButtonDefaults.shapesFor(contentHeight), modifier = Modifier .sizeIn(minHeight = contentHeight) @@ -156,13 +187,16 @@ fun OnboardingScreen(onSuccess: () -> Unit) { when (state) { is OnboardingUiState.Welcome -> WelcomeContent( state = state, - onContinue = viewModel::onNextStep + onContinue = onNextStep ) is OnboardingUiState.SetMainPassword -> MainPasswordContent(state = state) OnboardingUiState.EnableBiometrics -> EnableBiometricsContent() - OnboardingUiState.ImportData -> ImportVaultContent() + is OnboardingUiState.ImportData -> ImportVaultContent( + onChooseFile = onChooseImportFile, + ) + is OnboardingUiState.EnableAutofill -> EnableAutofillContent(state = state) } } @@ -188,7 +222,7 @@ private val OnboardingUiState.buttonText: String is OnboardingUiState.Welcome -> if (migrating) R.string.migrate else R.string.get_started is OnboardingUiState.SetMainPassword -> R.string.continue_text OnboardingUiState.EnableBiometrics -> R.string.enable_biometrics - OnboardingUiState.ImportData -> R.string.skip_for_now + is OnboardingUiState.ImportData -> R.string.skip_for_now is OnboardingUiState.EnableAutofill -> when (nextAction) { AutofillSetupAction.OpenSystemSettings -> R.string.autofill_open_settings AutofillSetupAction.OpenChromeSettings -> R.string.autofill_enable_in_chrome @@ -202,7 +236,7 @@ private val OnboardingUiState.optionalActionText: String? @Composable get() = when (this) { is OnboardingUiState.Welcome, - OnboardingUiState.ImportData, + is OnboardingUiState.ImportData, is OnboardingUiState.SetMainPassword -> null OnboardingUiState.EnableBiometrics -> R.string.skip_for_now diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index 5546f67db..ad891aa3a 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -12,6 +12,7 @@ import de.davis.keygo.core.ui.model.UiFieldError import de.davis.keygo.core.util.onSuccess import de.davis.keygo.feature.autofill.domain.repository.AutofillServiceRepository import de.davis.keygo.feature.autofill.domain.repository.ChromeAutofillRepository +import de.davis.keygo.feature.backup.domain.model.BackupDestinationUri import de.davis.keygo.feature.onboarding.presentation.model.AutofillSetupAction import de.davis.keygo.feature.onboarding.presentation.model.OnboardingStep import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState @@ -96,7 +97,7 @@ internal class OnboardingViewModel( ) private val _importDataState = MutableStateFlow( - OnboardingUiState.ImportData + OnboardingUiState.ImportData() ) private val _enableAutofillState = MutableStateFlow( @@ -237,6 +238,21 @@ internal class OnboardingViewModel( internalSkip() } + fun onImportFileChosen(uri: BackupDestinationUri) = + _importDataState.update { it.copy(fileUri = uri) } + + fun onImportCancelled() = _importDataState.update { it.copy(fileUri = null) } + + /** + * The wizard reports its own outcome, so onboarding only has to move on. + * + * Deliberately does not clear `fileUri` first. `state` derives from `_step.flatMapLatest`, so + * advancing `_step` here is what swaps `state` straight to the next step's flow. Clearing + * `fileUri` before that swap would emit `ImportData(null)` while `_step` still pointed at + * `ImportExistingData`, flashing the chooser card between the summary and the next step. + */ + fun onImportFinished() = internalSkip() + private fun internalSkip() { val nextStep = _step.value.nextStep(stepsToSkip.value) ?: return finishUp() _step.update { nextStep } diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt index cfec53963..7c435ebd5 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt @@ -3,6 +3,7 @@ package de.davis.keygo.feature.onboarding.presentation.model import androidx.compose.foundation.text.input.TextFieldState import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.ui.model.UiFieldError +import de.davis.keygo.feature.backup.domain.model.BackupDestinationUri internal sealed interface OnboardingUiState { @@ -17,7 +18,12 @@ internal sealed interface OnboardingUiState { ) : OnboardingUiState data object EnableBiometrics : OnboardingUiState - data object ImportData : OnboardingUiState + + /** + * @param fileUri the file the user picked to import. While it is set the import wizard owns the + * screen, and clearing it returns to the chooser. + */ + data class ImportData(val fileUri: BackupDestinationUri? = null) : OnboardingUiState data class EnableAutofill( val systemAutofillEnabled: Boolean = false, diff --git a/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepTest.kt b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepTest.kt new file mode 100644 index 000000000..23565669d --- /dev/null +++ b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepTest.kt @@ -0,0 +1,35 @@ +package de.davis.keygo.feature.onboarding.presentation.model + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class OnboardingStepTest { + + @Test + fun `finishing the import moves on to autofill setup`() { + assertEquals( + OnboardingStep.EnableAutofillService, + OnboardingStep.ImportExistingData.nextStep(skip = emptySet()), + ) + } + + @Test + fun `finishing the import ends onboarding when autofill is already set up`() { + assertNull( + OnboardingStep.ImportExistingData.nextStep( + skip = setOf(OnboardingStep.EnableAutofillService), + ), + ) + } + + @Test + fun `a migrating user never reaches the import step`() { + assertEquals( + OnboardingStep.EnableAutofillService, + OnboardingStep.EnableBiometrics.nextStep( + skip = setOf(OnboardingStep.ImportExistingData), + ), + ) + } +} From 862f1938e097e72a9766a520012a1ce85601d5af Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sun, 9 Aug 2026 19:42:52 +0200 Subject: [PATCH 11/24] refactor(auth): drop migration and create access path --- feature/auth/build.gradle.kts | 1 - .../feature/auth/presentation/AuthContent.kt | 112 +-------- .../feature/auth/presentation/AuthScreen.kt | 15 -- .../auth/presentation/AuthViewModel.kt | 220 ++---------------- .../auth/presentation/model/AuthEvent.kt | 8 - .../auth/presentation/model/AuthState.kt | 80 +------ .../auth/presentation/model/AuthUIEvent.kt | 4 - .../presentation/model/BiometricRequest.kt | 5 - 8 files changed, 28 insertions(+), 417 deletions(-) delete mode 100644 feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt diff --git a/feature/auth/build.gradle.kts b/feature/auth/build.gradle.kts index e421f02a6..e917dcbd4 100644 --- a/feature/auth/build.gradle.kts +++ b/feature/auth/build.gradle.kts @@ -11,7 +11,6 @@ dependencies { implementation(projects.core.identity) implementation(projects.core.item) implementation(projects.core.ui) - implementation(projects.migration.createAccess) implementation(libs.androidx.navigation.compose) } diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt index 89c53980c..4f86cf902 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt @@ -13,11 +13,8 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.foundation.text.input.TextObfuscationMode import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.AutoFixHigh import androidx.compose.material.icons.filled.Fingerprint -import androidx.compose.material3.AlertDialog import androidx.compose.material3.BasicAlertDialog -import androidx.compose.material3.Button import androidx.compose.material3.ContainedLoadingIndicator import androidx.compose.material3.ElevatedCard import androidx.compose.material3.ExperimentalMaterial3Api @@ -29,7 +26,6 @@ import androidx.compose.material3.LoadingIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedSecureTextField import androidx.compose.material3.Surface -import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue @@ -49,7 +45,6 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.withStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp -import de.davis.keygo.core.item.presentation.StrengthIndicator import de.davis.keygo.core.ui.components.VisibilityButton import de.davis.keygo.core.ui.model.error import de.davis.keygo.core.ui.theme.KeyGoTheme @@ -73,14 +68,14 @@ fun AuthContent(state: AuthState, onEvent: (AuthUIEvent) -> Unit) { } } - is AuthState.Interactable -> InteractableAuthContent(state = state, onEvent = onEvent) + is AuthState.Login -> InteractableAuthContent(state = state, onEvent = onEvent) } } @OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) @Composable private fun InteractableAuthContent( - state: AuthState.Interactable, + state: AuthState.Login, onEvent: (AuthUIEvent) -> Unit, ) { Surface(modifier = Modifier.fillMaxSize()) { @@ -99,7 +94,7 @@ private fun InteractableAuthContent( ) { Text( text = buildAnnotatedString { - append(state.firstTitlePart) + append(stringResource(R.string.authenticate_to_access)) append(" ") withStyle( @@ -150,54 +145,6 @@ private fun InteractableAuthContent( ) }, ) - - if (this is AuthState.CreateAccess) { - StrengthIndicator( - passwordScore = passwordScore, - forceCompact = forceCompact, - ) - - var confirmPasswordHidden by rememberSaveable { mutableStateOf(true) } - OutlinedSecureTextField( - state = confirmPasswordTextFieldState, - modifier = Modifier.fillMaxWidth(), - label = { - Text(text = stringResource(R.string.confirm_password)) - }, - isError = confirmPasswordError != null, - supportingText = confirmPasswordError?.let { - { Text(it.error) } - }, - textObfuscationMode = when { - confirmPasswordHidden -> TextObfuscationMode.RevealLastTyped - else -> TextObfuscationMode.Visible - }, - trailingIcon = { - VisibilityButton( - isHidden = confirmPasswordHidden, - onClick = { - confirmPasswordHidden = !confirmPasswordHidden - }, - ) - }, - ) - } - - if (state is AuthState.BiometricAuthState && state.biometricsAvailable) - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - ) { - Text(text = stringResource(R.string.use_biometrics)) - - Switch( - checked = state.useBiometrics, - onCheckedChange = { - onEvent(AuthUIEvent.ToggleUseBiometrics(it)) - } - ) - } } Row( @@ -209,10 +156,10 @@ private fun InteractableAuthContent( modifier = Modifier.weight(1f), enabled = !state.loading ) { - Text(text = state.buttonText) + Text(text = stringResource(R.string.authenticate)) } - if (state is AuthState.Login && state.biometricAuthenticationAvailable) { + if (state.biometricAuthenticationAvailable) { FilledTonalIconButton( onClick = { onEvent(AuthUIEvent.RequestBiometricAuthentication) @@ -244,58 +191,13 @@ private fun InteractableAuthContent( } } } - - if (state is AuthState.Migrating && state.showMigrationDialog) - MigrationDialog(onClick = { onEvent(AuthUIEvent.CloseMigrationDialog) }) } } } -@Composable -fun MigrationDialog(onClick: () -> Unit) { - AlertDialog( - onDismissRequest = {}, - icon = { - Icon( - imageVector = Icons.Default.AutoFixHigh, - contentDescription = null - ) - }, - title = { - Text(text = stringResource(R.string.migrating)) - }, - text = { - Text(text = stringResource(R.string.migrate_to_access_description)) - }, - confirmButton = { - Button( - onClick = onClick - ) { - Text(text = stringResource(R.string.migrate)) - } - } - ) -} - internal val DialogMinWidth = 280.dp internal val DialogMaxWidth = 560.dp -private val AuthState.Interactable.firstTitlePart: String - @Composable - get() = when (this) { - is AuthState.Login -> stringResource(R.string.authenticate_to_access) - is AuthState.Migrating -> stringResource(R.string.migrate_to_access) - is AuthState.CreateAccess -> stringResource(R.string.create_access_access) - } - -private val AuthState.Interactable.buttonText: String - @Composable - get() = when (this) { - is AuthState.Login -> stringResource(R.string.authenticate) - is AuthState.Migrating -> stringResource(R.string.migrate) - is AuthState.CreateAccess -> stringResource(R.string.create_access) - } - @Composable @Preview @Preview( @@ -304,9 +206,9 @@ private val AuthState.Interactable.buttonText: String private fun AuthContentPreview() { KeyGoTheme { AuthContent( - state = AuthState.CreateAccess( + state = AuthState.Login( passwordTextFieldState = TextFieldState(), - biometricsAvailable = true + biometricAuthenticationAvailable = true ), onEvent = {} ) diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt index 80ad7dcb9..a88df51a9 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt @@ -1,15 +1,12 @@ package de.davis.keygo.feature.auth.presentation -import android.util.Log import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.davis.keygo.core.identity.presentation.rememberBiometricUnlockAdapter import de.davis.keygo.core.identity.presentation.useAdapter -import de.davis.keygo.core.security.domain.model.KeyId import de.davis.keygo.core.security.presentation.rememberBiometricCryptoController -import de.davis.keygo.core.util.onFailure import de.davis.keygo.core.util.onSuccess import de.davis.keygo.core.util.presentation.ObserveAsEvents import de.davis.keygo.feature.auth.presentation.model.BiometricRequest @@ -31,18 +28,6 @@ fun AuthScreen(onSuccess: () -> Unit) { ObserveAsEvents(viewModel.biometricFlow) { request -> when (request) { - is BiometricRequest.CreateAccess -> { - biometricCryptoController.requestCipher( - keyId = KeyId.BiometricVaultKek, - mode = request.cryptoMode - ).onSuccess { - viewModel.createAccessWithUnwrappingCipher(request, it) - }.onFailure { - Log.e("AuthScreen", "Failed to create cipher for biometric access: $it") - // TODO: show error - } - } - BiometricRequest.Login -> { biometricUnlockAdapter.useAdapter { biometricCryptoController.requestUnlockVault() diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt index d9b259fda..f4b740d2e 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt @@ -1,7 +1,6 @@ package de.davis.keygo.feature.auth.presentation import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -9,38 +8,21 @@ import androidx.navigation.toRoute import de.davis.keygo.core.identity.domain.repository.AccountRepository import de.davis.keygo.core.identity.domain.usecase.CreateAccessUseCase import de.davis.keygo.core.identity.domain.usecase.UnlockWithPasswordUseCase -import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository import de.davis.keygo.core.ui.model.UiFieldError import de.davis.keygo.core.util.Result -import de.davis.keygo.core.util.asResult import de.davis.keygo.core.util.onFailure import de.davis.keygo.core.util.onSuccess import de.davis.keygo.feature.auth.presentation.model.AuthState import de.davis.keygo.feature.auth.presentation.model.AuthUIEvent import de.davis.keygo.feature.auth.presentation.model.BiometricRequest -import de.davis.keygo.migration.create_access.domain.usecase.ClearMainPasswordUseCase -import de.davis.keygo.migration.create_access.domain.usecase.HasMainPasswordUseCase -import de.davis.keygo.migration.create_access.domain.usecase.ValidateMainPasswordUseCase -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.debounce -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.flowOn -import kotlinx.coroutines.flow.launchIn -import kotlinx.coroutines.flow.mapLatest -import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.koin.core.annotation.KoinViewModel -import javax.crypto.Cipher -import kotlin.time.Duration.Companion.milliseconds @KoinViewModel internal class AuthViewModel( @@ -48,13 +30,6 @@ internal class AuthViewModel( biometricAvailabilityRepository: BiometricAvailabilityRepository, accountRepository: AccountRepository, - // ---- Migration ---- - hasV1MainPassword: HasMainPasswordUseCase, - private val validateMainPassword: ValidateMainPasswordUseCase, - private val clearMainPasswordUseCase: ClearMainPasswordUseCase, - // ------------------- - - private val passwordStrengthEstimator: PasswordStrengthEstimator, private val unlockWithPassword: UnlockWithPasswordUseCase, private val createAllAccesses: CreateAccessUseCase, ) : ViewModel() { @@ -64,7 +39,6 @@ internal class AuthViewModel( private val authRoute = savedStateHandle.toRoute() private val passwordTextFieldState = TextFieldState() - private val confirmPasswordTextFieldState = TextFieldState() private val _uiState = MutableStateFlow(AuthState.Loading) val uiState = _uiState.asStateFlow() @@ -73,8 +47,6 @@ internal class AuthViewModel( viewModelScope.launch { val activeAccount = accountRepository.getOrNull() val hasAccess = activeAccount != null - val hasAccessButShouldMigrate = if (!hasAccess) hasV1MainPassword() - else false val isBiometricHardwareAvailable = biometricAvailabilityRepository.availability() val isBiometricCryptoSetupAvailable = @@ -83,89 +55,15 @@ internal class AuthViewModel( val biometricsUsable = isBiometricHardwareAvailable && isBiometricCryptoSetupAvailable if (biometricsUsable && authRoute.showBiometricPromptIfPossible) requestBiometricLogin() - _uiState.update { - when { - hasAccessButShouldMigrate -> { - AuthState.Migrating( - passwordTextFieldState = passwordTextFieldState, - biometricsAvailable = isBiometricHardwareAvailable, - ) - } - - hasAccess -> AuthState.Login( - passwordTextFieldState = passwordTextFieldState, - biometricAuthenticationAvailable = biometricsUsable - ) - - else -> { - observePasswordStrength() - observePasswordError() - observeConfirmPasswordError() - - AuthState.CreateAccess( - passwordTextFieldState = passwordTextFieldState, - confirmPasswordTextFieldState = confirmPasswordTextFieldState, - biometricsAvailable = isBiometricHardwareAvailable - ) - } - } + AuthState.Login( + passwordTextFieldState = passwordTextFieldState, + biometricAuthenticationAvailable = biometricsUsable + ) } } } - @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) - private fun observePasswordError() { - snapshotFlow { passwordTextFieldState.text } - .debounce(150.milliseconds) - .mapLatest { it.isBlank() } - .distinctUntilChanged() - .onEach { isBlank -> - if (isBlank) return@onEach - - _uiState.update { - if (it !is AuthState.CreateAccess) return@update it - it.copy(passwordError = null) - } - } - .flowOn(Dispatchers.Default) - .launchIn(viewModelScope) - } - - private fun observeConfirmPasswordError() { - snapshotFlow { passwordTextFieldState.text } - .combine(snapshotFlow { confirmPasswordTextFieldState.text }) { password, confirm -> - password == confirm - } - .distinctUntilChanged() - .onEach { equal -> - if (!equal) return@onEach - - _uiState.update { - if (it !is AuthState.CreateAccess) return@update it - it.copy(confirmPasswordError = null) - } - } - .flowOn(Dispatchers.Default) - .launchIn(viewModelScope) - } - - @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) - private fun observePasswordStrength() { - snapshotFlow { passwordTextFieldState.text } - .debounce(150.milliseconds) - .mapLatest { passwordStrengthEstimator(it.toString()) } - .distinctUntilChanged() - .onEach { score -> - _uiState.update { - if (it !is AuthState.CreateAccess) return@update it - it.copy(passwordScore = score) - } - } - .flowOn(Dispatchers.Default) - .launchIn(viewModelScope) - } - private val navigationEventChannel = Channel() val navigationEvent = navigationEventChannel.receiveAsFlow() @@ -174,129 +72,45 @@ internal class AuthViewModel( is AuthUIEvent.RequestBiometricAuthentication -> if (uiState.value is AuthState.Login) requestBiometricLogin() AuthUIEvent.Submit -> { - val state = _uiState.value as? AuthState.Interactable ?: return + val state = _uiState.value as? AuthState.Login ?: return val password = state.passwordTextFieldState.text.toString() - when (state) { - is AuthState.Login -> { - loading(setLoading = password.isNotBlank()) { - unlockWithPassword( - password = password - ).handleAuthenticationResult { - copyDefaultState(passwordError = UiFieldError.Incorrect) - } - } - } - - is AuthState.Migrating -> { - loading { - validateMainPassword(password).asResult(Unit) - .onFailure { - _uiState.update { - if (it !is AuthState.Interactable) return@update it - it.copyDefaultState(passwordError = UiFieldError.Incorrect) - } - }.onSuccess { - clearMainPasswordUseCase() - createPasswordOrBiometricAccess(state, password) - } - } + loading(setLoading = password.isNotBlank()) { + unlockWithPassword( + password = password + ).handleAuthenticationResult { + state.copy(passwordError = UiFieldError.Incorrect) } - - is AuthState.CreateAccess -> { - val errorFreeState = state.copy( - passwordError = null, - confirmPasswordError = null - ) - - if (password.isBlank()) { - _uiState.update { - errorFreeState.copy(passwordError = UiFieldError.Empty) - } - return - } - val confirmedPassword = confirmPasswordTextFieldState.text.toString() - if (password != confirmedPassword) { - _uiState.update { - errorFreeState.copy(confirmPasswordError = UiFieldError.Incorrect) - } - return - } - - createPasswordOrBiometricAccess(errorFreeState, password) - } - } - } - - AuthUIEvent.CloseMigrationDialog -> { - _uiState.update { - if (it !is AuthState.Migrating) return@update it - it.copy(showMigrationDialog = false) - } - } - - is AuthUIEvent.ToggleUseBiometrics -> { - _uiState.update { - if (it !is AuthState.BiometricAuthState) return@update it - it.copyBiometricState(useBiometrics = event.checked) } } } } - private fun createPasswordOrBiometricAccess( - authState: AuthState.BiometricAuthState, - password: String - ) { - if (!authState.biometricsAvailable || !authState.useBiometrics) { - loading { - createAllAccesses(password = password).handleAuthenticationResult() - } - - return - } - - biometricChannel.trySend(BiometricRequest.CreateAccess(password)) - } - private fun requestBiometricLogin() { biometricChannel.trySend(BiometricRequest.Login) } private fun loading( setLoading: Boolean = true, - block: suspend LoadingScope.() -> Unit + block: suspend LoadingScope.() -> Unit ) { - if (setLoading) - _uiState.update { - if (it !is AuthState.Interactable) return@update it - it.copyDefaultState(loading = true) - } + if (setLoading) _uiState.update { + if (it !is AuthState.Login) return@update it + it.copy(passwordError = null) + } viewModelScope.launch { _uiState.update { - if (it !is AuthState.Interactable) return@update it + if (it !is AuthState.Login) return@update it LoadingScope( state = it, onSuccess = { navigationEventChannel.trySend(Unit) }, ).apply { block() - }.updatedState.copyDefaultState(loading = false) + }.updatedState.copy(loading = false) } } } - - fun createAccessWithUnwrappingCipher( - createAccessRequest: BiometricRequest.CreateAccess, - cipher: Cipher - ) { - loading { - createAllAccesses( - password = createAccessRequest.password, - biometricCipher = cipher - ).handleAuthenticationResult() - } - } } private class LoadingScope( diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt deleted file mode 100644 index bd8657b24..000000000 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt +++ /dev/null @@ -1,8 +0,0 @@ -package de.davis.keygo.feature.auth.presentation.model - -internal sealed interface AuthEvent { - - data object Success : AuthEvent - data object Failure : AuthEvent - data object None : AuthEvent -} \ No newline at end of file diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt index 0e582c34e..77c1fa910 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt @@ -1,88 +1,16 @@ package de.davis.keygo.feature.auth.presentation.model import androidx.compose.foundation.text.input.TextFieldState -import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.ui.model.UiFieldError sealed interface AuthState { data object Loading : AuthState - sealed interface Interactable : AuthState { - val passwordTextFieldState: TextFieldState - val passwordError: UiFieldError? - val loading: Boolean - - fun copyDefaultState( - loading: Boolean = this.loading, - passwordTextFieldState: TextFieldState = this.passwordTextFieldState, - passwordError: UiFieldError? = this.passwordError, - ): Interactable = when (this) { - is Login -> copy( - loading = loading, - passwordTextFieldState = passwordTextFieldState, - passwordError = passwordError, - ) - - is CreateAccess -> copy( - loading = loading, - passwordTextFieldState = passwordTextFieldState, - passwordError = passwordError, - ) - - is Migrating -> copy( - loading = loading, - passwordTextFieldState = passwordTextFieldState, - passwordError = passwordError, - ) - } - } - data class Login( - override val passwordTextFieldState: TextFieldState, - override val passwordError: UiFieldError? = null, - override val loading: Boolean = false, + val passwordTextFieldState: TextFieldState, + val passwordError: UiFieldError? = null, + val loading: Boolean = false, val biometricAuthenticationAvailable: Boolean = false, - ) : Interactable - - - sealed interface BiometricAuthState : Interactable { - val biometricsAvailable: Boolean - val useBiometrics: Boolean - - fun copyBiometricState( - biometricsAvailable: Boolean = this.biometricsAvailable, - useBiometrics: Boolean = this.useBiometrics, - ): BiometricAuthState = when (this) { - is CreateAccess -> copy( - biometricsAvailable = biometricsAvailable, - useBiometrics = useBiometrics - ) - - is Migrating -> copy( - biometricsAvailable = biometricsAvailable, - useBiometrics = useBiometrics - ) - } - } - - data class Migrating( - override val passwordTextFieldState: TextFieldState, - override val passwordError: UiFieldError? = null, - override val loading: Boolean = false, - override val biometricsAvailable: Boolean = false, - override val useBiometrics: Boolean = true, - val showMigrationDialog: Boolean = true - ) : BiometricAuthState - - data class CreateAccess( - override val passwordTextFieldState: TextFieldState, - override val passwordError: UiFieldError? = null, - override val loading: Boolean = false, - override val biometricsAvailable: Boolean = false, - override val useBiometrics: Boolean = true, - val confirmPasswordTextFieldState: TextFieldState = TextFieldState(), - val confirmPasswordError: UiFieldError? = null, - val passwordScore: PasswordScore = PasswordScore.None, - ) : BiometricAuthState + ) : AuthState } diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthUIEvent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthUIEvent.kt index 03245614a..111f826d9 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthUIEvent.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthUIEvent.kt @@ -4,8 +4,4 @@ sealed interface AuthUIEvent { data object Submit : AuthUIEvent data object RequestBiometricAuthentication : AuthUIEvent - - data object CloseMigrationDialog : AuthUIEvent - - data class ToggleUseBiometrics(val checked: Boolean) : AuthUIEvent } \ No newline at end of file diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/BiometricRequest.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/BiometricRequest.kt index d7672808c..0eaf594c6 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/BiometricRequest.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/BiometricRequest.kt @@ -6,11 +6,6 @@ internal sealed interface BiometricRequest { val cryptoMode: CryptographicMode - data class CreateAccess(val password: String) : BiometricRequest { - override val cryptoMode: CryptographicMode - get() = CryptographicMode.Wrap - } - data object Login : BiometricRequest { override val cryptoMode: CryptographicMode get() = CryptographicMode.Unwrap From 0e6a402b7dbed901a9b2360a8e254122c05ae05d Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sun, 9 Aug 2026 22:39:18 +0200 Subject: [PATCH 12/24] fix(onboarding): make resposive --- .../presentation/OnboardingScreen.kt | 86 +++++++++++++------ 1 file changed, 60 insertions(+), 26 deletions(-) diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index 3e1127bf1..687370e04 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -14,12 +14,14 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.sizeIn +import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.BasicAlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ContainedLoadingIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text @@ -30,6 +32,8 @@ 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.tooling.preview.Preview +import androidx.compose.ui.tooling.preview.PreviewScreenSizes import androidx.compose.ui.unit.dp import androidx.core.net.toUri import androidx.lifecycle.compose.LifecycleResumeEffect @@ -48,6 +52,7 @@ import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState import org.koin.androidx.compose.koinViewModel private const val TAG = "OnboardingScreen" +private val OnboardingMaxWidth = 480.dp @OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) @Composable @@ -137,21 +142,40 @@ private fun OnboardingSteps( .fillMaxSize() .padding(16.dp), bottomBar = { - Column( - verticalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.padding(top = 8.dp) + Box( + modifier = Modifier.fillMaxWidth(), + contentAlignment = Alignment.TopCenter, ) { - state.optionalActionText?.let { - TextButton( - onClick = onSkip, - modifier = Modifier.fillMaxWidth(), - ) { - Text(text = it) + Column( + verticalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier + .padding(top = 8.dp) + .widthIn(max = OnboardingMaxWidth), + ) { + state.optionalActionText?.let { + TextButton( + onClick = onSkip, + modifier = Modifier.fillMaxWidth(), + ) { + Text(text = it) + } } - } - if (state.isOutlinedButonCandidate()) - OutlinedButton( + if (state.isOutlinedButonCandidate()) + OutlinedButton( + onClick = onNextStep, + shapes = ButtonDefaults.shapesFor(contentHeight), + modifier = Modifier + .sizeIn(minHeight = contentHeight) + .fillMaxWidth(), + contentPadding = ButtonDefaults.contentPaddingFor(contentHeight) + ) { + Text( + text = state.buttonText, + style = ButtonDefaults.textStyleFor(contentHeight), + ) + } + else Button( onClick = onNextStep, shapes = ButtonDefaults.shapesFor(contentHeight), modifier = Modifier @@ -164,26 +188,21 @@ private fun OnboardingSteps( style = ButtonDefaults.textStyleFor(contentHeight), ) } - else Button( - onClick = onNextStep, - shapes = ButtonDefaults.shapesFor(contentHeight), - modifier = Modifier - .sizeIn(minHeight = contentHeight) - .fillMaxWidth(), - contentPadding = ButtonDefaults.contentPaddingFor(contentHeight) - ) { - Text( - text = state.buttonText, - style = ButtonDefaults.textStyleFor(contentHeight), - ) } } } ) { innerPadding -> Box( - modifier = Modifier.padding(innerPadding) + modifier = Modifier + .padding(innerPadding) + .fillMaxSize(), + contentAlignment = Alignment.TopCenter, ) { - AnimatedContent(state, contentKey = { it::class }) { state -> + AnimatedContent( + targetState = state, + contentKey = { it::class }, + modifier = Modifier.widthIn(max = OnboardingMaxWidth), + ) { state -> when (state) { is OnboardingUiState.Welcome -> WelcomeContent( state = state, @@ -245,3 +264,18 @@ private val OnboardingUiState.optionalActionText: String? }?.let { stringResource(it) } private fun OnboardingUiState.isOutlinedButonCandidate() = this is OnboardingUiState.ImportData + +@Preview +@PreviewScreenSizes +@Composable +private fun OnboardingStepsPreview() { + MaterialTheme { + OnboardingSteps( + state = OnboardingUiState.Welcome(), + loading = false, + onNextStep = {}, + onSkip = {}, + onChooseImportFile = {}, + ) + } +} From bd59881dd396496cbfa83f6b7c6e9911cf144dd4 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Mon, 10 Aug 2026 20:33:34 +0200 Subject: [PATCH 13/24] Revert "refactor(auth): drop migration and create access path" This reverts commit 862f1938e097e72a9766a520012a1ce85601d5af. --- feature/auth/build.gradle.kts | 1 + .../feature/auth/presentation/AuthContent.kt | 112 ++++++++- .../feature/auth/presentation/AuthScreen.kt | 15 ++ .../auth/presentation/AuthViewModel.kt | 220 ++++++++++++++++-- .../auth/presentation/model/AuthEvent.kt | 8 + .../auth/presentation/model/AuthState.kt | 80 ++++++- .../auth/presentation/model/AuthUIEvent.kt | 4 + .../presentation/model/BiometricRequest.kt | 5 + 8 files changed, 417 insertions(+), 28 deletions(-) create mode 100644 feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt diff --git a/feature/auth/build.gradle.kts b/feature/auth/build.gradle.kts index e917dcbd4..e421f02a6 100644 --- a/feature/auth/build.gradle.kts +++ b/feature/auth/build.gradle.kts @@ -11,6 +11,7 @@ dependencies { implementation(projects.core.identity) implementation(projects.core.item) implementation(projects.core.ui) + implementation(projects.migration.createAccess) implementation(libs.androidx.navigation.compose) } diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt index 4f86cf902..89c53980c 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt @@ -13,8 +13,11 @@ import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.foundation.text.input.TextObfuscationMode import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AutoFixHigh import androidx.compose.material.icons.filled.Fingerprint +import androidx.compose.material3.AlertDialog import androidx.compose.material3.BasicAlertDialog +import androidx.compose.material3.Button import androidx.compose.material3.ContainedLoadingIndicator import androidx.compose.material3.ElevatedCard import androidx.compose.material3.ExperimentalMaterial3Api @@ -26,6 +29,7 @@ import androidx.compose.material3.LoadingIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedSecureTextField import androidx.compose.material3.Surface +import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue @@ -45,6 +49,7 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.withStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp +import de.davis.keygo.core.item.presentation.StrengthIndicator import de.davis.keygo.core.ui.components.VisibilityButton import de.davis.keygo.core.ui.model.error import de.davis.keygo.core.ui.theme.KeyGoTheme @@ -68,14 +73,14 @@ fun AuthContent(state: AuthState, onEvent: (AuthUIEvent) -> Unit) { } } - is AuthState.Login -> InteractableAuthContent(state = state, onEvent = onEvent) + is AuthState.Interactable -> InteractableAuthContent(state = state, onEvent = onEvent) } } @OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) @Composable private fun InteractableAuthContent( - state: AuthState.Login, + state: AuthState.Interactable, onEvent: (AuthUIEvent) -> Unit, ) { Surface(modifier = Modifier.fillMaxSize()) { @@ -94,7 +99,7 @@ private fun InteractableAuthContent( ) { Text( text = buildAnnotatedString { - append(stringResource(R.string.authenticate_to_access)) + append(state.firstTitlePart) append(" ") withStyle( @@ -145,6 +150,54 @@ private fun InteractableAuthContent( ) }, ) + + if (this is AuthState.CreateAccess) { + StrengthIndicator( + passwordScore = passwordScore, + forceCompact = forceCompact, + ) + + var confirmPasswordHidden by rememberSaveable { mutableStateOf(true) } + OutlinedSecureTextField( + state = confirmPasswordTextFieldState, + modifier = Modifier.fillMaxWidth(), + label = { + Text(text = stringResource(R.string.confirm_password)) + }, + isError = confirmPasswordError != null, + supportingText = confirmPasswordError?.let { + { Text(it.error) } + }, + textObfuscationMode = when { + confirmPasswordHidden -> TextObfuscationMode.RevealLastTyped + else -> TextObfuscationMode.Visible + }, + trailingIcon = { + VisibilityButton( + isHidden = confirmPasswordHidden, + onClick = { + confirmPasswordHidden = !confirmPasswordHidden + }, + ) + }, + ) + } + + if (state is AuthState.BiometricAuthState && state.biometricsAvailable) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text(text = stringResource(R.string.use_biometrics)) + + Switch( + checked = state.useBiometrics, + onCheckedChange = { + onEvent(AuthUIEvent.ToggleUseBiometrics(it)) + } + ) + } } Row( @@ -156,10 +209,10 @@ private fun InteractableAuthContent( modifier = Modifier.weight(1f), enabled = !state.loading ) { - Text(text = stringResource(R.string.authenticate)) + Text(text = state.buttonText) } - if (state.biometricAuthenticationAvailable) { + if (state is AuthState.Login && state.biometricAuthenticationAvailable) { FilledTonalIconButton( onClick = { onEvent(AuthUIEvent.RequestBiometricAuthentication) @@ -191,13 +244,58 @@ private fun InteractableAuthContent( } } } + + if (state is AuthState.Migrating && state.showMigrationDialog) + MigrationDialog(onClick = { onEvent(AuthUIEvent.CloseMigrationDialog) }) } } } +@Composable +fun MigrationDialog(onClick: () -> Unit) { + AlertDialog( + onDismissRequest = {}, + icon = { + Icon( + imageVector = Icons.Default.AutoFixHigh, + contentDescription = null + ) + }, + title = { + Text(text = stringResource(R.string.migrating)) + }, + text = { + Text(text = stringResource(R.string.migrate_to_access_description)) + }, + confirmButton = { + Button( + onClick = onClick + ) { + Text(text = stringResource(R.string.migrate)) + } + } + ) +} + internal val DialogMinWidth = 280.dp internal val DialogMaxWidth = 560.dp +private val AuthState.Interactable.firstTitlePart: String + @Composable + get() = when (this) { + is AuthState.Login -> stringResource(R.string.authenticate_to_access) + is AuthState.Migrating -> stringResource(R.string.migrate_to_access) + is AuthState.CreateAccess -> stringResource(R.string.create_access_access) + } + +private val AuthState.Interactable.buttonText: String + @Composable + get() = when (this) { + is AuthState.Login -> stringResource(R.string.authenticate) + is AuthState.Migrating -> stringResource(R.string.migrate) + is AuthState.CreateAccess -> stringResource(R.string.create_access) + } + @Composable @Preview @Preview( @@ -206,9 +304,9 @@ internal val DialogMaxWidth = 560.dp private fun AuthContentPreview() { KeyGoTheme { AuthContent( - state = AuthState.Login( + state = AuthState.CreateAccess( passwordTextFieldState = TextFieldState(), - biometricAuthenticationAvailable = true + biometricsAvailable = true ), onEvent = {} ) diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt index a88df51a9..80ad7dcb9 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt @@ -1,12 +1,15 @@ package de.davis.keygo.feature.auth.presentation +import android.util.Log import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.davis.keygo.core.identity.presentation.rememberBiometricUnlockAdapter import de.davis.keygo.core.identity.presentation.useAdapter +import de.davis.keygo.core.security.domain.model.KeyId import de.davis.keygo.core.security.presentation.rememberBiometricCryptoController +import de.davis.keygo.core.util.onFailure import de.davis.keygo.core.util.onSuccess import de.davis.keygo.core.util.presentation.ObserveAsEvents import de.davis.keygo.feature.auth.presentation.model.BiometricRequest @@ -28,6 +31,18 @@ fun AuthScreen(onSuccess: () -> Unit) { ObserveAsEvents(viewModel.biometricFlow) { request -> when (request) { + is BiometricRequest.CreateAccess -> { + biometricCryptoController.requestCipher( + keyId = KeyId.BiometricVaultKek, + mode = request.cryptoMode + ).onSuccess { + viewModel.createAccessWithUnwrappingCipher(request, it) + }.onFailure { + Log.e("AuthScreen", "Failed to create cipher for biometric access: $it") + // TODO: show error + } + } + BiometricRequest.Login -> { biometricUnlockAdapter.useAdapter { biometricCryptoController.requestUnlockVault() diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt index f4b740d2e..d9b259fda 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt @@ -1,6 +1,7 @@ package de.davis.keygo.feature.auth.presentation import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -8,21 +9,38 @@ import androidx.navigation.toRoute import de.davis.keygo.core.identity.domain.repository.AccountRepository import de.davis.keygo.core.identity.domain.usecase.CreateAccessUseCase import de.davis.keygo.core.identity.domain.usecase.UnlockWithPasswordUseCase +import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository import de.davis.keygo.core.ui.model.UiFieldError import de.davis.keygo.core.util.Result +import de.davis.keygo.core.util.asResult import de.davis.keygo.core.util.onFailure import de.davis.keygo.core.util.onSuccess import de.davis.keygo.feature.auth.presentation.model.AuthState import de.davis.keygo.feature.auth.presentation.model.AuthUIEvent import de.davis.keygo.feature.auth.presentation.model.BiometricRequest +import de.davis.keygo.migration.create_access.domain.usecase.ClearMainPasswordUseCase +import de.davis.keygo.migration.create_access.domain.usecase.HasMainPasswordUseCase +import de.davis.keygo.migration.create_access.domain.usecase.ValidateMainPasswordUseCase +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.debounce +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.mapLatest +import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.koin.core.annotation.KoinViewModel +import javax.crypto.Cipher +import kotlin.time.Duration.Companion.milliseconds @KoinViewModel internal class AuthViewModel( @@ -30,6 +48,13 @@ internal class AuthViewModel( biometricAvailabilityRepository: BiometricAvailabilityRepository, accountRepository: AccountRepository, + // ---- Migration ---- + hasV1MainPassword: HasMainPasswordUseCase, + private val validateMainPassword: ValidateMainPasswordUseCase, + private val clearMainPasswordUseCase: ClearMainPasswordUseCase, + // ------------------- + + private val passwordStrengthEstimator: PasswordStrengthEstimator, private val unlockWithPassword: UnlockWithPasswordUseCase, private val createAllAccesses: CreateAccessUseCase, ) : ViewModel() { @@ -39,6 +64,7 @@ internal class AuthViewModel( private val authRoute = savedStateHandle.toRoute() private val passwordTextFieldState = TextFieldState() + private val confirmPasswordTextFieldState = TextFieldState() private val _uiState = MutableStateFlow(AuthState.Loading) val uiState = _uiState.asStateFlow() @@ -47,6 +73,8 @@ internal class AuthViewModel( viewModelScope.launch { val activeAccount = accountRepository.getOrNull() val hasAccess = activeAccount != null + val hasAccessButShouldMigrate = if (!hasAccess) hasV1MainPassword() + else false val isBiometricHardwareAvailable = biometricAvailabilityRepository.availability() val isBiometricCryptoSetupAvailable = @@ -55,15 +83,89 @@ internal class AuthViewModel( val biometricsUsable = isBiometricHardwareAvailable && isBiometricCryptoSetupAvailable if (biometricsUsable && authRoute.showBiometricPromptIfPossible) requestBiometricLogin() + _uiState.update { - AuthState.Login( - passwordTextFieldState = passwordTextFieldState, - biometricAuthenticationAvailable = biometricsUsable - ) + when { + hasAccessButShouldMigrate -> { + AuthState.Migrating( + passwordTextFieldState = passwordTextFieldState, + biometricsAvailable = isBiometricHardwareAvailable, + ) + } + + hasAccess -> AuthState.Login( + passwordTextFieldState = passwordTextFieldState, + biometricAuthenticationAvailable = biometricsUsable + ) + + else -> { + observePasswordStrength() + observePasswordError() + observeConfirmPasswordError() + + AuthState.CreateAccess( + passwordTextFieldState = passwordTextFieldState, + confirmPasswordTextFieldState = confirmPasswordTextFieldState, + biometricsAvailable = isBiometricHardwareAvailable + ) + } + } } } } + @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) + private fun observePasswordError() { + snapshotFlow { passwordTextFieldState.text } + .debounce(150.milliseconds) + .mapLatest { it.isBlank() } + .distinctUntilChanged() + .onEach { isBlank -> + if (isBlank) return@onEach + + _uiState.update { + if (it !is AuthState.CreateAccess) return@update it + it.copy(passwordError = null) + } + } + .flowOn(Dispatchers.Default) + .launchIn(viewModelScope) + } + + private fun observeConfirmPasswordError() { + snapshotFlow { passwordTextFieldState.text } + .combine(snapshotFlow { confirmPasswordTextFieldState.text }) { password, confirm -> + password == confirm + } + .distinctUntilChanged() + .onEach { equal -> + if (!equal) return@onEach + + _uiState.update { + if (it !is AuthState.CreateAccess) return@update it + it.copy(confirmPasswordError = null) + } + } + .flowOn(Dispatchers.Default) + .launchIn(viewModelScope) + } + + @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) + private fun observePasswordStrength() { + snapshotFlow { passwordTextFieldState.text } + .debounce(150.milliseconds) + .mapLatest { passwordStrengthEstimator(it.toString()) } + .distinctUntilChanged() + .onEach { score -> + _uiState.update { + if (it !is AuthState.CreateAccess) return@update it + it.copy(passwordScore = score) + } + } + .flowOn(Dispatchers.Default) + .launchIn(viewModelScope) + } + private val navigationEventChannel = Channel() val navigationEvent = navigationEventChannel.receiveAsFlow() @@ -72,45 +174,129 @@ internal class AuthViewModel( is AuthUIEvent.RequestBiometricAuthentication -> if (uiState.value is AuthState.Login) requestBiometricLogin() AuthUIEvent.Submit -> { - val state = _uiState.value as? AuthState.Login ?: return + val state = _uiState.value as? AuthState.Interactable ?: return val password = state.passwordTextFieldState.text.toString() - loading(setLoading = password.isNotBlank()) { - unlockWithPassword( - password = password - ).handleAuthenticationResult { - state.copy(passwordError = UiFieldError.Incorrect) + when (state) { + is AuthState.Login -> { + loading(setLoading = password.isNotBlank()) { + unlockWithPassword( + password = password + ).handleAuthenticationResult { + copyDefaultState(passwordError = UiFieldError.Incorrect) + } + } + } + + is AuthState.Migrating -> { + loading { + validateMainPassword(password).asResult(Unit) + .onFailure { + _uiState.update { + if (it !is AuthState.Interactable) return@update it + it.copyDefaultState(passwordError = UiFieldError.Incorrect) + } + }.onSuccess { + clearMainPasswordUseCase() + createPasswordOrBiometricAccess(state, password) + } + } } + + is AuthState.CreateAccess -> { + val errorFreeState = state.copy( + passwordError = null, + confirmPasswordError = null + ) + + if (password.isBlank()) { + _uiState.update { + errorFreeState.copy(passwordError = UiFieldError.Empty) + } + return + } + val confirmedPassword = confirmPasswordTextFieldState.text.toString() + if (password != confirmedPassword) { + _uiState.update { + errorFreeState.copy(confirmPasswordError = UiFieldError.Incorrect) + } + return + } + + createPasswordOrBiometricAccess(errorFreeState, password) + } + } + } + + AuthUIEvent.CloseMigrationDialog -> { + _uiState.update { + if (it !is AuthState.Migrating) return@update it + it.copy(showMigrationDialog = false) + } + } + + is AuthUIEvent.ToggleUseBiometrics -> { + _uiState.update { + if (it !is AuthState.BiometricAuthState) return@update it + it.copyBiometricState(useBiometrics = event.checked) } } } } + private fun createPasswordOrBiometricAccess( + authState: AuthState.BiometricAuthState, + password: String + ) { + if (!authState.biometricsAvailable || !authState.useBiometrics) { + loading { + createAllAccesses(password = password).handleAuthenticationResult() + } + + return + } + + biometricChannel.trySend(BiometricRequest.CreateAccess(password)) + } + private fun requestBiometricLogin() { biometricChannel.trySend(BiometricRequest.Login) } private fun loading( setLoading: Boolean = true, - block: suspend LoadingScope.() -> Unit + block: suspend LoadingScope.() -> Unit ) { - if (setLoading) _uiState.update { - if (it !is AuthState.Login) return@update it - it.copy(passwordError = null) - } + if (setLoading) + _uiState.update { + if (it !is AuthState.Interactable) return@update it + it.copyDefaultState(loading = true) + } viewModelScope.launch { _uiState.update { - if (it !is AuthState.Login) return@update it + if (it !is AuthState.Interactable) return@update it LoadingScope( state = it, onSuccess = { navigationEventChannel.trySend(Unit) }, ).apply { block() - }.updatedState.copy(loading = false) + }.updatedState.copyDefaultState(loading = false) } } } + + fun createAccessWithUnwrappingCipher( + createAccessRequest: BiometricRequest.CreateAccess, + cipher: Cipher + ) { + loading { + createAllAccesses( + password = createAccessRequest.password, + biometricCipher = cipher + ).handleAuthenticationResult() + } + } } private class LoadingScope( diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt new file mode 100644 index 000000000..bd8657b24 --- /dev/null +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt @@ -0,0 +1,8 @@ +package de.davis.keygo.feature.auth.presentation.model + +internal sealed interface AuthEvent { + + data object Success : AuthEvent + data object Failure : AuthEvent + data object None : AuthEvent +} \ No newline at end of file diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt index 77c1fa910..0e582c34e 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt @@ -1,16 +1,88 @@ package de.davis.keygo.feature.auth.presentation.model import androidx.compose.foundation.text.input.TextFieldState +import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.ui.model.UiFieldError sealed interface AuthState { data object Loading : AuthState + sealed interface Interactable : AuthState { + val passwordTextFieldState: TextFieldState + val passwordError: UiFieldError? + val loading: Boolean + + fun copyDefaultState( + loading: Boolean = this.loading, + passwordTextFieldState: TextFieldState = this.passwordTextFieldState, + passwordError: UiFieldError? = this.passwordError, + ): Interactable = when (this) { + is Login -> copy( + loading = loading, + passwordTextFieldState = passwordTextFieldState, + passwordError = passwordError, + ) + + is CreateAccess -> copy( + loading = loading, + passwordTextFieldState = passwordTextFieldState, + passwordError = passwordError, + ) + + is Migrating -> copy( + loading = loading, + passwordTextFieldState = passwordTextFieldState, + passwordError = passwordError, + ) + } + } + data class Login( - val passwordTextFieldState: TextFieldState, - val passwordError: UiFieldError? = null, - val loading: Boolean = false, + override val passwordTextFieldState: TextFieldState, + override val passwordError: UiFieldError? = null, + override val loading: Boolean = false, val biometricAuthenticationAvailable: Boolean = false, - ) : AuthState + ) : Interactable + + + sealed interface BiometricAuthState : Interactable { + val biometricsAvailable: Boolean + val useBiometrics: Boolean + + fun copyBiometricState( + biometricsAvailable: Boolean = this.biometricsAvailable, + useBiometrics: Boolean = this.useBiometrics, + ): BiometricAuthState = when (this) { + is CreateAccess -> copy( + biometricsAvailable = biometricsAvailable, + useBiometrics = useBiometrics + ) + + is Migrating -> copy( + biometricsAvailable = biometricsAvailable, + useBiometrics = useBiometrics + ) + } + } + + data class Migrating( + override val passwordTextFieldState: TextFieldState, + override val passwordError: UiFieldError? = null, + override val loading: Boolean = false, + override val biometricsAvailable: Boolean = false, + override val useBiometrics: Boolean = true, + val showMigrationDialog: Boolean = true + ) : BiometricAuthState + + data class CreateAccess( + override val passwordTextFieldState: TextFieldState, + override val passwordError: UiFieldError? = null, + override val loading: Boolean = false, + override val biometricsAvailable: Boolean = false, + override val useBiometrics: Boolean = true, + val confirmPasswordTextFieldState: TextFieldState = TextFieldState(), + val confirmPasswordError: UiFieldError? = null, + val passwordScore: PasswordScore = PasswordScore.None, + ) : BiometricAuthState } diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthUIEvent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthUIEvent.kt index 111f826d9..03245614a 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthUIEvent.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthUIEvent.kt @@ -4,4 +4,8 @@ sealed interface AuthUIEvent { data object Submit : AuthUIEvent data object RequestBiometricAuthentication : AuthUIEvent + + data object CloseMigrationDialog : AuthUIEvent + + data class ToggleUseBiometrics(val checked: Boolean) : AuthUIEvent } \ No newline at end of file diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/BiometricRequest.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/BiometricRequest.kt index 0eaf594c6..d7672808c 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/BiometricRequest.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/BiometricRequest.kt @@ -6,6 +6,11 @@ internal sealed interface BiometricRequest { val cryptoMode: CryptographicMode + data class CreateAccess(val password: String) : BiometricRequest { + override val cryptoMode: CryptographicMode + get() = CryptographicMode.Wrap + } + data object Login : BiometricRequest { override val cryptoMode: CryptographicMode get() = CryptographicMode.Unwrap From e4dfcd7ce871c10e038ccfe025db5309bc6a6486 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Mon, 10 Aug 2026 20:49:01 +0200 Subject: [PATCH 14/24] refactor: drop migration from onboarding and create access from auth --- app/build.gradle.kts | 1 + .../keygo/app/presentation/AppViewModel.kt | 16 ++- .../keygo/app/presentation/MainActivity.kt | 39 +++--- .../feature/auth/presentation/AuthContent.kt | 47 +------ .../auth/presentation/AuthViewModel.kt | 115 +----------------- .../auth/presentation/model/AuthEvent.kt | 8 -- .../auth/presentation/model/AuthState.kt | 45 +------ .../presentation/OnboardingScreen.kt | 4 +- .../presentation/OnboardingViewModel.kt | 24 ++-- .../presentation/model/OnboardingStep.kt | 3 +- .../presentation/model/OnboardingUiState.kt | 2 +- .../src/main/res/values/strings.xml | 1 - gradle/libs.versions.toml | 2 + 13 files changed, 62 insertions(+), 245 deletions(-) delete mode 100644 feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 521beac26..0cdb936dd 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -122,6 +122,7 @@ dependencies { implementation(projects.migration.createAccess) implementation(projects.migration.legacyData) + implementation(libs.androidx.core.splashscreen) implementation(libs.androidx.core.ktx) implementation(libs.androidx.lifecycle.runtime.ktx) implementation(platform(libs.androidx.compose.bom)) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt index ed8f2f053..d51b6f94f 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt @@ -1,15 +1,25 @@ package de.davis.keygo.app.presentation import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope import de.davis.keygo.core.identity.domain.repository.AccountRepository -import de.davis.keygo.migration.create_access.domain.usecase.HasMainPasswordUseCase +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch import org.koin.core.annotation.KoinViewModel @KoinViewModel internal class AppViewModel( - private val hasV1Password: HasMainPasswordUseCase, private val accountRepository: AccountRepository ) : ViewModel() { - suspend fun hasValidAccount() = accountRepository.getOrNull() != null && !hasV1Password() + private val _hasAccess = MutableStateFlow(null) + val hasAccess = _hasAccess.asStateFlow() + + init { + viewModelScope.launch { + _hasAccess.update { accountRepository.getOrNull() != null } + } + } } \ No newline at end of file diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt index 575184ce6..a271a09de 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt @@ -13,13 +13,12 @@ import androidx.compose.material3.adaptive.layout.ThreePaneScaffoldRole import androidx.compose.material3.adaptive.navigation.rememberListDetailPaneScaffoldNavigator import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier -import androidx.compose.ui.tooling.preview.Preview -import androidx.compose.ui.tooling.preview.Wallpapers +import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.fragment.app.FragmentActivity import androidx.navigation.NavDestination.Companion.hasRoute import androidx.navigation.NavDestination.Companion.hierarchy @@ -49,20 +48,35 @@ import de.davis.keygo.feature.settings.presentation.ChangePasswordRoute import de.davis.keygo.feature.settings.presentation.settingsGraph import de.davis.keygo.item.dialog.SelectItemContent import kotlinx.coroutines.launch -import org.koin.androidx.compose.koinViewModel +import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.compose.koinInject class MainActivity : FragmentActivity() { + + private val viewModel by viewModel() + override fun onCreate(savedInstanceState: Bundle?) { + val splashScreen = installSplashScreen() + super.onCreate(savedInstanceState) + + splashScreen.setKeepOnScreenCondition { + viewModel.hasAccess.value == null + } + enableEdgeToEdge() setContent { + val hasAccess by viewModel.hasAccess.collectAsState() + hasAccess ?: return@setContent + KeyGoTheme { val snackbarManager = koinInject() CompositionLocalProvider( LocalSnackbarManager provides snackbarManager, ) { - App() + App( + startDestinations = if (hasAccess == true) AuthRoute() else OnboardingRoute() + ) } } } @@ -70,11 +84,8 @@ class MainActivity : FragmentActivity() { } @OptIn(ExperimentalMaterial3AdaptiveApi::class) -@Preview(wallpaper = Wallpapers.RED_DOMINATED_EXAMPLE) -@Preview(wallpaper = Wallpapers.RED_DOMINATED_EXAMPLE, device = "spec:width=673dp,height=841dp") -@Preview(wallpaper = Wallpapers.RED_DOMINATED_EXAMPLE, device = "id:desktop_large") @Composable -private fun App() { +private fun App(startDestinations: Any) { val listNavigator = rememberListDetailPaneScaffoldNavigator() val navController = rememberNavController() @@ -97,14 +108,6 @@ private fun App() { SnackbarHandler(snackbarHostState) val scope = rememberCoroutineScope() - - val viewModel = koinViewModel() - val hasAccess by produceState(null) { - value = viewModel.hasValidAccount() - } - - if (hasAccess == null) return // TODO: Add this to splash screen - KeyGoNavigationWrapper( currentDestination = currentDestination, navigateToTopLevelDestination = { @@ -136,7 +139,7 @@ private fun App() { ) { NavHost( navController = navController, - startDestination = if (hasAccess == true) AuthRoute() else OnboardingRoute(), + startDestination = startDestinations, ) { authGraph( onSuccess = { totpUri -> diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt index 89c53980c..50bb2b927 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt @@ -38,7 +38,6 @@ 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.focus.onFocusChanged import androidx.compose.ui.graphics.Brush import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.SpanStyle @@ -49,7 +48,6 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.withStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp -import de.davis.keygo.core.item.presentation.StrengthIndicator import de.davis.keygo.core.ui.components.VisibilityButton import de.davis.keygo.core.ui.model.error import de.davis.keygo.core.ui.theme.KeyGoTheme @@ -124,14 +122,9 @@ private fun InteractableAuthContent( with(state) { var passwordHidden by rememberSaveable { mutableStateOf(true) } - var forceCompact by rememberSaveable { mutableStateOf(false) } OutlinedSecureTextField( state = passwordTextFieldState, - modifier = Modifier - .fillMaxWidth() - .onFocusChanged { - forceCompact = !it.hasFocus - }, + modifier = Modifier.fillMaxWidth(), label = { Text(text = stringResource(CoreItemR.string.password)) }, @@ -151,39 +144,7 @@ private fun InteractableAuthContent( }, ) - if (this is AuthState.CreateAccess) { - StrengthIndicator( - passwordScore = passwordScore, - forceCompact = forceCompact, - ) - - var confirmPasswordHidden by rememberSaveable { mutableStateOf(true) } - OutlinedSecureTextField( - state = confirmPasswordTextFieldState, - modifier = Modifier.fillMaxWidth(), - label = { - Text(text = stringResource(R.string.confirm_password)) - }, - isError = confirmPasswordError != null, - supportingText = confirmPasswordError?.let { - { Text(it.error) } - }, - textObfuscationMode = when { - confirmPasswordHidden -> TextObfuscationMode.RevealLastTyped - else -> TextObfuscationMode.Visible - }, - trailingIcon = { - VisibilityButton( - isHidden = confirmPasswordHidden, - onClick = { - confirmPasswordHidden = !confirmPasswordHidden - }, - ) - }, - ) - } - - if (state is AuthState.BiometricAuthState && state.biometricsAvailable) + if (state is AuthState.Migrating && state.biometricsAvailable) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, @@ -285,7 +246,6 @@ private val AuthState.Interactable.firstTitlePart: String get() = when (this) { is AuthState.Login -> stringResource(R.string.authenticate_to_access) is AuthState.Migrating -> stringResource(R.string.migrate_to_access) - is AuthState.CreateAccess -> stringResource(R.string.create_access_access) } private val AuthState.Interactable.buttonText: String @@ -293,7 +253,6 @@ private val AuthState.Interactable.buttonText: String get() = when (this) { is AuthState.Login -> stringResource(R.string.authenticate) is AuthState.Migrating -> stringResource(R.string.migrate) - is AuthState.CreateAccess -> stringResource(R.string.create_access) } @Composable @@ -304,7 +263,7 @@ private val AuthState.Interactable.buttonText: String private fun AuthContentPreview() { KeyGoTheme { AuthContent( - state = AuthState.CreateAccess( + state = AuthState.Migrating( passwordTextFieldState = TextFieldState(), biometricsAvailable = true ), diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt index d9b259fda..eaad0a14b 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt @@ -1,7 +1,6 @@ package de.davis.keygo.feature.auth.presentation import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -9,7 +8,6 @@ import androidx.navigation.toRoute import de.davis.keygo.core.identity.domain.repository.AccountRepository import de.davis.keygo.core.identity.domain.usecase.CreateAccessUseCase import de.davis.keygo.core.identity.domain.usecase.UnlockWithPasswordUseCase -import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository import de.davis.keygo.core.ui.model.UiFieldError import de.davis.keygo.core.util.Result @@ -22,25 +20,14 @@ import de.davis.keygo.feature.auth.presentation.model.BiometricRequest import de.davis.keygo.migration.create_access.domain.usecase.ClearMainPasswordUseCase import de.davis.keygo.migration.create_access.domain.usecase.HasMainPasswordUseCase import de.davis.keygo.migration.create_access.domain.usecase.ValidateMainPasswordUseCase -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.debounce -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.flowOn -import kotlinx.coroutines.flow.launchIn -import kotlinx.coroutines.flow.mapLatest -import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.koin.core.annotation.KoinViewModel import javax.crypto.Cipher -import kotlin.time.Duration.Companion.milliseconds @KoinViewModel internal class AuthViewModel( @@ -54,7 +41,6 @@ internal class AuthViewModel( private val clearMainPasswordUseCase: ClearMainPasswordUseCase, // ------------------- - private val passwordStrengthEstimator: PasswordStrengthEstimator, private val unlockWithPassword: UnlockWithPasswordUseCase, private val createAllAccesses: CreateAccessUseCase, ) : ViewModel() { @@ -64,7 +50,6 @@ internal class AuthViewModel( private val authRoute = savedStateHandle.toRoute() private val passwordTextFieldState = TextFieldState() - private val confirmPasswordTextFieldState = TextFieldState() private val _uiState = MutableStateFlow(AuthState.Loading) val uiState = _uiState.asStateFlow() @@ -73,8 +58,7 @@ internal class AuthViewModel( viewModelScope.launch { val activeAccount = accountRepository.getOrNull() val hasAccess = activeAccount != null - val hasAccessButShouldMigrate = if (!hasAccess) hasV1MainPassword() - else false + val shouldMigrate = if (!hasAccess) hasV1MainPassword() else false val isBiometricHardwareAvailable = biometricAvailabilityRepository.availability() val isBiometricCryptoSetupAvailable = @@ -86,86 +70,22 @@ internal class AuthViewModel( _uiState.update { when { - hasAccessButShouldMigrate -> { + shouldMigrate -> { AuthState.Migrating( passwordTextFieldState = passwordTextFieldState, biometricsAvailable = isBiometricHardwareAvailable, ) } - hasAccess -> AuthState.Login( + else -> AuthState.Login( passwordTextFieldState = passwordTextFieldState, biometricAuthenticationAvailable = biometricsUsable ) - - else -> { - observePasswordStrength() - observePasswordError() - observeConfirmPasswordError() - - AuthState.CreateAccess( - passwordTextFieldState = passwordTextFieldState, - confirmPasswordTextFieldState = confirmPasswordTextFieldState, - biometricsAvailable = isBiometricHardwareAvailable - ) - } } } } } - @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) - private fun observePasswordError() { - snapshotFlow { passwordTextFieldState.text } - .debounce(150.milliseconds) - .mapLatest { it.isBlank() } - .distinctUntilChanged() - .onEach { isBlank -> - if (isBlank) return@onEach - - _uiState.update { - if (it !is AuthState.CreateAccess) return@update it - it.copy(passwordError = null) - } - } - .flowOn(Dispatchers.Default) - .launchIn(viewModelScope) - } - - private fun observeConfirmPasswordError() { - snapshotFlow { passwordTextFieldState.text } - .combine(snapshotFlow { confirmPasswordTextFieldState.text }) { password, confirm -> - password == confirm - } - .distinctUntilChanged() - .onEach { equal -> - if (!equal) return@onEach - - _uiState.update { - if (it !is AuthState.CreateAccess) return@update it - it.copy(confirmPasswordError = null) - } - } - .flowOn(Dispatchers.Default) - .launchIn(viewModelScope) - } - - @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) - private fun observePasswordStrength() { - snapshotFlow { passwordTextFieldState.text } - .debounce(150.milliseconds) - .mapLatest { passwordStrengthEstimator(it.toString()) } - .distinctUntilChanged() - .onEach { score -> - _uiState.update { - if (it !is AuthState.CreateAccess) return@update it - it.copy(passwordScore = score) - } - } - .flowOn(Dispatchers.Default) - .launchIn(viewModelScope) - } - private val navigationEventChannel = Channel() val navigationEvent = navigationEventChannel.receiveAsFlow() @@ -201,29 +121,6 @@ internal class AuthViewModel( } } } - - is AuthState.CreateAccess -> { - val errorFreeState = state.copy( - passwordError = null, - confirmPasswordError = null - ) - - if (password.isBlank()) { - _uiState.update { - errorFreeState.copy(passwordError = UiFieldError.Empty) - } - return - } - val confirmedPassword = confirmPasswordTextFieldState.text.toString() - if (password != confirmedPassword) { - _uiState.update { - errorFreeState.copy(confirmPasswordError = UiFieldError.Incorrect) - } - return - } - - createPasswordOrBiometricAccess(errorFreeState, password) - } } } @@ -236,15 +133,15 @@ internal class AuthViewModel( is AuthUIEvent.ToggleUseBiometrics -> { _uiState.update { - if (it !is AuthState.BiometricAuthState) return@update it - it.copyBiometricState(useBiometrics = event.checked) + if (it !is AuthState.Migrating) return@update it + it.copy(useBiometrics = event.checked) } } } } private fun createPasswordOrBiometricAccess( - authState: AuthState.BiometricAuthState, + authState: AuthState.Migrating, password: String ) { if (!authState.biometricsAvailable || !authState.useBiometrics) { diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt deleted file mode 100644 index bd8657b24..000000000 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthEvent.kt +++ /dev/null @@ -1,8 +0,0 @@ -package de.davis.keygo.feature.auth.presentation.model - -internal sealed interface AuthEvent { - - data object Success : AuthEvent - data object Failure : AuthEvent - data object None : AuthEvent -} \ No newline at end of file diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt index 0e582c34e..330a32306 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/model/AuthState.kt @@ -1,7 +1,6 @@ package de.davis.keygo.feature.auth.presentation.model import androidx.compose.foundation.text.input.TextFieldState -import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.ui.model.UiFieldError sealed interface AuthState { @@ -24,12 +23,6 @@ sealed interface AuthState { passwordError = passwordError, ) - is CreateAccess -> copy( - loading = loading, - passwordTextFieldState = passwordTextFieldState, - passwordError = passwordError, - ) - is Migrating -> copy( loading = loading, passwordTextFieldState = passwordTextFieldState, @@ -45,44 +38,12 @@ sealed interface AuthState { val biometricAuthenticationAvailable: Boolean = false, ) : Interactable - - sealed interface BiometricAuthState : Interactable { - val biometricsAvailable: Boolean - val useBiometrics: Boolean - - fun copyBiometricState( - biometricsAvailable: Boolean = this.biometricsAvailable, - useBiometrics: Boolean = this.useBiometrics, - ): BiometricAuthState = when (this) { - is CreateAccess -> copy( - biometricsAvailable = biometricsAvailable, - useBiometrics = useBiometrics - ) - - is Migrating -> copy( - biometricsAvailable = biometricsAvailable, - useBiometrics = useBiometrics - ) - } - } - data class Migrating( override val passwordTextFieldState: TextFieldState, override val passwordError: UiFieldError? = null, override val loading: Boolean = false, - override val biometricsAvailable: Boolean = false, - override val useBiometrics: Boolean = true, + val biometricsAvailable: Boolean = false, + val useBiometrics: Boolean = true, val showMigrationDialog: Boolean = true - ) : BiometricAuthState - - data class CreateAccess( - override val passwordTextFieldState: TextFieldState, - override val passwordError: UiFieldError? = null, - override val loading: Boolean = false, - override val biometricsAvailable: Boolean = false, - override val useBiometrics: Boolean = true, - val confirmPasswordTextFieldState: TextFieldState = TextFieldState(), - val confirmPasswordError: UiFieldError? = null, - val passwordScore: PasswordScore = PasswordScore.None, - ) : BiometricAuthState + ) : Interactable } diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index 687370e04..aec695224 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -238,7 +238,7 @@ private val OnboardingUiState.buttonText: String @Composable get() = stringResource( when (this) { - is OnboardingUiState.Welcome -> if (migrating) R.string.migrate else R.string.get_started + is OnboardingUiState.Welcome -> R.string.get_started is OnboardingUiState.SetMainPassword -> R.string.continue_text OnboardingUiState.EnableBiometrics -> R.string.enable_biometrics is OnboardingUiState.ImportData -> R.string.skip_for_now @@ -271,7 +271,7 @@ private fun OnboardingUiState.isOutlinedButonCandidate() = this is OnboardingUiS private fun OnboardingStepsPreview() { MaterialTheme { OnboardingSteps( - state = OnboardingUiState.Welcome(), + state = OnboardingUiState.Welcome, loading = false, onNextStep = {}, onSkip = {}, diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index ad891aa3a..a0c982888 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -4,7 +4,6 @@ import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope -import de.davis.keygo.core.identity.domain.repository.AccountRepository import de.davis.keygo.core.identity.domain.usecase.CreateAccessUseCase import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository @@ -16,7 +15,6 @@ import de.davis.keygo.feature.backup.domain.model.BackupDestinationUri import de.davis.keygo.feature.onboarding.presentation.model.AutofillSetupAction import de.davis.keygo.feature.onboarding.presentation.model.OnboardingStep import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState -import de.davis.keygo.migration.create_access.domain.usecase.HasMainPasswordUseCase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview @@ -28,6 +26,7 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.receiveAsFlow @@ -41,8 +40,6 @@ import kotlin.time.Duration.Companion.milliseconds @KoinViewModel internal class OnboardingViewModel( private val biometricAvailabilityRepository: BiometricAvailabilityRepository, - private val hasV1Password: HasMainPasswordUseCase, - private val accountRepository: AccountRepository, private val autofillServiceRepository: AutofillServiceRepository, private val chromeAutofillRepository: ChromeAutofillRepository, @@ -51,25 +48,20 @@ internal class OnboardingViewModel( ) : ViewModel() { private val stepsToSkip = MutableStateFlow>(emptySet()) - private val isMigrating = MutableStateFlow(false) private fun calculateStepsToSkip() { viewModelScope.launch { - val hasAccount = accountRepository.getOrNull() != null - val hasLegacyPassword = hasV1Password() val autofill = readAutofillState() _enableAutofillState.update { autofill } val skipSteps = buildSet { if (!biometricAvailabilityRepository.availability()) add(OnboardingStep.EnableBiometrics) - if (hasAccount || hasLegacyPassword) add(OnboardingStep.ImportExistingData) // Not "both enabled": on a device with no Chrome the Chrome read is false forever, // which would keep offering a step that has nothing left to do. if (autofill.nextAction == AutofillSetupAction.Finish) add(OnboardingStep.EnableAutofillService) } stepsToSkip.update { skipSteps } - isMigrating.update { hasLegacyPassword && !hasAccount } } } @@ -112,7 +104,7 @@ internal class OnboardingViewModel( calculateStepsToSkip() } - private val biometricChannel = Channel() + private val biometricChannel = Channel(Channel.BUFFERED) val biometricFlow = biometricChannel.receiveAsFlow() private val autofillPickerChannel = Channel(Channel.BUFFERED) @@ -159,9 +151,7 @@ internal class OnboardingViewModel( @OptIn(ExperimentalCoroutinesApi::class) val state = _step.flatMapLatest { when (it) { - OnboardingStep.Welcome -> isMigrating.mapLatest { migrating -> - OnboardingUiState.Welcome(migrating) - } + OnboardingStep.Welcome -> flowOf(OnboardingUiState.Welcome) OnboardingStep.SetMainPassword -> _mainPasswordState OnboardingStep.EnableBiometrics -> _enableBiometricsState @@ -171,7 +161,7 @@ internal class OnboardingViewModel( }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), - initialValue = OnboardingUiState.Welcome() + initialValue = OnboardingUiState.Welcome ) fun onNextStep() { @@ -190,7 +180,7 @@ internal class OnboardingViewModel( return } - if (OnboardingStep.EnableBiometrics in stepsToSkip.value) performCreateAccess() + if (OnboardingStep.EnableBiometrics in stepsToSkip.value) return performCreateAccess() } OnboardingStep.EnableBiometrics -> { @@ -264,7 +254,9 @@ internal class OnboardingViewModel( private suspend fun loading(block: suspend () -> R): R { _loading.update { true } - return block().also { + try { + return block() + } finally { _loading.update { false } } } diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt index 3ba6f4956..688bd055d 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt @@ -9,6 +9,7 @@ internal enum class OnboardingStep { fun nextStep(skip: Set): OnboardingStep? { val pool = OnboardingStep.entries.filterNot { it in skip } - return pool.getOrNull(pool.indexOf(this) + 1) + val currentIndex = pool.indexOf(this) + return if (currentIndex != -1) pool.getOrNull(currentIndex + 1) else null } } \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt index 7c435ebd5..fc078b307 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt @@ -7,7 +7,7 @@ import de.davis.keygo.feature.backup.domain.model.BackupDestinationUri internal sealed interface OnboardingUiState { - data class Welcome(val migrating: Boolean = false) : OnboardingUiState + data object Welcome : OnboardingUiState data class SetMainPassword( val passwordTextFieldState: TextFieldState, diff --git a/feature/onboarding/src/main/res/values/strings.xml b/feature/onboarding/src/main/res/values/strings.xml index 488f88125..374d9ec86 100644 --- a/feature/onboarding/src/main/res/values/strings.xml +++ b/feature/onboarding/src/main/res/values/strings.xml @@ -1,7 +1,6 @@ Get Started - Migrate Continue Skip for now Enable Biometrics diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index e9115ff64..087fe20df 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -42,6 +42,7 @@ robolectric = "4.16.1" emvnfccard = "3.1.0" aboutlibraries = "14.2.1" work = "2.11.2" +splashscreen = "1.2.0" [libraries] google-protobuf-protoc = { group = "com.google.protobuf", name = "protoc", version.ref = "protoc" } @@ -52,6 +53,7 @@ kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-cor kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" } kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinSerializationJson" } kotlinx-collections-immutable = { group = "org.jetbrains.kotlinx", name = "kotlinx-collections-immutable", version.ref = "collectionsImmutable" } +androidx-core-splashscreen = { group = "androidx.core", name = "core-splashscreen", version.ref = "splashscreen" } androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } From 0da69e87c46efd88a875b82d54fdbad7576d7ead Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Mon, 10 Aug 2026 21:41:46 +0200 Subject: [PATCH 15/24] chore: ignore .worktrees/ directory --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 7616e4628..23ac73ffc 100644 --- a/.gitignore +++ b/.gitignore @@ -186,6 +186,7 @@ google-services.json docs/superpowers/ .superpowers/ .claude/ +.worktrees/ graphify-out/ .gitattributes \ No newline at end of file From 1a214d7e2a4631610a23504031621c19d8d5e16e Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Mon, 10 Aug 2026 21:48:12 +0200 Subject: [PATCH 16/24] refactor(totp): outsource deep link --- app/build.gradle.kts | 4 + .../keygo/app/presentation/MainActivity.kt | 17 ++- .../app/presentation/TotpImportRedirect.kt | 42 ++++++ .../presentation/TotpImportNavGraphTest.kt | 120 ++++++++++++++++++ core/ui/build.gradle.kts | 1 + .../keygo/core/ui/model/PendingTotpImport.kt | 19 +++ .../core/ui/model/PendingTotpImportTest.kt | 49 +++++++ .../feature/auth/presentation/AuthContent.kt | 21 ++- .../feature/auth/presentation/AuthGraph.kt | 11 +- .../feature/auth/presentation/AuthScreen.kt | 6 +- .../auth/presentation/AuthViewModel.kt | 2 + .../auth/presentation/RouteDestination.kt | 19 ++- feature/auth/src/main/res/values/strings.xml | 1 + .../presentation/OnboardingGraph.kt | 26 ++-- .../presentation/OnboardingScreen.kt | 2 +- .../presentation/OnboardingViewModel.kt | 9 +- .../onboarding/presentation/WelcomeContent.kt | 4 +- .../presentation/model/OnboardingUiState.kt | 2 +- .../src/main/res/values/strings.xml | 4 +- gradle/libs.versions.toml | 1 + 20 files changed, 316 insertions(+), 44 deletions(-) create mode 100644 app/src/main/kotlin/de/davis/keygo/app/presentation/TotpImportRedirect.kt create mode 100644 app/src/test/kotlin/de/davis/keygo/app/presentation/TotpImportNavGraphTest.kt create mode 100644 core/ui/src/main/kotlin/de/davis/keygo/core/ui/model/PendingTotpImport.kt create mode 100644 core/ui/src/test/kotlin/de/davis/keygo/core/ui/model/PendingTotpImportTest.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 0cdb936dd..ffb70bed1 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -136,6 +136,10 @@ dependencies { implementation(libs.androidx.navigation.compose) testImplementation(libs.kotlin.test) + testImplementation(libs.androidx.navigation.testing) + testImplementation(libs.robolectric) + testImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.espresso.core) androidTestImplementation(platform(libs.androidx.compose.bom)) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt index a271a09de..0abc889a5 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt @@ -74,9 +74,7 @@ class MainActivity : FragmentActivity() { CompositionLocalProvider( LocalSnackbarManager provides snackbarManager, ) { - App( - startDestinations = if (hasAccess == true) AuthRoute() else OnboardingRoute() - ) + App(hasAccess = hasAccess == true) } } } @@ -85,7 +83,7 @@ class MainActivity : FragmentActivity() { @OptIn(ExperimentalMaterial3AdaptiveApi::class) @Composable -private fun App(startDestinations: Any) { +private fun App(hasAccess: Boolean) { val listNavigator = rememberListDetailPaneScaffoldNavigator() val navController = rememberNavController() @@ -139,8 +137,17 @@ private fun App(startDestinations: Any) { ) { NavHost( navController = navController, - startDestination = startDestinations, + startDestination = if (hasAccess) AuthRoute() else OnboardingRoute(), ) { + totpImportRedirectGraph( + hasAccess = hasAccess, + navigateAndReplace = { dest -> + navController.navigate(dest) { + popUpTo { inclusive = true } + } + } + ) + authGraph( onSuccess = { totpUri -> val dest = totpUri?.let { diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/TotpImportRedirect.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/TotpImportRedirect.kt new file mode 100644 index 000000000..60a420298 --- /dev/null +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/TotpImportRedirect.kt @@ -0,0 +1,42 @@ +package de.davis.keygo.app.presentation + +import androidx.compose.runtime.LaunchedEffect +import androidx.navigation.NavGraphBuilder +import androidx.navigation.compose.composable +import androidx.navigation.navDeepLink +import androidx.navigation.toRoute +import de.davis.keygo.core.ui.RouteDestination +import de.davis.keygo.core.ui.model.PendingTotpImport +import de.davis.keygo.feature.auth.presentation.AuthRoute +import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute +import kotlinx.serialization.Serializable + +@Serializable +data class TotpImportRedirect( + val totpInfo: String? = null, + val queries: String? = null, +) : RouteDestination { + val pendingImport: PendingTotpImport + get() = PendingTotpImport(totpInfo, queries) +} + +fun NavGraphBuilder.totpImportRedirectGraph( + hasAccess: Boolean, + navigateAndReplace: (Any) -> Unit, +) { + composable( + deepLinks = listOf( + navDeepLink(basePath = PendingTotpImport.BASE_PATH) { + uriPattern = PendingTotpImport.URI_PATTERN + } + ) + ) { entry -> + val route = entry.toRoute() + LaunchedEffect(route) { + navigateAndReplace( + if (hasAccess) AuthRoute(totpInfo = route.totpInfo, queries = route.queries) + else OnboardingRoute(totpInfo = route.totpInfo, queries = route.queries) + ) + } + } +} diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/TotpImportNavGraphTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/TotpImportNavGraphTest.kt new file mode 100644 index 000000000..b6c381712 --- /dev/null +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/TotpImportNavGraphTest.kt @@ -0,0 +1,120 @@ +package de.davis.keygo.app.presentation + +import androidx.core.net.toUri +import androidx.navigation.NavDestination.Companion.hasRoute +import androidx.navigation.compose.ComposeNavigator +import androidx.navigation.compose.DialogNavigator +import androidx.navigation.createGraph +import androidx.navigation.testing.TestNavHostController +import androidx.navigation.toRoute +import androidx.test.core.app.ApplicationProvider +import de.davis.keygo.core.ui.model.PendingTotpImport +import de.davis.keygo.feature.auth.presentation.AuthRoute +import de.davis.keygo.feature.auth.presentation.authGraph +import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute +import de.davis.keygo.feature.onboarding.presentation.onboardingGraph +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class TotpImportNavGraphTest { + + private fun navController(hasAccess: Boolean): TestNavHostController { + val controller = + TestNavHostController(ApplicationProvider.getApplicationContext()) + controller.navigatorProvider.addNavigator(ComposeNavigator()) + controller.navigatorProvider.addNavigator(DialogNavigator()) + + controller.graph = controller.createGraph( + startDestination = if (hasAccess) AuthRoute() else OnboardingRoute(), + ) { + totpImportRedirectGraph(hasAccess = hasAccess, navigateAndReplace = {}) + authGraph(onSuccess = {}) + onboardingGraph(onSuccess = {}) + } + + return controller + } + + @Test + fun `graph builds for an account that already has access`() { + val controller = navController(hasAccess = true) + + assertTrue(controller.currentDestination?.hasRoute() == true) + } + + @Test + fun `graph builds for an account without access`() { + val controller = navController(hasAccess = false) + + assertTrue(controller.currentDestination?.hasRoute() == true) + } + + @Test + fun `otpauth deep link resolves to the redirect destination`() { + val controller = navController(hasAccess = true) + + controller.navigate("otpauth://totp/Example:me@example.com?secret=ABC".toUri()) + + val entry = assertNotNull(controller.currentBackStackEntry) + assertTrue(entry.destination.hasRoute()) + + val route = entry.toRoute() + assertEquals("Example:me@example.com", route.totpInfo) + assertEquals("secret=ABC", route.queries) + assertEquals( + "otpauth://totp/Example:me@example.com?secret=ABC", + route.pendingImport.uri, + ) + } + + @Test + fun `AuthRoute round trips the pending import through the back stack`() { + val controller = navController(hasAccess = true) + val redirect = TotpImportRedirect( + totpInfo = "Example:me@example.com", + queries = "secret=ABC", + ) + + controller.navigate( + AuthRoute(totpInfo = redirect.totpInfo, queries = redirect.queries), + ) + + val route = assertNotNull(controller.currentBackStackEntry).toRoute() + assertEquals(redirect.pendingImport, route.pendingTotpImport) + assertEquals("otpauth://totp/Example:me@example.com?secret=ABC", route.uri) + } + + @Test + fun `OnboardingRoute round trips the pending import through the back stack`() { + val controller = navController(hasAccess = false) + val redirect = TotpImportRedirect( + totpInfo = "Example:me@example.com", + queries = "secret=ABC", + ) + + controller.navigate( + OnboardingRoute(totpInfo = redirect.totpInfo, queries = redirect.queries), + ) + + val route = assertNotNull(controller.currentBackStackEntry).toRoute() + assertEquals(redirect.pendingImport, route.pendingTotpImport) + assertEquals("otpauth://totp/Example:me@example.com?secret=ABC", route.uri) + } + + @Test + fun `a plain launch carries no pending import`() { + val controller = navController(hasAccess = true) + + val route = assertNotNull(controller.currentBackStackEntry).toRoute() + assertEquals(PendingTotpImport(), route.pendingTotpImport) + assertNull(route.uri) + } +} diff --git a/core/ui/build.gradle.kts b/core/ui/build.gradle.kts index 01c33859b..7dddcfd3e 100644 --- a/core/ui/build.gradle.kts +++ b/core/ui/build.gradle.kts @@ -1,5 +1,6 @@ plugins { alias(libs.plugins.keygo.android.compose) + alias(libs.plugins.kotlin.serialization) } android { diff --git a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/model/PendingTotpImport.kt b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/model/PendingTotpImport.kt new file mode 100644 index 000000000..ef2a1d156 --- /dev/null +++ b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/model/PendingTotpImport.kt @@ -0,0 +1,19 @@ +package de.davis.keygo.core.ui.model + +import kotlinx.serialization.Serializable + +@Serializable +data class PendingTotpImport( + val totpInfo: String? = null, + val queries: String? = null, +) { + val uri: String? + get() = if (!totpInfo.isNullOrBlank() && !queries.isNullOrBlank()) + "otpauth://totp/$totpInfo?$queries" + else null + + companion object { + const val BASE_PATH = "otpauth://totp" + const val URI_PATTERN = "otpauth://totp/{totpInfo}?{queries}" + } +} diff --git a/core/ui/src/test/kotlin/de/davis/keygo/core/ui/model/PendingTotpImportTest.kt b/core/ui/src/test/kotlin/de/davis/keygo/core/ui/model/PendingTotpImportTest.kt new file mode 100644 index 000000000..a35a443c8 --- /dev/null +++ b/core/ui/src/test/kotlin/de/davis/keygo/core/ui/model/PendingTotpImportTest.kt @@ -0,0 +1,49 @@ +package de.davis.keygo.core.ui.model + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class PendingTotpImportTest { + + @Test + fun `uri rebuilds the full otpauth string when both parts are present`() { + val pending = PendingTotpImport( + totpInfo = "Example:me@example.com", + queries = "secret=JBSWY3DPEHPK3PXP&issuer=Example", + ) + assertEquals( + "otpauth://totp/Example:me@example.com?secret=JBSWY3DPEHPK3PXP&issuer=Example", + pending.uri, + ) + } + + @Test + fun `uri is null when totpInfo is missing`() { + val pending = PendingTotpImport(totpInfo = null, queries = "secret=ABC") + assertNull(pending.uri) + } + + @Test + fun `uri is null when queries is missing`() { + val pending = PendingTotpImport(totpInfo = "Example:me@example.com", queries = null) + assertNull(pending.uri) + } + + @Test + fun `uri is null when totpInfo is blank`() { + val pending = PendingTotpImport(totpInfo = " ", queries = "secret=ABC") + assertNull(pending.uri) + } + + @Test + fun `uri is null when queries is blank`() { + val pending = PendingTotpImport(totpInfo = "Example:me@example.com", queries = " ") + assertNull(pending.uri) + } + + @Test + fun `default construction has no pending uri`() { + assertNull(PendingTotpImport().uri) + } +} diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt index 50bb2b927..07191375c 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt @@ -58,7 +58,11 @@ import de.davis.keygo.core.item.R as CoreItemR @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -fun AuthContent(state: AuthState, onEvent: (AuthUIEvent) -> Unit) { +fun AuthContent( + state: AuthState, + onEvent: (AuthUIEvent) -> Unit, + hasPendingTotpImport: Boolean = false, +) { when (state) { is AuthState.Loading -> { Surface(modifier = Modifier.fillMaxSize()) { @@ -71,7 +75,11 @@ fun AuthContent(state: AuthState, onEvent: (AuthUIEvent) -> Unit) { } } - is AuthState.Interactable -> InteractableAuthContent(state = state, onEvent = onEvent) + is AuthState.Interactable -> InteractableAuthContent( + state = state, + onEvent = onEvent, + hasPendingTotpImport = hasPendingTotpImport, + ) } } @@ -80,6 +88,7 @@ fun AuthContent(state: AuthState, onEvent: (AuthUIEvent) -> Unit) { private fun InteractableAuthContent( state: AuthState.Interactable, onEvent: (AuthUIEvent) -> Unit, + hasPendingTotpImport: Boolean, ) { Surface(modifier = Modifier.fillMaxSize()) { Box( @@ -120,6 +129,14 @@ private fun InteractableAuthContent( textAlign = TextAlign.Center, ) + if (hasPendingTotpImport) + Text( + text = stringResource(R.string.pending_totp_import_subtitle), + modifier = Modifier.fillMaxWidth(), + textAlign = TextAlign.Center, + style = MaterialTheme.typography.bodyMedium, + ) + with(state) { var passwordHidden by rememberSaveable { mutableStateOf(true) } OutlinedSecureTextField( diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthGraph.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthGraph.kt index 6324e1535..ab34ab9e7 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthGraph.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthGraph.kt @@ -2,21 +2,14 @@ package de.davis.keygo.feature.auth.presentation import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable -import androidx.navigation.navDeepLink import androidx.navigation.toRoute fun NavGraphBuilder.authGraph(onSuccess: (String?) -> Unit) { - composable( - deepLinks = listOf( - navDeepLink(basePath = "otpauth://totp") { - uriPattern = "otpauth://totp/{totpInfo}?{queries}" - } - ) - ) { s -> + composable { s -> AuthScreen( onSuccess = { onSuccess(s.toRoute().uri) } ) } -} \ No newline at end of file +} diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt index 80ad7dcb9..33ce451fb 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt @@ -53,5 +53,9 @@ fun AuthScreen(onSuccess: () -> Unit) { } } - AuthContent(state = state, onEvent = viewModel::onEvent) + AuthContent( + state = state, + onEvent = viewModel::onEvent, + hasPendingTotpImport = viewModel.hasPendingTotpImport, + ) } \ No newline at end of file diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt index eaad0a14b..a143ac542 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt @@ -49,6 +49,8 @@ internal class AuthViewModel( private val authRoute = savedStateHandle.toRoute() + val hasPendingTotpImport: Boolean = authRoute.uri != null + private val passwordTextFieldState = TextFieldState() private val _uiState = MutableStateFlow(AuthState.Loading) diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/RouteDestination.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/RouteDestination.kt index 1f07323ac..ea6e84bbf 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/RouteDestination.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/RouteDestination.kt @@ -1,16 +1,23 @@ package de.davis.keygo.feature.auth.presentation import de.davis.keygo.core.ui.RouteDestination +import de.davis.keygo.core.ui.model.PendingTotpImport import kotlinx.serialization.Serializable +/** + * The pending import travels as primitives, not as a [PendingTotpImport] field. Type-safe + * navigation has no [androidx.navigation.NavType] for a custom class unless one is supplied + * through a typeMap, and building the graph without it throws while the graph is created. + */ @Serializable data class AuthRoute( val totpInfo: String? = null, val queries: String? = null, - val showBiometricPromptIfPossible: Boolean = true + val showBiometricPromptIfPossible: Boolean = true, ) : RouteDestination { - val uri - get() = if (!totpInfo.isNullOrBlank() && !queries.isNullOrBlank()) - "otpauth://totp/$totpInfo?$queries" - else null -} \ No newline at end of file + val pendingTotpImport: PendingTotpImport + get() = PendingTotpImport(totpInfo, queries) + + val uri: String? + get() = pendingTotpImport.uri +} diff --git a/feature/auth/src/main/res/values/strings.xml b/feature/auth/src/main/res/values/strings.xml index e731ab442..e795c0efd 100644 --- a/feature/auth/src/main/res/values/strings.xml +++ b/feature/auth/src/main/res/values/strings.xml @@ -17,4 +17,5 @@ To ensure the integrity of your data, please migrate your access credentials. You will be prompted to enter your master password. Request biometric authentication + Unlock your vault to add this authenticator code. \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingGraph.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingGraph.kt index 391df6771..70843faeb 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingGraph.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingGraph.kt @@ -2,20 +2,14 @@ package de.davis.keygo.feature.onboarding.presentation import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable -import androidx.navigation.navDeepLink import androidx.navigation.toRoute import de.davis.keygo.core.ui.RouteDestination +import de.davis.keygo.core.ui.model.PendingTotpImport import kotlinx.serialization.Serializable fun NavGraphBuilder.onboardingGraph(onSuccess: (String?) -> Unit) { - composable( - deepLinks = listOf( - navDeepLink(basePath = "otpauth://totp") { - uriPattern = "otpauth://totp/{totpInfo}?{queries}" - } - ) - ) { s -> + composable { s -> OnboardingScreen( onSuccess = { onSuccess(s.toRoute().uri) @@ -24,13 +18,19 @@ fun NavGraphBuilder.onboardingGraph(onSuccess: (String?) -> Unit) { } } +/** + * The pending import travels as primitives, not as a [PendingTotpImport] field. Type-safe + * navigation has no [androidx.navigation.NavType] for a custom class unless one is supplied + * through a typeMap, and building the graph without it throws while the graph is created. + */ @Serializable data class OnboardingRoute( val totpInfo: String? = null, val queries: String? = null, ) : RouteDestination { - val uri - get() = if (!totpInfo.isNullOrBlank() && !queries.isNullOrBlank()) - "otpauth://totp/$totpInfo?$queries" - else null -} \ No newline at end of file + val pendingTotpImport: PendingTotpImport + get() = PendingTotpImport(totpInfo, queries) + + val uri: String? + get() = pendingTotpImport.uri +} diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index aec695224..8eaa486d0 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -271,7 +271,7 @@ private fun OnboardingUiState.isOutlinedButonCandidate() = this is OnboardingUiS private fun OnboardingStepsPreview() { MaterialTheme { OnboardingSteps( - state = OnboardingUiState.Welcome, + state = OnboardingUiState.Welcome(), loading = false, onNextStep = {}, onSkip = {}, diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index a0c982888..849f55b4f 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -2,8 +2,10 @@ package de.davis.keygo.feature.onboarding.presentation import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.runtime.snapshotFlow +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import androidx.navigation.toRoute import de.davis.keygo.core.identity.domain.usecase.CreateAccessUseCase import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository @@ -39,6 +41,7 @@ import kotlin.time.Duration.Companion.milliseconds @KoinViewModel internal class OnboardingViewModel( + savedStateHandle: SavedStateHandle, private val biometricAvailabilityRepository: BiometricAvailabilityRepository, private val autofillServiceRepository: AutofillServiceRepository, private val chromeAutofillRepository: ChromeAutofillRepository, @@ -47,6 +50,8 @@ internal class OnboardingViewModel( private val createAccess: CreateAccessUseCase, ) : ViewModel() { + private val hasPendingTotpImport = savedStateHandle.toRoute().uri != null + private val stepsToSkip = MutableStateFlow>(emptySet()) private fun calculateStepsToSkip() { @@ -151,7 +156,7 @@ internal class OnboardingViewModel( @OptIn(ExperimentalCoroutinesApi::class) val state = _step.flatMapLatest { when (it) { - OnboardingStep.Welcome -> flowOf(OnboardingUiState.Welcome) + OnboardingStep.Welcome -> flowOf(OnboardingUiState.Welcome(pendingTotpImport = hasPendingTotpImport)) OnboardingStep.SetMainPassword -> _mainPasswordState OnboardingStep.EnableBiometrics -> _enableBiometricsState @@ -161,7 +166,7 @@ internal class OnboardingViewModel( }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), - initialValue = OnboardingUiState.Welcome + initialValue = OnboardingUiState.Welcome() ) fun onNextStep() { diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt index 8f69759c1..d08fb5e1e 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt @@ -35,8 +35,8 @@ internal fun WelcomeContent(state: OnboardingUiState.Welcome, onContinue: () -> ) } }, - title = stringResource(if (state.migrating) R.string.welcome_migrating_title else R.string.welcome_title), - description = stringResource(if (state.migrating) R.string.welcome_migrating_subtitle else R.string.welcome_subtitle), + title = stringResource(if (state.pendingTotpImport) R.string.welcome_totp_import_title else R.string.welcome_title), + description = stringResource(if (state.pendingTotpImport) R.string.welcome_totp_import_subtitle else R.string.welcome_subtitle), contentHorizontalAlignment = Alignment.CenterHorizontally ) { // No content for Welcome diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt index fc078b307..c551a33ff 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt @@ -7,7 +7,7 @@ import de.davis.keygo.feature.backup.domain.model.BackupDestinationUri internal sealed interface OnboardingUiState { - data object Welcome : OnboardingUiState + data class Welcome(val pendingTotpImport: Boolean = false) : OnboardingUiState data class SetMainPassword( val passwordTextFieldState: TextFieldState, diff --git a/feature/onboarding/src/main/res/values/strings.xml b/feature/onboarding/src/main/res/values/strings.xml index 374d9ec86..fa635dc76 100644 --- a/feature/onboarding/src/main/res/values/strings.xml +++ b/feature/onboarding/src/main/res/values/strings.xml @@ -9,8 +9,8 @@ Own your credentials, own your privacy. KeyGo encrypts everything locally. No servers, no cloud, no tracking. Just you and your data. - Welcome back. - You already have a KeyGo vault on this device. Let\'s finish setting up your account. + One more step to add your code + Complete your account setup to have this authenticator code added. Set your main password This password will encrypt your vaults. KeyGo never stores this password. Make it secure. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 087fe20df..ddee4dd9f 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -73,6 +73,7 @@ androidx-material3 = { group = "androidx.compose.material3", name = "material3", androidx-material3-adaptive-navigation = { group = "androidx.compose.material3.adaptive", name = "adaptive-navigation" } androidx-material3-adaptive-navigation-suite = { group = "androidx.compose.material3", name = "material3-adaptive-navigation-suite" } androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigation" } +androidx-navigation-testing = { group = "androidx.navigation", name = "navigation-testing", version.ref = "navigation" } androidx-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" } androidx-biometric = { group = "androidx.biometric", name = "biometric", version.ref = "biometric" } From c876dd93d86af0f6de8050a1b92dc749ec62a1a0 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Mon, 10 Aug 2026 23:18:17 +0200 Subject: [PATCH 17/24] refactor(onboarding): cleanup --- .../feature/onboarding/presentation/OnboardingScreen.kt | 5 +---- .../keygo/feature/onboarding/presentation/WelcomeContent.kt | 5 ++--- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index 8eaa486d0..1eb4e59c3 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -204,10 +204,7 @@ private fun OnboardingSteps( modifier = Modifier.widthIn(max = OnboardingMaxWidth), ) { state -> when (state) { - is OnboardingUiState.Welcome -> WelcomeContent( - state = state, - onContinue = onNextStep - ) + is OnboardingUiState.Welcome -> WelcomeContent(state = state) is OnboardingUiState.SetMainPassword -> MainPasswordContent(state = state) diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt index d08fb5e1e..60544754b 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt @@ -23,7 +23,7 @@ import de.davis.keygo.core.ui.R as CoreUiR @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable -internal fun WelcomeContent(state: OnboardingUiState.Welcome, onContinue: () -> Unit) { +internal fun WelcomeContent(state: OnboardingUiState.Welcome) { OnboardingScaffold( iconContainer = { LargeIconContainer( @@ -51,8 +51,7 @@ private fun WelcomeContentPreview() { SharedTransitionLayout { AnimatedVisibility(visible = true) { WelcomeContent( - state = OnboardingUiState.Welcome(), - onContinue = {} + state = OnboardingUiState.Welcome() ) } } From ec640e739fa1c715213d350841bf6a871cdd3d28 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Tue, 11 Aug 2026 01:53:26 +0200 Subject: [PATCH 18/24] fix: navigate user to auth if migration is possible --- .../de/davis/keygo/app/presentation/AppViewModel.kt | 10 ++++++---- .../de/davis/keygo/app/presentation/MainActivity.kt | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt index d51b6f94f..add7fd8e3 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt @@ -3,6 +3,7 @@ package de.davis.keygo.app.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import de.davis.keygo.core.identity.domain.repository.AccountRepository +import de.davis.keygo.migration.create_access.domain.usecase.HasMainPasswordUseCase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update @@ -11,15 +12,16 @@ import org.koin.core.annotation.KoinViewModel @KoinViewModel internal class AppViewModel( - private val accountRepository: AccountRepository + private val accountRepository: AccountRepository, + private val hasV1Password: HasMainPasswordUseCase, ) : ViewModel() { - private val _hasAccess = MutableStateFlow(null) - val hasAccess = _hasAccess.asStateFlow() + private val _isReturningUser = MutableStateFlow(null) + val isReturningUser = _isReturningUser.asStateFlow() init { viewModelScope.launch { - _hasAccess.update { accountRepository.getOrNull() != null } + _isReturningUser.update { accountRepository.getOrNull() != null || hasV1Password() } } } } \ No newline at end of file diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt index 0abc889a5..86b01ee38 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt @@ -61,12 +61,12 @@ class MainActivity : FragmentActivity() { super.onCreate(savedInstanceState) splashScreen.setKeepOnScreenCondition { - viewModel.hasAccess.value == null + viewModel.isReturningUser.value == null } enableEdgeToEdge() setContent { - val hasAccess by viewModel.hasAccess.collectAsState() + val hasAccess by viewModel.isReturningUser.collectAsState() hasAccess ?: return@setContent KeyGoTheme { From f379b2291038794f1db957d2dee90dd955de684f Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Tue, 11 Aug 2026 03:03:13 +0200 Subject: [PATCH 19/24] fix: auto biometric prompt --- .../de/davis/keygo/feature/auth/presentation/AuthViewModel.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt index a143ac542..4ddb3de11 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt @@ -44,7 +44,7 @@ internal class AuthViewModel( private val unlockWithPassword: UnlockWithPasswordUseCase, private val createAllAccesses: CreateAccessUseCase, ) : ViewModel() { - private val biometricChannel = Channel() + private val biometricChannel = Channel(Channel.BUFFERED) val biometricFlow = biometricChannel.receiveAsFlow() private val authRoute = savedStateHandle.toRoute() From 646bcc71c3dfde8aac35d9c0df2d7bc3bc3ca5ac Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Tue, 11 Aug 2026 20:54:40 +0200 Subject: [PATCH 20/24] feat(onboarding): add indicator --- .../presentation/OnboardingScreen.kt | 84 +++++++++++++++++++ .../presentation/OnboardingViewModel.kt | 31 +++++++ .../presentation/model/OnboardingStep.kt | 17 +++- .../model/OnboardingStepProgress.kt | 7 ++ .../presentation/model/OnboardingStepTest.kt | 56 +++++++++++++ 5 files changed, 194 insertions(+), 1 deletion(-) create mode 100644 feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepProgress.kt diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index 1eb4e59c3..d1a09a3e3 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -4,36 +4,54 @@ import android.content.ActivityNotFoundException import android.content.Intent import android.provider.Settings import android.util.Log +import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.expandHorizontally +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkHorizontally +import androidx.compose.foundation.background 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.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.BasicAlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ContainedLoadingIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.tooling.preview.PreviewScreenSizes +import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.core.net.toUri import androidx.lifecycle.compose.LifecycleResumeEffect @@ -48,6 +66,7 @@ import de.davis.keygo.feature.backup.presentation.import.ImportWizardScreen import de.davis.keygo.feature.backup.presentation.import.rememberImportFilePicker import de.davis.keygo.feature.onboarding.R import de.davis.keygo.feature.onboarding.presentation.model.AutofillSetupAction +import de.davis.keygo.feature.onboarding.presentation.model.OnboardingStepProgress import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState import org.koin.androidx.compose.koinViewModel @@ -59,9 +78,14 @@ private val OnboardingMaxWidth = 480.dp fun OnboardingScreen(onSuccess: () -> Unit) { val viewModel = koinViewModel() val state by viewModel.state.collectAsStateWithLifecycle() + val stepProgress by viewModel.stepProgress.collectAsStateWithLifecycle() val loading by viewModel.loading.collectAsStateWithLifecycle() + BackHandler(enabled = stepProgress.canGoBack) { + viewModel.onPreviousStep() + } + val biometricCryptoController = rememberBiometricCryptoController() ObserveAsEvents(viewModel.biometricFlow) { biometricCryptoController.requestCipher( @@ -120,8 +144,10 @@ fun OnboardingScreen(onSuccess: () -> Unit) { ) else OnboardingSteps( state = state, + stepProgress = stepProgress, loading = loading, onNextStep = viewModel::onNextStep, + onPreviousStep = viewModel::onPreviousStep, onSkip = viewModel::onSkip, onChooseImportFile = chooseImportFile::launch, ) @@ -131,8 +157,10 @@ fun OnboardingScreen(onSuccess: () -> Unit) { @Composable private fun OnboardingSteps( state: OnboardingUiState, + stepProgress: OnboardingStepProgress, loading: Boolean, onNextStep: () -> Unit, + onPreviousStep: () -> Unit, onSkip: () -> Unit, onChooseImportFile: () -> Unit, ) { @@ -141,6 +169,56 @@ private fun OnboardingSteps( modifier = Modifier .fillMaxSize() .padding(16.dp), + topBar = { + TopAppBar( + title = { + Row( + modifier = Modifier, + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + repeat(stepProgress.totalSteps) { index -> + val color by animateColorAsState( + targetValue = if (index <= stepProgress.currentIndex) + MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.primaryContainer, + label = "onboarding_step_indicator", + ) + Box( + modifier = Modifier + .height(8.dp) + .weight(1f) + .clip(CircleShape) + .background(color), + ) + } + } + }, + navigationIcon = { + val effectsSpec = MaterialTheme.motionScheme.defaultEffectsSpec() + val spatialSpec = MaterialTheme.motionScheme.defaultSpatialSpec() + AnimatedVisibility( + visible = stepProgress.canGoBack, + exit = fadeOut(effectsSpec) + shrinkHorizontally( + animationSpec = spatialSpec, + shrinkTowards = Alignment.Start, + ), + enter = fadeIn(effectsSpec) + expandHorizontally( + animationSpec = spatialSpec, + expandFrom = Alignment.Start, + ) + ) { + IconButton( + onClick = onPreviousStep + ) { + Icon( + imageVector = Icons.AutoMirrored.Default.ArrowBack, + contentDescription = null + ) + } + } + } + ) + }, bottomBar = { Box( modifier = Modifier.fillMaxWidth(), @@ -269,8 +347,14 @@ private fun OnboardingStepsPreview() { MaterialTheme { OnboardingSteps( state = OnboardingUiState.Welcome(), + stepProgress = OnboardingStepProgress( + currentIndex = 0, + totalSteps = 5, + canGoBack = false, + ), loading = false, onNextStep = {}, + onPreviousStep = {}, onSkip = {}, onChooseImportFile = {}, ) diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index 849f55b4f..594007ab4 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -16,6 +16,7 @@ import de.davis.keygo.feature.autofill.domain.repository.ChromeAutofillRepositor import de.davis.keygo.feature.backup.domain.model.BackupDestinationUri import de.davis.keygo.feature.onboarding.presentation.model.AutofillSetupAction import de.davis.keygo.feature.onboarding.presentation.model.OnboardingStep +import de.davis.keygo.feature.onboarding.presentation.model.OnboardingStepProgress import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -169,6 +170,36 @@ internal class OnboardingViewModel( initialValue = OnboardingUiState.Welcome() ) + val stepProgress = combine(_step, stepsToSkip) { step, skip -> + val activeSteps = OnboardingStep.activeSteps(skip) + OnboardingStepProgress( + currentIndex = activeSteps.indexOf(step), + totalSteps = activeSteps.size, + canGoBack = step.canGoBack, + ) + }.stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5_000), + initialValue = OnboardingStepProgress( + currentIndex = 0, + totalSteps = OnboardingStep.entries.size, + canGoBack = false, + ), + ) + + fun onPreviousStep() { + val previous = _step.value.previousStep(stepsToSkip.value) ?: return + + // fileUri survives onImportFinished by design (see its own comment), so stepping back + // from autofill into a completed import would otherwise reopen the wizard on the old + // file instead of the chooser. Only autofill's back reaches this step, so this never + // fires while the chooser itself is still on screen. + if (previous == OnboardingStep.ImportExistingData) + _importDataState.update { it.copy(fileUri = null) } + + _step.update { previous } + } + fun onNextStep() { when (_step.value) { OnboardingStep.SetMainPassword -> { diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt index 688bd055d..f58f71054 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStep.kt @@ -8,8 +8,23 @@ internal enum class OnboardingStep { EnableAutofillService; fun nextStep(skip: Set): OnboardingStep? { - val pool = OnboardingStep.entries.filterNot { it in skip } + val pool = activeSteps(skip) val currentIndex = pool.indexOf(this) return if (currentIndex != -1) pool.getOrNull(currentIndex + 1) else null } + + fun previousStep(skip: Set): OnboardingStep? { + if (!canGoBack) return null + val pool = activeSteps(skip) + val currentIndex = pool.indexOf(this) + return if (currentIndex != -1) pool.getOrNull(currentIndex - 1) else null + } + + val canGoBack: Boolean + get() = this == SetMainPassword || this == EnableBiometrics || this == EnableAutofillService + + companion object { + fun activeSteps(skip: Set): List = + entries.filterNot { it in skip } + } } \ No newline at end of file diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepProgress.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepProgress.kt new file mode 100644 index 000000000..8a5678aeb --- /dev/null +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepProgress.kt @@ -0,0 +1,7 @@ +package de.davis.keygo.feature.onboarding.presentation.model + +internal data class OnboardingStepProgress( + val currentIndex: Int, + val totalSteps: Int, + val canGoBack: Boolean, +) diff --git a/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepTest.kt b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepTest.kt index 23565669d..d44e411fb 100644 --- a/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepTest.kt +++ b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingStepTest.kt @@ -32,4 +32,60 @@ class OnboardingStepTest { ), ) } + + @Test + fun `every step but welcome and import allows going back`() { + assertEquals( + setOf( + OnboardingStep.SetMainPassword, + OnboardingStep.EnableBiometrics, + OnboardingStep.EnableAutofillService, + ), + OnboardingStep.entries.filter { it.canGoBack }.toSet(), + ) + } + + @Test + fun `stepping back from biometrics returns to the password step`() { + assertEquals( + OnboardingStep.SetMainPassword, + OnboardingStep.EnableBiometrics.previousStep(skip = emptySet()), + ) + } + + @Test + fun `stepping back from the password step returns to welcome`() { + assertEquals( + OnboardingStep.Welcome, + OnboardingStep.SetMainPassword.previousStep(skip = emptySet()), + ) + } + + @Test + fun `welcome has nothing to go back to`() { + assertNull(OnboardingStep.Welcome.previousStep(skip = emptySet())) + } + + @Test + fun `import is a dead end going backwards`() { + assertNull(OnboardingStep.ImportExistingData.previousStep(skip = emptySet())) + } + + @Test + fun `stepping back from autofill returns to the import step`() { + assertEquals( + OnboardingStep.ImportExistingData, + OnboardingStep.EnableAutofillService.previousStep(skip = emptySet()), + ) + } + + @Test + fun `stepping back from autofill still lands on import when biometrics was skipped`() { + assertEquals( + OnboardingStep.ImportExistingData, + OnboardingStep.EnableAutofillService.previousStep( + skip = setOf(OnboardingStep.EnableBiometrics), + ), + ) + } } From c17ae204d7de5197e686fe544805da1b0a581d36 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Tue, 11 Aug 2026 22:15:14 +0200 Subject: [PATCH 21/24] fix: review findings --- .../feature/onboarding/presentation/OnboardingScreen.kt | 6 +++--- .../feature/settings/presentation/SettingsViewModel.kt | 5 +---- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt index d1a09a3e3..851bb037a 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingScreen.kt @@ -95,7 +95,7 @@ fun OnboardingScreen(onSuccess: () -> Unit) { viewModel.performCreateAccess(it) }.onFailure { Log.e("OnboardingScreen", "Failed to create cipher for biometric access: $it") - // TODO: show error + viewModel.performCreateAccess() //TODO: maybe show error msg to user } } @@ -239,7 +239,7 @@ private fun OnboardingSteps( } } - if (state.isOutlinedButonCandidate()) + if (state.isOutlinedButtonCandidate()) OutlinedButton( onClick = onNextStep, shapes = ButtonDefaults.shapesFor(contentHeight), @@ -338,7 +338,7 @@ private val OnboardingUiState.optionalActionText: String? R.string.finish_setup.takeIf { nextAction != AutofillSetupAction.Finish } }?.let { stringResource(it) } -private fun OnboardingUiState.isOutlinedButonCandidate() = this is OnboardingUiState.ImportData +private fun OnboardingUiState.isOutlinedButtonCandidate() = this is OnboardingUiState.ImportData @Preview @PreviewScreenSizes diff --git a/feature/settings/src/main/kotlin/de/davis/keygo/feature/settings/presentation/SettingsViewModel.kt b/feature/settings/src/main/kotlin/de/davis/keygo/feature/settings/presentation/SettingsViewModel.kt index 9780d1ef5..42f128d0e 100644 --- a/feature/settings/src/main/kotlin/de/davis/keygo/feature/settings/presentation/SettingsViewModel.kt +++ b/feature/settings/src/main/kotlin/de/davis/keygo/feature/settings/presentation/SettingsViewModel.kt @@ -8,7 +8,6 @@ import de.davis.keygo.feature.autofill.domain.repository.AutofillServiceReposito import de.davis.keygo.feature.autofill.domain.repository.ChromeAutofillRepository import de.davis.keygo.feature.backup.domain.usecase.ObserveLastBackupUseCase import de.davis.keygo.feature.settings.domain.repository.AppVersionRepository -import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted @@ -70,9 +69,7 @@ internal class SettingsViewModel( // Re-read on resume: the autofill selection changes in the system picker/settings, which // run in a separate activity, so this is where we learn KeyGo was enabled or disabled. autofillEnabled.update { autofillServiceRepository.isEnabled() } - // Chrome's read is a cross-process ContentProvider query (binder IPC, can cold-start - // Chrome's process) — unlike the two reads above, keep it off the main thread. - viewModelScope.launch(Dispatchers.IO) { + viewModelScope.launch { chromeAutofillEnabled.update { chromeAutofillRepository.isAutofillEnabled() } } } From b5d84b371ef6bcaa4299ee8e6a3f312ae6cfc596 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Tue, 11 Aug 2026 22:41:13 +0200 Subject: [PATCH 22/24] ci: add concurrency --- .github/workflows/ci.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 23f76da42..2aafa5061 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -6,6 +6,11 @@ on: pull_request: branches: [ "v2" ] +concurrency: + # Groups runs by workflow name and the branch/PR number. + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + permissions: contents: read From 1ad58c549605fd3dc9c620c3687609235c0d7f79 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Tue, 11 Aug 2026 22:43:53 +0200 Subject: [PATCH 23/24] fix: import --- .../main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt index 268379b70..119e8637d 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt @@ -21,6 +21,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.fragment.app.FragmentActivity import androidx.navigation.NavDestination.Companion.hasRoute From b477256c5111b61d7c954a5d436a99b3ee4b1ccc Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Tue, 11 Aug 2026 22:56:45 +0200 Subject: [PATCH 24/24] chore: increase heap size --- gradle.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index 132244e5b..4c51ec73c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -6,7 +6,7 @@ # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. -org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +org.gradle.jvmargs=-Xmx3g -XX:+UseParallelGC -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. For more details, visit # https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects @@ -20,4 +20,4 @@ kotlin.code.style=official # Enables namespacing of each library's R class so that its R class includes only the # resources declared in the library itself and none from the library's dependencies, # thereby reducing the size of the R class for that library -android.nonTransitiveRClass=true +android.nonTransitiveRClass=true \ No newline at end of file