From 7085e42b17b85cb8b0a1a04d0d5fc4dfd4ca3eb2 Mon Sep 17 00:00:00 2001 From: Fabian Norlin Date: Mon, 15 Sep 2025 00:46:00 +0200 Subject: [PATCH] shared(ui): add WriteDocContent; app(write): integrate and fix focus/placeholder/cursor; outbox: persist image using captured URI --- app/src/main/java/app/klottr/MainActivity.kt | 260 ++++++++---------- .../kotlin/app/klottr/ui/WriteDocContent.kt | 164 +++++++++++ 2 files changed, 275 insertions(+), 149 deletions(-) create mode 100644 shared/src/commonMain/kotlin/app/klottr/ui/WriteDocContent.kt diff --git a/app/src/main/java/app/klottr/MainActivity.kt b/app/src/main/java/app/klottr/MainActivity.kt index 4d17c54..8a98416 100644 --- a/app/src/main/java/app/klottr/MainActivity.kt +++ b/app/src/main/java/app/klottr/MainActivity.kt @@ -145,6 +145,7 @@ import app.klottr.ui.NearbyEntryRow import app.klottr.ui.NearbyList // Delad material-fri listkomponent import app.klottr.ui.MapPanelShell import app.klottr.ui.SettingsContent // Delad material-fri UI för inställningar +import app.klottr.ui.WriteDocContent // Använd delad, material-fri formulär-UI import app.klottr.util.Auth import app.klottr.util.Config import app.klottr.util.FoundStore @@ -1079,80 +1080,11 @@ private fun KlottrApp( } is CreateNoteOutcome.UploadFailed -> { // Fallback till offline-utkorg även när bilduppladdning misslyckas - val titleText = draft.title.trim() - val bodyText = draft.body.trim() - - val queued = withContext(Dispatchers.IO) { - queueNoteDocOutbox( - lat = selLat, - lon = selLon, - title = titleText, - body = bodyText, - createdAt = created, - radiusM = Config.DEFAULT_KLOTTER_RADIUS_M, - hasImage = (draft.imageUri != null), - persistImageIfAny = { - val uri = draft.imageUri ?: return@queueNoteDocOutbox null - val mime = context.contentResolver.getType(uri) ?: "image/jpeg" - val ext = when { - mime.equals("image/jpeg", true) || mime.equals("image/jpg", true) -> ".jpg" - mime.equals("image/png", true) -> ".png" - else -> ".img" - } - val outDir = File(context.filesDir, "outbox").apply { mkdirs() } - val outFile = File(outDir, "img_${created}$ext") - try { - context.contentResolver.openInputStream(uri)?.use { ins -> - outFile.outputStream().use { outs -> ins.copyTo(outs, 8 * 1024) } - } - outFile.absolutePath to mime - } catch (_: Exception) { - null - } - }, - addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime -> - OutboxStore.addDoc( - context = context, - lat = la, - lon = lo, - title = t, - body = b, - createdAt = ts, - radiusM = rad, - imagePath = imagePath, - imageMime = imageMime - ) - }, - scheduleUpload = { - val constraints = Constraints.Builder() - .setRequiredNetworkType(NetworkType.CONNECTED) - .build() - val req = OneTimeWorkRequestBuilder() - .setConstraints(constraints).build() - WorkManager.getInstance(context).enqueue(req) - } - ) - } - - when (queued) { - QueueOutboxOutcome.Queued -> { - Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show() - showWrite = false - } - QueueOutboxOutcome.ImagePersistFailed -> { - val msg = outcome.message ?: "Bilduppladdning misslyckades." - Toast.makeText(context, "$msg\nKunde inte spara bilden lokalt.", Toast.LENGTH_LONG).show() - // 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 imgUri = draft.imageUri // Ta en snapshot av den valda bilden + val queued = withContext(Dispatchers.IO) { queueNoteDocOutbox( lat = selLat, @@ -1161,10 +1093,10 @@ private fun KlottrApp( body = bodyText, createdAt = created, radiusM = Config.DEFAULT_KLOTTER_RADIUS_M, - hasImage = (draft.imageUri != null), + hasImage = (imgUri != null), // Använd snapshotten persistImageIfAny = { - // Spara vald bild till appens outbox-mapp, returnera (path, mime) eller null vid fel - val uri = draft.imageUri ?: return@queueNoteDocOutbox null + val uri = imgUri ?: return@queueNoteDocOutbox null + try { context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } catch (_: Exception) {} val mime = context.contentResolver.getType(uri) ?: "image/jpeg" val ext = when { mime.equals("image/jpeg", true) || mime.equals("image/jpg", true) -> ".jpg" @@ -1178,9 +1110,7 @@ private fun KlottrApp( outFile.outputStream().use { outs -> ins.copyTo(outs, 8 * 1024) } } outFile.absolutePath to mime - } catch (_: Exception) { - null - } + } catch (_: Exception) { null } }, addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime -> OutboxStore.addDoc( @@ -1206,6 +1136,78 @@ private fun KlottrApp( ) } + when (queued) { + QueueOutboxOutcome.Queued -> { + Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show() + showWrite = false + } + QueueOutboxOutcome.ImagePersistFailed -> { + val msg = outcome.message ?: "Bilduppladdning misslyckades." + Toast.makeText(context, "$msg\nKunde inte spara bilden lokalt.", Toast.LENGTH_LONG).show() + // 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 imgUri = draft.imageUri // 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 = (imgUri != null), // Använd snapshotten + persistImageIfAny = { + val uri = imgUri ?: return@queueNoteDocOutbox null + try { context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } catch (_: Exception) {} + val mime = context.contentResolver.getType(uri) ?: "image/jpeg" + val ext = when { + mime.equals("image/jpeg", true) || mime.equals("image/jpg", true) -> ".jpg" + mime.equals("image/png", true) -> ".png" + else -> ".img" + } + val outDir = File(context.filesDir, "outbox").apply { mkdirs() } + val outFile = File(outDir, "img_${created}$ext") + try { + context.contentResolver.openInputStream(uri)?.use { ins -> + outFile.outputStream().use { outs -> ins.copyTo(outs, 8 * 1024) } + } + outFile.absolutePath to mime + } catch (_: Exception) { null } + }, + addOutboxDoc = { la, lo, t, b, ts, rad, imagePath, imageMime -> + OutboxStore.addDoc( + context = context, + lat = la, + lon = lo, + title = t, + body = b, + createdAt = ts, + radiusM = rad, + imagePath = imagePath, + imageMime = imageMime + ) + }, + scheduleUpload = { + val constraints = Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + val req = OneTimeWorkRequestBuilder() + .setConstraints(constraints).build() + WorkManager.getInstance(context).enqueue(req) + } + ) + } + + when (queued) { QueueOutboxOutcome.Queued -> { Toast.makeText(context, "Offline. Sparas i utkorgen.", Toast.LENGTH_LONG).show() @@ -1402,7 +1404,6 @@ private fun WriteDocDialog( } val satellite = SettingsStore.getSatelliteMap() - AlertDialog( onDismissRequest = onClose, title = { Text("Klottra här") }, @@ -1468,76 +1469,37 @@ private fun WriteDocDialog( } // --- Formdel: scrollbar --- - val scroll = rememberScrollState() - Column( - modifier = Modifier - .verticalScroll(scroll) - .imePadding(), - verticalArrangement = Arrangement.spacedBy(12.dp) - ) { - OutlinedTextField( - value = title, - onValueChange = { - title = it - if (titleError != null && it.isNotBlank()) titleError = null // rensa fel när man börjar skriva något annat än blanksteg - }, - modifier = Modifier - .fillMaxWidth() - .focusRequester(titleFocus), - label = { Text("Rubrik") }, // inte längre “(valfri)” - singleLine = true, - isError = titleError != null, // röd ram när fel - supportingText = { - if (titleError != null) { - Text( - titleError!!, - color = MaterialTheme.colorScheme.error, - style = MaterialTheme.typography.bodySmall - ) - } - } - ) + // Beräkna förhandsvisning som ImageBitmap för delad UI + val imgBitmap: androidx.compose.ui.graphics.ImageBitmap? = remember(imageUri) { + if (imageUri == null) return@remember null + try { + context.contentResolver.openInputStream(imageUri!!).use { ins -> + android.graphics.BitmapFactory.decodeStream(ins)?.asImageBitmap() + } + } catch (_: Exception) { null } + } - // Bildförhandsvisning (om vald) - val bmp: Bitmap? = remember(imageUri) { - if (imageUri == null) return@remember null - try { - context.contentResolver.openInputStream(imageUri!!).use { ins -> - BitmapFactory.decodeStream(ins) - } - } catch (_: Exception) { null } - } - if (bmp != null) { - Image( - bitmap = bmp.asImageBitmap(), - contentDescription = null, - modifier = Modifier - .fillMaxWidth() - .heightIn(min = 120.dp, max = 240.dp) - .clip(RoundedCornerShape(8.dp)), - contentScale = ContentScale.Fit - ) - } - - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Button(onClick = { - picker.launch(PickVisualMediaRequest(PickVisualMedia.ImageOnly)) - }) { Text(if (imageUri == null) "Välj bild" else "Byt bild") } - - if (imageUri != null) { - Button(onClick = { imageUri = null }) { Text("Ta bort bild") } - } - } - - OutlinedTextField( - value = body, - onValueChange = { body = it }, - modifier = Modifier - .fillMaxWidth() - .heightIn(min = 120.dp), - placeholder = { Text("Din text…") } - ) - } + WriteDocContent( + title = title, + onTitleChange = { + title = it + if (titleError != null && it.isNotBlank()) titleError = null + }, + titleError = titleError, + body = body, + onBodyChange = { body = it }, + hasImage = (imageUri != null), + imagePreview = imgBitmap, + onPickImage = { + picker.launch( + PickVisualMediaRequest(PickVisualMedia.ImageOnly) + ) + }, + onRemoveImage = { imageUri = null }, + rowTextStyle = MaterialTheme.typography.bodyMedium.copy( + color = MaterialTheme.colorScheme.onSurface + ) + ) } }, confirmButton = { @@ -1819,8 +1781,8 @@ private fun SettingsDialog( .height(maxDialogHeight) ) { SettingsContent( - versionLine = versionLine, // Ny - buildTimeLine = buildTimeLine, // Ny + versionLine = versionLine, + buildTimeLine = buildTimeLine, onlyNew = onlyNew, onOnlyNewChanged = onOnlyNewChanged, showCoords = showCoords, diff --git a/shared/src/commonMain/kotlin/app/klottr/ui/WriteDocContent.kt b/shared/src/commonMain/kotlin/app/klottr/ui/WriteDocContent.kt new file mode 100644 index 0000000..e6770e6 --- /dev/null +++ b/shared/src/commonMain/kotlin/app/klottr/ui/WriteDocContent.kt @@ -0,0 +1,164 @@ +package app.klottr.ui + +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicText +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember + +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.SolidColor // För tydlig cursor-färg +import androidx.compose.ui.graphics.takeOrElse +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp + + + +/** + * Material-fritt formulär för att skriva ett dokument (rubrik, text, valfri bild). + * All plattformslogik (bildväljare, fil-IO) hanteras av anroparen via callbacks. + */ +@Composable +fun WriteDocContent( + title: String, + onTitleChange: (String) -> Unit, + titleError: String?, + body: String, + onBodyChange: (String) -> Unit, + hasImage: Boolean, + imagePreview: ImageBitmap?, + onPickImage: () -> Unit, + onRemoveImage: () -> Unit, + rowTextStyle: TextStyle, + modifier: Modifier = Modifier +) { + val base = rowTextStyle.color.takeOrElse { Color(0xFFDDDDDD) } + val dim = base.copy(alpha = 0.65f) + val hint = base.copy(alpha = 0.55f) + val border = base.copy(alpha = 0.40f) + val error = Color(0xFFB3261E) + val shape = RoundedCornerShape(8.dp) + val titleFocus = remember { FocusRequester() } + val bodyFocus = remember { FocusRequester() } + + + Column( + modifier = modifier + .verticalScroll(rememberScrollState()) + .imePadding(), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + // Rubrik + BasicText("Rubrik", style = rowTextStyle.copy(fontWeight = FontWeight.Medium)) + Box( + modifier = Modifier + .fillMaxWidth() + .border(1.dp, if (titleError == null) border else error, shape) + .clickable { titleFocus.requestFocus() } + .padding(horizontal = 12.dp, vertical = 10.dp) + ) { + if (title.isBlank()) { + BasicText("Skriv en rubrik…", style = rowTextStyle.copy(color = hint)) + } + BasicTextField( + value = title, + onValueChange = onTitleChange, + textStyle = rowTextStyle, + modifier = Modifier + .fillMaxWidth() + .focusRequester(titleFocus), + cursorBrush = SolidColor(rowTextStyle.color.takeOrElse { Color.White }) + ) + } + if (titleError != null) { + BasicText(titleError, style = rowTextStyle.copy(color = error)) + } + + // Bildförhandsvisning (om någon) + if (imagePreview != null) { + Image( + bitmap = imagePreview, + contentDescription = null, + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 120.dp, max = 240.dp) + .border(1.dp, border, shape), + contentScale = ContentScale.Fit + ) + } + + // Bild-knappar (material-fria) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Box( + modifier = Modifier + .border(1.dp, border, shape) + .background(Color.Transparent, shape) + .clickable(onClick = onPickImage) + .padding(horizontal = 12.dp, vertical = 8.dp), + contentAlignment = Alignment.Center + ) { + BasicText(if (hasImage) "Byt bild" else "Välj bild", style = rowTextStyle) + } + if (hasImage) { + Box( + modifier = Modifier + .border(1.dp, border, shape) + .clickable(onClick = onRemoveImage) + .padding(horizontal = 12.dp, vertical = 8.dp), + contentAlignment = Alignment.Center + ) { + BasicText("Ta bort bild", style = rowTextStyle) + } + } + } + + // Brödtext + BasicText("Text", style = rowTextStyle.copy(color = dim, fontWeight = FontWeight.Medium)) + Box( + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 120.dp) + .border(1.dp, border, shape) + .padding(horizontal = 12.dp, vertical = 10.dp) + ) { + if (body.isBlank()) { + BasicText("Din text…", style = rowTextStyle.copy(color = hint)) + } + BasicTextField( + value = body, + onValueChange = onBodyChange, + textStyle = rowTextStyle, + modifier = Modifier + .fillMaxWidth() + .matchParentSize(), // Klick var som helst i boxen ger fokus + cursorBrush = SolidColor(rowTextStyle.color.takeOrElse { // Synlig cursor i mörkt läge + Color.White + } ) + ) + } + Spacer(Modifier.width(1.dp)) // Liten spacer i botten för scroll-känsla + } +}