DetailDialogsShell (finally!) platform independent and moved to shared

This commit is contained in:
Olof Hedman
2025-09-24 16:45:12 +02:00
parent ed3cf0e56a
commit b98a12abe0
4 changed files with 29 additions and 10 deletions

View File

@@ -3,7 +3,12 @@ package app.klottr.platform
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.Dp
//TODO: OH: Verkar som vi inte borde bero på dessa, utan använda compose api:et LocalWindowInfo.containerSize istället
// som redan är platformsoberoende
/**
* Platform-agnostic screen height in dp for sizing dialogs proportionally.
*/
@Composable expect fun platformScreenHeightDp(): Dp
@Composable expect fun platformScreenWidthDp(): Dp

View File

@@ -0,0 +1,347 @@
package app.klottr.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue // Gör 'by remember { ... }' läsbart
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue // Gör 'by remember { ... }' skrivbart
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.DialogProperties
import app.klottr.net.DigitaltMuseumItem
import app.klottr.net.FornsokItem
import app.klottr.net.Wikipedia
import app.klottr.location.LocationServiceProvider
import app.klottr.platform.AppNavigator
import app.klottr.platform.platformScreenWidthDp
import app.klottr.util.SettingsStore
import app.klottr.util.formatCoords
import app.klottr.util.formatDistance
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.withContext
import kotlin.math.roundToInt
// Lämna imports tomma. Android Studio lägger in exakt vad som behövs när du klistrar in funktionerna.
@Composable
fun WikiArticleDialog(
pageId: Long,
lat: Double?,
lon: Double?,
onClose: () -> Unit
) {
val dialogWidth = (platformScreenWidthDp() * 0.98f)
var loading by remember { mutableStateOf(true) }
var title by remember { mutableStateOf("") }
var extract by remember { mutableStateOf("") }
// Avståndstext uppdateras via KMP LocationService
var wikiDistanceText by remember { mutableStateOf("-") }
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
val locService = remember { LocationServiceProvider.get() }
DisposableEffect(Unit) {
locService.start()
onDispose { locService.stop() }
}
val current = locService.location.collectAsState(initial = null)
LaunchedEffect(current.value?.lat, current.value?.lon, lat, lon) {
val gp = current.value
val d = if (lat != null && lon != null && gp != null)
app.klottr.util.distanceMeters(gp.lat, gp.lon, lat, lon).roundToInt()
else null
wikiDistanceText = d?.let { f -> "${f}\u00A0m" } ?: "-"
}
LaunchedEffect(pageId) {
loading = true
val detail = withContext(Dispatchers.IO) { Wikipedia.getExtract(pageId) }
title = detail.title
extract = detail.extract
loading = false
}
AlertDialog(
onDismissRequest = onClose,
properties = DialogProperties(usePlatformDefaultWidth = false),
title = {
Box(Modifier.fillMaxWidth().widthIn(max = dialogWidth)) {
Text(if (title.isNotBlank()) title else "Wikipedia")
}
},
text = {
Box(
Modifier
.fillMaxWidth()
.widthIn(max = dialogWidth)
.heightIn(max = 520.dp)
) {
if (loading) {
Text("Söker …")
} else {
WikiDetailContent(
titleText = title,
extractText = extract,
distanceText = wikiDistanceText, // Oför: redan beräknad
coordText = if (showCoords && lat != null && lon != null) formatCoords(lat, lon) else null,
pageId = pageId,
titleStyle = MaterialTheme.typography.titleLarge.copy(
color = MaterialTheme.colorScheme.onSurface // Ny: följer dag/natt
),
bodyStyle = MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurface // Ny
),
captionStyle = MaterialTheme.typography.bodySmall.copy(
color = MaterialTheme.colorScheme.onSurfaceVariant // Ny
),
actions = {
Button(onClick = {
val url = "https://sv.m.wikipedia.org/?curid=$pageId"
AppNavigator.openUrl(url);
}) { Text("Läs mer") }
Button(
onClick = {
if (lat != null && lon != null) {
val label = if (title.isNullOrBlank()) "Wikipedia-plats" else title // Ny: hantera null/blank
AppNavigator.openMap(lat, lon, label)
}
},
enabled = lat != null && lon != null
) { Text("Maps") }
}
)
}
}
},
confirmButton = { Button(onClick = onClose) { Text("Stäng") } }
)
}
@Composable
fun FornsokDialog(
item: FornsokItem,
onClose: () -> Unit
) {
val dialogWidth = (platformScreenWidthDp() * 0.98f)
// Vi använder fälten från FornsokItem; om desc/uri saknas visar vi "saknas"-text.
val title = remember(item.id) { item.title.ifBlank { "Fornlämning" } }
val desc = remember(item.id) { item.desc ?: "" }
val link = remember(item.id) { item.uri ?: (if (item.id.startsWith("http")) item.id else null) }
val platLat = item.lat
val platLon = item.lon
// Avståndstext uppdateras via KMP LocationService
var fornDistanceText by remember { mutableStateOf("-") }
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
val locService = remember { LocationServiceProvider.get() }
LaunchedEffect(Unit) { locService.start() }
val current = locService.location.collectAsState(initial = null)
LaunchedEffect(current.value?.lat, current.value?.lon, platLat, platLon) {
val gp = current.value
val d = if (gp != null)
app.klottr.util.distanceMeters(gp.lat, gp.lon, platLat, platLon).roundToInt()
else null
fornDistanceText = d?.let { f -> "${f}\u00A0m" } ?: "-"
}
AlertDialog(
onDismissRequest = onClose,
properties = DialogProperties(usePlatformDefaultWidth = false),
title = {
Box(Modifier.fillMaxWidth().widthIn(max = dialogWidth)) {
Text(title)
}
},
text = {
Box(
Modifier
.fillMaxWidth()
.widthIn(max = dialogWidth)
.heightIn(max = 520.dp)
) {
FornsokDetailContent(
titleText = title,
descText = desc,
distanceText = fornDistanceText,
coordText = if (showCoords) formatCoords(platLat, platLon) else null,
titleStyle = MaterialTheme.typography.titleLarge.copy(
color = MaterialTheme.colorScheme.onSurface
),
bodyStyle = MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurface
),
captionStyle = MaterialTheme.typography.bodySmall.copy(
color = MaterialTheme.colorScheme.onSurfaceVariant
),
actions = {
Button(
onClick = {
AppNavigator.openMap(platLat, platLon, title)
}
) { Text("Maps") }
Button(
onClick = {
val u = link ?: return@Button
AppNavigator.openUrl(u)
},
enabled = link != null
) { Text("Läs mer") }
}
)
}
},
confirmButton = { Button(onClick = onClose) { Text("Stäng") } }
)
}
@Composable
fun DmDialog(
item: DigitaltMuseumItem,
onClose: () -> Unit
) {
val dialogWidth = (platformScreenWidthDp() * 0.98f)
var detailText by remember { mutableStateOf<String?>(null) }
var loading by remember { mutableStateOf(false) }
// Avstånd som tickar
var dmDistanceText by remember { mutableStateOf("-") }
val showCoords = remember { SettingsStore.getShowCoordinates() }
fun recalcDmDistance() {
val my = app.klottr.location.LastLocationStore.lastKnownLocation.value
val d = my?.let {
app.klottr.util.distanceMeters(it.lat, it.lon, item.lat, item.lon).roundToInt()
}
dmDistanceText = d?.let { formatDistance(it) } ?: "-"
}
LaunchedEffect(item.lat, item.lon) { recalcDmDistance() }
// Hämta miniatyr om vi har bild-URL
LaunchedEffect(item.id) {
// Text (om uniqueId finns)
detailText = withContext(Dispatchers.IO) {
app.klottr.net.DigitaltMuseum.getDetailText(
uniqueId = item.uniqueId,
owner = item.owner,
identifierId = item.id
)
}
}
// Post-process: om text saknas eller är samma som titel, försök stycka titeln i meningar.
val originalTitle = item.title.ifBlank { "DigitaltMuseum" }.trim()
val bodyFromApi = detailText?.trim()
fun splitSentences(s: String): Pair<String, String?> {
// Enkel men robust meningdelning: dela på . ! ? följt av mellanslag och stor bokstav/siffra
val regex = Regex("(?<=[.!?])\\s+(?=[A-ZÅÄÖ0-9])")
val parts = s.split(regex).map { it.trim() }.filter { it.isNotEmpty() }
return if (parts.size >= 2) {
val first = parts.first()
val rest = parts.drop(1).joinToString(" ").take(4000).trim().ifEmpty { null }
first to rest
} else s to null
}
val (displayTitle, displayBody) = run {
val noBody = bodyFromApi.isNullOrBlank()
val sameAsTitle =
!bodyFromApi.isNullOrBlank() && bodyFromApi.equals(originalTitle, ignoreCase = true)
if (noBody || sameAsTitle) {
val (t, rest) = splitSentences(originalTitle)
t to rest
} else {
originalTitle to bodyFromApi
}
}
AlertDialog(
onDismissRequest = onClose,
properties = DialogProperties(usePlatformDefaultWidth = false),
title = {
Box(Modifier.fillMaxWidth().widthIn(max = dialogWidth)) {
Text(displayTitle)
}
},
text = {
Box(
Modifier
.fillMaxWidth()
.widthIn(max = dialogWidth)
.heightIn(max = 520.dp)
) {
val displayTitle = remember(item.id, detailText) {
val t = item.title.ifBlank { "DigitaltMuseum" }.trim()
t
}
// Samma heuristik som du hade: splitta ev. text
val (firstLine, restText) = remember(item.id, detailText) {
val body = detailText?.trim().orEmpty()
if (body.isBlank()) "" to null
else {
val idx = body.indexOfFirst { it == '.' || it == '!' || it == '?' }
if (idx >= 0 && idx + 1 < body.length) {
val first = body.substring(0, idx + 1).trim()
val rest = body.substring(idx + 1).trim().ifEmpty { null }
first to rest
} else body to null
}
}
DmDetailContent(
titleText = displayTitle,
bodyText = listOfNotNull(firstLine, restText).joinToString("\n\n"),
distanceText = dmDistanceText,
coordText = if (showCoords) formatCoords(item.lat, item.lon) else null,
imageUrl = item.url,
titleStyle = MaterialTheme.typography.titleLarge.copy(
color = MaterialTheme.colorScheme.onSurface
),
bodyStyle = MaterialTheme.typography.bodyMedium.copy(
color = MaterialTheme.colorScheme.onSurface
),
captionStyle = MaterialTheme.typography.bodySmall.copy(
color = MaterialTheme.colorScheme.onSurfaceVariant
),
actions = {
Button(
onClick = {
AppNavigator.openMap(item.lat, item.lon, displayTitle)
}
) { Text("Maps") }
Button(
onClick = {
val u = item.webUrl // Ändrad: objectUrl -> webUrl
if (!u.isNullOrBlank()) {
AppNavigator.openUrl(u)
}
},
enabled = !item.webUrl.isNullOrBlank() // Ändrad: objectUrl -> webUrl
) { Text("Läs mer") }
}
)
}
},
confirmButton = { Button(onClick = onClose) { Text("Stäng") } }
)
}