diff --git a/shared/src/commonMain/kotlin/app/klottr/KlottrAppShell.kt b/shared/src/commonMain/kotlin/app/klottr/KlottrAppShell.kt index b120807..4d18793 100644 --- a/shared/src/commonMain/kotlin/app/klottr/KlottrAppShell.kt +++ b/shared/src/commonMain/kotlin/app/klottr/KlottrAppShell.kt @@ -1,8 +1,13 @@ package app.klottr import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.Orientation +import androidx.compose.foundation.gestures.draggable +import androidx.compose.foundation.gestures.rememberDraggableState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -16,6 +21,7 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Bookmark @@ -37,6 +43,7 @@ import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CenterAlignedTopAppBar +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.HorizontalDivider @@ -48,6 +55,7 @@ import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField 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 @@ -63,9 +71,15 @@ 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.draw.clip import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup 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) @@ -80,6 +94,7 @@ import app.klottr.location.LastLocationStore import app.klottr.location.LocationServiceProvider import app.klottr.nearby.FoundOpenAction import app.klottr.nearby.NearbyBundleShared +import app.klottr.nearby.NearbyEntryShared import app.klottr.nearby.OpenFornsok import app.klottr.nearby.OpenKlotter import app.klottr.nearby.OpenWiki @@ -88,6 +103,7 @@ import app.klottr.nearby.getNearbyBundle import app.klottr.nearby.resolveFoundOpenAction import app.klottr.nearby.scanAndMarkFound import app.klottr.net.Api +import app.klottr.net.NoteDTO import app.klottr.net.DigitaltMuseum import app.klottr.net.DigitaltMuseumItem import app.klottr.net.FornsokShared @@ -97,6 +113,7 @@ import app.klottr.net.Wikipedia import app.klottr.net.createNoteDoc import app.klottr.net.fetchMe import app.klottr.net.fetchNoteDetail +import app.klottr.net.fetchUserNotes import app.klottr.net.fetchUserStats import app.klottr.net.setUsernameRemote import app.klottr.net.uploadImage @@ -121,8 +138,10 @@ import app.klottr.util.NoteDetailCache import app.klottr.util.OutboxStore import app.klottr.util.SettingsStore import app.klottr.util.UUID +import app.klottr.util.distanceMeters import app.klottr.util.formatCoords import app.klottr.util.formatDistance +import app.klottr.util.parseIsoToEpochMsOrNull import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.launch @@ -209,6 +228,12 @@ fun KlottrAppShell( var lastKnownLat by remember { mutableStateOf(null) } var lastKnownLon by remember { mutableStateOf(null) } + var myNotesLoading by remember { mutableStateOf(false) } + var myNotesError by remember { mutableStateOf(null) } + var myNotesEtag by remember { mutableStateOf(null) } + var myNotesEntries by remember { mutableStateOf(listOf()) } + var myNotesRaw by remember { mutableStateOf>(emptyList()) } + // Klotter-detalj var openKlotter by remember {mutableStateOf(null) } // Wiki-detalj @@ -348,7 +373,7 @@ fun KlottrAppShell( }, floatingActionButtonPosition = androidx.compose.material3.FabPosition.Center, content = { innerPadding -> - if (selectedTab !in listOf("home", "nearby", "menu", "account", "about", "settings")) { + if (selectedTab !in listOf("home", "nearby", "menu", "account", "about", "settings", "mynotes")) { selectedTab = "home" } // VIKTIGT: vi komponerar ALLA flikar alltid, och växlar bara synlighet. @@ -446,6 +471,8 @@ fun KlottrAppShell( .alpha(if (selectedTab == "nearby") 1f else 0f) .zIndex(if (selectedTab == "nearby") 1f else 0f) ) { + var nearbySplit by rememberSaveable { mutableStateOf(0.5f) } + // 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 @@ -484,92 +511,97 @@ fun KlottrAppShell( 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. + + // Layout: dragbar delare mellan karta (top) och lista (bottom) 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 + // hasLocOrCache måste ligga kvar här om du använde det innan: 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 - ) - ) - } + SplitPaneVertical( + split = nearbySplit, + onSplitChange = { value -> nearbySplit = value }, + handleHeight = 18.dp, + top = { + Box(Modifier.fillMaxSize()) { + 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() } + } + ) + } + }, + bottom = { + Box(Modifier.fillMaxSize()) { + NearbyContent( + loading = (nearbyBundle == null && nearbyRefreshing), + error = nearbyError, + hasLocation = hasLocOrCache, + 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 === @@ -603,7 +635,7 @@ fun KlottrAppShell( 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.Create, "Mitt klotter") { selectedTab = "mynotes"}, Triple( Icons.Filled.Login, if (loggedIn) "Logga ut" else "Logga in" @@ -725,6 +757,178 @@ fun KlottrAppShell( } ) } + // === MITT KLOTTER === +// if (selectedTab == "mynotes" ) +// { + Box( + modifier = Modifier + .fillMaxSize() + .alpha(if (selectedTab == "mynotes") 1f else 0f) + .zIndex(if (selectedTab == "mynotes") 1f else 0f) + ) { + // Ladda mina klotter när fliken blir aktiv (och när login ändras) + LaunchedEffect(selectedTab, loggedIn, currentUserId) { + if (selectedTab != "mynotes") return@LaunchedEffect + + if (!loggedIn || currentUserId == null) { + myNotesLoading = false + myNotesError = "Logga in för att se ditt klotter." + myNotesEntries = emptyList() + return@LaunchedEffect + } + + myNotesLoading = true + myNotesError = null + + // Försök få en position (för att kunna visa avstånd), men listan visas ändå utan filter + val gp = LocationServiceProvider.get().current(highAccuracy = false) + if (gp != null) { + lastKnownLat = gp.lat + lastKnownLon = gp.lon + } + + // Lägg detta precis innan withContext-blocket: + val uid = currentUserId ?: run { + myNotesLoading = false + myNotesError = "Logga in för att se ditt klotter." + myNotesEntries = emptyList() + return@LaunchedEffect + } + + // Anropa API:t med en icke-null lokal variabel (undviker delegated smart-cast-problem) + val res = withContext(Dispatchers.IO) { + fetchUserNotes( + userId = uid, + sinceMs = 0, + lastEtag = myNotesEtag, + limit = 500 + ) + } + + if (res.code == 0) { + // Nätmiss – behåll tidigare myNotesRaw och entries oförändrade + myNotesLoading = false + myNotesError = "Nätverksfel – försök igen." + return@LaunchedEffect + } + if (res.code == 304) { + // Oförändrat – behåll tidigare myNotesRaw och entries + myNotesLoading = false + return@LaunchedEffect + } + + // Endast vid 200 uppdaterar vi rådatan och bygger om listan/kartan + myNotesRaw = res.items + + // Bygg listposter från res.items + val creator = me?.username + val entries = res.items.map { n -> + val dist = if (lastKnownLat != null && lastKnownLon != null) { + distanceMeters(lastKnownLat!!, lastKnownLon!!, n.a, n.o).toInt() + } else 0 + val updatedMs = parseIsoToEpochMsOrNull(n.u) ?: n.c + NearbyEntryShared( + layer = FoundStore.LAYER_KLOTTER, + id = n.i.toString(), + label = n.t, + lat = n.a, lon = n.o, + distanceM = dist, + insideRadiusM = 0, + //insideRadiusM = Int.MAX_VALUE, // Ingen gräns: allt är “inom” + + updatedAtMs = updatedMs, + creatorUsername = creator + ) + }.sortedBy { it.distanceM } + + entries.forEach { e -> + val ts = e.updatedAtMs ?: app.klottr.util.nowEpochMs() + app.klottr.util.FoundStore.markFound( + layer = app.klottr.util.FoundStore.LAYER_KLOTTER, + id = e.id ?: return@forEach, + label = e.label, + lat = e.lat, + lon = e.lon, + timeMillis = ts + ) + } + + myNotesEntries = entries + myNotesEtag = res.etag + } + + var myNotesSplit by rememberSaveable { mutableStateOf(0.5f) } + + // Layout: övre halvan karta, undre halvan lista (samma som "Nära") + Column(Modifier.fillMaxSize().padding(innerPadding)) { + SplitPaneVertical( + split = myNotesSplit, + onSplitChange = { myNotesSplit = it }, + handleHeight = 18.dp, + top = { + Box(Modifier.fillMaxSize()) { + MapContent( + onKlotterClick = { id, la, lo, label -> openKlotter = OpenKlotter(id, la, lo, label) }, + onOpenUrl = { title, url -> AppNavigator.openUrl(url) }, + onFornsokClick = { _ -> }, + isKnownNote = { noteId -> + FoundStore.getAll().any { it.layer == FoundStore.LAYER_KLOTTER && it.id == noteId.toString() } + }, + extraKlotter = myNotesRaw, + revealKlotterTitles = true, + klotterRadiusM = 0, // obegränsat + onlyExtraKlotter = true, + onFeaturesApplied = { myNotesLoading = false } + ) + } + }, + bottom = { + Box(Modifier.fillMaxSize()) { + NearbyContent( + loading = myNotesLoading, + error = myNotesError, + hasLocation = true, + entries = myNotesEntries, + dm = emptyList(), + forn = emptyList(), + onOpenAction = { action -> + if (action is FoundOpenAction.Klotter) { + openKlotter = OpenKlotter(action.id, action.lat, action.lon, action.label) + } + }, + rowTextStyle = MaterialTheme.typography.bodyMedium.copy( + color = MaterialTheme.colorScheme.onSurface + ) + ) + } + } + ) + } + + // Overlay: använd Popup så den hamnar över MapContainer (native view) + if (myNotesLoading) { + Popup( + alignment = Alignment.Center, + onDismissRequest = {} // ej stängbar + ) { + Surface( + shape = MaterialTheme.shapes.medium, + tonalElevation = 6.dp + ) { + Row( + modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp) + ) { + CircularProgressIndicator() + Text("Laddar …", style = MaterialTheme.typography.bodyLarge) + } + } + } + } + } +// } + // === ABOUT === Box( modifier = Modifier @@ -787,6 +991,26 @@ fun KlottrAppShell( ) } } + // Global overlay för "Mitt klotter": dialog alltid överst, oavsett kartvy/native-view. + if (selectedTab == "mynotes" && myNotesLoading) { + androidx.compose.ui.window.Dialog( + onDismissRequest = { /* ej stängbar medan vi laddar */ } + ) { + Surface( + shape = MaterialTheme.shapes.medium, + tonalElevation = 6.dp + ) { + Row( + modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp) + ) { + CircularProgressIndicator() + Text("Laddar …", style = MaterialTheme.typography.bodyLarge) + } + } + } + } } ) } @@ -1334,3 +1558,58 @@ fun AccountScreen( } } } + +@Composable +private fun SplitPaneVertical( + split: Float, + onSplitChange: (Float) -> Unit, + handleHeight: Dp = 16.dp, + minSplit: Float = 0.15f, + maxSplit: Float = 0.85f, + top: @Composable () -> Unit, + bottom: @Composable () -> Unit +) { + var localSplit by remember(split) { mutableStateOf(split.coerceIn(minSplit, maxSplit)) } + + BoxWithConstraints(Modifier.fillMaxSize()) { + val density = LocalDensity.current + val totalPx = with(density) { maxHeight.toPx() } + + val dragState = rememberDraggableState { deltaPx -> + if (totalPx <= 0f) return@rememberDraggableState + val deltaFrac = deltaPx / totalPx + val newSplit = (localSplit + deltaFrac).coerceIn(minSplit, maxSplit) + if (newSplit != localSplit) { + localSplit = newSplit + onSplitChange(newSplit) + } + } + + Column(Modifier.fillMaxSize()) { + Box(Modifier.weight(localSplit).fillMaxWidth()) { top() } + + // Handtag att dra i + Box( + Modifier + .height(handleHeight) + .fillMaxWidth() + .draggable( + orientation = Orientation.Vertical, + state = dragState + ) + .semantics { contentDescription = "drag-handle" } + .background(MaterialTheme.colorScheme.surfaceVariant) + ) { + Box( + Modifier + .align(Alignment.Center) + .size(width = 40.dp, height = 4.dp) + .clip(RoundedCornerShape(2.dp)) + .background(MaterialTheme.colorScheme.onSurface.copy(alpha = 0.35f)) + ) + } + + Box(Modifier.weight(1f - localSplit).fillMaxWidth()) { bottom() } + } + } +} diff --git a/shared/src/commonMain/kotlin/app/klottr/nearby/NearbyBuild.kt b/shared/src/commonMain/kotlin/app/klottr/nearby/NearbyBuild.kt index 4e311af..348fd7b 100644 --- a/shared/src/commonMain/kotlin/app/klottr/nearby/NearbyBuild.kt +++ b/shared/src/commonMain/kotlin/app/klottr/nearby/NearbyBuild.kt @@ -48,7 +48,7 @@ fun buildNearbyEntries( // if (showWiki) { // for (w in wiki) { // val d = distanceMeters(lat, lon, w.lat, w.lon).roundToInt() // - if (d <= wikiRadius) { // [NY] filtrera på radie + if (wikiRadius == 0 || d <= wikiRadius) { // [NY] filtrera på radie out += NearbyEntryShared( // layer = FoundStore.LAYER_WIKI, // id = w.pageId.toString(), // @@ -65,7 +65,7 @@ fun buildNearbyEntries( // if (showDm) { // [NY] for (dmi in dm) { // val d = distanceMeters(lat, lon, dmi.lat, dmi.lon).roundToInt() // - if (d <= dmRadius) { // [NY] filtrera på radie + if (dmRadius == 0 || d <= dmRadius) { // [NY] filtrera på radie out += NearbyEntryShared( // layer = FoundStore.LAYER_DM, // id = dmi.id, // @@ -82,7 +82,7 @@ fun buildNearbyEntries( // if (showFornsok) { // [NY] for (f in forn) { // val d = distanceMeters(lat, lon, f.lat, f.lon).roundToInt() // - if (d <= fornsokRadius) { // [NY] filtrera på radie + if (fornsokRadius == 0 || d <= fornsokRadius) { // [NY] filtrera på radie out += NearbyEntryShared( // layer = FoundStore.LAYER_FORNSOK, // Använd delad konstant från KMP istället för hårdkodad sträng id = f.id, // diff --git a/shared/src/commonMain/kotlin/app/klottr/net/Api.kt b/shared/src/commonMain/kotlin/app/klottr/net/Api.kt index 156624b..d2ff557 100644 --- a/shared/src/commonMain/kotlin/app/klottr/net/Api.kt +++ b/shared/src/commonMain/kotlin/app/klottr/net/Api.kt @@ -302,3 +302,21 @@ suspend fun fetchUserStats(): UserStats? { return sh } + +/** user_notes.php → shared. */ +suspend fun fetchUserNotes( + userId: Long, + sinceMs: Long = 0, + lastEtag: String? = null, + limit: Int = 500 +): NearbyResult { + return KlottrApiShared.userNotes( + baseUrl = ApiConfig.SERVER_API_BASE_URL, + apiKey = ApiConfig.SERVER_API_KEY, + bearerToken = AuthShared.idToken, + userId = userId, + sinceMs = sinceMs, + lastEtag = lastEtag, + limit = limit + ) +} diff --git a/shared/src/commonMain/kotlin/app/klottr/net/KlottrApiShared.kt b/shared/src/commonMain/kotlin/app/klottr/net/KlottrApiShared.kt index 60624cb..aa7cfc5 100644 --- a/shared/src/commonMain/kotlin/app/klottr/net/KlottrApiShared.kt +++ b/shared/src/commonMain/kotlin/app/klottr/net/KlottrApiShared.kt @@ -50,6 +50,13 @@ object KlottrApiShared { val limit: Int = 200 ) + @kotlinx.serialization.Serializable + private data class UserNotesBodyShared( + val user_id: Long, + val since: Long = 0, + val limit: Int = 500 + ) + @kotlinx.serialization.Serializable private data class NoteDetailBodyShared( val id: Long, @@ -147,6 +154,67 @@ object KlottrApiShared { return NearbyResult(code = code, items = items, etag = newEtag) } + + /** + * KMP-variant av user_notes.php. Returnerar NearbyResult-lik struktur (items + etag). + */ + suspend fun userNotes( + baseUrl: String, + apiKey: String, + bearerToken: String?, + userId: Long, + sinceMs: Long = 0, + lastEtag: String? = null, + limit: Int = 500 + ): NearbyResult { + val url = ensureSlash(baseUrl) + "user_notes.php" + val body = UserNotesBodyShared(user_id = userId, since = sinceMs, limit = limit) + + val resp = try { + client.post(url) { + contentType(ContentType.Application.Json) + setBody(body) + header("X-API-Key", apiKey) + if (bearerToken != null) header(HttpHeaders.Authorization, "Bearer $bearerToken") + if (!lastEtag.isNullOrBlank()) header(HttpHeaders.IfNoneMatch, lastEtag) + } + } catch (_: Throwable) { + // Nätfel → som nearby: tom lista + 0/utan etag + return NearbyResult(code = 0, items = emptyList(), etag = null) + } + + val code = resp.status.value + if (code == 304) { + return NearbyResult(code = 304, items = emptyList(), etag = lastEtag) + } + if (code != 200) { + return NearbyResult(code = code, items = emptyList(), etag = null) + } + + val newEtag = resp.headers[HttpHeaders.ETag] + val text = try { resp.body() } catch (_: Throwable) { "[]" } + + // Samma parsinglogik som nearby() → NoteDTO-lista + val items = try { + val arr = kotlinx.serialization.json.Json.parseToJsonElement(text).jsonArray + arr.mapNotNull { el -> + val obj = el.jsonObject + val i = obj["i"]?.jsonPrimitive?.longOrNull ?: return@mapNotNull null + val a = obj["a"]?.jsonPrimitive?.doubleOrNull ?: return@mapNotNull null + val o = obj["o"]?.jsonPrimitive?.doubleOrNull ?: return@mapNotNull null + val t = obj["t"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null + val c = obj["c"]?.jsonPrimitive?.longOrNull ?: return@mapNotNull null + val u = obj["u"]?.jsonPrimitive?.contentOrNull ?: return@mapNotNull null + NoteDTO(i = i, a = a, o = o, t = t, c = c, u = u) + } + } catch (_: Throwable) { + emptyList() + } + + return NearbyResult(code = code, items = items, etag = newEtag) + } + + /** * KMP-variant av get_note.php. Returnerar null vid icke-200 eller undantag. */ diff --git a/shared/src/commonMain/kotlin/app/klottr/ui/MapContent.kt b/shared/src/commonMain/kotlin/app/klottr/ui/MapContent.kt index beff9c2..ee43e00 100644 --- a/shared/src/commonMain/kotlin/app/klottr/ui/MapContent.kt +++ b/shared/src/commonMain/kotlin/app/klottr/ui/MapContent.kt @@ -24,7 +24,14 @@ fun MapContent( initialLat: Double? = null, initialLon: Double? = null, modifier: Modifier = Modifier.fillMaxSize(), - onFornsokClick: (FornsokItem) -> Unit + onFornsokClick: (FornsokItem) -> Unit, + // Extra-data och styrning för titel/radie + extraKlotter: List = emptyList(), + revealKlotterTitles: Boolean = false, + // Radie-override för klotter; null = använd default, 0 = obegränsat + klotterRadiusM: Int? = null, + onlyExtraKlotter: Boolean = false, + onFeaturesApplied: (() -> Unit)? = null ) { val satellite = SettingsStore.getSatelliteMap() val showKlotter = SettingsStore.getShowKlotter() @@ -88,15 +95,75 @@ fun MapContent( fun buildFeatures(): List { val lat = myLat; val lon = myLon val out = mutableListOf() - if (showKlotter) { - klotter.forEach { n -> + + // ----- "Mitt klotter"-läge: visa ENDAST extraKlotter oavsett SettingsStore ----- + if (onlyExtraKlotter) { + val radius = (klotterRadiusM ?: Config.DEFAULT_KLOTTER_RADIUS_M) + val unlimited = (radius == 0) + extraKlotter + .distinctBy { it.i } + .forEach { n -> val d = if (lat != null && lon != null) distanceMeters(lat, lon, n.a, n.o).roundToInt() else Int.MAX_VALUE + val within = if (unlimited) true else (d != Int.MAX_VALUE && d <= radius) val titleLine = n.t.substringBefore('\n').ifBlank { "Okänt klotter" } - val radius = Config.DEFAULT_KLOTTER_RADIUS_M + // I "Mitt klotter" ska rubriker ALLTID synas (det är ju dina egna), oavsett avstånd: + val display = titleLine + // Vi ritar ALLA markörer (within påverkar inte synlighet här): + out += MapFeature.Marker( + id = "klotter:${n.i}", + position = LatLng(n.a, n.o), + title = display + ) + } + return out + } +// === Klotter-markörer (bakåtkompatibelt läge) === + run { + // Om inga nya parametrar används → exakt gamla koden + val usingExtras = (extraKlotter.isNotEmpty() || revealKlotterTitles || klotterRadiusM != null) + + if (!usingExtras) { + if (showKlotter) { + klotter.forEach { n -> + val d = if (lat != null && lon != null) + distanceMeters(lat, lon, n.a, n.o).roundToInt() else Int.MAX_VALUE + val titleLine = n.t.substringBefore('\n').ifBlank { "Okänt klotter" } + val radius = Config.DEFAULT_KLOTTER_RADIUS_M + val visited = isKnownNote(n.i.toLong()) + val within = (d != Int.MAX_VALUE && d <= radius) + val display = if (visited || (within && titleLine != "Okänt klotter")) titleLine else "Okänt klotter" + out += MapFeature.Marker( + id = "klotter:${n.i}", + position = LatLng(n.a, n.o), + title = display + ) + } + } + return@run + } + + // Nytt beteende (endast när extras faktiskt används) + val combined: List = when { + extraKlotter.isNotEmpty() && showKlotter -> (klotter + extraKlotter).distinctBy { it.i } + extraKlotter.isNotEmpty() && !showKlotter -> extraKlotter.distinctBy { it.i } + else -> if (showKlotter) klotter else emptyList() + } + + val radius = (klotterRadiusM ?: Config.DEFAULT_KLOTTER_RADIUS_M) + val unlimited = (radius == 0) + + combined.forEach { n -> + val d = if (lat != null && lon != null) + distanceMeters(lat, lon, n.a, n.o).roundToInt() else Int.MAX_VALUE + + val titleLine = n.t.substringBefore('\n').ifBlank { "Okänt klotter" } + val within = if (unlimited) true else (d != Int.MAX_VALUE && d <= radius) val visited = isKnownNote(n.i.toLong()) - val within = (d != Int.MAX_VALUE && d <= radius) - val display = if (visited || (within && titleLine != "Okänt klotter")) titleLine else "Okänt klotter" + + val display = if (revealKlotterTitles || visited || (within && titleLine != "Okänt klotter")) + titleLine else "Okänt klotter" + out += MapFeature.Marker( id = "klotter:${n.i}", position = LatLng(n.a, n.o), @@ -104,6 +171,7 @@ fun MapContent( ) } } + if (showWiki) { wiki.forEach { w -> out += MapFeature.Marker( @@ -159,11 +227,14 @@ fun MapContent( MapContainer( state = mapState, onMapClick = { /* inget extra här */ }, + onMarkerClick = { id -> when { id.startsWith("klotter:") -> { val nid = id.removePrefix("klotter:") - klotter.firstOrNull { it.i.toString() == nid }?.let { n -> + val n = klotter.firstOrNull { it.i.toString() == nid } + ?: extraKlotter.firstOrNull { it.i.toString() == nid } + if (n != null) { val titleLine = n.t.substringBefore('\n').ifBlank { "Okänt klotter" } onKlotterClick(nid, n.a, n.o, titleLine) } @@ -196,17 +267,26 @@ fun MapContent( mapController = ctrl ctrl.setMyLocationEnabled(hasFgLocationPerms()) ctrl.setFeatures(buildFeatures()) + onFeaturesApplied?.invoke() } ) MapSyncEffects( controller = mapController, - myLat = myLat, - myLon = myLon, + myLat = if (onlyExtraKlotter) null else myLat, + myLon = if (onlyExtraKlotter) null else myLon, featuresBuilder = { buildFeatures() }, showKlotter, showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius, klotter, wiki, dm, forn ) + // När vi visar endast egna klotter: applicera features igen när datan ändras, + // och signalera att features är på plats (så "Laddar..." kan stängas). + LaunchedEffect(onlyExtraKlotter, extraKlotter) { + if (onlyExtraKlotter) { + mapController?.setFeatures(buildFeatures()) + onFeaturesApplied?.invoke() + } + } } }