From 3ac58287e54ec04ade54a53b5ffe7f7b666ecd0e Mon Sep 17 00:00:00 2001 From: Fabian Norlin Date: Fri, 3 Oct 2025 21:48:31 +0200 Subject: [PATCH] Removed old-UI and cleaned up. --- .../kotlin/app/klottr/KlottrAppShell.kt | 1306 ++++++----------- .../kotlin/app/klottr/SettingsDialog.kt | 102 +- .../app/klottr/ui/CommonDialogsShell.kt | 153 -- 3 files changed, 433 insertions(+), 1128 deletions(-) diff --git a/shared/src/commonMain/kotlin/app/klottr/KlottrAppShell.kt b/shared/src/commonMain/kotlin/app/klottr/KlottrAppShell.kt index e3fa110..b120807 100644 --- a/shared/src/commonMain/kotlin/app/klottr/KlottrAppShell.kt +++ b/shared/src/commonMain/kotlin/app/klottr/KlottrAppShell.kt @@ -1,7 +1,5 @@ package app.klottr -import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -50,7 +48,6 @@ import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold -import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -66,15 +63,12 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha -import androidx.compose.ui.graphics.decodeToImageBitmap import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import app.cash.sqldelight.coroutines.asFlow // SQLDelight coroutine-extensions (Flow-stöd för queries) import app.cash.sqldelight.coroutines.mapToList // SQLDelight coroutine-extensions (Flow-stöd för queries) -import app.klottr.SettingsScreen import app.klottr.create.CreateNoteOutcome import app.klottr.create.QueueOutboxOutcome import app.klottr.create.createNoteFlow @@ -90,7 +84,6 @@ import app.klottr.nearby.OpenFornsok import app.klottr.nearby.OpenKlotter import app.klottr.nearby.OpenWiki import app.klottr.nearby.ScanConfig -import app.klottr.nearby.enrichKlotterLabels import app.klottr.nearby.getNearbyBundle import app.klottr.nearby.resolveFoundOpenAction import app.klottr.nearby.scanAndMarkFound @@ -102,7 +95,6 @@ import app.klottr.net.Geocache import app.klottr.net.UserStats import app.klottr.net.Wikipedia import app.klottr.net.createNoteDoc -import app.klottr.net.fetchImageStreamPost import app.klottr.net.fetchMe import app.klottr.net.fetchNoteDetail import app.klottr.net.fetchUserStats @@ -112,7 +104,6 @@ import app.klottr.platform.AppNavigator import app.klottr.platform.OutboxScheduler import app.klottr.platform.UiFeedback import app.klottr.platform.UiFeedbackDuration -import app.klottr.platform.hasFgLocationPerms import app.klottr.ui.AboutScreen import app.klottr.ui.DmDialog import app.klottr.ui.FornsokDialog @@ -120,16 +111,12 @@ import app.klottr.ui.KlottrHomeContent import app.klottr.ui.LoginRequiredContent import app.klottr.ui.MapContent import app.klottr.ui.NearbyContent -import app.klottr.ui.NearbyDialog -import app.klottr.ui.NearbyDialogContent import app.klottr.ui.UsernameDialog import app.klottr.ui.WikiArticleDialog import app.klottr.util.AuthShared import app.klottr.util.Config import app.klottr.util.FoundStore import app.klottr.util.FoundStore.LAYER_KLOTTER -import app.klottr.util.ImageBitmapCache -import app.klottr.util.KLog import app.klottr.util.NoteDetailCache import app.klottr.util.OutboxStore import app.klottr.util.SettingsStore @@ -140,11 +127,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import kotlin.collections.component1 -import kotlin.collections.component2 -import kotlin.collections.iterator import kotlin.collections.orEmpty -import kotlin.collections.set import kotlin.time.Clock import kotlin.time.ExperimentalTime @@ -315,694 +298,169 @@ fun KlottrAppShell( } } - - var showAbout by remember { mutableStateOf(false) } - Scaffold( topBar = { CenterAlignedTopAppBar( title = { Text("") }, // Standardtitel i appbaren (ingen special-Box, inga extra modifiers) - actions = { // Dina befintliga actions (Info/Inställningar) - IconButton(onClick = { showAbout = true }) { - Icon(imageVector = Icons.Filled.Info, contentDescription = "Om") - } - IconButton(onClick = { showSettings = true }) { - Icon(imageVector = Icons.Filled.Settings, contentDescription = "Inställningar") - } - } ) } ) { padding -> - if (useNewUi) { - var selectedTab by rememberSaveable { mutableStateOf("home") } - var showChangeUsernameDialog by remember { mutableStateOf(false) } - Scaffold( - topBar = { - CenterAlignedTopAppBar( - title = { Text("") }, - actions = { - IconButton(onClick = { showAbout = true }) { - Icon(imageVector = Icons.Filled.Info, contentDescription = "Om") - } - IconButton(onClick = { showSettings = true }) { - Icon(imageVector = Icons.Filled.Settings, contentDescription = "Inställningar") - } - } + + var selectedTab by rememberSaveable { mutableStateOf("home") } + var showChangeUsernameDialog by remember { mutableStateOf(false) } + Scaffold( + bottomBar = { + NavigationBar { + NavigationBarItem( + selected = (selectedTab == "home"), + onClick = { selectedTab = "home" }, + icon = { Icon(Icons.Filled.Home, contentDescription = "Hem") }, + label = { Text("Hem") } ) - }, - bottomBar = { - NavigationBar { - NavigationBarItem( - selected = (selectedTab == "home"), - onClick = { selectedTab = "home" }, - icon = { Icon(Icons.Filled.Home, contentDescription = "Hem") }, - label = { Text("Hem") } - ) - NavigationBarItem( - selected = false, - onClick = { /* TODO Lager */ }, - icon = { Icon(Icons.Filled.Layers, contentDescription = "Lager") }, - label = { Text("Lager") } - ) - NavigationBarItem( - selected = (selectedTab == "nearby"), - onClick = { selectedTab = "nearby" }, - icon = { Icon(Icons.Filled.Place, contentDescription = "Nära") }, - label = { Text("Nära") } - ) - NavigationBarItem( - selected = (selectedTab == "menu"), - onClick = { selectedTab = "menu" }, - icon = { Icon(Icons.Filled.Menu, contentDescription = "Meny") }, - label = { Text("Meny") } - ) + NavigationBarItem( + selected = false, + onClick = { /* TODO Lager */ }, + icon = { Icon(Icons.Filled.Layers, contentDescription = "Lager") }, + label = { Text("Lager") } + ) + NavigationBarItem( + selected = (selectedTab == "nearby"), + onClick = { selectedTab = "nearby" }, + icon = { Icon(Icons.Filled.Place, contentDescription = "Nära") }, + label = { Text("Nära") } + ) + NavigationBarItem( + selected = (selectedTab == "menu"), + onClick = { selectedTab = "menu" }, + icon = { Icon(Icons.Filled.Menu, contentDescription = "Meny") }, + label = { Text("Meny") } + ) + } + }, + floatingActionButton = { + if (selectedTab in listOf("home", "nearby")) { + FloatingActionButton( + onClick = { showWrite = true } + ) { + Icon(Icons.Filled.Add, contentDescription = "Klottra") } - }, - floatingActionButton = { - if (selectedTab in listOf("home", "nearby")) { - FloatingActionButton( - onClick = { showWrite = true } - ) { - Icon(Icons.Filled.Add, contentDescription = "Klottra") + } + }, + floatingActionButtonPosition = androidx.compose.material3.FabPosition.Center, + content = { innerPadding -> + if (selectedTab !in listOf("home", "nearby", "menu", "account", "about", "settings")) { + selectedTab = "home" + } + // VIKTIGT: vi komponerar ALLA flikar alltid, och växlar bara synlighet. + // => MapContent förstörs inte när du byter flik, så kartan slipper “blinka”. + Box(Modifier.fillMaxSize().consumeWindowInsets(innerPadding)) { + + // === HEM === + Box( + modifier = Modifier + .fillMaxSize() + .alpha(if (selectedTab == "home") 1f else 0f) + .zIndex(if (selectedTab == "home") 1f else 0f) + ) { + // Återanvänd gamla layoutens lista med fynd + val foundList = remember(foundRefresh, forceEmptyFound) { + if (forceEmptyFound) emptyList() else FoundStore.getAll().reversed() } - } - }, - floatingActionButtonPosition = androidx.compose.material3.FabPosition.Center, - content = { innerPadding -> - if (selectedTab !in listOf("home", "nearby", "menu", "account", "about", "settings")) { - selectedTab = "home" - } - // VIKTIGT: vi komponerar ALLA flikar alltid, och växlar bara synlighet. - // => MapContent förstörs inte när du byter flik, så kartan slipper “blinka”. - Box(Modifier.fillMaxSize().consumeWindowInsets(innerPadding)) { + val labelOverrides = remember { androidx.compose.runtime.mutableStateMapOf() } + val foundKey = foundList.joinToString("|") { "${it.layer}:${it.id}" } - // === HEM === - Box( - modifier = Modifier - .fillMaxSize() - .alpha(if (selectedTab == "home") 1f else 0f) - .zIndex(if (selectedTab == "home") 1f else 0f) - ) { - // Återanvänd gamla layoutens lista med fynd - val foundList = remember(foundRefresh, forceEmptyFound) { - if (forceEmptyFound) emptyList() else FoundStore.getAll().reversed() - } - val labelOverrides = remember { androidx.compose.runtime.mutableStateMapOf() } - val foundKey = foundList.joinToString("|") { "${it.layer}:${it.id}" } - - LaunchedEffect(foundKey) { - val my = LastLocationStore.lastKnownLocation - val myLat = my.value?.lat - val myLon = my.value?.lon - labelOverrides.clear() - foundList.forEach { f -> - if (f.layer == LAYER_KLOTTER) { - val inside = if (myLat != null && myLon != null) - app.klottr.util.distanceMeters(myLat, myLon, f.lat, f.lon) <= Config.DEFAULT_KLOTTER_RADIUS_M - else true - if (inside) { - val idL = f.id.toLongOrNull() ?: return@forEach - if (NoteDetailCache.get(idL) == null) { - val detail = fetchNoteDetail(idL, f.lat, f.lon) - if (detail != null) { - NoteDetailCache.put(idL, detail) - } + LaunchedEffect(foundKey) { + val my = LastLocationStore.lastKnownLocation + val myLat = my.value?.lat + val myLon = my.value?.lon + labelOverrides.clear() + foundList.forEach { f -> + if (f.layer == LAYER_KLOTTER) { + val inside = if (myLat != null && myLon != null) + app.klottr.util.distanceMeters(myLat, myLon, f.lat, f.lon) <= Config.DEFAULT_KLOTTER_RADIUS_M + else true + if (inside) { + val idL = f.id.toLongOrNull() ?: return@forEach + if (NoteDetailCache.get(idL) == null) { + val detail = fetchNoteDetail(idL, f.lat, f.lon) + if (detail != null) { + NoteDetailCache.put(idL, detail) } } } } } - - // OBS: INGEN extra padding här — KlottrHomeContent får innerPadding via argumentet nedan. - KlottrHomeContent( - contentPadding = innerPadding, - entries = foundList, - location = LastLocationStore.lastKnownLocation.collectAsState(), - showCoords = showCoords, - labelOverrides = labelOverrides, - isClickable = { f -> - (f.layer == FoundStore.LAYER_WIKI) || - (f.layer == FoundStore.LAYER_FORNSOK) || - (f.layer == FoundStore.LAYER_KLOTTER) || - (f.layer == FoundStore.LAYER_DM) - }, - onEntryClick = { f -> - scope.launch { - val action = withContext(Dispatchers.IO) { - resolveFoundOpenAction( - entry = f, - labelOverrides = labelOverrides, - fornsokAround = { lat, lon, radius -> - try { FornsokShared.getNearby(lat, lon, radius) } catch (_: Exception) { emptyList() } - }, - dmLookupByIdentifier = { id -> - try { app.klottr.net.DigitaltMuseum.lookupByIdentifier(id) } catch (_: Exception) { null } - } - ) - } - when (action) { - is FoundOpenAction.Klotter -> openKlotter = OpenKlotter(action.id, action.lat, action.lon, action.label) - is FoundOpenAction.Wiki -> openWiki = OpenWiki(action.pageId, action.lat, action.lon) - is FoundOpenAction.Fornsok -> openFornsok = OpenFornsok(action.item) - is FoundOpenAction.DigitaltMuseum -> openDm = action.item - FoundOpenAction.None -> Unit - } - } - }, - isBold = { f -> !FoundStore.isAway(f.layer, f.id) }, - distanceFormatter = ::formatDistance, - coordsFormatter = ::formatCoords, - rowTextStyle = MaterialTheme.typography.bodyMedium.copy( - color = MaterialTheme.colorScheme.onSurface - ), - header = { /* tom i nya layouten */ }, - footer = { /* tom i nya layouten */ } - ) } - // === NÄRA === - Box( - modifier = Modifier - .fillMaxSize() - .alpha(if (selectedTab == "nearby") 1f else 0f) - .zIndex(if (selectedTab == "nearby") 1f else 0f) - ) { - // Trigga scanning när fliken blir aktiv (och när lager-inställningar ändras) - LaunchedEffect(selectedTab, showKlotter, showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) { - if (selectedTab != "nearby") return@LaunchedEffect - nearbyRefreshing = true - nearbyError = null - - val gp = LocationServiceProvider.get().current(highAccuracy = false) - if (gp == null) { - nearbyLoading = false - nearbyError = "Ingen plats ännu – prova igen." - } else { - lastKnownLat = gp.lat - lastKnownLon = gp.lon - - val newBundle = withContext(Dispatchers.IO) { - getNearbyBundle( - lat = gp.lat, - lon = gp.lon, - showKlotter = showKlotter, - showWiki = showWiki, - showDm = showDm, - showFornsok = showFornsok, - wikiRadius = wikiRadius, - dmRadius = dmRadius, - fornsokRadius = fornsokRadius, - defaultKlotterRadiusM = Config.DEFAULT_KLOTTER_RADIUS_M, - knownKlotterLabel = { id -> - FoundStore.getAll() - .asSequence() - .filter { it.layer == FoundStore.LAYER_KLOTTER } - .associate { it.id to it.label }[id] + // OBS: INGEN extra padding här — KlottrHomeContent får innerPadding via argumentet nedan. + KlottrHomeContent( + contentPadding = innerPadding, + entries = foundList, + location = LastLocationStore.lastKnownLocation.collectAsState(), + showCoords = showCoords, + labelOverrides = labelOverrides, + isClickable = { f -> + (f.layer == FoundStore.LAYER_WIKI) || + (f.layer == FoundStore.LAYER_FORNSOK) || + (f.layer == FoundStore.LAYER_KLOTTER) || + (f.layer == FoundStore.LAYER_DM) + }, + onEntryClick = { f -> + scope.launch { + val action = withContext(Dispatchers.IO) { + resolveFoundOpenAction( + entry = f, + labelOverrides = labelOverrides, + fornsokAround = { lat, lon, radius -> + try { FornsokShared.getNearby(lat, lon, radius) } catch (_: Exception) { emptyList() } }, - klotterFetcher = { la, lo -> Geocache.getNearby(lat = la, lon = lo, radiusMeters = 300, ttlMs = 0L) }, - wikiFetcher = { la, lo, r -> Wikipedia.getNearby(la, lo, radiusMeters = r) }, - dmFetcher = { la, lo, r -> DigitaltMuseum.getNearby(la, lo, radiusMeters = r) }, - fornFetcher = { la, lo, r -> FornsokShared.getNearby(la, lo, radiusMeters = r) } - ) - } - - nearbyBundle = newBundle // uppdatera när klar - nearbyRefreshing = false - } - } - - // Layout (övre halvan karta, undre halvan lista). Vi ger innerPadding här. - Column(Modifier.fillMaxSize()) { - // Övre halvan: karta (ligger kvar i minnet eftersom hela lagret alltid finns) - Box(modifier = Modifier.weight(1f).fillMaxWidth()) { - MapContent( - onKlotterClick = { id, la, lo, label -> openKlotter = OpenKlotter(id, la, lo, label) }, - onOpenUrl = { title, url -> - when { - url.contains("wikipedia.org") -> { - val pageId = url.substringAfter("curid=").toLongOrNull() - if (pageId != null) { - openWiki = OpenWiki(pageId, null, null) - } else { - AppNavigator.openUrl(url) // fallback - } - } - url.contains("digitaltmuseum.se") -> { - val match = nearbyBundle?.dm?.firstOrNull { - it.webUrl == url || it.url == url - || url.contains(it.id, ignoreCase = true) - } - if (match != null) { - openDm = match - } else { - AppNavigator.openUrl(url) - } - } - url.contains("fornsok") -> { - val match = nearbyBundle?.forn?.firstOrNull { - it.uri == url || it.id == url || it.title == url - || (it.uri != null && url.contains(it.uri!!, ignoreCase = true)) - } - if (match != null) { - openFornsok = OpenFornsok(match) - } else { - AppNavigator.openUrl(url) - } - } - else -> AppNavigator.openUrl(url) - } - }, - onFornsokClick = { item -> - openFornsok = OpenFornsok(item) - }, - isKnownNote = { noteId -> - FoundStore.getAll().any { it.layer == LAYER_KLOTTER && it.id == noteId.toString() } - } - ) - } - - // Undre halvan: närliggande-listan — visa ALLTID senast cachdade data direkt - val hasLocOrCache = - (lastKnownLat != null && lastKnownLon != null) || - (nearbyBundle?.entries?.isNotEmpty() == true || - nearbyBundle?.dm?.isNotEmpty() == true || - nearbyBundle?.forn?.isNotEmpty() == true) - - Box(modifier = Modifier.weight(1f).fillMaxWidth()) { - NearbyContent( - loading = (nearbyBundle == null && nearbyRefreshing), - error = nearbyError, - hasLocation = hasLocOrCache, // undvik "Okänt avstånd"-baneret när cache finns - entries = nearbyBundle?.entries.orEmpty(), - dm = nearbyBundle?.dm.orEmpty(), - forn = nearbyBundle?.forn.orEmpty(), - onOpenAction = { action -> - when (action) { - is FoundOpenAction.Klotter -> openKlotter = OpenKlotter(action.id, action.lat, action.lon, action.label) - is FoundOpenAction.Wiki -> openWiki = OpenWiki(action.pageId, action.lat, action.lon) - is FoundOpenAction.Fornsok -> openFornsok = OpenFornsok(action.item) - is FoundOpenAction.DigitaltMuseum -> openDm = action.item - FoundOpenAction.None -> Unit - } - }, - rowTextStyle = MaterialTheme.typography.bodyMedium.copy( - color = MaterialTheme.colorScheme.onSurface - ) - ) - } - } - } - - // === MENY === - Box( - modifier = Modifier - .fillMaxSize() - .alpha(if (selectedTab == "menu") 1f else 0f) - .zIndex(if (selectedTab == "menu") 1f else 0f) - ) { - Column( - modifier = Modifier - .fillMaxSize() - .padding(innerPadding) - ) { - Text( - "Meny", - style = MaterialTheme.typography.headlineMedium, - modifier = Modifier.padding(16.dp) - ) - LazyVerticalGrid( - columns = GridCells.Fixed(3), - modifier = Modifier - .fillMaxSize() - .padding(8.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), - horizontalArrangement = Arrangement.spacedBy(12.dp) - ) { - items( - listOf( - Triple(Icons.Filled.Settings, "Inställningar") { selectedTab = "settings" }, - Triple(Icons.Filled.Info, "Om") { selectedTab = "about" }, - Triple(Icons.Filled.Person, "Konto") { selectedTab = "account" }, - Triple(Icons.Filled.Bookmark, "Bokmärken") { }, - Triple(Icons.Filled.Create, "Mitt klotter") { }, - Triple( - Icons.Filled.Login, - if (loggedIn) "Logga ut" else "Logga in" - ) { - if (loggedIn) onLogout() else onLogin() + dmLookupByIdentifier = { id -> + try { app.klottr.net.DigitaltMuseum.lookupByIdentifier(id) } catch (_: Exception) { null } } ) - ) { (icon, label, action) -> - MenuTile(icon = icon, label = label, onClick = action) + } + when (action) { + is FoundOpenAction.Klotter -> openKlotter = OpenKlotter(action.id, action.lat, action.lon, action.label) + is FoundOpenAction.Wiki -> openWiki = OpenWiki(action.pageId, action.lat, action.lon) + is FoundOpenAction.Fornsok -> openFornsok = OpenFornsok(action.item) + is FoundOpenAction.DigitaltMuseum -> openDm = action.item + FoundOpenAction.None -> Unit } } - } - } - // === KONTO === - Box( - modifier = Modifier - .fillMaxSize() - .alpha(if (selectedTab == "account") 1f else 0f) - .zIndex(if (selectedTab == "account") 1f else 0f) - ) { - LaunchedEffect(selectedTab, loggedIn) { - if (selectedTab != "account") return@LaunchedEffect - if (!loggedIn) { - me = null - userStats = null - return@LaunchedEffect - } - me = withContext(Dispatchers.IO) { fetchMe() } - // Hämta färsk statistik - userStats = withContext(Dispatchers.IO) { fetchUserStats() } - } - AccountScreen( - me = me, - userStats = userStats, - onLogin = { onLogin() }, - onLogout = { - onLogout() - selectedTab = "menu" - }, - onDeleteAccount = { - selectedTab = "menu" - }, - onChangeUsername = { showChangeUsernameDialog = true }, - modifier = Modifier.padding(innerPadding) - ) - } - if (showChangeUsernameDialog) { - var newName by remember { mutableStateOf("") } - var errorText by remember { mutableStateOf(null) } - var saving by remember { mutableStateOf(false) } - val scope = rememberCoroutineScope() - - AlertDialog( - onDismissRequest = { if (!saving) showChangeUsernameDialog = false }, - title = { - Column { - Text("Byt användarnamn", style = MaterialTheme.typography.titleLarge) - Spacer(Modifier.height(4.dp)) - Text( - "Efter att du har bytt kan du inte byta igen förrän om tre månader.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - }, - text = { - Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - OutlinedTextField( - value = newName, - onValueChange = { newName = it; errorText = null }, - label = { Text("Nytt användarnamn") }, - singleLine = true, - enabled = !saving, - modifier = Modifier.fillMaxWidth() - ) - if (errorText != null) { - Text(errorText!!, color = MaterialTheme.colorScheme.error) - } - } - }, - confirmButton = { - TextButton( - enabled = !saving && newName.isNotBlank(), - onClick = { - saving = true - scope.launch { - val resp = setUsernameRemote(newName) - if (resp == null) { - errorText = "Nätverksfel" - saving = false - return@launch - } - if (resp.ok) { - // Uppdatera me från servern - me = withContext(Dispatchers.IO) { fetchMe() } - showChangeUsernameDialog = false - saving = false - } else { - errorText = when (resp.reason) { - "invalid" -> "Ogiltigt användarnamn" - "taken" -> "Användarnamnet är upptaget" - "reserved" -> "Nyligen använt, reserverat i 6 månader" - "too_soon" -> "Du måste vänta innan du kan byta igen" - "already_set" -> "Du har redan ett användarnamn" - else -> "Fel: ${resp.reason}" - } - saving = false - } - } - } - ) { - Text("Spara") - } - }, - dismissButton = { - TextButton(onClick = { if (!saving) showChangeUsernameDialog = false }) { - Text("Avbryt") - } - } - ) - } - // === ABOUT === - Box( - modifier = Modifier - .fillMaxSize() - .alpha(if (selectedTab == "about") 1f else 0f) - .zIndex(if (selectedTab == "about") 1f else 0f) - ) { - AboutScreen( - modifier = Modifier - .fillMaxSize() - .padding(horizontal = 16.dp, vertical = 0.dp) // egen padding, ingen top-padding - ) - } - // === SETTINGS === - Box( - modifier = Modifier - .fillMaxSize() - .alpha(if (selectedTab == "settings") 1f else 0f) - .zIndex(if (selectedTab == "settings") 1f else 0f) - ) { - SettingsScreen( - onlyNew = onlyNew, - satellite = satellite, - night = night, - showCoords = showCoords, - onShowCoordsChanged = { SettingsStore.setShowCoordinates(it); showCoords = it }, - useNewUi = useNewUi, - onUseNewUiChanged = { SettingsStore.setUseNewUi(it); useNewUi = it }, - showKlotter = showKlotter, - showWiki = showWiki, - wikiRadius = wikiRadius, - showDm = showDm, - dmRadius = dmRadius, - showFornsok = showFornsok, - fornsokRadius = fornsokRadius, - onOnlyNewChanged = { SettingsStore.setOnlyNewHits(it); onlyNew = it }, - onSatelliteChanged = { SettingsStore.setSatelliteMap(it); satellite = it }, - onNightChanged = { SettingsStore.setNightMode(it); night = it }, - onShowKlotterChanged = { SettingsStore.setShowKlotter(it); showKlotter = it }, - onShowWikiChanged = { SettingsStore.setShowWikipedia(it); showWiki = it }, - onWikiRadiusChanged = { SettingsStore.setWikiRadiusMeters(it); wikiRadius = it }, - onShowDmChanged = { SettingsStore.setShowDigitaltMuseum(it); showDm = it }, - onDmRadiusChanged = { SettingsStore.setDigitaltMuseumRadiusMeters(it); dmRadius = it }, - onShowFornsokChanged = { SettingsStore.setShowFornsok(it); showFornsok = it }, - onFornsokRadiusChanged = { SettingsStore.setFornsokRadiusMeters(it); fornsokRadius = it }, - onClearFinds = { - FoundStore.clearAll() - forceEmptyFound = true - refreshFound() - FoundEvents.notifyFoundUpdated() - }, - modifier = Modifier - .fillMaxSize() - .padding( - start = 16.dp, - end = 16.dp, - top = innerPadding.calculateTopPadding(), // 👈 respektera AppBar - bottom = innerPadding.calculateBottomPadding() - ) - ) - } - } - } - ) - } else { - // --- Nytt: definiera listan + overrides före UI-anropet --- - val foundList = remember(foundRefresh, forceEmptyFound) { - if (forceEmptyFound) emptyList() else FoundStore.getAll().reversed() - } - val labelOverrides = - remember { androidx.compose.runtime.mutableStateMapOf() } - val foundKey = foundList.joinToString("|") { "${it.layer}:${it.id}" } - - // Förladdning av etiketter/bilder (oförändrad logik, flyttad hit) - LaunchedEffect(foundKey) { - val my = LastLocationStore.lastKnownLocation - val myLat = my.value?.lat - val myLon = my.value?.lon - labelOverrides.clear() - foundList.forEach { f -> - if (f.layer == LAYER_KLOTTER) { - val inside = if (myLat != null && myLon != null) - app.klottr.util.distanceMeters( - myLat, - myLon, - f.lat, - f.lon - ) <= Config.DEFAULT_KLOTTER_RADIUS_M - else true - if (inside) { - val idL = f.id.toLongOrNull() ?: return@forEach - if (NoteDetailCache.get(idL) == null) { - val detail = fetchNoteDetail(idL, f.lat, f.lon) - if (detail != null) { - NoteDetailCache.put(idL, detail) - val img = detail.image - if (img != null && img.id > 0 && ImageBitmapCache.get(img.id) == null) { - withContext(Dispatchers.IO) { - fetchImageStreamPost( - imageId = img.id, - noteId = detail.id, - lat = f.lat, - lon = f.lon - )?.decodeToImageBitmap() - } - } - } - } - } - val enriched = withContext(Dispatchers.IO) { - enrichKlotterLabels( - found = foundList, - radiusMeters = 60, - fetchNearbyKlotter = { la, lo, r -> - Geocache.getNearby( - lat = la, - lon = lo, - radiusMeters = r, - ttlMs = 0L - ) - } - ) - } - for ((k, v) in enriched) { - labelOverrides[k] = v - } - } - } - } - - // --- Nytt: KlottrHomeContent (delat mitt-innehåll) --- - KlottrHomeContent( - contentPadding = padding, - entries = foundList, - location = LastLocationStore.lastKnownLocation.collectAsState(), - showCoords = showCoords, - labelOverrides = labelOverrides, - isClickable = { f -> - (f.layer == FoundStore.LAYER_WIKI) || - (f.layer == FoundStore.LAYER_FORNSOK) || - (f.layer == FoundStore.LAYER_KLOTTER) || - (f.layer == FoundStore.LAYER_DM) - }, - onEntryClick = { f -> - scope.launch { - val action = withContext(Dispatchers.IO) { - resolveFoundOpenAction( - entry = f, - labelOverrides = labelOverrides, - fornsokAround = { lat, lon, radius -> - try { - FornsokShared.getNearby(lat, lon, radius) - } catch (_: Exception) { - emptyList() - } - }, - dmLookupByIdentifier = { id -> - try { - app.klottr.net.DigitaltMuseum.lookupByIdentifier(id) - } catch (_: Exception) { - null - } - } - ) - } - when (action) { - is FoundOpenAction.Klotter -> { - openKlotter = OpenKlotter( - id = action.id, - lat = action.lat, - lon = action.lon, - label = action.label - ) - } - - is FoundOpenAction.Wiki -> { - openWiki = OpenWiki(action.pageId, action.lat, action.lon) - } - - is FoundOpenAction.Fornsok -> { - openFornsok = OpenFornsok(action.item) - } - - is FoundOpenAction.DigitaltMuseum -> { - openDm = action.item - } - - FoundOpenAction.None -> Unit - } - } - }, - isBold = { f -> !FoundStore.isAway(f.layer, f.id) }, - distanceFormatter = ::formatDistance, - coordsFormatter = ::formatCoords, - rowTextStyle = MaterialTheme.typography.bodyMedium.copy( - color = MaterialTheme.colorScheme.onSurface - ), - header = { - val hasPerms = hasFgLocationPerms() - if (!hasPerms) { - Button(onClick = onRequestPerms) { Text("Begär platstillstånd") } - } - - Row(verticalAlignment = Alignment.CenterVertically) { - Text("Avisera endast nya fynd", modifier = Modifier.weight(1f)) - Switch( - checked = onlyNew, - onCheckedChange = { - onlyNew = it - SettingsStore.setOnlyNewHits(it) - } + }, + isBold = { f -> !FoundStore.isAway(f.layer, f.id) }, + distanceFormatter = ::formatDistance, + coordsFormatter = ::formatCoords, + rowTextStyle = MaterialTheme.typography.bodyMedium.copy( + color = MaterialTheme.colorScheme.onSurface + ), + header = { /* tom i nya layouten */ }, + footer = { /* tom i nya layouten */ } ) } - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Button(onClick = { - if (loggedIn) showWrite = true else showLoginRequired = true - }) { Text("Klottra") } - - Button(onClick = { - nearbyLoading = true + // === NÄRA === + Box( + modifier = Modifier + .fillMaxSize() + .alpha(if (selectedTab == "nearby") 1f else 0f) + .zIndex(if (selectedTab == "nearby") 1f else 0f) + ) { + // Trigga scanning när fliken blir aktiv (och när lager-inställningar ändras) + LaunchedEffect(selectedTab, showKlotter, showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) { + if (selectedTab != "nearby") return@LaunchedEffect + nearbyRefreshing = true nearbyError = null - showNearby = true - scope.launch { - val gp = LocationServiceProvider.get().current(highAccuracy = false) - if (gp == null) { - nearbyLoading = false - nearbyError = "Ingen plats ännu – prova igen." - return@launch - } + + val gp = LocationServiceProvider.get().current(highAccuracy = false) + if (gp == null) { + nearbyLoading = false + nearbyError = "Ingen plats ännu – prova igen." + } else { lastKnownLat = gp.lat lastKnownLon = gp.lon - KLog.d { "Närliggande-debug: toggles klotter=$showKlotter wiki=$showWiki dm=$showDm forn=$showFornsok" } - KLog.d { "Närliggande-debug: loc=${lastKnownLat},${lastKnownLon}" } - - val bundle = withContext(Dispatchers.IO) { + val newBundle = withContext(Dispatchers.IO) { getNearbyBundle( lat = gp.lat, lon = gp.lon, @@ -1020,200 +478,316 @@ fun KlottrAppShell( .filter { it.layer == FoundStore.LAYER_KLOTTER } .associate { it.id to it.label }[id] }, - klotterFetcher = { la, lo -> - Geocache.getNearby( - lat = la, - lon = lo, - radiusMeters = 300, - ttlMs = 0L - ) - }, - wikiFetcher = { la, lo, r -> - Wikipedia.getNearby( - la, - lo, - radiusMeters = r - ) - }, - dmFetcher = { la, lo, r -> - DigitaltMuseum.getNearby( - la, - lo, - radiusMeters = r - ) - }, - fornFetcher = { la, lo, r -> - FornsokShared.getNearby( - la, - lo, - radiusMeters = r - ) - } + klotterFetcher = { la, lo -> Geocache.getNearby(lat = la, lon = lo, radiusMeters = 300, ttlMs = 0L) }, + wikiFetcher = { la, lo, r -> Wikipedia.getNearby(la, lo, radiusMeters = r) }, + dmFetcher = { la, lo, r -> DigitaltMuseum.getNearby(la, lo, radiusMeters = r) }, + fornFetcher = { la, lo, r -> FornsokShared.getNearby(la, lo, radiusMeters = r) } ) } - nearbyBundle = bundle - val nowMillis = Clock.System.now().toEpochMilliseconds() - app.klottr.nearby.markNewFinds( - entries = bundle.entries, // Använd direkt från bundle - nowMillis = nowMillis, - onMarked = { refreshFound() } - ) - - nearbyLoading = false + nearbyBundle = newBundle // uppdatera när klar + nearbyRefreshing = false } - }) { Text("Närliggande") } + } - Button(onClick = { showMap = true }) { Text("Karta") } + // Layout (övre halvan karta, undre halvan lista). Vi ger innerPadding här. + Column(Modifier.fillMaxSize()) { + // Övre halvan: karta (ligger kvar i minnet eftersom hela lagret alltid finns) + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { + MapContent( + onKlotterClick = { id, la, lo, label -> openKlotter = OpenKlotter(id, la, lo, label) }, + onOpenUrl = { title, url -> + when { + url.contains("wikipedia.org") -> { + val pageId = url.substringAfter("curid=").toLongOrNull() + if (pageId != null) { + openWiki = OpenWiki(pageId, null, null) + } else { + AppNavigator.openUrl(url) // fallback + } + } + url.contains("digitaltmuseum.se") -> { + val match = nearbyBundle?.dm?.firstOrNull { + it.webUrl == url || it.url == url + || url.contains(it.id, ignoreCase = true) + } + if (match != null) { + openDm = match + } else { + AppNavigator.openUrl(url) + } + } + url.contains("fornsok") -> { + val match = nearbyBundle?.forn?.firstOrNull { + it.uri == url || it.id == url || it.title == url + || (it.uri != null && url.contains(it.uri!!, ignoreCase = true)) + } + if (match != null) { + openFornsok = OpenFornsok(match) + } else { + AppNavigator.openUrl(url) + } + } + else -> AppNavigator.openUrl(url) + } + }, + onFornsokClick = { item -> + openFornsok = OpenFornsok(item) + }, + isKnownNote = { noteId -> + FoundStore.getAll().any { it.layer == LAYER_KLOTTER && it.id == noteId.toString() } + } + ) + } + + // Undre halvan: närliggande-listan — visa ALLTID senast cachdade data direkt + val hasLocOrCache = + (lastKnownLat != null && lastKnownLon != null) || + (nearbyBundle?.entries?.isNotEmpty() == true || + nearbyBundle?.dm?.isNotEmpty() == true || + nearbyBundle?.forn?.isNotEmpty() == true) + + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { + NearbyContent( + loading = (nearbyBundle == null && nearbyRefreshing), + error = nearbyError, + hasLocation = hasLocOrCache, // undvik "Okänt avstånd"-baneret när cache finns + entries = nearbyBundle?.entries.orEmpty(), + dm = nearbyBundle?.dm.orEmpty(), + forn = nearbyBundle?.forn.orEmpty(), + onOpenAction = { action -> + when (action) { + is FoundOpenAction.Klotter -> openKlotter = OpenKlotter(action.id, action.lat, action.lon, action.label) + is FoundOpenAction.Wiki -> openWiki = OpenWiki(action.pageId, action.lat, action.lon) + is FoundOpenAction.Fornsok -> openFornsok = OpenFornsok(action.item) + is FoundOpenAction.DigitaltMuseum -> openDm = action.item + FoundOpenAction.None -> Unit + } + }, + rowTextStyle = MaterialTheme.typography.bodyMedium.copy( + color = MaterialTheme.colorScheme.onSurface + ) + ) + } + } } - HorizontalDivider() - }, - footer = { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - if (!loggedIn) Button(onClick = onLogin) { Text("Logga in") } - if (loggedIn) Button(onClick = onLogout) { Text("Logga ut") } - } - } - ) - } - } - // Närliggande - if (showNearby) { - NearbyDialog( - loading = nearbyLoading, - error = nearbyError, - lat = lastKnownLat, - lon = lastKnownLon, - // Använd namngivna fält från NearbyBundleShared - entries = nearbyBundle?.entries.orEmpty(), // Ändrad - dm = nearbyBundle?.dm.orEmpty(), // Ändrad - forn = nearbyBundle?.forn.orEmpty(), // Ändrad - - onOpenAction = { action -> - when (action) { - is FoundOpenAction.Klotter -> - openKlotter = OpenKlotter(action.id, action.lat, action.lon, action.label) - is FoundOpenAction.Wiki -> - openWiki = OpenWiki(action.pageId, action.lat, action.lon) - is FoundOpenAction.Fornsok -> - openFornsok = OpenFornsok(action.item) - is FoundOpenAction.DigitaltMuseum -> - openDm = action.item - FoundOpenAction.None -> Unit - } - }, - onClose = { showNearby = false } - ) - } - - // Karta - if (showMap) { - MapDialog( - onClose = { showMap = false }, - onKlotterClick = { id, la, lo, label -> - openKlotter = OpenKlotter(id = id, lat = la, lon = lo, label = label) - }, - onOpenUrl = { _, url -> AppNavigator.openUrl(url) }, - isKnownNote = { noteId -> - // Känd = finns i Hittat (FoundStore) → ska alltid visa titel - FoundStore - .getAll() - .any { it.layer == LAYER_KLOTTER && it.id == noteId.toString() } - } - ) - } - - - // Inställningar - if (showSettings) { - SettingsDialog( - onlyNew = onlyNew, - satellite = satellite, - night = night, - showCoords = showCoords, - - useNewUi = useNewUi, - onUseNewUiChanged = { SettingsStore.setUseNewUi(it); useNewUi = it }, - - // Sparar via KMP SettingsStore no-arg setters (kompat-overloads med Context är utfasade här). - onShowCoordsChanged = { SettingsStore.setShowCoordinates(it); showCoords = it }, - showKlotter = showKlotter, - showWiki = showWiki, - wikiRadius = wikiRadius, - showDm = showDm, - dmRadius = dmRadius, - showFornsok = showFornsok, - fornsokRadius = fornsokRadius, - onOnlyNewChanged = { SettingsStore.setOnlyNewHits(it); onlyNew = it }, - onSatelliteChanged = { SettingsStore.setSatelliteMap(it); satellite = it }, - onNightChanged = { SettingsStore.setNightMode(it); night = it }, - onShowKlotterChanged = { SettingsStore.setShowKlotter(it); showKlotter = it }, - onShowWikiChanged = { SettingsStore.setShowWikipedia(it); showWiki = it }, - onWikiRadiusChanged = { SettingsStore.setWikiRadiusMeters(it); wikiRadius = it }, - onShowDmChanged = { SettingsStore.setShowDigitaltMuseum(it); showDm = it }, - onDmRadiusChanged = { SettingsStore.setDigitaltMuseumRadiusMeters(it); dmRadius = it }, - onShowFornsokChanged = { SettingsStore.setShowFornsok(it); showFornsok = it }, - onFornsokRadiusChanged = { SettingsStore.setFornsokRadiusMeters(it); fornsokRadius = it }, - - onClearFinds = { - FoundStore.clearAll() // Töm allt - forceEmptyFound = true // Visa tomt direkt - refreshFound() // Tvinga omritning - - // Clear session + notify via shared events (handled in platform location impl) - FoundStore.clearAll(); - FoundEvents.notifyFoundUpdated() -// // 1) Nollställ sessions-gates inne i tjänsten -// context.startService( -// Intent(context, LocationService::class.java) -// .setAction(LocationService.ACTION_CLEAR_FOUND_SESSION) -// ) -// -// // 2) Pinga UI:t att rita om (nollat läge) -// context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED)) - - // 3) Be tjänsten göra en rescan - // old Android service call removed (handled in shared layer) - - // 4) Gör även en direkt lokal scan nu (parallellt) → snabb UI-återfyllnad - // Använder vår delade scanAndMarkFound så listan fylls utan att vänta på tjänsten. - val cfg = ScanConfig( - showWiki = showWiki, - wikiRadius = wikiRadius, - showDm = showDm, - dmRadius = dmRadius, - showFornsok = showFornsok, - fornsokRadius = fornsokRadius - ) - scope.launch { - val gp = LocationServiceProvider.get().current(highAccuracy = false) - if (gp != null) { - val anyNew = withContext(Dispatchers.IO) { - scanAndMarkFound( - lat = gp.lat, lon = gp.lon, - config = cfg, - fetchWiki = { la, lo, r -> Wikipedia.getNearby(la, lo, radiusMeters = r) }, - fetchDm = { la, lo, r -> DigitaltMuseum.getNearby(la, lo, radiusMeters = r) }, - fetchFornsok = { la, lo, r -> FornsokShared.getNearby(la, lo, radiusMeters = r) }, - markFound = { layer, id, label, la, lo, now -> - FoundStore.markFound(layer, id, label, la, lo, now) - }, - updateAwayFlags = { la, lo -> - FoundStore.updateAwayFlags(la, lo) - } + // === MENY === + Box( + modifier = Modifier + .fillMaxSize() + .alpha(if (selectedTab == "menu") 1f else 0f) + .zIndex(if (selectedTab == "menu") 1f else 0f) + ) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + ) { + Text( + "Meny", + style = MaterialTheme.typography.headlineMedium, + modifier = Modifier.padding(16.dp) ) - } - if (anyNew) { - forceEmptyFound = false // Tillåt visning igen - refreshFound() // Rita om “Senaste” - /* notify listeners inline: refreshFound() already called */ + LazyVerticalGrid( + columns = GridCells.Fixed(3), + modifier = Modifier + .fillMaxSize() + .padding(8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp) + ) { + items( + listOf( + Triple(Icons.Filled.Settings, "Inställningar") { selectedTab = "settings" }, + Triple(Icons.Filled.Info, "Om") { selectedTab = "about" }, + Triple(Icons.Filled.Person, "Konto") { selectedTab = "account" }, + Triple(Icons.Filled.Bookmark, "Bokmärken") { }, + Triple(Icons.Filled.Create, "Mitt klotter") { }, + Triple( + Icons.Filled.Login, + if (loggedIn) "Logga ut" else "Logga in" + ) { + if (loggedIn) onLogout() else onLogin() + } + ) + ) { (icon, label, action) -> + MenuTile(icon = icon, label = label, onClick = action) + } + } } } + // === KONTO === + Box( + modifier = Modifier + .fillMaxSize() + .alpha(if (selectedTab == "account") 1f else 0f) + .zIndex(if (selectedTab == "account") 1f else 0f) + ) { + LaunchedEffect(selectedTab, loggedIn) { + if (selectedTab != "account") return@LaunchedEffect + if (!loggedIn) { + me = null + userStats = null + return@LaunchedEffect + } + me = withContext(Dispatchers.IO) { fetchMe() } + // Hämta färsk statistik + userStats = withContext(Dispatchers.IO) { fetchUserStats() } + } + AccountScreen( + me = me, + userStats = userStats, + onLogin = { onLogin() }, + onLogout = { + onLogout() + selectedTab = "menu" + }, + onDeleteAccount = { + selectedTab = "menu" + }, + onChangeUsername = { showChangeUsernameDialog = true }, + modifier = Modifier.padding(innerPadding) + ) + } + if (showChangeUsernameDialog) { + var newName by remember { mutableStateOf("") } + var errorText by remember { mutableStateOf(null) } + var saving by remember { mutableStateOf(false) } + val scope = rememberCoroutineScope() + + AlertDialog( + onDismissRequest = { if (!saving) showChangeUsernameDialog = false }, + title = { + Column { + Text("Byt användarnamn", style = MaterialTheme.typography.titleLarge) + Spacer(Modifier.height(4.dp)) + Text( + "Efter att du har bytt kan du inte byta igen förrän om tre månader.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + value = newName, + onValueChange = { newName = it; errorText = null }, + label = { Text("Nytt användarnamn") }, + singleLine = true, + enabled = !saving, + modifier = Modifier.fillMaxWidth() + ) + if (errorText != null) { + Text(errorText!!, color = MaterialTheme.colorScheme.error) + } + } + }, + confirmButton = { + TextButton( + enabled = !saving && newName.isNotBlank(), + onClick = { + saving = true + scope.launch { + val resp = setUsernameRemote(newName) + if (resp == null) { + errorText = "Nätverksfel" + saving = false + return@launch + } + if (resp.ok) { + // Uppdatera me från servern + me = withContext(Dispatchers.IO) { fetchMe() } + showChangeUsernameDialog = false + saving = false + } else { + errorText = when (resp.reason) { + "invalid" -> "Ogiltigt användarnamn" + "taken" -> "Användarnamnet är upptaget" + "reserved" -> "Nyligen använt, reserverat i 6 månader" + "too_soon" -> "Du måste vänta innan du kan byta igen" + "already_set" -> "Du har redan ett användarnamn" + else -> "Fel: ${resp.reason}" + } + saving = false + } + } + } + ) { + Text("Spara") + } + }, + dismissButton = { + TextButton(onClick = { if (!saving) showChangeUsernameDialog = false }) { + Text("Avbryt") + } + } + ) + } + // === ABOUT === + Box( + modifier = Modifier + .fillMaxSize() + .alpha(if (selectedTab == "about") 1f else 0f) + .zIndex(if (selectedTab == "about") 1f else 0f) + ) { + AboutScreen( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = 16.dp, vertical = 0.dp) // egen padding, ingen top-padding + ) + } + // === SETTINGS === + Box( + modifier = Modifier + .fillMaxSize() + .alpha(if (selectedTab == "settings") 1f else 0f) + .zIndex(if (selectedTab == "settings") 1f else 0f) + ) { + SettingsScreen( + onlyNew = onlyNew, + satellite = satellite, + night = night, + showCoords = showCoords, + onShowCoordsChanged = { SettingsStore.setShowCoordinates(it); showCoords = it }, + useNewUi = useNewUi, + onUseNewUiChanged = { SettingsStore.setUseNewUi(it); useNewUi = it }, + showKlotter = showKlotter, + showWiki = showWiki, + wikiRadius = wikiRadius, + showDm = showDm, + dmRadius = dmRadius, + showFornsok = showFornsok, + fornsokRadius = fornsokRadius, + onOnlyNewChanged = { SettingsStore.setOnlyNewHits(it); onlyNew = it }, + onSatelliteChanged = { SettingsStore.setSatelliteMap(it); satellite = it }, + onNightChanged = { SettingsStore.setNightMode(it); night = it }, + onShowKlotterChanged = { SettingsStore.setShowKlotter(it); showKlotter = it }, + onShowWikiChanged = { SettingsStore.setShowWikipedia(it); showWiki = it }, + onWikiRadiusChanged = { SettingsStore.setWikiRadiusMeters(it); wikiRadius = it }, + onShowDmChanged = { SettingsStore.setShowDigitaltMuseum(it); showDm = it }, + onDmRadiusChanged = { SettingsStore.setDigitaltMuseumRadiusMeters(it); dmRadius = it }, + onShowFornsokChanged = { SettingsStore.setShowFornsok(it); showFornsok = it }, + onFornsokRadiusChanged = { SettingsStore.setFornsokRadiusMeters(it); fornsokRadius = it }, + onClearFinds = { + FoundStore.clearAll() + forceEmptyFound = true + refreshFound() + FoundEvents.notifyFoundUpdated() + }, + modifier = Modifier + .fillMaxSize() + .padding( + start = 16.dp, + end = 16.dp, + top = innerPadding.calculateTopPadding(), // 👈 respektera AppBar + bottom = innerPadding.calculateBottomPadding() + ) + ) + } } - UiFeedback.showMessage( "Alla fynd rensade.", UiFeedbackDuration.SHORT) - }, - onClose = { showSettings = false } + } ) } @@ -1259,7 +833,6 @@ fun KlottrAppShell( ) } - // Skrivdialog (dokument) var isSavingDoc by remember { mutableStateOf(false) } if (showWrite) { @@ -1553,21 +1126,6 @@ fun KlottrAppShell( } } -@Composable -private fun MenuItem(icon: ImageVector, label: String, onClick: () -> Unit) { - Button( - onClick = onClick, - modifier = Modifier.fillMaxWidth().height(64.dp) - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp) - ) { - Icon(icon, contentDescription = label) - Text(label) - } - } -} @Composable private fun MenuTile(icon: ImageVector, label: String, onClick: () -> Unit) { diff --git a/shared/src/commonMain/kotlin/app/klottr/SettingsDialog.kt b/shared/src/commonMain/kotlin/app/klottr/SettingsDialog.kt index e7f1fd4..c674775 100644 --- a/shared/src/commonMain/kotlin/app/klottr/SettingsDialog.kt +++ b/shared/src/commonMain/kotlin/app/klottr/SettingsDialog.kt @@ -24,107 +24,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.window.DialogProperties import app.klottr.ui.SettingsContent -/* ---------- Inställningar (scroll + “Stäng” synlig) ---------- */ - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun SettingsDialog( - onlyNew: Boolean, - satellite: Boolean, - night: Boolean, - showCoords: Boolean, - onShowCoordsChanged: (Boolean) -> Unit, - useNewUi: Boolean, - onUseNewUiChanged: (Boolean) -> Unit, - showKlotter: Boolean, - showWiki: Boolean, - wikiRadius: Int, - showDm: Boolean, - dmRadius: Int, - showFornsok: Boolean, - fornsokRadius: Int, - onOnlyNewChanged: (Boolean) -> Unit, - onSatelliteChanged: (Boolean) -> Unit, - onNightChanged: (Boolean) -> Unit, - onShowKlotterChanged: (Boolean) -> Unit, - onShowWikiChanged: (Boolean) -> Unit, - onWikiRadiusChanged: (Int) -> Unit, - onShowDmChanged: (Boolean) -> Unit, - onDmRadiusChanged: (Int) -> Unit, - onShowFornsokChanged: (Boolean) -> Unit, - onFornsokRadiusChanged: (Int) -> Unit, - onClearFinds: () -> Unit, - onClose: () -> Unit -) { - val maxDialogHeight = (LocalWindowInfo.current.containerSize.height.dp * 0.75f) - - val wikiOptions = listOf(20, 50, 100, 200, 500, 1000, 2000, 5000) - val fornsokOptions = listOf(50, 100, 200, 500, 1000, 2000, 5000) - val dmOptions = listOf(50, 100, 200, 500, 1000, 2000) - - var askClear by remember { mutableStateOf(false) } - - AlertDialog( - onDismissRequest = onClose, - properties = DialogProperties(usePlatformDefaultWidth = false), - title = { Text("Inställningar") }, - text = { - Box( - Modifier - .fillMaxWidth() - .height(maxDialogHeight) - ) { - SettingsContent( - versionLine = "FIXME_VERSIONLINE", // TODO: OH: Do this platform independenlty - buildTimeLine = "FIXME_BUILDTIME", - onlyNew = onlyNew, - onOnlyNewChanged = onOnlyNewChanged, - showCoords = showCoords, - onShowCoordsChanged = onShowCoordsChanged, - satellite = satellite, - onSatelliteChanged = onSatelliteChanged, - night = night, - onNightChanged = onNightChanged, - useNewUi = useNewUi, - onUseNewUiChanged = onUseNewUiChanged, - showKlotter = showKlotter, - onShowKlotterChanged = onShowKlotterChanged, - showWiki = showWiki, - wikiRadius = wikiRadius, - wikiOptions = listOf(20, 50, 100, 200, 500, 1000, 2000, 5000), - onShowWikiChanged = onShowWikiChanged, - onWikiRadiusChanged = onWikiRadiusChanged, - showDm = showDm, - dmRadius = dmRadius, - dmOptions = listOf(50, 100, 200, 500, 1000, 2000), - onShowDmChanged = onShowDmChanged, - onDmRadiusChanged = onDmRadiusChanged, - showFornsok = showFornsok, - fornsokRadius = fornsokRadius, - fornsokOptions = listOf(50, 100, 200, 500, 1000, 2000, 5000), - onShowFornsokChanged = onShowFornsokChanged, - onFornsokRadiusChanged = onFornsokRadiusChanged, - onRequestClear = { askClear = true }, // trigga bekräftelsedialog - rowTextStyle = MaterialTheme.typography.bodyMedium.copy( - color = MaterialTheme.colorScheme.onSurface - ) - ) - - // Behåll den inre bekräftelsedialogen för rensning - if (askClear) { - AlertDialog( - onDismissRequest = { askClear = false }, - title = { Text("Radera historik?") }, - text = { Text("Vill du verkligen radera alla fynd? Detta går inte att ångra.") }, - confirmButton = { Button(onClick = { askClear = false; onClearFinds() }) { Text("Ja, radera") } }, - dismissButton = { Button(onClick = { askClear = false }) { Text("Avbryt") } } - ) - } - } - }, - confirmButton = { Button(onClick = onClose) { Text("Stäng") } } - ) -} +/* ---------- Inställningar ---------- */ @Composable fun SettingsScreen( diff --git a/shared/src/commonMain/kotlin/app/klottr/ui/CommonDialogsShell.kt b/shared/src/commonMain/kotlin/app/klottr/ui/CommonDialogsShell.kt index b3c59a7..99db707 100644 --- a/shared/src/commonMain/kotlin/app/klottr/ui/CommonDialogsShell.kt +++ b/shared/src/commonMain/kotlin/app/klottr/ui/CommonDialogsShell.kt @@ -60,65 +60,6 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -/* ---------- Nearby (shared) ---------- */ - -@Composable -fun NearbyDialog( - loading: Boolean, - error: String?, - lat: Double?, - lon: Double?, - entries: List, - dm: List, - forn: List, - onOpenAction: (FoundOpenAction) -> Unit, - onClose: () -> Unit, - /** Optional max content height; if null, content becomes scrollable. */ - maxHeight: Dp? = null -) { - AlertDialog( - onDismissRequest = onClose, - title = { Text("Närliggande") }, - text = { - val hasLocation = (lat != null && lon != null) - - // Cap to caller-provided height or ~75% of the real screen height (platform-agnostic). - val percentageCap = (platformScreenHeightDp() * 0.75f) - val cap = (maxHeight ?: percentageCap).coerceAtLeast(320.dp) - - val container = @Composable { inner: @Composable () -> Unit -> - // Bound the height BEFORE measuring child content; do NOT add verticalScroll here. - Box( - Modifier - .widthIn(min = 280.dp) - .requiredHeightIn(max = cap) - ) { - // Let inner content (NearbyList) own scrolling; fill available space. - Column(Modifier.fillMaxSize()) { inner() } - } - } - - NearbyDialogContent(maxHeight = cap) { - container { - NearbyContent( - loading = loading, - error = error, - hasLocation = hasLocation, - entries = if (hasLocation) entries else emptyList(), - dm = dm, - forn = forn, - onOpenAction = onOpenAction, - rowTextStyle = MaterialTheme.typography.bodyMedium.copy( - color = MaterialTheme.colorScheme.onSurface - ) - ) - } - } - }, - confirmButton = { Button(onClick = onClose) { Text("Stäng") } } - ) -} - /* ---------- Username (shared) ---------- */ @Composable @@ -283,100 +224,6 @@ fun UsernameDialog( } } -/* ---------- About (shared, platform-fed) ---------- */ - -@Composable -fun AboutDialog(onDismiss: () -> Unit) { - val info = remember { appAboutInfo() } // platform provides - AlertDialog( - onDismissRequest = onDismiss, - properties = DialogProperties(usePlatformDefaultWidth = false), - confirmButton = { TextButton(onClick = onDismiss) { Text("Stäng") } }, - text = { - Box( - Modifier - .fillMaxWidth() - .widthIn(max = 520.dp) - ) { - KlottrAboutContent( - header = { - KlottrLogo(modifier = Modifier.height(48.dp)) - }, - lines = listOf( - "Version ${info.versionName} (${info.buildType}) • build ${info.buildNumber}", - "Byggd ${info.buildTimeUtc}", - "Utvecklad av ${info.devBy}.", - "IOS-ansvarig: ${info.iosLead}.", - "Mejlkontakt: ${info.contactEmail}" - ), - lineStyle = MaterialTheme.typography.bodyMedium.copy( - color = MaterialTheme.colorScheme.onSurface - ), - spacingDp = 12 - ) - } - } - ) -} - -/* ---------- Image viewer (shared, byte[] + Coil KMP, pinch/zoom) ---------- */ - -@Composable -fun ImageViewerDialog( - bytes: ByteArray, - mimeType: String? = null, - onClose: () -> Unit -) { - Dialog( - onDismissRequest = onClose, - properties = DialogProperties(usePlatformDefaultWidth = false) - ) { - Box( - modifier = Modifier - .fillMaxSize() - .background(Color.Black) - ) { - var scale by remember { mutableStateOf(1f) } - var offset by remember { mutableStateOf(Offset.Zero) } - - AsyncImage( - model = ImageRequest.Builder(LocalPlatformContext.current) - .data(bytes) - .build(), - contentDescription = null, - modifier = Modifier - .fillMaxSize() - .clipToBounds() - .pointerInput(Unit) { - detectTransformGestures { _, pan, zoom, _ -> - scale = (scale * zoom).coerceIn(0.5f, 6f) - offset += pan - val clamp = 2000f - offset = Offset( - x = offset.x.coerceIn(-clamp, clamp), - y = offset.y.coerceIn(-clamp, clamp) - ) - } - } - .graphicsLayer( - scaleX = scale, - scaleY = scale, - translationX = offset.x, - translationY = offset.y - ) - ) - - Box( - modifier = Modifier - .align(Alignment.TopEnd) - .padding(12.dp) - ) { - Button(onClick = onClose) { Text("Stäng") } - } - } - } -} - @Composable fun AboutScreen(modifier: Modifier = Modifier) { val info = remember { appAboutInfo() } // platform provides