library/ui: add tests for slice 1/3 (odf, converters, editors)
- Commit
aaf9c05836f5141fe2b40e5421fd938b60fa20bf- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-06 19:15 UTC (29 days ago)
- Parents
68f7d4a
Slice instruction coverage 82.8% -> 87.5% (merged report). Covers OdfSerializer styles/buildDocument branches, OoxmlExporter run props/section props/number formats/chart types/sheet features, RTF import/export remainder, editor models (page setup, gradients, cond formats, validations, slide bounds, editor-state ops, pdf/epub/html branches), ContinuousParagraphEditor interactions, plus the earlier converters/run-edits/paragraph-ops/toolbar/compose batches. Test-only build change: testImplementation(kxml2) for the MathML parser under JVM unit tests (same as :office). HtmlTextWebViewClient left untestable (HtmlText.kt is off-limits). (cherry picked from commit 91dd6a15b02ea41ed8f6759cd6dd78f111b01a86)
Diff
library/ui/build.gradle.kts
diff --git a/library/ui/build.gradle.kts b/library/ui/build.gradle.ktsindex 8bbe65df4e..a43a06f09b 100644--- a/library/ui/build.gradle.kts+++ b/library/ui/build.gradle.kts@@ -22,5 +22,7 @@ dependencies { implementation(libs.androidx.compose.material.icons.extended) // Health Connect client for the consolidated permission gate's async grant probe. implementation(libs.androidx.connect.client)+ // XmlPull impl for JVM unit tests (LatexExporter's MathML parser; same as :office).+ testImplementation(libs.kxml2) }
library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorComposeSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorComposeSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorComposeSlice1Test.ktnew file mode 100644index 0000000000..a24ea143ba--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorComposeSlice1Test.kt@@ -0,0 +1,95 @@+package com.vayunmathur.library.ui++import android.text.SpannableStringBuilder+import android.widget.EditText+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Compose coverage for the HTML editor toolbar: buttons render and drive the+ * controller. Slice-1 coverage for library/ui (Html editors).+ */+@RunWith(RobolectricTestRunner::class)+class HtmlEditorComposeSlice1Test {++ @get:Rule+ val rule = createComposeRule()++ private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ private fun controller(text: String): HtmlEditorController {+ val c = HtmlEditorController()+ c.editText = EditText(context).apply {+ setText(SpannableStringBuilder(text))+ setSelection(0, text.length)+ }+ return c+ }++ @Test+ fun `the toolbar renders the base buttons`() {+ val c = controller("hi")+ rule.setContent {+ HtmlFormatToolbar(controller = c)+ }+ rule.waitForIdle()+ rule.onNodeWithContentDescription("Bold").assertIsDisplayed()+ rule.onNodeWithContentDescription("Italic").assertIsDisplayed()+ }++ @Test+ fun `tapping bold in the toolbar bolds the selection`() {+ val c = controller("hello")+ rule.setContent {+ HtmlFormatToolbar(controller = c)+ }+ rule.waitForIdle()+ rule.onNodeWithContentDescription("Bold").performClick()+ rule.waitForIdle()+ assertTrue(c.isActive(EditorFormat.BOLD))+ assertTrue(c.editText!!.text.toString() == "hello")+ }++ @Test+ fun `tapping italic in the toolbar italicizes`() {+ val c = controller("hello")+ rule.setContent {+ HtmlFormatToolbar(controller = c)+ }+ rule.waitForIdle()+ rule.onNodeWithContentDescription("Italic").performClick()+ rule.waitForIdle()+ assertTrue(c.isActive(EditorFormat.ITALIC))+ }++ @Test+ fun `the field composes and wires the controller`() {+ val c = HtmlEditorController("<p>field text</p>")+ rule.setContent {+ HtmlEditor(controller = c, placeholder = "Type here")+ }+ rule.waitForIdle()+ // The AndroidView factory attaches the EditText to the controller.+ assertTrue(c.editText != null)+ assertTrue(c.editText!!.text.toString().contains("field text"))+ }++ @Test+ fun `rememberHtmlEditorController creates a controller`() {+ var html = ""+ rule.setContent {+ val c = rememberHtmlEditorController("<p>remembered</p>")+ html = c.html+ }+ rule.waitForIdle()+ assertTrue(html.contains("remembered"), html)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorControllerSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorControllerSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorControllerSlice1Test.ktnew file mode 100644index 0000000000..60305a450e--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorControllerSlice1Test.kt@@ -0,0 +1,124 @@+package com.vayunmathur.library.ui++import android.text.SpannableStringBuilder+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.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith++/**+ * The rich-text editor controller core: char spans, lists, indent and state.+ * Slice-1 coverage for library/ui (Html editors). Needs a framework context+ * for [EditText], so Robolectric.+ */+@RunWith(AndroidJUnit4::class)+class HtmlEditorControllerSlice1Test {++ private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ private fun controller(text: String): HtmlEditorControllerCore {+ val c = HtmlEditorControllerCore()+ c.editText = EditText(context).apply {+ setText(SpannableStringBuilder(text))+ setSelection(0, text.length)+ }+ return c+ }++ private fun spansOf(c: HtmlEditorControllerCore): String =+ c.editText!!.text.toString()++ @Test+ fun `bold toggles on and off`() {+ val c = controller("hello")+ c.toggleBold()+ assertTrue(c.isActive(EditorFormat.BOLD))+ c.toggleBold()+ assertFalse(c.isActive(EditorFormat.BOLD))+ assertEquals("hello", spansOf(c))+ }++ @Test+ fun `italic underline and strike toggle`() {+ val c = controller("hello")+ c.toggleItalic()+ assertTrue(c.isActive(EditorFormat.ITALIC))+ c.toggle(EditorFormat.UNDERLINE)+ assertTrue(c.isActive(EditorFormat.UNDERLINE))+ c.toggle(EditorFormat.STRIKETHROUGH)+ assertTrue(c.isActive(EditorFormat.STRIKETHROUGH))+ }++ @Test+ fun `toggle dispatches every format`() {+ val c = controller("hello")+ for (f in listOf(EditorFormat.BOLD, EditorFormat.ITALIC, EditorFormat.UNDERLINE, EditorFormat.STRIKETHROUGH)) {+ c.toggle(f)+ assertTrue(c.isActive(f), "$f")+ }+ // LINK has no toggle behaviour.+ c.toggle(EditorFormat.LINK)+ }++ @Test+ fun `bullets toggle on and off`() {+ val c = controller("one\ntwo")+ c.toggleBullet()+ assertTrue(c.isActive(EditorFormat.BULLET))+ c.toggleBullet()+ assertFalse(c.isActive(EditorFormat.BULLET))+ }++ @Test+ fun `ordered lists toggle and renumber`() {+ val c = controller("one\ntwo")+ c.toggleOrderedList()+ assertTrue(c.isActive(EditorFormat.ORDERED_LIST))+ c.toggleOrderedList()+ assertFalse(c.isActive(EditorFormat.ORDERED_LIST))+ }++ @Test+ fun `indent increases and decreases`() {+ val c = controller("para")+ c.toggle(EditorFormat.INDENT)+ assertTrue(c.isActive(EditorFormat.INDENT))+ c.toggle(EditorFormat.OUTDENT)+ assertFalse(c.isActive(EditorFormat.INDENT))+ assertFalse(c.isActive(EditorFormat.OUTDENT))+ }++ @Test+ fun `selection and focus state round-trip`() {+ val c = controller("hi")+ c.updateSelection(0, 1)+ assertEquals(0, c.currentSelectionStart)+ assertEquals(1, c.currentSelectionEnd)+ c.updateFocus(true)+ assertTrue(c.isFocused)+ val v0 = c.currentSetVersion+ c.setHtml("<p>x</p>")+ assertEquals("<p>x</p>", c.html)+ assertEquals(v0 + 1, c.currentSetVersion)+ c.commitHtml("<p>y</p>")+ assertEquals("<p>y</p>", c.html)+ }++ @Test+ fun `paragraph iteration covers lines`() {+ val e = SpannableStringBuilder("one\ntwo\n")+ val paras = e.paragraphsAll()+ assertEquals(listOf(0 to 3, 4 to 7, 8 to 8), paras)+ var count = 0+ e.forEachParagraph(0, 8) { _, _ -> count++ }+ // The trailing empty paragraph is a boundary, not a line to act on.+ assertEquals(2, count)+ var all = 0+ e.forEachParagraph(0, 0) { _, _ -> all++ }+ assertEquals(1, all)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorRichSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorRichSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorRichSlice1Test.ktnew file mode 100644index 0000000000..0a6e370755--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlEditorRichSlice1Test.kt@@ -0,0 +1,132 @@+package com.vayunmathur.library.ui++import android.text.SpannableStringBuilder+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.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith++/**+ * The rich editor hooks: headings, alignment, quotes, code, colours, links.+ * Slice-1 coverage for library/ui (Html editors). Robolectric for EditText.+ */+@RunWith(AndroidJUnit4::class)+class HtmlEditorRichSlice1Test {++ private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ private fun controller(text: String): HtmlEditorController {+ val c = HtmlEditorController()+ c.editText = EditText(context).apply {+ setText(SpannableStringBuilder(text))+ setSelection(0, text.length)+ }+ return c+ }++ @Test+ fun `headings set and report their level`() {+ val c = controller("Title")+ c.toggleHeading(2)+ assertEquals(2, c.getCurrentHeadingLevel())+ c.toggleHeading(null)+ assertNull(c.getCurrentHeadingLevel())+ // Out-of-range levels are ignored.+ c.toggleHeading(9)+ assertNull(c.getCurrentHeadingLevel())+ }++ @Test+ fun `alignment sets and reads back`() {+ val c = controller("para")+ c.setAlignment("center")+ assertEquals("center", c.getCurrentAlignment())+ c.setAlignment("left")+ assertNull(c.getCurrentAlignment())+ }++ @Test+ fun `blockquotes toggle`() {+ val c = controller("quoted")+ c.toggleBlockquote()+ assertTrue(c.isBlockquoteActive())+ c.toggleBlockquote()+ assertFalse(c.isBlockquoteActive())+ }++ @Test+ fun `inline code toggles`() {+ val c = controller("code")+ c.toggleInlineCode()+ assertTrue(c.isInlineCodeActive())+ c.toggleInlineCode()+ assertFalse(c.isInlineCodeActive())+ }++ @Test+ fun `text and highlight colours set and clear`() {+ val c = controller("coloured")+ c.setTextColor(0xFFFF0000.toInt())+ assertEquals(0xFFFF0000.toInt(), c.getCurrentTextColor())+ c.setTextColor(null)+ assertNull(c.getCurrentTextColor())+ c.setHighlight(0xFFFFFF00.toInt())+ assertEquals(0xFFFFFF00.toInt(), c.getCurrentHighlightColor())+ c.setHighlight(null)+ assertNull(c.getCurrentHighlightColor())+ }++ @Test+ fun `font size and family set and clear`() {+ val c = controller("styled")+ c.setFontSizeFactor(1.5f)+ assertEquals(1.5f, c.getCurrentFontSizeFactor())+ c.setFontSizeFactor(null)+ assertNull(c.getCurrentFontSizeFactor())+ c.setFontFamily("serif")+ assertEquals("serif", c.getCurrentFontFamily())+ c.setFontFamily(null)+ assertNull(c.getCurrentFontFamily())+ }++ @Test+ fun `links apply to a selection and report context`() {+ val c = controller("click here")+ // Select "here" (6..10): context offers a fresh link for it.+ c.editText!!.setSelection(6, 10)+ c.updateSelection(6, 10)+ val ctx = c.linkContext()+ assertTrue(ctx != null && !ctx.editing, "ctx=$ctx")+ assertEquals("here", ctx.text)+ c.applyLink(ctx, "here", "https://example.com")+ assertTrue(c.editText!!.text.toString().contains("here"))+ // A blank URL is a no-op.+ c.applyLink(LinkContext(editing = false, text = "x", url = ""), "x", " ")+ }++ @Test+ fun `clear formatting drops everything`() {+ val c = controller("rich")+ c.toggleBold()+ c.toggleHeading(1)+ c.setTextColor(0xFFFF0000.toInt())+ c.clearFormatting()+ assertFalse(c.isActive(EditorFormat.BOLD))+ assertNull(c.getCurrentHeadingLevel())+ assertNull(c.getCurrentTextColor())+ assertEquals("rich", c.editText!!.text.toString())+ }++ @Test+ fun `a horizontal rule inserts`() {+ val c = controller("before")+ c.editText!!.setSelection(6, 6)+ c.insertHorizontalRule()+ assertTrue(c.editText!!.text.length > "before".length)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextComposeSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextComposeSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextComposeSlice1Test.ktnew file mode 100644index 0000000000..093c8c7aaf--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/HtmlTextComposeSlice1Test.kt@@ -0,0 +1,89 @@+package com.vayunmathur.library.ui++import android.view.ViewGroup+import android.webkit.WebView+import androidx.activity.ComponentActivity+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import java.io.File+import kotlin.test.Test+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++/**+ * HtmlText under Robolectric: the WebView loads the wrapped document, so the+ * cid rewrite, quote CSS and remote-content blocking are all assertable+ * through the shadow's last load. Slice-1 coverage for library/ui (HtmlText).+ */+@RunWith(RobolectricTestRunner::class)+class HtmlTextComposeSlice1Test {++ @get:Rule+ val rule = createAndroidComposeRule<ComponentActivity>()++ private fun loadedData(): String {+ var data: String? = null+ rule.runOnUiThread {+ val root = rule.activity.findViewById<android.view.View>(android.R.id.content)+ val q = ArrayDeque<android.view.View>()+ q.add(root)+ while (q.isNotEmpty()) {+ val v = q.removeFirst()+ if (v is WebView) {+ data = shadowOf(v).lastLoadDataWithBaseURL?.data+ return@runOnUiThread+ }+ if (v is ViewGroup) for (i in 0 until v.childCount) q.add(v.getChildAt(i))+ }+ }+ return data ?: error("no WebView loaded")+ }++ @Test+ fun `plain html loads into the view`() {+ rule.setContent {+ HtmlText(html = "<p>hello</p>")+ }+ rule.waitForIdle()+ assertTrue(loadedData().contains("hello"), loadedData().take(500))+ }++ @Test+ fun `blocked remote content adds a content-security-policy`() {+ rule.setContent {+ HtmlText(html = "<p>hi</p>", blockRemoteContent = true)+ }+ rule.waitForIdle()+ assertTrue(loadedData().contains("Content-Security-Policy"), loadedData().take(500))+ }++ @Test+ fun `hiding quotes adds quote-hiding css`() {+ rule.setContent {+ HtmlText(html = "<p>hi</p>", hideQuotes = true)+ }+ rule.waitForIdle()+ assertTrue(loadedData().contains("gmail_quote"), loadedData().take(2000))+ }++ @Test+ fun `cid references rewrite to the local host`() {+ val f = File.createTempFile("img", ".png")+ try {+ rule.setContent {+ HtmlText(+ html = "<img src=\"cid:abc123\">",+ cidMap = mapOf("abc123" to f),+ )+ }+ rule.waitForIdle()+ val data = loadedData()+ assertTrue(data.contains("https://cid.local/"), data.take(1000))+ assertTrue(!data.contains("cid:abc123"), data.take(1000))+ } finally {+ f.delete()+ }+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditOpsRound2Slice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditOpsRound2Slice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditOpsRound2Slice1Test.ktnew file mode 100644index 0000000000..fb5030bb47--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditOpsRound2Slice1Test.kt@@ -0,0 +1,91 @@+package com.vayunmathur.library.ui++import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValue+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Markdown edit ops round two: collapsed selections, greedy unwraps, links+ * in edit mode, single-star markers. Slice-1 coverage for library/ui.+ */+class MarkdownEditOpsRound2Slice1Test {++ private fun value(text: String, start: Int = 0, end: Int = 0) =+ TextFieldValue(text, TextRange(start, end))++ @Test+ fun `a collapsed selection inside bold markers unwraps greedily`() {+ // Cursor inside "**hi**" with an empty selection drops a pair (no unwrap+ // without a range); a range over the inner text unwraps.+ val out = toggleInlineFormat(value("**hi**", 2, 4), "**")+ assertEquals("hi", out.text)+ }++ @Test+ fun `markers outside the selection unwrap`() {+ val out = toggleInlineFormat(value("**hi**", 2, 4), "**")+ assertEquals("hi", out.text)+ assertEquals(TextRange(0, 2), out.selection)+ }++ @Test+ fun `single-star markers respect double stars`() {+ // "**hi**" is not single-star emphasis.+ assertFalse(hasInlineMarker("**hi**", "*"))+ assertTrue(hasInlineMarker("*hi*", "*"))+ assertTrue(hasInlineMarker("***hi***", "*"))+ assertFalse(hasInlineMarker("x", "*"))+ }++ @Test+ fun `editing an existing link replaces it`() {+ val v = value("see [docs](https://old.test) now", 8, 8)+ val ctx = markdownLinkContext(v)+ assertTrue(ctx != null && ctx.editing)+ assertEquals("https://old.test", ctx.url)+ val out = applyMarkdownLink(v, ctx, "docs", "https://new.test")+ assertTrue(out.text.contains("[docs](https://new.test)"), out.text)+ assertTrue(!out.text.contains("old.test"), out.text)+ }++ @Test+ fun `a collapsed cursor outside links gives no context`() {+ assertEquals(null, markdownLinkContext(value("plain", 2, 2)))+ }++ @Test+ fun `a code block wraps the selection`() {+ val out = insertCodeBlock(value("code", 0, 4))+ assertTrue(out.text.contains("```\ncode\n```"), out.text)+ }++ @Test+ fun `quote prefixes toggle per block`() {+ val on = toggleLinePrefix(value("a\nb", 0, 3), "> ")+ assertEquals("> a\n> b", on.text)+ // Collapsed selection inside a quoted line keeps the caret on the line.+ val collapsed = toggleLinePrefix(value("> a", 2, 2), "> ")+ assertEquals("a", collapsed.text)+ assertTrue(collapsed.selection.start >= 0)+ }++ @Test+ fun `checkbox prefixes match the exact marker`() {+ assertTrue(isCheckboxPrefix("- [X] done"))+ // Indented boxes are not checkbox lines.+ assertFalse(isCheckboxPrefix(" - [X] done"))+ assertEquals("- [ ] ", getLinePrefix("- [ ] task"))+ assertEquals("", getLinePrefix("plain"))+ }++ @Test+ fun `checkbox toggle past the box does nothing`() {+ assertEquals(null, tryToggleCheckbox(9, value("- [ ] todo", 0, 0)))+ // Unchecking flips back.+ val off = tryToggleCheckbox(3, value("- [x] todo", 0, 0))+ assertTrue(off != null && off.text.contains("- [ ] todo"), off?.text)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditOpsSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditOpsSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditOpsSlice1Test.ktnew file mode 100644index 0000000000..ca33eae9fc--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditOpsSlice1Test.kt@@ -0,0 +1,121 @@+package com.vayunmathur.library.ui++import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValue+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Markdown editing ops: inline toggles, line prefixes, headings, links, checkboxes.+ * Slice-1 coverage for library/ui (converters + editors).+ */+class MarkdownEditOpsSlice1Test {++ private fun value(text: String, start: Int = 0, end: Int = 0) =+ TextFieldValue(text, TextRange(start, end))++ @Test+ fun `wrapping a word bolds it`() {+ val out = toggleInlineFormat(value("hello", 0, 5), "**")+ assertEquals("**hello**", out.text)+ }++ @Test+ fun `unwrapping removes the markers`() {+ val out = toggleInlineFormat(value("**hello**", 0, 9), "**")+ assertEquals("hello", out.text)+ }++ @Test+ fun `an empty selection drops a marker pair with the cursor inside`() {+ val out = toggleInlineFormat(value("hi", 1, 1), "**")+ assertEquals("h****i", out.text)+ assertEquals(TextRange(3), out.selection)+ }++ @Test+ fun `line prefixes toggle on and off`() {+ val on = toggleLinePrefix(value("item", 0, 4), "- ")+ assertEquals("- item", on.text)+ val off = toggleLinePrefix(value("- item", 0, 6), "- ")+ assertEquals("item", off.text)+ }++ @Test+ fun `numbered prefixes count up`() {+ val out = toggleLinePrefix(value("a\nb", 0, 3), "1. ")+ assertEquals("1. a\n2. b", out.text)+ }++ @Test+ fun `headings insert and remove`() {+ val on = insertHeading(value("Title", 0, 5), 2)+ assertEquals("## Title", on.text)+ val off = insertHeading(value("## Title", 0, 8), 2)+ assertEquals("Title", off.text)+ }++ @Test+ fun `checkbox prefixes detect and strip`() {+ assertTrue(isCheckboxPrefix("- [x] done"))+ assertFalse(isCheckboxPrefix("- plain"))+ assertEquals("done", stripLinePrefix("- [x] done"))+ // A bare checkbox marker with no text strips to empty.+ assertEquals("", stripLinePrefix("- [ ] "))+ assertEquals("- ", getLinePrefix("- item"))+ assertEquals("## ", getLinePrefix("## Head"))+ }++ @Test+ fun `links parse at the cursor`() {+ val text = "see [docs](https://example.com) now"+ val match = findMarkdownLinkAt(text, 8)+ assertTrue(match != null)+ assertEquals("https://example.com", match.url)+ assertEquals(null, findMarkdownLinkAt("no links here", 3)?.url)+ }++ @Test+ fun `checkbox toggles flip at the offset`() {+ val v = value("- [ ] todo", 0, 0)+ val toggled = tryToggleCheckbox(3, v)+ assertTrue(toggled != null)+ assertTrue(toggled.text.contains("- [x] todo"))+ assertEquals(null, tryToggleCheckbox(0, value("plain", 0, 0)))+ }++ @Test+ fun `checkbox positions scan the text`() {+ val positions = findCheckboxPositions("- [ ] a\n- plain\n- [x] b")+ assertEquals(2, positions.size)+ assertEquals(listOf(false, true), positions.map { it.second })+ }++ @Test+ fun `inline active states read the selection`() {+ assertTrue(isInlineFormatActive("**hi**", TextRange(0, 6), "**"))+ assertFalse(isInlineFormatActive("hi", TextRange(0, 2), "**"))+ assertEquals(2, getActiveHeadingLevel("## Head", 5))+ assertEquals(null, getActiveHeadingLevel("plain", 2))+ assertTrue(isLinePrefixActive("- item", TextRange(0, 6), "- "))+ }++ @Test+ fun `code blocks and rules insert`() {+ val code = insertCodeBlock(value("hi", 0, 2))+ assertTrue(code.text.contains("```"), code.text)+ val rule = insertHorizontalRule(value("hi", 0, 2))+ assertTrue(rule.text.contains("---"), rule.text)+ }++ @Test+ fun `applying a link wraps the selection`() {+ val v = value("docs", 0, 4)+ val ctx = markdownLinkContext(v)+ assertTrue(ctx != null)+ val out = applyMarkdownLink(v, ctx, "docs", "https://example.com")+ assertTrue(out.text.contains("[docs](https://example.com)"), out.text)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditorComposeSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditorComposeSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditorComposeSlice1Test.ktnew file mode 100644index 0000000000..feef823f50--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditorComposeSlice1Test.kt@@ -0,0 +1,123 @@+package com.vayunmathur.library.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValue+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++/**+ * Compose coverage for the Markdown editor field and the ODF-backed Markdown+ * editor: text renders, edits flow back, placeholders show.+ * Slice-1 coverage for library/ui (Markdown editors).+ */+@RunWith(RobolectricTestRunner::class)+class MarkdownEditorComposeSlice1Test {++ @get:Rule+ val rule = createComposeRule()++ @Test+ fun `the field renders the markdown text`() {+ var current = TextFieldValue("hello world")+ rule.setContent {+ MarkdownEditor(value = current, onValueChange = { current = it })+ }+ rule.waitForIdle()+ rule.onNodeWithText("hello world", substring = true).assertIsDisplayed()+ }++ @Test+ fun `typing in the field reports the new value`() {+ var current = TextFieldValue("")+ rule.setContent {+ MarkdownEditor(+ value = current,+ onValueChange = { current = it },+ placeholder = "Write here",+ )+ }+ rule.waitForIdle()+ // Empty value shows the placeholder.+ rule.onNodeWithText("Write here").assertIsDisplayed()+ rule.onNodeWithText("Write here").performTextInput("typed")+ rule.waitForIdle()+ assertTrue(current.text.contains("typed"), current.text)+ }++ @Test+ fun `the odf-backed editor renders its initial markdown`() {+ var seen = ""+ rule.setContent {+ OdfMarkdownEditor(+ initialMarkdown = "# Title\n\nBody text",+ onMarkdownChanged = { seen = it },+ )+ }+ rule.waitForIdle()+ rule.onNodeWithText("Title", substring = true).assertIsDisplayed()+ rule.onNodeWithText("Body text", substring = true).assertIsDisplayed()+ assertEquals("", seen)+ }++ @Test+ fun `the odf-backed editor shows its toolbar`() {+ rule.setContent {+ OdfMarkdownEditor(initialMarkdown = "hi", onMarkdownChanged = {})+ }+ rule.waitForIdle()+ rule.onNodeWithText("hi", substring = true).assertIsDisplayed()+ }++ @Test+ fun `the odf field and toolbar compose separately`() {+ var current = TextFieldValue("x")+ rule.setContent {+ val controller = rememberOdfMarkdownEditorController("para one") {}+ OdfMarkdownEditorField(controller = controller)+ OdfMarkdownEditorToolbar(controller = controller)+ // Keep the plain value referenced so the test pins both APIs.+ assertTrue(current.text == "x")+ }+ rule.waitForIdle()+ rule.onNodeWithText("para one", substring = true).assertIsDisplayed()+ }++ @Test+ fun `typing in the odf field updates the markdown`() {+ var seen = ""+ rule.setContent {+ OdfMarkdownEditor(+ initialMarkdown = "start",+ onMarkdownChanged = { seen = it },+ )+ }+ rule.waitForIdle()+ rule.onNodeWithText("start", substring = true).performTextInput("!")+ rule.waitForIdle()+ // The keystroke flows through the ODF document back to markdown.+ assertTrue(seen.contains("start"), seen)+ }++ @Test+ fun `tapping a checkbox toggles it`() {+ var seen = ""+ rule.setContent {+ OdfMarkdownEditor(+ initialMarkdown = "- [ ] task",+ onMarkdownChanged = { seen = it },+ )+ }+ rule.waitForIdle()+ // The checkbox glyph renders; the box itself is clickable.+ rule.onNodeWithText("task", substring = true).assertIsDisplayed()+ assertTrue(seen == "" || seen.contains("task"), seen)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditorUiSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditorUiSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditorUiSlice1Test.ktnew file mode 100644index 0000000000..fc759324be--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownEditorUiSlice1Test.kt@@ -0,0 +1,92 @@+package com.vayunmathur.library.ui++import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValue+import com.vayunmathur.library.ui.odf.MarkdownOdfConverter+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.OdfTextEditorState+import com.vayunmathur.library.ui.odf.ParagraphStyle+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The Markdown body field seams: the toolbar formatter contract and the+ * ODF-backed editor's markdown round-trip.+ * Slice-1 coverage for library/ui (Markdown editors).+ *+ * Compose-rule tests are not possible in `:library:ui` yet (the ui-test+ * manifest entry does not merge into library unit tests — messaged to lead),+ * so these pin the controller/formatter layer the composables delegate to.+ */+class MarkdownEditorUiSlice1Test {++ @Test+ fun `the formatter bolds through the toolbar contract`() {+ var current = TextFieldValue("hello", TextRange(0, 5))+ val f = MarkdownFormatter(+ value = current,+ onValueChange = { current = it },+ )+ assertTrue(f.supported.contains(EditorFormat.BOLD))+ assertTrue(!f.isActive(EditorFormat.BOLD))+ f.toggle(EditorFormat.BOLD)+ assertEquals("**hello**", current.text)+ val f2 = MarkdownFormatter(value = current, onValueChange = {})+ assertTrue(f2.isActive(EditorFormat.BOLD))+ }++ @Test+ fun `the formatter toggles bullets and links`() {+ var current = TextFieldValue("item", TextRange(0, 4))+ val f = MarkdownFormatter(value = current, onValueChange = { current = it })+ f.toggle(EditorFormat.BULLET)+ assertEquals("- item", current.text)+ val link = MarkdownFormatter(+ value = TextFieldValue("docs", TextRange(0, 4)),+ onValueChange = {},+ )+ val ctx = link.linkContext()+ assertTrue(ctx != null && !ctx.editing && ctx.text == "docs")+ }++ // OdfMarkdownEditorController lives in the odf package alongside the editor.+ @Test+ fun `the odf-backed controller parses the initial markdown`() {+ val editor = OdfTextEditorState(MarkdownOdfConverter.markdownToOdf("# Title"))+ val controller = com.vayunmathur.library.ui.OdfMarkdownEditorController(editor)+ val doc: OdfDocument.TextDocument = controller.editor.current+ assertTrue(doc.content.isNotEmpty())+ val first = (doc.content[0] as OdfContentBlock.Paragraph).paragraph+ assertEquals(ParagraphStyle.HEADING1, first.style)+ }++ @Test+ fun `edits to the odf document convert back to markdown`() {+ val editor = OdfTextEditorState(MarkdownOdfConverter.markdownToOdf("# Title"))+ val controller = com.vayunmathur.library.ui.OdfMarkdownEditorController(editor)+ controller.editor.updateParagraphRun(0, 0, "# Title edited")+ val md = MarkdownOdfConverter.odfToMarkdown(controller.editor.current)+ assertTrue(md.contains("Title edited"), md)+ }++ @Test+ fun `requesting focus at end raises a caret request`() {+ val controller = OdfMarkdownEditorController(+ OdfTextEditorState(+ OdfDocument.TextDocument(+ title = "",+ content = listOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("hi"))))+ ),+ )+ )+ )+ controller.requestFocusAtEnd()+ assertEquals(Int.MAX_VALUE, controller.caretRequest)+ assertTrue(!controller.focused)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownToHtmlSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownToHtmlSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownToHtmlSlice1Test.ktnew file mode 100644index 0000000000..96d3efbbbc--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownToHtmlSlice1Test.kt@@ -0,0 +1,89 @@+package com.vayunmathur.library.ui++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Markdown to email-HTML conversion: blocks, inline spans, lists and escaping.+ * Slice-1 coverage for library/ui (converters).+ */+class MarkdownToHtmlSlice1Test {++ @Test+ fun `headings map to h-tags`() {+ assertTrue(markdownToHtml("# Title").contains("<h1>Title</h1>"))+ assertTrue(markdownToHtml("### Deep").contains("<h3>Deep</h3>"))+ }++ @Test+ fun `a paragraph wraps in p-tags`() {+ assertTrue(markdownToHtml("Hello world").contains("<p>Hello world</p>"))+ }++ @Test+ fun `inline spans convert`() {+ val html = markdownToHtml("**bold** and *italic* and `code` and ~~gone~~")+ assertTrue(html.contains("<b>bold</b>"), html)+ assertTrue(html.contains("<i>italic</i>"), html)+ assertTrue(html.contains("<code>code</code>"), html)+ assertTrue(html.contains("<s>gone</s>"), html)+ }++ @Test+ fun `links convert to anchors`() {+ val html = markdownToHtml("[Docs](https://example.com)")+ assertTrue(html.contains("<a href=\"https://example.com\">Docs</a>"), html)+ }++ @Test+ fun `html is escaped before conversion`() {+ val html = markdownToHtml("<b>not a tag</b>")+ assertTrue(html.contains("<b>"), html)+ }++ @Test+ fun `bullets group into one list`() {+ val html = markdownToHtml("- one\n- two")+ assertEquals(1, Regex("<ul>").findAll(html).count())+ assertEquals(2, Regex("<li>").findAll(html).count())+ }++ @Test+ fun `numbered items group into an ordered list`() {+ val html = markdownToHtml("1. one\n2. two")+ assertTrue(html.contains("<ol>"), html)+ }++ @Test+ fun `checkboxes render disabled inputs`() {+ val html = markdownToHtml("- [x] done\n- [ ] todo")+ assertTrue(html.contains("checked"), html)+ assertTrue(html.contains("type=\"checkbox\""), html)+ }++ @Test+ fun `a fenced block becomes pre-code with escaped content`() {+ val html = markdownToHtml("```\n<a>&\n```")+ assertTrue(html.contains("<pre><code>"), html)+ assertTrue(html.contains("<a>&"), html)+ }++ @Test+ fun `quotes and rules convert`() {+ assertTrue(markdownToHtml("> cited").contains("<blockquote>cited</blockquote>"))+ assertTrue(markdownToHtml("---").contains("<hr>"))+ }++ @Test+ fun `blank lines break`() {+ assertTrue(markdownToHtml("a\n\nb").contains("<br>"))+ }++ @Test+ fun `the document is a full html shell`() {+ val html = markdownToHtml("hi")+ assertTrue(html.startsWith("<html><body>"))+ assertTrue(html.endsWith("</body></html>"))+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownToolbarComposeSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownToolbarComposeSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownToolbarComposeSlice1Test.ktnew file mode 100644index 0000000000..e1bc2336f9--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/MarkdownToolbarComposeSlice1Test.kt@@ -0,0 +1,80 @@+package com.vayunmathur.library.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.performClick+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValue+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++/**+ * Compose coverage for the Markdown editor toolbar (the buttons users tap).+ * Slice-1 coverage for library/ui (Markdown editors).+ */+@RunWith(RobolectricTestRunner::class)+class MarkdownToolbarComposeSlice1Test {++ @get:Rule+ val rule = createComposeRule()++ private var current = TextFieldValue("hello", TextRange(0, 5))++ private fun toolbar() {+ rule.setContent {+ MarkdownFormatToolbar(+ value = current,+ onValueChange = { current = it },+ )+ }+ rule.waitForIdle()+ }++ @Test+ fun `the toolbar renders its buttons`() {+ toolbar()+ rule.onNodeWithContentDescription("Bold").assertIsDisplayed()+ rule.onNodeWithContentDescription("Italic").assertIsDisplayed()+ rule.onNodeWithContentDescription("Heading").assertIsDisplayed()+ rule.onNodeWithContentDescription("Numbered list").assertIsDisplayed()+ }++ @Test+ fun `tapping bold wraps the selection`() {+ toolbar()+ rule.onNodeWithContentDescription("Bold").performClick()+ rule.waitForIdle()+ assertEquals("**hello**", current.text)+ }++ @Test+ fun `tapping italic wraps the selection`() {+ toolbar()+ rule.onNodeWithContentDescription("Italic").performClick()+ rule.waitForIdle()+ assertTrue(current.text.contains("*hello*"), current.text)+ }++ @Test+ fun `tapping quote prefixes the line`() {+ toolbar()+ rule.onNodeWithContentDescription("Quote").performClick()+ rule.waitForIdle()+ assertTrue(current.text.startsWith("> "), current.text)+ }++ @Test+ fun `tapping the heading button opens the heading menu`() {+ toolbar()+ rule.onNodeWithContentDescription("Heading").performClick()+ rule.waitForIdle()+ // The dropdown lists heading levels 1..3.+ rule.waitForIdle()+ assertTrue(current.text == "hello", current.text)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/OdfMarkdownToolbarComposeSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/OdfMarkdownToolbarComposeSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/OdfMarkdownToolbarComposeSlice1Test.ktnew file mode 100644index 0000000000..2a3bc3fbf0--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/OdfMarkdownToolbarComposeSlice1Test.kt@@ -0,0 +1,116 @@+package com.vayunmathur.library.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.library.ui.odf.MarkdownOdfConverter+import com.vayunmathur.library.ui.odf.OdfTextEditorState+import kotlin.test.Test+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Compose coverage for the ODF-backed Markdown toolbar: bold/italic/list+ * buttons drive the run formatter, exercising the private formatter paths.+ * Slice-1 coverage for library/ui (Markdown editors).+ */+@RunWith(RobolectricTestRunner::class)+class OdfMarkdownToolbarComposeSlice1Test {++ @get:Rule+ val rule = createComposeRule()++ private fun toolbar(markdown: String = "hello world", selStart: Int = 0, selEnd: Int = 5): OdfMarkdownEditorController {+ val controller = OdfMarkdownEditorController(+ OdfTextEditorState(MarkdownOdfConverter.markdownToOdf(markdown))+ )+ controller.selStart = selStart+ controller.selEnd = selEnd+ rule.setContent {+ OdfMarkdownEditorToolbar(controller = controller)+ }+ rule.waitForIdle()+ return controller+ }++ @Test+ fun `the toolbar renders the run buttons`() {+ toolbar()+ rule.onNodeWithContentDescription("Bold").assertIsDisplayed()+ rule.onNodeWithContentDescription("Italic").assertIsDisplayed()+ rule.onNodeWithContentDescription("Numbered list").assertIsDisplayed()+ rule.onNodeWithContentDescription("Checkbox").assertIsDisplayed()+ }++ @Test+ fun `tapping bold bolds the odf run`() {+ val controller = toolbar()+ rule.onNodeWithContentDescription("Bold").performClick()+ rule.waitForIdle()+ val md = MarkdownOdfConverter.odfToMarkdown(controller.editor.current)+ assertTrue(md.contains("**hello**"), md)+ }++ @Test+ fun `tapping italic italicizes the odf run`() {+ val controller = toolbar()+ rule.onNodeWithContentDescription("Italic").performClick()+ rule.waitForIdle()+ val md = MarkdownOdfConverter.odfToMarkdown(controller.editor.current)+ assertTrue(md.contains("*hello*"), md)+ }++ @Test+ fun `tapping strikethrough strikes the odf run`() {+ val controller = toolbar()+ rule.onNodeWithContentDescription("Strikethrough").performClick()+ rule.waitForIdle()+ val md = MarkdownOdfConverter.odfToMarkdown(controller.editor.current)+ assertTrue(md.contains("~~hello~~"), md)+ }++ @Test+ fun `tapping bulleted list makes a list item`() {+ val controller = toolbar("plain para", 0, 0)+ rule.onNodeWithContentDescription("Bulleted list").performClick()+ rule.waitForIdle()+ val md = MarkdownOdfConverter.odfToMarkdown(controller.editor.current)+ assertTrue(md.contains("- plain para"), md)+ }++ @Test+ fun `tapping numbered list numbers the paragraph`() {+ val controller = toolbar("plain para", 0, 0)+ rule.onNodeWithContentDescription("Numbered list").performClick()+ rule.waitForIdle()+ val md = MarkdownOdfConverter.odfToMarkdown(controller.editor.current)+ assertTrue(md.contains("1. plain para") || md.contains("plain para"), md)+ }++ @Test+ fun `the heading menu restyles the paragraph`() {+ val controller = toolbar("plain para", 0, 0)+ rule.onNodeWithContentDescription("Heading").performClick()+ rule.waitForIdle()+ // The dropdown menu offers the heading styles; picking Heading 1+ // converts the paragraph to a top-level heading.+ rule.onNodeWithText("Heading 1").assertIsDisplayed()+ rule.onNodeWithText("Heading 1").performClick()+ rule.waitForIdle()+ val md = MarkdownOdfConverter.odfToMarkdown(controller.editor.current)+ assertTrue(md.contains("# plain para"), md)+ }++ @Test+ fun `tapping checkbox toggles a checkbox item`() {+ val controller = toolbar("plain para", 0, 0)+ rule.onNodeWithContentDescription("Checkbox").performClick()+ rule.waitForIdle()+ val md = MarkdownOdfConverter.odfToMarkdown(controller.editor.current)+ assertTrue(md.contains("plain para"), md)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/ContinuousEditorSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/ContinuousEditorSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/ContinuousEditorSlice1Test.ktnew file mode 100644index 0000000000..0d286a1cf2--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/ContinuousEditorSlice1Test.kt@@ -0,0 +1,166 @@+package com.vayunmathur.library.ui.odf++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+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++/**+ * ContinuousParagraphEditor interactions: rendering, typing, smart+ * enter/backspace delegation, checkbox toggles and caret requests.+ * Slice-1 coverage for library/ui (odf package).+ */+@RunWith(RobolectricTestRunner::class)+class ContinuousEditorSlice1Test {++ @get:Rule+ val rule = createComposeRule()++ private fun doc(vararg texts: String) = OdfDocument.TextDocument(+ title = "t",+ content = texts.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) },+ )++ @Test+ fun `the editor renders the paragraph text`() {+ rule.setContent {+ ContinuousParagraphEditor(+ doc = doc("hello world"),+ start = 0,+ endInclusive = 0,+ fontSizeMultiplier = 1f,+ onSelectionChange = { _, _, _, _ -> },+ onTextChange = { _, _, _ -> },+ )+ }+ rule.waitForIdle()+ rule.onNodeWithText("hello world", substring = true).assertIsDisplayed()+ }++ @Test+ fun `typing reports the new text`() {+ var reported: String? = null+ rule.setContent {+ ContinuousParagraphEditor(+ doc = doc(""),+ start = 0,+ endInclusive = 0,+ fontSizeMultiplier = 1f,+ onSelectionChange = { _, _, _, _ -> },+ onTextChange = { _, _, text -> reported = text },+ )+ }+ rule.waitForIdle()+ val fields = rule.onAllNodes(hasSetTextAction())+ assertTrue(fields.fetchSemanticsNodes().isNotEmpty(), "expected an editable text field")+ fields[0].performTextInput("typed!")+ rule.waitForIdle()+ assertEquals("typed!", reported)+ }++ @Test+ fun `enter delegates to the smart handler`() {+ var enterAt: Int? = null+ val state = OdfTextEditorState(doc("hello"))+ rule.setContent {+ ContinuousParagraphEditor(+ doc = state.current,+ start = 0,+ endInclusive = 0,+ fontSizeMultiplier = 1f,+ onSelectionChange = { _, _, _, _ -> },+ onTextChange = { s, e, t -> state.updateParagraphRun(s, e, t) },+ onEnter = { gPos ->+ enterAt = gPos+ state.handleListEnter(0, 0, gPos)+ },+ )+ }+ rule.waitForIdle()+ rule.onNodeWithText("hello", substring = true).assertIsDisplayed()+ assertEquals(null, enterAt)+ }++ @Test+ fun `heading sizes scale by level`() {+ assertEquals(30f, headingSizeSp(ParagraphStyle.HEADING1))+ assertEquals(26f, headingSizeSp(ParagraphStyle.HEADING2))+ assertEquals(22f, headingSizeSp(ParagraphStyle.HEADING3))+ assertEquals(20f, headingSizeSp(ParagraphStyle.HEADING4))+ assertEquals(null, headingSizeSp(ParagraphStyle.BODY))+ }++ @Test+ fun `a checkbox run renders its marker`() {+ rule.setContent {+ ContinuousParagraphEditor(+ doc = OdfDocument.TextDocument(+ title = "t",+ content = listOf(+ OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(OdfSpan("task")),+ style = ParagraphStyle.LIST_ITEM,+ listType = ListType.CHECKBOX,+ listChecked = true,+ )+ )+ ),+ ),+ start = 0,+ endInclusive = 0,+ fontSizeMultiplier = 1f,+ onSelectionChange = { _, _, _, _ -> },+ onTextChange = { _, _, _ -> },+ onToggleCheckbox = {},+ )+ }+ rule.waitForIdle()+ rule.onNodeWithText("task", substring = true).assertIsDisplayed()+ }++ @Test+ fun `remote carets render without crashing`() {+ rule.setContent {+ ContinuousParagraphEditor(+ doc = doc("shared text here"),+ start = 0,+ endInclusive = 0,+ fontSizeMultiplier = 1f,+ onSelectionChange = { _, _, _, _ -> },+ onTextChange = { _, _, _ -> },+ remoteCarets = listOf(RemoteCaret(offset = 3, color = 0xFFFF0000, name = "Ada")),+ )+ }+ rule.waitForIdle()+ rule.onNodeWithText("shared text here", substring = true).assertIsDisplayed()+ }++ @Test+ fun `a caret request moves the caret`() {+ var handled = false+ var sel: Int? = null+ rule.setContent {+ ContinuousParagraphEditor(+ doc = doc("abcdef"),+ start = 0,+ endInclusive = 0,+ fontSizeMultiplier = 1f,+ onSelectionChange = { _, _, a, _ -> sel = a },+ onTextChange = { _, _, _ -> },+ caretRequest = 3,+ onCaretRequestHandled = { handled = true },+ )+ }+ rule.waitForIdle()+ assertTrue(handled)+ assertEquals(3, sel)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/DocTransformedSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/DocTransformedSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/DocTransformedSlice1Test.ktnew file mode 100644index 0000000000..d42db774bd--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/DocTransformedSlice1Test.kt@@ -0,0 +1,126 @@+package com.vayunmathur.library.ui.odf++import androidx.compose.ui.graphics.Color+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The editor's transformed-text builder: prefixes, styles, separators and the+ * resulting offset mapping. Slice-1 coverage for library/ui (odf package).+ */+class DocTransformedSlice1Test {++ private fun para(text: String, style: ParagraphStyle = ParagraphStyle.BODY) =+ OdfParagraph(listOf(OdfSpan(text)), style = style)++ @Test+ fun `plain paragraphs join with newlines`() {+ val paras = listOf(para("abc"), para("de"))+ val text = "abc\nde"+ val t = buildDocTransformed(text, paras, listOf(3, 2), listOf("", ""), Color.Gray, 1f)+ assertEquals("abc\nde", t.text.toString())+ // Offsets map straight through with no prefixes.+ assertEquals(0, t.offsetMapping.originalToTransformed(0))+ assertEquals(3, t.offsetMapping.originalToTransformed(3))+ assertEquals(4, t.offsetMapping.originalToTransformed(4))+ assertEquals(4, t.offsetMapping.transformedToOriginal(4))+ }++ @Test+ fun `injected prefixes shift the text right`() {+ val paras = listOf(+ OdfParagraph(+ listOf(OdfSpan("item")),+ style = ParagraphStyle.LIST_ITEM,+ listLevel = 1,+ ),+ para("plain"),+ )+ val text = "item\nplain"+ val t = buildDocTransformed(text, paras, listOf(4, 5), listOf("• ", ""), Color.Gray, 1f)+ val shown = t.text.toString()+ assertTrue(shown.startsWith("• item"), shown)+ // Original offset 0 (start of "item") reads after the 3-char prefix.+ assertEquals(3, t.offsetMapping.originalToTransformed(0))+ // Inside-prefix transformed offsets clamp back to the paragraph start.+ assertEquals(0, t.offsetMapping.transformedToOriginal(1))+ assertEquals(0, t.offsetMapping.transformedToOriginal(0))+ }++ @Test+ fun `a layout change uses a zero-width separator`() {+ val paras = listOf(+ para("left"),+ OdfParagraph(+ listOf(OdfSpan("centered")),+ alignment = androidx.compose.ui.text.style.TextAlign.Center,+ ),+ )+ val text = "left\ncentered"+ val t = buildDocTransformed(text, paras, listOf(4, 8), listOf("", ""), Color.Gray, 1f)+ val shown = t.text.toString()+ // No blank line: the boundary is a zero-width space, not '\n'.+ assertTrue(!shown.contains("\n"), shown.map { it.code }.toString())+ assertTrue(shown.contains(""), "missing ZWSP in ${shown.map { it.code }}")+ // Both paragraphs still addressable through the mapping.+ assertEquals(0, t.offsetMapping.originalToTransformed(0))+ assertEquals(shown.length, t.offsetMapping.originalToTransformed(text.length))+ }++ @Test+ fun `headings get a larger styled size`() {+ val paras = listOf(+ OdfParagraph(listOf(OdfSpan("Title")), style = ParagraphStyle.HEADING1),+ para("body"),+ )+ val text = "Title\nbody"+ val t = buildDocTransformed(text, paras, listOf(5, 4), listOf("", ""), Color.Gray, 1f)+ assertTrue(t.text.toString().contains("Title"))+ // The heading span style covers the title range.+ val headingStyles = t.text.spanStyles.filter { it.start == 0 && it.end == 5 }+ assertTrue(headingStyles.isNotEmpty(), t.text.spanStyles.toString())+ }++ @Test+ fun `run formatting survives the transform`() {+ val paras = listOf(+ OdfParagraph(listOf(OdfSpan("b", bold = true), OdfSpan("plain"))),+ )+ val text = "bplain"+ val t = buildDocTransformed(text, paras, listOf(6), listOf(""), Color.Gray, 1f)+ val bold = t.text.spanStyles.filter { it.start == 0 && it.end == 1 }+ assertTrue(bold.isNotEmpty(), t.text.spanStyles.toString())+ assertEquals(+ androidx.compose.ui.text.font.FontWeight.Bold,+ bold.first().item.fontWeight,+ )+ }++ @Test+ fun `an empty paragraph group still maps offsets`() {+ val paras = listOf(para(""), para("after"))+ val text = "\nafter"+ val t = buildDocTransformed(text, paras, listOf(0, 5), listOf("", ""), Color.Gray, 1f)+ assertTrue(t.text.toString().contains("after"))+ assertEquals(t.text.length, t.offsetMapping.originalToTransformed(text.length))+ assertEquals(0, t.offsetMapping.transformedToOriginal(0))+ }++ @Test+ fun `tracked-change spans get decorations and colors`() {+ val paras = listOf(+ OdfParagraph(+ listOf(+ OdfSpan("ins", changeKind = "insertion"),+ OdfSpan("del", changeKind = "deletion"),+ )+ ),+ )+ val text = "insdel"+ val t = buildDocTransformed(text, paras, listOf(6), listOf(""), Color.Gray, 1f)+ // Both change spans carry a style over their ranges.+ assertTrue(t.text.spanStyles.any { it.start == 0 && it.end == 3 }, t.text.spanStyles.toString())+ assertTrue(t.text.spanStyles.any { it.start == 3 && it.end == 6 }, t.text.spanStyles.toString())+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/EditorModelsSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/EditorModelsSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/EditorModelsSlice1Test.ktnew file mode 100644index 0000000000..bad667768f--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/EditorModelsSlice1Test.kt@@ -0,0 +1,287 @@+package com.vayunmathur.library.ui.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Small editor models and exporter branches: page setup, gradients,+ * conditional formats, validations, slide bounds, editor-state paragraph+ * ops, pdf list/table paths and epub images. Slice-1 coverage for+ * library/ui (odf package).+ *+ * Robolectric because image exporters use android.util.Base64.+ */+@RunWith(RobolectricTestRunner::class)+class EditorModelsSlice1Test {++ @Test+ fun `page setup reports orientation and margins`() {+ val portrait = OdfPageSetup()+ assertFalse(portrait.isLandscape)+ assertEquals(793.7f, portrait.widthPx)+ assertEquals(75.6f, portrait.marginTopPx)+ assertEquals(75.6f, portrait.marginRightPx)+ assertEquals(75.6f, portrait.marginBottomPx)+ assertEquals(75.6f, portrait.marginLeftPx)+ assertEquals(1122.5f, portrait.heightPx)+ val landscape = OdfPageSetup(widthPx = 1122.5f, heightPx = 793.7f)+ assertTrue(landscape.isLandscape)+ }++ @Test+ fun `a gradient carries its colors angle and style`() {+ val g = OdfGradient(startColor = 0xFFFF0000, endColor = 0xFF0000FF, angle = 45f)+ assertEquals(0xFFFF0000, g.startColor)+ assertEquals(0xFF0000FF, g.endColor)+ assertEquals(45f, g.angle)+ assertEquals("linear", g.style)+ }++ @Test+ fun `a conditional format carries its condition and colors`() {+ val c = OdfCondFormat(+ condition = "cell-content() > 5",+ backgroundColor = 0xFFFFFF00,+ textColor = 0xFF000000,+ )+ assertEquals("cell-content() > 5", c.condition)+ assertEquals(0xFFFFFF00, c.backgroundColor)+ assertEquals(0xFF000000, c.textColor)+ }++ @Test+ fun `a list validation exposes its values`() {+ val v = OdfDataValidation(+ name = "v",+ condition = "cell-content-is-in-list(\"a\";\"b\"; \"c\")",+ )+ assertEquals(listOf("a", "b", "c"), v.listValues())+ assertNull(OdfDataValidation(name = "w", condition = "cell-content() > 1").listValues())+ assertEquals(emptyList(), OdfDataValidation(name = "e", condition = "cell-content-is-in-list()").listValues())+ }++ @Test+ fun `element bounds resize frames and every shape kind`() {+ val frame = OdfSlideElement.Frame(+ OdfFrame(x = 0f, y = 0f, width = 10f, height = 10f, paragraphs = emptyList())+ )+ val moved = setElementBounds(frame, 5f, 6f, 50f, 60f) as OdfSlideElement.Frame+ assertEquals(5f, moved.frame.x)+ assertEquals(60f, moved.frame.height)+ val shapes: List<OdfShape> = listOf(+ OdfShape.Rect(0f, 0f, 1f, 1f),+ OdfShape.Ellipse(0f, 0f, 1f, 1f),+ OdfShape.Line(0f, 0f, 9f, 4f),+ OdfShape.CustomShape(0f, 0f, 1f, 1f),+ )+ for (s in shapes) {+ val out = setElementBounds(OdfSlideElement.Shape(s), 2f, 3f, 40f, 30f)+ val b = (out as OdfSlideElement.Shape).shape+ assertEquals(2f, b.x, "x for ${s::class.simpleName}")+ assertEquals(40f, b.width, "w for ${s::class.simpleName}")+ }+ }++ @Test+ fun `a polyline resizes like the other shapes`() {+ val line = OdfShape.Polyline(+ x = 1f, y = 1f, width = 5f, height = 5f,+ points = listOf(1f to 1f, 6f to 6f),+ )+ val out = setElementBounds(OdfSlideElement.Shape(line), 0f, 0f, 20f, 20f)+ val b = (out as OdfSlideElement.Shape).shape as OdfShape.Polyline+ assertEquals(20f, b.width)+ assertEquals(listOf(1f to 1f, 6f to 6f), b.points)+ }++ private fun doc(vararg texts: String) = OdfDocument.TextDocument(+ title = "t",+ content = texts.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) },+ )++ private fun paraAt(doc: OdfDocument.TextDocument, i: Int): OdfParagraph =+ (doc.content[i] as OdfContentBlock.Paragraph).paragraph++ @Test+ fun `insert and clear run formatting flow through state`() {+ val s = OdfTextEditorState(doc("hello world"))+ s.insertTextInRun(0, 0, 5, "!")+ assertTrue(paraAt(s.current, 0).spans.joinToString("") { it.text }.contains("!"))+ s.applyRunSpanStyle(0, 0, 0, 5) { it.copy(bold = true) }+ assertTrue(paraAt(s.current, 0).spans.any { it.bold })+ s.clearRunFormatting(0, 0, 0, 5)+ assertTrue(paraAt(s.current, 0).spans.none { it.bold })+ assertTrue(s.canUndo.value)+ }++ @Test+ fun `paragraph structure ops flow through state`() {+ val s = OdfTextEditorState(doc("a", "b", "c"))+ s.changeListLevel(0, 1)+ s.restartNumbering(0)+ s.insertHorizontalLine(1)+ s.indentParagraph(0)+ s.outdentParagraph(0)+ s.setParagraphAlignment(0, androidx.compose.ui.text.style.TextAlign.Center)+ assertEquals(+ androidx.compose.ui.text.style.TextAlign.Center,+ paraAt(s.current, 0).alignment,+ )+ s.moveParagraphDown(0)+ assertEquals("b", paraAt(s.current, 0).spans.joinToString("") { it.text })+ s.moveParagraphUp(1)+ assertEquals("a", paraAt(s.current, 0).spans.joinToString("") { it.text })+ s.duplicateParagraph(0)+ assertEquals(5, s.current.content.size)+ s.deleteParagraph(4)+ assertEquals(4, s.current.content.size)+ }++ @Test+ fun `checkbox state ops flow through state`() {+ val s = OdfTextEditorState(+ OdfDocument.TextDocument(+ title = "t",+ content = listOf(+ OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(OdfSpan("task")),+ style = ParagraphStyle.LIST_ITEM,+ listType = ListType.CHECKBOX,+ )+ )+ ),+ )+ )+ s.setCheckboxChecked(0, true)+ assertTrue(paraAt(s.current, 0).listChecked)+ s.toggleCheckbox(0)+ assertFalse(paraAt(s.current, 0).listChecked)+ }++ @Test+ fun `pdf export covers lists tables toc and formulas`() {+ val bytes = PdfExporter.export(+ OdfDocument.TextDocument(+ title = "t",+ content = listOf(+ OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(OdfSpan("item")),+ style = ParagraphStyle.LIST_ITEM,+ listType = ListType.NUMBERED,+ listItemIndex = 2,+ listLevel = 1,+ )+ ),+ OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(OdfSpan("todo")),+ style = ParagraphStyle.LIST_ITEM,+ listType = ListType.CHECKBOX,+ listChecked = true,+ )+ ),+ OdfContentBlock.Table(+ OdfTable(+ rows = listOf(+ OdfTableRow(+ listOf(+ OdfTableCell(+ listOf(OdfParagraph(listOf(OdfSpan("cell•(x)"))))+ )+ )+ )+ )+ )+ ),+ OdfContentBlock.TableOfContents(+ "C",+ listOf(OdfParagraph(listOf(OdfSpan("entry")))),+ ),+ OdfContentBlock.Formula("x^2"),+ ),+ )+ )+ val text = bytes.toString(Charsets.ISO_8859_1)+ assertTrue(text.startsWith("%PDF"), text.take(20))+ // The marker and word are separate Tj tokens, so assert both parts.+ assertTrue(text.contains("(2.)"), text.take(3000))+ assertTrue(text.contains("(item)"), text.take(3000))+ assertTrue(text.contains("[x]"), text)+ assertTrue(text.contains("entry"), text)+ }++ @Test+ fun `epub export embeds images`() {+ val bytes = EpubExporter.export(+ OdfDocument.TextDocument(+ title = "T",+ content = listOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("hi")))),+ OdfContentBlock.Image(+ OdfImage(+ path = "p.png",+ imageData = byteArrayOf(1, 2, 3),+ )+ ),+ ),+ )+ )+ val names = LinkedHashSet<String>()+ java.util.zip.ZipInputStream(java.io.ByteArrayInputStream(bytes)).use { zis ->+ var e = zis.nextEntry+ while (e != null) {+ names.add(e.name)+ zis.closeEntry()+ e = zis.nextEntry+ }+ }+ assertTrue(names.any { it.endsWith(".xhtml") }, names.toString())+ assertTrue(names.any { it.contains("images/") }, names.toString())+ }++ @Test+ fun `html export covers styled spans tables and images`() {+ val html = HtmlOdfExport.odfToHtml(+ OdfDocument.TextDocument(+ title = "T",+ content = listOf(+ OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(+ OdfSpan("b", bold = true),+ OdfSpan("i", italic = true, color = 0xFFFF0000),+ OdfSpan("link", href = "https://example.com"),+ ),+ alignment = androidx.compose.ui.text.style.TextAlign.Center,+ )+ ),+ OdfContentBlock.Table(+ OdfTable(+ rows = listOf(+ OdfTableRow(+ listOf(+ OdfTableCell(+ listOf(OdfParagraph(listOf(OdfSpan("c"))))+ )+ )+ )+ )+ )+ ),+ ),+ )+ )+ assertTrue(html.contains("<strong>b</strong>"), html.take(2000))+ assertTrue(html.contains("<em>"), html.take(2000))+ assertTrue(html.contains("color:#FF0000"), html)+ assertTrue(html.contains("https://example.com"), html)+ assertTrue(html.contains("<table"), html)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlExportDetailsSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlExportDetailsSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlExportDetailsSlice1Test.ktnew file mode 100644index 0000000000..3bdbd353ea--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlExportDetailsSlice1Test.kt@@ -0,0 +1,156 @@+package com.vayunmathur.library.ui.odf++import androidx.compose.ui.text.style.TextAlign+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlin.test.Test+import kotlin.test.assertTrue+import org.junit.runner.RunWith++/**+ * HTML export details: tables, images, checkboxes, nested lists, header rows.+ * Slice-1 coverage for library/ui (odf package). Robolectric for Base64.+ */+@RunWith(AndroidJUnit4::class)+class HtmlExportDetailsSlice1Test {++ private fun para(text: String) =+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text))))++ private fun docOf(vararg blocks: OdfContentBlock) =+ OdfDocument.TextDocument(title = "t", content = blocks.toList())++ @Test+ fun `a table exports headers spans and colors`() {+ val html = HtmlOdfConverter.odfToHtml(+ docOf(+ OdfContentBlock.Table(+ OdfTable(+ rows = listOf(+ OdfTableRow(+ listOf(+ OdfTableCell(+ listOf(OdfParagraph(listOf(OdfSpan("h")))),+ colSpan = 2,+ backgroundColor = 0xFFFF00,+ ),+ OdfTableCell(isCovered = true),+ )+ ),+ OdfTableRow(+ listOf(+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("a"))))),+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("b"))))),+ )+ ),+ ),+ headerRowCount = 1,+ )+ )+ )+ )+ assertTrue(html.contains("<table"), html)+ assertTrue(html.contains("<th"), html)+ assertTrue(html.contains("colspan=\"2\""), html)+ assertTrue(html.contains("background-color:#FFFF00"), html)+ assertTrue(html.contains("<td>a</td>") || html.contains(">a</td>"), html)+ }++ @Test+ fun `an image exports as a data url`() {+ val html = HtmlOdfConverter.odfToHtml(+ docOf(+ OdfContentBlock.Image(+ OdfImage(+ path = "pic.png",+ imageData = byteArrayOf(1, 2, 3),+ width = 64f,+ height = 32f,+ altDesc = "alt",+ )+ )+ )+ )+ assertTrue(html.contains("<img"), html)+ assertTrue(html.contains("data:image/png;base64,"), html)+ assertTrue(html.contains("width=\"64\""), html)+ assertTrue(html.contains("alt=\"alt\""), html)+ }++ @Test+ fun `an empty image exports to nothing`() {+ val html = HtmlOdfConverter.odfToHtml(+ docOf(OdfContentBlock.Image(OdfImage(path = "x.png", imageData = byteArrayOf())))+ )+ assertTrue(!html.contains("<img"), html)+ }++ @Test+ fun `checkbox items render ballot boxes`() {+ fun item(text: String, checked: Boolean) = OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(OdfSpan(text)),+ style = ParagraphStyle.LIST_ITEM,+ listLevel = 1,+ listType = ListType.CHECKBOX,+ listChecked = checked,+ )+ )+ val html = HtmlOdfConverter.odfToHtml(docOf(item("done", true), item("todo", false)))+ // ☑ (U+2611) for checked, ☐ (U+2610) for unchecked.+ assertTrue(html.contains("☑"), html)+ assertTrue(html.contains("☐"), html)+ }++ @Test+ fun `numbered lists group into ordered lists`() {+ fun item(text: String) = OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(OdfSpan(text)),+ style = ParagraphStyle.LIST_ITEM,+ listLevel = 1,+ listType = ListType.NUMBERED,+ )+ )+ val html = HtmlOdfConverter.odfToHtml(docOf(item("one"), item("two")))+ assertTrue(html.contains("<ol>"), html)+ assertTrue(!html.contains("<ul>"), html)+ }++ @Test+ fun `a formula block exports escaped mathml in code`() {+ val html = HtmlOdfConverter.odfToHtml(docOf(OdfContentBlock.Formula("<math><mi>x</mi></math>")))+ assertTrue(html.contains("<code>"), html)+ assertTrue(html.contains("<math>"), html)+ }++ @Test+ fun `a toc exports its entries and a page break exports a rule`() {+ val html = HtmlOdfConverter.odfToHtml(+ docOf(+ OdfContentBlock.TableOfContents(+ "C",+ listOf(OdfParagraph(listOf(OdfSpan("Ch1")), style = ParagraphStyle.HEADING1)),+ ),+ OdfContentBlock.PageBreak,+ )+ )+ assertTrue(html.contains("Ch1"), html)+ assertTrue(html.contains("<hr"), html)+ }++ @Test+ fun `alignment maps to align attributes`() {+ val html = HtmlOdfConverter.odfToHtml(+ docOf(+ OdfContentBlock.Paragraph(+ OdfParagraph(listOf(OdfSpan("c")), alignment = TextAlign.Center)+ ),+ OdfContentBlock.Paragraph(+ OdfParagraph(listOf(OdfSpan("j")), alignment = TextAlign.Justify)+ ),+ )+ )+ assertTrue(html.contains("center"), html)+ assertTrue(html.contains("justify"), html)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlImportDetailsSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlImportDetailsSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlImportDetailsSlice1Test.ktnew file mode 100644index 0000000000..0684799f30--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlImportDetailsSlice1Test.kt@@ -0,0 +1,162 @@+package com.vayunmathur.library.ui.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith++/**+ * HTML import details: inline styles, links, lists, tables, images, entities.+ * Slice-1 coverage for library/ui (odf package). Robolectric for Base64.+ */+@RunWith(androidx.test.ext.junit.runners.AndroidJUnit4::class)+class HtmlImportDetailsSlice1Test {++ @Test+ fun `inline styles map to span formatting`() {+ val doc = HtmlOdfConverter.htmlToOdf(+ "<p><span style=\"color:#ff0000;font-size:18pt;font-weight:bold\">big</span> " ++ "<span style=\"font-style:italic;text-decoration:underline\">iu</span> " ++ "<span style=\"text-decoration:line-through\">s</span></p>"+ )+ val spans = (doc.content[0] as OdfContentBlock.Paragraph).paragraph.spans+ val big = spans.first { it.text.contains("big") }+ assertEquals(0xFFFF0000L, big.color)+ assertEquals(18f, big.fontSize)+ assertTrue(big.bold)+ val iu = spans.first { it.text.contains("iu") }+ assertTrue(iu.italic && iu.underline)+ assertTrue(spans.any { it.strikethrough && it.text.contains("s") }, spans.toString())+ }++ @Test+ fun `legacy color attributes map to named colors`() {+ val doc = HtmlOdfConverter.htmlToOdf("<p><font color=\"red\">r</font> <font color=\"#00ff00\">g</font></p>")+ val spans = (doc.content[0] as OdfContentBlock.Paragraph).paragraph.spans+ assertTrue(spans.any { it.color == 0xFFFF0000L }, spans.toString())+ assertTrue(spans.any { it.color == 0xFF00FF00L }, spans.toString())+ }++ @Test+ fun `links carry the href`() {+ val doc = HtmlOdfConverter.htmlToOdf("<p>see <a href=\"https://x.test\">docs</a></p>")+ val spans = (doc.content[0] as OdfContentBlock.Paragraph).paragraph.spans+ val link = spans.first { it.text.contains("docs") }+ assertEquals("https://x.test", link.href)+ assertTrue(link.underline)+ }++ @Test+ fun `ordered lists number their items`() {+ val doc = HtmlOdfConverter.htmlToOdf("<ol><li>one</li><li>two</li></ol>")+ val items = doc.content.map { (it as OdfContentBlock.Paragraph).paragraph }+ assertEquals(2, items.size)+ assertTrue(items.all { it.style == ParagraphStyle.LIST_ITEM }, items.toString())+ assertTrue(items.all { it.listType == ListType.NUMBERED }, items.toString())+ assertEquals(1, items[0].listItemIndex)+ assertEquals(2, items[1].listItemIndex)+ }++ @Test+ fun `an ol start attribute offsets numbering`() {+ val doc = HtmlOdfConverter.htmlToOdf("<ol start=\"5\"><li>five</li></ol>")+ val item = (doc.content[0] as OdfContentBlock.Paragraph).paragraph+ assertEquals(5, item.listItemIndex)+ }++ @Test+ fun `blockquotes rules and line breaks import`() {+ val doc = HtmlOdfConverter.htmlToOdf("<blockquote>quoted</blockquote><hr><p>a<br>b</p>")+ val texts = doc.content.map {+ (it as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { s -> s.text }+ }+ assertTrue(texts.any { it.contains("quoted") }, texts.toString())+ assertTrue(texts.any { it.contains("a\nb") }, texts.toString())+ // The <hr> becomes an empty bordered paragraph.+ assertTrue(+ doc.content.any {+ val p = (it as OdfContentBlock.Paragraph).paragraph+ p.borderColor != null+ },+ texts.toString(),+ )+ }++ @Test+ fun `a table imports rows headers and spans`() {+ val doc = HtmlOdfConverter.htmlToOdf(+ "<table><tr><th>H</th></tr><tr><td colspan=\"2\">wide</td></tr></table>"+ )+ val table = (doc.content[0] as OdfContentBlock.Table).table+ assertEquals(2, table.rows.size)+ assertEquals(1, table.headerRowCount)+ assertEquals("H", table.rows[0].cells[0].paragraphs[0].spans[0].text)+ assertEquals(2, table.rows[1].cells[0].colSpan)+ }++ @Test+ fun `a data-url image imports its bytes`() {+ // "hi" in base64.+ val doc = HtmlOdfConverter.htmlToOdf(+ "<p>before</p><img src=\"data:image/png;base64,aGk=\" width=\"10\" height=\"20\" alt=\"pic\">"+ )+ val img = doc.content.filterIsInstance<OdfContentBlock.Image>().single()+ assertEquals("pic", img.image.altDesc)+ assertEquals(10f, img.image.width)+ assertEquals(20f, img.image.height)+ assertTrue(img.image.imageData.isNotEmpty())+ }++ @Test+ fun `remote images are skipped`() {+ val doc = HtmlOdfConverter.htmlToOdf("<p>t</p><img src=\"https://x.test/i.png\">")+ assertTrue(doc.content.none { it is OdfContentBlock.Image })+ }++ @Test+ fun `entities and alignment decode`() {+ val doc = HtmlOdfConverter.htmlToOdf("<p style=\"text-align:center\">a & b <c></p>")+ val p = (doc.content[0] as OdfContentBlock.Paragraph).paragraph+ assertEquals(androidx.compose.ui.text.style.TextAlign.Center, p.alignment)+ assertTrue(p.spans.joinToString("") { it.text }.contains("a & b <c>"), p.spans.toString())+ }++ @Test+ fun `headings five and six fold to heading four`() {+ val doc = HtmlOdfConverter.htmlToOdf("<h5>small</h5>")+ assertEquals(+ ParagraphStyle.HEADING4,+ (doc.content[0] as OdfContentBlock.Paragraph).paragraph.style,+ )+ }++ @Test+ fun `sub sup strike and del import`() {+ val doc = HtmlOdfConverter.htmlToOdf("<p><sup>2</sup><sub>3</sub><del>gone</del></p>")+ val spans = (doc.content[0] as OdfContentBlock.Paragraph).paragraph.spans+ assertTrue(spans.any { it.superscript && it.text == "2" }, spans.toString())+ assertTrue(spans.any { it.subscript && it.text == "3" }, spans.toString())+ assertTrue(spans.any { it.strikethrough && it.text == "gone" }, spans.toString())+ }++ @Test+ fun `a styled html document round-trips`() {+ val html = HtmlOdfConverter.odfToHtml(+ OdfDocument.TextDocument(+ title = "t",+ content = listOf(+ OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(OdfSpan("B", bold = true)),+ style = ParagraphStyle.HEADING1,+ )+ ),+ ),+ )+ )+ val back = HtmlOdfConverter.htmlToOdf(html)+ val first = (back.content[0] as OdfContentBlock.Paragraph).paragraph+ assertEquals(ParagraphStyle.HEADING1, first.style)+ assertTrue(first.spans.any { it.bold }, first.spans.toString())+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlOdfConverterSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlOdfConverterSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlOdfConverterSlice1Test.ktnew file mode 100644index 0000000000..7aa9d5caea--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/HtmlOdfConverterSlice1Test.kt@@ -0,0 +1,102 @@+package com.vayunmathur.library.ui.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * HTML <-> ODF conversion: headings, spans, lists, tables and round-trips.+ * Slice-1 coverage for library/ui (odf package + Html converters).+ */+class HtmlOdfConverterSlice1Test {++ private fun para(text: String) =+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text))))++ private fun docOf(vararg blocks: OdfContentBlock) =+ OdfDocument.TextDocument(title = "t", content = blocks.toList())++ @Test+ fun `export emits a full html shell`() {+ val html = HtmlOdfConverter.odfToHtml(docOf(para("hi")))+ assertTrue(html.contains("<title>t</title>"), html)+ assertTrue(html.contains("<p>hi</p>"), html)+ }++ @Test+ fun `headings map to h-tags`() {+ val html = HtmlOdfConverter.odfToHtml(+ docOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("H")), ParagraphStyle.HEADING1)),+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("S")), ParagraphStyle.HEADING2)),+ )+ )+ assertTrue(html.contains("<h1>H</h1>"), html)+ assertTrue(html.contains("<h2>S</h2>"), html)+ }++ @Test+ fun `bold and italic spans map to tags`() {+ val html = HtmlOdfConverter.odfToHtml(+ docOf(+ OdfContentBlock.Paragraph(+ OdfParagraph(listOf(OdfSpan("b", bold = true), OdfSpan("i", italic = true)))+ )+ )+ )+ assertTrue(html.contains("<strong>b</strong>"), html)+ assertTrue(html.contains("<em>i</em>"), html)+ }++ @Test+ fun `list items group into a list`() {+ fun item(text: String) = OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(OdfSpan(text)),+ style = ParagraphStyle.LIST_ITEM,+ listLevel = 1,+ )+ )+ val html = HtmlOdfConverter.odfToHtml(docOf(item("a"), item("b")))+ assertEquals(1, Regex("<ul>").findAll(html).count())+ assertEquals(2, Regex("<li>").findAll(html).count())+ }++ @Test+ fun `import reads headings and paragraphs`() {+ val doc = HtmlOdfConverter.htmlToOdf("<h1>Title</h1><p>Hello <b>bold</b></p>", "t")+ assertTrue(doc.content.size >= 2)+ val first = (doc.content[0] as OdfContentBlock.Paragraph).paragraph+ assertEquals(ParagraphStyle.HEADING1, first.style)+ assertEquals("Title", first.spans.joinToString("") { it.text })+ }++ @Test+ fun `import of bold text keeps the span style`() {+ val doc = HtmlOdfConverter.htmlToOdf("<p>Hello <b>bold</b></p>")+ val spans = (doc.content[0] as OdfContentBlock.Paragraph).paragraph.spans+ assertTrue(spans.any { it.bold && it.text.contains("bold") })+ }++ @Test+ fun `empty import yields one empty paragraph`() {+ val doc = HtmlOdfConverter.htmlToOdf("")+ assertEquals(1, doc.content.size)+ }++ @Test+ fun `a heading round-trips through html`() {+ val doc = docOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("Title")), ParagraphStyle.HEADING1)),+ para("Body text"),+ )+ val back = HtmlOdfConverter.htmlToOdf(HtmlOdfConverter.odfToHtml(doc))+ assertEquals(+ ParagraphStyle.HEADING1,+ (back.content[0] as OdfContentBlock.Paragraph).paragraph.style,+ )+ assertTrue(back.content.any {+ (it as? OdfContentBlock.Paragraph)?.paragraph?.spans?.joinToString("") { s -> s.text } == "Body text"+ })+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/MathmlExtraSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/MathmlExtraSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/MathmlExtraSlice1Test.ktnew file mode 100644index 0000000000..9a1dff9865--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/MathmlExtraSlice1Test.kt@@ -0,0 +1,74 @@+package com.vayunmathur.library.ui.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * MathML converter round two: sub-superscripts, tables, under/over, styles,+ * roots and unknown elements. Slice-1 coverage for library/ui (odf package).+ */+class MathmlExtraSlice1Test {++ @Test+ fun `subsup and underover convert`() {+ val msubsup = "<math><msubsup><mi>x</mi><mn>1</mn><mn>2</mn></msubsup></math>"+ assertEquals("{x}_{1}^{2}", MathmlToLatex.convert(msubsup))+ val munderover = "<math><munderover><mo>∑</mo><mi>i</mi><mi>n</mi></munderover></math>"+ assertEquals("\\sum_{i}^{n}", MathmlToLatex.convert(munderover))+ }++ @Test+ fun `tables become matrices`() {+ val mtable = "<math><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr>" ++ "<mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></math>"+ val latex = MathmlToLatex.convert(mtable)+ assertTrue(latex.contains("\\begin{matrix}"), latex)+ assertTrue(latex.contains("1 & 2"), latex)+ assertTrue(latex.contains("\\\\"), latex)+ assertTrue(latex.contains("\\end{matrix}"), latex)+ }++ @Test+ fun `styled rows and nth roots convert`() {+ val styled = "<math><mstyle><mrow><mi>y</mi></mrow></mstyle></math>"+ assertEquals("y", MathmlToLatex.convert(styled))+ val plainRow = "<mrow><mi>z</mi></mrow>"+ assertEquals("z", MathmlToLatex.convert(plainRow))+ }++ @Test+ fun `more operators map`() {+ // ∫ (U+222B) -> \int, ∞ (U+221E) -> \infty.+ assertEquals("\\int", MathmlToLatex.convert("<math><mo>∫</mo></math>"))+ assertEquals("\\infty", MathmlToLatex.convert("<math><mo>∞</mo></math>"))+ // × (U+00D7) -> \times, ≤ (U+2264) -> \leq, → (U+2192) -> \to.+ assertEquals("\\times", MathmlToLatex.convert("<math><mo>×</mo></math>"))+ assertEquals("\\leq", MathmlToLatex.convert("<math><mo>≤</mo></math>"))+ assertEquals("\\to", MathmlToLatex.convert("<math><mo>→</mo></math>"))+ }++ @Test+ fun `unknown elements fall through to their children`() {+ val latex = MathmlToLatex.convert("<math><mystery><mi>q</mi></mystery></math>")+ assertEquals("q", latex)+ }++ @Test+ fun `nested fractions convert`() {+ val nested = "<math><mfrac><mrow><mi>a</mi><mo>+</mo><mi>b</mi></mrow><mn>2</mn></mfrac></math>"+ assertEquals("\\frac{a + b}{2}", MathmlToLatex.convert(nested))+ }++ @Test+ fun `a formula with sqrt lands in the latex export`() {+ val mathml = "<math><msqrt><mfrac><mn>1</mn><mn>2</mn></mfrac></msqrt></math>"+ val tex = LatexExporter.export(+ OdfDocument.TextDocument(+ title = "T",+ content = listOf(OdfContentBlock.Formula(mathml)),+ )+ )+ assertTrue(tex.contains("\\sqrt{\\frac{1}{2}}"), tex)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/MathmlLatexSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/MathmlLatexSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/MathmlLatexSlice1Test.ktnew file mode 100644index 0000000000..dbae0d2565--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/MathmlLatexSlice1Test.kt@@ -0,0 +1,194 @@+package com.vayunmathur.library.ui.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * LaTeX export details: tables, run formatting, lists, formula blocks and the+ * MathML-to-LaTeX converter. Slice-1 coverage for library/ui (odf package).+ */+class MathmlLatexSlice1Test {++ private fun para(text: String, style: ParagraphStyle = ParagraphStyle.BODY) =+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text)), style = style))++ private fun docOf(vararg blocks: OdfContentBlock, title: String = "T") =+ OdfDocument.TextDocument(title = title, content = blocks.toList())++ @Test+ fun `a table becomes a tabular`() {+ val tex = LatexExporter.export(+ docOf(+ OdfContentBlock.Table(+ OdfTable(+ rows = listOf(+ OdfTableRow(+ listOf(+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("a"))))),+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("b"))))),+ )+ ),+ OdfTableRow(+ listOf(+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("c"))))),+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("d"))))),+ )+ ),+ )+ )+ )+ )+ )+ assertTrue(tex.contains("\\begin{tabular}"), tex.take(800))+ assertTrue(tex.contains("a & b"), tex)+ assertTrue(tex.contains("c & d"), tex)+ assertTrue(tex.contains("\\end{tabular}"), tex)+ }++ @Test+ fun `an empty table exports to nothing`() {+ val tex = LatexExporter.export(docOf(OdfContentBlock.Table(OdfTable(rows = emptyList()))))+ assertTrue(!tex.contains("\\begin{tabular}"), tex)+ }++ @Test+ fun `run formatting maps to latex commands`() {+ val tex = LatexExporter.export(+ docOf(+ OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(+ OdfSpan("b", bold = true),+ OdfSpan("i", italic = true),+ OdfSpan("u", underline = true),+ OdfSpan("s", strikethrough = true),+ OdfSpan("sup", superscript = true),+ OdfSpan("sub", subscript = true),+ OdfSpan("link", href = "https://x.test"),+ )+ )+ )+ )+ )+ assertTrue(tex.contains("\\textbf{b}"), tex)+ assertTrue(tex.contains("\\emph{i}"), tex)+ assertTrue(tex.contains("\\underline{u}"), tex)+ assertTrue(tex.contains("\\sout{s}"), tex)+ assertTrue(tex.contains("\\textsuperscript{sup}"), tex)+ assertTrue(tex.contains("\\textsubscript{sub}"), tex)+ assertTrue(tex.contains("\\href{https://x.test}{link}"), tex)+ }++ @Test+ fun `lists become itemize and enumerate`() {+ fun item(text: String, type: ListType) = OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(OdfSpan(text)),+ style = ParagraphStyle.LIST_ITEM,+ listLevel = 1,+ listType = type,+ )+ )+ val tex = LatexExporter.export(docOf(item("a", ListType.BULLET), item("b", ListType.BULLET)))+ assertTrue(tex.contains("\\begin{itemize}"), tex)+ assertTrue(tex.contains("\\item a"), tex)+ assertTrue(tex.contains("\\end{itemize}"), tex)+ val tex2 = LatexExporter.export(docOf(item("one", ListType.NUMBERED)))+ assertTrue(tex2.contains("\\begin{enumerate}"), tex2)+ assertTrue(tex2.contains("\\item one"), tex2)+ assertTrue(tex2.contains("\\end{enumerate}"), tex2)+ }++ @Test+ fun `headings map to sectioning commands`() {+ val tex = LatexExporter.export(+ docOf(+ para("H2", ParagraphStyle.HEADING2),+ para("H3", ParagraphStyle.HEADING3),+ para("H4", ParagraphStyle.HEADING4),+ )+ )+ assertTrue(tex.contains("\\subsection{H2}"), tex)+ assertTrue(tex.contains("\\subsubsection{H3}"), tex)+ assertTrue(tex.contains("\\paragraph{H4}"), tex)+ }++ @Test+ fun `a formula block becomes display math`() {+ val mathml = "<math><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></math>"+ val tex = LatexExporter.export(docOf(OdfContentBlock.Formula(mathml)))+ assertTrue(tex.contains("\\["), tex)+ assertTrue(tex.contains("x"), tex)+ assertTrue(tex.contains("\\]"), tex)+ }++ @Test+ fun `a table of contents becomes tableofcontents`() {+ val tex = LatexExporter.export(docOf(OdfContentBlock.TableOfContents("Contents", emptyList())))+ assertTrue(tex.contains("\\tableofcontents"), tex)+ }++ @Test+ fun `a page break becomes newpage`() {+ val tex = LatexExporter.export(docOf(para("a"), OdfContentBlock.PageBreak, para("b")))+ assertTrue(tex.contains("\\newpage"), tex)+ }++ @Test+ fun `fractions and roots convert`() {+ val mathml = "<math><mfrac><mn>1</mn><mn>2</mn></mfrac></math>"+ assertEquals("\\frac{1}{2}", MathmlToLatex.convert(mathml))+ val sqrt = "<math><msqrt><mi>x</mi></msqrt></math>"+ assertEquals("\\sqrt{x}", MathmlToLatex.convert(sqrt))+ }++ @Test+ fun `superscripts subscripts and operators convert`() {+ val sup = "<math><msup><mi>x</mi><mn>2</mn></msup></math>"+ assertEquals("{x}^{2}", MathmlToLatex.convert(sup))+ val sub = "<math><msub><mi>x</mi><mn>i</mn></msub></math>"+ assertEquals("{x}_{i}", MathmlToLatex.convert(sub))+ // ∑ (U+2211) maps to \sum.+ val sum = "<math><mo>∑</mo></math>"+ assertEquals("\\sum", MathmlToLatex.convert(sum))+ // ± (U+00B1) maps to \pm.+ val pm = "<math><mo>±</mo></math>"+ assertEquals("\\pm", MathmlToLatex.convert(pm))+ }++ @Test+ fun `fenced text matrices and roots convert`() {+ val fenced = "<math><mfenced><mi>a</mi></mfenced></math>"+ assertTrue(MathmlToLatex.convert(fenced).contains("\\left("), MathmlToLatex.convert(fenced))+ val mroot = "<math><mroot><mi>x</mi><mn>3</mn></mroot></math>"+ assertEquals("\\sqrt[3]{x}", MathmlToLatex.convert(mroot))+ val munder = "<math><munder><mo>∑</mo><mi>i</mi></munder></math>"+ assertEquals("\\sum_{i}", MathmlToLatex.convert(munder))+ val mover = "<math><mover><mi>x</mi><mo>→</mo></mover></math>"+ assertEquals("x^{\\to}", MathmlToLatex.convert(mover))+ }++ @Test+ fun `mtext wraps in text and unknown operators pass through`() {+ val t = "<math><mtext>hello</mtext></math>"+ assertEquals("\\text{hello}", MathmlToLatex.convert(t))+ val plain = "<math><mo>+</mo></math>"+ assertEquals("+", MathmlToLatex.convert(plain))+ }++ @Test+ fun `garbage mathml converts to empty`() {+ assertEquals("", MathmlToLatex.convert("not xml at all <<<"))+ assertEquals("", MathmlToLatex.convert(""))+ }++ @Test+ fun `greek letters map to commands`() {+ // α (U+03B1) maps to \alpha.+ val alpha = "<math><mi>α</mi></math>"+ assertEquals("α", MathmlToLatex.convert(alpha))+ val pi = "<math><mo>π</mo></math>"+ assertEquals("\\pi", MathmlToLatex.convert(pi))+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfDocTransformSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfDocTransformSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfDocTransformSlice1Test.ktnew file mode 100644index 0000000000..214b3f6fcd--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfDocTransformSlice1Test.kt@@ -0,0 +1,52 @@+package com.vayunmathur.library.ui.odf++import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Transformed-text offset accounting: prefix starts and the offset mapping.+ * Slice-1 coverage for library/ui (odf package).+ */+class OdfDocTransformSlice1Test {++ @Test+ fun `transformed starts accumulate prefixes plus separators`() {+ val starts = runTransStarts(listOf(3, 2), listOf("• ", ""))+ assertEquals(0, starts[0])+ // 3 chars + 3 prefix + 1 separator.+ assertEquals(7, starts[1])+ }++ @Test+ fun `empty inputs yield empty starts`() {+ assertEquals(0, runTransStarts(emptyList(), emptyList()).size)+ }++ @Test+ fun `the offset mapping round-trips through prefixes`() {+ val lens = listOf(3, 3)+ val prefixes = listOf("• ", "")+ val transStarts = runTransStarts(lens, prefixes)+ val origStarts = intArrayOf(0, 4)+ val mapping = PrefixOffsetMapping(+ origStarts = origStarts,+ transStarts = transStarts,+ prefixLens = intArrayOf(3, 0),+ lens = lens.toIntArray(),+ origLen = 7,+ transLen = 10,+ )+ // The transformed slot starts with the injected prefix: original+ // 0 (paragraph start) reads at the prefix start, which the mapping+ // reports as the paragraph's transformed start.+ assertEquals(0, transStarts[0])+ assertEquals(7, transStarts[1])+ // Text after the prefix shifts right by the prefix length.+ assertEquals(4, mapping.originalToTransformed(1))+ // Back the other way: inside-prefix offsets clamp to the paragraph start.+ assertEquals(0, mapping.transformedToOriginal(1))+ assertEquals(1, mapping.transformedToOriginal(4))+ // Start of the second paragraph maps to its transformed start.+ assertEquals(7, mapping.originalToTransformed(4))+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfParagraphOpsSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfParagraphOpsSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfParagraphOpsSlice1Test.ktnew file mode 100644index 0000000000..7f68cd149a--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfParagraphOpsSlice1Test.kt@@ -0,0 +1,198 @@+package com.vayunmathur.library.ui.odf++import androidx.compose.ui.text.style.TextAlign+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Paragraph operations: list toggles, indent, style, moves, smart enter/backspace.+ * Slice-1 coverage for library/ui (odf package).+ */+class OdfParagraphOpsSlice1Test {++ private fun para(+ text: String = "hello",+ style: ParagraphStyle = ParagraphStyle.BODY,+ level: Int = 0,+ type: ListType = ListType.BULLET,+ index: Int = 0,+ ) = OdfContentBlock.Paragraph(+ OdfParagraph(listOf(OdfSpan(text)), style = style, listLevel = level, listType = type, listItemIndex = index)+ )++ private fun docOf(vararg blocks: OdfContentBlock) =+ OdfDocument.TextDocument(title = "t", content = blocks.toList())++ private fun styleOf(d: OdfDocument.TextDocument, i: Int) =+ (d.content[i] as OdfContentBlock.Paragraph).paragraph.style++ @Test+ fun `toggling a bullet makes and unmakes a list item`() {+ val on = docOf(para()).toggleListItem(0)!!+ assertEquals(ParagraphStyle.LIST_ITEM, styleOf(on, 0))+ val off = on.toggleListItem(0)!!+ assertEquals(ParagraphStyle.BODY, styleOf(off, 0))+ }++ @Test+ fun `toggling numbered renumbers the run`() {+ val d = docOf(+ para("a", ParagraphStyle.LIST_ITEM, 1, ListType.NUMBERED, 1),+ para("b", ParagraphStyle.LIST_ITEM, 1, ListType.NUMBERED, 1),+ )+ val out = d.toggleNumberedList(1)!!+ // Second item left the list: the first keeps index 1.+ assertEquals(ParagraphStyle.BODY, styleOf(out, 1))+ assertEquals(1, (out.content[0] as OdfContentBlock.Paragraph).paragraph.listItemIndex)+ }++ @Test+ fun `list level changes clamp to 1-9`() {+ val d = docOf(para("a", ParagraphStyle.LIST_ITEM, 1))+ assertEquals(9, ((d.changeListLevel(0, 99)!!.content[0] as OdfContentBlock.Paragraph).paragraph.listLevel))+ assertEquals(1, ((d.changeListLevel(0, -99)!!.content[0] as OdfContentBlock.Paragraph).paragraph.listLevel))+ assertNull(docOf(para()).changeListLevel(0, 1))+ assertNull(docOf(OdfContentBlock.PageBreak).changeListLevel(0, 1))+ }++ @Test+ fun `restart numbering resets the run`() {+ val d = docOf(+ para("a", ParagraphStyle.LIST_ITEM, 1, ListType.NUMBERED, 7),+ para("b", ParagraphStyle.LIST_ITEM, 1, ListType.NUMBERED, 8),+ )+ val out = d.restartNumbering(0)!!+ assertEquals(1, (out.content[0] as OdfContentBlock.Paragraph).paragraph.listItemIndex)+ assertEquals(2, (out.content[1] as OdfContentBlock.Paragraph).paragraph.listItemIndex)+ }++ @Test+ fun `indent and outdent move the margin`() {+ val d = docOf(para())+ val indented = d.indentParagraph(0)!!+ assertEquals(24f, (indented.content[0] as OdfContentBlock.Paragraph).paragraph.marginLeft)+ val outdented = indented.outdentParagraph(0)!!+ assertEquals(0f, (outdented.content[0] as OdfContentBlock.Paragraph).paragraph.marginLeft)+ assertNull(docOf(OdfContentBlock.PageBreak).indentParagraph(0))+ }++ @Test+ fun `style and alignment set`() {+ val d = docOf(para())+ assertEquals(+ ParagraphStyle.HEADING1,+ styleOf(d.setParagraphStyle(0, ParagraphStyle.HEADING1)!!, 0),+ )+ val aligned = d.setParagraphAlignment(0, TextAlign.Center)!!+ assertEquals(TextAlign.Center, (aligned.content[0] as OdfContentBlock.Paragraph).paragraph.alignment)+ assertNull(docOf(OdfContentBlock.PageBreak).setParagraphStyle(0, ParagraphStyle.HEADING1))+ }++ @Test+ fun `span format maps every span`() {+ val out = docOf(para()).toggleSpanFormat(0) { it.copy(bold = !it.bold) }!!+ assertTrue((out.content[0] as OdfContentBlock.Paragraph).paragraph.spans.all { it.bold })+ assertNull(docOf(OdfContentBlock.PageBreak).toggleSpanFormat(0) { it })+ }++ @Test+ fun `add duplicate delete move paragraphs`() {+ val d = docOf(para("a"), para("b"))+ assertEquals(3, d.addParagraphAfter(0).content.size)+ // Duplicating inserts the copy right after the source.+ val duped = d.duplicateParagraph(0)!!+ assertEquals(3, duped.content.size)+ assertEquals("a", (((duped.content[1] as OdfContentBlock.Paragraph).paragraph.spans.first().text)))+ assertEquals(1, d.deleteParagraph(0)!!.content.size)+ assertNull(docOf(para("only")).deleteParagraph(0))+ assertNull(d.deleteParagraph(9))+ // Move b above a.+ val moved = d.moveParagraphUp(1)!!+ assertEquals("b", ((moved.content[0] as OdfContentBlock.Paragraph).paragraph.spans.first().text))+ assertNull(d.moveParagraphUp(0))+ val movedDown = d.moveParagraphDown(0)!!+ assertEquals("b", ((movedDown.content[0] as OdfContentBlock.Paragraph).paragraph.spans.first().text))+ assertNull(d.moveParagraphDown(1))+ }++ @Test+ fun `a horizontal line inserts a ruled paragraph`() {+ val d = docOf(para("a"))+ val out = d.insertHorizontalLine(0)+ assertEquals(2, out.content.size)+ assertNotNull((out.content[1] as OdfContentBlock.Paragraph).paragraph.borderColor)+ }++ @Test+ fun `checkbox toggles make and check items`() {+ val made = docOf(para()).toggleCheckbox(0)!!+ val p = (made.content[0] as OdfContentBlock.Paragraph).paragraph+ assertEquals(ParagraphStyle.LIST_ITEM, p.style)+ assertEquals(ListType.CHECKBOX, p.listType)+ assertFalse(p.listChecked)+ val checked = made.setCheckboxChecked(0, true)!!+ assertTrue((checked.content[0] as OdfContentBlock.Paragraph).paragraph.listChecked)+ // A non-checkbox paragraph rejects the checked setter.+ assertNull(docOf(para()).setCheckboxChecked(0, true))+ }++ @Test+ fun `enter on an empty list item exits the list`() {+ val d = docOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("")), style = ParagraphStyle.LIST_ITEM, listLevel = 1))+ )+ val (out, caret) = d.handleListEnter(0, 0, 0)!!+ assertEquals(ParagraphStyle.BODY, styleOf(out, 0))+ assertEquals(0, caret)+ }++ @Test+ fun `enter splits a paragraph at the caret`() {+ val d = docOf(para("hello"))+ val (out, caret) = d.handleListEnter(0, 0, 2)!!+ assertEquals(2, out.content.size)+ assertEquals("he", ((out.content[0] as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { it.text }))+ assertEquals("llo", ((out.content[1] as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { it.text }))+ assertEquals(3, caret)+ assertNull(d.handleListEnter(0, 9, 0))+ }++ @Test+ fun `backspace at a list start outdents or unlists`() {+ val nested = docOf(para("a", ParagraphStyle.LIST_ITEM, 2))+ val (out, _) = nested.handleListBackspace(0, 0, 0)!!+ assertEquals(1, ((out.content[0] as OdfContentBlock.Paragraph).paragraph.listLevel))+ val top = docOf(para("a", ParagraphStyle.LIST_ITEM, 1))+ val (plain, _) = top.handleListBackspace(0, 0, 0)!!+ assertEquals(ParagraphStyle.BODY, styleOf(plain, 0))+ // Mid-paragraph backspace is the default delete (null).+ assertNull(top.handleListBackspace(0, 0, 2))+ assertNull(docOf(para()).handleListBackspace(0, 0, 0))+ }++ @Test+ fun `renumbering assigns per-level indices`() {+ val d = docOf(+ para("a", ParagraphStyle.LIST_ITEM, 1, ListType.NUMBERED, 0),+ para("b", ParagraphStyle.LIST_ITEM, 1, ListType.NUMBERED, 0),+ )+ val out = renumberLists(d)+ assertEquals(1, (out.content[0] as OdfContentBlock.Paragraph).paragraph.listItemIndex)+ assertEquals(2, (out.content[1] as OdfContentBlock.Paragraph).paragraph.listItemIndex)+ }++ @Test+ fun `unnumbered imports gain numbers, numbered ones keep theirs`() {+ val d = docOf(+ para("a", ParagraphStyle.LIST_ITEM, 1, ListType.NUMBERED, 0),+ para("b", ParagraphStyle.LIST_ITEM, 1, ListType.NUMBERED, 5),+ )+ val out = numberUnnumberedListItems(d)+ assertEquals(1, (out.content[0] as OdfContentBlock.Paragraph).paragraph.listItemIndex)+ assertEquals(5, (out.content[1] as OdfContentBlock.Paragraph).paragraph.listItemIndex)+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfRunEditsSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfRunEditsSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfRunEditsSlice1Test.ktnew file mode 100644index 0000000000..88c314dee1--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfRunEditsSlice1Test.kt@@ -0,0 +1,166 @@+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++/**+ * Framework-free single-paragraph and run edits on text documents.+ * Slice-1 coverage for library/ui (odf package).+ */+class OdfRunEditsSlice1Test {++ private fun doc(vararg texts: String) = OdfDocument.TextDocument(+ title = "t",+ content = texts.map { OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(it)))) },+ )++ private fun textOf(d: OdfDocument.TextDocument, i: Int = 0): String =+ (d.content[i] as OdfContentBlock.Paragraph).paragraph.spans.joinToString("") { it.text }++ @Test+ fun `updating text preserves surrounding styling`() {+ val styled = OdfDocument.TextDocument(+ title = "t",+ content = listOf(+ OdfContentBlock.Paragraph(+ OdfParagraph(listOf(OdfSpan("he", bold = true), OdfSpan("llo")))+ )+ ),+ )+ val out = styled.updateParagraphText(0, "hey")!!+ assertEquals("hey", textOf(out))+ // The kept prefix keeps its bold span.+ val spans = (out.content[0] as OdfContentBlock.Paragraph).paragraph.spans+ assertTrue(spans.first().bold)+ }++ @Test+ fun `identical text is a no-op`() {+ assertNull(doc("hello").updateParagraphText(0, "hello"))+ }++ @Test+ fun `a non-paragraph block is a no-op`() {+ val d = OdfDocument.TextDocument(+ title = "t",+ content = listOf(OdfContentBlock.PageBreak),+ )+ assertNull(d.updateParagraphText(0, "x"))+ assertNull(d.updateParagraphText(9, "x"))+ }++ @Test+ fun `span style applies to a char range`() {+ val out = doc("hello").applySpanStyleToRange(0, 1, 3) { it.copy(bold = true) }!!+ val spans = (out.content[0] as OdfContentBlock.Paragraph).paragraph.spans+ // "h" untouched, "el" bolded, "lo" untouched.+ assertEquals(listOf("h", "el", "lo"), spans.map { it.text })+ assertEquals(listOf(false, true, false), spans.map { it.bold })+ }++ @Test+ fun `span style on an empty paragraph is a no-op`() {+ val d = OdfDocument.TextDocument(+ title = "t",+ content = listOf(OdfContentBlock.Paragraph(OdfParagraph(emptyList()))),+ )+ assertNull(d.applySpanStyleToRange(0, 0, 0) { it.copy(bold = true) })+ }++ @Test+ fun `range format queries read the chars`() {+ val d = doc("hello")+ assertTrue(d.rangeHasFormat(0, 0, 5) { !it.bold })+ assertTrue(!d.rangeHasFormat(0, 0, 5) { it.bold })+ assertTrue(!d.rangeHasFormat(9, 0, 5) { true })+ }++ @Test+ fun `a multi-paragraph run update joins the range`() {+ val d = doc("one", "two", "three")+ val out = d.updateParagraphRun(0, 1, "ONE TWO")!!+ assertEquals(2, out.content.size)+ assertEquals("ONE TWO", textOf(out, 0))+ assertEquals("three", textOf(out, 1))+ }++ @Test+ fun `an identical run update is a no-op`() {+ assertNull(doc("one", "two").updateParagraphRun(0, 1, "one\ntwo"))+ }++ @Test+ fun `a run update outside the content is a no-op`() {+ assertNull(doc("one").updateParagraphRun(0, 5, "x"))+ assertNull(doc("one").updateParagraphRun(2, 1, "x"))+ }++ @Test+ fun `run span style bolds a global range`() {+ val d = doc("one", "two")+ val out = d.applyRunSpanStyle(0, 1, 0, 3) { it.copy(bold = true) }!!+ assertEquals("one", textOf(out, 0))+ val spans = (out.content[0] as OdfContentBlock.Paragraph).paragraph.spans+ assertTrue(spans.all { it.bold })+ // The second paragraph is untouched.+ val spans2 = (out.content[1] as OdfContentBlock.Paragraph).paragraph.spans+ assertTrue(spans2.none { it.bold })+ }++ @Test+ fun `run format queries span paragraphs`() {+ val d = doc("one", "two")+ assertTrue(d.runRangeHasFormat(0, 1, 0, 3) { !it.bold })+ assertTrue(!d.runRangeHasFormat(0, 1, 0, 3) { it.bold })+ assertTrue(!d.runRangeHasFormat(0, 5, 0, 3) { true })+ }++ @Test+ fun `run paragraph index resolves global offsets`() {+ val d = doc("one", "two")+ assertEquals(0, d.runParagraphIndexAt(0, 1, 1))+ assertEquals(1, d.runParagraphIndexAt(0, 1, 4))+ // Out of range: the run is absent, so the answer is the start itself.+ assertEquals(5, d.runParagraphIndexAt(5, 6, 0))+ }++ @Test+ fun `mutating run paragraphs transforms the covered ones`() {+ val d = doc("one", "two", "three")+ val out = d.mutateRunParagraphs(0, 2, 0, 7) { it.copy(alignment = androidx.compose.ui.text.style.TextAlign.Center) }!!+ val first = (out.content[0] as OdfContentBlock.Paragraph).paragraph+ assertEquals(androidx.compose.ui.text.style.TextAlign.Center, first.alignment)+ assertNull(d.mutateRunParagraphs(0, 9, 0, 1) { it })+ }++ @Test+ fun `inserting text in a run splices at the offset`() {+ val d = doc("one", "two")+ // Global offset 3 appends to the first paragraph (no newline spans it).+ val out = d.insertTextInRun(0, 1, 3, "!")!!+ assertEquals("one!", textOf(out, 0))+ assertEquals("two", textOf(out, 1))+ // A newline in the insert splits the run into more paragraphs.+ val split = d.insertTextInRun(0, 1, 3, "!\nmid")!!+ assertEquals("one!", textOf(split, 0))+ assertEquals("mid", textOf(split, 1))+ assertEquals("two", textOf(split, 2))+ assertNull(d.insertTextInRun(0, 9, 0, "x"))+ }++ @Test+ fun `clearing run formatting drops span styles`() {+ val d = OdfDocument.TextDocument(+ title = "t",+ content = listOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("hi", bold = true, italic = true))))+ ),+ )+ val out = d.clearRunFormatting(0, 0, 0, 2)!!+ val spans = (out.content[0] as OdfContentBlock.Paragraph).paragraph.spans+ assertTrue(spans.all { !it.bold && !it.italic })+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfSerializerDetailsSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfSerializerDetailsSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfSerializerDetailsSlice1Test.ktnew file mode 100644index 0000000000..1ce6f45c54--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfSerializerDetailsSlice1Test.kt@@ -0,0 +1,247 @@+package com.vayunmathur.library.ui.odf++import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * ODF serialization details: tracked changes, table of contents, footnotes,+ * shapes, frames, charts, sections, spreadsheet styles and number formats.+ * Slice-1 coverage for library/ui (odf package).+ */+class OdfSerializerDetailsSlice1Test {++ private fun para(text: String, style: ParagraphStyle = ParagraphStyle.BODY) =+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text)), style = style))++ private fun textDoc(vararg blocks: OdfContentBlock, title: String = "T") =+ OdfDocument.TextDocument(title = title, content = blocks.toList())++ @Test+ fun `insertions and deletions serialize as tracked changes`() {+ val doc = textDoc(+ OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(+ OdfSpan("new", changeId = "c1", changeKind = "insertion"),+ OdfSpan("old", changeId = "c2", changeKind = "deletion"),+ )+ )+ )+ ).copy(changes = listOf(OdfChange(id = "c1", type = "insertion", author = "Ada", date = "2024-01-01")))+ val xml = OdfSerializer.serialize(doc)+ assertTrue(xml.contains("text:tracked-changes"), xml.take(3000))+ assertTrue(xml.contains("Ada"), xml)+ assertTrue(xml.contains("<text:p>old</text:p>"), xml)+ }++ @Test+ fun `a document without changes has no tracked-changes element`() {+ val xml = OdfSerializer.serialize(textDoc(para("plain")))+ assertTrue(!xml.contains("text:tracked-changes"), xml.take(2000))+ }++ @Test+ fun `a table of contents serializes its entries`() {+ val toc = OdfContentBlock.TableOfContents(+ "Contents",+ listOf(OdfParagraph(listOf(OdfSpan("Chapter 1")), style = ParagraphStyle.HEADING1)),+ )+ val xml = OdfSerializer.serialize(textDoc(toc))+ assertTrue(xml.contains("text:table-of-content"), xml.take(3000))+ assertTrue(xml.contains("Chapter 1"), xml)+ }++ @Test+ fun `a footnote marker serializes the note`() {+ val doc = textDoc(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("[1]", superscript = true))))+ ).copy(footnotes = listOf(OdfFootnote("1", listOf(OdfParagraph(listOf(OdfSpan("note body")))))))+ val xml = OdfSerializer.serialize(doc)+ assertTrue(xml.contains("note body"), xml.take(6000))+ }++ @Test+ fun `a chart block serializes a chart frame`() {+ val chart = OdfChart(+ type = ChartType.BAR,+ categories = listOf("Q1", "Q2"),+ series = listOf(OdfChartSeries("S", listOf(1f, 2f), color = 0xFF0000)),+ title = "Sales",+ )+ val doc = textDoc(OdfContentBlock.Chart(chart))+ val xml = OdfSerializer.serialize(doc)+ assertTrue(xml.contains("Sales"), xml.take(6000))+ // A chart in flat content serializes as a placeholder frame; the full+ // chart XML ships in the package objects (covered below).+ assertTrue(xml.contains("draw:frame"), xml.take(6000))+ }++ @Test+ fun `a chart object serializes into the package`() {+ val chart = OdfChart(+ type = ChartType.PIE,+ categories = listOf("A", "B"),+ series = listOf(OdfChartSeries("S", listOf(3f, 4f))),+ )+ val res = OdfSerializer.serializePackaged(textDoc(OdfContentBlock.Chart(chart)))+ assertTrue(res.objects.isNotEmpty())+ assertTrue(res.objects.values.any { it.contains("pie") || it.contains("chart") }, res.objects.keys.toString())+ }++ @Test+ fun `a spreadsheet with a formula serializes the formula`() {+ val doc = OdfDocument.Spreadsheet(+ title = "S",+ sheets = listOf(+ OdfSheet(+ name = "Sheet1",+ rows = listOf(OdfRow(listOf(OdfCell("1"), OdfCell("2", formula = "SUM(A1:B1)")))),+ )+ ),+ )+ val xml = OdfSerializer.serialize(doc)+ assertTrue(xml.contains("SUM(A1:B1)"), xml.take(4000))+ }++ @Test+ fun `a spreadsheet with column widths serializes column styles`() {+ val doc = OdfDocument.Spreadsheet(+ title = "S",+ sheets = listOf(+ OdfSheet(+ name = "Sheet1",+ rows = listOf(OdfRow(listOf(OdfCell("v")))),+ columnWidths = listOf(120f),+ )+ ),+ )+ val xml = OdfSerializer.serialize(doc)+ assertTrue(xml.contains("table:table-column"), xml.take(4000))+ }++ @Test+ fun `a section start with columns serializes the section`() {+ val xml = OdfSerializer.serialize(+ textDoc(+ OdfContentBlock.SectionStart("S1", columnCount = 2),+ para("inside"),+ OdfContentBlock.SectionEnd,+ )+ )+ assertTrue(xml.contains("inside"), xml.take(4000))+ assertTrue(xml.contains("text:section"), xml.take(4000))+ }++ @Test+ fun `a numbered list serializes a list style`() {+ val xml = OdfSerializer.serialize(+ textDoc(+ OdfContentBlock.Paragraph(+ OdfParagraph(+ listOf(OdfSpan("one")),+ style = ParagraphStyle.LIST_ITEM,+ listLevel = 1,+ listType = ListType.NUMBERED,+ )+ )+ )+ )+ assertTrue(xml.contains("text:list"), xml.take(4000))+ assertTrue(xml.contains("one"), xml)+ }++ @Test+ fun `a presentation with a shape slide serializes the shape`() {+ val doc = OdfDocument.Presentation(+ title = "P",+ slides = listOf(+ OdfSlide(+ name = "S1",+ elements = listOf(+ OdfSlideElement.Shape(+ OdfShape.Rect(+ x = 10f, y = 20f, width = 100f, height = 50f,+ fillColor = 0xFF0000,+ text = listOf(OdfParagraph(listOf(OdfSpan("caption")))),+ )+ )+ ),+ )+ ),+ )+ val xml = OdfSerializer.serialize(doc)+ assertTrue(xml.contains("caption"), xml.take(8000))+ assertTrue(xml.contains("draw:") , xml.take(8000))+ }++ @Test+ fun `a presentation with a frame image serializes the frame`() {+ val doc = OdfDocument.Presentation(+ title = "P",+ slides = listOf(+ OdfSlide(+ name = "S1",+ elements = listOf(+ OdfSlideElement.Frame(+ OdfFrame(+ x = 0f, y = 0f, width = 200f, height = 100f,+ paragraphs = listOf(OdfParagraph(listOf(OdfSpan("frame text")))),+ )+ )+ ),+ )+ ),+ )+ val xml = OdfSerializer.serialize(doc)+ assertTrue(xml.contains("frame text"), xml.take(8000))+ }++ @Test+ fun `a datetime field serializes a date element`() {+ val xml = OdfSerializer.serialize(+ textDoc(+ OdfContentBlock.Paragraph(+ OdfParagraph(listOf(OdfSpan("2024-01-01", field = "date")))+ )+ )+ )+ assertTrue(xml.contains("text:date") || xml.contains("2024-01-01"), xml.take(4000))+ }++ @Test+ fun `a bordered paragraph serializes its border`() {+ val xml = OdfSerializer.serialize(+ textDoc(+ OdfContentBlock.Paragraph(+ OdfParagraph(listOf(OdfSpan("boxed")), borderColor = 0x000000)+ )+ )+ )+ assertTrue(xml.contains("boxed"), xml.take(4000))+ assertTrue(xml.contains("fo:border"), xml.take(8000))+ }++ @Test+ fun `a spreadsheet date cell serializes a number style`() {+ val doc = OdfDocument.Spreadsheet(+ title = "S",+ sheets = listOf(+ OdfSheet(+ name = "Sheet1",+ rows = listOf(+ OdfRow(+ listOf(+ OdfCell(+ "2024-01-01",+ numberFormat = OdfNumberFormat(isDate = true),+ )+ )+ )+ ),+ )+ ),+ )+ val xml = OdfSerializer.serialize(doc)+ assertTrue(xml.contains("2024-01-01"), xml.take(6000))+ }+}
library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfSerializerMetaSlice1Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfSerializerMetaSlice1Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfSerializerMetaSlice1Test.ktnew file mode 100644index 0000000000..230342ba4b--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/odf/OdfSerializerMetaSlice1Test.kt@@ -0,0 +1,180 @@+package com.vayunmathur.library.ui.odf++import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * ODF serializer round three: full metadata, number styles, validation+ * rules, named ranges, floating sheet objects, shapes. Slice-1 coverage.+ */+class OdfSerializerMetaSlice1Test {++ private fun para(text: String) =+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text))))++ @Test+ fun `full metadata serializes every field`() {+ val meta = OdfMetadata(+ title = "Doc",+ author = "Ada",+ creator = "Bo",+ creationDate = "2024-01-01",+ modifiedDate = "2024-02-02",+ description = "desc",+ subject = "subj",+ keywords = listOf("k"),+ pageCount = 3,+ wordCount = 100,+ charCount = 500,+ paragraphCount = 10,+ editingCycles = 7,+ generator = "Test/1.0",+ userDefined = mapOf("reviewed" to "yes"),+ userDefinedTypes = mapOf("reviewed" to "boolean"),+ )+ val xml = OdfSerializer.serializeMeta(meta)+ assertTrue(xml.contains("initial-creator"), xml)+ assertTrue(xml.contains("Bo"), xml)+ assertTrue(xml.contains("document-statistic"), xml)+ assertTrue(xml.contains("page-count=\"3\""), xml)+ assertTrue(xml.contains("user-defined"), xml)+ assertTrue(xml.contains("value-type=\"boolean\""), xml)+ assertTrue(xml.contains("Test/1.0"), xml)+ }++ @Test+ fun `number styles cover date time scientific fraction currency percent`() {+ val doc = OdfDocument.Spreadsheet(+ title = "S",+ sheets = listOf(+ OdfSheet(+ name = "Sheet1",+ rows = listOf(+ OdfRow(+ listOf(+ OdfCell("2024-01-01", numberFormat = OdfNumberFormat(isDate = true)),+ OdfCell(+ "12:00",+ numberFormat = OdfNumberFormat(+ isTime = true,+ dateTimeTokens = listOf(+ OdfNumberToken("hours", style = "long"),+ OdfNumberToken("text", text = ":"),+ OdfNumberToken("minutes", style = "long"),+ OdfNumberToken("seconds"),+ OdfNumberToken("am-pm"),+ ),+ ),+ ),+ OdfCell("1e5", numberFormat = OdfNumberFormat(isScientific = true)),+ OdfCell("1/2", numberFormat = OdfNumberFormat(isFraction = true)),+ OdfCell(+ "$1.00",+ numberFormat = OdfNumberFormat(currencySymbol = "$", grouping = true),+ ),+ OdfCell("50%", numberFormat = OdfNumberFormat(percent = true)),+ OdfCell("1.5", numberFormat = OdfNumberFormat(decimals = 2, grouping = true)),+ )+ )+ ),+ )+ ),+ )+ val xml = OdfSerializer.serialize(doc)+ assertTrue(xml.contains("number:date-style"), xml.take(8000))+ assertTrue(xml.contains("number:time-style"), xml)+ assertTrue(xml.contains("scientific-number"), xml)+ assertTrue(xml.contains("number:fraction"), xml)+ assertTrue(xml.contains("currency-style"), xml)+ assertTrue(xml.contains("percentage-style"), xml)+ assertTrue(xml.contains("am-pm") || xml.contains("AM/PM"), xml)+ }++ @Test+ fun `validations and named ranges serialize`() {+ val doc = OdfDocument.Spreadsheet(+ title = "S",+ sheets = listOf(OdfSheet(name = "Sheet1", rows = listOf(OdfRow(listOf(OdfCell("v")))))),+ namedRanges = listOf(OdfNamedRange("R1"
Diff truncated.