diff --git a/app/src/main/java/app/klottr/MainActivity.kt b/app/src/main/java/app/klottr/MainActivity.kt index d962f93..e3b15a0 100644 --- a/app/src/main/java/app/klottr/MainActivity.kt +++ b/app/src/main/java/app/klottr/MainActivity.kt @@ -142,6 +142,7 @@ import app.klottr.ui.FornsokDetailContent // Ny: delad Fornsök-layout import app.klottr.ui.FoundList // Delad, material-fri listkomponent för "Hittat" import app.klottr.ui.FoundContent // Delat innehåll för “Hittat” import app.klottr.ui.FoundDetailContent // Delad detalj-UI (CMP) +import app.klottr.ui.KlottrHomeContent // Ny: delat mittinnehåll import app.klottr.ui.NearbyContent // Delat material-fritt innehåll för Närliggande import app.klottr.ui.MapPanelShell import app.klottr.ui.SettingsContent // Delad material-fri UI för inställningar @@ -595,236 +596,209 @@ private fun KlottrApp( ) } ) { padding -> - Column( - Modifier - .fillMaxSize() - .padding(padding) - .padding(12.dp), - verticalArrangement = Arrangement.spacedBy(12.dp) - ) { - val hasPerms = hasFgLocationPerms(context) - if (!hasPerms) { - Button(onClick = onRequestPerms) { Text("Begär platstillstånd") } - } + // --- Nytt: definiera listan + overrides före UI-anropet --- + val foundList = remember(foundRefresh, forceEmptyFound) { + if (forceEmptyFound) emptyList() else FoundStore.getAll(context) + } + val labelOverrides = remember { androidx.compose.runtime.mutableStateMapOf() } + val foundKey = foundList.joinToString("|") { "${it.layer}:${it.id}" } - Row(verticalAlignment = Alignment.CenterVertically) { - Text("Avisera endast nya fynd", modifier = Modifier.weight(1f)) - Switch( - checked = onlyNew, - onCheckedChange = { - onlyNew = it - SettingsStore.setOnlyNewHits(it) - } - ) - } - - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Button(onClick = { - if (loggedIn) showWrite = true else showLoginRequired = true - }) { Text("Klottra") } - - Button(onClick = { - nearbyLoading = true - nearbyError = null - showNearby = true - val ctx = context - scope.launch { - val gp = AndroidLocationProvider.currentOrLastKnown(ctx) // Nytt: centraliserad plats - if (gp == null) { - nearbyLoading = false - nearbyError = "Ingen plats ännu – prova igen." - return@launch - } - lastKnownLat = gp.lat // Nytt - lastKnownLon = gp.lon // Nytt - - KLog.d { "Närliggande-debug: toggles klotter=$showKlotter wiki=$showWiki dm=$showDm forn=$showFornsok"} - KLog.d { "Närliggande-debug: loc=${lastKnownLat},${lastKnownLon}"} - - // Re-arm: markera alla tidigare fynd som "borta" om vi nu står >200 m från dem - // Hämta alla lager via delad KMP-funktion (DI med våra befintliga klientanrop) - // [ÄNDRAD] Kör delad use-case som både hämtar och bygger entries - val bundle = 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 -> - // [NY] samma källor för “känd etikett” som du redan använde i dialogen - FoundStore.getAll(context) - .asSequence() - .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 -> Fornsok.getNearby(la, lo, radiusMeters = r) } - ) - } - - // [NY] Sätt färdiga entries + listor som behövs för öppna-aktioner - nearbyEntries = bundle.entries - nearbyDm = bundle.dm - nearbyFornsok = bundle.forn - // [NY] Markera nya fynd direkt här (inte i dialogen) - val nowMillis = System.currentTimeMillis() // [NY] - app.klottr.nearby.markNewFinds( // [NY] (fullt kvalificerat anrop, ingen extra import) - ctx = ctx, // [NY] - entries = nearbyEntries, // [NY] - nowMillis = nowMillis, // [NY] - onMarked = { refreshFound() } // [NY] trigga samma uppdatering som tidigare - ) - - // [VALFRITT] Logg – nu summerar vi entries + per-lager - KLog.d { - "Närliggande-resultat: entries=${nearbyEntries.size}, dm=${nearbyDm.size}, forn=${nearbyFornsok.size}" - } - - nearbyLoading = false - } - }) { Text("Närliggande") } - - Button(onClick = { showMap = true }) { Text("Karta") } - } - - HorizontalDivider() // Avdelare under knappraden - - MapPanelShell( - modifier = Modifier - .fillMaxWidth() - .weight(1f), - title = "Senaste", - titleTextStyle = MaterialTheme.typography.titleLarge.copy( - color = MaterialTheme.colorScheme.onSurface - ), - mainContent = { - // Hittat (flyttat hit för att kapslas i skalet) - // Hittat – bind till refreshflaggan så UI uppdaterar direkt - val foundList = remember(foundRefresh, forceEmptyFound) { // Trigga om vid foundRefresh/clear - if (forceEmptyFound) emptyList() else FoundStore.getAll(context) // Hämta aktuell lista - } - - val labelOverrides = remember { androidx.compose.runtime.mutableStateMapOf() } - - val foundKey = foundList.joinToString("|") { "${it.layer}:${it.id}" } - - // Förbättra etiketter och förladda detaljer/bilder när innehållet ändras - LaunchedEffect(foundKey) { - val my = LastLocationStore.lastKnownLocation - val myLat = my?.latitude - val myLon = my?.longitude - 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(img.id, detail.id, f.lat, f.lon)?.let { bytes -> - val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) - if (bmp != null) { - ImageBitmapCache.put(img.id, bmp) - } - } - } + // Förladdning av etiketter/bilder (oförändrad logik, flyttad hit) + LaunchedEffect(foundKey) { + val my = LastLocationStore.lastKnownLocation + val myLat = my?.latitude + val myLon = my?.longitude + 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(img.id, detail.id, f.lat, f.lon)?.let { bytes -> + val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) + if (bmp != null) { + ImageBitmapCache.put(img.id, bmp) } } } } - 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 - } } } } - val my = LastLocationStore.lastKnownLocation // Ny: Flytta upp så FoundContent alltid ritas - val _tick = locationTick // Ny: Behåll trigger - - FoundContent( - entries = foundList, - currentLat = my?.latitude, - currentLon = my?.longitude, - 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 { Fornsok.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 - } + val enriched = withContext(Dispatchers.IO) { + enrichKlotterLabels( + found = foundList, + radiusMeters = 60, + fetchNearbyKlotter = { la, lo, r -> + Geocache.getNearby(lat = la, lon = lo, radiusMeters = r, ttlMs = 0L) } - }, - isBold = { f -> !FoundStore.isAway(context, f.layer, f.id) }, - distanceFormatter = ::formatDistance, - coordsFormatter = ::formatCoords, - rowTextStyle = MaterialTheme.typography.bodyMedium.copy( - color = MaterialTheme.colorScheme.onSurface ) - ) - }, - footerContent = { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - if (!loggedIn) Button(onClick = onLogin) { Text("Logga in") } - if (loggedIn) Button(onClick = onLogout) { Text("Logga ut") } + } + for ((k, v) in enriched) { + labelOverrides[k] = v } } - ) + } } + + // --- Nytt: KlottrHomeContent (delat mitt-innehåll) --- + KlottrHomeContent( + contentPadding = padding, + entries = foundList, + currentLat = LastLocationStore.lastKnownLocation?.latitude, + currentLon = LastLocationStore.lastKnownLocation?.longitude, + 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 { Fornsok.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(context, f.layer, f.id) }, + distanceFormatter = ::formatDistance, + coordsFormatter = ::formatCoords, + rowTextStyle = MaterialTheme.typography.bodyMedium.copy( + color = MaterialTheme.colorScheme.onSurface + ), + header = { + val hasPerms = hasFgLocationPerms(context) + 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) + } + ) + } + + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button(onClick = { + if (loggedIn) showWrite = true else showLoginRequired = true + }) { Text("Klottra") } + + Button(onClick = { + nearbyLoading = true + nearbyError = null + showNearby = true + val ctx = context + scope.launch { + val gp = AndroidLocationProvider.currentOrLastKnown(ctx) + if (gp == null) { + nearbyLoading = false + nearbyError = "Ingen plats ännu – prova igen." + return@launch + } + 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) { + 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(context) + .asSequence() + .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 -> Fornsok.getNearby(la, lo, radiusMeters = r) } + ) + } + + nearbyEntries = bundle.entries + nearbyDm = bundle.dm + nearbyFornsok = bundle.forn + + val nowMillis = System.currentTimeMillis() + app.klottr.nearby.markNewFinds( + ctx = ctx, + entries = nearbyEntries, + nowMillis = nowMillis, + onMarked = { refreshFound() } + ) + + KLog.d { + "Närliggande-resultat: entries=${nearbyEntries.size}, dm=${nearbyDm.size}, forn=${nearbyFornsok.size}" + } + + nearbyLoading = false + } + }) { Text("Närliggande") } + + Button(onClick = { showMap = true }) { Text("Karta") } + } + + HorizontalDivider() + }, + footer = { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (!loggedIn) Button(onClick = onLogin) { Text("Logga in") } + if (loggedIn) Button(onClick = onLogout) { Text("Logga ut") } + } + } + ) } // Om-appen if (showAbout) { diff --git a/shared/src/commonMain/kotlin/app/klottr/ui/KlottrHomeContent.kt b/shared/src/commonMain/kotlin/app/klottr/ui/KlottrHomeContent.kt new file mode 100644 index 0000000..d6bf84c --- /dev/null +++ b/shared/src/commonMain/kotlin/app/klottr/ui/KlottrHomeContent.kt @@ -0,0 +1,58 @@ +package app.klottr.ui + +import androidx.compose.foundation.layout.* +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.unit.dp // För .dp i padding/spacedBy +import app.klottr.util.FoundEntry + +@Composable +fun KlottrHomeContent( + contentPadding: PaddingValues, + // FoundContent-parametrar (delat) + entries: List, + currentLat: Double?, + currentLon: Double?, + showCoords: Boolean, + labelOverrides: Map, + isClickable: (FoundEntry) -> Boolean, + onEntryClick: (FoundEntry) -> Unit, + isBold: (FoundEntry) -> Boolean, + distanceFormatter: (Int) -> String, + coordsFormatter: (Double, Double) -> String, + rowTextStyle: TextStyle, + // Slots från Android (Material-komponenter placeras här) + header: @Composable ColumnScope.() -> Unit, + footer: @Composable () -> Unit +) { + Column( + Modifier + .fillMaxSize() + .padding(contentPadding) + .padding(12.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + header() + Box( + Modifier + .fillMaxSize() + .weight(1f) // Låt innehållet ta resten av höjden så footern syns + ) { + FoundContent( + entries = entries, + currentLat = currentLat, + currentLon = currentLon, + showCoords = showCoords, + labelOverrides = labelOverrides, + isClickable = isClickable, + onEntryClick = onEntryClick, + isBold = isBold, + distanceFormatter = distanceFormatter, + coordsFormatter = coordsFormatter, + rowTextStyle = rowTextStyle + ) + } + footer() + } +}