feat: instant found refresh, silent self-notes, better write flow

Found list updates live (KvPrefs listener + broadcasts) — no rotation needed.

Auto-mark newly created notes as “found” and auto-scroll list to top.

Suppress notification for the just-created note (TTL), keep others unchanged.

Write dialog: BasicTextField plumbing with visible cursor (dark mode), full-area focus, proper placeholders.

Offline w/ image: persist file, queue OutboxWorker, idempotent retries.
This commit is contained in:
2025-09-15 17:44:12 +02:00
parent 7085e42b17
commit 851b03a97f
4 changed files with 121 additions and 29 deletions

View File

@@ -42,6 +42,8 @@ class LocationService : Service() {
const val ACTION_CLEAR_FOUND_SESSION = "app.klottr.ACTION_CLEAR_FOUND_SESSION"
const val ACTION_RESCAN_NOW = "app.klottr.ACTION_RESCAN_NOW"
const val ACTION_LOCATION_TICK = "app.klottr.ACTION_LOCATION_TICK"
const val ACTION_SUPPRESS_NOTIFY = "app.klottr.ACTION_SUPPRESS_NOTIFY" // Tysta notiser för ett id
}
@@ -51,6 +53,8 @@ class LocationService : Service() {
// Sessiontillstånd – används för “gå utanför ~200 m → tillåt om-avisering”
private val notifiedWhileInside = mutableMapOf<String, Boolean>() // key(layer:id) -> om vi redan aviserat denna session.
private val lastKnownDistance = mutableMapOf<String, Int>() // senaste uppmätta avståndet (meter).
private val suppressedUntil = mutableMapOf<String, Long>() // key(layer:id) -> tyst till tidsstämpel
private lateinit var callback: LocationCallback
@@ -74,6 +78,14 @@ class LocationService : Service() {
notifiedWhileInside.clear()
lastKnownDistance.clear()
}
ACTION_SUPPRESS_NOTIFY -> {
val layer = intent.getStringExtra("layer")
val id = intent.getStringExtra("id")
val ttl = intent.getLongExtra("ttlMs", 60_000L) // default 60s
if (layer != null && id != null) {
suppressedUntil[key(layer, id)] = System.currentTimeMillis() + ttl // Lägg in tystnad
}
}
ACTION_RESCAN_NOW -> {
scope.launch {
val loc = try {
@@ -243,10 +255,17 @@ class LocationService : Service() {
// Notiser:
// - onlyNew=true → bara för helt nya (inte för återinträde)
// - onlyNew=false → en gång per session ELLER om re-arm via FoundStore (wasAwayStore) eller session-reentry
val nowMs = System.currentTimeMillis() // Nu
val suppressed = (suppressedUntil[k] ?: 0L) > nowMs // Är tystnad aktiv?
val shouldNotify = if (onlyNew) {
!alreadyFound && !wasNotifiedThisSession
!alreadyFound && !wasNotifiedThisSession && !suppressed
} else {
!wasNotifiedThisSession || wasAwayStore || reenteredSession
(!wasNotifiedThisSession || wasAwayStore || reenteredSession) && !suppressed
}
if (suppressed) {
notifiedWhileInside[k] = true // Blockera fler notiser denna session
}
if (shouldNotify) {
val (title, text) = notificationTitleAndText(layer, label, distanceM)

View File

@@ -482,6 +482,7 @@ private fun KlottrApp(
refreshFound()
}
}
if (Build.VERSION.SDK_INT >= 33) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@@ -491,6 +492,20 @@ private fun KlottrApp(
onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} }
}
// Direkt UI-uppdatering när FoundStore/KvPrefs ändras (oavsett broadcast)
DisposableEffect(Unit) {
val handler = android.os.Handler(android.os.Looper.getMainLooper())
val kvListener: (String?) -> Unit = {
handler.post {
forceEmptyFound = false
refreshFound() // trigga recomposition av “Senaste”
}
}
app.klottr.prefs.KvPrefs.addListener(kvListener)
onDispose { app.klottr.prefs.KvPrefs.removeListener(kvListener) }
}
// Lyssna efter ACTION_LOCATION_TICK
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
@@ -574,7 +589,6 @@ private fun KlottrApp(
}
)
}
) { padding ->
Column(
Modifier
@@ -677,9 +691,10 @@ private fun KlottrApp(
),
mainContent = {
// Hittat (flyttat hit för att kapslas i skalet)
val foundList =
if (forceEmptyFound) emptyList()
else FoundStore.getAll(context)
// 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<String, String>() }
@@ -1044,41 +1059,52 @@ private fun KlottrApp(
is CreateNoteOutcome.Success -> {
Toast.makeText(context, "Sparat.", Toast.LENGTH_SHORT).show()
// Förladda närliggande post och ev. bild (oförändrat beteende)
// Markera nyskapad notis som "hittad" och uppdatera UI direkt
scope.launch(Dispatchers.IO) {
try {
val nearby = Geocache.getNearby(
lat = selLat, lon = selLon, radiusMeters = 100, ttlMs = 0L
lat = selLat,
lon = selLon,
radiusMeters = 120,
ttlMs = 0L
)
val combined = buildString {
if (titleText.isNotBlank()) append(titleText).append("\n\n")
append(bodyText)
}.trim()
val match = nearby.firstOrNull {
it.t == combined && abs(it.c - created) <= 2_000
// Kandidater nära i både tid och rum (tighta gränser för att undvika felmatch)
val candidates = nearby.filter {
app.klottr.util.distanceMeters(selLat, selLon, it.a, it.o) <= 40.0 &&
kotlin.math.abs(it.c - created) <= 10_000
}
val match = candidates.minByOrNull { kotlin.math.abs(it.c - created) }
if (match != null) {
val labelTitle = titleText.ifBlank { match.t ?: "Klotter" } // Spara endast rubriken i “Senaste”
FoundStore.markFound(
context,
LAYER_KLOTTER,
match.i.toString(),
label = match.t,
label = labelTitle,
lat = match.a,
lon = match.o,
timeMillis = System.currentTimeMillis()
)
withContext(Dispatchers.Main) {
context.sendBroadcast(
Intent(LocationService.Companion.ACTION_FOUND_UPDATED)
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
}
// Tysta avisering för just detta klotter under 60s (slipper “pling” på eget klotter)
context.startService(
Intent(context, LocationService::class.java)
.setAction(LocationService.ACTION_SUPPRESS_NOTIFY)
.putExtra("layer", LAYER_KLOTTER)
.putExtra("id", match.i.toString())
.putExtra("ttlMs", 60_000L) // Valfri – hur länge det ska vara tyst
)
}
} catch (_: Throwable) { /* no-op */ }
}
} catch (_: Throwable) { }
}
showWrite = false
}
is CreateNoteOutcome.UploadFailed -> { // Fallback till offline-utkorg även när bilduppladdning misslyckas
val titleText = draft.title.trim()
val bodyText = draft.body.trim()

View File

@@ -1,16 +1,19 @@
package app.klottr.work
import android.content.Context
import android.content.Intent
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import app.klottr.LocationService
import app.klottr.net.Geocache
import app.klottr.net.createNote
import app.klottr.net.createNoteDoc
import app.klottr.net.uploadImageFromFile
import app.klottr.util.FoundStore
import app.klottr.util.OutboxStore
import java.io.File
import java.security.MessageDigest
import kotlin.math.abs
/**
* Försöker skicka allt som ligger i utkorgen (offline-klotter).
@@ -33,7 +36,6 @@ class OutboxWorker(
return sb.toString()
}
override suspend fun doWork(): Result {
val ctx = applicationContext
val pending = OutboxStore.all(ctx)
@@ -96,9 +98,45 @@ class OutboxWorker(
} catch (_: Throwable) {
false
}
if (!ok) keep.add(p)
if (ok) {
try {
// Hämta närliggande från servern för att få rätt id/koordinater
val nearby = Geocache.getNearby(
lat = p.lat, lon = p.lon, radiusMeters = 120, ttlMs = 0L
)
// Välj bästa kandidat: nära i både tid och rum
val match = nearby
.filter { app.klottr.util.distanceMeters(p.lat, p.lon, it.a, it.o) <= 80.0 }
.minByOrNull { abs(it.c - p.createdAt) }
if (match != null) {
// Sätt label på ett rimligt sätt (titel + ev. brödtext, annars fallback)
val label = when {
!p.title.isNullOrBlank() -> p.title!!.trim()
else -> (match.t ?: "Klotter")
}
// Markera som hittad i FoundStore
FoundStore.markFound(
ctx,
FoundStore.LAYER_KLOTTER,
match.i.toString(),
label = label,
lat = match.a,
lon = match.o,
timeMillis = System.currentTimeMillis()
)
// Pinga UI så “Senaste” uppdateras direkt
ctx.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
}
} catch (_: Throwable) {
// Tyst fallback – Workern ska inte krascha pga visuell uppdatering
}
}
if (!ok) keep.add(p)
}
OutboxStore.replaceAll(ctx, keep)
return if (keep.isEmpty()) Result.success() else Result.retry()

View File

@@ -13,12 +13,13 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.lazy.rememberLazyListState // Styr scrollposition
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect // Kör scroll efter recomposition
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.remember // Memo för trigger
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
@@ -72,10 +73,18 @@ fun FoundList(
val baseColor = rowTextStyle.color.takeOrElse { Color.LightGray }
val thumbColor = baseColor.copy(alpha = 0.45f)
val listState = rememberLazyListState()
// Trigger: nyaste raden (lager:id:tid) – ändras när nya fynd kommer eller efter rensning
val scrollTrigger = remember(entries) {
entries.firstOrNull()?.let { "${it.layer}:${it.id}:${it.timeMillis}" } ?: "empty"
}
LaunchedEffect(scrollTrigger) { // Scrolla upp när triggern ändras
listState.scrollToItem(0)
}
Box(modifier = modifier.fillMaxSize()) {
LazyColumn(
state = state,
state = listState,
modifier = Modifier.fillMaxSize()
) {
items(entries, key = { e -> "${e.layer}:${e.id}" }) { e ->