Yokan / rebuild
Course 1 8624561

BrowseSettingsScreen.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/browse/BrowseSettingsScreen.kt

implementation298 lines
1package eu.friedcutlet.yokan.ui.screens.settings.browse23import androidx.compose.runtime.Composable4import androidx.compose.runtime.LaunchedEffect5import androidx.compose.runtime.getValue6import androidx.compose.runtime.mutableStateOf7import androidx.compose.runtime.remember8import androidx.compose.runtime.setValue9import androidx.compose.foundation.layout.Column10import androidx.compose.foundation.layout.Row11import androidx.compose.foundation.layout.fillMaxWidth12import androidx.compose.foundation.layout.padding13import androidx.compose.material3.AlertDialog14import androidx.compose.material3.MaterialTheme15import androidx.compose.material3.OutlinedTextField16import androidx.compose.material3.Text17import androidx.compose.material3.TextButton18import androidx.compose.ui.Modifier19import androidx.compose.ui.semantics.LiveRegionMode20import androidx.compose.ui.semantics.liveRegion21import androidx.compose.ui.semantics.semantics22import androidx.compose.ui.unit.dp23import androidx.lifecycle.compose.collectAsStateWithLifecycle24import androidx.lifecycle.viewmodel.compose.viewModel25import eu.friedcutlet.yokan.app.YokanRuntime26import eu.friedcutlet.yokan.database.DbSettings27import eu.friedcutlet.yokan.domain.ItemType28import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeMode29import eu.friedcutlet.yokan.services.library.SelectiveDataClearService30import eu.friedcutlet.yokan.services.notifications.InAppNotifications31import eu.friedcutlet.yokan.ui.components.ConfirmDialog32import eu.friedcutlet.yokan.ui.navigation.SettingsPage33import eu.friedcutlet.yokan.ui.navigation.SettingsPage.CreateBackup34import eu.friedcutlet.yokan.ui.navigation.SettingsPage.AnimeRepositories35import eu.friedcutlet.yokan.ui.navigation.SettingsPage.Cookies36import eu.friedcutlet.yokan.ui.navigation.SettingsPage.ExtensionServer37import eu.friedcutlet.yokan.ui.navigation.SettingsPage.MangaRepositories38import eu.friedcutlet.yokan.ui.navigation.SettingsPage.MetadataServer39import eu.friedcutlet.yokan.ui.navigation.SettingsPage.NovelRepositories40import eu.friedcutlet.yokan.ui.screens.settings.ButtonRow41import eu.friedcutlet.yokan.ui.screens.settings.InfoRow42import eu.friedcutlet.yokan.ui.screens.settings.RouteTile43import eu.friedcutlet.yokan.ui.screens.settings.SettingTile44import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold45import eu.friedcutlet.yokan.ui.screens.settings.SettingsSection46import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile47import org.jetbrains.compose.resources.stringResource48import yokan.composeapp.generated.resources.Res49import yokan.composeapp.generated.resources.action_cancel50import yokan.composeapp.generated.resources.auto_extensions_updates51import yokan.composeapp.generated.resources.check_for_extension_updates52import yokan.composeapp.generated.resources.clean_database53import yokan.composeapp.generated.resources.only_include_pinned_sources54import yokan.composeapp.generated.resources.tile_show_nsfw_sources55import yokan.composeapp.generated.resources.hide_library_section56import yokan.composeapp.generated.resources.hide_library_summary5758internal data class DestructiveAction(59    val title: String,60    val message: String,61    val onConfirm: () -> Unit,62)6364internal fun parseClearItemTypes(input: String): Set<ItemType>? {65    val parts = input.split(',')66    if (parts.isEmpty() || parts.any { it.isBlank() }) return null67    val selected = linkedSetOf<ItemType>()68    for (part in parts) {69        val type = ItemType.entries.firstOrNull { it.name.equals(part.trim(), ignoreCase = true) } ?: return null70        selected += type71    }72    return selected.takeIf { it.isNotEmpty() }73}7475private enum class ClearTarget { Library, Sources }7677@Composable78internal fun BrowseSettingsRoute(79    title: String,80    settings: DbSettings,81    onUpdate: ((DbSettings) -> DbSettings) -> Unit,82    onBack: () -> Unit,83    onOpen: (SettingsPage) -> Unit,84) {85    val owner = remember { YokanRuntime.activeSession }86    val clearViewModel = viewModel {87        val service = SelectiveDataClearService(88            database = owner.database,89            downloader = owner.services.downloader,90            onSourcesCommitted = { ids ->91                ids.forEach { sourceId ->92                    owner.services.extensionRuntimeFactory.evict(sourceId)93                    owner.chapterPages.invalidateSource(sourceId)94                }95            },96        )97        BrowseClearViewModel(98            service = service,99            hasConfiguredHub = {100                owner.database.snapshot().syncPreferences.any {101                    !it.server.isNullOrBlank() && !it.server.startsWith("cloud://")102                }103            },104        )105    }106    val clearState by clearViewModel.state.collectAsStateWithLifecycle()107    BrowseSettingsScreen(108        title, settings, onUpdate, onBack, onOpen,109        extensionServerIsRemoteOnly = owner.services.extensionServer.mode == ExtensionServerRuntimeMode.Unsupported,110        onClearSources = clearViewModel::clearSources,111        onCleanDatabase = { owner.repository.cleanDatabase() },112        onClearLibrary = clearViewModel::clearLibrary,113        onClearLocalLibrary = owner.localLibrary::clear,114        clearBusy = clearState.busy,115        clearError = clearState.error,116        clearSuccess = clearState.success,117        onClearFeedback = clearViewModel::clearFeedback,118    )119}120121@Composable122internal fun BrowseSettingsScreen(123    title: String,124    settings: DbSettings,125    onUpdate: ((DbSettings) -> DbSettings) -> Unit,126    onBack: () -> Unit,127    onOpen: (SettingsPage) -> Unit,128    extensionServerIsRemoteOnly: Boolean,129    onClearSources: (Set<ItemType>) -> Unit,130    onCleanDatabase: () -> Unit,131    onClearLibrary: (Set<ItemType>) -> Unit,132    onClearLocalLibrary: () -> Int,133    clearBusy: Boolean = false,134    clearError: String? = null,135    clearSuccess: String? = null,136    onClearFeedback: () -> Unit = {},137) {138    var pendingDestructive by remember { mutableStateOf<DestructiveAction?>(null) }139    var pendingClear by remember { mutableStateOf<ClearTarget?>(null) }140    var clearTypesText by remember { mutableStateOf("") }141    val selectedClearTypes = parseClearItemTypes(clearTypesText)142    LaunchedEffect(clearSuccess) {143        if (clearSuccess != null) {144            pendingClear = null145            clearTypesText = ""146        }147    }148    val dismissClear = {149        pendingClear = null150        clearTypesText = ""151        onClearFeedback()152    }153    pendingClear?.let { target ->154        val selectedLabels = selectedClearTypes?.joinToString { it.label } ?: ""155        val library = target == ClearTarget.Library156        AlertDialog(157            onDismissRequest = { if (!clearBusy) dismissClear() },158            title = { Text(if (library) "Clear library records" else "Clear source definitions") },159            text = {160                Column {161                    Text(if (library) {162                        "This deletes all selected titles, including favorites and cached entries, plus their chapters, progress, tracking, and download records. With a connected yokan-hub, deletions propagate to your other devices; without a configured hub, this clear is local-only. Sources stay in place. Downloaded and local media files are not deleted."163                    } else {164                        "This deletes only the selected local source definitions and preferences from the database. Library entries stay in place. A later repository refresh may rediscover some sources. Downloaded and local media files are not deleted."165                    })166                    OutlinedTextField(167                        value = clearTypesText,168                        onValueChange = { clearTypesText = it },169                        modifier = Modifier.fillMaxWidth().padding(top = 12.dp),170                        label = { Text("Types to clear") },171                        placeholder = { Text("manga,anime,novel") },172                        supportingText = {173                            Text(if (selectedClearTypes == null) "Enter one or more types separated by commas: manga, anime, novel." else "Selected: $selectedLabels")174                        },175                        isError = selectedClearTypes == null && clearTypesText.isNotEmpty(),176                        singleLine = true,177                        enabled = !clearBusy,178                    )179                    if (clearError != null) {180                        Text(clearError, color = MaterialTheme.colorScheme.error,181                            modifier = Modifier.semantics { liveRegion = LiveRegionMode.Assertive })182                    }183                }184            },185            confirmButton = {186                TextButton(187                    onClick = { selectedClearTypes?.let { types -> if (library) onClearLibrary(types) else onClearSources(types) } },188                    enabled = selectedClearTypes != null && !clearBusy,189                ) { Text(if (clearBusy) "Clearing…" else if (library) "Clear library records" else "Clear source definitions") }190            },191            dismissButton = {192                Row {193                    TextButton(onClick = { onOpen(CreateBackup) }, enabled = !clearBusy) { Text("Create backup") }194                    TextButton(onClick = dismissClear, enabled = !clearBusy) { Text(stringResource(Res.string.action_cancel)) }195                }196            },197        )198    }199    pendingDestructive?.let { action ->200        ConfirmDialog(201            title = action.title,202            message = action.message,203            confirmLabel = "Yes, clear",204            danger = true,205            onConfirm = action.onConfirm,206            onDismiss = { pendingDestructive = null },207        )208    }209    SettingsScaffold(title, onBack) {210        item { SettingsSection("Extensions") }211        item {212            RouteTile(213                ExtensionServer,214                if (extensionServerIsRemoteOnly) "Remote APK extension server" else "Android proxy server (Mihon)",215                if (extensionServerIsRemoteOnly) "Connect to a hosted server URL" else "Install and run the local bridge",216                onOpen = onOpen,217            )218        }219        item { RouteTile(MetadataServer, "Metadata server", "Alternative titles, tags, and tracker sync", onOpen = onOpen) }220        item { RouteTile(MangaRepositories, "Manga extensions repo", "Manage manga repo URLs", onOpen = onOpen) }221        item { RouteTile(AnimeRepositories, "Anime extensions repo", "Manage anime repo URLs", onOpen = onOpen) }222        item { RouteTile(NovelRepositories, "Novel extensions repo", "Manage novel repo URLs", onOpen = onOpen) }223        item { SwitchTile(stringResource(Res.string.check_for_extension_updates), null, settings.checkForExtensionUpdates, { value -> onUpdate { it.copy(checkForExtensionUpdates = value) } }) }224        item {225            ButtonRow("Clear source definitions", danger = true) {226                onClearFeedback()227                clearTypesText = ""228                pendingClear = ClearTarget.Sources229            }230        }231        item {232            val cleanDatabaseTitle = stringResource(Res.string.clean_database)233            SettingTile(234                cleanDatabaseTitle,235                "Delete non-favorited entries and their chapter data",236                onClick = {237                    pendingDestructive = DestructiveAction(238                        title = cleanDatabaseTitle,239                        message = "Delete every entry that isn't in your library (cached browsing results) and its chapter data? Favorited entries are kept.",240                    ) { onCleanDatabase() }241                },242            )243        }244        item {245            SettingTile("Clear library records", "Remove selected media types from the library database", onClick = {246                onClearFeedback()247                clearTypesText = ""248                pendingClear = ClearTarget.Library249            })250        }251        if (clearSuccess != null) {252            item {253                Text(254                    clearSuccess,255                    modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp).semantics { liveRegion = LiveRegionMode.Polite },256                    color = MaterialTheme.colorScheme.primary,257                )258            }259        }260        item {261            SettingTile(262                "Clear local library",263                "Remove indexed local and archive titles",264                onClick = {265                    pendingDestructive = DestructiveAction(266                        title = "Clear local library",267                        message = "All local and archive titles, chapters, history, updates, and download records will be removed. Remote library entries are kept. This cannot be undone.",268                    ) {269                        val removed = onClearLocalLibrary()270                        InAppNotifications.post(271                            "Local library cleared",272                            "$removed ${if (removed == 1) "title" else "titles"} removed",273                        )274                    }275                },276            )277        }278        if (settings.checkForExtensionUpdates) {279            item { SwitchTile(stringResource(Res.string.auto_extensions_updates), "Auto-install updates when available", settings.autoExtensionsUpdates, { value -> onUpdate { it.copy(autoExtensionsUpdates = value) } }) }280        }281        item { SettingsSection(stringResource(Res.string.hide_library_section)) }282        item { InfoRow(stringResource(Res.string.hide_library_summary)) }283        ItemType.entries.forEach { type ->284            item(key = "hide-library-${type.name}") {285                SwitchTile(type.label, null, settings.features.browse.hidesLibrary(type), { value ->286                    onUpdate { it.copy(features = it.features.copy(browse = it.features.browse.withHideLibrary(type, value))) }287                })288            }289        }290        item { SettingsSection("Global search") }291        item { SwitchTile(stringResource(Res.string.only_include_pinned_sources), null, settings.onlyIncludePinnedSources, { value -> onUpdate { it.copy(onlyIncludePinnedSources = value) } }) }292        item { SettingsSection("NSFW sources") }293        item { SwitchTile(stringResource(Res.string.tile_show_nsfw_sources), null, settings.showNsfw, { value -> onUpdate { it.copy(showNsfw = value) } }) }294        item { InfoRow("NSFW sources may contain explicit material. The app does not endorse or curate this content — use at your own discretion.") }295        item { SettingsSection("Cookies") }296        item { RouteTile(Cookies, "Cookies", "Manage stored source cookies", onOpen = onOpen) }297    }298}299

Search chapters, reference and source filenames.