notes: update packages and imports from util -> platform (canonical structure)
- Commit
c97ac8cc6c729e412c0ae1479ceec1db5c6e4d44- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-15 18:15 UTC (3 months ago)
- Parents
78aecab
Diff
notes/src/main/java/com/vayunmathur/notes/MainActivity.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt b/notes/src/main/java/com/vayunmathur/notes/MainActivity.ktindex 7174257c4c..415b0ae961 100644--- a/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt+++ b/notes/src/main/java/com/vayunmathur/notes/MainActivity.kt@@ -1,121 +1,121 @@-package com.vayunmathur.notes--import android.content.Intent-import android.os.Bundle-import android.util.Log-import androidx.activity.ComponentActivity-import androidx.activity.compose.setContent-import androidx.activity.enableEdgeToEdge-import androidx.activity.viewModels-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.ui.Modifier-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import androidx.lifecycle.lifecycleScope-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.library.util.IntentHelper-import com.vayunmathur.library.util.ListDetailPage-import com.vayunmathur.library.util.ListPage-import com.vayunmathur.library.util.MainNavigation-import com.vayunmathur.library.util.NavKey-import com.vayunmathur.library.util.onFileDrop-import com.vayunmathur.library.util.rememberNavBackStack-import com.vayunmathur.notes.data.NotesRepository-import com.vayunmathur.notes.ui.NotePage-import com.vayunmathur.notes.ui.NotesListPage-import com.vayunmathur.notes.ui.ExternalNoteScreen-import com.vayunmathur.notes.util.NotesViewModel-import com.vayunmathur.notes.util.NotesViewModelFactory-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext-import kotlinx.serialization.Serializable--class MainActivity : ComponentActivity() {- private lateinit var notesRepository: NotesRepository- private val notesViewModel: NotesViewModel by viewModels {- NotesViewModelFactory(application, notesRepository)- }-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- enableEdgeToEdge()-- val ready = mutableStateOf(false)- lifecycleScope.launch(Dispatchers.IO) {- notesRepository = NotesRepository.get(applicationContext)- val legacyNotes = notesRepository.readAndClearLegacyNotes()- if (legacyNotes.isNotEmpty()) notesRepository.upsertAll(legacyNotes)- withContext(Dispatchers.Main) {- handleIntent(intent)- ready.value = true- }- }-- setContent {- DynamicTheme {- Box(Modifier.fillMaxSize().onFileDrop { uris ->- notesViewModel.importFiles(uris)- }) {- if (ready.value) Navigation(notesViewModel)- }- }- }- }-- override fun onNewIntent(intent: Intent) {- super.onNewIntent(intent)- if (::notesRepository.isInitialized) handleIntent(intent)- }-- /**- * External VIEW/EDIT/SEND opens are shown on their own [ExternalNoteScreen]- * (a standalone markdown editor) instead of being auto-added to the DB.- */- private fun handleIntent(intent: Intent?) {- intent ?: return- val uris = IntentHelper.getUrisFromIntent(intent).ifEmpty { listOfNotNull(intent.data) }- notesViewModel.openExternal(uris)- }-- companion object {- private const val TAG = "NotesMainActivity"- }-}--@Serializable-sealed interface Route: NavKey {- @Serializable- data object NotesList: Route- @Serializable- data class Note(val id: Long): Route- @Serializable- data class ExternalNote(val uri: String): Route-}--@Composable-fun Navigation(notesViewModel: NotesViewModel) {- val backStack = rememberNavBackStack<Route>(Route.NotesList)- val externalOpens by notesViewModel.externalOpens.collectAsStateWithLifecycle()- LaunchedEffect(externalOpens) {- externalOpens.firstOrNull()?.let { uri ->- notesViewModel.consumeExternal(uri)- backStack.add(Route.ExternalNote(uri))- }- }- MainNavigation(backStack) {- entry<Route.NotesList>(metadata = ListPage()) {- NotesListPage(backStack, notesViewModel)- }- entry<Route.Note>(metadata = ListDetailPage()) {- NotePage(backStack, notesViewModel, it.id)- }- entry<Route.ExternalNote>(metadata = ListDetailPage()) {- ExternalNoteScreen(backStack, notesViewModel, it.uri)- }- }-}+package com.vayunmathur.notes++import android.content.Intent+import android.os.Bundle+import android.util.Log+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.Modifier+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.lifecycle.lifecycleScope+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.IntentHelper+import com.vayunmathur.library.util.ListDetailPage+import com.vayunmathur.library.util.ListPage+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.onFileDrop+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.notes.data.NotesRepository+import com.vayunmathur.notes.ui.NotePage+import com.vayunmathur.notes.ui.NotesListPage+import com.vayunmathur.notes.ui.ExternalNoteScreen+import com.vayunmathur.notes.platform.NotesViewModel+import com.vayunmathur.notes.platform.NotesViewModelFactory+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {+ private lateinit var notesRepository: NotesRepository+ private val notesViewModel: NotesViewModel by viewModels {+ NotesViewModelFactory(application, notesRepository)+ }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()++ val ready = mutableStateOf(false)+ lifecycleScope.launch(Dispatchers.IO) {+ notesRepository = NotesRepository.get(applicationContext)+ val legacyNotes = notesRepository.readAndClearLegacyNotes()+ if (legacyNotes.isNotEmpty()) notesRepository.upsertAll(legacyNotes)+ withContext(Dispatchers.Main) {+ handleIntent(intent)+ ready.value = true+ }+ }++ setContent {+ DynamicTheme {+ Box(Modifier.fillMaxSize().onFileDrop { uris ->+ notesViewModel.importFiles(uris)+ }) {+ if (ready.value) Navigation(notesViewModel)+ }+ }+ }+ }++ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ if (::notesRepository.isInitialized) handleIntent(intent)+ }++ /**+ * External VIEW/EDIT/SEND opens are shown on their own [ExternalNoteScreen]+ * (a standalone markdown editor) instead of being auto-added to the DB.+ */+ private fun handleIntent(intent: Intent?) {+ intent ?: return+ val uris = IntentHelper.getUrisFromIntent(intent).ifEmpty { listOfNotNull(intent.data) }+ notesViewModel.openExternal(uris)+ }++ companion object {+ private const val TAG = "NotesMainActivity"+ }+}++@Serializable+sealed interface Route: NavKey {+ @Serializable+ data object NotesList: Route+ @Serializable+ data class Note(val id: Long): Route+ @Serializable+ data class ExternalNote(val uri: String): Route+}++@Composable+fun Navigation(notesViewModel: NotesViewModel) {+ val backStack = rememberNavBackStack<Route>(Route.NotesList)+ val externalOpens by notesViewModel.externalOpens.collectAsStateWithLifecycle()+ LaunchedEffect(externalOpens) {+ externalOpens.firstOrNull()?.let { uri ->+ notesViewModel.consumeExternal(uri)+ backStack.add(Route.ExternalNote(uri))+ }+ }+ MainNavigation(backStack) {+ entry<Route.NotesList>(metadata = ListPage()) {+ NotesListPage(backStack, notesViewModel)+ }+ entry<Route.Note>(metadata = ListDetailPage()) {+ NotePage(backStack, notesViewModel, it.id)+ }+ entry<Route.ExternalNote>(metadata = ListDetailPage()) {+ ExternalNoteScreen(backStack, notesViewModel, it.uri)+ }+ }+}
notes/src/main/java/com/vayunmathur/notes/data/NoteBlock.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/data/NoteBlock.kt b/notes/src/main/java/com/vayunmathur/notes/data/NoteBlock.ktindex 431bb3eca1..61861c9082 100644--- a/notes/src/main/java/com/vayunmathur/notes/data/NoteBlock.kt+++ b/notes/src/main/java/com/vayunmathur/notes/data/NoteBlock.kt@@ -1,86 +1,86 @@-@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)--package com.vayunmathur.notes.data--import kotlin.uuid.Uuid-import com.vayunmathur.library.ink.SerializedStroke-import kotlinx.serialization.SerialName-import kotlinx.serialization.Serializable-import kotlinx.serialization.encodeToString-import kotlinx.serialization.json.Json--/**- * One piece of a note's body. A note is an ordered list of blocks so it can mix- * typed text, inserted images, and handwriting like OneNote / Apple Notes.- *- * Legacy text-only notes have no stored blocks; they are read back as a single- * [Text] block built from [Note.content] (see [Note.blockList]).- */-@Serializable-sealed interface NoteBlock {- val id: String-- @Serializable- @SerialName("text")- data class Text(- val markdown: String = "",- override val id: String = randomBlockId(),- ) : NoteBlock-- /** [fileName] names an image file in the note-images dir (see [com.vayunmathur.notes.util.NoteImageStore]). */- @Serializable- @SerialName("image")- data class Image(- val fileName: String,- /** Display width as a fraction of the editor width, so images can be resized. */- val widthFraction: Float = 1f,- override val id: String = randomBlockId(),- ) : NoteBlock-- /** Handwriting strokes drawn on a canvas [heightDp] tall. */- @Serializable- @SerialName("ink")- data class Ink(- val strokes: List<SerializedStroke> = emptyList(),- val heightDp: Int = 300,- override val id: String = randomBlockId(),- ) : NoteBlock-}--fun randomBlockId(): String = Uuid.random().toString()--/**- * The full body of a note: an ordered list of inline [blocks]. Serialized to the- * [Note.blocks] JSON column.- */-@Serializable-data class NoteBody(- val blocks: List<NoteBlock> = emptyList(),-)--// ignoreUnknownKeys lets us drop any legacy fields (e.g. an old "floating" list-// from earlier builds) so older notes still parse instead of crashing.-private val blockJson = Json { ignoreUnknownKeys = true }--/** The note body: parses stored [Note.blocks], or falls back to a single text block. */-fun Note.body(): NoteBody {- val json = blocks- if (json.isNullOrBlank()) return NoteBody(blocks = listOf(NoteBlock.Text(content)))- return try {- blockJson.decodeFromString<NoteBody>(json)- } catch (e: Exception) {- NoteBody(blocks = listOf(NoteBlock.Text(content)))- }-}--/**- * Returns a copy storing [newBody], keeping [Note.content] in sync with the text- * blocks so search, list previews, sharing, and the assistant intents keep working- * on plain text.- */-fun Note.withBody(newBody: NoteBody): Note = copy(- blocks = blockJson.encodeToString(newBody),- content = newBody.blocks.filterIsInstance<NoteBlock.Text>()- .joinToString("\n\n") { it.markdown }- .trim(),-)+@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)++package com.vayunmathur.notes.data++import kotlin.uuid.Uuid+import com.vayunmathur.library.ink.SerializedStroke+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * One piece of a note's body. A note is an ordered list of blocks so it can mix+ * typed text, inserted images, and handwriting like OneNote / Apple Notes.+ *+ * Legacy text-only notes have no stored blocks; they are read back as a single+ * [Text] block built from [Note.content] (see [Note.blockList]).+ */+@Serializable+sealed interface NoteBlock {+ val id: String++ @Serializable+ @SerialName("text")+ data class Text(+ val markdown: String = "",+ override val id: String = randomBlockId(),+ ) : NoteBlock++ /** [fileName] names an image file in the note-images dir (see [com.vayunmathur.notes.platform.NoteImageStore]). */+ @Serializable+ @SerialName("image")+ data class Image(+ val fileName: String,+ /** Display width as a fraction of the editor width, so images can be resized. */+ val widthFraction: Float = 1f,+ override val id: String = randomBlockId(),+ ) : NoteBlock++ /** Handwriting strokes drawn on a canvas [heightDp] tall. */+ @Serializable+ @SerialName("ink")+ data class Ink(+ val strokes: List<SerializedStroke> = emptyList(),+ val heightDp: Int = 300,+ override val id: String = randomBlockId(),+ ) : NoteBlock+}++fun randomBlockId(): String = Uuid.random().toString()++/**+ * The full body of a note: an ordered list of inline [blocks]. Serialized to the+ * [Note.blocks] JSON column.+ */+@Serializable+data class NoteBody(+ val blocks: List<NoteBlock> = emptyList(),+)++// ignoreUnknownKeys lets us drop any legacy fields (e.g. an old "floating" list+// from earlier builds) so older notes still parse instead of crashing.+private val blockJson = Json { ignoreUnknownKeys = true }++/** The note body: parses stored [Note.blocks], or falls back to a single text block. */+fun Note.body(): NoteBody {+ val json = blocks+ if (json.isNullOrBlank()) return NoteBody(blocks = listOf(NoteBlock.Text(content)))+ return try {+ blockJson.decodeFromString<NoteBody>(json)+ } catch (e: Exception) {+ NoteBody(blocks = listOf(NoteBlock.Text(content)))+ }+}++/**+ * Returns a copy storing [newBody], keeping [Note.content] in sync with the text+ * blocks so search, list previews, sharing, and the assistant intents keep working+ * on plain text.+ */+fun Note.withBody(newBody: NoteBody): Note = copy(+ blocks = blockJson.encodeToString(newBody),+ content = newBody.blocks.filterIsInstance<NoteBlock.Text>()+ .joinToString("\n\n") { it.markdown }+ .trim(),+)
notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.ktindex 4ff42ac841..94db549058 100644--- a/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt@@ -8,8 +8,8 @@ import com.vayunmathur.notes.data.NoteBlock * * Screens take a state value and an actions interface rather than the ViewModel itself, so * they can be rendered by a `@Preview` — which is what the store listing images are- * generated from. It lives in `util` rather than `ui` so the dependency runs one way:- * `ui` depends on `util`, and the binders in `ui` implement these interfaces.+ * generated from. It lives in `platform` rather than `ui` so the dependency runs one way:+ * `ui` depends on `platform`, and the binders in `ui` implement these interfaces. */ /** Everything the notes list draws. */
notes/src/main/java/com/vayunmathur/notes/ui/ExternalNoteScreen.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/ExternalNoteScreen.kt b/notes/src/main/java/com/vayunmathur/notes/ui/ExternalNoteScreen.ktindex 9ea2401418..f515bc795c 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/ExternalNoteScreen.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/ExternalNoteScreen.kt@@ -1,99 +1,99 @@-package com.vayunmathur.notes.ui--import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding-import com.vayunmathur.library.util.AppMessages-import com.vayunmathur.library.ui.CircularProgressIndicator-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.IconAdd-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconNavigation-import com.vayunmathur.library.ui.IconSave-import com.vayunmathur.library.ui.OdfMarkdownEditor-import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.res.stringResource-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.notes.R-import com.vayunmathur.notes.Route-import com.vayunmathur.notes.util.NotesViewModel--/**- * Standalone markdown editor for a file opened from outside the app (VIEW/EDIT/SEND).- *- * The file is NOT added to the app database on open. It behaves like a normal- * markdown file editor: edits are held in memory and written back to the original- * file only when the user taps Save. An explicit "Add to app" action imports the- * current content as a real note and opens it.- */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun ExternalNoteScreen(- backStack: NavBackStack<Route>,- notesViewModel: NotesViewModel,- uri: String,-) {- val readFailedMsg = stringResource(R.string.external_read_failed)- val savedMsg = stringResource(R.string.external_saved)- val saveFailedMsg = stringResource(R.string.external_save_failed)-- var loaded by remember(uri) { mutableStateOf(false) }- var title by remember(uri) { mutableStateOf("") }- var content by remember(uri) { mutableStateOf("") }-- LaunchedEffect(uri) {- val result = notesViewModel.readExternal(uri)- if (result == null) {- AppMessages.show(readFailedMsg)- backStack.pop()- return@LaunchedEffect- }- title = result.title- content = result.content- loaded = true- }-- Scaffold(- topBar = {- TopAppBar(- title = { Text(title.ifBlank { stringResource(R.string.title) }) },- navigationIcon = { IconNavigation { backStack.pop() } },- actions = {- IconButton(onClick = {- notesViewModel.saveExternal(uri, content) { ok ->- AppMessages.show(if (ok) savedMsg else saveFailedMsg)- }- }) { IconSave() }- IconButton(onClick = {- notesViewModel.addExternalToApp(title, content) { id ->- backStack.pop()- backStack.add(Route.Note(id))- }- }) { IconAdd() }- },- )- },- ) { paddingValues ->- if (loaded) {- OdfMarkdownEditor(- initialMarkdown = content,- onMarkdownChanged = { content = it },- modifier = Modifier.fillMaxSize().padding(paddingValues),- )- } else {- Box(Modifier.fillMaxSize().padding(paddingValues), contentAlignment = Alignment.Center) {- CircularProgressIndicator()- }- }- }-}+package com.vayunmathur.notes.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.IconSave+import com.vayunmathur.library.ui.OdfMarkdownEditor+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.notes.R+import com.vayunmathur.notes.Route+import com.vayunmathur.notes.platform.NotesViewModel++/**+ * Standalone markdown editor for a file opened from outside the app (VIEW/EDIT/SEND).+ *+ * The file is NOT added to the app database on open. It behaves like a normal+ * markdown file editor: edits are held in memory and written back to the original+ * file only when the user taps Save. An explicit "Add to app" action imports the+ * current content as a real note and opens it.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun ExternalNoteScreen(+ backStack: NavBackStack<Route>,+ notesViewModel: NotesViewModel,+ uri: String,+) {+ val readFailedMsg = stringResource(R.string.external_read_failed)+ val savedMsg = stringResource(R.string.external_saved)+ val saveFailedMsg = stringResource(R.string.external_save_failed)++ var loaded by remember(uri) { mutableStateOf(false) }+ var title by remember(uri) { mutableStateOf("") }+ var content by remember(uri) { mutableStateOf("") }++ LaunchedEffect(uri) {+ val result = notesViewModel.readExternal(uri)+ if (result == null) {+ AppMessages.show(readFailedMsg)+ backStack.pop()+ return@LaunchedEffect+ }+ title = result.title+ content = result.content+ loaded = true+ }++ Scaffold(+ topBar = {+ TopAppBar(+ title = { Text(title.ifBlank { stringResource(R.string.title) }) },+ navigationIcon = { IconNavigation { backStack.pop() } },+ actions = {+ IconButton(onClick = {+ notesViewModel.saveExternal(uri, content) { ok ->+ AppMessages.show(if (ok) savedMsg else saveFailedMsg)+ }+ }) { IconSave() }+ IconButton(onClick = {+ notesViewModel.addExternalToApp(title, content) { id ->+ backStack.pop()+ backStack.add(Route.Note(id))+ }+ }) { IconAdd() }+ },+ )+ },+ ) { paddingValues ->+ if (loaded) {+ OdfMarkdownEditor(+ initialMarkdown = content,+ onMarkdownChanged = { content = it },+ modifier = Modifier.fillMaxSize().padding(paddingValues),+ )+ } else {+ Box(Modifier.fillMaxSize().padding(paddingValues), contentAlignment = Alignment.Center) {+ CircularProgressIndicator()+ }+ }+ }+}
notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.ktindex 9e4b5cb4cc..54a2e1d56a 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotePage.kt@@ -1,454 +1,454 @@-package com.vayunmathur.notes.ui--import android.content.ClipData-import android.content.Intent-import android.net.Uri-import androidx.activity.compose.BackHandler-import androidx.activity.compose.rememberLauncherForActivityResult-import androidx.activity.result.PickVisualMediaRequest-import androidx.activity.result.contract.ActivityResultContracts-import androidx.compose.foundation.border-import androidx.compose.foundation.clickable-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.RowScope-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.rememberScrollState-import androidx.compose.foundation.shape.RoundedCornerShape-import androidx.compose.foundation.text.BasicTextField-import androidx.compose.foundation.verticalScroll-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.Icon-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconDraw-import com.vayunmathur.library.ui.IconImage-import com.vayunmathur.library.ui.IconKeyboardArrowDown-import com.vayunmathur.library.ui.IconKeyboardArrowUp-import com.vayunmathur.library.ui.LocalContentColor-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.key-import androidx.compose.runtime.mutableStateListOf-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.rememberCoroutineScope-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.draw.clip-import androidx.compose.ui.graphics.SolidColor-import androidx.compose.ui.platform.ClipEntry-import androidx.compose.ui.platform.LocalClipboard-import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.unit.dp-import androidx.ink.brush.Brush-import androidx.ink.brush.StockBrushes-import com.vayunmathur.library.ui.IconCopy-import com.vayunmathur.library.ui.IconDelete-import com.vayunmathur.library.ui.IconNavigation-import com.vayunmathur.library.ui.EditorBottomBar-import com.vayunmathur.library.ui.FormatIconButton-import com.vayunmathur.library.ui.IconShare-import com.vayunmathur.library.ink.InkCanvasView-import com.vayunmathur.library.ui.OdfMarkdownEditorController-import com.vayunmathur.library.ui.OdfMarkdownEditorField-import com.vayunmathur.library.ui.OdfMarkdownEditorToolbar-import com.vayunmathur.library.ui.rememberOdfMarkdownEditorController-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.library.ink.deserialize-import com.vayunmathur.notes.R-import com.vayunmathur.notes.Route-import com.vayunmathur.notes.data.Note-import com.vayunmathur.notes.data.NoteBlock-import com.vayunmathur.notes.data.NoteBody-import com.vayunmathur.notes.data.body-import com.vayunmathur.notes.data.randomBlockId-import com.vayunmathur.notes.data.withBody-import com.vayunmathur.notes.util.NoteActions-import com.vayunmathur.notes.util.NoteImageStore-import com.vayunmathur.notes.util.NoteUiState-import com.vayunmathur.notes.util.NotesViewModel-import com.vayunmathur.notes.util.exportNoteMarkdown-import com.vayunmathur.notes.util.markdownCacheUri-import com.vayunmathur.library.image.compose.AsyncImage-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext-import java.io.File--/**- * Binds the note with [noteID] to the stateless [NoteScreen]: owns the editable row, the- * block list, and everything that needs a real device (image picker, clipboard, share).- */-@Composable-fun NotePage(- backStack: NavBackStack<Route>,- notesViewModel: NotesViewModel,- noteID: Long,-) {- var note by notesViewModel.editableNote(noteID) { Note(0, "", "") }-- if (noteID != 0L && note.id == 0L) return-- val context = LocalContext.current- val clipboard = LocalClipboard.current- val scope = rememberCoroutineScope()- val shareNoteLabel = stringResource(R.string.share_note)- val noteClipLabel = stringResource(R.string.note)-- // Local, editable copy of the note body: an ordered list of inline blocks- // (text / image / ink). Every change is written back to [note], which persists- // via the ViewModel's debounced upsert.- val blocks = remember(noteID) { mutableStateListOf<NoteBlock>().apply { addAll(note.body().blocks) } }- fun commit() { note = note.withBody(NoteBody(blocks.toList())) }-- var editingInk by remember { mutableStateOf<NoteBlock.Ink?>(null) }- // Where inserted media lands: the text block that had focus when the picker or the- // drawing editor was opened. Kept here because the insert completes after a trip out- // of the app, by which time focus is gone.- var insertAfterId by remember { mutableStateOf<String?>(null) }-- fun insertBlock(block: NoteBlock) {- val at = blocks.indexOfFirst { it.id == insertAfterId }.takeIf { it >= 0 }?.plus(1) ?: blocks.size- blocks.add(at, block)- // Keep a text block after inserted media so the user can keep typing below it.- if (block !is NoteBlock.Text && (at + 1 > blocks.lastIndex || blocks[at + 1] !is NoteBlock.Text)) {- blocks.add(at + 1, NoteBlock.Text("", randomBlockId()))- }- commit()- }-- fun importImage(uri: Uri) {- scope.launch {- val name = withContext(Dispatchers.IO) { NoteImageStore.import(context, uri) }- if (name != null) insertBlock(NoteBlock.Image(name))- }- }-- val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->- if (uri != null) importImage(uri)- }-- LaunchedEffect(notesViewModel) {- notesViewModel.shareRequests.collect { share ->- val intent = Intent(Intent.ACTION_SEND).apply {- type = "text/markdown"- putExtra(Intent.EXTRA_STREAM, share.uri)- // Only inline the markdown as text when it is small. Notes with images- // embed base64 data URIs, which can be many MB and would overflow the- // Binder transaction limit (TransactionTooLargeException). In that case- // the .md file (EXTRA_STREAM) is the payload.- if (share.markdown.length < 100_000) {- putExtra(Intent.EXTRA_TEXT, share.markdown)- }- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)- }- context.startActivity(Intent.createChooser(intent, shareNoteLabel))- }- }-- // The drawing editor takes over the whole screen while open.- val ink = editingInk- if (ink != null) {- BackHandler { editingInk = null }- InkEditor(- initialStrokes = ink.strokes,- onDone = { newStrokes ->- val i = blocks.indexOfFirst { it.id == ink.id }- if (i >= 0) {- blocks[i] = ink.copy(strokes = newStrokes)- commit()- } else {- insertBlock(ink.copy(strokes = newStrokes))- }- editingInk = null- },- onCancel = { editingInk = null },- )- return- }-- NoteScreen(- state = NoteUiState(title = note.title, blocks = blocks.toList()),- actions = object : NoteActions {- override fun back() = backStack.pop()-- override fun setTitle(title: String) { note = note.copy(title = title) }-- override fun setBlockMarkdown(id: String, markdown: String) {- val i = blocks.indexOfFirst { it.id == id }- if (i >= 0) {- blocks[i] = NoteBlock.Text(markdown, id)- commit()- }- }-- override fun addImage(afterBlockId: String?) {- insertAfterId = afterBlockId- pickImage.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))- }-- override fun addDrawing(afterBlockId: String?) {- insertAfterId = afterBlockId- editingInk = NoteBlock.Ink(emptyList(), id = randomBlockId())- }-- override fun editDrawing(block: NoteBlock.Ink) { editingInk = block }-- override fun resizeImage(id: String, widthFraction: Float) {- val i = blocks.indexOfFirst { it.id == id }- val block = blocks.getOrNull(i) as? NoteBlock.Image ?: return- blocks[i] = block.copy(widthFraction = widthFraction)- commit()- }-- override fun moveBlock(id: String, delta: Int) {- val i = blocks.indexOfFirst { it.id == id }- val j = i + delta- if (i < 0 || j < 0 || j > blocks.lastIndex) return- val moved = blocks.removeAt(i)- blocks.add(j, moved)- commit()- }-- override fun deleteBlock(id: String) {- val i = blocks.indexOfFirst { it.id == id }- if (i < 0) return- val block = blocks[i]- if (block is NoteBlock.Image) NoteImageStore.delete(context, block.fileName)- blocks.removeAt(i)- if (blocks.isEmpty()) blocks.add(NoteBlock.Text("", randomBlockId()))- commit()- }-- override fun copyNote() {- scope.launch {- val clip = withContext(Dispatchers.IO) {- val markdown = exportNoteMarkdown(context, note)- // Big base64 images blow past Binder's ~1MB clip limit- // (TransactionTooLargeException), so for large notes copy a- // URI to the exported .md instead of the raw text.- if (markdown.length < 100_000) {- ClipData.newPlainText(noteClipLabel, markdown)- } else {- val uri = markdownCacheUri(context, note, markdown)- ClipData.newUri(context.contentResolver, "note", uri)- }- }- clipboard.setClipEntry(ClipEntry(clip))- }- }-- override fun shareNote() = notesViewModel.requestShare(note)-- override fun deleteNote() {- notesViewModel.delete(note)- backStack.pop()- }- },- )-}--/**- * The note editor, with no dependency on the ViewModel or the back stack so it can be- * rendered from a `@Preview` — see `src/screenshotTest`, which is where the store listing- * images come from.- */-@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun NoteScreen(state: NoteUiState, actions: NoteActions) {- val context = LocalContext.current-- // Which text block currently has focus, so new media is inserted next to it- // and the formatting toolbar targets the right editor.- var focusedBlockId by remember { mutableStateOf<String?>(null) }- var activeController by remember { mutableStateOf<OdfMarkdownEditorController?>(null) }-- Scaffold(- topBar = {- TopAppBar(- title = {},- navigationIcon = { IconNavigation { actions.back() } },- actions = {- IconButton({ actions.copyNote() }) { IconCopy() }- IconButton({ actions.shareNote() }) { IconShare() }- IconButton({ actions.deleteNote() }) { IconDelete() }- },- )- },- bottomBar = {- // One horizontally-scrollable bar. While a text block is focused it shows- // the markdown formatting buttons followed by the insert buttons; otherwise- // it shows just the insert buttons. Everything lives in a single row.- val insertButtons: @Composable RowScope.() -> Unit = {- FormatIconButton(stringResource(R.string.add_image), onClick = {- actions.addImage(focusedBlockId)- }) { IconImage() }- FormatIconButton(stringResource(R.string.add_drawing), onClick = {- actions.addDrawing(focusedBlockId)- }) { IconDraw() }- }- val controller = activeController- if (controller != null && controller.focused) {- OdfMarkdownEditorToolbar(controller, trailing = insertButtons)- } else {- EditorBottomBar(scrollable = true, content = insertButtons)- }- },- ) { paddingValues ->- Column(- Modifier- .padding(paddingValues)- .fillMaxSize()- .verticalScroll(rememberScrollState())- .padding(horizontal = 16.dp),- ) {- BasicTextField(- state.title,- { actions.setTitle(it) },- Modifier.fillMaxWidth().padding(top = 8.dp),- singleLine = true,- textStyle = MaterialTheme.typography.headlineMedium.copy(color = LocalContentColor.current),- cursorBrush = SolidColor(LocalContentColor.current),- decorationBox = { innerTextField ->- Box {- if (state.title.isEmpty()) Text(- text = stringResource(R.string.title),- style = MaterialTheme.typography.headlineMedium.copy(color = MaterialTheme.colorScheme.onSurfaceVariant),- )- innerTextField()- }- },- )-- state.blocks.forEach { block ->- key(block.id) {- when (block) {- is NoteBlock.Text -> {- val controller = rememberOdfMarkdownEditorController(initialMarkdown = block.markdown) { newMd ->- actions.setBlockMarkdown(block.id, newMd)- }- LaunchedEffect(controller.focused) {- if (controller.focused) {- focusedBlockId = block.id- activeController = controller- }- }- OdfMarkdownEditorField(controller = controller, modifier = Modifier.fillMaxWidth())- }-- is NoteBlock.Image -> ImageBlock(- block = block,- file = NoteImageStore.fileFor(context, block.fileName),- onResize = { fraction -> actions.resizeImage(block.id, fraction) },- onMoveUp = { actions.moveBlock(block.id, -1) },- onMoveDown = { actions.moveBlock(block.id, 1) },- onDelete = { actions.deleteBlock(block.id) },- )-- is NoteBlock.Ink -> InkBlock(- block = block,- onEdit = { actions.editDrawing(block) },- onMoveUp = { actions.moveBlock(block.id, -1) },- onMoveDown = { actions.moveBlock(block.id, 1) },- onDelete = { actions.deleteBlock(block.id) },- )- }- }- }- }- }-}--@Composable-private fun ImageBlock(- block: NoteBlock.Image,- file: File,- onResize: (Float) -> Unit,- onMoveUp: () -> Unit,- onMoveDown: () -> Unit,- onDelete: () -> Unit,-) {- Column(Modifier.fillMaxWidth().padding(vertical = 8.dp)) {- AsyncImage(- model = file,- contentDescription = null,- modifier = Modifier- .fillMaxWidth(block.widthFraction)- .clip(RoundedCornerShape(8.dp)),- )- BlockControls(onMoveUp = onMoveUp, onMoveDown = onMoveDown, onDelete = onDelete) {- // Step image width between quarter and full width.- IconButton(onClick = { onResize((block.widthFraction - 0.25f).coerceAtLeast(0.25f)) }) {- IconKeyboardArrowDown()- }- IconButton(onClick = { onResize((block.widthFraction + 0.25f).coerceAtMost(1f)) }) {- IconKeyboardArrowUp()- }- }- }-}--@Composable-private fun InkBlock(- block: NoteBlock.Ink,- onEdit: () -> Unit,- onMoveUp: () -> Unit,- onMoveDown: () -> Unit,- onDelete: () -> Unit,-) {- val strokes = remember(block) { block.strokes.map { it.deserialize() } }- Column(Modifier.fillMaxWidth().padding(vertical = 8.dp)) {- Box(- Modifier- .fillMaxWidth()- .height(block.heightDp.dp)- .border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(8.dp))- .clip(RoundedCornerShape(8.dp))- .clickable { onEdit() },- ) {- InkCanvasView(- currentBrush = previewBrush,- finishedStrokes = strokes,- onStrokeFinished = {},- enabled = false,- modifier = Modifier.fillMaxSize(),- )- }- BlockControls(onMoveUp = onMoveUp, onMoveDown = onMoveDown, onDelete = onDelete)- }-}--@Composable-private fun BlockControls(- onMoveUp: () -> Unit,- onMoveDown: () -> Unit,- onDelete: () -> Unit,- extra: @Composable () -> Unit = {},-) {- Row(verticalAlignment = Alignment.CenterVertically) {- extra()- IconButton(onClick = onMoveUp) {- IconKeyboardArrowUp()- }- IconButton(onClick = onMoveDown) {- IconKeyboardArrowDown()- }- IconButton(onClick = onDelete) { IconDelete() }- }-}--// A read-only ink preview needs some brush, but strokes carry their own; this is unused for drawing.-private val previewBrush by lazy {- Brush.createWithColorIntArgb(StockBrushes.pressurePen(), 0xFF000000.toInt(), 6f, 0.1f)-}+package com.vayunmathur.notes.ui++import android.content.ClipData+import android.content.Intent+import android.net.Uri+import androidx.activity.compose.BackHandler+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.PickVisualMediaRequest+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+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.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.verticalScroll+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDraw+import com.vayunmathur.library.ui.IconImage+import com.vayunmathur.library.ui.IconKeyboardArrowDown+import com.vayunmathur.library.ui.IconKeyboardArrowUp+import com.vayunmathur.library.ui.LocalContentColor+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.key+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.platform.ClipEntry+import androidx.compose.ui.platform.LocalClipboard+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.ink.brush.Brush+import androidx.ink.brush.StockBrushes+import com.vayunmathur.library.ui.IconCopy+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.EditorBottomBar+import com.vayunmathur.library.ui.FormatIconButton+import com.vayunmathur.library.ui.IconShare+import com.vayunmathur.library.ink.InkCanvasView+import com.vayunmathur.library.ui.OdfMarkdownEditorController+import com.vayunmathur.library.ui.OdfMarkdownEditorField+import com.vayunmathur.library.ui.OdfMarkdownEditorToolbar+import com.vayunmathur.library.ui.rememberOdfMarkdownEditorController+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.ink.deserialize+import com.vayunmathur.notes.R+import com.vayunmathur.notes.Route+import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.NoteBlock+import com.vayunmathur.notes.data.NoteBody+import com.vayunmathur.notes.data.body+import com.vayunmathur.notes.data.randomBlockId+import com.vayunmathur.notes.data.withBody+import com.vayunmathur.notes.platform.NoteActions+import com.vayunmathur.notes.platform.NoteImageStore+import com.vayunmathur.notes.platform.NoteUiState+import com.vayunmathur.notes.platform.NotesViewModel+import com.vayunmathur.notes.platform.exportNoteMarkdown+import com.vayunmathur.notes.platform.markdownCacheUri+import com.vayunmathur.library.image.compose.AsyncImage+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File++/**+ * Binds the note with [noteID] to the stateless [NoteScreen]: owns the editable row, the+ * block list, and everything that needs a real device (image picker, clipboard, share).+ */+@Composable+fun NotePage(+ backStack: NavBackStack<Route>,+ notesViewModel: NotesViewModel,+ noteID: Long,+) {+ var note by notesViewModel.editableNote(noteID) { Note(0, "", "") }++ if (noteID != 0L && note.id == 0L) return++ val context = LocalContext.current+ val clipboard = LocalClipboard.current+ val scope = rememberCoroutineScope()+ val shareNoteLabel = stringResource(R.string.share_note)+ val noteClipLabel = stringResource(R.string.note)++ // Local, editable copy of the note body: an ordered list of inline blocks+ // (text / image / ink). Every change is written back to [note], which persists+ // via the ViewModel's debounced upsert.+ val blocks = remember(noteID) { mutableStateListOf<NoteBlock>().apply { addAll(note.body().blocks) } }+ fun commit() { note = note.withBody(NoteBody(blocks.toList())) }++ var editingInk by remember { mutableStateOf<NoteBlock.Ink?>(null) }+ // Where inserted media lands: the text block that had focus when the picker or the+ // drawing editor was opened. Kept here because the insert completes after a trip out+ // of the app, by which time focus is gone.+ var insertAfterId by remember { mutableStateOf<String?>(null) }++ fun insertBlock(block: NoteBlock) {+ val at = blocks.indexOfFirst { it.id == insertAfterId }.takeIf { it >= 0 }?.plus(1) ?: blocks.size+ blocks.add(at, block)+ // Keep a text block after inserted media so the user can keep typing below it.+ if (block !is NoteBlock.Text && (at + 1 > blocks.lastIndex || blocks[at + 1] !is NoteBlock.Text)) {+ blocks.add(at + 1, NoteBlock.Text("", randomBlockId()))+ }+ commit()+ }++ fun importImage(uri: Uri) {+ scope.launch {+ val name = withContext(Dispatchers.IO) { NoteImageStore.import(context, uri) }+ if (name != null) insertBlock(NoteBlock.Image(name))+ }+ }++ val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->+ if (uri != null) importImage(uri)+ }++ LaunchedEffect(notesViewModel) {+ notesViewModel.shareRequests.collect { share ->+ val intent = Intent(Intent.ACTION_SEND).apply {+ type = "text/markdown"+ putExtra(Intent.EXTRA_STREAM, share.uri)+ // Only inline the markdown as text when it is small. Notes with images+ // embed base64 data URIs, which can be many MB and would overflow the+ // Binder transaction limit (TransactionTooLargeException). In that case+ // the .md file (EXTRA_STREAM) is the payload.+ if (share.markdown.length < 100_000) {+ putExtra(Intent.EXTRA_TEXT, share.markdown)+ }+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ }+ context.startActivity(Intent.createChooser(intent, shareNoteLabel))+ }+ }++ // The drawing editor takes over the whole screen while open.+ val ink = editingInk+ if (ink != null) {+ BackHandler { editingInk = null }+ InkEditor(+ initialStrokes = ink.strokes,+ onDone = { newStrokes ->+ val i = blocks.indexOfFirst { it.id == ink.id }+ if (i >= 0) {+ blocks[i] = ink.copy(strokes = newStrokes)+ commit()+ } else {+ insertBlock(ink.copy(strokes = newStrokes))+ }+ editingInk = null+ },+ onCancel = { editingInk = null },+ )+ return+ }++ NoteScreen(+ state = NoteUiState(title = note.title, blocks = blocks.toList()),+ actions = object : NoteActions {+ override fun back() = backStack.pop()++ override fun setTitle(title: String) { note = note.copy(title = title) }++ override fun setBlockMarkdown(id: String, markdown: String) {+ val i = blocks.indexOfFirst { it.id == id }+ if (i >= 0) {+ blocks[i] = NoteBlock.Text(markdown, id)+ commit()+ }+ }++ override fun addImage(afterBlockId: String?) {+ insertAfterId = afterBlockId+ pickImage.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))+ }++ override fun addDrawing(afterBlockId: String?) {+ insertAfterId = afterBlockId+ editingInk = NoteBlock.Ink(emptyList(), id = randomBlockId())+ }++ override fun editDrawing(block: NoteBlock.Ink) { editingInk = block }++ override fun resizeImage(id: String, widthFraction: Float) {+ val i = blocks.indexOfFirst { it.id == id }+ val block = blocks.getOrNull(i) as? NoteBlock.Image ?: return+ blocks[i] = block.copy(widthFraction = widthFraction)+ commit()+ }++ override fun moveBlock(id: String, delta: Int) {+ val i = blocks.indexOfFirst { it.id == id }+ val j = i + delta+ if (i < 0 || j < 0 || j > blocks.lastIndex) return+ val moved = blocks.removeAt(i)+ blocks.add(j, moved)+ commit()+ }++ override fun deleteBlock(id: String) {+ val i = blocks.indexOfFirst { it.id == id }+ if (i < 0) return+ val block = blocks[i]+ if (block is NoteBlock.Image) NoteImageStore.delete(context, block.fileName)+ blocks.removeAt(i)+ if (blocks.isEmpty()) blocks.add(NoteBlock.Text("", randomBlockId()))+ commit()+ }++ override fun copyNote() {+ scope.launch {+ val clip = withContext(Dispatchers.IO) {+ val markdown = exportNoteMarkdown(context, note)+ // Big base64 images blow past Binder's ~1MB clip limit+ // (TransactionTooLargeException), so for large notes copy a+ // URI to the exported .md instead of the raw text.+ if (markdown.length < 100_000) {+ ClipData.newPlainText(noteClipLabel, markdown)+ } else {+ val uri = markdownCacheUri(context, note, markdown)+ ClipData.newUri(context.contentResolver, "note", uri)+ }+ }+ clipboard.setClipEntry(ClipEntry(clip))+ }+ }++ override fun shareNote() = notesViewModel.requestShare(note)++ override fun deleteNote() {+ notesViewModel.delete(note)+ backStack.pop()+ }+ },+ )+}++/**+ * The note editor, with no dependency on the ViewModel or the back stack so it can be+ * rendered from a `@Preview` — see `src/screenshotTest`, which is where the store listing+ * images come from.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun NoteScreen(state: NoteUiState, actions: NoteActions) {+ val context = LocalContext.current++ // Which text block currently has focus, so new media is inserted next to it+ // and the formatting toolbar targets the right editor.+ var focusedBlockId by remember { mutableStateOf<String?>(null) }+ var activeController by remember { mutableStateOf<OdfMarkdownEditorController?>(null) }++ Scaffold(+ topBar = {+ TopAppBar(+ title = {},+ navigationIcon = { IconNavigation { actions.back() } },+ actions = {+ IconButton({ actions.copyNote() }) { IconCopy() }+ IconButton({ actions.shareNote() }) { IconShare() }+ IconButton({ actions.deleteNote() }) { IconDelete() }+ },+ )+ },+ bottomBar = {+ // One horizontally-scrollable bar. While a text block is focused it shows+ // the markdown formatting buttons followed by the insert buttons; otherwise+ // it shows just the insert buttons. Everything lives in a single row.+ val insertButtons: @Composable RowScope.() -> Unit = {+ FormatIconButton(stringResource(R.string.add_image), onClick = {+ actions.addImage(focusedBlockId)+ }) { IconImage() }+ FormatIconButton(stringResource(R.string.add_drawing), onClick = {+ actions.addDrawing(focusedBlockId)+ }) { IconDraw() }+ }+ val controller = activeController+ if (controller != null && controller.focused) {+ OdfMarkdownEditorToolbar(controller, trailing = insertButtons)+ } else {+ EditorBottomBar(scrollable = true, content = insertButtons)+ }+ },+ ) { paddingValues ->+ Column(+ Modifier+ .padding(paddingValues)+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(horizontal = 16.dp),+ ) {+ BasicTextField(+ state.title,+ { actions.setTitle(it) },+ Modifier.fillMaxWidth().padding(top = 8.dp),+ singleLine = true,+ textStyle = MaterialTheme.typography.headlineMedium.copy(color = LocalContentColor.current),+ cursorBrush = SolidColor(LocalContentColor.current),+ decorationBox = { innerTextField ->+ Box {+ if (state.title.isEmpty()) Text(+ text = stringResource(R.string.title),+ style = MaterialTheme.typography.headlineMedium.copy(color = MaterialTheme.colorScheme.onSurfaceVariant),+ )+ innerTextField()+ }+ },+ )++ state.blocks.forEach { block ->+ key(block.id) {+ when (block) {+ is NoteBlock.Text -> {+ val controller = rememberOdfMarkdownEditorController(initialMarkdown = block.markdown) { newMd ->+ actions.setBlockMarkdown(block.id, newMd)+ }+ LaunchedEffect(controller.focused) {+ if (controller.focused) {+ focusedBlockId = block.id+ activeController = controller+ }+ }+ OdfMarkdownEditorField(controller = controller, modifier = Modifier.fillMaxWidth())+ }++ is NoteBlock.Image -> ImageBlock(+ block = block,+ file = NoteImageStore.fileFor(context, block.fileName),+ onResize = { fraction -> actions.resizeImage(block.id, fraction) },+ onMoveUp = { actions.moveBlock(block.id, -1) },+ onMoveDown = { actions.moveBlock(block.id, 1) },+ onDelete = { actions.deleteBlock(block.id) },+ )++ is NoteBlock.Ink -> InkBlock(+ block = block,+ onEdit = { actions.editDrawing(block) },+ onMoveUp = { actions.moveBlock(block.id, -1) },+ onMoveDown = { actions.moveBlock(block.id, 1) },+ onDelete = { actions.deleteBlock(block.id) },+ )+ }+ }+ }+ }+ }+}++@Composable+private fun ImageBlock(+ block: NoteBlock.Image,+ file: File,+ onResize: (Float) -> Unit,+ onMoveUp: () -> Unit,+ onMoveDown: () -> Unit,+ onDelete: () -> Unit,+) {+ Column(Modifier.fillMaxWidth().padding(vertical = 8.dp)) {+ AsyncImage(+ model = file,+ contentDescription = null,+ modifier = Modifier+ .fillMaxWidth(block.widthFraction)+ .clip(RoundedCornerShape(8.dp)),+ )+ BlockControls(onMoveUp = onMoveUp, onMoveDown = onMoveDown, onDelete = onDelete) {+ // Step image width between quarter and full width.+ IconButton(onClick = { onResize((block.widthFraction - 0.25f).coerceAtLeast(0.25f)) }) {+ IconKeyboardArrowDown()+ }+ IconButton(onClick = { onResize((block.widthFraction + 0.25f).coerceAtMost(1f)) }) {+ IconKeyboardArrowUp()+ }+ }+ }+}++@Composable+private fun InkBlock(+ block: NoteBlock.Ink,+ onEdit: () -> Unit,+ onMoveUp: () -> Unit,+ onMoveDown: () -> Unit,+ onDelete: () -> Unit,+) {+ val strokes = remember(block) { block.strokes.map { it.deserialize() } }+ Column(Modifier.fillMaxWidth().padding(vertical = 8.dp)) {+ Box(+ Modifier+ .fillMaxWidth()+ .height(block.heightDp.dp)+ .border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(8.dp))+ .clip(RoundedCornerShape(8.dp))+ .clickable { onEdit() },+ ) {+ InkCanvasView(+ currentBrush = previewBrush,+ finishedStrokes = strokes,+ onStrokeFinished = {},+ enabled = false,+ modifier = Modifier.fillMaxSize(),+ )+ }+ BlockControls(onMoveUp = onMoveUp, onMoveDown = onMoveDown, onDelete = onDelete)+ }+}++@Composable+private fun BlockControls(+ onMoveUp: () -> Unit,+ onMoveDown: () -> Unit,+ onDelete: () -> Unit,+ extra: @Composable () -> Unit = {},+) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ extra()+ IconButton(onClick = onMoveUp) {+ IconKeyboardArrowUp()+ }+ IconButton(onClick = onMoveDown) {+ IconKeyboardArrowDown()+ }+ IconButton(onClick = onDelete) { IconDelete() }+ }+}++// A read-only ink preview needs some brush, but strokes carry their own; this is unused for drawing.+private val previewBrush by lazy {+ Brush.createWithColorIntArgb(StockBrushes.pressurePen(), 0xFF000000.toInt(), 6f, 0.1f)+}
notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.ktindex 55c1e79ca3..b97fc7db7b 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListPage.kt@@ -1,310 +1,310 @@-package com.vayunmathur.notes.ui--import androidx.compose.ui.res.stringResource-import com.vayunmathur.notes.R-import androidx.activity.compose.BackHandler-import androidx.compose.animation.core.animateDpAsState-import androidx.compose.foundation.ExperimentalFoundationApi-import androidx.compose.foundation.combinedClickable-import androidx.compose.foundation.layout.PaddingValues-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.RowScope-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.foundation.lazy.rememberLazyListState-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.FloatingActionButton-import com.vayunmathur.library.ui.IconDragHandle-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.ListItemDefaults-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.Surface-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import androidx.compose.runtime.derivedStateOf-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateListOf-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.graphics.graphicsLayer-import androidx.compose.ui.hapticfeedback.HapticFeedbackType-import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.platform.LocalHapticFeedback-import androidx.compose.ui.unit.dp-import androidx.compose.ui.zIndex-import com.vayunmathur.library.ui.BackupButtons-import com.vayunmathur.library.room.SqlCipherDbCodec-import com.vayunmathur.library.ui.CommonSearchBar-import com.vayunmathur.library.ui.IconAdd-import com.vayunmathur.library.ui.IconClose-import com.vayunmathur.library.ui.IconDelete-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.notes.Route-import com.vayunmathur.notes.data.Note-import com.vayunmathur.notes.data.noteDbConfigs-import com.vayunmathur.notes.util.NotesListActions-import com.vayunmathur.notes.util.NotesListUiState-import com.vayunmathur.notes.util.NotesViewModel-import com.vayunmathur.library.ui.ReorderableItem-import com.vayunmathur.library.ui.rememberReorderableLazyListState-import com.vayunmathur.library.ui.reorderDragHandle--/** Binds [NotesViewModel] and the nav back stack to the stateless [NotesListScreen]. */-@Composable-fun NotesListPage(backStack: NavBackStack<Route>, viewModel: NotesViewModel) {- val context = LocalContext.current- val notes by viewModel.notes.collectAsStateWithLifecycle()-- val actions = remember(backStack, viewModel) {- object : NotesListActions {- override fun openNote(id: Long) { backStack.add(Route.Note(id)) }- override fun createNote() { backStack.add(Route.Note(0)) }- override fun delete(note: Note) { viewModel.delete(note) }- override fun upsertAll(notes: List<Note>) { viewModel.upsertAll(notes) }- }- }-- NotesListScreen(- state = NotesListUiState(notes = notes, showAddButton = backStack.last() !is Route.Note),- actions = actions,- // Passed in rather than built inside the screen: the backup buttons need the- // database passphrase, which only exists on a real device.- backupButtons = {- BackupButtons(- dbConfigs = remember { noteDbConfigs(context) },- dbCodec = SqlCipherDbCodec,- extraFiles = emptyList()- )- },- )-}--/**- * The notes list, with no dependency on the ViewModel or the back stack so it can be- * rendered from a `@Preview` — see `src/screenshotTest`, which is where the store listing- * images come from.- */-@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)-@Composable-fun NotesListScreen(- state: NotesListUiState,- actions: NotesListActions,- /** Top-bar backup/restore buttons; empty in a preview, which has no database. */- backupButtons: @Composable RowScope.() -> Unit = {},- /**- * Seed for the screen's own UI-only search state. The app always takes the default;- * previews set it so the search results can be captured without typing.- */- initialSearchQuery: String = "",-) {- var searchQuery by remember { mutableStateOf(initialSearchQuery) }- val filtered = remember(state.notes, searchQuery) {- if (searchQuery.isBlank()) state.notes- else state.notes.filter { it.toString().contains(searchQuery, true) }- }-- BackHandler(enabled = searchQuery.isNotEmpty()) {- searchQuery = ""- }-- val hapticFeedback = LocalHapticFeedback.current- val selectedIds = remember { mutableStateListOf<Long>() }- val isSelectionMode by remember { derivedStateOf { selectedIds.isNotEmpty() } }-- val listState = rememberLazyListState()- var localData by remember { mutableStateOf(filtered) }-- val selectedIndices by remember {- derivedStateOf {- localData.mapIndexedNotNull { index, item ->- if (item.id in selectedIds) index else null- }- }- }- val isContiguous by remember {- derivedStateOf {- selectedIndices.isEmpty() || selectedIndices.size == 1 ||- (selectedIndices.last() - selectedIndices.first() == selectedIndices.size - 1)- }- }-- var hasDragged by remember { mutableStateOf(false) }-- val reorderState = rememberReorderableLazyListState(listState, onMove = { from, to ->- val fromIdx = from.index- val toIdx = to.index- if (fromIdx in localData.indices && toIdx in localData.indices) {- val mutableList = localData.toMutableList()- val draggedItem = localData[fromIdx]- if (isSelectionMode && isContiguous && draggedItem.id in selectedIds) {- val selectedInOrder = selectedIndices.map { localData[it] }- mutableList.removeAll { it.id in selectedIds }- val targetItem = localData[toIdx]- var insertIdx = mutableList.indexOfFirst { it.id == targetItem.id }- if (insertIdx == -1) insertIdx = 0- if (toIdx > fromIdx) insertIdx++- val prevPos = mutableList.getOrNull(insertIdx - 1)?.position- val nextPos = mutableList.getOrNull(insertIdx)?.position- val startPos = prevPos ?: ((nextPos ?: 0.0) - 100.0)- val endPos = nextPos ?: (startPos + 100.0)- val step = (endPos - startPos) / (selectedInOrder.size + 1)- val movedItems = selectedInOrder.mapIndexed { index, item ->- item.withPosition(startPos + step * (index + 1))- }- mutableList.addAll(insertIdx, movedItems)- localData = mutableList- } else if (!isSelectionMode) {- val prevIdx = if (toIdx > fromIdx) toIdx else toIdx - 1- val nextIdx = if (toIdx > fromIdx) toIdx + 1 else toIdx- val prevPos = localData.getOrNull(prevIdx)?.position- val nextPos = localData.getOrNull(nextIdx)?.position- val resultItemPosition = when {- prevPos == null -> (nextPos ?: 0.0) - 50.0- nextPos == null -> prevPos + 50.0- else -> (prevPos + nextPos) / 2.0- }- val movedItem = mutableList.removeAt(fromIdx).withPosition(resultItemPosition)- mutableList.add(toIdx, movedItem)- localData = mutableList- }- hasDragged = true- hapticFeedback.performHapticFeedback(HapticFeedbackType.SegmentFrequentTick)- }- })-- LaunchedEffect(filtered) {- if (!reorderState.isAnyItemDragging) {- localData = filtered.sortedBy { it.position }- }- }-- val isDragging = reorderState.isAnyItemDragging- LaunchedEffect(isDragging) {- if (!isDragging && hasDragged) {- actions.upsertAll(localData)- hasDragged = false- }- }-- Scaffold(- topBar = {- if (isSelectionMode) {- TopAppBar(- title = { Text(selectedIds.size.toString()) },- navigationIcon = {- IconButton(onClick = { selectedIds.clear() }) {- IconClose()- }- },- actions = {- val selectedNotes = localData.filter { it.id in selectedIds }- IconButton(onClick = {- selectedNotes.forEach { actions.delete(it) }- selectedIds.clear()- }) {- IconDelete()- }- }- )- } else {- TopAppBar(- title = {- CommonSearchBar(- value = searchQuery,- onValueChange = { searchQuery = it },- placeholder = stringResource(R.string.app_name),- padding = PaddingValues(0.dp)- )- },- actions = backupButtons- )- }- },- floatingActionButton = {- if (state.showAddButton && !isSelectionMode) {- FloatingActionButton(onClick = { actions.createNote() }) {- IconAdd()- }- }- }- ) { paddingValues ->- LazyColumn(- state = listState,- modifier = Modifier.fillMaxSize(),- contentPadding = paddingValues- ) {- items(localData, key = { it.id }) { note ->- val dragging = reorderState.draggingKey == note.id- // Item root: follow the finger 1:1 while dragging; otherwise glide into place.- val itemMod = if (dragging) {- Modifier- .zIndex(1f)- .graphicsLayer { translationY = reorderState.draggingItemTranslation }- } else {- Modifier.animateItem()- }- ReorderableItem(reorderState, key = note.id, modifier = itemMod) { isDragging ->- val elevation by animateDpAsState(if (isDragging) 8.dp else 0.dp)- val isSelected = note.id in selectedIds- Surface(shadowElevation = elevation) {- ListItem(- content = { Text(note.title) },- modifier = Modifier.combinedClickable(- onClick = {- if (isSelectionMode) {- if (isSelected) selectedIds.remove(note.id)- else selectedIds.add(note.id)- } else {- actions.openNote(note.id)- }- },- onLongClick = {- if (!isSelectionMode) {- selectedIds.add(note.id)- }- }- ),- supportingContent = {- Text(note.content.substringBefore('\n').take(40))- },- trailingContent = {- Row(verticalAlignment = Alignment.CenterVertically) {- if (localData.size > 1 && selectedIds.size < localData.size && (!isSelectionMode || isContiguous)) {- IconButton(- modifier = Modifier.reorderDragHandle(- reorderState = reorderState,- key = note.id,- onDragStarted = {- hapticFeedback.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate)- },- onDragStopped = {- hapticFeedback.performHapticFeedback(HapticFeedbackType.GestureEnd)- },- ),- onClick = {},- ) {- IconDragHandle()- }- }- }- },- colors = ListItemDefaults.colors(- containerColor = if (isSelected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface- ),- elevation = ListItemDefaults.elevation(elevation = elevation),- )- }- }- }- }- }-}+package com.vayunmathur.notes.ui++import androidx.compose.ui.res.stringResource+import com.vayunmathur.notes.R+import androidx.activity.compose.BackHandler+import androidx.compose.animation.core.animateDpAsState+import androidx.compose.foundation.ExperimentalFoundationApi+import androidx.compose.foundation.combinedClickable+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.FloatingActionButton+import com.vayunmathur.library.ui.IconDragHandle+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.ListItemDefaults+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.unit.dp+import androidx.compose.ui.zIndex+import com.vayunmathur.library.ui.BackupButtons+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.notes.Route+import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.noteDbConfigs+import com.vayunmathur.notes.platform.NotesListActions+import com.vayunmathur.notes.platform.NotesListUiState+import com.vayunmathur.notes.platform.NotesViewModel+import com.vayunmathur.library.ui.ReorderableItem+import com.vayunmathur.library.ui.rememberReorderableLazyListState+import com.vayunmathur.library.ui.reorderDragHandle++/** Binds [NotesViewModel] and the nav back stack to the stateless [NotesListScreen]. */+@Composable+fun NotesListPage(backStack: NavBackStack<Route>, viewModel: NotesViewModel) {+ val context = LocalContext.current+ val notes by viewModel.notes.collectAsStateWithLifecycle()++ val actions = remember(backStack, viewModel) {+ object : NotesListActions {+ override fun openNote(id: Long) { backStack.add(Route.Note(id)) }+ override fun createNote() { backStack.add(Route.Note(0)) }+ override fun delete(note: Note) { viewModel.delete(note) }+ override fun upsertAll(notes: List<Note>) { viewModel.upsertAll(notes) }+ }+ }++ NotesListScreen(+ state = NotesListUiState(notes = notes, showAddButton = backStack.last() !is Route.Note),+ actions = actions,+ // Passed in rather than built inside the screen: the backup buttons need the+ // database passphrase, which only exists on a real device.+ backupButtons = {+ BackupButtons(+ dbConfigs = remember { noteDbConfigs(context) },+ dbCodec = SqlCipherDbCodec,+ extraFiles = emptyList()+ )+ },+ )+}++/**+ * The notes list, with no dependency on the ViewModel or the back stack so it can be+ * rendered from a `@Preview` — see `src/screenshotTest`, which is where the store listing+ * images come from.+ */+@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)+@Composable+fun NotesListScreen(+ state: NotesListUiState,+ actions: NotesListActions,+ /** Top-bar backup/restore buttons; empty in a preview, which has no database. */+ backupButtons: @Composable RowScope.() -> Unit = {},+ /**+ * Seed for the screen's own UI-only search state. The app always takes the default;+ * previews set it so the search results can be captured without typing.+ */+ initialSearchQuery: String = "",+) {+ var searchQuery by remember { mutableStateOf(initialSearchQuery) }+ val filtered = remember(state.notes, searchQuery) {+ if (searchQuery.isBlank()) state.notes+ else state.notes.filter { it.toString().contains(searchQuery, true) }+ }++ BackHandler(enabled = searchQuery.isNotEmpty()) {+ searchQuery = ""+ }++ val hapticFeedback = LocalHapticFeedback.current+ val selectedIds = remember { mutableStateListOf<Long>() }+ val isSelectionMode by remember { derivedStateOf { selectedIds.isNotEmpty() } }++ val listState = rememberLazyListState()+ var localData by remember { mutableStateOf(filtered) }++ val selectedIndices by remember {+ derivedStateOf {+ localData.mapIndexedNotNull { index, item ->+ if (item.id in selectedIds) index else null+ }+ }+ }+ val isContiguous by remember {+ derivedStateOf {+ selectedIndices.isEmpty() || selectedIndices.size == 1 ||+ (selectedIndices.last() - selectedIndices.first() == selectedIndices.size - 1)+ }+ }++ var hasDragged by remember { mutableStateOf(false) }++ val reorderState = rememberReorderableLazyListState(listState, onMove = { from, to ->+ val fromIdx = from.index+ val toIdx = to.index+ if (fromIdx in localData.indices && toIdx in localData.indices) {+ val mutableList = localData.toMutableList()+ val draggedItem = localData[fromIdx]+ if (isSelectionMode && isContiguous && draggedItem.id in selectedIds) {+ val selectedInOrder = selectedIndices.map { localData[it] }+ mutableList.removeAll { it.id in selectedIds }+ val targetItem = localData[toIdx]+ var insertIdx = mutableList.indexOfFirst { it.id == targetItem.id }+ if (insertIdx == -1) insertIdx = 0+ if (toIdx > fromIdx) insertIdx+++ val prevPos = mutableList.getOrNull(insertIdx - 1)?.position+ val nextPos = mutableList.getOrNull(insertIdx)?.position+ val startPos = prevPos ?: ((nextPos ?: 0.0) - 100.0)+ val endPos = nextPos ?: (startPos + 100.0)+ val step = (endPos - startPos) / (selectedInOrder.size + 1)+ val movedItems = selectedInOrder.mapIndexed { index, item ->+ item.withPosition(startPos + step * (index + 1))+ }+ mutableList.addAll(insertIdx, movedItems)+ localData = mutableList+ } else if (!isSelectionMode) {+ val prevIdx = if (toIdx > fromIdx) toIdx else toIdx - 1+ val nextIdx = if (toIdx > fromIdx) toIdx + 1 else toIdx+ val prevPos = localData.getOrNull(prevIdx)?.position+ val nextPos = localData.getOrNull(nextIdx)?.position+ val resultItemPosition = when {+ prevPos == null -> (nextPos ?: 0.0) - 50.0+ nextPos == null -> prevPos + 50.0+ else -> (prevPos + nextPos) / 2.0+ }+ val movedItem = mutableList.removeAt(fromIdx).withPosition(resultItemPosition)+ mutableList.add(toIdx, movedItem)+ localData = mutableList+ }+ hasDragged = true+ hapticFeedback.performHapticFeedback(HapticFeedbackType.SegmentFrequentTick)+ }+ })++ LaunchedEffect(filtered) {+ if (!reorderState.isAnyItemDragging) {+ localData = filtered.sortedBy { it.position }+ }+ }++ val isDragging = reorderState.isAnyItemDragging+ LaunchedEffect(isDragging) {+ if (!isDragging && hasDragged) {+ actions.upsertAll(localData)+ hasDragged = false+ }+ }++ Scaffold(+ topBar = {+ if (isSelectionMode) {+ TopAppBar(+ title = { Text(selectedIds.size.toString()) },+ navigationIcon = {+ IconButton(onClick = { selectedIds.clear() }) {+ IconClose()+ }+ },+ actions = {+ val selectedNotes = localData.filter { it.id in selectedIds }+ IconButton(onClick = {+ selectedNotes.forEach { actions.delete(it) }+ selectedIds.clear()+ }) {+ IconDelete()+ }+ }+ )+ } else {+ TopAppBar(+ title = {+ CommonSearchBar(+ value = searchQuery,+ onValueChange = { searchQuery = it },+ placeholder = stringResource(R.string.app_name),+ padding = PaddingValues(0.dp)+ )+ },+ actions = backupButtons+ )+ }+ },+ floatingActionButton = {+ if (state.showAddButton && !isSelectionMode) {+ FloatingActionButton(onClick = { actions.createNote() }) {+ IconAdd()+ }+ }+ }+ ) { paddingValues ->+ LazyColumn(+ state = listState,+ modifier = Modifier.fillMaxSize(),+ contentPadding = paddingValues+ ) {+ items(localData, key = { it.id }) { note ->+ val dragging = reorderState.draggingKey == note.id+ // Item root: follow the finger 1:1 while dragging; otherwise glide into place.+ val itemMod = if (dragging) {+ Modifier+ .zIndex(1f)+ .graphicsLayer { translationY = reorderState.draggingItemTranslation }+ } else {+ Modifier.animateItem()+ }+ ReorderableItem(reorderState, key = note.id, modifier = itemMod) { isDragging ->+ val elevation by animateDpAsState(if (isDragging) 8.dp else 0.dp)+ val isSelected = note.id in selectedIds+ Surface(shadowElevation = elevation) {+ ListItem(+ content = { Text(note.title) },+ modifier = Modifier.combinedClickable(+ onClick = {+ if (isSelectionMode) {+ if (isSelected) selectedIds.remove(note.id)+ else selectedIds.add(note.id)+ } else {+ actions.openNote(note.id)+ }+ },+ onLongClick = {+ if (!isSelectionMode) {+ selectedIds.add(note.id)+ }+ }+ ),+ supportingContent = {+ Text(note.content.substringBefore('\n').take(40))+ },+ trailingContent = {+ Row(verticalAlignment = Alignment.CenterVertically) {+ if (localData.size > 1 && selectedIds.size < localData.size && (!isSelectionMode || isContiguous)) {+ IconButton(+ modifier = Modifier.reorderDragHandle(+ reorderState = reorderState,+ key = note.id,+ onDragStarted = {+ hapticFeedback.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate)+ },+ onDragStopped = {+ hapticFeedback.performHapticFeedback(HapticFeedbackType.GestureEnd)+ },+ ),+ onClick = {},+ ) {+ IconDragHandle()+ }+ }+ }+ },+ colors = ListItemDefaults.colors(+ containerColor = if (isSelected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface+ ),+ elevation = ListItemDefaults.elevation(elevation = elevation),+ )+ }+ }+ }+ }+ }+}
notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.kt
diff --git a/notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.kt b/notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.ktindex 86f49c80b2..310d69efb0 100644--- a/notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.kt+++ b/notes/src/screenshotTest/kotlin/com/vayunmathur/notes/ui/MetadataPreviews.kt@@ -1,120 +1,120 @@-package com.vayunmathur.notes.ui--import androidx.compose.runtime.Composable-import androidx.compose.ui.tooling.preview.Preview-import com.android.tools.screenshot.PreviewTest-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.notes.data.Note-import com.vayunmathur.notes.data.NoteBlock-import com.vayunmathur.notes.util.NoteActions-import com.vayunmathur.notes.util.NoteUiState-import com.vayunmathur.notes.util.NotesListActions-import com.vayunmathur.notes.util.NotesListUiState--/** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */-private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"--/**- * Store listing images for `:notes`. See `common-conventions-preview-metadata`.- *- * Each preview needs @PreviewTest as well as @Preview: @Preview alone renders in Studio but- * is not collected as a screenshot test. Previews must also be class members, not top-level- * functions. Order comes from the function names (Preview1…, Preview2…).- *- * Everything here is a literal — no ViewModel, no database, no device — which is also what- * makes the images reproducible from a clean checkout. Block ids are spelled out for the- * same reason: the default is a random UUID, which would change the `key()` identity (and- * so the render) on every run.- */-class MetadataPreviews {-- private val samples = listOf(- Note(- id = 1,- title = "Weekend plans",- content = "Saturday: farmers market + hike at Twin Peaks. Sunday: brunch with Sam, then finish the book.",- position = 0.0,- ),- Note(- id = 2,- title = "Groceries",- content = "Oat milk, eggs, sourdough, spinach, cherry tomatoes, olive oil, dark chocolate.",- position = 1.0,- ),- Note(- id = 3,- title = "Project ideas",- content = "1. Auto-generate app screenshots 2. Offline map tiles 3. A tiny synth in Compose.",- position = 2.0,- ),- Note(- id = 4,- title = "Meeting notes",- content = "Ship the metadata pipeline. Add dark-mode shots. Review the release checklist.",- position = 3.0,- ),- Note(- id = 5,- title = "Books to read",- content = "Project Hail Mary • The Pragmatic Programmer • Piranesi • Thinking in Systems.",- position = 4.0,- ),- )-- @PreviewTest- @Preview(name = "1-notes", device = PHONE, showSystemUi = true)- @Composable- fun Preview1Notes() {- DynamicTheme(darkTheme = true) {- NotesListScreen(- state = NotesListUiState(notes = samples),- actions = NotesListActions.Noop,- )- }- }-- @PreviewTest- @Preview(name = "2-editor", device = PHONE, showSystemUi = true)- @Composable- fun Preview2Editor() {- DynamicTheme(darkTheme = true) {- NoteScreen(- state = NoteUiState(- title = "Weekend plans",- blocks = listOf(- NoteBlock.Text(- markdown = """- ## Saturday-- - [x] Farmers market at 9- - [ ] Hike at Twin Peaks- - [ ] Pick up the framed print-- ## Sunday-- Brunch with **Sam** at 11, then finish *Piranesi*.-- Bring: water, sunscreen, the good camera.- """.trimIndent(),- id = "weekend-body",- ),- ),- ),- actions = NoteActions.Noop,- )- }- }-- @PreviewTest- @Preview(name = "3-search", device = PHONE, showSystemUi = true)- @Composable- fun Preview3Search() {- DynamicTheme(darkTheme = true) {- NotesListScreen(- state = NotesListUiState(notes = samples),- actions = NotesListActions.Noop,- initialSearchQuery = "book",- )- }- }-}+package com.vayunmathur.notes.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.tooling.preview.Preview+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.NoteBlock+import com.vayunmathur.notes.platform.NoteActions+import com.vayunmathur.notes.platform.NoteUiState+import com.vayunmathur.notes.platform.NotesListActions+import com.vayunmathur.notes.platform.NotesListUiState++/** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */+private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"++/**+ * Store listing images for `:notes`. See `common-conventions-preview-metadata`.+ *+ * Each preview needs @PreviewTest as well as @Preview: @Preview alone renders in Studio but+ * is not collected as a screenshot test. Previews must also be class members, not top-level+ * functions. Order comes from the function names (Preview1…, Preview2…).+ *+ * Everything here is a literal — no ViewModel, no database, no device — which is also what+ * makes the images reproducible from a clean checkout. Block ids are spelled out for the+ * same reason: the default is a random UUID, which would change the `key()` identity (and+ * so the render) on every run.+ */+class MetadataPreviews {++ private val samples = listOf(+ Note(+ id = 1,+ title = "Weekend plans",+ content = "Saturday: farmers market + hike at Twin Peaks. Sunday: brunch with Sam, then finish the book.",+ position = 0.0,+ ),+ Note(+ id = 2,+ title = "Groceries",+ content = "Oat milk, eggs, sourdough, spinach, cherry tomatoes, olive oil, dark chocolate.",+ position = 1.0,+ ),+ Note(+ id = 3,+ title = "Project ideas",+ content = "1. Auto-generate app screenshots 2. Offline map tiles 3. A tiny synth in Compose.",+ position = 2.0,+ ),+ Note(+ id = 4,+ title = "Meeting notes",+ content = "Ship the metadata pipeline. Add dark-mode shots. Review the release checklist.",+ position = 3.0,+ ),+ Note(+ id = 5,+ title = "Books to read",+ content = "Project Hail Mary • The Pragmatic Programmer • Piranesi • Thinking in Systems.",+ position = 4.0,+ ),+ )++ @PreviewTest+ @Preview(name = "1-notes", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview1Notes() {+ DynamicTheme(darkTheme = true) {+ NotesListScreen(+ state = NotesListUiState(notes = samples),+ actions = NotesListActions.Noop,+ )+ }+ }++ @PreviewTest+ @Preview(name = "2-editor", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview2Editor() {+ DynamicTheme(darkTheme = true) {+ NoteScreen(+ state = NoteUiState(+ title = "Weekend plans",+ blocks = listOf(+ NoteBlock.Text(+ markdown = """+ ## Saturday++ - [x] Farmers market at 9+ - [ ] Hike at Twin Peaks+ - [ ] Pick up the framed print++ ## Sunday++ Brunch with **Sam** at 11, then finish *Piranesi*.++ Bring: water, sunscreen, the good camera.+ """.trimIndent(),+ id = "weekend-body",+ ),+ ),+ ),+ actions = NoteActions.Noop,+ )+ }+ }++ @PreviewTest+ @Preview(name = "3-search", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview3Search() {+ DynamicTheme(darkTheme = true) {+ NotesListScreen(+ state = NotesListUiState(notes = samples),+ actions = NotesListActions.Noop,+ initialSearchQuery = "book",+ )+ }+ }+}