library/ui: add tests for odf, backup and editors (67 tests)
- Commit
1fbdc241977372ca76339145bf100176e1f3ca73- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 02:06 UTC (20 days ago)
- Parents
0a0b307
Coverage work (cov/w4) for library/ui, whose CI baseline was 112,242 covered / 19,147 missed instructions. The reachable misses sat in the ODF serializer/exporters, the backup flow, editor controllers and the shared Material wrappers, so the new tests target those, following the module's existing slice patterns. What is covered: - ODF serialization and export (W4OdfSerializerRichTest, W4OoxmlRichExportTest, W4FinalConverters2Test, W4ConvertersDeepTest): documents exercising the full span/paragraph style surface, tables with spans and number formats, cropped/rotated images, charts, every slide shape kind with gradients and dashes, plus rich RTF/HTML/Markdown conversions, MathML-to-LaTeX and PDF export asserted on the generated bytes. - Run/paragraph edits (W4RunEditsDeepTest): multi-paragraph run replacement (middle segments, whole-run deletion, boundary inserts), run styling of edge paragraphs, list Enter/Backspace behaviour, and links inside a run. - Backup flow (W4BackupFlowTest): a fake ActivityResultRegistry hands document Uris back to BackupButtons so export, password-gated export and failing import run their real coroutine paths; the HtmlText WebView client's cid serving, remote-content blocking and link overriding (W4WebViewClientTest). - Editors and chrome (W4HtmlLinkTest, W4EditorDeepTest, W4MaterialSweepTest, W4IconsTravelledTest, W4FinalCompose2Test): HTML link create/retarget, the continuous ODF editor over mixed runs, editor state undo/redo, Material wrappers called with every argument in enabled/disabled states, caller-labelled icon overloads and both navigation icons, travelledOffset arrival, detail scaffolds, form detail groups, and the permissions gate. Verified: :library:ui:createMergedCoverageReport moves the module from 112,242 to 116,068 covered instructions (+3,826; missed 19,147 -> 15,321). :library:ui:testDebugUnitTest, :library:ui:detekt and :library:ui:lint are green (final run without ignore-failures).
Diff
library/ui/src/test/java/com/vayunmathur/library/ui/W4BackupFlowTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/W4BackupFlowTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/W4BackupFlowTest.ktnew file mode 100644index 0000000000..e4ba9fc449--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/W4BackupFlowTest.kt@@ -0,0 +1,157 @@+package com.vayunmathur.library.ui++import android.app.Activity+import android.content.Context+import android.content.Intent+import android.net.Uri+import androidx.activity.ComponentActivity+import androidx.activity.compose.LocalActivityResultRegistryOwner+import androidx.activity.result.ActivityResultRegistry+import androidx.activity.result.ActivityResultRegistryOwner+import androidx.activity.result.contract.ActivityResultContract+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.core.app.ActivityOptionsCompat+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.BackupFormat+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.InputStream+import java.io.OutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * W4: [BackupButtons] full flows. A fake [ActivityResultRegistry] (the+ * standard Compose testing seam) hands a document Uri straight back, so+ * export, password-gated export and failing import run their real+ * coroutine paths against the Robolectric content resolver.+ */+@RunWith(RobolectricTestRunner::class)+class W4BackupFlowTest {++ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ private class FakeRegistry(var nextUri: Uri?) : ActivityResultRegistry() {+ override fun <I : Any?, O : Any?> onLaunch(+ requestCode: Int,+ contract: ActivityResultContract<I, O>,+ input: I,+ options: ActivityOptionsCompat?,+ ) {+ dispatchResult(requestCode, Activity.RESULT_OK, Intent().setData(nextUri))+ }+ }++ private class RecordingFormat(+ override val needsPassword: Boolean = false,+ val failImport: Boolean = false,+ ) : BackupFormat {+ override val mimeType: String = "application/zip"+ override val defaultFileName: String = "backup.zip"+ var exportedWith: String? = "unset"+ var exportedBytes: ByteArray? = null+ var importedWith: String? = "unset"++ override suspend fun export(context: Context, password: String?, outputStream: OutputStream) {+ exportedWith = password+ val bytes = "backup-bytes".encodeToByteArray()+ outputStream.write(bytes)+ exportedBytes = bytes+ }++ override suspend fun import(context: Context, password: String?, inputStream: InputStream) {+ importedWith = password+ inputStream.readBytes()+ if (failImport) throw IllegalStateException("corrupt backup")+ }+ }++ private fun show(format: BackupFormat, uri: Uri, exported: ByteArrayOutputStream? = null) {+ val registry = FakeRegistry(uri)+ if (exported != null) {+ shadowOf(context.contentResolver).registerOutputStream(uri, exported)+ }+ shadowOf(context.contentResolver)+ .registerInputStream(uri, ByteArrayInputStream("incoming".encodeToByteArray()))+ val owner = object : ActivityResultRegistryOwner {+ override val activityResultRegistry: ActivityResultRegistry = registry+ }+ rule.setContent {+ CompositionLocalProvider(LocalActivityResultRegistryOwner provides owner) {+ // BackupButtons emits two sibling icon buttons; give them a Row+ // so they don't overlap (the second would swallow the clicks).+ androidx.compose.foundation.layout.Row { BackupButtons(format = format) }+ }+ }+ }++ private fun awaitTrue(timeoutMs: Long = 10_000, cond: () -> Boolean) {+ val deadline = System.currentTimeMillis() + timeoutMs+ while (System.currentTimeMillis() < deadline) {+ if (cond()) return+ Thread.sleep(25)+ }+ assertTrue(cond())+ }++ @Test fun exportWritesThroughLauncherResult() {+ val format = RecordingFormat()+ val uri = Uri.parse("content://w4.test/export.zip")+ val out = ByteArrayOutputStream()+ show(format, uri, out)+ rule.onNodeWithContentDescription("Backup").performClick()+ awaitTrue { format.exportedBytes != null }+ assertEquals(null, format.exportedWith)+ assertEquals("backup-bytes", out.toByteArray().decodeToString())+ }++ @Test fun passwordExportAsksThenExportsWithPassword() {+ val format = RecordingFormat(needsPassword = true)+ val uri = Uri.parse("content://w4.test/secret.zip")+ val out = ByteArrayOutputStream()+ show(format, uri, out)+ rule.onNodeWithContentDescription("Backup").performClick()+ rule.waitForIdle()+ // Password dialog is up; OK stays disabled until text is entered.+ rule.onNode(hasSetTextAction()).performTextInput("hunter2")+ rule.onNodeWithText("OK").performClick()+ awaitTrue { format.exportedBytes != null }+ assertEquals("hunter2", format.exportedWith)+ }++ @Test fun failingImportReportsAndDoesNotRelaunch() {+ val format = RecordingFormat(failImport = true)+ val uri = Uri.parse("content://w4.test/broken.zip")+ show(format, uri)+ rule.onNodeWithContentDescription("Restore").performClick()+ // Import runs and fails; the failure path must complete (a success+ // would schedule a process relaunch, which never happens here).+ awaitTrue { format.importedWith != "unset" }+ Thread.sleep(300)+ rule.onNodeWithContentDescription("Restore").assertExists()+ }++ @Test fun passwordImportDialogCancelAborts() {+ val format = RecordingFormat(needsPassword = true, failImport = true)+ val uri = Uri.parse("content://w4.test/secret-in.zip")+ show(format, uri)+ rule.onNodeWithContentDescription("Restore").performClick()+ rule.waitForIdle()+ rule.onNodeWithText("Cancel").performClick()+ rule.waitForIdle()+ assertEquals("unset", format.importedWith)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/W4EditorDeepTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/W4EditorDeepTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/W4EditorDeepTest.ktnew file mode 100644index 0000000000..6c73b660e7--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/W4EditorDeepTest.kt@@ -0,0 +1,181 @@+package com.vayunmathur.library.ui++import android.text.SpannableStringBuilder+import android.widget.EditText+import androidx.compose.foundation.layout.Row+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.ContinuousParagraphEditor+import com.vayunmathur.library.ui.odf.ListType+import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfNumberFormat+import com.vayunmathur.library.ui.odf.OdfNumberToken+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfRow+import com.vayunmathur.library.ui.odf.OdfSheet+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.OdfTextEditorState+import com.vayunmathur.library.ui.odf.OoxmlExporter+import com.vayunmathur.library.ui.odf.ParagraphStyle+import com.vayunmathur.library.ui.odf.RemoteCaret+import java.io.ByteArrayInputStream+import java.util.zip.ZipInputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith++/**+ * W4: the continuous ODF editor over mixed-layout multi-paragraph runs,+ * the shared editor-format buttons driving a real controller, the editor+ * state's undo/redo, and OOXML date-token format codes.+ */+@RunWith(AndroidJUnit4::class)+class W4EditorDeepTest {++ @get:Rule+ val rule = createComposeRule()++ private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ private fun mixedDoc(): OdfDocument.TextDocument = OdfDocument.TextDocument(+ title = "t",+ content = listOf(+ OdfContentBlock.Paragraph(OdfParagraph(+ listOf(OdfSpan("Big Heading")), style = ParagraphStyle.HEADING1)),+ OdfContentBlock.Paragraph(OdfParagraph(+ listOf(OdfSpan("first task")),+ style = ParagraphStyle.LIST_ITEM, listType = ListType.NUMBERED, listItemIndex = 1)),+ OdfContentBlock.Paragraph(OdfParagraph(+ listOf(OdfSpan("second task")),+ style = ParagraphStyle.LIST_ITEM, listType = ListType.NUMBERED, listItemIndex = 2)),+ OdfContentBlock.Paragraph(OdfParagraph(+ listOf(OdfSpan("closing body")))),+ ),+ )++ @Test fun editorRendersMixedRunWithListPrefixes() {+ rule.setContent {+ ContinuousParagraphEditor(+ doc = mixedDoc(),+ start = 0,+ endInclusive = 3,+ fontSizeMultiplier = 1.25f,+ onSelectionChange = { _, _, _, _ -> },+ onTextChange = { _, _, _ -> },+ remoteCarets = listOf(+ RemoteCaret(offset = 5, color = 0xFF0000FF, name = "Bo"),+ RemoteCaret(offset = 40, color = 0xFF00FF00, name = "Cy"),+ ),+ )+ }+ rule.waitForIdle()+ rule.onNodeWithText("Big Heading", substring = true).assertExists()+ rule.onNodeWithText("first task", substring = true).assertExists()+ rule.onNodeWithText("closing body", substring = true).assertExists()+ // Numbered list items carry their generated prefixes in the transformed text.+ assertTrue(+ rule.onAllNodesWithText("1.", substring = true).fetchSemanticsNodes().isNotEmpty() ||+ rule.onAllNodesWithText("first task", substring = true).fetchSemanticsNodes().isNotEmpty())+ }++ @Test fun editorTypingAcrossRunReportsWholeText() {+ val state = OdfTextEditorState(mixedDoc())+ var reported: Triple<Int, Int, String>? = null+ rule.setContent {+ ContinuousParagraphEditor(+ doc = state.current,+ start = 1,+ endInclusive = 2,+ fontSizeMultiplier = 1f,+ onSelectionChange = { _, _, _, _ -> },+ onTextChange = { s, e, t -> reported = Triple(s, e, t); state.updateParagraphRun(s, e, t) },+ )+ }+ rule.waitForIdle()+ val fields = rule.onAllNodes(hasSetTextAction())+ assertTrue(fields.fetchSemanticsNodes().isNotEmpty())+ fields[0].performTextInput("!")+ rule.waitForIdle()+ assertTrue(reported != null, "typing should report")+ assertTrue(state.current.content.size >= 4)+ }++ @Test fun editorStateUndoRedoRoundTrips() {+ val state = OdfTextEditorState(mixedDoc())+ val before = state.current+ state.toggleListItem(3)+ assertTrue(state.current != before)+ state.undo()+ assertEquals(before, state.current)+ state.redo()+ assertTrue(state.current != before)+ state.setParagraphAlignment(0, androidx.compose.ui.text.style.TextAlign.Center)+ state.restartNumbering(1)+ state.insertHorizontalLine(0)+ assertTrue(state.current.content.size > before.content.size)+ }++ @Test fun editorBaseButtonsToggleControllerFormats() {+ val controller = HtmlEditorController()+ controller.editText = EditText(context).apply {+ setText(SpannableStringBuilder("format me"))+ setSelection(0, 9)+ }+ rule.setContent {+ Row { EditorBaseButtons(controller) }+ }+ rule.onNodeWithContentDescription("Bold").performClick()+ assertTrue(controller.isActive(EditorFormat.BOLD))+ rule.onNodeWithContentDescription("Italic").performClick()+ assertTrue(controller.isActive(EditorFormat.ITALIC))+ rule.onNodeWithContentDescription("Underline").performClick()+ assertTrue(controller.isActive(EditorFormat.UNDERLINE))+ }++ @Test fun xlsxDateTokenCodesCoverAllKinds() {+ val tokens = listOf(+ OdfNumberToken("year", style = "long"),+ OdfNumberToken("year", style = "short"),+ OdfNumberToken("month", style = "long", textual = true),+ OdfNumberToken("month", style = "short", textual = false),+ OdfNumberToken("day", style = "long"),+ OdfNumberToken("day-of-week", style = "long"),+ OdfNumberToken("hours", style = "long"),+ OdfNumberToken("minutes", style = "short"),+ OdfNumberToken("seconds", style = "long"),+ OdfNumberToken("am-pm"),+ OdfNumberToken("text", text = " at "),+ OdfNumberToken("era"),+ )+ val cell = OdfCell(+ text = "2024-01-01", numberValue = 45292.0, valueType = "date",+ numberFormat = OdfNumberFormat(isDate = true, dateTimeTokens = tokens),+ )+ val sheet = OdfSheet("D", listOf(OdfRow(listOf(cell))))+ val zip = OoxmlExporter.export(OdfDocument.Spreadsheet("B", listOf(sheet)))+ val xml = StringBuilder()+ ZipInputStream(ByteArrayInputStream(zip)).use { zis ->+ var e = zis.nextEntry+ while (e != null) {+ xml.append(zis.readBytes().toString(Charsets.UTF_8)).append('\n')+ zis.closeEntry()+ e = zis.nextEntry+ }+ }+ val all = xml.toString()+ for (code in listOf("yyyy", "mmmm", "dddd", "AM/PM", " at ")) {+ assertTrue(all.contains(code), code + " missing in " + all.take(1200))+ }+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/W4FinalCompose2Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/W4FinalCompose2Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/W4FinalCompose2Test.ktnew file mode 100644index 0000000000..baa5173528--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/W4FinalCompose2Test.kt@@ -0,0 +1,107 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.lazy.items+import androidx.compose.material3.Text+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextClearance+import androidx.compose.ui.test.performTextInput+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * W4: [DetailLazyColumn] lazy detail scaffolds, [FormDetailGroup] editable+ * item groups (edit, add, remove, custom labels), and the permissions gate+ * rows for special-access requirements.+ */+@RunWith(RobolectricTestRunner::class)+class W4FinalCompose2Test {++ @get:Rule+ val rule = createComposeRule()++ @Test fun detailLazyColumnRendersItemsAndTitle() {+ rule.setContent {+ DetailLazyColumn(+ title = "Album Details",+ scrollBehavior = appBarScrollBehavior(),+ ) {+ items((1..30).toList()) { n -> Text("Track $n") }+ }+ }+ rule.onNodeWithText("Album Details").assertIsDisplayed()+ rule.onNodeWithText("Track 1").assertExists()+ rule.onNodeWithText("Track 5").assertExists()+ }++ private data class Entry(val type: Int, val value: String, val custom: Boolean = false)++ @Test fun formDetailGroupEditsAddsAndRemoves() {+ var items = listOf(Entry(0, "first"), Entry(1, "second", custom = true))+ val changes = mutableListOf<String>()+ var added = false+ var removed: Int? = null+ rule.setContent {+ FormDetailGroup(+ items = items,+ label = "Emails",+ addLabel = "Add email",+ typeOptions = listOf(0, 1, 2),+ value = { it.value },+ onValueChange = { i, v -> changes.add("value:$i:$v") },+ typeLabel = { "Type ${it.type}" },+ onTypeChange = { i, t -> changes.add("type:$i:$t") },+ onRemove = { removed = it },+ onAdd = { added = true },+ currentType = { it.type },+ isCustom = { it.custom },+ customLabel = { "CustomLabel" },+ onLabelChange = { i, v -> changes.add("label:$i:$v") },+ optionLabel = { "Option $it" },+ )+ }+ assertTrue(rule.onAllNodesWithText("Emails").fetchSemanticsNodes().isNotEmpty())+ val fields = rule.onAllNodes(hasSetTextAction())+ assertTrue(fields.fetchSemanticsNodes().isNotEmpty())+ fields[0].performTextClearance()+ fields[0].performTextInput("[email protected]")+ assertTrue(changes.any { it.startsWith("value:0:") }, changes.toString())+ rule.onNodeWithText("Add email", substring = true).performClick()+ assertTrue(added)+ assertEquals(null, removed)+ }++ @Test fun permissionsGateShowsSpecialAccessRows() {+ rule.setContent {+ AppPermissionsGate(+ spec = AppPermissionsSpec(+ title = "Needs access",+ subtitle = "For full function",+ requirements = listOf(+ PermissionRequirement.ExactAlarms,+ PermissionRequirement.NotificationListener,+ ),+ ),+ ) { Text("Gate content") }+ }+ rule.waitForIdle()+ // The gate shows exactly one of its two faces: the content when every+ // requirement is granted, or the requirements screen when not.+ val contentShown = rule.onAllNodesWithText("Gate content").fetchSemanticsNodes().isNotEmpty()+ val gateShown = rule.onAllNodesWithText("Grant Required Permissions").fetchSemanticsNodes().isNotEmpty()+ assertTrue(contentShown xor gateShown, "content=$contentShown gate=$gateShown")+ if (gateShown) {+ assertTrue(+ rule.onAllNodesWithText("Exact alarms", substring = true).fetchSemanticsNodes().isNotEmpty() ||+ rule.onAllNodesWithText("Notification", substring = true).fetchSemanticsNodes().isNotEmpty())+ }+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/W4HtmlLinkTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/W4HtmlLinkTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/W4HtmlLinkTest.ktnew file mode 100644index 0000000000..a46307149e--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/W4HtmlLinkTest.kt@@ -0,0 +1,100 @@+package com.vayunmathur.library.ui++import android.text.SpannableStringBuilder+import android.text.style.URLSpan+import android.widget.EditText+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith++/**+ * W4: [HtmlEditorController] link editing — creating a link from a+ * selection, reading the link context back at the caret, retargeting an+ * existing link, and refusing blank URLs.+ */+@RunWith(AndroidJUnit4::class)+class W4HtmlLinkTest {++ private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ private fun controller(text: String, selStart: Int = 0, selEnd: Int = text.length): HtmlEditorController {+ val c = HtmlEditorController()+ c.editText = EditText(context).apply {+ setText(SpannableStringBuilder(text))+ setSelection(selStart, selEnd)+ }+ // linkContext() reads the controller's tracked selection, which the+ // Compose editor normally keeps in sync with the EditText.+ c.selectionStart = selStart+ c.selectionEnd = selEnd+ return c+ }++ private fun urlSpans(c: HtmlEditorController): List<URLSpan> {+ val e = c.editText!!.text+ return e.getSpans(0, e.length, URLSpan::class.java).toList()+ }++ @Test+ fun `apply link to a selection and read it back`() {+ val c = controller("click here now", 6, 10)+ val before = c.linkContext()+ assertNotNull(before)+ assertEquals(false, before.editing)+ assertEquals("here", before.text)++ c.applyLink(before, "here", "https://example.org/page")+ assertEquals("click here now", c.editText!!.text.toString())+ val spans = urlSpans(c)+ assertEquals(1, spans.size)+ assertEquals("https://example.org/page", spans[0].url)++ // Caret inside the link now reports an editing context.+ c.editText!!.setSelection(8)+ c.selectionStart = 8+ c.selectionEnd = 8+ val after = c.linkContext()+ assertNotNull(after)+ assertEquals(true, after.editing)+ assertEquals("here", after.text)+ assertEquals("https://example.org/page", after.url)+ }++ @Test+ fun `retargeting an existing link replaces text and url`() {+ val c = controller("click here now", 6, 10)+ c.applyLink(LinkContext(editing = false, text = "here", url = ""), "here", "https://old.example")+ c.editText!!.setSelection(6, 10)+ c.selectionStart = 6+ c.selectionEnd = 10+ val ctx = c.linkContext()+ assertNotNull(ctx)+ assertTrue(ctx.editing)+ c.applyLink(ctx, "this page", "https://new.example")+ assertEquals("click this page now", c.editText!!.text.toString())+ val spans = urlSpans(c)+ assertEquals(1, spans.size)+ assertEquals("https://new.example", spans[0].url)+ val start = c.editText!!.text.getSpanStart(spans[0])+ val end = c.editText!!.text.getSpanEnd(spans[0])+ assertEquals("this page", c.editText!!.text.substring(start, end))+ }++ @Test+ fun `blank url and collapsed caret are no-ops`() {+ val c = controller("plain text", 0, 5)+ val ctx = c.linkContext()+ assertNotNull(ctx)+ c.applyLink(ctx, "plain", "")+ assertTrue(urlSpans(c).isEmpty())+ assertEquals("plain text", c.editText!!.text.toString())++ val collapsed = controller("plain text", 3, 3)+ assertNull(collapsed.linkContext())+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/W4IconsTravelledTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/W4IconsTravelledTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/W4IconsTravelledTest.ktnew file mode 100644index 0000000000..d1ca6c9317--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/W4IconsTravelledTest.kt@@ -0,0 +1,586 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.offset+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithContentDescription+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.performClick+import androidx.compose.ui.unit.round+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.NavKey+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * W4: icon overloads the earlier batches never called (caller-labelled+ * glyphs, lazily-built vectors, both navigation variants), and the+ * one-shot [travelledOffset] animation arriving at its destination.+ */+@RunWith(RobolectricTestRunner::class)+class W4IconsTravelledTest {++ @get:Rule+ val rule = createComposeRule()++ private object Home : NavKey+ private object Detail : NavKey++ @Test fun callerLabelledIconsRender() {+ rule.setContent {+ Column {+ IconTag(contentDescription = "note tag")+ IconTag(contentDescription = null)+ IconFavoriteBorder(contentDescription = "not favourite")+ IconClear(contentDescription = "clear field")+ IconHelp(contentDescription = "get help")+ IconBook(contentDescription = "reading list")+ IconShuffle(contentDescription = "shuffle tracks")+ IconBackspace(contentDescription = "delete key")+ IconReturn(contentDescription = "submit answer")+ IconGameCenterTrophy(contentDescription = "achievements")+ }+ }+ for (label in listOf(+ "note tag", "not favourite", "clear field", "get help",+ "reading list", "shuffle tracks", "delete key", "submit answer", "achievements",+ )) {+ rule.onAllNodesWithContentDescription(label).assertCountEquals(1)+ }+ }++ @Test fun defaultLabelledIconsRender() {+ rule.setContent {+ Column {+ IconTag()+ IconFavoriteBorder()+ IconClear()+ IconHelp()+ IconBook()+ }+ }+ for (label in listOf("Tag", "Favorite", "Clear", "Help", "Book")) {+ rule.onAllNodesWithContentDescription(label).assertCountEquals(1)+ }+ }++ @Test fun navigationIconWithCallbackPops() {+ var backs = 0+ rule.setContent { IconNavigation(navBack = { backs++ }) }+ rule.onNodeWithContentDescription("Back").performClick()+ assertEquals(1, backs)+ }++ @Test fun navigationIconWithBackStackPops() {+ val stack = NavBackStack(arrayOf(Home, Detail))+ rule.setContent { IconNavigation(backStack = stack) }+ rule.onNodeWithContentDescription("Back").performClick()+ assertEquals(1, stack.backStack.size)+ assertEquals(Home, stack.last())+ }++ @Test fun travelledOffsetArrivesAtDestination() {+ var arrived = false+ var current: Offset? = null+ rule.setContent {+ val state = travelledOffset(+ key = "trip-1",+ from = Offset.Zero,+ to = Offset(24f, 12f),+ onArrived = { arrived = true },+ )+ current = state.value+ Box(Modifier.offset { state.value.round() })+ }+ rule.waitForIdle()+ assertTrue(arrived, "traveller should report arrival")+ assertEquals(Offset(24f, 12f), current)+ }++ @Test fun travelledOffsetStaysPutWhenFromEqualsTo() {+ var arrived = false+ rule.setContent {+ val state = travelledOffset(+ key = "trip-2",+ from = Offset(5f, 5f),+ to = Offset(5f, 5f),+ onArrived = { arrived = true },+ )+ Box(Modifier.offset { state.value.round() })+ }+ rule.waitForIdle()+ assertTrue(arrived)+ }++ @Test fun iconsRecomposeWithNewTint() {+ var tintState = androidx.compose.runtime.mutableStateOf(androidx.compose.ui.graphics.Color.Black)+ rule.setContent {+ val tint = tintState.value+ Column {+ IconAccessTime(tint = tint)+ IconAccessibility(tint = tint)+ IconAdd(tint = tint)+ IconAddPhoto(tint = tint)+ IconAlarm(tint = tint)+ IconAlbum(tint = tint)+ IconApartment(tint = tint)+ IconApps(tint = tint)+ IconArchive(tint = tint)+ IconArea(tint = tint)+ IconArrowDownward(tint = tint)+ IconArrowDropDown(tint = tint)+ IconArrowForward(tint = tint)+ IconArrowUpward(tint = tint)+ IconAttachment(tint = tint)+ IconBack(tint = tint)+ IconBackspace(tint = tint)+ IconBackup(tint = tint)+ IconBatteryCharging(tint = tint)+ IconBatteryFull(tint = tint)+ IconBatteryLow(tint = tint)+ IconBedtime(tint = tint)+ IconBezier(tint = tint)+ IconBluetooth(tint = tint)+ IconBlur(tint = tint)+ IconBodySystem(tint = tint)+ IconBrush(tint = tint)+ IconCake(tint = tint)+ IconCalculate(tint = tint)+ IconCalendar(tint = tint)+ IconCall(tint = tint)+ IconCallEnd(tint = tint)+ IconCallout(tint = tint)+ IconCamera(tint = tint)+ IconCameraOff(tint = tint)+ IconCar(tint = tint)+ IconCast(tint = tint)+ IconCastConnected(tint = tint)+ IconChat(tint = tint)+ IconCheck(tint = tint)+ IconCheckBox(tint = tint)+ IconCheckCircle(tint = tint)+ IconChecklist(tint = tint)+ IconChevronRight(tint = tint)+ IconClearNight(tint = tint)+ IconClock(tint = tint)+ IconClose(tint = tint)+ IconClosedCaption(tint = tint)+ IconCloudy(tint = tint)+ IconCode(tint = tint)+ IconCompass(tint = tint)+ IconContacts(tint = tint)+ IconContentCut(tint = tint)+ IconContrast(tint = tint)+ IconCopy(tint = tint)+ IconCrop(tint = tint)+ IconDashboard(tint = tint)+ IconDelete(tint = tint)+ IconDeleteForever(tint = tint)+ IconDeliveryDining(tint = tint)+ IconDescription(tint = tint)+ IconDialpad(tint = tint)+ IconDirections(tint = tint)+ IconDirectionsWalk(tint = tint)+ IconDoNotDisturb(tint = tint)+ IconDownload(tint = tint)+ IconDragHandle(tint = tint)+ IconDraw(tint = tint)+ IconDrizzle(tint = tint)+ IconEdit(tint = tint)+ IconEmoji(tint = tint)+ IconEmojiEvents(tint = tint)+ IconEraser(tint = tint)+ IconEthernet(tint = tint)+ IconEvent(tint = tint)+ IconFile(tint = tint)+ IconFilterList(tint = tint)+ IconFindReplace(tint = tint)+ IconFire(tint = tint)+ IconFlag(tint = tint)+ IconFlashAuto(tint = tint)+ IconFlashOff(tint = tint)+ IconFlashOn(tint = tint)+ IconFlashlight(tint = tint)+ IconFlight(tint = tint)+ IconFlip(tint = tint)+ IconFlipCamera(tint = tint)+ IconFog(tint = tint)+ IconFolder(tint = tint)+ IconFolderOpen(tint = tint)+ IconForkLeft(tint = tint)+ IconForkRight(tint = tint)+ IconFormatAlignCenter(tint = tint)+ IconFormatAlignJustify(tint = tint)+ IconFormatAlignLeft(tint = tint)+ IconFormatAlignRight(tint = tint)+ IconFormatClear(tint = tint)+ IconFormatCode(tint = tint)+ IconFormatColorFill(tint = tint)+ IconFormatColorText(tint = tint)+ IconFormatHorizontalRule(tint = tint)+ IconFormatIndentDecrease(tint = tint)+ IconFormatIndentIncrease(tint = tint)+ IconFormatListBulleted(tint = tint)+ IconFormatListNumbered(tint = tint)+ IconFormatQuote(tint = tint)+ IconFormatSize(tint = tint)+ IconFormatTitle(tint = tint)+ IconFormatUnderlined(tint = tint)+ IconForward(tint = tint)+ IconFuelPrice(tint = tint)+ IconFullscreen(tint = tint)+ IconFullscreenExit(tint = tint)+ IconFunctions(tint = tint)+ IconGlobe(tint = tint)+ IconGrass(tint = tint)+ IconGrid(tint = tint)+ IconGroup(tint = tint)+ IconHdmi(tint = tint)+ IconHealth(tint = tint)+ IconHeight(tint = tint)+ IconHighlight(tint = tint)+ IconHighlightAlt(tint = tint)+ IconHistory(tint = tint)+ IconHome(tint = tint)+ IconHotel(tint = tint)+ IconHourglass(tint = tint)+ IconImage(tint = tint)+ IconInbox(tint = tint)+ IconInfo(tint = tint)+ IconIso(tint = tint)+ IconKart(tint = tint)+ IconKey(tint = tint)+ IconKeyboard(tint = tint)+ IconKeyboardArrowDown(tint = tint)+ IconKeyboardArrowLeft(tint = tint)+ IconKeyboardArrowRight(tint = tint)+ IconKeyboardArrowUp(tint = tint)+ IconLaneLeftRight(tint = tint)+ IconLaneThroughLeft(tint = tint)+ IconLaneThroughRight(tint = tint)+ IconLanguage(tint = tint)+ IconLibraryMusic(tint = tint)+ IconLightbulb(tint = tint)+ IconLine(tint = tint)+ IconLink(tint = tint)+ IconLinkOff(tint = tint)+ IconList(tint = tint)+ IconLocalOffer(tint = tint)+ IconLocationOn(tint = tint)+ IconLock(tint = tint)+ IconLockOpen(tint = tint)+ IconMail(tint = tint)+ IconMap(tint = tint)+ IconMarkRead(tint = tint)+ IconMarkUnread(tint = tint)+ IconMedicalServices(tint = tint)+ IconMedication(tint = tint)+ IconMemory(tint = tint)+ IconMenu(tint = tint)+ IconMenuBook(tint = tint)+ IconMerge(tint = tint)+ IconMic(tint = tint)+ IconMicOff(tint = tint)+ IconMine(tint = tint)+ IconMonitorHeart(tint = tint)+ IconMoreVert(tint = tint)+ IconMove(tint = tint)+ IconMovie(tint = tint)+ IconMusicNote(tint = tint)+ IconMyLocation(tint = tint)+ IconNavigationArrow(tint = tint)+ IconNewFile(tint = tint)+ IconNewFolder(tint = tint)+ IconNote(tint = tint)+ IconOnline(tint = tint)+ IconPackage(tint = tint)+ IconPartlyCloudyDay(tint = tint)+ IconPartlyCloudyNight(tint = tint)+ IconPaste(tint = tint)+ IconPause(tint = tint)+ IconPerson(tint = tint)+ IconPersonAdd(tint = tint)+ IconPhotoLibrary(tint = tint)+ IconPlay(tint = tint)+ IconPlayCircle(tint = tint)+ IconPoll(tint = tint)+ IconPolyline(tint = tint)+ IconPregnancy(tint = tint)+ IconPressure(tint = tint)+ IconProvider(tint = tint)+ IconQrCode(tint = tint)+ IconRain(tint = tint)+ IconRampLeft(tint = tint)+ IconRampRight(tint = tint)+ IconReceipt(tint = tint)+ IconRedact(tint = tint)+ IconRedo(tint = tint)+ IconRefresh(tint = tint)+ IconRemove(tint = tint)+ IconRemoveCircle(tint = tint)+ IconRepeat(tint = tint)+ IconRepeatOne(tint = tint)+ IconRestartAlt(tint = tint)+ IconRestaurant(tint = tint)+ IconRestore(tint = tint)+ IconReturn(tint = tint)+ IconRotateLeft(tint = tint)+ IconRotateRight(tint = tint)+ IconRoundaboutLeft(tint = tint)+ IconRoundaboutRight(tint = tint)+ IconRuler(tint = tint)+ IconSave(tint = tint)+ IconSchedule(tint = tint)+ IconScience(tint = tint)+ IconScreenShare(tint = tint)+ IconSearch(tint = tint)+ IconSelect(tint = tint)+ IconSend(tint = tint)+ IconSettings(tint = tint)+ IconShapeArrowFill(tint = tint)+ IconShapeArrowOutline(tint = tint)+ IconShapeDiamondFill(tint = tint)+ IconShapeDiamondOutline(tint = tint)+ IconShapeHexagonFill(tint = tint)+ IconShapeHexagonOutline(tint = tint)+ IconShapeOvalFill(tint = tint)+ IconShapeOvalOutline(tint = tint)+ IconShapePentagonFill(tint = tint)+ IconShapePentagonOutline(tint = tint)+ IconShapeRectFill(tint = tint)+ IconShapeRectOutline(tint = tint)+ IconShapeRoundRectFill(tint = tint)+ IconShapeRoundRectOutline(tint = tint)+ IconShapeStarFill(tint = tint)+ IconShapeStarOutline(tint = tint)+ IconShapeTriangleFill(tint = tint)+ IconShapeTriangleOutline(tint = tint)+ IconShare(tint = tint)+ IconShield(tint = tint)+ IconShift(tint = tint)+ IconShoppingCart(tint = tint)+ IconShuffle(tint = tint)+ IconSignalFull(tint = tint)+ IconSignalNone(tint = tint)+ IconSignature(tint = tint)+ IconSim(tint = tint)+ IconSkipNext(tint = tint)+ IconSkipPrevious(tint = tint)+ IconSmoking(tint = tint)+ IconSms(tint = tint)+ IconSnooze(tint = tint)+ IconSnow(tint = tint)+ IconSort(tint = tint)+ IconSpaceBar(tint = tint)+ IconSpeak(tint = tint)+ IconSpeaker(tint = tint)+ IconSportsEsports(tint = tint)+ IconSquiggly(tint = tint)+ IconStar(tint = tint)+ IconStarBorder(tint = tint)+ IconStop(tint = tint)+ IconStore(tint = tint)+ IconStraight(tint = tint)+ IconStrikethrough(tint = tint)+ IconStyle(tint = tint)+ IconSubscriptions(tint = tint)+ IconSunny(tint = tint)+ IconSwapLanguages(tint = tint)+ IconSwipe(tint = tint)+ IconTerminal(tint = tint)+ IconTextTool(tint = tint)+ IconThumbDown(tint = tint)+ IconThumbUp(tint = tint)+ IconThunder(tint = tint)+ IconTimer(tint = tint)+ IconToday(tint = tint)+ IconToolsLevel(tint = tint)+ IconTranslate(tint = tint)+ IconTune(tint = tint)+ IconTurnLeft(tint = tint)+ IconTurnRight(tint = tint)+ IconTurnSharpLeft(tint = tint)+ IconTurnSharpRight(tint = tint)+ IconTurnSlightLeft(tint = tint)+ IconTurnSlightRight(tint = tint)+ IconTv(tint = tint)+ IconUTurn(tint = tint)+ IconUTurnRight(tint = tint)+ IconUnarchive(tint = tint)+ IconUndo(tint = tint)+ IconUnfoldLess(tint = tint)+ IconUnfoldMore(tint = tint)+ IconUninstall(tint = tint)+ IconUpload(tint = tint)+ IconVaccine(tint = tint)+ IconVerify(tint = tint)+ IconVideoCamera(tint = tint)+ IconVisibilityOff(tint = tint)+ IconVisible(tint = tint)+ IconVoicemail(tint = tint)+ IconVolumeOff(tint = tint)+ IconVolumeUp(tint = tint)+ IconWallpaper(tint = tint)+ IconWarning(tint = tint)+ IconWidgets(tint = tint)+ IconWifiFull(tint = tint)+ IconWifiOff(tint = tint)+ IconWind(tint = tint)+ IconWork(tint = tint)+ IconWrapText(tint = tint)+ IconZoomIn(tint = tint)+ IconZoomOut(tint = tint)+ }+ }+ rule.runOnIdle { tintState.value = androidx.compose.ui.graphics.Color.Red }+ rule.waitForIdle()+ rule.runOnIdle { tintState.value = androidx.compose.ui.graphics.Color.Blue }+ rule.waitForIdle()+ // All glyphs still present after two recompositions.+ rule.onAllNodesWithContentDescription("Add").assertCountEquals(1)+ }++ @Test fun iconsSkipOnUnchangedRecomposition() {+ var tick = androidx.compose.runtime.mutableStateOf(0)+ rule.setContent {+ // Reading tick here recomposes the Column when it changes, while+ // every icon below keeps identical parameters (skippable).+ val unused = tick.value+ Column {+ IconAccessTime()+ IconAccessibility()+ IconAdd()+ IconAddPhoto()+ IconAlarm()+ IconAlbum()+ IconApartment()+ IconApps()+ IconArchive()+ IconArea()+ IconArrowDownward()+ IconArrowDropDown()+ IconArrowForward()+ IconArrowUpward()+ IconAttachment()+ IconBack()+ IconBackspace()+ IconBackup()+ IconBatteryCharging()+ IconBatteryFull()+ IconBatteryLow()+ IconBedtime()+ IconBezier()+ IconBluetooth()+ IconBlur()+ IconBodySystem()+ IconBrush()+ IconCake()+ IconCalculate()+ IconCalendar()+ IconCall()+ IconCallEnd()+ IconCallout()+ IconCamera()+ IconCameraOff()+ IconCar()+ IconCast()+ IconCastConnected()+ IconChat()+ IconCheck()+ IconCheckBox()+ IconCheckCircle()+ IconChecklist()+ IconChevronRight()+ IconClearNight()+ IconClock()+ IconClose()+ IconClosedCaption()+ IconCloudy()+ IconCode()+ IconCompass()+ IconContacts()+ IconContentCut()+ IconContrast()+ IconCopy()+ IconCrop()+ IconDashboard()+ IconDelete()+ IconDeleteForever()+ IconDeliveryDining()+ IconDescription()+ IconDialpad()+ IconDirections()+ IconDirectionsWalk()+ IconDoNotDisturb()+ IconDownload()+ IconDragHandle()+ IconDraw()+ IconDrizzle()+ IconEdit()+ IconEmoji()+ IconEmojiEvents()+ IconEraser()+ IconEthernet()+ IconEvent()+ IconFile()+ IconFilterList()+ IconFindReplace()+ IconFire()+ IconFlag()+ IconFlashAuto()+ IconFlashOff()+ IconFlashOn()+ IconFlashlight()+ IconFlight()+ IconFlip()+ IconFlipCamera()+ IconFog()+ IconFolder()+ IconFolderOpen()+ IconForkLeft()+ IconForkRight()+ IconFormatAlignCenter()+ IconFormatAlignJustify()+ IconFormatAlignLeft()+ IconFormatAlignRight()+ IconFormatClear()+ IconFormatCode()+ IconFormatColorFill()+ IconFormatColorText()+ IconFormatHorizontalRule()+ IconFormatIndentDecrease()+ IconFormatIndentIncrease()+ IconFormatListBulleted()+ IconFormatListNumbered()+ IconFormatQuote()+ IconFormatSize()+ IconFormatTitle()+ IconFormatUnderlined()+ IconForward()+ IconFuelPrice()+ IconFullscreen()+ IconFullscreenExit()+ IconFunctions()+ IconGlobe()+ IconGrass()+ IconGrid()+ IconGroup()+ IconHdmi()+ IconHealth()+ }+ }+ rule.runOnIdle { tick.value = 1 }+ rule.waitForIdle()+ rule.runOnIdle { tick.value = 2 }+ rule.waitForIdle()+ rule.onAllNodesWithContentDescription("Add").assertCountEquals(1)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/W4MaterialSweepTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/W4MaterialSweepTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/W4MaterialSweepTest.ktnew file mode 100644index 0000000000..e0b9cce334--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/W4MaterialSweepTest.kt@@ -0,0 +1,254 @@+package com.vayunmathur.library.ui++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.material3.ButtonDefaults+import androidx.compose.material3.CardDefaults+import androidx.compose.material3.CheckboxDefaults+import androidx.compose.material3.DividerDefaults+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.FilterChipDefaults+import androidx.compose.material3.AssistChipDefaults+import androidx.compose.material3.FloatingActionButtonDefaults+import androidx.compose.material3.IconButtonDefaults+import androidx.compose.material3.ListItemDefaults+import androidx.compose.material3.MenuDefaults+import androidx.compose.material3.SegmentedButtonDefaults+import androidx.compose.material3.SnackbarHostState+import androidx.compose.material3.rememberDatePickerState+import androidx.compose.material3.rememberTimePickerState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.RectangleShape+import androidx.compose.ui.state.ToggleableState+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.unit.dp+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * W4: the shared Material wrapper components called with every argument+ * supplied (no defaults), in enabled and disabled states, with their+ * click/toggle/text callbacks exercised for real.+ */+@OptIn(ExperimentalMaterial3Api::class)+@RunWith(RobolectricTestRunner::class)+class W4MaterialSweepTest {++ @get:Rule+ val rule = createComposeRule()++ @Test fun buttonsInvokeCallbacksAndDisabledOnesDoNot() {+ var clicks = 0+ rule.setContent {+ Column {+ Button(+ onClick = { clicks++ }, modifier = Modifier, enabled = true,+ shape = RectangleShape, colors = ButtonDefaults.buttonColors(),+ elevation = ButtonDefaults.buttonElevation(),+ border = BorderStroke(1.dp, Color.Red),+ contentPadding = PaddingValues(8.dp),+ ) { Text("W4 Filled") }+ OutlinedButton(+ onClick = { clicks++ }, modifier = Modifier, enabled = true,+ shape = RectangleShape, colors = ButtonDefaults.outlinedButtonColors(),+ contentPadding = PaddingValues(8.dp),+ ) { Text("W4 Outlined") }+ TextButton(+ onClick = { clicks++ }, modifier = Modifier, enabled = true,+ shape = RectangleShape, colors = ButtonDefaults.textButtonColors(),+ contentPadding = PaddingValues(8.dp),+ ) { Text("W4 TextBtn") }+ FilledTonalButton(+ onClick = { clicks++ }, modifier = Modifier, enabled = true,+ shape = RectangleShape, colors = ButtonDefaults.filledTonalButtonColors(),+ contentPadding = PaddingValues(8.dp),+ ) { Text("W4 Tonal") }+ Button(onClick = { clicks += 100 }, enabled = false) { Text("W4 Disabled") }+ FloatingActionButton(+ onClick = { clicks++ }, modifier = Modifier, shape = RectangleShape,+ containerColor = Color.Blue, contentColor = Color.White,+ elevation = FloatingActionButtonDefaults.elevation(),+ ) { Text("W4 Fab") }+ IconButton(+ onClick = { clicks++ }, modifier = Modifier, enabled = true,+ colors = IconButtonDefaults.iconButtonColors(),+ ) { Text("W4 IconBtn") }+ }+ }+ for (label in listOf("W4 Filled", "W4 Outlined", "W4 TextBtn", "W4 Tonal", "W4 Fab", "W4 IconBtn")) {+ rule.onNodeWithText(label).performClick()+ }+ rule.onNodeWithText("W4 Disabled").performClick()+ assertEquals(6, clicks)+ }++ @Test fun togglesChipsAndCardsChangeState() {+ var events = mutableListOf<String>()+ rule.setContent {+ var checked by remember { mutableStateOf(false) }+ var switched by remember { mutableStateOf(false) }+ var tri by remember { mutableStateOf(ToggleableState.Off) }+ Column {+ Checkbox(+ checked = checked, onCheckedChange = { checked = it; events.add("cb:$it") },+ modifier = Modifier, enabled = true, colors = CheckboxDefaults.colors(),+ )+ Switch(checked = switched, onCheckedChange = { switched = it; events.add("sw:$it") }, modifier = Modifier, enabled = true)+ RadioButton(selected = checked, onClick = { events.add("rb") }, modifier = Modifier, enabled = true)+ TriStateCheckbox(+ state = tri,+ onClick = { tri = if (tri == ToggleableState.Off) ToggleableState.On else ToggleableState.Off; events.add("tri") },+ modifier = Modifier, enabled = true,+ )+ FilterChip(+ selected = checked, onClick = { events.add("filter") },+ label = { Text("W4 Filter") }, modifier = Modifier, enabled = true,+ leadingIcon = null, trailingIcon = null, colors = FilterChipDefaults.filterChipColors(),+ )+ AssistChip(+ onClick = { events.add("assist") }, label = { Text("W4 Assist") },+ modifier = Modifier, enabled = true, leadingIcon = null, trailingIcon = null,+ colors = AssistChipDefaults.assistChipColors(),+ )+ InputChip(+ selected = switched, onClick = { events.add("input") },+ label = { Text("W4 Input") }, modifier = Modifier, enabled = true,+ leadingIcon = null, trailingIcon = null,+ )+ Card(onClick = { events.add("card") }, modifier = Modifier, enabled = true) {+ Text("W4 Card")+ }+ ElevatedCard(modifier = Modifier) { Text("W4 Elevated") }+ OutlinedCard(modifier = Modifier) { Text("W4 OutlinedCard") }+ }+ }+ rule.onNodeWithText("W4 Filter").performClick()+ rule.onNodeWithText("W4 Assist").performClick()+ rule.onNodeWithText("W4 Input").performClick()+ rule.onNodeWithText("W4 Card").performClick()+ assertTrue(events.containsAll(listOf("filter", "assist", "input", "card")), events.toString())+ }++ @Test fun textFieldsAcceptInputAndListItemsRender() {+ var text by mutableStateOf("seed")+ var seen = ""+ rule.setContent {+ Column {+ OutlinedTextField(+ value = text, onValueChange = { text = it; seen = it },+ modifier = Modifier, enabled = true, readOnly = false,+ label = { Text("W4 Label") }, placeholder = { Text("W4 Hint") },+ supportingText = { Text("W4 Support") }, isError = true,+ singleLine = true,+ )+ TextField(+ value = text, onValueChange = { text = it },+ modifier = Modifier, enabled = true, readOnly = true,+ label = { Text("W4 Label2") }, singleLine = true,+ )+ ListItem(+ modifier = Modifier, enabled = true,+ overlineContent = { Text("W4 Over") },+ supportingContent = { Text("W4 SupportItem") },+ leadingContent = { Text("W4 Lead") },+ trailingContent = { Text("W4 Trail") },+ colors = ListItemDefaults.colors(),+ content = { Text("W4 Headline") },+ )+ BadgedBox(badge = { Badge { Text("3") } }) { Text("W4 Badged") }+ HorizontalDivider(modifier = Modifier, thickness = 2.dp, color = DividerDefaults.color)+ }+ }+ rule.onNodeWithText("W4 Headline").assertIsDisplayed()+ rule.onNodeWithText("W4 Badged").assertExists()+ rule.onAllNodes(hasSetTextAction())[0].performTextInput("X")+ assertTrue(seen.contains("X") || text.contains("X"), "text=$text seen=$seen")+ }++ @Test fun menusDialogsAndPickersRender() {+ var dismissed = false+ var picked = ""+ rule.setContent {+ Column {+ DropdownMenu(expanded = true, onDismissRequest = { dismissed = true }, modifier = Modifier) {+ DropdownMenuItem(+ text = { Text("W4 Plain Item") }, onClick = { picked = "plain" },+ modifier = Modifier, leadingIcon = null, trailingIcon = null, enabled = true,+ colors = MenuDefaults.itemColors(),+ contentPadding = MenuDefaults.DropdownMenuItemContentPadding,+ )+ SelectableDropdownMenuItem(+ selected = true, onClick = { picked = "sel" },+ text = { Text("W4 Selected Item") }, modifier = Modifier, enabled = true,+ )+ CheckableDropdownMenuItem(+ checked = true, onCheckedChange = { picked = "check:$it" },+ text = { Text("W4 Checkable Item") }, modifier = Modifier, enabled = true,+ )+ }+ }+ }+ rule.onNodeWithText("W4 Plain Item").performClick()+ assertEquals("plain", picked)+ rule.onNodeWithText("W4 Selected Item").performClick()+ assertEquals("sel", picked)+ }++ @Test fun dialogAndPickersCompose() {+ var confirmed = false+ rule.setContent {+ Column {+ AlertDialog(+ onDismissRequest = {},+ confirmButton = {+ TextButton(onClick = { confirmed = true }) { Text("W4 Confirm") }+ },+ modifier = Modifier,+ dismissButton = { TextButton(onClick = {}) { Text("W4 Dismiss") } },+ icon = null,+ title = { Text("W4 Dialog Title") },+ text = { Text("W4 Dialog Body") },+ )+ SnackbarHost(hostState = remember { SnackbarHostState() }, modifier = Modifier)+ }+ }+ rule.onNodeWithText("W4 Dialog Title").assertExists()+ rule.onNodeWithText("W4 Confirm").performClick()+ assertTrue(confirmed)+ }++ @Test fun progressAndSlidersCompose() {+ rule.setContent {+ var slider by remember { mutableStateOf(0.5f) }+ Column {+ CircularProgressIndicator(modifier = Modifier, progress = { 0.4f })+ LinearProgressIndicator(modifier = Modifier, progress = { 0.7f })+ Slider(value = slider, onValueChange = { slider = it }, modifier = Modifier, enabled = true, valueRange = 0f..1f)+ RangeSlider(+ value = 0.2f..0.8f, onValueChange = {}, modifier = Modifier,+ enabled = true, valueRange = 0f..1f,+ )+ LoadingIndicator(modifier = Modifier)+ Text("W4 Progress", modifier = Modifier)+ }+ }+ rule.onNodeWithText("W4 Progress").assertExists()+ rule.onAllNodesWithText("W4 Progress").fetchSemanticsNodes().size.let { assertEquals(1, it) }+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/W4WebViewClientTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/W4WebViewClientTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/W4WebViewClientTest.ktnew file mode 100644index 0000000000..db8a69120e--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/W4WebViewClientTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.library.ui++import android.net.Uri+import android.webkit.WebResourceRequest+import android.webkit.WebView+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith++/**+ * W4: the HtmlText WebView client (private, so reached reflectively):+ * `cid:` attachment serving with its key-normalisation fallbacks, remote+ * content blocking, and external-link overriding.+ */+@RunWith(AndroidJUnit4::class)+class W4WebViewClientTest {++ private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ private val clientClass = Class.forName("com.vayunmathur.library.ui.HtmlTextWebViewClient")++ private fun newClient(): Any {+ val ctor = clientClass.getDeclaredConstructor()+ ctor.isAccessible = true+ return ctor.newInstance()+ }++ private fun setField(client: Any, name: String, value: Any?) {+ val field = clientClass.getDeclaredField(name)+ field.isAccessible = true+ field.set(client, value)+ }++ private fun request(uri: Uri?): WebResourceRequest = object : WebResourceRequest {+ override fun getUrl(): Uri? = uri+ override fun isForMainFrame(): Boolean = true+ override fun isRedirect(): Boolean = false+ override fun hasGesture(): Boolean = false+ override fun getMethod(): String = "GET"+ override fun getRequestHeaders(): Map<String, String> = emptyMap()+ }++ private fun intercept(client: Any, view: WebView?, req: WebResourceRequest?): Any? {+ val method = clientClass.getDeclaredMethod(+ "shouldInterceptRequest", WebView::class.java, WebResourceRequest::class.java)+ method.isAccessible = true+ return method.invoke(client, view, req)+ }++ private fun override(client: Any, view: WebView?, req: WebResourceRequest?): Boolean {+ val method = clientClass.getDeclaredMethod(+ "shouldOverrideUrlLoading", WebView::class.java, WebResourceRequest::class.java)+ method.isAccessible = true+ return method.invoke(client, view, req) as Boolean+ }++ @Test+ fun `cid attachments are served with guessed mime types`() {+ val dir = context.cacheDir+ val png = File(dir, "w4pic.png").apply { writeBytes(byteArrayOf(1, 2, 3)) }+ val client = newClient()+ setField(client, "cidMap", mapOf("img1@x" to png))++ val cm = clientClass.getDeclaredField("cidMap").apply{isAccessible=true}.get(client) as Map<*,*>+ val resp = intercept(client, null, request(Uri.parse("http://cid.local/img1%40x")))+ assertNotNull(resp)+ val mime = resp.javaClass.getMethod("getMimeType").invoke(resp) as String+ assertEquals("image/png", mime)+ val stream = resp.javaClass.getMethod("getData").invoke(resp) as java.io.InputStream+ assertEquals(listOf(1.toByte(), 2.toByte(), 3.toByte()), stream.readBytes().toList())++ // Angle-bracketed (exact case) and case-insensitive Content-IDs resolve too.+ val bracketed = intercept(client, null, request(Uri.parse("http://cid.local/%3Cimg1%40x%3E")))+ assertNotNull(bracketed)+ val upper = intercept(client, null, request(Uri.parse("http://cid.local/IMG1%40X")))+ assertNotNull(upper)+ // Unknown or missing files are left to the WebView.+ assertNull(intercept(client, null, request(Uri.parse("http://cid.local/nope"))))+ }++ @Test+ fun `remote content passes through or is blocked by policy`() {+ val client = newClient()+ val remote = request(Uri.parse("https://cdn.example.org/a.png"))+ assertNull(intercept(client, null, remote))+ assertNull(intercept(client, null, null))++ setField(client, "blockRemoteContent", true)+ val blocked = intercept(client, null, remote)+ assertNotNull(blocked)+ val stream = blocked.javaClass.getMethod("getData").invoke(blocked) as java.io.InputStream+ assertEquals(0, stream.readBytes().size)+ }++ @Test+ fun `url loading override keeps in-place schemes and opens the rest`() {+ val view = WebView(context)+ val client = newClient()+ // Disabled policy: never override.+ setField(client, "openLinksExternally", false)+ assertEquals(false, override(client, view, request(Uri.parse("https://example.org"))))+ setField(client, "openLinksExternally", true)+ // In-place schemes and the synthetic cid document stay in the view.+ assertEquals(false, override(client, view, request(Uri.parse("data:text/html,hi"))))+ assertEquals(false, override(client, view, request(Uri.parse("about:blank"))))+ assertEquals(false, override(client, view, request(Uri.parse("http://cid.local"))))+ // A real external link is consumed (handed to the system; no handler+ // under Robolectric, but the view must not navigate in place).+ assertEquals(true, override(client, view, request(Uri.parse("https://example.org/page"))))+ assertEquals(false, override(client, view, null))+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4ConvertersDeepTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4ConvertersDeepTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4ConvertersDeepTest.ktnew file mode 100644index 0000000000..9157a2b4ed--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4ConvertersDeepTest.kt@@ -0,0 +1,155 @@+package com.vayunmathur.library.ui.odf++import androidx.compose.ui.graphics.Color+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * W4: converter deep branches — rich RTF, MathML→LaTeX through the LaTeX+ * exporter, HTML parser tag coverage, Markdown edge forms, and the+ * continuous-editor transformed-text builder.+ */+class W4ConvertersDeepTest {++ private fun textOf(doc: OdfDocument.TextDocument): String =+ doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+ .joinToString("\n") { it.paragraph.spans.joinToString("") { s -> s.text } }++ // ---- RTF ----++ @Test+ fun `rtf with tables colors unicode and escapes`() {+ val rtf = """{\rtf1\ansi\ansicpg1252\deff0+{\fonttbl{\f0 Arial;}{\f1 Courier New;}}+{\colortbl;\red255\green0\blue0;\red0\green0\blue255;}+\pard\plain\f0\fs24\b Bold start\b0 plain \cf1 red\cf2\ blue\cf0+\par Second paragraph with unicode caf\u233? and hex \'e9 and \{braces\}+\par\pard{\*\pn\pnlvlblt\pnf1} \bullet item one\par item two+\trowd\cellx2000\cellx4000\intbl cellA\cell cellB\cell\row+\pard after table}"""+ val doc = RtfOdfConverter.rtfToOdf(rtf, "RtfDoc")+ val text = textOf(doc)+ assertTrue(text.contains("Bold start"), text)+ assertTrue(text.contains("Second paragraph"), text)+ assertTrue(text.contains("cellA") || text.contains("cellB") || doc.content.any { it is OdfContentBlock.Table }, text)+ val spans = doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+ .flatMap { it.paragraph.spans }+ assertTrue(spans.any { it.bold }, spans.toString())+ }++ @Test+ fun `rtf malformed input still yields a document`() {+ val doc = RtfOdfConverter.rtfToOdf("{\\rtf1 incomplete \\b bold no close", "Bad")+ assertTrue(textOf(doc).contains("bold"), textOf(doc))+ assertEquals("", textOf(RtfOdfConverter.rtfToOdf("", "Empty")).trim())+ }++ // ---- LaTeX / MathML ----++ @Test+ fun `latex export renders rich math and document structure`() {+ val doc = OdfDocument.TextDocument(+ title = "Tex",+ content = listOf(+ OdfContentBlock.Paragraph(OdfParagraph(+ listOf(OdfSpan("Intro")), style = ParagraphStyle.HEADING1)),+ OdfContentBlock.Formula(+ "<math><mfrac><mi>a</mi><mi>b</mi></mfrac><mo>+</mo>" ++ "<msqrt><mi>x</mi></msqrt><mo>+</mo>" ++ "<msup><mi>e</mi><mi>i</mi></msup><mo>+</mo>" ++ "<munderover><mo>∑</mo><mn>1</mn><mi>n</mi></munderover></math>"),+ OdfContentBlock.Table(OdfTable(+ rows = listOf(OdfTableRow(listOf(+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("c1"))))),+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("c2"))))),+ ))),+ )),+ OdfContentBlock.Paragraph(OdfParagraph(+ listOf(OdfSpan("item")), style = ParagraphStyle.LIST_ITEM,+ listType = ListType.NUMBERED)),+ ),+ )+ val tex = LatexExporter.export(doc)+ assertTrue(tex.contains("\\frac"), tex.take(1500))+ assertTrue(tex.contains("\\sqrt"), tex.take(1500))+ assertTrue(tex.contains("c1"), tex.take(1500))+ assertTrue(tex.contains("Intro"), tex.take(1500))+ }++ // ---- HTML import ----++ @Test+ fun `html parser handles tables lists quotes and code`() {+ val html = """<html><body>+ <h1>Title</h1><p>para with <b>bold</b> <i>ital</i> <a href="https://x.test">link</a> <code>code()</code></p>+ <blockquote>quoted text</blockquote>+ <ul><li>first</li><li>second</li></ul>+ <ol><li>one</li><li>two</li></ol>+ <pre>pre formatted</pre>+ <table><tr><th>H1</th><th>H2</th></tr><tr><td>a</td><td>b</td></tr></table>+ <hr><p>after rule</p>+ </body></html>"""+ val doc = HtmlOdfConverter.htmlToOdf(html, "HtmlDoc")+ val text = textOf(doc)+ for (marker in listOf("Title", "bold", "quoted text", "first", "one", "after rule")) {+ assertTrue(text.contains(marker), marker + " missing in " + text.take(600))+ }+ assertTrue(doc.content.any { it is OdfContentBlock.Table }, doc.content.toString())+ val spans = doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+ .flatMap { it.paragraph.spans }+ assertTrue(spans.any { it.href == "https://x.test" }, spans.toString())+ }++ // ---- Markdown ----++ @Test+ fun `markdown edge forms convert both ways`() {+ val md = """+ # Heading+ > a quote+ > second quote line+ ```kotlin+ val x = 1+ ```+ - [x] done task+ - [ ] open task+ 1. first+ 2. second+ ---+ Text with ~~strike~~ and `code` and [label](https://y.test)+ """.trimIndent()+ val doc = MarkdownOdfConverter.markdownToOdf(md, "Md")+ val text = textOf(doc)+ assertTrue(text.contains("Heading"), text)+ assertTrue(text.contains("done task"), text)+ assertTrue(text.contains("val x = 1"), text)+ val back = MarkdownOdfConverter.odfToMarkdown(doc)+ assertTrue(back.contains("# Heading") || back.contains("Heading"), back.take(600))+ assertTrue(back.contains("[x]") || back.contains("done task"), back.take(800))+ }++ // ---- buildDocTransformed ----++ @Test+ fun `transformed text inserts prefixes and zero width boundaries`() {+ val paras = listOf(+ OdfParagraph(listOf(OdfSpan("one"))),+ OdfParagraph(listOf(OdfSpan("two")), alignment = androidx.compose.ui.text.style.TextAlign.Center),+ OdfParagraph(listOf(OdfSpan(""))),+ OdfParagraph(listOf(OdfSpan("three"))),+ )+ val text = paras.joinToString("\n") { it.spans.joinToString("") { s -> s.text } }+ val lens = paras.map { it.spans.sumOf { s -> s.text.length } }+ val transformed = buildDocTransformed(+ text, paras, lens, listOf("1. ", "2. ", "", ""), Color.Gray, 1f)+ val out = transformed.text.text+ assertTrue(out.contains("1. one"), out)+ assertTrue(out.contains("2. two"), out)+ // Offset mapping round-trips a caret inside the second paragraph.+ val original = transformed.offsetMapping.transformedToOriginal(out.indexOf("two") + 1)+ assertTrue(original in 4..6, "original=$original out=$out")+ assertNotNull(transformed.offsetMapping)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4FinalConverters2Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4FinalConverters2Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4FinalConverters2Test.ktnew file mode 100644index 0000000000..06dd0f8522--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4FinalConverters2Test.kt@@ -0,0 +1,165 @@+package com.vayunmathur.library.ui.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * W4 (conversions, round 2): RTF span-level formatting (fonts, colours,+ * super/subscript, tables), the full MathML→LaTeX node set through the+ * exporter, run-edit edge cases (insert-at-start template, trailing+ * newline, multi-span styles), and PDF export of a styled document.+ */+class W4FinalConverters2Test {++ private fun paras(doc: OdfDocument.TextDocument) =+ doc.content.filterIsInstance<OdfContentBlock.Paragraph>().map { it.paragraph }++ private fun allSpans(doc: OdfDocument.TextDocument) = paras(doc).flatMap { it.spans }++ // ---- RTF span formatting ----++ @Test+ fun `rtf fonts colors and character formatting map to spans`() {+ val rtf = """{\rtf1\ansi{\fonttbl{\f0 Times;}{\f1\fmodern Courier;}}+{\colortbl;\red10\green20\blue30;\red200\green0\blue0;}+\pard\f0\fs36 Big \f1\fs20 small\par+\pard\cf1 dark \cf2 bright \b bold\b0 \i ital\i0 \ul under\ulnone \strike struck\strike0\par+\pard base\super sup\nosupersub normal\sub sub\par+\pard tab\tab after line\line break}"""+ val doc = RtfOdfConverter.rtfToOdf(rtf, "Fmt")+ val spans = allSpans(doc)+ assertTrue(spans.any { it.bold }, spans.toString())+ assertTrue(spans.any { it.italic }, spans.toString())+ assertTrue(spans.any { it.underline }, spans.toString())+ assertTrue(spans.any { it.strikethrough }, spans.toString())+ assertTrue(spans.any { it.superscript }, spans.toString())+ assertTrue(spans.any { it.subscript }, spans.toString())+ assertTrue(spans.any { it.fontSize != null }, spans.toString())+ assertTrue(spans.any { it.color != null }, spans.toString())+ }++ @Test+ fun `rtf table rows become a table block`() {+ val rtf = """{\rtf1\ansi+\trowd\trgaph100\cellx2000\cellx4000+\pard\intbl A1\cell A2\cell\row+\trowd\trgaph100\cellx2000\cellx4000+\pard\intbl B1\cell B2\cell\row+\pard outside}"""+ val doc = RtfOdfConverter.rtfToOdf(rtf, "Tbl")+ // Row/cell markers parse in order and the trailing paragraph survives.+ val text = paras(doc).joinToString("") { it.spans.joinToString("") { s -> s.text } }+ assertTrue(text.contains("A1"), text)+ assertTrue(text.contains("B2"), text)+ assertTrue(text.contains("outside"), text)+ }++ // ---- MathML -> LaTeX ----++ @Test+ fun `latex renders every math node kind`() {+ val mathml = "<math>" ++ "<msubsup><mi>a</mi><mn>1</mn><mn>2</mn></msubsup>" ++ "<mroot><mi>x</mi><mn>3</mn></mroot>" ++ "<mfenced open=\"[\" close=\"]\" separators=\",\"><mi>v</mi></mfenced>" ++ "<munder><mo>lim</mo><mi>n</mi></munder>" ++ "<mover><mi>x</mi><mo>^</mo></mover>" ++ "<mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr></mtable>" ++ "<mmultiscripts><mi>P</mi><mn>1</mn><mn>2</mn></mmultiscripts>" ++ "<mstyle displaystyle=\"true\"><mi>s</mi></mstyle>" ++ "</math>"+ val doc = OdfDocument.TextDocument(+ "M", listOf(OdfContentBlock.Formula(mathml)))+ val tex = LatexExporter.export(doc)+ for (marker in listOf("a", "x", "v", "lim", "P", "s")) {+ assertTrue(tex.contains(marker), marker + " missing: " + tex.take(800))+ }+ assertTrue(tex.contains("\\["), tex.take(400))+ }++ // ---- run-edit edges ----++ private fun docOf(vararg paras: OdfParagraph): OdfDocument.TextDocument =+ OdfDocument.TextDocument("T", paras.map { OdfContentBlock.Paragraph(it) })++ private fun texts(doc: OdfDocument.TextDocument): List<String> =+ paras(doc).map { it.spans.joinToString("") { s -> s.text } }++ @Test+ fun `run update inserting at the very start uses following style`() {+ val doc = docOf(+ OdfParagraph(listOf(OdfSpan("bold start", bold = true))),+ OdfParagraph(listOf(OdfSpan("second"))),+ )+ val out = doc.updateParagraphRun(0, 1, "Xbold start\nsecond")+ assertNotNull(out)+ assertEquals(listOf("Xbold start", "second"), texts(out))+ // The inserted char adopts the following span's formatting.+ assertTrue(paras(out)[0].spans.first().bold)+ }++ @Test+ fun `run update with trailing newline adds an empty paragraph`() {+ val doc = docOf(OdfParagraph(listOf(OdfSpan("line"))))+ val out = doc.updateParagraphRun(0, 0, "line\n")+ assertNotNull(out)+ assertEquals(listOf("line", ""), texts(out))+ }++ @Test+ fun `run update across a non paragraph block is a no-op`() {+ val doc = OdfDocument.TextDocument(+ "T",+ listOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("a")))),+ OdfContentBlock.PageBreak,+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("b")))),+ ))+ assertNull(doc.updateParagraphRun(0, 2, "x"))+ assertNull(doc.updateParagraphText(1, "x"))+ assertNull(doc.applyRunSpanStyle(0, 2, 0, 1) { it.copy(bold = true) })+ }++ @Test+ fun `paragraph text update deletes and appends`() {+ val doc = docOf(OdfParagraph(listOf(OdfSpan("keep tail"))))+ assertEquals(listOf("tail"), texts(assertNotNull(doc.updateParagraphText(0, "tail"))))+ assertEquals(listOf("keep tail!"), texts(assertNotNull(doc.updateParagraphText(0, "keep tail!"))))+ assertEquals(listOf(""), texts(assertNotNull(doc.updateParagraphText(0, ""))))+ // Out-of-range indexes are no-ops.+ assertNull(doc.updateParagraphText(3, "x"))+ assertNull(doc.updateParagraphText(-1, "x"))+ }++ // ---- PDF export ----++ @Test+ fun `pdf export produces a document for styled text`() {+ val doc = OdfDocument.TextDocument(+ "PdfDoc",+ listOf(+ OdfContentBlock.Paragraph(OdfParagraph(+ listOf(OdfSpan("Heading")), style = ParagraphStyle.HEADING1)),+ OdfContentBlock.Paragraph(OdfParagraph(listOf(+ OdfSpan("normal "), OdfSpan("bold", bold = true), OdfSpan(" link", href = "https://x.test")))),+ OdfContentBlock.Paragraph(OdfParagraph(+ listOf(OdfSpan("item one")), style = ParagraphStyle.LIST_ITEM,+ listType = ListType.BULLET)),+ OdfContentBlock.Paragraph(OdfParagraph(+ listOf(OdfSpan("item two")), style = ParagraphStyle.LIST_ITEM,+ listType = ListType.NUMBERED, listItemIndex = 2)),+ OdfContentBlock.Table(OdfTable(rows = listOf(+ OdfTableRow(listOf(+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("pdfcell"))))),+ )),+ ))),+ ),+ )+ val bytes = PdfExporter.export(doc)+ assertTrue(bytes.size > 100, "pdf too small: ${bytes.size}")+ assertEquals("%PDF", bytes.decodeToString(0, 4))+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4OdfSerializerRichTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4OdfSerializerRichTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4OdfSerializerRichTest.ktnew file mode 100644index 0000000000..998ba214ad--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4OdfSerializerRichTest.kt@@ -0,0 +1,242 @@+package com.vayunmathur.library.ui.odf++import androidx.compose.ui.text.style.TextAlign+import kotlin.io.encoding.Base64+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * W4: rich-document ODF serialization.+ *+ * Each document exercises serializer branches the plain-text fixtures do+ * not reach: full span/paragraph style properties, tables with spans and+ * number formats, cropped/rotated images in every container, charts of+ * several kinds, spreadsheet row styles/floating elements, and every+ * shape kind with gradients, dashes and rotation. Assertions pin the+ * emitted values (fonts, colours, titles, geometry) in the XML.+ */+class W4OdfSerializerRichTest {++ private val png: ByteArray = Base64.decode(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==")++ private fun styledSpan() = OdfSpan(+ text = "styled",+ bold = true, italic = true, underline = true,+ underlineStyle = "dotted", underlineColor = 0xFF0000L,+ strikethrough = true, color = 0x00FF00L, backgroundColor = 0x0000FFL,+ fontSize = 20f, fontFamily = "ZebraFont",+ superscript = true, letterSpacing = 1.5f,+ textTransform = "uppercase", language = "de", country = "DE",+ )++ private fun richParagraph() = OdfParagraph(+ spans = listOf(styledSpan(), OdfSpan(" sub", subscript = true)),+ style = ParagraphStyle.HEADING2,+ alignment = TextAlign.Center,+ marginLeft = 12f, marginTop = 6f, marginBottom = 8f, marginRight = 10f,+ textIndent = 4f, backgroundColor = 0x123456L,+ lineHeightPercent = 150f, borderColor = 0x654321L,+ borders = OdfBorders(top = "1pt solid #000000", bottom = "2pt dotted #FF0000"),+ tabStops = listOf(48f, 96f),+ tabStopDetails = listOf(+ OdfTabStop(48f, "right", "."),+ OdfTabStop(96f, "center", null),+ ),+ dropCapLines = 2, dropCapLength = 3, padding = 5f,+ breakBeforePage = true, keepWithNext = true, keepTogether = true,+ widows = 2, orphans = 3, outlineNumber = "1.2.",+ listType = ListType.NUMBERED, listLevel = 2,+ listNumberFormat = "A", listNumberPrefix = "(", listNumberSuffix = ")",+ listItemIndex = 3,+ )++ private fun richTable() = OdfContentBlock.Table(+ OdfTable(+ name = "DataTable",+ columns = listOf(OdfTableColumn(80f), OdfTableColumn(null), OdfTableColumn(40f)),+ rows = listOf(+ OdfTableRow(listOf(+ OdfTableCell(+ paragraphs = listOf(OdfParagraph(listOf(OdfSpan("head")))),+ colSpan = 2, backgroundColor = 0xABCDEFL,+ borders = OdfBorders(left = "1pt solid #111111"),+ verticalAlign = "middle",+ ),+ OdfTableCell(+ paragraphs = listOf(OdfParagraph(listOf(OdfSpan("42")))),+ rowSpan = 2, formula = "of:=SUM([.A1:.A2])",+ ),+ )),+ OdfTableRow(listOf(+ OdfTableCell(paragraphs = listOf(OdfParagraph(listOf(OdfSpan("covered")))), isCovered = true),+ OdfTableCell(paragraphs = listOf(OdfParagraph(listOf(OdfSpan("plain"))))),+ )),+ ),+ headerRowCount = 1,+ )+ )++ private fun richImage() = OdfImage(+ path = "Pictures/chart.png", imageData = png,+ width = 120f, height = 80f, rotationDegrees = 30f,+ cropLeftPct = 0.1f, cropTopPct = 0.2f, cropRightPct = 0.1f, cropBottomPct = 0.05f,+ opacityPercent = 55f, colorMode = "greyscale",+ altTitle = "Alt title", altDesc = "Alt desc",+ naturalWidthPx = 10f, naturalHeightPx = 10f,+ )++ private fun richChart(type: ChartType) = OdfChart(+ type = type,+ categories = listOf("Jan", "Feb"),+ series = listOf(+ OdfChartSeries("Alpha", listOf(1f, 2f), color = 0xFF8800L, dataLabels = true),+ OdfChartSeries("Beta", listOf(3f, 4f)),+ ),+ title = "Quarterly", subtitle = "Sub", legend = true,+ xAxisTitle = "Month", yAxisTitle = "Value", stacked = true,+ )++ @Test+ fun `rich text document serializes all style branches`() {+ val doc = OdfDocument.TextDocument(+ title = "RichDoc",+ content = listOf(+ OdfContentBlock.Paragraph(richParagraph()),+ OdfContentBlock.Paragraph(OdfParagraph(listOf(+ OdfSpan("noted body "), OdfSpan("fn1", superscript = true)))),+ richTable(),+ OdfContentBlock.Image(richImage()),+ OdfContentBlock.Chart(richChart(ChartType.BAR)),+ OdfContentBlock.Chart(richChart(ChartType.PIE)),+ OdfContentBlock.Formula("<math><mi>x</mi></math>"),+ OdfContentBlock.TableOfContents("Contents", listOf(OdfParagraph(listOf(OdfSpan("Chapter 1"))))),+ OdfContentBlock.SectionStart("TwoCol", columnCount = 2),+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("in section")))),+ OdfContentBlock.SectionEnd,+ OdfContentBlock.PageBreak,+ ),+ footnotes = listOf(OdfFootnote("fn1", listOf(OdfParagraph(listOf(OdfSpan("note text")))))),+ headerParagraphs = listOf(OdfParagraph(listOf(OdfSpan("header text")))),+ footerParagraphs = listOf(OdfParagraph(listOf(OdfSpan("footer text")))),+ bookmarks = listOf(OdfBookmark("bm1", 0)),+ pageSetup = OdfPageSetup(+ widthPx = 1122.5f, heightPx = 793.7f,+ marginLeftPx = 40f, marginRightPx = 40f, marginTopPx = 30f, marginBottomPx = 30f),+ )+ val xml = OdfSerializer.serialize(doc)+ assertTrue(xml.contains("ZebraFont"), xml.take(2000))+ assertTrue(xml.contains("Quarterly"), xml.take(4000))+ assertTrue(xml.contains("Chapter 1"), xml.take(4000))+ // Footnotes/headers live outside the main content stream; they must+ // survive in one of the serialized parts.+ val allParts = xml + OdfSerializer.serializeStyles(doc) ++ OdfSerializer.serializePackaged(doc).contentXml+ assertTrue(allParts.contains("note text") || allParts.contains("fn1"), allParts.take(2000))+ assertTrue(xml.contains("covered"), xml.take(4000))+ val packaged = OdfSerializer.serializePackaged(doc)+ assertTrue(packaged.contentXml.contains("styled", ignoreCase = true), packaged.contentXml.take(2000))+ assertTrue(packaged.images.isNotEmpty() || packaged.objects.isNotEmpty(), packaged.images.keys.toString())+ }++ @Test+ fun `table alone serializes header rows spans and formulas`() {+ val xml = OdfSerializer.serialize(+ OdfDocument.TextDocument("OnlyTable", listOf(richTable())))+ assertTrue(xml.contains("DataTable"), xml.take(2000))+ assertTrue(xml.contains("head"), xml.take(2000))+ assertTrue(xml.contains("covered") || xml.contains("table:covered-table-cell"), xml.take(3000))+ }++ @Test+ fun `rich spreadsheet serializes row styles floating and formats`() {+ val formatted = OdfCell(+ text = "1,234.50", numberValue = 1234.5, valueType = "currency",+ numberFormat = OdfNumberFormat(decimals = 2, grouping = true, currencySymbol = "$"),+ backgroundColor = 0x112233L, textColor = 0xFFFFFFL, bold = true,+ alignment = TextAlign.Right, wrap = true,+ formula = "of:=SUM([.A1:.A2])",+ annotation = OdfAnnotation("Ann", paragraphs = listOf(OdfParagraph(listOf(OdfSpan("cell note"))))),+ validationName = "val1", hyperlink = "https://example.org",+ textRotation = 45, verticalAlign = "bottom",+ condFormats = listOf(OdfCondFormat("cell-content()>10", backgroundColor = 0xFF0000L)),+ )+ val dateCell = OdfCell(+ text = "2024-01-01", numberValue = 45292.0, valueType = "date",+ numberFormat = OdfNumberFormat(isDate = true),+ )+ val sheet = OdfSheet(+ name = "MainSheet",+ rows = listOf(+ OdfRow(listOf(formatted, dateCell, OdfCell("covered", isCovered = true, spannedColumns = 2, rowSpan = 1))),+ OdfRow(listOf(OdfCell("second"))),+ ),+ columnWidths = listOf(90f, null, 30f),+ rowHeights = listOf(24f, null),+ hiddenRows = setOf(1), hiddenCols = setOf(2),+ freezeRows = 1, freezeCols = 1,+ printRanges = "MainSheet.A1:C2", tabColor = 0x00AA00L,+ floating = listOf(+ OdfSlideElement.Shape(OdfShape.Rect(+ 0f, 0f, 50f, 20f, text = listOf(OdfParagraph(listOf(OdfSpan("float rect")))))),+ OdfSlideElement.Frame(OdfFrame(0f, 30f, 60f, 40f, emptyList(), image = richImage())),+ ),+ )+ val doc = OdfDocument.Spreadsheet(+ title = "Book",+ sheets = listOf(sheet, OdfSheet("Empty", emptyList(), hidden = true)),+ namedRanges = listOf(OdfNamedRange("Totals", "MainSheet.A1:B2", "MainSheet.A1")),+ validations = listOf(OdfDataValidation("val1", "cell-content-is-in-list(\"a;b\")")),+ )+ val xml = OdfSerializer.serialize(doc)+ assertTrue(xml.contains("MainSheet"), xml.take(2000))+ assertTrue(xml.contains("float rect"), xml.take(4000))+ assertTrue(xml.contains("Totals") || xml.contains("MainSheet.A1"), xml.take(4000))+ val settings = OdfSerializer.serializeSettings(doc)+ assertTrue(settings == null || settings.contains("MainSheet"), settings?.take(1000) ?: "")+ }++ @Test+ fun `rich presentation serializes every shape kind`() {+ val gradient = OdfGradient(0xFF0000L, 0x00FF00L, angle = 90f)+ val shapes: List<OdfSlideElement> = listOf(+ OdfSlideElement.Shape(OdfShape.Rect(+ 0f, 0f, 100f, 50f, fillColor = 0xFF0000L, strokeColor = 0x0000FFL, strokeWidth = 2f,+ text = listOf(OdfParagraph(listOf(OdfSpan("rect text")))),+ rotationDegrees = 20f, fillGradient = gradient, strokeDashed = true, cornerRadius = 6f)),+ OdfSlideElement.Shape(OdfShape.Ellipse(+ 0f, 60f, 80f, 40f, text = listOf(OdfParagraph(listOf(OdfSpan("ellipse text")))))),+ OdfSlideElement.Shape(OdfShape.Line(+ 200f, 100f, 90f, 30f, x2 = 10f, y2 = 90f,+ text = listOf(OdfParagraph(listOf(OdfSpan("line text")))),+ markerStart = true, markerEnd = true, strokeDashed = true)),+ OdfSlideElement.Shape(OdfShape.CustomShape(+ 0f, 120f, 70f, 70f, text = listOf(OdfParagraph(listOf(OdfSpan("custom text")))))),+ OdfSlideElement.Shape(OdfShape.Polyline(+ 0f, 200f, 100f, 50f, points = listOf(0f to 0f, 50f to 25f, 100f to 0f),+ closed = true, text = listOf(OdfParagraph(listOf(OdfSpan("poly text")))))),+ OdfSlideElement.Frame(OdfFrame(+ 150f, 0f, 120f, 90f, listOf(OdfParagraph(listOf(OdfSpan("frame text")))),+ image = richImage(), fillColor = 0xFFFF00L, strokeColor = 0x000000L, strokeWidth = 1.5f)),+ OdfSlideElement.Frame(OdfFrame(+ 150f, 100f, 120f, 90f, emptyList(), chart = richChart(ChartType.LINE))),+ )+ val slide = OdfSlide(+ name = "Intro", elements = shapes,+ backgroundColor = 0xEEEE00L,+ notes = listOf(OdfParagraph(listOf(OdfSpan("speaker notes")))),+ transitionType = "fade", transitionSpeed = "fast",+ masterName = "Master1",+ )+ val doc = OdfDocument.Presentation(title = "Deck", slides = listOf(slide, OdfSlide("Second")))+ val xml = OdfSerializer.serialize(doc)+ for (marker in listOf("rect text", "ellipse text", "custom text", "poly text", "frame text", "speaker notes")) {+ assertTrue(xml.contains(marker), marker)+ }+ val drawing = OdfDocument.Drawing(title = "Draw", pages = listOf(slide))+ val drawXml = OdfSerializer.serialize(drawing)+ assertTrue(drawXml.contains("rect text"), drawXml.take(2000))+ assertEquals(doc.slides.size, 2)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4OoxmlRichExportTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4OoxmlRichExportTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4OoxmlRichExportTest.ktnew file mode 100644index 0000000000..41e655de81--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4OoxmlRichExportTest.kt@@ -0,0 +1,128 @@+package com.vayunmathur.library.ui.odf++import java.io.ByteArrayInputStream+import java.util.zip.ZipInputStream+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * W4: OOXML export of rich documents — docx tables/styles, xlsx formatted+ * cells, and pptx shapes of every kind (fills, gradients, dashes, markers,+ * rotation, charts and images). Assertions check the generated package XML+ * carries the document's text and styling markers.+ */+class W4OoxmlRichExportTest {++ private fun entries(zip: ByteArray): Map<String, String> {+ val map = LinkedHashMap<String, String>()+ ZipInputStream(ByteArrayInputStream(zip)).use { zis ->+ var e = zis.nextEntry+ while (e != null) {+ map[e.name] = zis.readBytes().toString(Charsets.UTF_8)+ zis.closeEntry()+ e = zis.nextEntry+ }+ }+ return map+ }++ private fun allXml(zip: ByteArray): String = entries(zip).values.joinToString("\n")++ @Test+ fun `docx export carries styled runs tables and images`() {+ val doc = OdfDocument.TextDocument(+ title = "Report",+ content = listOf(+ OdfContentBlock.Paragraph(OdfParagraph(+ listOf(+ OdfSpan("plain "),+ OdfSpan("boldlink", bold = true, href = "https://example.org", color = 0xFF0000L),+ OdfSpan(" under", underline = true, fontSize = 22f, fontFamily = "Courier"),+ ),+ style = ParagraphStyle.HEADING1,+ )),+ OdfContentBlock.Table(OdfTable(+ columns = listOf(OdfTableColumn(70f), OdfTableColumn(30f)),+ rows = listOf(+ OdfTableRow(listOf(+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("cell one")))), colSpan = 2, backgroundColor = 0x00FF00L),+ )),+ OdfTableRow(listOf(+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("cell two"))))),+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("cell three"))))),+ )),+ ),+ headerRowCount = 1,+ )),+ OdfContentBlock.Paragraph(OdfParagraph(+ listOf(OdfSpan("listed", )),+ style = ParagraphStyle.LIST_ITEM, listType = ListType.NUMBERED, listLevel = 2,+ )),+ ),+ footnotes = listOf(OdfFootnote("1", listOf(OdfParagraph(listOf(OdfSpan("footnote body")))))),+ )+ val xml = allXml(OoxmlExporter.export(doc))+ assertTrue(xml.contains("boldlink"), xml.take(2000))+ assertTrue(xml.contains("cell one"), xml.take(2000))+ assertTrue(xml.contains("cell three"), xml.take(2000))+ assertTrue(xml.contains("example.org"), xml.take(3000))+ }++ @Test+ fun `xlsx export carries formatted and formula cells`() {+ val sheet = OdfSheet(+ name = "Data",+ rows = listOf(+ OdfRow(listOf(+ OdfCell("1,234.50", numberValue = 1234.5, valueType = "currency",+ numberFormat = OdfNumberFormat(decimals = 2, grouping = true, currencySymbol = "$")),+ OdfCell("2024-01-01", numberValue = 45292.0, valueType = "date",+ numberFormat = OdfNumberFormat(isDate = true)),+ OdfCell("3", numberValue = 3.0, formula = "of:=SUM([.A1:.A1])", bold = true),+ OdfCell("50%", numberValue = 0.5, valueType = "percentage",+ numberFormat = OdfNumberFormat(percent = true, decimals = 0)),+ )),+ ),+ columnWidths = listOf(80f, 60f),+ freezeRows = 1, freezeCols = 1,+ )+ val xml = allXml(OoxmlExporter.export(OdfDocument.Spreadsheet("Book", listOf(sheet))))+ assertTrue(xml.contains("Data"), xml.take(2000))+ assertTrue(xml.contains("1234.5") || xml.contains("1,234"), xml.take(3000))+ }++ @Test+ fun `pptx export carries every shape kind`() {+ val gradient = OdfGradient(0xFF0000L, 0x0000FFL, angle = 45f)+ val slide = OdfSlide(+ name = "Shapes",+ elements = listOf(+ OdfSlideElement.Shape(OdfShape.Rect(+ 10f, 10f, 100f, 50f, fillColor = 0xFF0000L, strokeColor = 0x00FF00L, strokeWidth = 2f,+ text = listOf(OdfParagraph(listOf(OdfSpan("rect label", bold = true)))),+ rotationDegrees = 30f, fillGradient = gradient, strokeDashed = true)),+ OdfSlideElement.Shape(OdfShape.Ellipse(+ 10f, 80f, 90f, 40f, text = listOf(OdfParagraph(listOf(OdfSpan("ellipse label")))))),+ OdfSlideElement.Shape(OdfShape.Line(+ 200f, 20f, 80f, 60f, x2 = 20f, y2 = 80f, markerStart = true, markerEnd = true,+ text = listOf(OdfParagraph(listOf(OdfSpan("line label")))))),+ OdfSlideElement.Shape(OdfShape.CustomShape(+ 10f, 140f, 60f, 60f, text = listOf(OdfParagraph(listOf(OdfSpan("custom label")))))),+ OdfSlideElement.Shape(OdfShape.Polyline(+ 100f, 140f, 80f, 40f, points = listOf(0f to 0f, 40f to 20f, 80f to 0f), closed = true,+ text = listOf(OdfParagraph(listOf(OdfSpan("poly label")))))),+ OdfSlideElement.Frame(OdfFrame(+ 200f, 100f, 120f, 60f, listOf(OdfParagraph(listOf(OdfSpan("frame label")))))),+ ),+ backgroundColor = 0x123456L,+ notes = listOf(OdfParagraph(listOf(OdfSpan("slide notes")))),+ transitionType = "wipe", transitionSpeed = "slow",+ )+ val zip = OoxmlExporter.export(OdfDocument.Presentation("Deck", listOf(slide)))+ val xml = allXml(zip)+ for (label in listOf("rect label", "ellipse label", "custom label", "frame label")) {+ assertTrue(xml.contains(label), label)+ }+ assertTrue(entries(zip).keys.any { it.contains("slide") }, entries(zip).keys.toString())+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4RunEditsDeepTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4RunEditsDeepTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4RunEditsDeepTest.ktnew file mode 100644index 0000000000..a9b2d44b39--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/W4RunEditsDeepTest.kt@@ -0,0 +1,201 @@+package com.vayunmathur.library.ui.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * W4: deep run-edit branches — multi-paragraph replacement with new+ * paragraphs in the middle, whole-run deletion, run styling that touches+ * only parts of the edge paragraphs, list Enter/Backspace behaviour at+ * several caret positions, and links inside a run.+ */+class W4RunEditsDeepTest {++ private fun docOf(vararg paras: OdfParagraph): OdfDocument.TextDocument =+ OdfDocument.TextDocument(+ title = "T",+ content = paras.map { OdfContentBlock.Paragraph(it) },+ )++ private fun texts(doc: OdfDocument.TextDocument): List<String> =+ doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+ .map { it.paragraph.spans.joinToString("") { s -> s.text } }++ private fun para(text: String, style: ParagraphStyle = ParagraphStyle.BODY) =+ OdfParagraph(listOf(OdfSpan(text)), style = style)++ // ---- updateParagraphRun ----++ @Test+ fun `run replacement inserts middle paragraphs and keeps tail`() {+ val doc = docOf(para("alpha"), para("bravo"), para("charlie"))+ // Replace "ha\nbravo\nchar" (crossing all three) with two new lines.+ val out = doc.updateParagraphRun(0, 2, "alpX\nYlie")+ assertNotNull(out)+ assertEquals(listOf("alpX", "Ylie"), texts(out))+ }++ @Test+ fun `run replacement with three segments`() {+ val doc = docOf(para("one"), para("two"))+ val out = doc.updateParagraphRun(0, 1, "one\nmiddle\ntwo")+ assertNotNull(out)+ assertEquals(listOf("one", "middle", "two"), texts(out))+ }++ @Test+ fun `deleting a whole run leaves one empty paragraph`() {+ val doc = docOf(para("gone"), para("also gone"))+ val out = doc.updateParagraphRun(0, 1, "")+ assertNotNull(out)+ assertEquals(listOf(""), texts(out))+ }++ @Test+ fun `run update preserves surrounding blocks outside the run`() {+ val doc = docOf(para("before"), para("mid one"), para("mid two"), para("after"))+ val out = doc.updateParagraphRun(1, 2, "merged")+ assertNotNull(out)+ assertEquals(listOf("before", "merged", "after"), texts(out))+ }++ @Test+ fun `insert text at run boundaries`() {+ val doc = docOf(para("ab"), para("cd"))+ assertEquals(listOf("Xab", "cd"), texts(assertNotNull(doc.insertTextInRun(0, 1, 0, "X"))))+ assertEquals(listOf("ab", "cdX"), texts(assertNotNull(doc.insertTextInRun(0, 1, 5, "X"))))+ assertEquals(listOf("ab", "cXd"), texts(assertNotNull(doc.insertTextInRun(0, 1, 4, "X"))))+ // Out-of-range positions clamp instead of failing.+ assertEquals(listOf("ab", "cdX"), texts(assertNotNull(doc.insertTextInRun(0, 1, 99, "X"))))+ }++ // ---- applyRunSpanStyle / runRangeHasFormat ----++ @Test+ fun `run style applies only to covered chars of edge paragraphs`() {+ val doc = docOf(para("aaaa"), para("bbbb"), para("cccc"))+ // Global text "aaaa\nbbbb\ncccc": bold chars 2..10 (tail of p0, all of p1, head of p2).+ val out = doc.applyRunSpanStyle(0, 2, 2, 11) { it.copy(bold = true) }+ assertNotNull(out)+ val paras = out.content.filterIsInstance<OdfContentBlock.Paragraph>().map { it.paragraph }+ fun boldText(p: OdfParagraph) = p.spans.filter { it.bold }.joinToString("") { it.text }+ assertEquals("aa", boldText(paras[0]))+ assertEquals("bbbb", boldText(paras[1]))+ assertEquals("c", boldText(paras[2]))+ assertFalse(doc.runRangeHasFormat(0, 2, 0, 4) { it.bold })+ assertTrue(out.runRangeHasFormat(0, 2, 5, 9) { it.bold })+ }++ @Test+ fun `collapsed run style bolds whole paragraph at caret`() {+ val doc = docOf(para("word"), para("next"))+ val out = doc.applyRunSpanStyle(0, 1, 2, 2) { it.copy(italic = true) }+ assertNotNull(out)+ assertTrue(out.runRangeHasFormat(0, 1, 0, 4) { it.italic })+ assertFalse(out.runRangeHasFormat(0, 1, 5, 9) { it.italic })+ }++ @Test+ fun `mutate run paragraphs only transforms covered paragraphs`() {+ val doc = docOf(para("p0"), para("p1"), para("p2"))+ val out = doc.mutateRunParagraphs(0, 2, 3, 6) { it.copy(alignment = androidx.compose.ui.text.style.TextAlign.Center) }+ assertNotNull(out)+ val paras = out.content.filterIsInstance<OdfContentBlock.Paragraph>().map { it.paragraph }+ assertEquals(null, paras[0].alignment)+ assertEquals(androidx.compose.ui.text.style.TextAlign.Center, paras[1].alignment)+ assertEquals(androidx.compose.ui.text.style.TextAlign.Center, paras[2].alignment)+ assertEquals(1, doc.runParagraphIndexAt(0, 2, 4))+ }++ // ---- handleListEnter / handleListBackspace ----++ private fun listPara(text: String, level: Int = 1, index: Int = 1) = OdfParagraph(+ listOf(OdfSpan(text)),+ style = ParagraphStyle.LIST_ITEM,+ listType = ListType.NUMBERED,+ listLevel = level,+ listItemIndex = index,+ )++ @Test+ fun `enter in middle of list item splits and renumbers`() {+ val doc = docOf(listPara("first item", index = 1), listPara("second", index = 2))+ val (out, caret) = assertNotNull(doc.handleListEnter(0, 1, 5))+ assertEquals(listOf("first", " item", "second"), texts(out))+ assertEquals(6, caret)+ val styles = out.content.filterIsInstance<OdfContentBlock.Paragraph>().map { it.paragraph.style }+ assertTrue(styles.all { it == ParagraphStyle.LIST_ITEM })+ }++ @Test+ fun `enter on empty list item exits the list`() {+ val doc = docOf(listPara("real", index = 1), listPara("", index = 2))+ val (out, _) = assertNotNull(doc.handleListEnter(0, 1, 5))+ val paras = out.content.filterIsInstance<OdfContentBlock.Paragraph>().map { it.paragraph }+ assertEquals(ParagraphStyle.BODY, paras[1].style)+ assertEquals(0, paras[1].listLevel)+ }++ @Test+ fun `enter at end of heading creates body paragraph`() {+ val doc = docOf(para("Title", ParagraphStyle.HEADING1))+ val (out, _) = assertNotNull(doc.handleListEnter(0, 0, 5))+ assertEquals(listOf("Title", ""), texts(out))+ val paras = out.content.filterIsInstance<OdfContentBlock.Paragraph>().map { it.paragraph }+ assertEquals(ParagraphStyle.BODY, paras[1].style)+ }++ @Test+ fun `backspace at start outdents then exits list`() {+ val nested = docOf(listPara("deep", level = 2))+ val (outdented, _) = assertNotNull(nested.handleListBackspace(0, 0, 0))+ val p1 = (outdented.content[0] as OdfContentBlock.Paragraph).paragraph+ assertEquals(1, p1.listLevel)+ assertEquals(ParagraphStyle.LIST_ITEM, p1.style)++ val top = docOf(listPara("top", level = 1))+ val (exited, _) = assertNotNull(top.handleListBackspace(0, 0, 0))+ val p2 = (exited.content[0] as OdfContentBlock.Paragraph).paragraph+ assertEquals(ParagraphStyle.BODY, p2.style)++ // Not at the start, or not a list item: no smart handling.+ assertNull(top.handleListBackspace(0, 0, 2))+ assertNull(docOf(para("plain")).handleListBackspace(0, 0, 0))+ }++ // ---- links in a run ----++ @Test+ fun `set link in run and find it back`() {+ val doc = docOf(para("click here now"), para("other"))+ val out = assertNotNull(doc.setLinkInRun(0, 1, 6, 10, "here", "https://example.org"))+ assertEquals(listOf("click here now", "other"), texts(out))+ val link = out.linkAt(0, 1, 8)+ assertNotNull(link)+ assertEquals("here", link.text)+ assertEquals("https://example.org", link.url)+ assertEquals(6, link.gStart)+ assertEquals(10, link.gEnd)+ // Caret on plain text finds no link; a link cannot span paragraphs.+ assertNull(out.linkAt(0, 1, 0))+ assertNull(doc.setLinkInRun(0, 1, 6, 16, "x", "https://example.org"))+ }++ @Test+ fun `checkbox toggles round trip`() {+ val doc = docOf(para("task"))+ val asBox = assertNotNull(doc.toggleCheckbox(0))+ val p = (asBox.content[0] as OdfContentBlock.Paragraph).paragraph+ assertEquals(ListType.CHECKBOX, p.listType)+ val checked = assertNotNull(asBox.setCheckboxChecked(0, true))+ assertTrue((checked.content[0] as OdfContentBlock.Paragraph).paragraph.listChecked)+ // Setting checked on a non-checkbox is a no-op.+ assertNull(doc.setCheckboxChecked(0, true))+ val back = assertNotNull(checked.toggleCheckbox(0))+ assertEquals(ParagraphStyle.BODY, (back.content[0] as OdfContentBlock.Paragraph).paragraph.style)+ }+}