1966 lines
96 KiB
Kotlin
1966 lines
96 KiB
Kotlin
package app.klottr
|
||
|
||
import androidx.compose.foundation.BorderStroke
|
||
import androidx.compose.foundation.background
|
||
import androidx.compose.foundation.border
|
||
import androidx.compose.foundation.clickable
|
||
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
|
||
import androidx.compose.foundation.layout.WindowInsets
|
||
import androidx.compose.foundation.layout.consumeWindowInsets
|
||
import androidx.compose.foundation.layout.fillMaxSize
|
||
import androidx.compose.foundation.layout.fillMaxWidth
|
||
import androidx.compose.foundation.layout.height
|
||
import androidx.compose.foundation.layout.padding
|
||
import androidx.compose.foundation.layout.safeDrawing
|
||
import androidx.compose.foundation.layout.size
|
||
import androidx.compose.foundation.layout.statusBars
|
||
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
|
||
import androidx.compose.material.icons.filled.Create
|
||
import androidx.compose.material.icons.filled.Delete
|
||
import androidx.compose.material.icons.filled.Edit
|
||
import androidx.compose.material.icons.filled.Home
|
||
import androidx.compose.material.icons.filled.Info
|
||
import androidx.compose.material.icons.filled.Layers
|
||
import androidx.compose.material.icons.filled.Login
|
||
import androidx.compose.material.icons.filled.Menu
|
||
import androidx.compose.material.icons.filled.Person
|
||
import androidx.compose.material.icons.filled.Place
|
||
import androidx.compose.material.icons.filled.Settings
|
||
import androidx.compose.material3.AlertDialog
|
||
import androidx.compose.material3.AssistChip
|
||
import androidx.compose.material3.Button
|
||
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
|
||
import androidx.compose.material3.Icon
|
||
import androidx.compose.material3.IconButton
|
||
import androidx.compose.material3.MaterialTheme
|
||
import androidx.compose.material3.NavigationBar
|
||
import androidx.compose.material3.NavigationBarItem
|
||
import androidx.compose.material3.OutlinedButton
|
||
import androidx.compose.material3.OutlinedTextField
|
||
import androidx.compose.material3.Scaffold
|
||
import androidx.compose.material3.Slider
|
||
import androidx.compose.material3.Surface
|
||
import androidx.compose.material3.Switch
|
||
import androidx.compose.material3.Text
|
||
import androidx.compose.material3.TextButton
|
||
import androidx.compose.runtime.Composable
|
||
import androidx.compose.runtime.LaunchedEffect
|
||
import androidx.compose.runtime.collectAsState
|
||
import androidx.compose.runtime.derivedStateOf
|
||
import androidx.compose.runtime.getValue
|
||
import androidx.compose.runtime.mutableStateOf
|
||
import androidx.compose.runtime.remember
|
||
import androidx.compose.runtime.rememberCoroutineScope
|
||
import androidx.compose.runtime.saveable.rememberSaveable
|
||
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.Color
|
||
import androidx.compose.ui.graphics.vector.ImageVector
|
||
import androidx.compose.ui.input.pointer.pointerInput
|
||
import androidx.compose.ui.platform.LocalDensity
|
||
import androidx.compose.ui.semantics.contentDescription
|
||
import androidx.compose.ui.semantics.semantics
|
||
import androidx.compose.ui.text.font.FontWeight
|
||
import androidx.compose.ui.text.style.TextAlign
|
||
import androidx.compose.ui.unit.LayoutDirection
|
||
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)
|
||
import app.klottr.create.CreateNoteOutcome
|
||
import app.klottr.create.QueueOutboxOutcome
|
||
import app.klottr.create.createNoteFlow
|
||
import app.klottr.create.queueNoteDocOutbox
|
||
import app.klottr.events.FoundEvents
|
||
import app.klottr.images.ImageWriter
|
||
import app.klottr.images.ImageReader
|
||
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
|
||
import app.klottr.nearby.ScanConfig
|
||
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
|
||
import app.klottr.net.Geocache
|
||
import app.klottr.net.UserStats
|
||
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
|
||
import app.klottr.platform.AppNavigator
|
||
import app.klottr.platform.OutboxScheduler
|
||
import app.klottr.platform.UiFeedback
|
||
import app.klottr.platform.UiFeedbackDuration
|
||
import app.klottr.ui.AboutScreen
|
||
import app.klottr.ui.DmDialog
|
||
import app.klottr.ui.FornsokDialog
|
||
import app.klottr.ui.KlottrHomeContent
|
||
import app.klottr.ui.LoginRequiredContent
|
||
import app.klottr.ui.MapContent
|
||
import app.klottr.ui.NearbyContent
|
||
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.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
|
||
import kotlinx.coroutines.withContext
|
||
import kotlin.collections.orEmpty
|
||
import kotlin.math.roundToInt
|
||
import kotlin.time.Clock
|
||
import kotlin.time.ExperimentalTime
|
||
|
||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalTime::class)
|
||
@Composable
|
||
fun KlottrAppShell(
|
||
onRequestPerms: () -> Unit,
|
||
onLogin: () -> Unit,
|
||
onLogout: () -> Unit
|
||
) {
|
||
val locService = remember { LocationServiceProvider.get() }
|
||
LaunchedEffect(Unit) { locService.start() }
|
||
val currentLoc = locService.location.collectAsState(initial = null)
|
||
val scope = rememberCoroutineScope()
|
||
|
||
// Inloggning
|
||
val loggedIn by AuthShared.loggedIn.collectAsState(initial = false)
|
||
|
||
// Initiera SQLDelight-databasen med hjälp av DatabaseFactory.
|
||
val db = remember {
|
||
val driver = app.klottr.db.DatabaseFactory.createDriver()
|
||
app.klottr.db.KlottrDatabase(driver)
|
||
}
|
||
|
||
// Exponera notes som en State<List<Note>> med Compose-stöd.
|
||
// asFlow() -> gör queryn reaktiv (ström av ändringar).
|
||
// mapToList() -> konverterar varje queryresultat till en lista.
|
||
// collectAsState() -> gör om Flow till Compose-State, så UI ritas om automatiskt.
|
||
val notes by db.notesQueries.all()
|
||
.asFlow()
|
||
.mapToList(Dispatchers.IO)
|
||
.collectAsState(initial = emptyList())
|
||
|
||
|
||
// Settings-state
|
||
// Läser från KMP SettingsStore (no-arg-API). Inga Context-beroenden här längre.
|
||
var onlyNew by remember { mutableStateOf(SettingsStore.getOnlyNewHits()) }
|
||
var satellite by remember { mutableStateOf(SettingsStore.getSatelliteMap()) }
|
||
var night by remember { mutableStateOf(SettingsStore.getNightMode()) }
|
||
var showCoords by remember { mutableStateOf(SettingsStore.getShowCoordinates()) }
|
||
var showKlotter by remember { mutableStateOf(SettingsStore.getShowKlotter()) }
|
||
var showWiki by remember { mutableStateOf(SettingsStore.getShowWikipedia()) }
|
||
var wikiRadius by remember { mutableStateOf(SettingsStore.getWikiRadiusMeters()) }
|
||
var showDm by remember { mutableStateOf(SettingsStore.getShowDigitaltMuseum()) }
|
||
var dmRadius by remember { mutableStateOf(SettingsStore.getDigitaltMuseumRadiusMeters()) }
|
||
var showFornsok by remember { mutableStateOf(SettingsStore.getShowFornsok()) }
|
||
var fornsokRadius by remember { mutableStateOf(SettingsStore.getFornsokRadiusMeters()) }
|
||
// Aktiv flik (lyfts upp så top-baren kan läsa den)
|
||
var selectedTab by rememberSaveable { mutableStateOf("home") }
|
||
|
||
|
||
// UI-state
|
||
var showWrite by remember { mutableStateOf(false) }
|
||
var resetSavingCounter by remember { mutableStateOf(0) }
|
||
var locationTick by remember { mutableStateOf(0) }
|
||
var showLoginRequired by remember { mutableStateOf(false) }
|
||
var me by remember { mutableStateOf<app.klottr.net.MeShared?>(null) }
|
||
var userStats by remember { mutableStateOf<UserStats?>(null) }
|
||
|
||
// Härledd användar-id som uppdateras automatiskt när 'me' ändras
|
||
val currentUserId by remember { derivedStateOf { me?.id } }
|
||
var showUsernameDialog by remember { mutableStateOf(false) }
|
||
|
||
// Nearby-data
|
||
|
||
// Ändrad: Triple -> NearbyBundleShared
|
||
var nearbyBundle by remember {
|
||
mutableStateOf<NearbyBundleShared?>(null)
|
||
}
|
||
|
||
var nearbyRefreshing by remember { mutableStateOf(false) }
|
||
|
||
var nearbyError by remember { mutableStateOf<String?>(null) }
|
||
var lastKnownLat by remember { mutableStateOf<Double?>(null) }
|
||
var lastKnownLon by remember { mutableStateOf<Double?>(null) }
|
||
|
||
var myNotesLoading by remember { mutableStateOf(false) }
|
||
var myNotesError by remember { mutableStateOf<String?>(null) }
|
||
var myNotesEtag by remember { mutableStateOf<String?>(null) }
|
||
var myNotesEntries by remember { mutableStateOf(listOf<NearbyEntryShared>()) }
|
||
var myNotesRaw by remember { mutableStateOf<List<NoteDTO>>(emptyList()) }
|
||
|
||
// Klotter-detalj
|
||
var openKlotter by remember {mutableStateOf<OpenKlotter?>(null) }
|
||
// Wiki-detalj
|
||
var openWiki by remember { mutableStateOf<OpenWiki?>(null) }
|
||
// Fornsok-detalj
|
||
var openFornsok by remember { mutableStateOf<OpenFornsok?>(null) }
|
||
// DigitaltMuseum
|
||
var openDm by remember { mutableStateOf<DigitaltMuseumItem?>(null) }
|
||
|
||
|
||
// Hittat-refresh + “force tomt” efter rensning
|
||
var foundRefresh by remember { mutableStateOf(0) }
|
||
var forceEmptyFound by remember { mutableStateOf(false) }
|
||
fun refreshFound() { foundRefresh++ }
|
||
|
||
LaunchedEffect(loggedIn) {
|
||
if (!loggedIn) {
|
||
showUsernameDialog = false
|
||
me = null
|
||
return@LaunchedEffect
|
||
}
|
||
val m = withContext(Dispatchers.IO) { app.klottr.net.fetchMe() }
|
||
|
||
if (m != null) {
|
||
me = m
|
||
// Visa dialogen ENDAST när vi säkert vet att username saknas
|
||
showUsernameDialog = m.username.isNullOrBlank()
|
||
} else {
|
||
// Okänt läge (nätfel/401 osv) → visa inte dialogen
|
||
showUsernameDialog = false
|
||
}
|
||
}
|
||
|
||
// Kickstarta avstånd direkt vid appstart (via KMP LocationService)
|
||
// Lyssna på KMP LocationService-flöde istället för broadcast
|
||
LaunchedEffect(currentLoc.value?.lat, currentLoc.value?.lon) {
|
||
currentLoc.value?.let { gp ->
|
||
FoundStore.updateAwayFlags(gp.lat, gp.lon)
|
||
locationTick++
|
||
}
|
||
}
|
||
|
||
|
||
// 🔴 NYTT: Omedelbar UI-uppdatering när FoundStore ändras
|
||
// Found updates via shared event bus (no broadcasts)
|
||
LaunchedEffect(Unit) {
|
||
FoundEvents.foundUpdated.collect {
|
||
// Trigga omritning varje gång FoundStore uppdateras
|
||
forceEmptyFound = false
|
||
refreshFound()
|
||
}
|
||
}
|
||
|
||
LaunchedEffect(showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) {
|
||
if (!showWiki && !showDm && !showFornsok) return@LaunchedEffect
|
||
|
||
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||
if (gp != null) {
|
||
val anyNew = withContext(Dispatchers.IO) {
|
||
scanAndMarkFound(
|
||
lat = gp.lat,
|
||
lon = gp.lon,
|
||
config = ScanConfig(
|
||
showWiki = showWiki,
|
||
wikiRadius = wikiRadius,
|
||
showDm = showDm,
|
||
dmRadius = dmRadius,
|
||
showFornsok = showFornsok,
|
||
fornsokRadius = fornsokRadius
|
||
),
|
||
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)
|
||
}
|
||
)
|
||
}
|
||
if (anyNew) {
|
||
forceEmptyFound = false // Sätt tillbaka visning efter “Glöm alla fynd”
|
||
refreshFound() // Tvinga omritning av “Senaste”
|
||
/* notify listeners inline: refreshFound() already called */
|
||
}
|
||
}
|
||
}
|
||
|
||
// Löser bugg som gjorde att Klotter-fynd inte dök upp: Klotter: skanna nära klotter och markera i FoundStore så Hem-fliken uppdateras
|
||
LaunchedEffect(showKlotter, locationTick) {
|
||
if (!showKlotter) return@LaunchedEffect
|
||
|
||
val gp = LocationServiceProvider.get().current(highAccuracy = false) ?: return@LaunchedEffect
|
||
lastKnownLat = gp.lat
|
||
lastKnownLon = gp.lon
|
||
|
||
// Hämta klotter inom standardradien (20 m)
|
||
val nearby = withContext(Dispatchers.IO) {
|
||
Geocache.getNearby(
|
||
lat = gp.lat,
|
||
lon = gp.lon,
|
||
radiusMeters = Config.DEFAULT_KLOTTER_RADIUS_M,
|
||
ttlMs = 0L
|
||
)
|
||
}
|
||
|
||
// Markera nya (ej tidigare kända) som "hittade"
|
||
val known = FoundStore.getAll()
|
||
.asSequence()
|
||
.filter { it.layer == LAYER_KLOTTER }
|
||
.map { it.id }
|
||
.toSet()
|
||
|
||
var anyNew = false
|
||
val now = Clock.System.now().toEpochMilliseconds()
|
||
|
||
for (n in nearby) {
|
||
val idStr = n.i.toString()
|
||
if (idStr !in known) {
|
||
FoundStore.markFound(
|
||
layer = LAYER_KLOTTER,
|
||
id = idStr,
|
||
label = n.t ?: "Klotter",
|
||
lat = n.a,
|
||
lon = n.o,
|
||
timeMillis = now
|
||
)
|
||
anyNew = true
|
||
}
|
||
}
|
||
|
||
// Uppdatera away-flaggor (fetstil i listan blir korrekt)
|
||
FoundStore.updateAwayFlags(gp.lat, gp.lon)
|
||
|
||
if (anyNew) {
|
||
// Återställ ev. "tvinga tomt" och trigga omritning
|
||
forceEmptyFound = false
|
||
FoundEvents.notifyFoundUpdated()
|
||
refreshFound()
|
||
}
|
||
}
|
||
|
||
|
||
Scaffold(
|
||
topBar = {
|
||
CenterAlignedTopAppBar(
|
||
title = {
|
||
val titleText = when (selectedTab) {
|
||
"home" -> "Hem"
|
||
"layers" -> "Lager"
|
||
"nearby" -> "Nära"
|
||
"menu" -> "Meny"
|
||
"account" -> "Konto"
|
||
"settings"-> "Inställningar"
|
||
"about" -> "Om"
|
||
"mynotes" -> "Mitt klotter"
|
||
else -> ""
|
||
}
|
||
Text(
|
||
titleText,
|
||
style = MaterialTheme.typography.titleLarge,
|
||
color = MaterialTheme.colorScheme.onSurface
|
||
)
|
||
}
|
||
)
|
||
}
|
||
) { padding ->
|
||
|
||
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") }
|
||
)
|
||
NavigationBarItem(
|
||
selected = (selectedTab == "layers"),
|
||
onClick = { selectedTab = "layers" },
|
||
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")
|
||
}
|
||
}
|
||
},
|
||
floatingActionButtonPosition = androidx.compose.material3.FabPosition.Center,
|
||
content = { innerPadding ->
|
||
if (selectedTab !in listOf("home", "nearby", "menu", "account", "about", "settings", "mynotes", "layers")) {
|
||
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)
|
||
.padding(top = innerPadding.calculateTopPadding()) // Lägger till top-padding
|
||
) {
|
||
// === HEM ===
|
||
Box(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.alpha(if (selectedTab == "home") 1f else 0f)
|
||
.zIndex(if (selectedTab == "home") 1f else 0f)
|
||
.pointerInput(selectedTab) { } // 👈 blockerar klick när fliken inte är aktiv
|
||
|
||
) {
|
||
// Å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<String, String>() }
|
||
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)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 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 */ }
|
||
)
|
||
}
|
||
|
||
// === LAGER ===
|
||
Box(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.alpha(if (selectedTab == "layers") 1f else 0f)
|
||
.zIndex(if (selectedTab == "layers") 1f else 0f)
|
||
.pointerInput(selectedTab) { } // 👈 blockerar klick när fliken inte är aktiv
|
||
|
||
) {
|
||
// Samma innehåll som SettingsScreen men reducerat till endast lagren
|
||
Column(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.padding(innerPadding)
|
||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||
) {
|
||
// 🔹 Klotter
|
||
DiscreteSliderRow(
|
||
label = "Visningsradie för Klotter",
|
||
value = if (showKlotter) 20 else -1,
|
||
grMin = 20,
|
||
grMax = 20,
|
||
onValueChange = { newVal, enabled ->
|
||
if (enabled) {
|
||
SettingsStore.setShowKlotter(true)
|
||
showKlotter = true
|
||
} else {
|
||
SettingsStore.setShowKlotter(false)
|
||
showKlotter = false
|
||
}
|
||
}
|
||
)
|
||
|
||
// 🔹 Diskret slider för Wikipedia-radie
|
||
DiscreteSliderRow(
|
||
label = "Visningsradie för Wikipedia",
|
||
value = if (showWiki) wikiRadius else -1,
|
||
grMin = 20,
|
||
grMax = 5000,
|
||
onValueChange = { newVal, enabled ->
|
||
if (enabled) {
|
||
SettingsStore.setShowWikipedia(true)
|
||
SettingsStore.setWikiRadiusMeters(newVal)
|
||
wikiRadius = newVal
|
||
showWiki = true
|
||
} else {
|
||
SettingsStore.setShowWikipedia(false)
|
||
showWiki = false
|
||
}
|
||
}
|
||
)
|
||
|
||
// 🔹 Diskret slider för DigitaltMuseum-radie
|
||
DiscreteSliderRow(
|
||
label = "Visningsrade för DigitaltMuseum",
|
||
value = if (showDm) dmRadius else -1,
|
||
grMin = 50,
|
||
grMax = 2000,
|
||
onValueChange = { newVal, enabled ->
|
||
if (enabled) {
|
||
SettingsStore.setShowDigitaltMuseum(true)
|
||
SettingsStore.setDigitaltMuseumRadiusMeters(newVal)
|
||
dmRadius = newVal
|
||
showDm = true
|
||
} else {
|
||
SettingsStore.setShowDigitaltMuseum(false)
|
||
showDm = false
|
||
}
|
||
}
|
||
)
|
||
// 🔹 Diskret slider för Fornsök-radie
|
||
DiscreteSliderRow(
|
||
label = "Visningsradie för Fornsök",
|
||
value = if (showFornsok) fornsokRadius else -1,
|
||
grMin = 50,
|
||
grMax = 5000,
|
||
onValueChange = { newVal, enabled ->
|
||
if (enabled) {
|
||
SettingsStore.setShowFornsok(true)
|
||
SettingsStore.setFornsokRadiusMeters(newVal)
|
||
fornsokRadius = newVal
|
||
showFornsok = true
|
||
} else {
|
||
SettingsStore.setShowFornsok(false)
|
||
showFornsok = false
|
||
}
|
||
}
|
||
)
|
||
}
|
||
}
|
||
|
||
// === NÄRA ===
|
||
Box(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.alpha(if (selectedTab == "nearby") 1f else 0f)
|
||
.zIndex(if (selectedTab == "nearby") 1f else 0f)
|
||
.pointerInput(selectedTab) { } // 👈 blockerar klick när fliken inte är aktiv
|
||
) {
|
||
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
|
||
nearbyRefreshing = true
|
||
nearbyError = null
|
||
|
||
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||
if (gp == null) {
|
||
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]
|
||
},
|
||
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: dragbar delare mellan karta (top) och lista (bottom)
|
||
Column(
|
||
Modifier
|
||
.fillMaxSize()
|
||
.padding(bottom = innerPadding.calculateBottomPadding())
|
||
) {
|
||
// 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)
|
||
|
||
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() }
|
||
},
|
||
satellite = satellite,
|
||
night = night
|
||
)
|
||
}
|
||
},
|
||
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 ===
|
||
Box(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.alpha(if (selectedTab == "menu") 1f else 0f)
|
||
.zIndex(if (selectedTab == "menu") 1f else 0f)
|
||
.pointerInput(selectedTab) { } // 👈 blockerar klick när fliken inte är aktiv
|
||
) {
|
||
Column(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.padding(
|
||
start = 16.dp,
|
||
end = 16.dp,
|
||
top = innerPadding.calculateTopPadding() + 12.dp,
|
||
bottom = innerPadding.calculateBottomPadding()
|
||
)
|
||
) {
|
||
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") { selectedTab = "mynotes"},
|
||
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)
|
||
.pointerInput(selectedTab) { } // 👈 blockerar klick när fliken inte är aktiv
|
||
) {
|
||
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<String?>(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")
|
||
}
|
||
}
|
||
)
|
||
}
|
||
// === MITT KLOTTER ===
|
||
// if (selectedTab == "mynotes" )
|
||
// {
|
||
Box(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.alpha(if (selectedTab == "mynotes") 1f else 0f)
|
||
.zIndex(if (selectedTab == "mynotes") 1f else 0f)
|
||
.pointerInput(selectedTab) { } // 👈 blockerar klick när fliken inte är aktiv
|
||
) {
|
||
// 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 },
|
||
satellite = satellite,
|
||
night = night
|
||
)
|
||
}
|
||
},
|
||
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
|
||
.fillMaxSize()
|
||
.alpha(if (selectedTab == "about") 1f else 0f)
|
||
.zIndex(if (selectedTab == "about") 1f else 0f)
|
||
.pointerInput(selectedTab) { } // 👈 blockerar klick när fliken inte är aktiv
|
||
) {
|
||
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)
|
||
.pointerInput(selectedTab) { } // 👈 blockerar klick när fliken inte är aktiv
|
||
) {
|
||
SettingsScreen(
|
||
onlyNew = onlyNew,
|
||
satellite = satellite,
|
||
night = night,
|
||
showCoords = showCoords,
|
||
onShowCoordsChanged = { SettingsStore.setShowCoordinates(it); showCoords = it },
|
||
onOnlyNewChanged = { SettingsStore.setOnlyNewHits(it); onlyNew = it },
|
||
onSatelliteChanged = { SettingsStore.setSatelliteMap(it); satellite = it },
|
||
onNightChanged = { SettingsStore.setNightMode(it); night = 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()
|
||
)
|
||
)
|
||
}
|
||
}
|
||
// 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)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
)
|
||
}
|
||
|
||
// Klotter-detalj
|
||
val currentKlotter = openKlotter
|
||
if (currentKlotter != null) {
|
||
KlotterDialog(
|
||
id = currentKlotter.id,
|
||
lat = currentKlotter.lat,
|
||
lon = currentKlotter.lon,
|
||
label = currentKlotter.label,
|
||
currentUserId = currentUserId,
|
||
onClose = { openKlotter = null }
|
||
)
|
||
}
|
||
|
||
// Wiki-detalj
|
||
val currentWiki = openWiki
|
||
if (currentWiki != null) {
|
||
WikiArticleDialog(
|
||
pageId = currentWiki.pageId,
|
||
lat = currentWiki.lat,
|
||
lon = currentWiki.lon,
|
||
onClose = { openWiki = null }
|
||
)
|
||
}
|
||
|
||
// Fornsök-detalj
|
||
val currentForn = openFornsok
|
||
if (currentForn != null) {
|
||
FornsokDialog(
|
||
item = currentForn.item,
|
||
onClose = { openFornsok = null }
|
||
)
|
||
}
|
||
|
||
// DigitaltMuseum-detalj
|
||
val currentDm = openDm
|
||
if (currentDm != null) {
|
||
DmDialog(
|
||
item = currentDm,
|
||
onClose = { openDm = null }
|
||
)
|
||
}
|
||
|
||
// Skrivdialog (dokument)
|
||
var isSavingDoc by remember { mutableStateOf(false) }
|
||
if (showWrite) {
|
||
// Lagra positionen när man klickat Klottra:
|
||
val initial = LastLocationStore.lastKnownLocation.collectAsState()
|
||
val initialLat = initial.value?.lat
|
||
val initialLon = initial.value?.lon
|
||
|
||
WriteDocDialog(
|
||
onClose = { showWrite = false },
|
||
onSave = { draft, selLat, selLon ->
|
||
if (!loggedIn) {
|
||
UiFeedback.showMessage("Du måste logga in för att kunna klottra.", UiFeedbackDuration.SHORT)
|
||
return@WriteDocDialog
|
||
}
|
||
val created = Clock.System.now().toEpochMilliseconds()
|
||
val requestId = UUID.randomUUID()
|
||
|
||
if (isSavingDoc) return@WriteDocDialog
|
||
isSavingDoc = true
|
||
scope.launch {
|
||
try {
|
||
val titleText = draft.title.trim()
|
||
val bodyText = draft.body.trim()
|
||
|
||
// Kör delat online-flöde i IO-tråd
|
||
val outcome = withContext(Dispatchers.IO) {
|
||
createNoteFlow(
|
||
hasImage = draft.image != null,
|
||
uploadImage = {
|
||
// Plattformoberoende läsning via shared ImageReader
|
||
val read = app.klottr.images.ImageReader.read(draft.image!!)
|
||
?: run {
|
||
Api.lastUploadError = "Kunde inte läsa bilddata."
|
||
return@createNoteFlow null
|
||
}
|
||
// 4) ladda upp via commonMain-funktion
|
||
uploadImage(
|
||
data = read.bytes,
|
||
filename = read.filename,
|
||
mime = read.mime,
|
||
lat = selLat,
|
||
lon = selLon
|
||
)
|
||
},
|
||
createNote = { imageId ->
|
||
createNoteDoc(
|
||
lat = selLat,
|
||
lon = selLon,
|
||
title = titleText,
|
||
body = bodyText,
|
||
imageId = imageId,
|
||
radiusM = Config.DEFAULT_KLOTTER_RADIUS_M,
|
||
createdAt = created,
|
||
clientRequestId = requestId
|
||
)
|
||
},
|
||
getUploadError = { Api.lastUploadError }
|
||
)
|
||
}
|
||
|
||
when (outcome) {
|
||
is CreateNoteOutcome.Success -> {
|
||
UiFeedback.showMessage("Sparat.")
|
||
|
||
// Markera nyskapad notis som "hittad" och uppdatera UI direkt
|
||
scope.launch(Dispatchers.IO) {
|
||
try {
|
||
val nearby = Geocache.getNearby(
|
||
lat = selLat,
|
||
lon = selLon,
|
||
radiusMeters = 120,
|
||
ttlMs = 0L
|
||
)
|
||
|
||
// 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(
|
||
LAYER_KLOTTER,
|
||
match.i.toString(),
|
||
label = labelTitle,
|
||
lat = match.a,
|
||
lon = match.o,
|
||
timeMillis = Clock.System.now().toEpochMilliseconds()
|
||
)
|
||
withContext(Dispatchers.Main) {
|
||
// TODO: OH: Nog renare om foundstore är ansvarig för att skicka FoundEvents.
|
||
FoundEvents.notifyFoundUpdated()
|
||
}
|
||
// Tysta avisering för just detta klotter under 60s (slipper “pling” på eget klotter)
|
||
// TODO: OH: How to implement? Via foundstore?
|
||
// 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 */ }
|
||
}
|
||
showWrite = false
|
||
}
|
||
|
||
|
||
is CreateNoteOutcome.UploadFailed -> { // Fallback till offline-utkorg även när bilduppladdning misslyckas
|
||
val titleText = draft.title.trim()
|
||
val bodyText = draft.body.trim()
|
||
|
||
val img = draft.image // Ta en snapshot av den valda bilden
|
||
|
||
val queued = withContext(Dispatchers.IO) {
|
||
queueNoteDocOutbox(
|
||
lat = selLat,
|
||
lon = selLon,
|
||
title = titleText,
|
||
body = bodyText,
|
||
createdAt = created,
|
||
radiusM = Config.DEFAULT_KLOTTER_RADIUS_M,
|
||
hasImage = (img != null), // Använd snapshotten
|
||
persistImageIfAny = {
|
||
val handle = img ?: return@queueNoteDocOutbox null
|
||
val read = app.klottr.images.ImageReader.read(handle) ?: return@queueNoteDocOutbox null
|
||
val saved = ImageWriter.save(
|
||
read = read,
|
||
subdir = "outbox",
|
||
baseName = "img_${created}"
|
||
) ?: return@queueNoteDocOutbox null
|
||
saved.absolutePath to saved.mime
|
||
},
|
||
addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime ->
|
||
OutboxStore.addDoc(
|
||
lat = la,
|
||
lon = lo,
|
||
title = t,
|
||
body = b,
|
||
createdAt = ts,
|
||
radiusM = rad,
|
||
imagePath = imagePath,
|
||
imageMime = imageMime
|
||
)
|
||
},
|
||
scheduleUpload = {
|
||
//TODO: OH: Make sure sheduleUpload adhere to connected constraint.
|
||
OutboxScheduler.scheduleUpload();
|
||
// val constraints = Constraints.Builder()
|
||
// .setRequiredNetworkType(NetworkType.CONNECTED)
|
||
// .build()
|
||
// val req = OneTimeWorkRequestBuilder<OutboxWorker>()
|
||
// .setConstraints(constraints).build()
|
||
// WorkManager.getInstance(context).enqueue(req)
|
||
}
|
||
)
|
||
}
|
||
|
||
when (queued) {
|
||
QueueOutboxOutcome.Queued -> {
|
||
UiFeedback.showMessage( "Offline. Sparas i utkorgen.")
|
||
showWrite = false
|
||
}
|
||
QueueOutboxOutcome.ImagePersistFailed -> {
|
||
val msg = outcome.message ?: "Bilduppladdning misslyckades."
|
||
UiFeedback.showMessage("$msg\nKunde inte spara bilden lokalt.")
|
||
// Stanna kvar i dialogen
|
||
}
|
||
}
|
||
}
|
||
|
||
is CreateNoteOutcome.CreateFailed -> {
|
||
// Lägg i utkorgen via delad use-case (offline)
|
||
val titleText = draft.title.trim()
|
||
val bodyText = draft.body.trim()
|
||
|
||
val img = draft.image // Ta en snapshot av den valda bilden
|
||
|
||
val queued = withContext(Dispatchers.IO) {
|
||
queueNoteDocOutbox(
|
||
lat = selLat,
|
||
lon = selLon,
|
||
title = titleText,
|
||
body = bodyText,
|
||
createdAt = created,
|
||
radiusM = Config.DEFAULT_KLOTTER_RADIUS_M,
|
||
hasImage = (img != null), // Använd snapshotten
|
||
persistImageIfAny = {
|
||
val handle = img ?: return@queueNoteDocOutbox null
|
||
val read = ImageReader.read(handle) ?: return@queueNoteDocOutbox null
|
||
val saved = ImageWriter.save(
|
||
read = read,
|
||
subdir = "outbox",
|
||
baseName = "img_${created}"
|
||
) ?: return@queueNoteDocOutbox null
|
||
saved.absolutePath to saved.mime
|
||
},
|
||
addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime ->
|
||
OutboxStore.addDoc(
|
||
lat = la,
|
||
lon = lo,
|
||
title = t,
|
||
body = b,
|
||
createdAt = ts,
|
||
radiusM = rad,
|
||
imagePath = imagePath,
|
||
imageMime = imageMime
|
||
)
|
||
},
|
||
scheduleUpload = {
|
||
//TODO: OH: Make sure sheduleUpload adhere to connected constraint.
|
||
OutboxScheduler.scheduleUpload()
|
||
// val constraints = Constraints.Builder()
|
||
// .setRequiredNetworkType(NetworkType.CONNECTED)
|
||
// .build()
|
||
// val req = OneTimeWorkRequestBuilder<OutboxWorker>()
|
||
// .setConstraints(constraints).build()
|
||
// WorkManager.getInstance(context).enqueue(req)
|
||
}
|
||
)
|
||
}
|
||
|
||
|
||
when (queued) {
|
||
QueueOutboxOutcome.Queued -> {
|
||
UiFeedback.showMessage( "Offline. Sparas i utkorgen.")
|
||
showWrite = false
|
||
}
|
||
QueueOutboxOutcome.ImagePersistFailed -> {
|
||
UiFeedback.showMessage("Kunde inte spara bilden lokalt.")
|
||
// Stanna kvar i dialogen, låt användaren försöka igen eller spara utan bild
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} finally {
|
||
isSavingDoc = false
|
||
}
|
||
}
|
||
},
|
||
initialLat = initialLat,
|
||
initialLon = initialLon,
|
||
resetSavingCounter = resetSavingCounter
|
||
)
|
||
}
|
||
|
||
if (showLoginRequired) {
|
||
AlertDialog(
|
||
onDismissRequest = { showLoginRequired = false },
|
||
title = { Text("Inloggning krävs") },
|
||
text = {
|
||
LoginRequiredContent(
|
||
message = "Du måste logga in för att kunna klottra.",
|
||
textStyle = MaterialTheme.typography.bodyMedium.copy(
|
||
color = MaterialTheme.colorScheme.onSurface // Följer dag/natt
|
||
)
|
||
)
|
||
},
|
||
confirmButton = {
|
||
Button(onClick = {
|
||
showLoginRequired = false
|
||
onLogin() // använder samma onLogin som redan används av “Logga in”-knappen
|
||
}) { Text("Logga in") }
|
||
},
|
||
dismissButton = {
|
||
Button(onClick = { showLoginRequired = false }) {
|
||
Text("Stäng")
|
||
}
|
||
}
|
||
)
|
||
}
|
||
// --- Välj användarnamn (blockerande) ---
|
||
if (showUsernameDialog && loggedIn) {
|
||
UsernameDialog(
|
||
onSaved = { chosen ->
|
||
showUsernameDialog = false
|
||
scope.launch {
|
||
me = withContext(Dispatchers.IO) { app.klottr.net.fetchMe() }
|
||
}
|
||
// Should be short message.
|
||
UiFeedback.showMessage("Användarnamn satt till ”$chosen”.", UiFeedbackDuration.SHORT)
|
||
},
|
||
onLogout = {
|
||
onLogout() // ← samma onLogout som du redan skickar in till KlottrApp
|
||
}
|
||
)
|
||
}
|
||
}
|
||
|
||
|
||
@Composable
|
||
private fun MenuTile(icon: ImageVector, label: String, onClick: () -> Unit) {
|
||
Card(
|
||
onClick = onClick,
|
||
modifier = Modifier.size(110.dp),
|
||
shape = MaterialTheme.shapes.medium,
|
||
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
|
||
) {
|
||
Column(
|
||
modifier = Modifier
|
||
.fillMaxSize()
|
||
.padding(12.dp),
|
||
horizontalAlignment = Alignment.CenterHorizontally,
|
||
verticalArrangement = Arrangement.Center
|
||
) {
|
||
Icon(
|
||
icon,
|
||
contentDescription = label,
|
||
modifier = Modifier.size(32.dp),
|
||
tint = MaterialTheme.colorScheme.primary
|
||
)
|
||
Spacer(modifier = Modifier.height(8.dp))
|
||
Text(
|
||
label,
|
||
style = MaterialTheme.typography.bodySmall,
|
||
textAlign = TextAlign.Center
|
||
)
|
||
}
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
fun AccountScreen(
|
||
me: app.klottr.net.MeShared?,
|
||
userStats: app.klottr.net.UserStats?,
|
||
onLogin: () -> Unit,
|
||
onLogout: () -> Unit,
|
||
onDeleteAccount: () -> Unit,
|
||
onChangeUsername: () -> Unit,
|
||
modifier: Modifier = Modifier
|
||
) {
|
||
Column(
|
||
modifier = modifier
|
||
.fillMaxSize()
|
||
.padding(16.dp),
|
||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||
) {
|
||
Card(
|
||
modifier = Modifier.fillMaxWidth(),
|
||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||
) {
|
||
Column(
|
||
modifier = Modifier.padding(16.dp),
|
||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||
) {
|
||
if (me != null) {
|
||
Text("E-post", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
|
||
Text(me.email ?: "-", style = MaterialTheme.typography.bodyLarge)
|
||
|
||
Spacer(Modifier.height(8.dp))
|
||
|
||
Text("Användarnamn", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
|
||
Row(
|
||
modifier = Modifier.fillMaxWidth(),
|
||
verticalAlignment = Alignment.CenterVertically
|
||
) {
|
||
Text(
|
||
me.username ?: "-",
|
||
style = MaterialTheme.typography.bodyLarge,
|
||
modifier = Modifier.alignByBaseline()
|
||
)
|
||
Spacer(Modifier.weight(1f))
|
||
if (me.canChangeUsername == true) {
|
||
AssistChip(
|
||
onClick = onChangeUsername,
|
||
label = { Text("Byt användarnamn") }, // kortare text gör den ännu smalare
|
||
leadingIcon = { Icon(Icons.Filled.Edit, contentDescription = null) },
|
||
modifier = Modifier
|
||
.alignByBaseline()
|
||
.height(28.dp) // gör chippen lägre än standard
|
||
)
|
||
}
|
||
}
|
||
|
||
if (me.canChangeUsername == false && me.nextChangeAllowedAt != null) {
|
||
Spacer(Modifier.height(4.dp))
|
||
Text(
|
||
"Du kan byta användarnamn igen tidigast ${me.nextChangeAllowedAt}",
|
||
style = MaterialTheme.typography.bodySmall,
|
||
color = MaterialTheme.colorScheme.error
|
||
)
|
||
}
|
||
|
||
Spacer(Modifier.height(16.dp))
|
||
|
||
// Horisontell linje ovanför statistikdelen
|
||
HorizontalDivider(color = MaterialTheme.colorScheme.outline, thickness = 1.dp)
|
||
|
||
Box(modifier = Modifier.fillMaxWidth()) {
|
||
Text(
|
||
"Statistik",
|
||
style = MaterialTheme.typography.titleMedium,
|
||
color = MaterialTheme.colorScheme.primary,
|
||
modifier = Modifier.align(Alignment.Center) // 👈 centrerad
|
||
)
|
||
}
|
||
|
||
Spacer(Modifier.height(8.dp))
|
||
|
||
// Första inloggning
|
||
Text(
|
||
"Första inloggning",
|
||
style = MaterialTheme.typography.labelLarge,
|
||
color = MaterialTheme.colorScheme.primary
|
||
)
|
||
Text(me.firstLogin ?: "-", style = MaterialTheme.typography.bodyLarge)
|
||
|
||
Spacer(Modifier.height(12.dp))
|
||
|
||
// Antal skapade klotter
|
||
Text(
|
||
"Antal skapade klotter",
|
||
style = MaterialTheme.typography.labelLarge,
|
||
color = MaterialTheme.colorScheme.primary
|
||
)
|
||
|
||
if (userStats != null) {
|
||
val deletedText = when (userStats.deleted) {
|
||
0 -> "(inga raderade)"
|
||
1 -> "(varav ett raderat)"
|
||
else -> "(varav ${userStats.deleted} raderade)"
|
||
}
|
||
Text(
|
||
"${userStats.total} $deletedText",
|
||
style = MaterialTheme.typography.bodyLarge
|
||
)
|
||
} else {
|
||
Text(
|
||
"Statistik saknas",
|
||
style = MaterialTheme.typography.bodyLarge
|
||
)
|
||
}
|
||
|
||
} else {
|
||
Text("Ingen användare inloggad.", style = MaterialTheme.typography.bodyLarge)
|
||
}
|
||
}
|
||
}
|
||
|
||
Card(
|
||
modifier = Modifier.fillMaxWidth(),
|
||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||
) {
|
||
Column(
|
||
modifier = Modifier.padding(16.dp),
|
||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||
) {
|
||
if (me == null) {
|
||
Button(
|
||
onClick = onLogin,
|
||
modifier = Modifier.fillMaxWidth(),
|
||
colors = ButtonDefaults.buttonColors(
|
||
containerColor = MaterialTheme.colorScheme.primary,
|
||
contentColor = MaterialTheme.colorScheme.onPrimary
|
||
)
|
||
) {
|
||
Icon(Icons.Filled.Login, contentDescription = null)
|
||
Spacer(Modifier.width(8.dp))
|
||
Text("Logga in")
|
||
}
|
||
} else {
|
||
Button(
|
||
onClick = onLogout,
|
||
modifier = Modifier.fillMaxWidth(),
|
||
colors = ButtonDefaults.buttonColors(
|
||
containerColor = MaterialTheme.colorScheme.primary,
|
||
contentColor = MaterialTheme.colorScheme.onPrimary
|
||
)
|
||
) {
|
||
Icon(Icons.Filled.Login, contentDescription = null)
|
||
Spacer(Modifier.width(8.dp))
|
||
Text("Logga ut")
|
||
}
|
||
|
||
OutlinedButton(
|
||
onClick = onDeleteAccount,
|
||
modifier = Modifier.fillMaxWidth(),
|
||
colors = ButtonDefaults.outlinedButtonColors(
|
||
contentColor = MaterialTheme.colorScheme.error
|
||
),
|
||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error)
|
||
) {
|
||
Icon(
|
||
Icons.Filled.Delete,
|
||
contentDescription = null,
|
||
tint = MaterialTheme.colorScheme.error
|
||
)
|
||
Spacer(Modifier.width(8.dp))
|
||
Text("Radera konto (ej implementerat)")
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
@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() }
|
||
}
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun SwitchRow(label: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit) {
|
||
Row(
|
||
modifier = Modifier
|
||
.fillMaxWidth()
|
||
.padding(vertical = 4.dp),
|
||
horizontalArrangement = Arrangement.SpaceBetween,
|
||
verticalAlignment = Alignment.CenterVertically
|
||
) {
|
||
Text(label, style = MaterialTheme.typography.bodyLarge)
|
||
androidx.compose.material3.Switch(checked = checked, onCheckedChange = onCheckedChange)
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun SliderRow(
|
||
label: String,
|
||
value: Float,
|
||
onValueChange: (Float) -> Unit,
|
||
valueRange: ClosedFloatingPointRange<Float>
|
||
) {
|
||
Column(modifier = Modifier.fillMaxWidth()) {
|
||
Text(label, style = MaterialTheme.typography.bodyMedium)
|
||
androidx.compose.material3.Slider(
|
||
value = value,
|
||
onValueChange = onValueChange,
|
||
valueRange = valueRange
|
||
)
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun ValuePickerRow(
|
||
label: String,
|
||
enabled: Boolean,
|
||
selectedValue: Int,
|
||
options: List<Int>,
|
||
onPick: (Int) -> Unit
|
||
) {
|
||
var expanded by remember { mutableStateOf(false) }
|
||
val current = app.klottr.util.formatDistance(selectedValue)
|
||
|
||
Column {
|
||
Row(
|
||
modifier = Modifier
|
||
.fillMaxWidth()
|
||
.padding(top = 4.dp, bottom = 6.dp),
|
||
verticalAlignment = Alignment.CenterVertically
|
||
) {
|
||
Text(label, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f))
|
||
Box(
|
||
modifier = Modifier
|
||
.border(1.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(10.dp))
|
||
.background(
|
||
if (enabled) MaterialTheme.colorScheme.surfaceVariant
|
||
else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
|
||
RoundedCornerShape(10.dp)
|
||
)
|
||
.clickable(enabled = enabled, onClick = { expanded = !expanded })
|
||
.padding(horizontal = 12.dp, vertical = 8.dp)
|
||
) {
|
||
Text("$current ▾", style = MaterialTheme.typography.bodyMedium)
|
||
}
|
||
}
|
||
|
||
if (expanded) {
|
||
Column(
|
||
modifier = Modifier
|
||
.fillMaxWidth()
|
||
.border(1.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(10.dp))
|
||
.background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(10.dp))
|
||
) {
|
||
options.forEach { v ->
|
||
val labelText = app.klottr.util.formatDistance(v)
|
||
val selected = v == selectedValue
|
||
val bg = if (selected)
|
||
MaterialTheme.colorScheme.primary.copy(alpha = 0.12f)
|
||
else
|
||
Color.Transparent
|
||
Row(
|
||
modifier = Modifier
|
||
.fillMaxWidth()
|
||
.background(bg)
|
||
.clickable(enabled = enabled) {
|
||
onPick(v)
|
||
expanded = false
|
||
}
|
||
.padding(horizontal = 12.dp, vertical = 10.dp)
|
||
) {
|
||
Text(
|
||
text = if (selected) "✓ $labelText" else labelText,
|
||
style = if (selected)
|
||
MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Medium)
|
||
else
|
||
MaterialTheme.typography.bodyMedium
|
||
)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
@Composable
|
||
private fun DiscreteSliderRow(
|
||
label: String,
|
||
value: Int,
|
||
grMin: Int,
|
||
grMax: Int,
|
||
onValueChange: (Int, Boolean) -> Unit
|
||
) {
|
||
// 🔸 Lista över steg – innehåller alltid -1 först som betyder “inaktivt lager”
|
||
val steps = remember(grMin, grMax) { app.klottr.util.generateRadiusSteps(grMin, grMax) }
|
||
val allSteps = remember { listOf(-1) + steps }
|
||
|
||
// 🔸 Hitta aktuellt index (t.ex. -1 → index 0, 20 → index 1, 50 → index 2, osv.)
|
||
val currentIndex = remember(value) {
|
||
allSteps.indexOfFirst { it == value }.takeIf { it >= 0 } ?: 0
|
||
}
|
||
|
||
var sliderPos by remember { mutableStateOf(currentIndex.toFloat()) }
|
||
val isEnabled = allSteps.getOrNull(sliderPos.roundToInt()) != -1
|
||
|
||
Column(modifier = Modifier.fillMaxWidth()) {
|
||
|
||
// 🔹 Etiketttext
|
||
val displayText = if (!isEnabled) "Visas ej" else app.klottr.util.formatDistance(value)
|
||
Text(
|
||
"$label: $displayText",
|
||
style = MaterialTheme.typography.bodyMedium,
|
||
color = if (isEnabled)
|
||
MaterialTheme.colorScheme.onSurface
|
||
else
|
||
MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f)
|
||
)
|
||
// 🧭 Om bara ett steg (t.ex. Klotter), visa en på/av-knapp i stället för slider
|
||
if (steps.size == 1) {
|
||
Row(
|
||
modifier = Modifier
|
||
.fillMaxWidth()
|
||
.padding(vertical = 8.dp, horizontal = 32.dp),
|
||
horizontalArrangement = Arrangement.Center,
|
||
verticalAlignment = Alignment.CenterVertically
|
||
) {
|
||
Text(
|
||
if (isEnabled) "På" else "Av",
|
||
style = MaterialTheme.typography.bodyMedium,
|
||
modifier = Modifier.padding(end = 12.dp)
|
||
)
|
||
Switch(
|
||
checked = isEnabled,
|
||
onCheckedChange = { checked ->
|
||
val newVal = if (checked) steps.first() else -1
|
||
sliderPos = if (checked) 1f else 0f
|
||
onValueChange(newVal, checked)
|
||
}
|
||
)
|
||
}
|
||
} else {
|
||
// 🧭 Annars: vanlig slider
|
||
androidx.compose.material3.Slider(
|
||
value = sliderPos,
|
||
onValueChange = { newPos ->
|
||
val newIdx = newPos.roundToInt().coerceIn(0, allSteps.lastIndex)
|
||
sliderPos = newIdx.toFloat()
|
||
val newVal = allSteps[newIdx]
|
||
val newEnabled = newVal != -1
|
||
onValueChange(newVal, newEnabled)
|
||
},
|
||
steps = allSteps.size - 2,
|
||
valueRange = 0f..(allSteps.size - 1).toFloat(),
|
||
modifier = Modifier
|
||
.fillMaxWidth()
|
||
.padding(horizontal = 32.dp)
|
||
)
|
||
}
|
||
}
|
||
}
|