Modern Apps git

← Modern-Apps.git

notes: convert raw Scaffolds to shared scaffolds (DetailScaffold/LazyListScaffold/AppScaffold)

Commit
a0d68b703e8fffd86d0fb40fc8288b4a348e7df8
Author
vayun-mathur <[email protected]>
When
2026-08-16 03:06 UTC (3 months ago)
Parents
edb762f

Diff

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 f515bc795c..f3169fc34c 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,93 @@-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()-            }-        }-    }-}+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.AppScaffold+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.IconSave+import com.vayunmathur.library.ui.OdfMarkdownEditor+import com.vayunmathur.library.ui.Text+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+    }++    AppScaffold(+        title = title.ifBlank { stringResource(R.string.title) },+        onNavigateBack = { 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/InkEditorPage.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/InkEditorPage.kt b/notes/src/main/java/com/vayunmathur/notes/ui/InkEditorPage.ktindex 86008d7882..d067685481 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/InkEditorPage.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/InkEditorPage.kt@@ -14,15 +14,14 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape+import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.Icon import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Slider 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.getValue import androidx.compose.runtime.mutableStateListOf@@ -40,7 +39,6 @@ import androidx.ink.brush.StockBrushes import androidx.ink.strokes.Stroke import com.vayunmathur.library.ui.IconBrush import com.vayunmathur.library.ui.IconCheck-import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconDraw import com.vayunmathur.library.ui.IconEraser import com.vayunmathur.library.ui.IconForward@@ -94,15 +92,11 @@ fun InkEditor(         )     } -    Scaffold(-        topBar = {-            TopAppBar(-                title = { Text(stringResource(R.string.drawing)) },-                navigationIcon = { IconButton(onClick = onCancel) { IconClose() } },-                actions = {-                    IconButton(onClick = { onDone(strokes.map { it.serialize() }) }) { IconCheck() }-                },-            )+    AppScaffold(+        title = stringResource(R.string.drawing),+        onClose = onCancel,+        actions = {+            IconButton(onClick = { onDone(strokes.map { it.serialize() }) }) { IconCheck() }         },         bottomBar = {             InkToolbar(
notes/src/main/java/com/vayunmathur/notes/ui/NoteScreen.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NoteScreen.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NoteScreen.ktindex 15ef82b23f..f4f340f140 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NoteScreen.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NoteScreen.kt@@ -1,164 +1,146 @@-package com.vayunmathur.notes.ui--import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.RowScope-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.text.BasicTextField-import androidx.compose.foundation.verticalScroll-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.key-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.draw.clip-import androidx.compose.ui.graphics.SolidColor-import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.EditorBottomBar-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.FormatIconButton-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconCopy-import com.vayunmathur.library.ui.IconDelete-import com.vayunmathur.library.ui.IconDraw-import com.vayunmathur.library.ui.IconImage-import com.vayunmathur.library.ui.IconNavigation-import com.vayunmathur.library.ui.IconShare-import com.vayunmathur.library.ui.LocalContentColor-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OdfMarkdownEditorController-import com.vayunmathur.library.ui.OdfMarkdownEditorField-import com.vayunmathur.library.ui.OdfMarkdownEditorToolbar-import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBar-import com.vayunmathur.library.ui.rememberOdfMarkdownEditorController-import com.vayunmathur.library.ink.deserialize-import com.vayunmathur.notes.R-import com.vayunmathur.notes.data.NoteBlock-import com.vayunmathur.notes.data.randomBlockId-import com.vayunmathur.notes.platform.NoteActions-import com.vayunmathur.notes.platform.NoteImageStore-import com.vayunmathur.notes.platform.NoteUiState-import com.vayunmathur.notes.ui.components.ImageBlock-import com.vayunmathur.notes.ui.components.InkBlock--/**- * 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) },-                        )-                    }-                }-            }-        }-    }-}+package com.vayunmathur.notes.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.key+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.draw.clip+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.EditorBottomBar+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.DetailScaffold+import com.vayunmathur.library.ui.FormatIconButton+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconCopy+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconDraw+import com.vayunmathur.library.ui.IconImage+import com.vayunmathur.library.ui.IconShare+import com.vayunmathur.library.ui.LocalContentColor+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OdfMarkdownEditorController+import com.vayunmathur.library.ui.OdfMarkdownEditorField+import com.vayunmathur.library.ui.OdfMarkdownEditorToolbar+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberOdfMarkdownEditorController+import com.vayunmathur.library.ink.deserialize+import com.vayunmathur.notes.R+import com.vayunmathur.notes.data.NoteBlock+import com.vayunmathur.notes.data.randomBlockId+import com.vayunmathur.notes.platform.NoteActions+import com.vayunmathur.notes.platform.NoteImageStore+import com.vayunmathur.notes.platform.NoteUiState+import com.vayunmathur.notes.ui.components.ImageBlock+import com.vayunmathur.notes.ui.components.InkBlock++/**+ * 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) }++    DetailScaffold(+        title = {},+        onNavigateBack = { 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)+            }+        },+    ) {+        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) },+                        )+                    }+                }+            }+    }+}
notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.ktindex ca7f2a5676..ffd0170b08 100644--- a/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt+++ b/notes/src/main/java/com/vayunmathur/notes/ui/NotesListScreen.kt@@ -1,272 +1,267 @@-package com.vayunmathur.notes.ui--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 androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-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.LocalHapticFeedback-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.unit.dp-import androidx.compose.ui.zIndex-import com.vayunmathur.library.ui.CommonSearchBar-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.FloatingActionButton-import com.vayunmathur.library.ui.IconAdd-import com.vayunmathur.library.ui.IconClose-import com.vayunmathur.library.ui.IconDelete-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 com.vayunmathur.library.ui.ReorderableItem-import com.vayunmathur.library.ui.rememberReorderableLazyListState-import com.vayunmathur.library.ui.reorderDragHandle-import com.vayunmathur.notes.R-import com.vayunmathur.notes.data.Note-import com.vayunmathur.notes.platform.NotesListActions-import com.vayunmathur.notes.platform.NotesListUiState--/**- * 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.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 androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+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.LocalHapticFeedback+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.compose.ui.zIndex+import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.FloatingActionButton+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconDelete+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.LazyListScaffold+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.ui.ReorderableItem+import com.vayunmathur.library.ui.rememberReorderableLazyListState+import com.vayunmathur.library.ui.reorderDragHandle+import com.vayunmathur.notes.R+import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.platform.NotesListActions+import com.vayunmathur.notes.platform.NotesListUiState++/**+ * 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+        }+    }++    LazyListScaffold(+        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()+                }+            }+        },+        state = listState,+    ) {+            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),+                        )+                    }+                }+            }+    }+}