Modern Apps git

← Modern-Apps.git

notes: move util/ -> platform/ (AppBackupAgent, NoteImageStore, exporter, UiContract, ViewModel) (canonical structure)

Commit
d9505c550ae3150e4592b1cda66a1bb9a2ae49ec
Author
vayun-mathur <[email protected]>
When
2026-08-15 18:14 UTC (3 months ago)
Parents
505b896

Diff

notes/src/main/java/com/vayunmathur/notes/platform/AppBackupAgent.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/util/AppBackupAgent.kt b/notes/src/main/java/com/vayunmathur/notes/platform/AppBackupAgent.ktsimilarity index 88%rename from notes/src/main/java/com/vayunmathur/notes/util/AppBackupAgent.ktrename to notes/src/main/java/com/vayunmathur/notes/platform/AppBackupAgent.ktindex 5877b10f34..ae3d6472e7 100644--- a/notes/src/main/java/com/vayunmathur/notes/util/AppBackupAgent.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/AppBackupAgent.kt@@ -1,16 +1,16 @@-package com.vayunmathur.notes.util--import com.vayunmathur.library.room.SqlCipherDbCodec-import com.vayunmathur.library.util.BaseBackupAgent-import com.vayunmathur.notes.data.noteDbConfigs-import java.io.File--class AppBackupAgent : BaseBackupAgent() {-    override val dbCodec = SqlCipherDbCodec--    override val dbConfigs: List<Pair<String, String>>-        get() = noteDbConfigs(this)--    override val extraFiles: List<File>-        get() = emptyList()-}+package com.vayunmathur.notes.platform++import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.notes.data.noteDbConfigs+import java.io.File++class AppBackupAgent : BaseBackupAgent() {+    override val dbCodec = SqlCipherDbCodec++    override val dbConfigs: List<Pair<String, String>>+        get() = noteDbConfigs(this)++    override val extraFiles: List<File>+        get() = emptyList()+}
notes/src/main/java/com/vayunmathur/notes/platform/NoteImageStore.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/util/NoteImageStore.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NoteImageStore.ktsimilarity index 94%rename from notes/src/main/java/com/vayunmathur/notes/util/NoteImageStore.ktrename to notes/src/main/java/com/vayunmathur/notes/platform/NoteImageStore.ktindex c17e8d6d02..9697668ad2 100644--- a/notes/src/main/java/com/vayunmathur/notes/util/NoteImageStore.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NoteImageStore.kt@@ -1,42 +1,42 @@-@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)--package com.vayunmathur.notes.util--import kotlin.uuid.Uuid-import android.content.Context-import android.net.Uri-import java.io.File--/**- * Stores note images as files under `filesDir/note_images`. A [com.vayunmathur.notes.data.NoteBlock.Image]- * references an image by file name only, so the note database stays small and the- * images survive app restarts.- */-object NoteImageStore {-    private fun dir(context: Context): File =-        File(context.filesDir, "note_images").apply { mkdirs() }--    fun fileFor(context: Context, fileName: String): File = File(dir(context), fileName)--    /** Copies [uri] into the images dir and returns the new file name, or null on failure. */-    fun import(context: Context, uri: Uri): String? {-        val fileName = "img_${Uuid.random()}.jpg"-        val dest = File(dir(context), fileName)-        return try {-            context.contentResolver.openInputStream(uri)?.use { input ->-                dest.outputStream().use { output -> input.copyTo(output) }-            } ?: return null-            fileName-        } catch (e: Exception) {-            dest.delete()-            null-        }-    }--    fun delete(context: Context, fileName: String) {-        try {-            fileFor(context, fileName).delete()-        } catch (_: Exception) {-        }-    }-}+@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)++package com.vayunmathur.notes.platform++import kotlin.uuid.Uuid+import android.content.Context+import android.net.Uri+import java.io.File++/**+ * Stores note images as files under `filesDir/note_images`. A [com.vayunmathur.notes.data.NoteBlock.Image]+ * references an image by file name only, so the note database stays small and the+ * images survive app restarts.+ */+object NoteImageStore {+    private fun dir(context: Context): File =+        File(context.filesDir, "note_images").apply { mkdirs() }++    fun fileFor(context: Context, fileName: String): File = File(dir(context), fileName)++    /** Copies [uri] into the images dir and returns the new file name, or null on failure. */+    fun import(context: Context, uri: Uri): String? {+        val fileName = "img_${Uuid.random()}.jpg"+        val dest = File(dir(context), fileName)+        return try {+            context.contentResolver.openInputStream(uri)?.use { input ->+                dest.outputStream().use { output -> input.copyTo(output) }+            } ?: return null+            fileName+        } catch (e: Exception) {+            dest.delete()+            null+        }+    }++    fun delete(context: Context, fileName: String) {+        try {+            fileFor(context, fileName).delete()+        } catch (_: Exception) {+        }+    }+}
notes/src/main/java/com/vayunmathur/notes/platform/NoteMarkdownExporter.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/util/NoteMarkdownExporter.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NoteMarkdownExporter.ktsimilarity index 97%rename from notes/src/main/java/com/vayunmathur/notes/util/NoteMarkdownExporter.ktrename to notes/src/main/java/com/vayunmathur/notes/platform/NoteMarkdownExporter.ktindex f160ce0bae..6631349e94 100644--- a/notes/src/main/java/com/vayunmathur/notes/util/NoteMarkdownExporter.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NoteMarkdownExporter.kt@@ -1,162 +1,162 @@-package com.vayunmathur.notes.util--import android.content.Context-import android.graphics.Bitmap-import android.graphics.BitmapFactory-import android.net.Uri-import android.util.Base64-import androidx.core.content.FileProvider-import androidx.core.graphics.scale-import com.vayunmathur.library.ink.SerializedStroke-import com.vayunmathur.notes.data.Note-import com.vayunmathur.notes.data.NoteBlock-import com.vayunmathur.notes.data.body-import java.io.ByteArrayOutputStream-import java.io.File-import kotlin.math.roundToInt--/**- * Exports a note as a SINGLE self-contained Markdown document:- *  - text blocks are emitted verbatim,- *  - images are inlined as base64 `data:` URIs (no external files),- *  - drawings are converted to an inline `<svg>` element.- *- * Export-only: the stored JSON blocks stay the source of truth; this never- * touches storage. Reads image files, so call it off the main thread.- */-fun exportNoteMarkdown(context: Context, note: Note): String =-    note.body().blocks-        .map { block ->-            when (block) {-                is NoteBlock.Text -> block.markdown-                is NoteBlock.Image -> imageMarkdown(context, block)-                is NoteBlock.Ink -> inkSvg(block)-            }-        }-        .filter { it.isNotBlank() }-        .joinToString("\n\n")-        .trim() + "\n"--/**- * Writes [markdown] to `cacheDir/shared_notes/<title>.md` and returns a shareable- * FileProvider URI for it. Reuses the same cache dir + authority as- * [NotesViewModel.requestShare], so no extra manifest setup is needed. Used by copy- * so a note with inlined (multi-MB) images is passed as a URI instead of raw text.- */-fun markdownCacheUri(context: Context, note: Note, markdown: String): Uri {-    val cachePath = File(context.cacheDir, "shared_notes")-    cachePath.mkdirs()-    val file = File(cachePath, "${note.title.ifBlank { "note" }}.md")-    file.writeText(markdown)-    return FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)-}--/** Longest-side pixel cap and JPEG quality used when inlining images, to keep the export small. */-private const val MAX_IMAGE_DIMENSION = 1024-private const val JPEG_QUALITY = 60--/** An image inlined as an HTML `<img>` with a base64 data URI, honoring [NoteBlock.Image.widthFraction]. */-private fun imageMarkdown(context: Context, block: NoteBlock.Image): String {-    val bytes = try {-        downscaledJpegBytes(NoteImageStore.fileFor(context, block.fileName))-    } catch (e: Exception) {-        return ""-    } ?: return ""-    val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)-    val widthPercent = (block.widthFraction * 100).roundToInt().coerceIn(1, 100)-    return "<img src=\"data:image/jpeg;base64,$base64\" style=\"width:$widthPercent%\" />"-}--/**- * Decodes [file], downscales so the longest side is at most [MAX_IMAGE_DIMENSION]- * (never upscales), and re-encodes as JPEG at [JPEG_QUALITY] so the inlined base64- * stays small. Uses inSampleSize so large files aren't fully loaded into memory, and- * recycles bitmaps. Returns null if the file can't be decoded.- */-private fun downscaledJpegBytes(file: File): ByteArray? {-    val path = file.absolutePath--    // First pass: read only the dimensions (inJustDecodeBounds loads no pixels).-    val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }-    BitmapFactory.decodeFile(path, bounds)-    if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null--    // Second pass: decode at a reduced sample size to save memory on big images.-    val longest = maxOf(bounds.outWidth, bounds.outHeight)-    val options = BitmapFactory.Options().apply {-        inSampleSize = sampleSizeFor(longest, MAX_IMAGE_DIMENSION)-    }-    val decoded = BitmapFactory.decodeFile(path, options) ?: return null--    // Scale exactly to the cap if the sampled bitmap is still too large.-    val scaled = scaleToMax(decoded, MAX_IMAGE_DIMENSION)-    return ByteArrayOutputStream().use { out ->-        scaled.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, out)-        if (scaled != decoded) scaled.recycle()-        decoded.recycle()-        out.toByteArray()-    }-}--/** Largest power-of-two sample size that keeps the decoded longest side at least [target]. */-private fun sampleSizeFor(longest: Int, target: Int): Int {-    var sample = 1-    while (longest / (sample * 2) >= target) sample *= 2-    return sample-}--/** [bitmap] scaled so its longest side is [max], or the original if it's already small enough. */-private fun scaleToMax(bitmap: Bitmap, max: Int): Bitmap {-    val longest = maxOf(bitmap.width, bitmap.height)-    if (longest <= max) return bitmap-    val ratio = max.toFloat() / longest-    val width = (bitmap.width * ratio).roundToInt().coerceAtLeast(1)-    val height = (bitmap.height * ratio).roundToInt().coerceAtLeast(1)-    return bitmap.scale(width, height)-}--/** A drawing as an inline `<svg>`, one `<path>` per stroke, using the raw point coordinates. */-private fun inkSvg(block: NoteBlock.Ink): String {-    // Points are in the drawing canvas' pixel space. Size the SVG to bound them-    // (so it stays self-contained and keeps the right proportions); fall back to-    // the canvas height for an empty drawing.-    var width = 0f-    var height = 0f-    block.strokes.forEach { stroke ->-        stroke.points.forEach { p ->-            if (p.x > width) width = p.x-            if (p.y > height) height = p.y-        }-    }-    width = width.coerceAtLeast(1f)-    height = height.coerceAtLeast(block.heightDp.toFloat())--    val paths = block.strokes.mapNotNull { strokePath(it) }.joinToString("\n")-    return "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${num(width)}\" height=\"${num(height)}\" " +-        "viewBox=\"0 0 ${num(width)} ${num(height)}\">\n$paths\n</svg>"-}--/** Builds an SVG `<path>` ("M x y L x y ...") for one stroke, or null if it has no points. */-private fun strokePath(stroke: SerializedStroke): String? {-    if (stroke.points.isEmpty()) return null-    val d = stroke.points.mapIndexed { i, p ->-        "${if (i == 0) "M" else "L"} ${num(p.x)} ${num(p.y)}"-    }.joinToString(" ")-    return "<path d=\"$d\" fill=\"none\" stroke=\"${cssColor(stroke.brushColor)}\" " +-        "stroke-width=\"${num(stroke.brushSize)}\" stroke-linecap=\"round\" stroke-linejoin=\"round\" />"-}--/** An ARGB color int as a CSS `rgba(...)`, preserving alpha (e.g. highlighter transparency). */-private fun cssColor(argb: Int): String {-    val a = (argb ushr 24) and 0xFF-    val r = (argb ushr 16) and 0xFF-    val g = (argb ushr 8) and 0xFF-    val b = argb and 0xFF-    return "rgba($r,$g,$b,${num(a / 255f)})"-}--/** Formats a float compactly (drops the ".0" for whole numbers) to keep the output small. */-private fun num(value: Float): String {-    val rounded = (value * 100).roundToInt() / 100f-    return if (rounded % 1f == 0f) rounded.toInt().toString() else rounded.toString()-}+package com.vayunmathur.notes.platform++import android.content.Context+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.net.Uri+import android.util.Base64+import androidx.core.content.FileProvider+import androidx.core.graphics.scale+import com.vayunmathur.library.ink.SerializedStroke+import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.NoteBlock+import com.vayunmathur.notes.data.body+import java.io.ByteArrayOutputStream+import java.io.File+import kotlin.math.roundToInt++/**+ * Exports a note as a SINGLE self-contained Markdown document:+ *  - text blocks are emitted verbatim,+ *  - images are inlined as base64 `data:` URIs (no external files),+ *  - drawings are converted to an inline `<svg>` element.+ *+ * Export-only: the stored JSON blocks stay the source of truth; this never+ * touches storage. Reads image files, so call it off the main thread.+ */+fun exportNoteMarkdown(context: Context, note: Note): String =+    note.body().blocks+        .map { block ->+            when (block) {+                is NoteBlock.Text -> block.markdown+                is NoteBlock.Image -> imageMarkdown(context, block)+                is NoteBlock.Ink -> inkSvg(block)+            }+        }+        .filter { it.isNotBlank() }+        .joinToString("\n\n")+        .trim() + "\n"++/**+ * Writes [markdown] to `cacheDir/shared_notes/<title>.md` and returns a shareable+ * FileProvider URI for it. Reuses the same cache dir + authority as+ * [NotesViewModel.requestShare], so no extra manifest setup is needed. Used by copy+ * so a note with inlined (multi-MB) images is passed as a URI instead of raw text.+ */+fun markdownCacheUri(context: Context, note: Note, markdown: String): Uri {+    val cachePath = File(context.cacheDir, "shared_notes")+    cachePath.mkdirs()+    val file = File(cachePath, "${note.title.ifBlank { "note" }}.md")+    file.writeText(markdown)+    return FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)+}++/** Longest-side pixel cap and JPEG quality used when inlining images, to keep the export small. */+private const val MAX_IMAGE_DIMENSION = 1024+private const val JPEG_QUALITY = 60++/** An image inlined as an HTML `<img>` with a base64 data URI, honoring [NoteBlock.Image.widthFraction]. */+private fun imageMarkdown(context: Context, block: NoteBlock.Image): String {+    val bytes = try {+        downscaledJpegBytes(NoteImageStore.fileFor(context, block.fileName))+    } catch (e: Exception) {+        return ""+    } ?: return ""+    val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)+    val widthPercent = (block.widthFraction * 100).roundToInt().coerceIn(1, 100)+    return "<img src=\"data:image/jpeg;base64,$base64\" style=\"width:$widthPercent%\" />"+}++/**+ * Decodes [file], downscales so the longest side is at most [MAX_IMAGE_DIMENSION]+ * (never upscales), and re-encodes as JPEG at [JPEG_QUALITY] so the inlined base64+ * stays small. Uses inSampleSize so large files aren't fully loaded into memory, and+ * recycles bitmaps. Returns null if the file can't be decoded.+ */+private fun downscaledJpegBytes(file: File): ByteArray? {+    val path = file.absolutePath++    // First pass: read only the dimensions (inJustDecodeBounds loads no pixels).+    val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+    BitmapFactory.decodeFile(path, bounds)+    if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null++    // Second pass: decode at a reduced sample size to save memory on big images.+    val longest = maxOf(bounds.outWidth, bounds.outHeight)+    val options = BitmapFactory.Options().apply {+        inSampleSize = sampleSizeFor(longest, MAX_IMAGE_DIMENSION)+    }+    val decoded = BitmapFactory.decodeFile(path, options) ?: return null++    // Scale exactly to the cap if the sampled bitmap is still too large.+    val scaled = scaleToMax(decoded, MAX_IMAGE_DIMENSION)+    return ByteArrayOutputStream().use { out ->+        scaled.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, out)+        if (scaled != decoded) scaled.recycle()+        decoded.recycle()+        out.toByteArray()+    }+}++/** Largest power-of-two sample size that keeps the decoded longest side at least [target]. */+private fun sampleSizeFor(longest: Int, target: Int): Int {+    var sample = 1+    while (longest / (sample * 2) >= target) sample *= 2+    return sample+}++/** [bitmap] scaled so its longest side is [max], or the original if it's already small enough. */+private fun scaleToMax(bitmap: Bitmap, max: Int): Bitmap {+    val longest = maxOf(bitmap.width, bitmap.height)+    if (longest <= max) return bitmap+    val ratio = max.toFloat() / longest+    val width = (bitmap.width * ratio).roundToInt().coerceAtLeast(1)+    val height = (bitmap.height * ratio).roundToInt().coerceAtLeast(1)+    return bitmap.scale(width, height)+}++/** A drawing as an inline `<svg>`, one `<path>` per stroke, using the raw point coordinates. */+private fun inkSvg(block: NoteBlock.Ink): String {+    // Points are in the drawing canvas' pixel space. Size the SVG to bound them+    // (so it stays self-contained and keeps the right proportions); fall back to+    // the canvas height for an empty drawing.+    var width = 0f+    var height = 0f+    block.strokes.forEach { stroke ->+        stroke.points.forEach { p ->+            if (p.x > width) width = p.x+            if (p.y > height) height = p.y+        }+    }+    width = width.coerceAtLeast(1f)+    height = height.coerceAtLeast(block.heightDp.toFloat())++    val paths = block.strokes.mapNotNull { strokePath(it) }.joinToString("\n")+    return "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${num(width)}\" height=\"${num(height)}\" " ++        "viewBox=\"0 0 ${num(width)} ${num(height)}\">\n$paths\n</svg>"+}++/** Builds an SVG `<path>` ("M x y L x y ...") for one stroke, or null if it has no points. */+private fun strokePath(stroke: SerializedStroke): String? {+    if (stroke.points.isEmpty()) return null+    val d = stroke.points.mapIndexed { i, p ->+        "${if (i == 0) "M" else "L"} ${num(p.x)} ${num(p.y)}"+    }.joinToString(" ")+    return "<path d=\"$d\" fill=\"none\" stroke=\"${cssColor(stroke.brushColor)}\" " ++        "stroke-width=\"${num(stroke.brushSize)}\" stroke-linecap=\"round\" stroke-linejoin=\"round\" />"+}++/** An ARGB color int as a CSS `rgba(...)`, preserving alpha (e.g. highlighter transparency). */+private fun cssColor(argb: Int): String {+    val a = (argb ushr 24) and 0xFF+    val r = (argb ushr 16) and 0xFF+    val g = (argb ushr 8) and 0xFF+    val b = argb and 0xFF+    return "rgba($r,$g,$b,${num(a / 255f)})"+}++/** Formats a float compactly (drops the ".0" for whole numbers) to keep the output small. */+private fun num(value: Float): String {+    val rounded = (value * 100).roundToInt() / 100f+    return if (rounded % 1f == 0f) rounded.toInt().toString() else rounded.toString()+}
notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/util/NotesUiContract.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.ktsimilarity index 95%rename from notes/src/main/java/com/vayunmathur/notes/util/NotesUiContract.ktrename to notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.ktindex ce59bd4aa3..4ff42ac841 100644--- a/notes/src/main/java/com/vayunmathur/notes/util/NotesUiContract.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NotesUiContract.kt@@ -1,71 +1,71 @@-package com.vayunmathur.notes.util--import com.vayunmathur.notes.data.Note-import com.vayunmathur.notes.data.NoteBlock--/**- * The UI contract between [NotesViewModel] plus the nav back stack and the screens.- *- * 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.- */--/** Everything the notes list draws. */-data class NotesListUiState(-    val notes: List<Note> = emptyList(),-    /** Hidden while a note is already open beside the list in the list-detail layout. */-    val showAddButton: Boolean = true,-)--/**- * Notes list callbacks. Every method has a no-op default so a preview can render the screen- * without supplying behaviour — [Noop] is the whole implementation a preview needs.- */-interface NotesListActions {-    fun openNote(id: Long) {}-    fun createNote() {}-    fun delete(note: Note) {}--    /** Persists a reordered list; each note already carries its new position. */-    fun upsertAll(notes: List<Note>) {}--    companion object {-        val Noop: NotesListActions = object : NotesListActions {}-    }-}--/** Everything the note editor draws: the title plus the ordered body blocks. */-data class NoteUiState(-    val title: String = "",-    val blocks: List<NoteBlock> = emptyList(),-)--/** Note editor callbacks. Same no-op-default arrangement as [NotesListActions]. */-interface NoteActions {-    fun back() {}-    fun setTitle(title: String) {}--    /** The text block [id] was edited to [markdown]. */-    fun setBlockMarkdown(id: String, markdown: String) {}--    /** Insert media just below [afterBlockId] (the focused text block), or at the end. */-    fun addImage(afterBlockId: String?) {}-    fun addDrawing(afterBlockId: String?) {}--    fun editDrawing(block: NoteBlock.Ink) {}-    fun resizeImage(id: String, widthFraction: Float) {}--    /** Moves a block [delta] places: -1 up, +1 down. */-    fun moveBlock(id: String, delta: Int) {}-    fun deleteBlock(id: String) {}--    fun copyNote() {}-    fun shareNote() {}-    fun deleteNote() {}--    companion object {-        val Noop: NoteActions = object : NoteActions {}-    }-}+package com.vayunmathur.notes.platform++import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.NoteBlock++/**+ * The UI contract between [NotesViewModel] plus the nav back stack and the screens.+ *+ * 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.+ */++/** Everything the notes list draws. */+data class NotesListUiState(+    val notes: List<Note> = emptyList(),+    /** Hidden while a note is already open beside the list in the list-detail layout. */+    val showAddButton: Boolean = true,+)++/**+ * Notes list callbacks. Every method has a no-op default so a preview can render the screen+ * without supplying behaviour — [Noop] is the whole implementation a preview needs.+ */+interface NotesListActions {+    fun openNote(id: Long) {}+    fun createNote() {}+    fun delete(note: Note) {}++    /** Persists a reordered list; each note already carries its new position. */+    fun upsertAll(notes: List<Note>) {}++    companion object {+        val Noop: NotesListActions = object : NotesListActions {}+    }+}++/** Everything the note editor draws: the title plus the ordered body blocks. */+data class NoteUiState(+    val title: String = "",+    val blocks: List<NoteBlock> = emptyList(),+)++/** Note editor callbacks. Same no-op-default arrangement as [NotesListActions]. */+interface NoteActions {+    fun back() {}+    fun setTitle(title: String) {}++    /** The text block [id] was edited to [markdown]. */+    fun setBlockMarkdown(id: String, markdown: String) {}++    /** Insert media just below [afterBlockId] (the focused text block), or at the end. */+    fun addImage(afterBlockId: String?) {}+    fun addDrawing(afterBlockId: String?) {}++    fun editDrawing(block: NoteBlock.Ink) {}+    fun resizeImage(id: String, widthFraction: Float) {}++    /** Moves a block [delta] places: -1 up, +1 down. */+    fun moveBlock(id: String, delta: Int) {}+    fun deleteBlock(id: String) {}++    fun copyNote() {}+    fun shareNote() {}+    fun deleteNote() {}++    companion object {+        val Noop: NoteActions = object : NoteActions {}+    }+}
notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/util/NotesViewModel.kt b/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.ktsimilarity index 96%rename from notes/src/main/java/com/vayunmathur/notes/util/NotesViewModel.ktrename to notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.ktindex 19a69e3437..e5ddaab599 100644--- a/notes/src/main/java/com/vayunmathur/notes/util/NotesViewModel.kt+++ b/notes/src/main/java/com/vayunmathur/notes/platform/NotesViewModel.kt@@ -1,246 +1,246 @@-package com.vayunmathur.notes.util--import android.app.Application-import android.net.Uri-import android.util.Log-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.MutableState-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableLongStateOf-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.text.AnnotatedString-import androidx.core.content.FileProvider-import androidx.core.net.toUri-import androidx.lifecycle.AndroidViewModel-import androidx.lifecycle.ViewModel-import androidx.lifecycle.ViewModelProvider-import androidx.lifecycle.viewModelScope-import com.vayunmathur.library.util.IntentHelper-import com.vayunmathur.library.util.parseMarkdown-import com.vayunmathur.notes.data.Note-import com.vayunmathur.notes.data.NotesRepository-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.FlowPreview-import kotlinx.coroutines.flow.MutableSharedFlow-import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.SharedFlow-import kotlinx.coroutines.flow.SharingStarted-import kotlinx.coroutines.flow.StateFlow-import kotlinx.coroutines.flow.asSharedFlow-import kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.flow.collectLatest-import kotlinx.coroutines.flow.debounce-import kotlinx.coroutines.flow.filterNotNull-import kotlinx.coroutines.flow.stateIn-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext-import java.io.File--class NotesViewModel(-    application: Application,-    private val repository: NotesRepository,-) : AndroidViewModel(application) {--    val notes: StateFlow<List<Note>> = repository.notes-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())--    fun delete(note: Note) {-        viewModelScope.launch(Dispatchers.IO) { repository.delete(note) }-    }--    fun upsertAll(notes: List<Note>) {-        viewModelScope.launch(Dispatchers.IO) { repository.upsertAll(notes) }-    }--    @OptIn(FlowPreview::class)-    @Composable-    fun editableNote(initialId: Long, default: () -> Note): MutableState<Note> {-        var currentId by remember { mutableLongStateOf(initialId) }--        val noteFlow = remember(currentId) { repository.noteByIdFlow(currentId) }-        val dbNote by noteFlow.collectAsStateWithLifecycle(initialValue = null)--        val localState = remember { mutableStateOf<Note?>(null) }--        LaunchedEffect(dbNote, currentId) {-            dbNote?.let { localState.value = it }-        }--        val pendingWrites = remember { MutableStateFlow<Note?>(null) }-        LaunchedEffect(Unit) {-            pendingWrites.filterNotNull().debounce(300).collectLatest { newValue ->-                val newId = withContext(Dispatchers.IO) { repository.upsert(newValue) }-                if (currentId == 0L) currentId = newId-            }-        }--        return remember {-            object : MutableState<Note> {-                override var value: Note-                    get() = localState.value ?: default()-                    set(newValue) {-                        localState.value = newValue-                        pendingWrites.value = newValue-                    }--                override fun component1(): Note = value-                override fun component2(): (Note) -> Unit = { value = it }-            }-        }-    }--    private data class ParsedKey(-        val content: String,-        val searchQuery: String,-        val searchIndex: Int,-    )--    private val parsedCache = object : LinkedHashMap<ParsedKey, AnnotatedString>(32, 0.75f, true) {-        override fun removeEldestEntry(-            eldest: MutableMap.MutableEntry<ParsedKey, AnnotatedString>,-        ): Boolean = size > 32-    }--    @Synchronized-    fun parseDisplay(-        content: String,-        searchQuery: String = "",-        searchIndex: Int = -1,-    ): AnnotatedString {-        val key = ParsedKey(content, searchQuery, searchIndex)-        parsedCache[key]?.let { return it }-        val parsed = parseMarkdown(-            content,-            showMarkers = false,-            process = false,-            softWrap = false,-            searchQuery = searchQuery,-            searchIndex = searchIndex,-        )-        parsedCache[key] = parsed-        return parsed-    }--    fun searchResultsCount(content: String, searchText: String): Int {-        if (searchText.isEmpty()) return 0-        val text = parseDisplay(content).text-        return Regex(Regex.escape(searchText), RegexOption.IGNORE_CASE).findAll(text).count()-    }--    data class NoteShare(val uri: Uri, val markdown: String)--    private val _shareRequests = MutableSharedFlow<NoteShare>(extraBufferCapacity = 1)-    val shareRequests: SharedFlow<NoteShare> = _shareRequests.asSharedFlow()--    fun importFiles(uris: List<Uri>) {-        if (uris.isEmpty()) return-        val ctx = getApplication<Application>()-        viewModelScope.launch(Dispatchers.IO) {-            uris.forEach { uri ->-                try {-                    val content = ctx.contentResolver.openInputStream(uri)-                        ?.bufferedReader()?.use { it.readText() }-                    if (content != null) {-                        val name = IntentHelper.getFileName(ctx, uri) ?: "Imported Note"-                        repository.upsert(Note(0, name, content))-                    }-                } catch (e: Exception) {-                    Log.e(TAG, "Error importing file: $uri", e)-                }-            }-        }-    }--    fun requestShare(note: Note) {-        val ctx = getApplication<Application>()-        viewModelScope.launch {-            val share = withContext(Dispatchers.IO) {-                val markdown = exportNoteMarkdown(ctx, note)-                val cachePath = File(ctx.cacheDir, "shared_notes")-                cachePath.mkdirs()-                val file = File(cachePath, "${note.title.ifBlank { "note" }}.md")-                file.writeText(markdown)-                val uri = FileProvider.getUriForFile(-                    ctx,-                    "${ctx.packageName}.fileprovider",-                    file,-                )-                NoteShare(uri, markdown)-            }-            _shareRequests.emit(share)-        }-    }--    private val _externalOpens = MutableStateFlow<List<String>>(emptyList())-    val externalOpens: StateFlow<List<String>> = _externalOpens.asStateFlow()--    fun openExternal(uris: List<Uri>) {-        if (uris.isEmpty()) return-        _externalOpens.value = _externalOpens.value + uris.map { it.toString() }-    }--    fun consumeExternal(uri: String) {-        _externalOpens.value = _externalOpens.value.filterNot { it == uri }-    }--    data class ExternalNoteContent(val title: String, val content: String)--    suspend fun readExternal(uriString: String): ExternalNoteContent? = withContext(Dispatchers.IO) {-        val ctx = getApplication<Application>()-        try {-            val uri = uriString.toUri()-            val content = ctx.contentResolver.openInputStream(uri)-                ?.bufferedReader()?.use { it.readText() } ?: return@withContext null-            val name = IntentHelper.getFileName(ctx, uri) ?: "Untitled"-            ExternalNoteContent(name.removeSuffix(".markdown").removeSuffix(".md"), content)-        } catch (e: Exception) {-            Log.e(TAG, "Error reading external note: $uriString", e)-            null-        }-    }--    fun saveExternal(uriString: String, content: String, onResult: (Boolean) -> Unit) {-        val ctx = getApplication<Application>()-        viewModelScope.launch {-            val ok = withContext(Dispatchers.IO) {-                try {-                    ctx.contentResolver.openOutputStream(uriString.toUri(), "wt")?.use {-                        it.write(content.toByteArray())-                    } ?: return@withContext false-                    true-                } catch (e: Exception) {-                    Log.e(TAG, "Error saving external note: $uriString", e)-                    false-                }-            }-            onResult(ok)-        }-    }--    fun addExternalToApp(title: String, content: String, onAdded: (Long) -> Unit) {-        viewModelScope.launch {-            val id = withContext(Dispatchers.IO) { repository.upsert(Note(0, title, content)) }-            onAdded(id)-        }-    }--    companion object {-        private const val TAG = "NotesViewModel"-    }-}--/** Factory for constructing [NotesViewModel] with the repository. */-class NotesViewModelFactory(-    private val application: Application,-    private val repository: NotesRepository,-) : ViewModelProvider.Factory {-    @Suppress("UNCHECKED_CAST")-    override fun <T : ViewModel> create(modelClass: Class<T>): T {-        require(modelClass.isAssignableFrom(NotesViewModel::class.java)) { "Unexpected ViewModel class: $modelClass" }-        return NotesViewModel(application, repository) as T-    }-}+package com.vayunmathur.notes.platform++import android.app.Application+import android.net.Uri+import android.util.Log+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.MutableState+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.text.AnnotatedString+import androidx.core.content.FileProvider+import androidx.core.net.toUri+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.ViewModel+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.util.IntentHelper+import com.vayunmathur.library.util.parseMarkdown+import com.vayunmathur.notes.data.Note+import com.vayunmathur.notes.data.NotesRepository+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.FlowPreview+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asSharedFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.flow.debounce+import kotlinx.coroutines.flow.filterNotNull+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File++class NotesViewModel(+    application: Application,+    private val repository: NotesRepository,+) : AndroidViewModel(application) {++    val notes: StateFlow<List<Note>> = repository.notes+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    fun delete(note: Note) {+        viewModelScope.launch(Dispatchers.IO) { repository.delete(note) }+    }++    fun upsertAll(notes: List<Note>) {+        viewModelScope.launch(Dispatchers.IO) { repository.upsertAll(notes) }+    }++    @OptIn(FlowPreview::class)+    @Composable+    fun editableNote(initialId: Long, default: () -> Note): MutableState<Note> {+        var currentId by remember { mutableLongStateOf(initialId) }++        val noteFlow = remember(currentId) { repository.noteByIdFlow(currentId) }+        val dbNote by noteFlow.collectAsStateWithLifecycle(initialValue = null)++        val localState = remember { mutableStateOf<Note?>(null) }++        LaunchedEffect(dbNote, currentId) {+            dbNote?.let { localState.value = it }+        }++        val pendingWrites = remember { MutableStateFlow<Note?>(null) }+        LaunchedEffect(Unit) {+            pendingWrites.filterNotNull().debounce(300).collectLatest { newValue ->+                val newId = withContext(Dispatchers.IO) { repository.upsert(newValue) }+                if (currentId == 0L) currentId = newId+            }+        }++        return remember {+            object : MutableState<Note> {+                override var value: Note+                    get() = localState.value ?: default()+                    set(newValue) {+                        localState.value = newValue+                        pendingWrites.value = newValue+                    }++                override fun component1(): Note = value+                override fun component2(): (Note) -> Unit = { value = it }+            }+        }+    }++    private data class ParsedKey(+        val content: String,+        val searchQuery: String,+        val searchIndex: Int,+    )++    private val parsedCache = object : LinkedHashMap<ParsedKey, AnnotatedString>(32, 0.75f, true) {+        override fun removeEldestEntry(+            eldest: MutableMap.MutableEntry<ParsedKey, AnnotatedString>,+        ): Boolean = size > 32+    }++    @Synchronized+    fun parseDisplay(+        content: String,+        searchQuery: String = "",+        searchIndex: Int = -1,+    ): AnnotatedString {+        val key = ParsedKey(content, searchQuery, searchIndex)+        parsedCache[key]?.let { return it }+        val parsed = parseMarkdown(+            content,+            showMarkers = false,+            process = false,+            softWrap = false,+            searchQuery = searchQuery,+            searchIndex = searchIndex,+        )+        parsedCache[key] = parsed+        return parsed+    }++    fun searchResultsCount(content: String, searchText: String): Int {+        if (searchText.isEmpty()) return 0+        val text = parseDisplay(content).text+        return Regex(Regex.escape(searchText), RegexOption.IGNORE_CASE).findAll(text).count()+    }++    data class NoteShare(val uri: Uri, val markdown: String)++    private val _shareRequests = MutableSharedFlow<NoteShare>(extraBufferCapacity = 1)+    val shareRequests: SharedFlow<NoteShare> = _shareRequests.asSharedFlow()++    fun importFiles(uris: List<Uri>) {+        if (uris.isEmpty()) return+        val ctx = getApplication<Application>()+        viewModelScope.launch(Dispatchers.IO) {+            uris.forEach { uri ->+                try {+                    val content = ctx.contentResolver.openInputStream(uri)+                        ?.bufferedReader()?.use { it.readText() }+                    if (content != null) {+                        val name = IntentHelper.getFileName(ctx, uri) ?: "Imported Note"+                        repository.upsert(Note(0, name, content))+                    }+                } catch (e: Exception) {+                    Log.e(TAG, "Error importing file: $uri", e)+                }+            }+        }+    }++    fun requestShare(note: Note) {+        val ctx = getApplication<Application>()+        viewModelScope.launch {+            val share = withContext(Dispatchers.IO) {+                val markdown = exportNoteMarkdown(ctx, note)+                val cachePath = File(ctx.cacheDir, "shared_notes")+                cachePath.mkdirs()+                val file = File(cachePath, "${note.title.ifBlank { "note" }}.md")+                file.writeText(markdown)+                val uri = FileProvider.getUriForFile(+                    ctx,+                    "${ctx.packageName}.fileprovider",+                    file,+                )+                NoteShare(uri, markdown)+            }+            _shareRequests.emit(share)+        }+    }++    private val _externalOpens = MutableStateFlow<List<String>>(emptyList())+    val externalOpens: StateFlow<List<String>> = _externalOpens.asStateFlow()++    fun openExternal(uris: List<Uri>) {+        if (uris.isEmpty()) return+        _externalOpens.value = _externalOpens.value + uris.map { it.toString() }+    }++    fun consumeExternal(uri: String) {+        _externalOpens.value = _externalOpens.value.filterNot { it == uri }+    }++    data class ExternalNoteContent(val title: String, val content: String)++    suspend fun readExternal(uriString: String): ExternalNoteContent? = withContext(Dispatchers.IO) {+        val ctx = getApplication<Application>()+        try {+            val uri = uriString.toUri()+            val content = ctx.contentResolver.openInputStream(uri)+                ?.bufferedReader()?.use { it.readText() } ?: return@withContext null+            val name = IntentHelper.getFileName(ctx, uri) ?: "Untitled"+            ExternalNoteContent(name.removeSuffix(".markdown").removeSuffix(".md"), content)+        } catch (e: Exception) {+            Log.e(TAG, "Error reading external note: $uriString", e)+            null+        }+    }++    fun saveExternal(uriString: String, content: String, onResult: (Boolean) -> Unit) {+        val ctx = getApplication<Application>()+        viewModelScope.launch {+            val ok = withContext(Dispatchers.IO) {+                try {+                    ctx.contentResolver.openOutputStream(uriString.toUri(), "wt")?.use {+                        it.write(content.toByteArray())+                    } ?: return@withContext false+                    true+                } catch (e: Exception) {+                    Log.e(TAG, "Error saving external note: $uriString", e)+                    false+                }+            }+            onResult(ok)+        }+    }++    fun addExternalToApp(title: String, content: String, onAdded: (Long) -> Unit) {+        viewModelScope.launch {+            val id = withContext(Dispatchers.IO) { repository.upsert(Note(0, title, content)) }+            onAdded(id)+        }+    }++    companion object {+        private const val TAG = "NotesViewModel"+    }+}++/** Factory for constructing [NotesViewModel] with the repository. */+class NotesViewModelFactory(+    private val application: Application,+    private val repository: NotesRepository,+) : ViewModelProvider.Factory {+    @Suppress("UNCHECKED_CAST")+    override fun <T : ViewModel> create(modelClass: Class<T>): T {+        require(modelClass.isAssignableFrom(NotesViewModel::class.java)) { "Unexpected ViewModel class: $modelClass" }+        return NotesViewModel(application, repository) as T+    }+}