feat(lists): task and shopping-list note types with running total
dev / Build debug APK (push) Canceled after 15m52s

NoteType (TEXT / TASK_LIST / SHOPPING_LIST) persists in an additive
NoteEntity.typeKey column (ObjectBox auto-migrates; old rows = TEXT).
List bodies stay GitHub-flavoured '- [ ]' lines so search, field
encryption, backups (defaulted noteType) and Trash keep working.

Editor: checklist + basket buttons convert any note; rows are uniform
underlined line fields (13sp) - product, 'Quan.' quantity (defaults to
1 on blur), and POS-style price showing raw cents while focused and
$1.23 on focus loss. Sticky total bar sums qty x price of checked
rows in integer cents via an explicit {q.. p..} end-of-line marker so
product text is never scanned for numbers.

Fixes found in device testing: cards rendered raw markdown for list
notes stranded as TEXT by partial builds - read-time Note.inferListType
now heals them; quantity field was clipped invisible (64dp vs the 48dp
icon target) - replaced by the free-text line; the serializer emitted
a bare 'q' slot (broken '{q p1.23}' markers, stray ' x' folds) - now
null-when-default. Add-tag suggestions rebuilt on flatMapLatest so the
autocomplete re-queries per keystroke.

versionCode 32->33, versionName 0.3.8.0, APP_VERSION in lockstep.
This commit is contained in:
Incido Developer committed 2026-09-17 15:43:43 +12:00
1 parent 7b6187f99a
commit 32166a3100
14 files changed
+1044 -109

No files matched your search

@@ -6,6 +6,7 @@ import kotlinx.serialization.json.Json
import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
import org.incido.domain.repository.NoteRepository
/**
@@ -125,6 +126,12 @@ data class BackupNote(
val attachments: List<BackupAttachment> = emptyList(),
/** Preserve soft-delete state; defaults to false for older backups. */
val isTrashed: Boolean = false,
/**
* v0.3.8.0 — serialised as the [org.incido.domain.model.NoteType]
* enum name ("TEXT" / "TASK_LIST" / "SHOPPING_LIST"). Defaulted so
* pre-v0.3.8.0 backup files import as plain-text notes.
*/
val noteType: String = "TEXT",
)
@Serializable
@@ -156,6 +163,7 @@ private suspend fun Note.toBackup(repository: NoteRepository): BackupNote {
isFavorite = isFavorite,
color = color.name,
isTrashed = isTrashed,
noteType = type.name,
hashtags = hashtags,
attachments = backups,
)
@@ -172,6 +180,7 @@ private fun Note.toBackup(): BackupNote = BackupNote(
isFavorite = isFavorite,
color = color.name,
isTrashed = isTrashed,
noteType = type.name,
hashtags = hashtags,
attachments = emptyList(),
)
@@ -184,6 +193,7 @@ private fun BackupNote.toDomain(): Note = Note(
isFavorite = isFavorite,
color = runCatching { NoteColor.valueOf(color) }.getOrDefault(NoteColor.NONE),
isTrashed = isTrashed,
type = runCatching { NoteType.valueOf(noteType) }.getOrDefault(NoteType.TEXT),
hashtags = hashtags,
// Attachments are inserted separately by importSnapshot so they
// get assigned to the freshly-created note id.
@@ -25,6 +25,33 @@ object ReleaseNotes {
* Append a new entry on top each release.
*/
val RECENT: List<ReleaseNote> = listOf(
ReleaseNote(
version = "0.3.8.0",
date = "2026-09-16",
bullets = listOf(
"Task lists: a checklist button next to the # button in the " +
"editor turns any note into an editable task list — add, " +
"remove, and tick off items with real checkboxes.",
"Shopping lists with a running total: each row gets a " +
"quantity dropdown (1\u20139) and a supermarket-style " +
"price field \u2014 every digit you tap on the number pad " +
"is a cent, so entering 199 means $1.99 (the price box " +
"shows your raw entry beside its $ sign; the running " +
"total speaks real dollars). Tick an " +
"item once it's in your basket and the always-visible " +
"total at the top adds quantity \u00d7 price. Product, " +
"quantity, and price are strictly separate fields, so a " +
"product called \"Battery AA 3\" can never mess up your " +
"money maths.",
"Tapping the active list button again returns the note to " +
"plain text — nothing is lost, the items just become " +
"\"- [ ]\" lines you can also edit by hand.",
"Add-tag sheet fixed: existing hashtags now appear as a " +
"selectable suggestion list again, narrowing to matches " +
"live as you type (the suggestion pipeline was frozen, so " +
"only \"+ Create\\u2026\" ever showed).",
),
),
ReleaseNote(
version = "0.3.7.1",
date = "2026-08-30",
@@ -90,23 +117,6 @@ object ReleaseNotes {
"label\" group at the bottom of the card).",
),
),
ReleaseNote(
version = "0.3.5.0",
date = "2026-08-17",
bullets = listOf(
"\"Encrypt notes at rest\" now really works: your note text " +
"and attachment files are AES-256-GCM encrypted in place " +
"the moment you flip the switch (no restart), using the " +
"Android Keystore key.",
"Every time the app opens, each encrypted note is " +
"double-checked by decrypting it — a card only earns the " +
"\"Encrypted\" badge at the bottom of the card if that " +
"check passes.",
"New \"Block screenshots\" toggle (on by default): prevents " +
"screenshots, screen recording, and app-switcher previews " +
"while Incido is open.",
),
),
// v0.3.7.1 push drops v0.3.4.0 off the "5 most recent" tail.
// v0.3.8.0 push drops v0.3.5.0 off the "5 most recent" tail.
)
}
@@ -11,6 +11,7 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -23,30 +24,38 @@ import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.CameraAlt
import androidx.compose.material.icons.filled.Checklist
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.ShoppingBasket
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Tag
import androidx.compose.material.icons.outlined.StarOutline
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
@@ -60,7 +69,10 @@ import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberModalBottomSheetState
@@ -78,6 +90,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusEvent
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
@@ -85,8 +98,11 @@ import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.FileProvider
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
@@ -97,8 +113,11 @@ import org.incido.compose.data.security.SecurityManager
import org.incido.compose.ui.theme.AllNoteColors
import org.incido.compose.ui.theme.swatchBorderColor
import org.incido.compose.ui.theme.toComposeColor
import org.incido.domain.model.ChecklistItem
import org.incido.domain.model.Hashtag
import org.incido.domain.model.Note
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
import java.io.File
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@@ -247,6 +266,7 @@ fun NoteEditorScreen(
initialFavorite = viewModel.initialFavorite,
initialColor = viewModel.initialColor,
initialTags = viewModel.initialHashtags,
initialType = viewModel.initialType,
)
}
@@ -368,20 +388,48 @@ fun NoteEditorScreen(
}
Spacer(Modifier.height(12.dp))
OutlinedTextField(
value = state.content,
onValueChange = viewModel::onContentChange,
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.padding(horizontal = 16.dp)
.focusRequester(focusRequester),
placeholder = { Text("Write something…") },
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences,
imeAction = ImeAction.Default,
),
)
// v0.3.8.0 — structured list editors replace the free-text
// field whenever the note is a task / shopping list; the
// rows live in NoteEditorUiState.items and the view-model
// keeps `content` synchronised with their serialisation.
if (state.type == NoteType.TEXT) {
OutlinedTextField(
value = state.content,
onValueChange = viewModel::onContentChange,
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.padding(horizontal = 16.dp)
.focusRequester(focusRequester),
placeholder = { Text("Write something…", style = editorFieldStyle()) },
textStyle = editorFieldStyle(),
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences,
imeAction = ImeAction.Default,
),
)
} else {
// Sticky running total — always visible above the rows
// while shopping (per Development Plan §6.1), summing
// the costs of checked (= in-basket) items.
if (state.type == NoteType.SHOPPING_LIST) {
ShoppingTotalBar(totalCents = Note.shoppingTotalCents(state.items))
}
ChecklistEditorBody(
modifier = Modifier.weight(1f),
header = state.listHeader,
items = state.items,
isShopping = state.type == NoteType.SHOPPING_LIST,
focusRequester = focusRequester,
onHeaderChange = viewModel::onHeaderChange,
onToggleItem = viewModel::setItemChecked,
onItemTextChange = viewModel::setItemText,
onItemQuantityChange = viewModel::setItemQuantity,
onItemCostChange = viewModel::setItemCost,
onRemoveItem = viewModel::removeListItem,
onAddItem = viewModel::addListItem,
)
}
// v0.3.1.0: attachment thumbnail strip. Combines persisted
// attachments (loaded via observeAttachments in the VM) with
@@ -457,6 +505,30 @@ fun NoteEditorScreen(
else MaterialTheme.colorScheme.outlineVariant,
)
}
// v0.3.8.0 — task-list toggle next to the # button.
// Converts the body into editable checklist rows (and
// back); the active mode tints with the primary colour.
IconButton(onClick = { viewModel.convertTo(NoteType.TASK_LIST) }) {
Icon(
Icons.Filled.Checklist,
contentDescription = "Task list",
tint = if (state.type == NoteType.TASK_LIST)
MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
// v0.3.8.0 — shopping-list toggle: like the task list
// but each row gains a number-pad Cost field and a
// sticky running total of checked items sits on top.
IconButton(onClick = { viewModel.convertTo(NoteType.SHOPPING_LIST) }) {
Icon(
Icons.Filled.ShoppingBasket,
contentDescription = "Shopping list",
tint = if (state.type == NoteType.SHOPPING_LIST)
MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
@@ -863,6 +935,266 @@ private fun AddTagSheet(
}
}
// ---------------------------------------------------------------------
// v0.3.8.0: task / shopping list editor body
// ---------------------------------------------------------------------
/**
* Sticky running total for shopping lists — pinned above the rows so
* it stays visible at all times (Development Plan §6.1: "renders a
* sticky running total … updated live as prices are added/edited
* while shopping"). Sums the costs of CHECKED (= in-basket) items.
*/
@Composable
private fun ShoppingTotalBar(totalCents: Long) {
Row(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceVariant)
.padding(horizontal = 16.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
Icons.Filled.ShoppingBasket,
contentDescription = null,
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.size(8.dp))
Text(
"Running total (qty × price, checked items)",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.weight(1f))
Text(
text = Note.formatMoney(totalCents.toString()),
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.primary,
)
}
HorizontalDivider()
}
/**
* Structured body for task / shopping list notes: the title/preamble
* field, one [ChecklistItemRow] per item, and an "+ Add item" button.
* All mutations route through the view-model, which re-serialises the
* rows back into [NoteEditorUiState.content].
*/
@Composable
private fun ChecklistEditorBody(
modifier: Modifier = Modifier,
header: String,
items: List<ChecklistItem>,
isShopping: Boolean,
focusRequester: FocusRequester,
onHeaderChange: (String) -> Unit,
onToggleItem: (Int, Boolean) -> Unit,
onItemTextChange: (Int, String) -> Unit,
onItemQuantityChange: (Int, String) -> Unit,
onItemCostChange: (Int, String) -> Unit,
onRemoveItem: (Int) -> Unit,
onAddItem: () -> Unit,
) {
LazyColumn(modifier = modifier.fillMaxWidth()) {
item {
// Title / preamble. Kept as plain lines above the checkbox
// rows so the list cards' title+body split keeps working.
EditorLineField(
value = header,
onValueChange = onHeaderChange,
placeholder = "Title",
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences,
imeAction = ImeAction.Next,
),
fieldModifier = Modifier.focusRequester(focusRequester),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 4.dp),
)
}
itemsIndexed(items) { index, item ->
ChecklistItemRow(
item = item,
isShopping = isShopping,
onToggle = { checked -> onToggleItem(index, checked) },
onTextChange = { text -> onItemTextChange(index, text) },
onQuantityChange = { qty -> onItemQuantityChange(index, qty) },
onCostChange = { cost -> onItemCostChange(index, cost) },
onRemove = { onRemoveItem(index) },
)
}
item {
TextButton(onClick = onAddItem) {
Icon(
Icons.Filled.Add,
contentDescription = null,
modifier = Modifier.size(18.dp),
)
Spacer(Modifier.size(6.dp))
Text("+ Add item")
}
}
}
}
/** One row: `[ ]` · Product · Qty picker · per-item price · remove. */
@Composable
private fun ChecklistItemRow(
item: ChecklistItem,
isShopping: Boolean,
onToggle: (Boolean) -> Unit,
onTextChange: (String) -> Unit,
onQuantityChange: (String) -> Unit,
onCostChange: (String) -> Unit,
onRemove: () -> Unit,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Checkbox(checked = item.checked, onCheckedChange = onToggle)
// The product field holds ANY text — numbers included. Quantity /
// price live in their own controls and an explicit `{q… p…}`
// storage marker, so a product called "Battery AA 3" can never
// bleed into the money fields.
EditorLineField(
value = item.text,
onValueChange = onTextChange,
placeholder = if (isShopping) "Product" else "Task",
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences,
imeAction = ImeAction.Next,
),
modifier = Modifier.weight(1f),
)
if (isShopping) {
Spacer(Modifier.size(6.dp))
// Free-text quantity line (replaced the 1–9 dropdown, whose
// digit never fit its box). Blank means quantity 1: while
// focused an empty line shows the "Quan." hint; on focus
// loss it settles on "1" — display-only, storage keeps the
// blank default so {q1} never enters the saved text.
EditorLineField(
value = item.quantity,
onValueChange = onQuantityChange,
placeholder = "Quan.",
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next,
),
formatUnfocused = { digits ->
if (digits.isEmpty()) "1" else digits
},
modifier = Modifier.width(72.dp),
)
Spacer(Modifier.size(6.dp))
// Supermarket-style cents entry: while focused the line shows
// the RAW digits typed ("123"); on focus loss it switches to
// the parsed money form ("$1.23"). Storage always keeps the
// raw cent digits, so totals / serialisation are unaffected.
EditorLineField(
value = item.cost,
onValueChange = onCostChange,
placeholder = "Price",
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next,
),
formatUnfocused = { digits ->
if (digits.isEmpty()) "" else "$" + Note.amountFromPriceDigits(digits)
},
modifier = Modifier.width(110.dp),
)
}
IconButton(onClick = onRemove) {
Icon(
Icons.Filled.Close,
contentDescription = "Remove item",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
/**
* v0.3.8.0 — the ~20 % smaller text style every editor surface uses
* (plain body, list header, task/product/quantity/price lines). The 16sp
* bodyLarge default made rows look squashed inside their fields.
*/
@Composable
private fun editorFieldStyle(): TextStyle =
MaterialTheme.typography.bodyMedium.copy(fontSize = 13.sp, lineHeight = 18.sp)
/**
* v0.3.8.0 — one plain underlined editing line, shared by every editable
* field in the editor (title, task/product, quantity, price). Replaces
* the mismatched outlined boxes with a single visual rhythm: same
* minimum height, same 13sp text, and a 2 dp bottom rule that brightens
* while the field has focus.
*
* [formatUnfocused] swaps in a parsed display ("$1.23") while the field
* has no focus — editing always shows the raw stored value ("123").
* [fieldModifier] targets the inner text field itself (focus requester).
*/
@Composable
private fun EditorLineField(
value: String,
onValueChange: (String) -> Unit,
placeholder: String = "",
keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
formatUnfocused: ((String) -> String)? = null,
fieldModifier: Modifier = Modifier,
modifier: Modifier = Modifier,
) {
val fieldStyle = editorFieldStyle()
val hintColor = MaterialTheme.colorScheme.onSurfaceVariant
var focused by remember { mutableStateOf(false) }
val displayed =
if (focused || formatUnfocused == null) value else formatUnfocused(value)
Row(
modifier = modifier.heightIn(min = 44.dp),
verticalAlignment = Alignment.CenterVertically,
) {
// Material 3 filled TextField with fully transparent containers:
// what remains visible is just the text line and the 2 dp bottom
// indicator — exactly the "one line per field" look, for free.
TextField(
value = displayed,
onValueChange = onValueChange,
singleLine = true,
placeholder = {
Text(
text = placeholder,
style = fieldStyle,
color = hintColor,
maxLines = 1,
)
},
textStyle = fieldStyle.copy(
color = MaterialTheme.colorScheme.onSurface,
),
keyboardOptions = keyboardOptions,
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
disabledContainerColor = Color.Transparent,
errorContainerColor = Color.Transparent,
focusedIndicatorColor = MaterialTheme.colorScheme.primary,
unfocusedIndicatorColor = MaterialTheme.colorScheme.outlineVariant,
cursorColor = MaterialTheme.colorScheme.primary,
),
modifier = fieldModifier
.weight(1f)
.onFocusEvent { focused = it.isFocused },
)
}
}
// ---------------------------------------------------------------------
// v0.3.1.0: helpers (camera URI + SAF display-name query)
// ---------------------------------------------------------------------
@@ -7,20 +7,24 @@ import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.IncidoApplication
import org.incido.compose.share.LinkedShareComposer
import org.incido.domain.model.ChecklistItem
import org.incido.domain.model.Hashtag
import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
import org.incido.domain.repository.NoteRepository
/**
@@ -33,6 +37,16 @@ data class NoteEditorUiState(
val color: NoteColor = NoteColor.NONE,
/** Normalised, sorted ascending. */
val hashtags: List<String> = emptyList(),
/** v0.3.8.0 — which editor surface the body uses (see [NoteType]). */
val type: NoteType = NoteType.TEXT,
/** v0.3.8.0 — title / preamble kept above the rows in list modes. */
val listHeader: String = "",
/** v0.3.8.0 — parsed checklist rows; always empty for [NoteType.TEXT]. */
val items: List<ChecklistItem> = emptyList(),
/** True while the add-tag sheet is open. */
val isAddingTag: Boolean = false,
/** Latest typing in the add-tag sheet (raw, before normalisation). */
@@ -90,10 +104,12 @@ data class NoteEditorUiState(
initialFavorite: Boolean,
initialColor: NoteColor,
initialTags: List<String>,
initialType: NoteType,
): Boolean = content != initialContent ||
isFavorite != initialFavorite ||
color != initialColor ||
hashtags != initialTags
hashtags != initialTags ||
type != initialType
companion object {
/** Hard cap on tags per note (matches Development Plan §6.1). */
@@ -129,6 +145,7 @@ data class PendingAttachment(
val isImage: Boolean get() = mimeType.startsWith("image/")
}
@OptIn(ExperimentalCoroutinesApi::class)
class NoteEditorViewModel(
private val repository: NoteRepository,
private val noteId: Long?,
@@ -178,6 +195,8 @@ class NoteEditorViewModel(
private set
var initialHashtags: List<String> = emptyList()
private set
var initialType: NoteType = NoteType.TEXT
private set
/** Internal: re-emits suggestions whenever the tag input changes. */
private val tagInputFlow = MutableStateFlow("")
@@ -193,18 +212,27 @@ class NoteEditorViewModel(
init {
// Tag autocomplete — re-query on every keystroke (debounced upstream
// would be nice but ObjectBox is plenty fast for this size).
// Tag autocomplete. v0.3.8.0 FIX: the previous nested
// `tagInputFlow.collect { pool.collect { … } }` never resumed
// past the first keystroke — observeAllHashtags()/searchHashtags()
// are infinite callbackFlows, so the outer lambda suspended in
// the inner collect forever and typing never re-queried (the
// sheet only ever showed "+ Create"). flatMapLatest cancels the
// previous subscription per keystroke, and each fresh flow
// try-sends its snapshot immediately ⇒ live filtering.
viewModelScope.launch {
tagInputFlow.collect { raw ->
val prefix = Hashtag.normalise(raw)
val pool = if (prefix.isEmpty()) {
repository.observeAllHashtags()
} else {
repository.searchHashtags(prefix)
tagInputFlow
.flatMapLatest { raw ->
val prefix = Hashtag.normalise(raw)
if (prefix.isEmpty()) {
repository.observeAllHashtags()
} else {
repository.searchHashtags(prefix)
}
}
pool.collect { suggestions ->
.collect { suggestions ->
_state.update { it.copy(tagSuggestions = suggestions) }
}
}
}
// Live attachments: pump persisted rows into state.attachments.
@@ -258,12 +286,25 @@ class NoteEditorViewModel(
} else {
viewModelScope.launch {
repository.observeById(noteId).collect { note ->
if (note != null && _state.value.isLoading) {
val firstLoad = _state.value.isLoading
if (note != null && firstLoad) {
initialContent = note.content
initialFavorite = note.isFavorite
initialColor = note.color
initialHashtags = note.hashtags
initialType = note.type
}
// Parse list rows once on first load; later DB
// emissions must not clobber in-progress edits.
val listSeed: Pair<String, List<ChecklistItem>>? =
if (note != null && firstLoad && note.type != NoteType.TEXT) {
Note.splitListContent(
note.content,
interpretCosts = note.type == NoteType.SHOPPING_LIST,
)
} else {
null
}
_state.update {
it.copy(
existing = note,
@@ -271,6 +312,9 @@ class NoteEditorViewModel(
isFavorite = note?.isFavorite ?: it.isFavorite,
color = note?.color ?: it.color,
hashtags = note?.hashtags ?: it.hashtags,
type = note?.type ?: it.type,
listHeader = listSeed?.first ?: it.listHeader,
items = listSeed?.second ?: it.items,
isLoading = false,
)
}
@@ -292,17 +336,18 @@ class NoteEditorViewModel(
}
fun openAddTagSheet() {
_state.update {
it.copy(
isAddingTag = true,
tagInput = "",
tagSuggestions = emptyList(),
)
}
// v0.3.8.0 FIX: push the empty query through the suggestion
// pipeline FIRST so the flatMapLatest collector re-emits every
// existing tag (most-used first) while the sheet opens — the
// old code just cleared the list to emptyList() here and the
// stuck collector never refilled it.
tagInputFlow.value = ""
_state.update { it.copy(isAddingTag = true, tagInput = "") }
}
fun closeAddTagSheet() {
_state.update { it.copy(isAddingTag = false, tagInput = "", tagSuggestions = emptyList()) }
tagInputFlow.value = ""
_state.update { it.copy(isAddingTag = false, tagInput = "") }
}
fun onTagInputChange(raw: String) {
@@ -330,6 +375,139 @@ class NoteEditorViewModel(
_state.update { it.copy(hashtags = it.hashtags.filterNot { tag -> tag == normalised }) }
}
// ---- v0.3.8.0 task / shopping list editing ----
/**
* Keep the [NoteEditorUiState.items] / [NoteEditorUiState.listHeader]
* rows and the derived [NoteEditorUiState.content] in step, so the
* save path, dirty-check, search preview, and `canSave` gate all
* keep working off the single content string.
*/
private fun NoteEditorUiState.withListEdits(
header: String = this.listHeader,
items: List<ChecklistItem>,
): NoteEditorUiState = copy(
listHeader = header,
items = items,
content = Note.serializeListContent(header, items, type),
)
private fun List<ChecklistItem>.patched(
index: Int,
transform: (ChecklistItem) -> ChecklistItem,
): List<ChecklistItem> = mapIndexed { i, item ->
if (i == index) transform(item) else item
}
/**
* Convert the body to [target]; tapping the already-active mode
* converts back to [NoteType.TEXT]. Text moves losslessly between
* the plain editor and the checkbox serialisation — costs are only
* stored while the note is a shopping list (converting to a task
* list folds each cost back into the item text).
*/
fun convertTo(target: NoteType) {
_state.update { s ->
val next = if (s.type == target) NoteType.TEXT else target
if (next == NoteType.TEXT) {
// Content already holds the serialised `- [ ]` rows;
// just drop out of the structured editor (the inline
// GFM checklist rendering from v0.2.0.0 still applies).
s.copy(type = NoteType.TEXT, listHeader = "", items = emptyList())
} else {
val source = if (s.type == NoteType.TEXT) {
s.content
} else {
// Serialise through the FOLDED legacy form (plain
// "Milk 2 x 3.90" lines, never `{q…p…}` markers) so
// structured values survive the trip and re-parse
// cleanly under the target mode's rules.
Note.serializeListContent(s.listHeader, s.items, NoteType.TEXT)
}
val (header, parsedRaw) = Note.splitListContent(
source,
interpretCosts = next == NoteType.SHOPPING_LIST,
)
val parsed = if (parsedRaw.isEmpty()) listOf(ChecklistItem("")) else parsedRaw
s.copy(
type = next,
listHeader = header,
items = parsed,
content = Note.serializeListContent(header, parsed, next),
)
}
}
_state.update {
it.copy(
snackbar = when (it.type) {
NoteType.TASK_LIST -> "Task list mode — first line stays the title."
NoteType.SHOPPING_LIST -> "Shopping list mode — check an item once it's in your basket."
else -> "Back to plain text."
},
)
}
}
fun onHeaderChange(value: String) {
_state.update { it.withListEdits(header = value, items = it.items) }
}
fun addListItem() {
_state.update { s ->
if (s.type == NoteType.TEXT) return@update s
s.withListEdits(items = s.items + ChecklistItem(""))
}
}
fun removeListItem(index: Int) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.filterIndexed { i, _ -> i != index })
}
}
fun setItemChecked(index: Int, checked: Boolean) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(checked = checked) })
}
}
fun setItemText(index: Int, text: String) {
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(text = text) })
}
}
/**
* Price field input — POS style: everything is reduced to cents
* digits ("199" ⇒ $1.99, separators typed or pasted are stripped).
*/
fun setItemCost(index: Int, rawCost: String) {
val sanitized = Note.normalisePriceInput(rawCost)
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(cost = sanitized) })
}
}
/**
* Quantity line input (free-text digits); blank means the default 1.
*
* v0.3.8.0: "1" now stays stored as "1" — the field is free text, so
* the typed digit must remain visible. The serialiser already omits
* `{q1}` and cards only show "×qty" when the quantity is > 1, so this
* is storage-neutral. "0" / blank normalise to "" (meaning 1).
*/
fun setItemQuantity(index: Int, rawQty: String) {
val stored = Note.normaliseQuantity(rawQty)
_state.update { s ->
if (index !in s.items.indices) return@update s
s.withListEdits(items = s.items.patched(index) { it.copy(quantity = stored) })
}
}
fun consumeSnackbar() {
_state.update { it.copy(snackbar = null) }
}
@@ -419,12 +597,14 @@ class NoteEditorViewModel(
content = current.content,
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
) ?: Note(
content = current.content,
createdAt = System.currentTimeMillis(),
updatedAt = System.currentTimeMillis(),
isFavorite = current.isFavorite,
color = current.color,
type = current.type,
)
val previous = baseNote?.hashtags.orEmpty().toSet()
val currentSet = current.hashtags.toSet()
@@ -35,6 +35,7 @@ import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PhotoCamera
import androidx.compose.material.icons.filled.Restore
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.ShoppingBasket
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.outlined.StarOutline
import androidx.compose.material3.Card
@@ -76,6 +77,7 @@ import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteFilter
import org.incido.domain.model.NoteType
import org.incido.domain.repository.NoteRepository
/**
@@ -388,7 +390,11 @@ private fun NoteCard(
*/
showEncryptionBadge: Boolean = false,
) {
val (title, body) = Note.titleAndBody(note.content)
// v0.3.8.0: task / shopping lists render marker-free on cards —
// header line becomes the title, items show as clean "Name ×qty @$X"
// text. The checkbox state lives in the summary row below instead.
val (title, body) = if (note.type == NoteType.TEXT) Note.titleAndBody(note.content)
else Note.cardPresentation(note.content, note.type)
val bodyPreview = Note.bodyPreview(body)
val checklistSummary = Note.checklistSummary(note.content)
val noteColor = note.color
@@ -524,7 +530,11 @@ private fun NoteCard(
Spacer(modifier = Modifier.padding(top = 4.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Default.CheckBox,
// v0.3.8.0: shopping lists carry a basket
// on the card instead of the plain check box.
imageVector = if (note.type == NoteType.SHOPPING_LIST)
Icons.Default.ShoppingBasket
else Icons.Default.CheckBox,
contentDescription = null,
modifier = Modifier.size(14.dp),
tint = secondaryColor,
@@ -333,7 +333,7 @@ class SettingsViewModel(
/** The version string baked into backup payloads and shown on
* the About card. Mirrors `app/build.gradle.kts` `versionName`
* — if you bump one, bump both. */
const val APP_VERSION = "0.3.7.1"
const val APP_VERSION = "0.3.8.0"
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {