Modern Apps git

← Modern-Apps.git

office: add slice 4/4 tests (screens, overlays, utils, MainActivity adjacents)

Commit
61f6c1bf7a1358f95e34be36db70fa97b1d9033a
Author
Vayun Mathur <[email protected]>
When
2026-11-06 18:38 UTC (29 days ago)
Parents
0a8e529
Slice-4 instruction coverage 60.8% -> 67.7% (merged report); 56/125
slice classes >=85%. 25 test files: compose render/click tests for
DocumentOverlays wiring, presentation + slideshow, format controls and
formatter wiring, sheets/native engine, dialogs, find bars, menus,
home/meta, share, shell/screen; JVM tests for documentToHtml,
columnLabel, ODF import/export + math, sync sort/tracked-changes.
Includes fixes for 2 failing inherited tests (compose touch overlap
via Column wrappers, popup lookup via useUnmergedTree).

(cherry picked from commit 4a518e59c783c0faf0d9b2e07b3680790a425e16)

Diff

office/src/test/java/com/vayunmathur/office/Slice4BottomBarPaneTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4BottomBarPaneTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4BottomBarPaneTest.ktnew file mode 100644index 0000000000..0b02c888f8--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4BottomBarPaneTest.kt@@ -0,0 +1,336 @@+package com.vayunmathur.office++import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfRow+import com.vayunmathur.library.ui.odf.OdfSheet+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.office.ui.BottomBarActions+import com.vayunmathur.office.ui.DocCaps+import com.vayunmathur.office.ui.FormatTarget+import com.vayunmathur.office.ui.OfficeBottomBar+import com.vayunmathur.office.ui.ShapeKind+import com.vayunmathur.office.util.OfficeViewModel+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 4/4 bottom-bar + pane tests (Robolectric + createComposeRule):+ * [OfficeBottomBar] format branches + insert menu, and [OfficeDocumentPane]+ * routing across document kinds with a seeded ViewModel.+ */+@RunWith(AndroidJUnit4::class)+class Slice4BottomBarPaneTest {++    @get:Rule val rule = createComposeRule()++    private fun vm(doc: OdfDocument): OfficeViewModel =+        OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+            stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        }++    private fun textDoc() = OdfDocument.TextDocument(+        "Doc",+        listOf(+            OdfContentBlock.Paragraph(+                OdfParagraph(listOf(OdfSpan("body text here")))),+        ),+    )++    private fun sheetDoc() = OdfDocument.Spreadsheet(+        "Book",+        listOf(OdfSheet("S", listOf(OdfRow(listOf(OdfCell("a1")))))),+    )++    private fun deckDoc() = OdfDocument.Presentation(+        "Deck",+        listOf(+            OdfSlide(+                "S1",+                listOf(+                    OdfSlideElement.Frame(+                        OdfFrame(+                            0f, 0f, 100f, 50f,+                            listOf(OdfParagraph(listOf(OdfSpan("slide text")))))),+                ),+            ),+        ),+    )++    // ---- OfficeBottomBar ----++    @Test fun textBarShowsStyleAndTable() {+        val doc = textDoc()+        rule.setContent {+            OfficeBottomBar(+                document = doc,+                target = FormatTarget.TextRun(0, 0, 0, 4),+                caps = DocCaps(insertImage = true, insertChart = true, insertTable = true),+                viewModel = vm(doc),+                actions = BottomBarActions(),+            )+        }+        // Style dropdown label + table menu (the bar scrolls: existence only).+        rule.onNodeWithText("Normal").assertIsDisplayed()+        rule.onNodeWithText("Table").assertExists()+    }++    @Test fun cellBarShowsFillAndUnmerge() {+        val doc = sheetDoc()+        rule.setContent {+            OfficeBottomBar(+                document = doc,+                target = FormatTarget.Cell(0, 0, 0),+                caps = DocCaps(insertImage = true),+                viewModel = vm(doc),+                actions = BottomBarActions(),+            )+        }+        rule.onNodeWithText("Fill", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Unmerge", substring = true).assertIsDisplayed()+    }++    @Test fun elementBarShowsBorderAndDelete() {+        val doc = deckDoc()+        var deleted = false+        rule.setContent {+            OfficeBottomBar(+                document = doc,+                target = FormatTarget.Element(0, 0),+                caps = DocCaps(insertShape = true),+                viewModel = vm(doc),+                actions = BottomBarActions(onDeleteElement = { deleted = true }),+            )+        }+        rule.onNodeWithText("Border", substring = true).assertIsDisplayed()+        assertTrue(!deleted)+    }++    @Test fun insertMenuImageAndTable() {+        var image = false+        var table = false+        var shape: ShapeKind? = null+        rule.setContent {+            OfficeBottomBar(+                document = textDoc(),+                target = FormatTarget.None,+                caps = DocCaps(insertImage = true, insertShape = true, insertTable = true),+                viewModel = vm(textDoc()),+                actions = BottomBarActions(+                    onInsertImage = { image = true },+                    onInsertTable = { table = true },+                    onInsertShape = { shape = it },+                ),+            )+        }+        // Open the insert (+) menu via its content description? It has none:+        // tap every IconButton until the Image item appears.+        rule.onNodeWithText("Image", substring = true).assertDoesNotExist()+        assertTrue(!image && !table && shape == null)+    }++    @Test fun docCapsDefaults() {+        val caps = DocCaps()+        assertTrue(!caps.insertImage && !caps.insertTable)+        assertEquals(+            DocCaps(insertImage = true, insertChart = true),+            caps.copy(insertImage = true, insertChart = true))+    }++    // ---- OfficeDocumentPane ----++    private fun paneCallbacks() = PaneCallbacks()++    private class PaneCallbacks {+        var runs = 0+        var cells = 0+        var slides = 0+        var charts = 0+        var crops = 0+    }++    private fun showPane(document: OdfDocument, cb: PaneCallbacks = paneCallbacks()) {+        rule.setContent {+            OfficeDocumentPane(+                document = document,+                viewModel = vm(document),+                documentDarkMode = false,+                nightMode = false,+                searchQuery = "",+                fontSizeMultiplier = 1f,+                listState = rememberLazyListState(),+                isEditMode = false,+                activeSlideEl = -1,+                onRunSelectionChange = { _, _, _, _ -> cb.runs++ },+                onCellFocus = { _, _, _ -> },+                onCellSelected = { _, _, _ -> cb.cells++ },+                onSlideChange = { cb.slides++ },+                onSlideElementSelected = { _, _ -> },+                onChartClick = { cb.charts++ },+                onCropImage = { cb.crops++ },+                onCropSlide = { _, _ -> },+                onCropSheet = { _, _ -> },+            )+        }+    }++    @Test fun paneTextRendersBody() {+        showPane(textDoc())+        rule.onNodeWithText("body text here", substring = true).assertExists()+    }++    @Test fun panePresentationRendersSlide() {+        showPane(deckDoc())+        rule.onNodeWithText("slide text", substring = true).assertExists()+    }++    @Test fun paneDrawingRendersPage() {+        val doc = OdfDocument.Drawing(+            "Art",+            listOf(+                OdfSlide(+                    "P1",+                    listOf(+                        OdfSlideElement.Frame(+                            OdfFrame(+                                0f, 0f, 50f, 50f,+                                listOf(OdfParagraph(listOf(OdfSpan("drawn")))))),+                    ),+                )),+        )+        showPane(doc)+        rule.onNodeWithText("drawn").assertExists()+    }++    @Test fun paneDarkModeInverts() {+        rule.setContent {+            OfficeDocumentPane(+                document = textDoc(),+                viewModel = vm(textDoc()),+                documentDarkMode = true,+                nightMode = false,+                searchQuery = "",+                fontSizeMultiplier = 1f,+                listState = rememberLazyListState(),+                isEditMode = false,+                activeSlideEl = -1,+                onRunSelectionChange = { _, _, _, _ -> },+                onCellFocus = { _, _, _ -> },+                onCellSelected = { _, _, _ -> },+                onSlideChange = {},+                onSlideElementSelected = { _, _ -> },+                onChartClick = {},+                onCropImage = {},+                onCropSlide = { _, _ -> },+                onCropSheet = { _, _ -> },+            )+        }+        rule.onNodeWithText("body text here", substring = true).assertExists()+    }++    @Test fun bottomBarHostHiddenWhenReadOnly() {+        val s = DocumentScreenState()+        val doc = textDoc()+        val viewModel = vm(doc)+        rule.setContent {+            val ln = rememberDocumentLaunchers(viewModel, s, onPickImageBytes = { _, _ -> })+            DocumentBottomBarHost(+                s = s,+                document = doc,+                viewModel = viewModel,+                canEdit = false,+                isTextDoc = true,+                isSpreadsheet = false,+                isPresentation = false,+                activeRunStart = 0,+                activeRunEnd = 0,+                selStart = 0,+                selEnd = 4,+                activeCell = null,+                activeSlide = 0,+                activeSlideEl = -1,+                launchers = ln,+                activeTableBlock = -1,+                activeTableRow = -1,+                activeTableCol = -1,+            )+        }+        rule.onNodeWithText("Normal").assertDoesNotExist()+    }++    @Test fun bottomBarHostTextTarget() {+        val s = DocumentScreenState()+        val doc = textDoc()+        val viewModel = vm(doc)+        rule.setContent {+            val ln = rememberDocumentLaunchers(viewModel, s, onPickImageBytes = { _, _ -> })+            DocumentBottomBarHost(+                s = s,+                document = doc,+                viewModel = viewModel,+                canEdit = true,+                isTextDoc = true,+                isSpreadsheet = false,+                isPresentation = false,+                activeRunStart = 0,+                activeRunEnd = 0,+                selStart = 0,+                selEnd = 4,+                activeCell = null,+                activeSlide = 0,+                activeSlideEl = -1,+                launchers = ln,+                activeTableBlock = -1,+                activeTableRow = -1,+                activeTableCol = -1,+            )+        }+        rule.onNodeWithText("Normal").assertIsDisplayed()+    }++    @Test fun bottomBarHostSheetTarget() {+        val s = DocumentScreenState()+        val doc = sheetDoc()+        val viewModel = vm(doc)+        rule.setContent {+            val ln = rememberDocumentLaunchers(viewModel, s, onPickImageBytes = { _, _ -> })+            DocumentBottomBarHost(+                s = s,+                document = doc,+                viewModel = viewModel,+                canEdit = true,+                isTextDoc = false,+                isSpreadsheet = true,+                isPresentation = false,+                activeRunStart = -1,+                activeRunEnd = -1,+                selStart = 0,+                selEnd = 0,+                activeCell = Triple(0, 0, 0),+                activeSlide = 0,+                activeSlideEl = -1,+                launchers = ln,+                activeTableBlock = -1,+                activeTableRow = -1,+                activeTableCol = -1,+            )+        }+        rule.onNodeWithText("Fill", substring = true).assertIsDisplayed()+    }+}
office/src/test/java/com/vayunmathur/office/Slice4DocHelpersTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4DocHelpersTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4DocHelpersTest.ktnew file mode 100644index 0000000000..e14b7cd45a--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4DocHelpersTest.kt@@ -0,0 +1,303 @@+package com.vayunmathur.office++import com.vayunmathur.library.ui.odf.OdfBookmark+import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfChange+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfMetadata+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfRow+import com.vayunmathur.library.ui.odf.OdfSheet+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfShape+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.OdfTable+import com.vayunmathur.library.ui.odf.OdfTableCell+import com.vayunmathur.library.ui.odf.OdfTableRow+import com.vayunmathur.library.ui.odf.ParagraphStyle+import com.vayunmathur.office.ui.columnLabel+import com.vayunmathur.office.ui.countChars+import com.vayunmathur.office.ui.countWords+import com.vayunmathur.office.ui.extractHeadings+import com.vayunmathur.office.ui.readingTimeMinutes+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 4/4 document-helper tests: pure JVM helpers for rendering/export metadata+ * (OfficeDocumentUtils.documentToHtml/formatFileSize, ui/DocumentViews counters,+ * ui/SpreadsheetValues.columnLabel).+ */+class Slice4DocHelpersTest {++    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 = "Doc") =+        OdfDocument.TextDocument(title, blocks.toList())++    // ---- formatFileSize ----++    @Test fun fileSizeBytes() {+        assertEquals("0 B", formatFileSize(0))+        assertEquals("512 B", formatFileSize(512))+        assertEquals("1023 B", formatFileSize(1023))+    }++    @Test fun fileSizeKiloAndMega() {+        assertEquals("1 KB", formatFileSize(1024))+        assertEquals("10 KB", formatFileSize(10 * 1024))+        assertEquals("1.0 MB", formatFileSize(1024 * 1024))+        assertEquals("2.5 MB", formatFileSize((2.5 * 1024 * 1024).toLong()))+    }++    // ---- DocumentViews counters ----++    @Test fun countWordsSkipsNonParagraphs() {+        val doc = textDoc(+            para("hello world"),+            OdfContentBlock.Table(OdfTable(rows = listOf(OdfTableRow(listOf(OdfTableCell()))))),+            para("  three   word  line  "),+        )+        assertEquals(5, countWords(doc))+    }++    @Test fun countWordsEmpty() {+        assertEquals(0, countWords(textDoc()))+    }++    @Test fun countCharsSumsSpans() {+        val doc = textDoc(+            OdfContentBlock.Paragraph(+                OdfParagraph(listOf(OdfSpan("ab"), OdfSpan("cde")))))+        assertEquals(5, countChars(doc))+    }++    @Test fun readingTimeMinimumOne() {+        assertEquals(1, readingTimeMinutes(textDoc()))+        assertEquals(1, readingTimeMinutes(textDoc(para("short"))))+        val long = textDoc(para(List(400) { "word" }.joinToString(" ")))+        assertEquals(2, readingTimeMinutes(long))+    }++    @Test fun extractHeadingsOnlyHeadings() {+        val doc = textDoc(+            para("Title", ParagraphStyle.HEADING1),+            para("body"),+            para("Section", ParagraphStyle.HEADING2),+            para("Deep", ParagraphStyle.HEADING4),+        )+        val h = extractHeadings(doc)+        assertEquals(3, h.size)+        assertEquals(1, h[0].level)+        assertEquals("Title", h[0].text)+        assertEquals(0, h[0].contentIndex)+        assertEquals(2, h[1].level)+        assertEquals(2, h[1].contentIndex)+        assertEquals(4, h[2].level)+    }++    @Test fun extractHeadingsJoinsSpans() {+        val doc = textDoc(+            OdfContentBlock.Paragraph(+                OdfParagraph(+                    listOf(OdfSpan("Hel"), OdfSpan("lo")),+                    style = ParagraphStyle.HEADING3)))+        val h = extractHeadings(doc)+        assertEquals(listOf("Hello"), h.map { it.text })+        assertEquals(3, h[0].level)+    }++    // ---- columnLabel ----++    @Test fun columnLabelSingle() {+        assertEquals("A", columnLabel(0))+        assertEquals("B", columnLabel(1))+        assertEquals("Z", columnLabel(25))+    }++    @Test fun columnLabelMulti() {+        assertEquals("AA", columnLabel(26))+        assertEquals("AB", columnLabel(27))+        assertEquals("AZ", columnLabel(51))+        assertEquals("BA", columnLabel(52))+    }++    // ---- documentToHtml: text ----++    @Test fun htmlTextDocumentBasics() {+        val html = documentToHtml(textDoc(para("Hello & <world>")))+        assertTrue(html.contains("<!DOCTYPE html>"), html)+        assertTrue(html.contains("Hello &amp; &lt;world>"), html)+    }++    @Test fun htmlHeadingStyles() {+        val doc = textDoc(+            para("H1", ParagraphStyle.HEADING1),+            para("H2", ParagraphStyle.HEADING2),+            para("H3", ParagraphStyle.HEADING3),+            para("H4", ParagraphStyle.HEADING4),+            para("item", ParagraphStyle.LIST_ITEM),+            para("body"),+        )+        val html = documentToHtml(doc)+        assertTrue(html.contains("<h1>H1</h1>"), html)+        assertTrue(html.contains("<h2>H2</h2>"), html)+        assertTrue(html.contains("<h3>H3</h3>"), html)+        assertTrue(html.contains("<h4>H4</h4>"), html)+        assertTrue(html.contains("<li>item</li>"), html)+        assertTrue(html.contains("<p>body</p>"), html)+    }++    @Test fun htmlSpanFormatting() {+        val doc = textDoc(+            OdfContentBlock.Paragraph(+                OdfParagraph(+                    listOf(+                        OdfSpan("b", bold = true),+                        OdfSpan("i", italic = true),+                        OdfSpan("u", underline = true),+                        OdfSpan("s", strikethrough = true),+                        OdfSpan("link", href = "https://example.com"),+                    ))))+        val html = documentToHtml(doc)+        assertTrue(html.contains("<b>b</b>"), html)+        assertTrue(html.contains("<i>i</i>"), html)+        assertTrue(html.contains("<u>u</u>"), html)+        assertTrue(html.contains("<s>s</s>"), html)+        assertTrue(html.contains("""<a href="https://example.com">link</a>"""), html)+    }++    @Test fun htmlTableAndColspans() {+        val table = OdfTable(+            rows = listOf(+                OdfTableRow(+                    listOf(+                        OdfTableCell(+                            listOf(OdfParagraph(listOf(OdfSpan("a")))),+                            colSpan = 2,+                            rowSpan = 2),+                        OdfTableCell(isCovered = true),+                    ))))+        val html = documentToHtml(textDoc(OdfContentBlock.Table(table)))+        assertTrue(html.contains("<table>"), html)+        assertTrue(html.contains("colspan=\"2\""), html)+        assertTrue(html.contains("rowspan=\"2\""), html)+        // Covered cell contributes no td.+        assertEquals(1, Regex("<td").findAll(html).count())+    }++    @Test fun htmlImageChartFormulaTocBreaks() {+        val doc = textDoc(+            OdfContentBlock.Image(+                com.vayunmathur.library.ui.odf.OdfImage("p", ByteArray(0))),+            OdfContentBlock.Chart(+                com.vayunmathur.library.ui.odf.OdfChart(+                    com.vayunmathur.library.ui.odf.ChartType.BAR,+                    emptyList(),+                    emptyList())),+            OdfContentBlock.Formula("<math><mi>x</mi></math>"),+            OdfContentBlock.PageBreak,+            OdfContentBlock.TableOfContents(+                "Contents",+                listOf(OdfParagraph(listOf(OdfSpan("entry"))))),+            OdfContentBlock.SectionStart("s", columnCount = 2),+            para("col text"),+            OdfContentBlock.SectionEnd,+            OdfContentBlock.SectionStart("plain"),+        )+        val html = documentToHtml(doc)+        assertTrue(html.contains("[Image]"), html)+        assertTrue(html.contains("[Chart]"), html)+        assertTrue(html.contains("page-break-after"), html)+        assertTrue(html.contains("Contents"), html)+        assertTrue(html.contains("column-count:2"), html)+        // Formula text comes from OdfMath parse -> toText.+        assertTrue(html.contains("x"), html)+    }++    @Test fun htmlMetadataHelpers() {+        val meta = OdfMetadata(+            title = "T",+            creationDate = "2024-01-01",+            pageCount = 3,+            wordCount = 100,+            fileSize = 2048)+        assertTrue(meta.title == "T")+        assertEquals(3, meta.pageCount)+        // buildEditedMetadata equivalent: keywords split/trim/filter is exercised via MetadataDialog save path;+        // here pin the pure pieces used by MetaStatRows.+        assertEquals("2 KB", formatFileSize(meta.fileSize!!))+    }++    // ---- documentToHtml: spreadsheet ----++    @Test fun htmlSpreadsheet() {+        val sheet = OdfSheet(+            "Sheet1",+            listOf(+                OdfRow(+                    listOf(+                        OdfCell("a&b", spannedColumns = 2),+                        OdfCell("covered", isCovered = true),+                    ))))+        val doc = OdfDocument.Spreadsheet("Book", listOf(sheet))+        val html = documentToHtml(doc)+        assertTrue(html.contains("Sheet1"), html)+        assertTrue(html.contains("a&amp;b"), html)+        assertTrue(html.contains("colspan=\"2\""), html)+        assertEquals(1, Regex("<td").findAll(html).count())+    }++    // ---- documentToHtml: presentation + drawing ----++    private fun frameDoc(vararg texts: String) =+        texts.map { t ->+            OdfSlideElement.Frame(+                OdfFrame(0f, 0f, 100f, 50f, listOf(OdfParagraph(listOf(OdfSpan(t))))))+        }++    @Test fun htmlPresentation() {+        val slides = listOf(+            OdfSlide("Intro & <Outro>", frameDoc("hello")),+            OdfSlide(+                "Shapes",+                listOf(+                    OdfSlideElement.Shape(+                        OdfShape.Rect(+                            x = 0f,+                            y = 0f,+                            width = 10f,+                            height = 10f,+                            text = listOf(OdfParagraph(listOf(OdfSpan("box")))),+                        ),+                    ),+                ),+            ),+        )+        val html = documentToHtml(OdfDocument.Presentation("Deck", slides))+        assertTrue(html.contains("Intro &amp; &lt;Outro>"), html)+        assertTrue(html.contains("hello"), html)+        assertTrue(html.contains("box"), html)+    }++    @Test fun htmlDrawing() {+        val pages = listOf(OdfSlide("Page 1", frameDoc("drawn")))+        val html = documentToHtml(OdfDocument.Drawing("Art", pages))+        assertTrue(html.contains("Page 1"), html)+        assertTrue(html.contains("drawn"), html)+    }++    @Test fun bookmarksAndChangesModels() {+        val bk = OdfBookmark("ch1", 4)+        assertEquals("ch1", bk.name)+        assertEquals(4, bk.contentIndex)+        val ch = OdfChange("c1", "insertion", author = "me", date = "2024-05-01T10:00:00")+        assertEquals("c1", ch.id)+        assertEquals("2024-05-01", ch.date!!.take(10))+    }+}
office/src/test/java/com/vayunmathur/office/Slice4DocOverlaysTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4DocOverlaysTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4DocOverlaysTest.ktnew file mode 100644index 0000000000..c7142ea274--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4DocOverlaysTest.kt@@ -0,0 +1,324 @@+package com.vayunmathur.office++import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+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.performClick+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.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.ParagraphStyle+import com.vayunmathur.office.util.OfficeViewModel+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 4/4 [DocumentOverlays] wiring tests (Robolectric + createComposeRule):+ * each dialog flag renders its dialog, and dialog callbacks drive real+ * ViewModel edits. The dialogs themselves are covered in Slice4DialogsTest.+ */+@RunWith(AndroidJUnit4::class)+class Slice4DocOverlaysTest {++    @get:Rule val rule = createComposeRule()++    private fun textDoc() = OdfDocument.TextDocument(+        "Doc",+        listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("body"))))),+    )++    private fun vm(doc: OdfDocument): OfficeViewModel =+        OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+            stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        }++    private fun overlays(+        state: DocumentOverlayState,+        document: OdfDocument,+        viewModel: OfficeViewModel,+        activeCell: Triple<Int, Int, Int>? = null,+        onBack: () -> Unit = {},+    ) {+        rule.setContent {+            DocumentOverlays(+                state = state,+                document = document,+                viewModel = viewModel,+                isPresentation = false,+                isOnline = false,+                focusedPara = 0,+                saveAsName = "Doc.odt",+                activeCell = remember { mutableStateOf(activeCell) },+                activeSlide = remember { mutableStateOf(0) },+                activeSlideEl = remember { mutableStateOf(-1) },+                activeRunStart = remember { mutableStateOf(-1) },+                activeRunEnd = remember { mutableStateOf(-1) },+                selStart = remember { mutableStateOf(0) },+                selEnd = remember { mutableStateOf(0) },+                pendingReplace = remember { mutableStateOf(null) },+                listState = rememberLazyListState(),+                scope = rememberCoroutineScope(),+                launchers = rememberDocumentLaunchers(+                    viewModel,+                    DocumentScreenState(),+                    onPickImageBytes = { _, _ -> }),+                onBecameOnline = {},+                onBack = onBack,+            )+        }+    }++    private fun loadedText(viewModel: OfficeViewModel): OdfDocument.TextDocument =+        (viewModel.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.TextDocument++    @Test fun allHiddenRendersNothing() {+        overlays(DocumentOverlayState(), textDoc(), vm(textDoc()))+        rule.onNodeWithText("Info").assertDoesNotExist()+        rule.onNodeWithText("Tracked", substring = true).assertDoesNotExist()+        rule.onNodeWithText("Comments", substring = true).assertDoesNotExist()+    }++    @Test fun metadataSaveEditsTitle() {+        val state = DocumentOverlayState().apply { showMetadata = true }+        val viewModel = vm(textDoc())+        overlays(state, textDoc(), viewModel)+        rule.onNodeWithText("Info").assertIsDisplayed()+        rule.onAllNodes(hasSetTextAction())[0].performTextInput("New Title")+        rule.onNodeWithText("Save").performClick()+        assertEquals("New Title", loadedText(viewModel).metadata.title)+        assertTrue(!state.showMetadata)+    }++    @Test fun metadataCancelDismisses() {+        val state = DocumentOverlayState().apply { showMetadata = true }+        val viewModel = vm(textDoc())+        overlays(state, textDoc(), viewModel)+        rule.onNodeWithText("Cancel", substring = true).performClick()+        assertTrue(!state.showMetadata)+        assertEquals(null, loadedText(viewModel).metadata.title)+    }++    @Test fun unsavedDiscardGoesBack() {+        val state = DocumentOverlayState().apply { showUnsavedDialog = true }+        var back = 0+        overlays(state, textDoc(), vm(textDoc())) { back++ }+        rule.onNodeWithText("Unsaved", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Discard", substring = true).performClick()+        assertEquals(1, back)+        assertTrue(!state.showUnsavedDialog)+    }++    @Test fun unsavedCancelStays() {+        val state = DocumentOverlayState().apply { showUnsavedDialog = true }+        var back = 0+        overlays(state, textDoc(), vm(textDoc())) { back++ }+        rule.onNodeWithText("Cancel", substring = true).performClick()+        assertEquals(0, back)+        assertTrue(!state.showUnsavedDialog)+    }++    @Test fun exportWarningConfirmRunsAction() {+        var warned = false+        val state = DocumentOverlayState().apply { exportWarning = { warned = true } }+        overlays(state, textDoc(), vm(textDoc()))+        rule.onNodeWithText("Export to non-ODF format").assertIsDisplayed()+        rule.onNodeWithText("Export").performClick()+        assertTrue(warned)+        assertEquals(null, state.exportWarning)+    }++    @Test fun exportWarningCancelClears() {+        val state = DocumentOverlayState().apply { exportWarning = {} }+        overlays(state, textDoc(), vm(textDoc()))+        rule.onNodeWithText("Cancel", substring = true).performClick()+        assertEquals(null, state.exportWarning)+    }++    @Test fun enableOnlineDialogDismisses() {+        // NOTE: the enable button is deliberately NOT tapped: enabling mints+        // keys + a device id into the DataStore, which flips later test classes+        // (e.g. OnlineTab's disabled screen) to the enabled path and loads the+        // PQC native library into this classloader, breaking E2E tests.+        val state = DocumentOverlayState().apply { showEnableOnlineDialog = true }+        overlays(state, textDoc(), vm(textDoc()))+        rule.onNodeWithText("Enable online sharing?").assertIsDisplayed()+        rule.onNodeWithText("Cancel", substring = true).performClick()+        assertTrue(!state.showEnableOnlineDialog)+        assertTrue(!state.showShareDialog)+    }++    @Test fun shareDialogClosesViaWiring() {+        val state = DocumentOverlayState().apply { showShareDialog = true }+        val viewModel = vm(textDoc())+        overlays(state, textDoc(), viewModel)+        // Offline owner names the document first.+        rule.onNodeWithText("Document name", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Close").performClick()+        assertTrue(!state.showShareDialog)+    }++    @Test fun settingsOverlaySaves() {+        val state = DocumentOverlayState().apply { showSettings = true }+        overlays(state, textDoc(), vm(textDoc()))+        rule.onNodeWithText("Settings", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Save", substring = true).performClick()+        assertTrue(!state.showSettings)+    }++    @Test fun colorPickerClearDismissesViaWiring() {+        val state = DocumentOverlayState().apply { showColorPicker = true }+        overlays(state, textDoc(), vm(textDoc()))+        rule.onNodeWithText("∅").performClick()+        assertTrue(!state.showColorPicker)+    }++    @Test fun fontSizePickerSelectsViaWiring() {+        val state = DocumentOverlayState().apply { showFontSizePicker = true }+        overlays(state, textDoc(), vm(textDoc()))+        rule.onNodeWithText("24").performClick()+        assertTrue(!state.showFontSizePicker)+    }++    @Test fun insertTableAddsTable() {+        val state = DocumentOverlayState().apply { showInsertTable = true }+        val viewModel = vm(textDoc())+        overlays(state, textDoc(), viewModel)+        rule.onNodeWithText("Insert").performClick()+        val content = loadedText(viewModel).content+        assertTrue(content.any { it is OdfContentBlock.Table })+        assertTrue(!state.showInsertTable)+    }++    @Test fun insertLinkAddsParagraph() {+        val state = DocumentOverlayState().apply { showInsertLink = true }+        val viewModel = vm(textDoc())+        overlays(state, textDoc(), viewModel)+        rule.onAllNodes(hasSetTextAction())[0].performTextInput("Example")+        rule.onNodeWithText("Insert").performClick()+        val content = loadedText(viewModel).content+        assertTrue(content.size == 2)+        assertTrue(!state.showInsertLink)+    }++    @Test fun bookmarkAddsBookmark() {+        val state = DocumentOverlayState().apply { showAddBookmark = true }+        val viewModel = vm(textDoc())+        overlays(state, textDoc(), viewModel)+        rule.onNode(hasSetTextAction()).performTextInput("ch1")+        rule.onNodeWithText("Add").performClick()+        assertEquals(listOf("ch1"), loadedText(viewModel).bookmarks.map { it.name })+        assertTrue(!state.showAddBookmark)+    }++    @Test fun specialCharWithNoRunDismisses() {+        val state = DocumentOverlayState().apply { showSpecialChars = true }+        overlays(state, textDoc(), vm(textDoc()))+        // No active run: picking inserts nothing but still dismisses.+        rule.onNodeWithText("→").performClick()+        assertEquals(1, loadedText(vm(textDoc())).content.size)+        assertTrue(!state.showSpecialChars)+    }++    @Test fun footnoteWithNoRunDismisses() {+        val state = DocumentOverlayState().apply { showFootnote = true }+        overlays(state, textDoc(), vm(textDoc()))+        rule.onNode(hasSetTextAction()).performTextInput("note")+        rule.onNodeWithText("Insert").performClick()+        assertTrue(!state.showFootnote)+    }++    @Test fun commentAddsAnnotation() {+        val state = DocumentOverlayState().apply { showComment = true }+        val viewModel = vm(textDoc())+        overlays(state, textDoc(), viewModel)+        rule.onAllNodes(hasSetTextAction())[1].performTextInput("fix this")+        rule.onNodeWithText("Insert").performClick()+        val spans = (loadedText(viewModel).content[0] as OdfContentBlock.Paragraph)+            .paragraph.spans+        assertTrue(spans.any { it.annotation?.paragraphs?.first()?.spans?.first()?.text == "fix this" })+        assertTrue(!state.showComment)+    }++    @Test fun commentsHostEmptyPlaceholder() {+        val state = DocumentOverlayState().apply { showComments = true }+        overlays(state, textDoc(), vm(textDoc()))+        rule.onNodeWithText("No comments", substring = true).assertIsDisplayed()+    }++    @Test fun changesHostEmptyPlaceholder() {+        val state = DocumentOverlayState().apply { showChanges = true }+        overlays(state, textDoc(), vm(textDoc()))+        rule.onNodeWithText("No tracked", substring = true).assertIsDisplayed()+    }++    @Test fun cellTextColorClearsViaWiring() {+        val doc = OdfDocument.Spreadsheet(+            "Book",+            listOf(+                com.vayunmathur.library.ui.odf.OdfSheet(+                    "S",+                    listOf(+                        com.vayunmathur.library.ui.odf.OdfRow(+                            listOf(+                                com.vayunmathur.library.ui.odf.OdfCell("a1", textColor = 0xFFFF0000L)))))))+        val state = DocumentOverlayState().apply { showCellTextColor = true }+        val viewModel = vm(doc)+        overlays(state, doc, viewModel, activeCell = Triple(0, 0, 0))+        rule.onNodeWithText("Text Color").assertIsDisplayed()+        rule.onNodeWithText("∅").performClick()+        val cell = ((viewModel.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.Spreadsheet).sheets[0].rows[0].cells[0]+        assertEquals(null, cell.textColor)+        assertTrue(!state.showCellTextColor)+    }++    @Test fun cellOverlaysNullCellRendersNothing() {+        val state = DocumentOverlayState().apply {+            showCellTextColor = true+            showCellComment = true+        }+        overlays(state, textDoc(), vm(textDoc()))+        // Guards return early without an active cell: no dialog appears.+        rule.onNodeWithText("Text Color").assertDoesNotExist()+    }++    @Test fun headerFooterOverlaySaves() {+        val state = DocumentOverlayState().apply { showHeaderFooter = true }+        val viewModel = vm(textDoc())+        overlays(state, textDoc(), viewModel)+        rule.onNodeWithText("Header & Footer").assertIsDisplayed()+        rule.onNodeWithText("Save", substring = true).performClick()+        assertTrue(!state.showHeaderFooter)+    }++    @Test fun pageSetupOverlayRenders() {+        val state = DocumentOverlayState().apply { showPageSetup = true }+        overlays(state, textDoc(), vm(textDoc()))+        rule.onNodeWithText("Page setup", substring = true).assertIsDisplayed()+    }++    @Test fun chartEditorForTextDismisses() {+        val state = DocumentOverlayState().apply {+            showChartEditor = true+            editingChartBlock = 0+        }+        overlays(state, textDoc(), vm(textDoc()))+        rule.onNodeWithText("Insert Chart", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Cancel", substring = true).performClick()+        assertTrue(!state.showChartEditor)+        assertEquals(-1, state.editingChartBlock)+    }+}
office/src/test/java/com/vayunmathur/office/Slice4FindBarsTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4FindBarsTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4FindBarsTest.ktnew file mode 100644index 0000000000..63ab5e331d--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4FindBarsTest.kt@@ -0,0 +1,155 @@+package com.vayunmathur.office++import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.rememberCoroutineScope+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.performClick+import androidx.compose.ui.test.performTextClearance+import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.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.office.util.OfficeViewModel+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 4/4 find-bar tests (Robolectric + createComposeRule):+ * [DocumentFindBars] search/replace/font-scale/word-count/timer bars driven+ * through a [DocumentScreenState] with a seeded (Loaded) ViewModel.+ */+@RunWith(AndroidJUnit4::class)+class Slice4FindBarsTest {++    @get:Rule val rule = createComposeRule()++    private fun vm(doc: OdfDocument): OfficeViewModel =+        OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+            stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        }++    private fun doc() = OdfDocument.TextDocument(+        "Doc",+        listOf(+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("hello world")))),+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("say hello again")))),+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("other")))),+        ),+    )++    private fun show(+        s: DocumentScreenState,+        document: OdfDocument = doc(),+        viewModel: OfficeViewModel = vm(document),+        isTextDoc: Boolean = true,+        isPresentation: Boolean = false,+    ) {+        rule.setContent {+            DocumentFindBars(+                s = s,+                document = document,+                viewModel = viewModel,+                isTextDoc = isTextDoc,+                isPresentation = isPresentation,+                wordCount = 3,+                charCount = 20,+                readingTime = 1,+                scope = rememberCoroutineScope(),+                listState = rememberLazyListState(),+            )+        }+    }++    @Test fun searchFieldUpdatesQuery() {+        val s = DocumentScreenState().apply { showSearch = true }+        show(s)+        rule.onNode(hasSetTextAction()).performTextInput("hello")+        assertEquals("hello", s.searchQuery)+    }++    @Test fun matchNavigatorCounts() {+        val s = DocumentScreenState().apply {+            showSearch = true+            searchQuery = "hello"+        }+        show(s)+        // 2 matching blocks: navigator shows "1/2".+        rule.onNodeWithText("1/2").assertIsDisplayed()+    }++    @Test fun matchNavigatorNextPrev() {+        val s = DocumentScreenState().apply {+            showSearch = true+            searchQuery = "hello"+        }+        show(s)+        assertEquals(0, s.findIndex)+        // Navigator shows the position within the match list.+        rule.onNodeWithText("1/2").assertIsDisplayed()+        assertEquals(0, s.findIndex)+    }++    @Test fun replaceBarTypesReplacement() {+        val s = DocumentScreenState().apply {+            showSearch = true+            searchQuery = "hello"+            showReplaceBar = true+        }+        show(s)+        // Two editable fields: search + replace. Type into the replace one.+        val fields = rule.onAllNodes(hasSetTextAction())+        assertEquals(2, fields.fetchSemanticsNodes().size)+        fields[1].performTextInput("hi")+        assertEquals("hi", s.replaceText)+    }++    @Test fun wordCountBarShowsCounts() {+        val s = DocumentScreenState().apply { showWordBar = true }+        show(s)+        rule.onNodeWithText("3", substring = true).assertIsDisplayed()+        rule.onNodeWithText("20", substring = true).assertIsDisplayed()+    }++    @Test fun timerBarHiddenWithoutFlag() {+        val s = DocumentScreenState()+        show(s, isPresentation = true)+        rule.onNodeWithText("⏱", substring = true).assertDoesNotExist()+    }++    @Test fun timerBarShowsForPresentation() {+        val s = DocumentScreenState().apply {+            showTimer = true+            timerSeconds = 65+        }+        show(s, isPresentation = true)+        rule.onNodeWithText("01:05", substring = true).assertIsDisplayed()+    }++    @Test fun fontScaleBarHiddenByDefault() {+        val s = DocumentScreenState()+        show(s)+        // The font-scale slider row only appears with showFontControl.+        assertEquals(1f, s.fontSizeMultiplier)+    }++    @Test fun searchHiddenWithoutFlag() {+        val s = DocumentScreenState()+        show(s)+        rule.onNodeWithText("Search", substring = true).assertDoesNotExist()+    }++    @Test fun replaceToggleFlips() {+        val s = DocumentScreenState().apply { showSearch = true }+        show(s)+        assertTrue(!s.showReplaceBar)+    }+}
office/src/test/java/com/vayunmathur/office/Slice4HomeMetaTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4HomeMetaTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4HomeMetaTest.ktnew file mode 100644index 0000000000..8482e079ea--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4HomeMetaTest.kt@@ -0,0 +1,157 @@+package com.vayunmathur.office++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.performClick+import androidx.compose.ui.test.performTextClearance+import androidx.compose.ui.test.performTextInput+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfMetadata+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 4/4 home + metadata tests (Robolectric + createComposeRule):+ * [HomeScreen]/[InitialScreen] (VM-free lambdas except InitialScreen's+ * create-new wiring) and [MetadataDialog] save semantics.+ */+@RunWith(AndroidJUnit4::class)+class Slice4HomeMetaTest {++    @get:Rule val rule = createComposeRule()++    // ---- HomeScreen ----++    @Test fun homeScreenShowsActions() {+        var opened = false+        var text = false+        var sheet = false+        var pres = false+        rule.setContent {+            HomeScreen(+                onOpenDocument = { opened = true },+                onNewTextDocument = { text = true },+                onNewSpreadsheet = { sheet = true },+                onNewPresentation = { pres = true },+            )+        }+        rule.onNodeWithText("Open Document").assertIsDisplayed()+        rule.onNodeWithText("New Doc").assertIsDisplayed()+        rule.onNodeWithText("New Sheet").assertIsDisplayed()+        rule.onNodeWithText("New Slides").assertIsDisplayed()+        assertTrue(!opened && !text && !sheet && !pres)+    }++    @Test fun homeScreenNewDocumentCallbacks() {+        var text = false+        var sheet = false+        var pres = false+        rule.setContent {+            HomeScreen(+                onNewTextDocument = { text = true },+                onNewSpreadsheet = { sheet = true },+                onNewPresentation = { pres = true },+            )+        }+        rule.onNodeWithText("New Sheet").performClick()+        assertTrue(sheet)+        rule.onNodeWithText("New Slides").performClick()+        assertTrue(pres)+        assertTrue(!text)+    }++    // ---- MetadataDialog ----++    @Test fun metadataDialogShowsValuesAndStats() {+        rule.setContent {+            MetadataDialog(+                metadata = OdfMetadata(+                    title = "Report",+                    author = "me",+                    pageCount = 3,+                    wordCount = 100,+                    fileSize = 2048,+                ),+                onSave = {},+                onDismiss = {},+            )+        }+        rule.onNodeWithText("Report").assertIsDisplayed()+        rule.onNodeWithText("me").assertIsDisplayed()+        // Stat rows sit below the fold in the scrollable dialog: existence only.+        rule.onNodeWithText("3").assertExists()+        rule.onNodeWithText("100", substring = true).assertExists()+    }++    @Test fun metadataDialogSaveAppliesEdits() {+        var saved: OdfMetadata? = null+        var dismissed = false+        rule.setContent {+            MetadataDialog(+                metadata = OdfMetadata(title = "Old", keywords = listOf("a")),+                onSave = { saved = it },+                onDismiss = { dismissed = true },+            )+        }+        val fields = rule.onAllNodes(hasSetTextAction())+        // Title field first: clear + retype.+        fields[0].performTextClearance()+        fields[0].performTextInput("New title")+        // Keywords field last: add a second keyword.+        fields[4].performTextClearance()+        fields[4].performTextInput("a, b")+        rule.onNodeWithText("Save").performClick()+        val m = saved+        assertTrue(m != null)+        assertEquals("New title", m!!.title)+        assertEquals(listOf("a", "b"), m.keywords)+        assertTrue(dismissed)+    }++    @Test fun metadataDialogBlankTitleBecomesNull() {+        var saved: OdfMetadata? = null+        rule.setContent {+            MetadataDialog(+                metadata = OdfMetadata(title = "Old", author = "me"),+                onSave = { saved = it },+                onDismiss = {},+            )+        }+        val fields = rule.onAllNodes(hasSetTextAction())+        fields[0].performTextClearance()+        fields[1].performTextClearance()+        rule.onNodeWithText("Save").performClick()+        assertNull(saved?.title)+        assertNull(saved?.author)+        // Untouched description stays null; keywords empty.+        assertTrue(saved?.keywords?.isEmpty() == true)+    }++    @Test fun metadataDialogCancelDismissesWithoutSave() {+        var saved: OdfMetadata? = null+        var dismissed = false+        rule.setContent {+            MetadataDialog(+                metadata = OdfMetadata(),+                onSave = { saved = it },+                onDismiss = { dismissed = true },+            )+        }+        rule.onNodeWithText("Cancel").performClick()+        assertNull(saved)+        assertTrue(dismissed)+    }++    @Test fun formatFileSizeBoundaries() {+        assertEquals("1023 B", formatFileSize(1023))+        assertEquals("1 KB", formatFileSize(1024))+        assertEquals("1023 KB", formatFileSize(1023 * 1024))+        assertEquals("1.0 MB", formatFileSize(1024 * 1024))+    }+}
office/src/test/java/com/vayunmathur/office/Slice4MenuBarOnlineTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4MenuBarOnlineTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4MenuBarOnlineTest.ktnew file mode 100644index 0000000000..ad00d6176c--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4MenuBarOnlineTest.kt@@ -0,0 +1,188 @@+package com.vayunmathur.office++import androidx.activity.ComponentActivity+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.material3.DrawerValue+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+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.ParagraphStyle+import com.vayunmathur.office.util.OfficeDocMeta+import com.vayunmathur.office.util.OfficeViewModel+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 4/4 menu-bar + online-tab tests (Robolectric):+ * [DocumentMenuBar] file/view menus and the [OnlineTab] disabled screen.+ * The activity comes from the android compose rule; print/export launchers+ * are the production factory (never fired).+ */+@RunWith(AndroidJUnit4::class)+class Slice4MenuBarOnlineTest {++    @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++    private fun vm(doc: OdfDocument): OfficeViewModel =+        OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+            stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        }++    private fun textDoc() = OdfDocument.TextDocument(+        "Notes.odt",+        listOf(+            OdfContentBlock.Paragraph(+                OdfParagraph(listOf(OdfSpan("Title")), style = ParagraphStyle.HEADING1)),+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("body")))),+        ),+    )++    private fun showMenuBar(+        s: DocumentScreenState,+        document: OdfDocument = textDoc(),+        isOnline: Boolean = false,+        onlineEnabled: Boolean = false,+    ) {+        val viewModel = vm(document)+        rule.setContent {+            DocumentMenuBar(+                s = s,+                document = document,+                viewModel = viewModel,+                activity = rule.activity,+                isTextDoc = document is OdfDocument.TextDocument,+                isSpreadsheet = document is OdfDocument.Spreadsheet,+                isPresentation = document is OdfDocument.Presentation,+                isOnline = isOnline,+                onlineEnabled = onlineEnabled,+                hasUnsavedChanges = false,+                saveAsName = "Notes.odt",+                wordCount = 2,+                charCount = 10,+                readingTime = 1,+                nightMode = false,+                documentDarkMode = false,+                launchers = rememberDocumentLaunchers(+                    viewModel,+                    s,+                    onPickImageBytes = { _, _ -> }),+                scope = rememberCoroutineScope(),+                drawerState = com.vayunmathur.library.ui.rememberDrawerState(+                    DrawerValue.Closed),+            )+        }+    }++    @Test fun menuBarShowsFileInsertView() {+        showMenuBar(DocumentScreenState())+        rule.onNodeWithText("File").assertIsDisplayed()+        rule.onNodeWithText("Insert").assertIsDisplayed()+        rule.onNodeWithText("View").assertIsDisplayed()+    }++    @Test fun fileMenuSaveAndShare() {+        val s = DocumentScreenState()+        showMenuBar(s)+        rule.onNodeWithText("File").performClick()+        // Exact "Save" (substring also matches "Save As…").+        rule.onNodeWithText("Save").assertIsDisplayed()+        rule.onNodeWithText("Share", substring = true).assertIsDisplayed()+    }++    @Test fun fileMenuOnlineShowsSynced() {+        val s = DocumentScreenState()+        showMenuBar(s, isOnline = true, onlineEnabled = true)+        rule.onNodeWithText("File").performClick()+        rule.onNodeWithText("Synced", substring = true).assertIsDisplayed()+    }++    @Test fun viewMenuZoomAndOutline() {+        val s = DocumentScreenState()+        showMenuBar(s)+        rule.onNodeWithText("View").performClick()+        rule.onNodeWithText("Zoom", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Outline", substring = true).assertIsDisplayed()+    }++    @Test fun viewMenuZoomTogglesFontControl() {+        val s = DocumentScreenState()+        showMenuBar(s)+        rule.onNodeWithText("View").performClick()+        rule.onNodeWithText("Zoom", substring = true).performClick()+        assertTrue(s.showFontControl)+        assertTrue(!s.viewMenu)+    }++    @Test fun viewMenuTimerForPresentation() {+        val s = DocumentScreenState()+        val deck = OdfDocument.Presentation("D", emptyList())+        val viewModel = vm(deck)+        rule.setContent {+            DocumentMenuBar(+                s = s,+                document = deck,+                viewModel = viewModel,+                activity = rule.activity,+                isTextDoc = false,+                isSpreadsheet = false,+                isPresentation = true,+                isOnline = false,+                onlineEnabled = false,+                hasUnsavedChanges = false,+                saveAsName = "D.odp",+                wordCount = 0,+                charCount = 0,+                readingTime = 1,+                nightMode = false,+                documentDarkMode = false,+                launchers = rememberDocumentLaunchers(+                    viewModel,+                    s,+                    onPickImageBytes = { _, _ -> }),+                scope = rememberCoroutineScope(),+                drawerState = com.vayunmathur.library.ui.rememberDrawerState(+                    DrawerValue.Closed),+            )+        }+        rule.onNodeWithText("View").performClick()+        rule.onNodeWithText("Presentation timer").performClick()+        assertTrue(s.showTimer)+    }++    // ---- OnlineTab ----++    @Test fun onlineTabDisabledScreen() {+        // Fresh ViewModel: no online identity -> opt-in prompt, no network touched.+        // NOTE: the enable button is deliberately NOT tapped here: enabling mints+        // PQC keys into the DataStore, which the ViewModel init reads back —+        // flipping later tests in this class to the enabled path.+        val viewModel = vm(textDoc())+        var opened: OfficeDocMeta? = null+        rule.setContent {+            OnlineTab(viewModel = viewModel, onOpenDoc = { opened = it })+        }+        rule.onNodeWithText("Online sharing is off").assertIsDisplayed()+        rule.onNodeWithText("Enable online sharing").assertIsDisplayed()+        assertEquals(null, opened)+    }++    @Test fun onlineTabDisabledHasEnableButton() {+        val viewModel = vm(textDoc())+        rule.setContent {+            OnlineTab(viewModel = viewModel, onOpenDoc = {})+        }+        // Long explainer sits below spacers: existence only.+        rule.onNodeWithText("Turn on online sharing", substring = true).assertExists()+    }+}
office/src/test/java/com/vayunmathur/office/Slice4MenusOverlaysTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4MenusOverlaysTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4MenusOverlaysTest.ktnew file mode 100644index 0000000000..df0dffa642--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4MenusOverlaysTest.kt@@ -0,0 +1,225 @@+package com.vayunmathur.office++import androidx.compose.runtime.Composable+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfPageSetup+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfRow+import com.vayunmathur.library.ui.odf.OdfSheet+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.office.util.OfficeViewModel+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 4/4 menu + cell/slide overlay tests (Robolectric + createComposeRule):+ * insert/export menus, page-setup dialog, cell color/comment/resize overlays+ * and slide-element color overlays. A recording fake stands in for the+ * activity-result launchers (save/export pickers).+ */+@RunWith(AndroidJUnit4::class)+class Slice4MenusOverlaysTest {++    @get:Rule val rule = createComposeRule()++    /**+     * Real launchers via the production factory: under Robolectric they bind to+     * the test activity and never fire without user interaction, which is all+     * these render/callback tests need.+     */+    @Composable+    private fun testLaunchers(+        viewModel: OfficeViewModel,+        holder: DocumentScreenState,+    ): DocumentLaunchers = rememberDocumentLaunchers(viewModel, holder, onPickImageBytes = { _, _ -> })++    private fun vm(doc: OdfDocument): OfficeViewModel =+        OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+            stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        }++    private fun textDoc() = OdfDocument.TextDocument(+        "Doc",+        listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("body"))))),+    )++    private fun sheetDoc() = OdfDocument.Spreadsheet(+        "Book",+        listOf(OdfSheet("S", listOf(OdfRow(listOf(OdfCell("a")))))),+    )++    // ---- InsertMenu ----++    @Test fun insertMenuDisabledWithoutSelection() {+        val s = DocumentScreenState()+        val viewModel = vm(textDoc())+        rule.setContent {+            val ln = testLaunchers(viewModel, s)+            InsertMenu(+                s = s, viewModel = viewModel, isTextDoc = true,+                focusedPara = -1, launchers = ln)+        }+        rule.onNodeWithText("Insert").performClick()+        // Field items need an active run; without one they stay disabled.+        assertEquals(-1, s.activeRunStart)+    }++    @Test fun insertMenuHiddenForNonText() {+        val s = DocumentScreenState()+        val viewModel = vm(sheetDoc())+        rule.setContent {+            val ln = testLaunchers(viewModel, s)+            InsertMenu(+                s = s, viewModel = viewModel, isTextDoc = false,+                focusedPara = -1, launchers = ln)+        }+        rule.onNodeWithText("Insert").assertDoesNotExist()+    }++    // ---- ExportMenu ----++    @Test fun exportMenuTextDocOptions() {+        val s = DocumentScreenState().apply { exportMenu = true }+        val viewModel = vm(textDoc())+        rule.setContent {+            val ln = testLaunchers(viewModel, s)+            ExportMenu(+                s = s, document = textDoc(), viewModel = viewModel,+                isTextDoc = true, isSpreadsheet = false, isPresentation = false,+                launchers = ln)+        }+        rule.onNodeWithText("PDF", substring = true).assertIsDisplayed()+        rule.onNodeWithText("HTML", substring = true).assertIsDisplayed()+    }++    @Test fun exportMenuSpreadsheetOptions() {+        val s = DocumentScreenState().apply { exportMenu = true }+        val doc = sheetDoc()+        val viewModel = vm(doc)+        rule.setContent {+            val ln = testLaunchers(viewModel, s)+            ExportMenu(+                s = s, document = doc, viewModel = viewModel,+                isTextDoc = false, isSpreadsheet = true, isPresentation = false,+                launchers = ln)+        }+        rule.onNodeWithText("CSV", substring = true).assertIsDisplayed()+    }++    // ---- PageSetupOverlays ----++    @Test fun pageSetupHiddenByDefault() {+        val state = DocumentOverlayState()+        rule.setContent {+            PageSetupOverlays(+                state = state, document = textDoc(), viewModel = vm(textDoc()))+        }+        rule.onNodeWithText("Page setup", substring = true).assertDoesNotExist()+    }++    @Test fun pageSetupShowsCurrentGeometry() {+        val state = DocumentOverlayState().apply { showPageSetup = true }+        val doc = textDoc().copy(pageSetup = OdfPageSetup())+        rule.setContent {+            PageSetupOverlays(state = state, document = doc, viewModel = vm(doc))+        }+        rule.onNodeWithText("Page setup", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Landscape", substring = true).assertIsDisplayed()+    }++    @Test fun pageSetupToggleLandscapePersists() {+        val state = DocumentOverlayState().apply { showPageSetup = true }+        val doc = textDoc().copy(pageSetup = OdfPageSetup())+        val viewModel = vm(doc)+        rule.setContent {+            PageSetupOverlays(state = state, document = doc, viewModel = viewModel)+        }+        rule.onNodeWithText("Landscape", substring = true).performClick()+        rule.onNodeWithText("Apply").performClick()+        val cur = (viewModel.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.TextDocument+        assertTrue(cur.pageSetup?.isLandscape == true)+        assertTrue(!state.showPageSetup)+    }++    // ---- CellOverlays ----++    @Test fun cellTextColorOverlayApplies() {+        val state = DocumentOverlayState().apply { showCellTextColor = true }+        val viewModel = vm(sheetDoc())+        rule.setContent {+            CellOverlays(+                state = state,+                viewModel = viewModel,+                activeCell = mutableStateOf(Triple(0, 0, 0)),+                activeSlide = mutableIntStateOf(0),+                activeSlideEl = mutableIntStateOf(-1),+            )+        }+        rule.onNodeWithText("Text Color").assertIsDisplayed()+        // Pick the clear swatch: sets null color and dismisses.+        rule.onNodeWithText("∅").performClick()+        assertTrue(!state.showCellTextColor)+    }++    @Test fun cellOverlaysNoCellNoCrash() {+        val state = DocumentOverlayState().apply {+            showCellTextColor = true+            showCellComment = true+            showCellResize = true+        }+        rule.setContent {+            CellOverlays(+                state = state,+                viewModel = vm(sheetDoc()),+                activeCell = mutableStateOf(null),+                activeSlide = mutableIntStateOf(0),+                activeSlideEl = mutableIntStateOf(-1),+            )+        }+        // No active cell: color pickers stay hidden, nothing crashes.+        rule.onNodeWithText("Text Color").assertDoesNotExist()+    }++    // ---- SlideElementOverlays ----++    @Test fun slideElementOverlaysHiddenWithoutSelection() {+        val state = DocumentOverlayState().apply { showSlideTextColor = true }+        rule.setContent {+            SlideElementOverlays(+                state = state,+                viewModel = vm(textDoc()),+                activeSlide = mutableIntStateOf(0),+                activeSlideEl = mutableIntStateOf(-1),+            )+        }+        rule.onNodeWithText("Text Color").assertDoesNotExist()+    }++    // ---- DocumentScreenState extras ----++    @Test fun screenStateSelectionFields() {+        val s = DocumentScreenState()+        s.activeCell = Triple(1, 2, 3)+        assertEquals(Triple(1, 2, 3), s.activeCellState.value)+        s.findMatches = listOf(4, 9)+        assertEquals(listOf(4, 9), s.findMatches)+        s.pendingReplace = { _, _ -> }+        assertTrue(s.pendingReplace != null)+        s.timerSeconds = 90+        assertEquals(90, s.timerSecondsState.value)+    }+}
office/src/test/java/com/vayunmathur/office/Slice4OverlaysTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4OverlaysTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4OverlaysTest.ktnew file mode 100644index 0000000000..96cd818377--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4OverlaysTest.kt@@ -0,0 +1,333 @@+package com.vayunmathur.office++import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfAnnotation+import com.vayunmathur.library.ui.odf.OdfBookmark+import com.vayunmathur.library.ui.odf.OdfChange+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.ParagraphStyle+import com.vayunmathur.office.ui.HeadingItem+import com.vayunmathur.office.util.OfficeMember+import com.vayunmathur.office.util.OfficeRoles+import com.vayunmathur.office.util.OfficeViewModel+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 4/4 overlay composition tests (Robolectric + createComposeRule):+ * outline pane, share-members list, tracked-changes and comments overlays.+ */+@RunWith(AndroidJUnit4::class)+class Slice4OverlaysTest {++    @get:Rule val rule = createComposeRule()++    private fun vm(): OfficeViewModel =+        OfficeViewModel(ApplicationProvider.getApplicationContext())++    private fun textDoc(): OdfDocument.TextDocument = OdfDocument.TextDocument(+        "Doc",+        listOf(+            OdfContentBlock.Paragraph(+                OdfParagraph(listOf(OdfSpan("Title")), style = ParagraphStyle.HEADING1)),+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("body")))),+        ),+    )++    // ---- OfficeOutlinePane ----++    @Test fun outlinePaneShowsHeadingsAndBookmarks() {+        rule.setContent {+            OfficeOutlinePane(+                bookmarks = listOf(OdfBookmark("ch1", 1)),+                headings = listOf(+                    HeadingItem("Title", 1, 0),+                    HeadingItem("Sub", 2, 1),+                    HeadingItem("Deep", 3, 1),+                ),+                listState = androidx.compose.foundation.lazy.LazyListState(),+                drawerState = com.vayunmathur.library.ui.rememberDrawerState(androidx.compose.material3.DrawerValue.Closed),+                scope = rememberCoroutineScope(),+            )+        }+        rule.onNodeWithText("Outline", substring = true).assertIsDisplayed()+        rule.onNodeWithText("ch1", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Title").assertIsDisplayed()+        rule.onNodeWithText("Sub").assertIsDisplayed()+        rule.onNodeWithText("Deep").assertIsDisplayed()+    }++    @Test fun outlinePaneEmptyBookmarksHidesSection() {+        rule.setContent {+            OfficeOutlinePane(+                bookmarks = emptyList(),+                headings = listOf(HeadingItem("Only", 1, 0)),+                listState = androidx.compose.foundation.lazy.LazyListState(),+                drawerState = com.vayunmathur.library.ui.rememberDrawerState(androidx.compose.material3.DrawerValue.Closed),+                scope = rememberCoroutineScope(),+            )+        }+        rule.onNodeWithText("Only").assertIsDisplayed()+        rule.onNodeWithText("Bookmarks", substring = true).assertDoesNotExist()+    }++    // ---- ShareMembersList ----++    @Test fun shareMembersShowsRolesAndYou() {+        var menuFor: String? = "unset"+        rule.setContent {+            ShareMembersList(+                members = listOf(+                    OfficeMember("dev1", "Ann", OfficeRoles.OWNER),+                    OfficeMember("dev2", "", OfficeRoles.EDITOR),+                    OfficeMember("dev3", "Bob", OfficeRoles.REVOKED),+                ),+                deviceId = "dev1",+                isOwner = true,+                memberMenu = null,+                onMemberMenu = { menuFor = it },+                onSetRole = { _, _ -> },+                onTransferOwner = {},+            )+        }+        // Owner sees themselves with "(you)".+        rule.onNodeWithText("Ann (you)", substring = true).assertIsDisplayed()+        // Blank name falls back to id prefix.+        rule.onNodeWithText("dev2", substring = true).assertIsDisplayed()+        // Revoked members are filtered out.+        rule.onNodeWithText("Bob", substring = true).assertDoesNotExist()+        assertEquals("unset", menuFor)+    }++    @Test fun shareMembersNonOwnerSeesNoManage() {+        rule.setContent {+            ShareMembersList(+                members = listOf(OfficeMember("dev2", "Ann", OfficeRoles.EDITOR)),+                deviceId = "dev1",+                isOwner = false,+                memberMenu = null,+                onMemberMenu = {},+                onSetRole = { _, _ -> },+                onTransferOwner = {},+            )+        }+        rule.onNodeWithText("Manage", substring = true).assertDoesNotExist()+    }++    @Test fun shareMembersManageOpensMenu() {+        var menuFor: String? = "unset"+        var roleSet: Pair<String, String>? = null+        rule.setContent {+            ShareMembersList(+                members = listOf(OfficeMember("dev2", "Ann", OfficeRoles.EDITOR)),+                deviceId = "dev1",+                isOwner = true,+                memberMenu = "dev2",+                onMemberMenu = { menuFor = it },+                onSetRole = { id, role -> roleSet = id to role },+                onTransferOwner = {},+            )+        }+        // Editor gets "make viewer" + owner-transfer + remove options (Material3 dropdown).+        rule.onNodeWithText("Make viewer", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Make viewer", substring = true).performClick()+        assertEquals("dev2" to OfficeRoles.VIEWER, roleSet)+        assertEquals(null, menuFor)+    }++    @Test fun shareMembersViewerGetsMakeEditor() {+        var roleSet: Pair<String, String>? = null+        rule.setContent {+            ShareMembersList(+                members = listOf(OfficeMember("dev2", "Ann", OfficeRoles.VIEWER)),+                deviceId = "dev1",+                isOwner = true,+                memberMenu = "dev2",+                onMemberMenu = {},+                onSetRole = { id, role -> roleSet = id to role },+                onTransferOwner = {},+            )+        }+        rule.onNodeWithText("Make editor", substring = true).performClick()+        assertEquals("dev2" to OfficeRoles.EDITOR, roleSet)+    }++    @Test fun shareMembersTransferOwner() {+        var transferred: String? = null+        rule.setContent {+            ShareMembersList(+                members = listOf(OfficeMember("dev2", "Ann", OfficeRoles.EDITOR)),+                deviceId = "dev1",+                isOwner = true,+                memberMenu = "dev2",+                onMemberMenu = {},+                onSetRole = { _, _ -> },+                onTransferOwner = { transferred = it },+            )+        }+        rule.onNodeWithText("Make owner", substring = true).performClick()+        assertEquals("dev2", transferred)+    }++    @Test fun shareMembersEmptyShowsNothing() {+        rule.setContent {+            ShareMembersList(+                members = emptyList(),+                deviceId = "dev1",+                isOwner = true,+                memberMenu = null,+                onMemberMenu = {},+                onSetRole = { _, _ -> },+                onTransferOwner = {},+            )+        }+        rule.onNodeWithText("access", substring = true).assertDoesNotExist()+    }++    // ---- ChangesOverlays ----++    private fun changeDoc() = OdfDocument.TextDocument(+        "Doc",+        listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("hi"))))),+        changes = listOf(+            OdfChange("c1", "insertion", author = "me", date = "2024-05-01T10:00:00"),+            OdfChange("c2", "deletion", author = null, date = null),+        ),+    )++    @Test fun changesHiddenByDefault() {+        val state = DocumentOverlayState()+        val viewModel = vm()+        viewModel.stateMutable.value = OfficeViewModel.ViewState.Loaded(changeDoc())+        rule.setContent {+            ChangesOverlays(state = state, document = changeDoc(), viewModel = viewModel)+        }+        rule.onNodeWithText("Tracked", substring = true).assertDoesNotExist()+    }++    @Test fun changesDialogListsAndAccepts() {+        val state = DocumentOverlayState().apply { showChanges = true }+        val viewModel = vm()+        viewModel.stateMutable.value = OfficeViewModel.ViewState.Loaded(changeDoc())+        rule.setContent {+            ChangesOverlays(state = state, document = changeDoc(), viewModel = viewModel)+        }+        rule.onNodeWithText("Tracked", substring = true).assertIsDisplayed()+        rule.onNodeWithText("Insertion", substring = true).assertIsDisplayed()+        // Two changes -> two exact "Accept" buttons; accept the first (c1).+        rule.onAllNodesWithText("Accept")[0].performClick()+        val cur = (viewModel.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.TextDocument+        assertEquals(listOf("c2"), cur.changes.map { it.id })+    }++    @Test fun changesDialogRejects() {+        val state = DocumentOverlayState().apply { showChanges = true }+        val viewModel = vm()+        viewModel.stateMutable.value = OfficeViewModel.ViewState.Loaded(changeDoc())+        rule.setContent {+            ChangesOverlays(state = state, document = changeDoc(), viewModel = viewModel)+        }+        rule.onAllNodesWithText("Reject")[0].performClick()+        val cur = (viewModel.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.TextDocument+        assertEquals(listOf("c2"), cur.changes.map { it.id })+    }++    @Test fun changesEmptyShowsPlaceholder() {+        val state = DocumentOverlayState().apply { showChanges = true }+        val viewModel = vm()+        val doc = textDoc()+        viewModel.stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        rule.setContent {+            ChangesOverlays(state = state, document = doc, viewModel = viewModel)+        }+        rule.onNodeWithText("No tracked", substring = true).assertIsDisplayed()+    }++    // ---- CommentsOverlays ----++    private fun commentDoc() = OdfDocument.TextDocument(+        "Doc",+        listOf(+            OdfContentBlock.Paragraph(+                OdfParagraph(+                    listOf(+                        OdfSpan(+                            "noted",+                            annotation = OdfAnnotation(+                                author = "me",+                                date = "2024-01-01",+                                paragraphs = listOf(+                                    OdfParagraph(listOf(OdfSpan("fix this")))))),+                    ),+                )),+        ),+    )++    @Test fun commentsDialogListsAndResolves() {+        val state = DocumentOverlayState().apply { showComments = true }+        val viewModel = vm()+        viewModel.stateMutable.value = OfficeViewModel.ViewState.Loaded(commentDoc())+        rule.setContent {+            CommentsOverlays(+                state = state,+                document = commentDoc(),+                viewModel = viewModel,+                listState = rememberLazyListState(),+                scope = rememberCoroutineScope(),+            )+        }+        rule.onNodeWithText("fix this").assertIsDisplayed()+        rule.onNodeWithText("Resolve").performClick()+        val cur = (viewModel.state.value as OfficeViewModel.ViewState.Loaded)+            .document as OdfDocument.TextDocument+        val spans = (cur.content[0] as OdfContentBlock.Paragraph).paragraph.spans+        assertTrue(spans.all { it.annotation == null })+        assertTrue(state.showComments)+    }++    @Test fun commentsEmptyShowsPlaceholder() {+        val state = DocumentOverlayState().apply { showComments = true }+        val viewModel = vm()+        val doc = textDoc()+        viewModel.stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        rule.setContent {+            CommentsOverlays(+                state = state,+                document = doc,+                viewModel = viewModel,+                listState = rememberLazyListState(),+                scope = rememberCoroutineScope(),+            )+        }+        rule.onNodeWithText("No comments", substring = true).assertIsDisplayed()+    }++    @Test fun overlayStateDefaults() {+        val s = DocumentOverlayState()+        assertTrue(!s.showChanges)+        assertTrue(!s.showComments)+        assertTrue(!s.showMetadata)+        assertEquals(-1, s.editingChartBlock)+        val full = DocumentScreenState()+        assertTrue(!full.showSearch)+        assertEquals("", full.searchQuery)+        assertEquals(-1, full.activeRunStart)+        assertEquals(null, full.activeCell)+    }+}
office/src/test/java/com/vayunmathur/office/Slice4ScreenTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4ScreenTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4ScreenTest.ktnew file mode 100644index 0000000000..334513e42f--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4ScreenTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.office++import androidx.activity.ComponentActivity+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+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.ParagraphStyle+import com.vayunmathur.office.util.OfficeViewModel+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 4/4 screen tests (Robolectric): [DocumentScreen] end-to-end render+ * for text/sheet/presentation documents, [OfficeLightTheme] wrapping, and+ * the [OfficeRoute] navigation keys.+ */+@RunWith(AndroidJUnit4::class)+class Slice4ScreenTest {++    @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++    private fun vm(doc: OdfDocument): OfficeViewModel =+        OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+            stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        }++    private fun textDoc() = OdfDocument.TextDocument(+        "Notes.odt",+        listOf(+            OdfContentBlock.Paragraph(+                OdfParagraph(listOf(OdfSpan("Title")), style = ParagraphStyle.HEADING1)),+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("screen body")))),+        ),+    )++    private fun showDoc(document: OdfDocument, onBack: () -> Unit = {}) {+        rule.setContent {+            OfficeLightTheme {+                DocumentScreen(+                    document = document,+                    viewModel = vm(document),+                    activity = rule.activity,+                    onBack = onBack,+                )+            }+        }+        rule.waitForIdle()+    }++    @Test fun textScreenRendersChromeAndBody() {+        showDoc(textDoc())+        // App-bar title, menu bar, and document body all render.+        rule.onNodeWithText("Notes.odt").assertIsDisplayed()+        rule.onNodeWithText("File").assertIsDisplayed()+        rule.onNodeWithText("screen body", substring = true).assertExists()+    }++    @Test fun presentationScreenRenders() {+        val doc = OdfDocument.Presentation(+            "Deck.odp",+            listOf(+                com.vayunmathur.library.ui.odf.OdfSlide(+                    "S1",+                    listOf(+                        com.vayunmathur.library.ui.odf.OdfSlideElement.Frame(+                            com.vayunmathur.library.ui.odf.OdfFrame(+                                0f, 0f, 100f, 50f,+                                listOf(OdfParagraph(listOf(OdfSpan("deck body")))))),+                    ),+                )),+        )+        showDoc(doc)+        rule.onNodeWithText("Deck.odp").assertIsDisplayed()+    }++    @Test fun routeKeys() {+        val off = OfficeRoute.OfflineEditor("content://x")+        assertEquals("content://x", off.uri)+        val on = OfficeRoute.OnlineEditor("doc1")+        assertEquals("doc1", on.docId)+        assertTrue(OfficeRoute.Main is OfficeRoute)+    }++    @Test fun lightThemeWrapsContent() {+        rule.setContent {+            OfficeLightTheme {+                androidx.compose.material3.Text("themed")+            }+        }+        rule.onNodeWithText("themed").assertIsDisplayed()+    }+}
office/src/test/java/com/vayunmathur/office/Slice4ShareDialogTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4ShareDialogTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4ShareDialogTest.ktnew file mode 100644index 0000000000..21f7dc8afd--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4ShareDialogTest.kt@@ -0,0 +1,187 @@+package com.vayunmathur.office++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.performClick+import androidx.compose.ui.test.performTextClearance+import androidx.compose.ui.test.performTextInput+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.office.util.OfficeMember+import com.vayunmathur.office.util.OfficeRoles+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 4/4 share-dialog tests (Robolectric + createComposeRule):+ * [ShareOnlineDialog] viewer vs owner bodies. All collaborators arrive as+ * plain params/callbacks, so no ViewModel or network is needed.+ */+@RunWith(AndroidJUnit4::class)+class Slice4ShareDialogTest {++    @get:Rule val rule = createComposeRule()++    private fun viewerProps(+        onDismiss: () -> Unit = {},+    ): ShareDialogProps = ShareDialogProps(+        deviceId = "dev1",+        isOwner = false,+        isOnline = true,+        initialName = "Doc",+        myRole = OfficeRoles.VIEWER,+        members = listOf(OfficeMember("dev0", "Owner", OfficeRoles.OWNER)),+        onShare = { _, _, _, _ -> },+        onSetRole = { _, _ -> },+        onTransferOwner = {},+        onRename = {},+        onComputeCode = { _, _ -> },+        onDismiss = onDismiss,+    )++    // Local alias: ShareOnlineDialog takes many params; bundle the fixed ones.+    private data class ShareDialogProps(+        val deviceId: String,+        val isOwner: Boolean,+        val isOnline: Boolean,+        val initialName: String,+        val myRole: String,+        val members: List<OfficeMember>,+        val onShare: (String, String, String, (String?) -> Unit) -> Unit,+        val onSetRole: (String, String) -> Unit,+        val onTransferOwner: (String) -> Unit,+        val onRename: (String) -> Unit,+        val onComputeCode: (String, (String?) -> Unit) -> Unit,+        val onDismiss: () -> Unit,+    )++    private fun show(p: ShareDialogProps, shareLink: String? = null) {+        rule.setContent {+            ShareOnlineDialog(+                deviceId = p.deviceId,+                isOwner = p.isOwner,+                isOnline = p.isOnline,+                initialName = p.initialName,+                myRole = p.myRole,+                members = p.members,+                shareLink = shareLink,+                onShare = p.onShare,+                onSetRole = p.onSetRole,+                onTransferOwner = p.onTransferOwner,+                onRename = p.onRename,+                onComputeCode = p.onComputeCode,+                onDismiss = p.onDismiss,+            )+        }+    }++    @Test fun viewerSeesRoleNoteAndDeviceId() {+        show(viewerProps())+        rule.onNodeWithText("Share online").assertIsDisplayed()+        rule.onNodeWithText("viewer access", substring = true).assertIsDisplayed()+        rule.onNodeWithText("dev1").assertIsDisplayed()+        // Viewers get only a Close button (no Add/share confirm).+        rule.onNodeWithText("Close").assertIsDisplayed()+    }++    @Test fun viewerCloseDismisses() {+        var dismissed = false+        show(viewerProps(onDismiss = { dismissed = true }))+        rule.onNodeWithText("Close").performClick()+        assertTrue(dismissed)+    }++    @Test fun ownerOfflineNamesDocumentFirst() {+        var shared: Triple<String, String, String>? = null+        show(+            viewerProps().copy(+                isOwner = true,+                isOnline = false,+                members = emptyList(),+                onShare = { r, role, name, _ -> shared = Triple(r, role, name) },+            ),+        )+        rule.onNodeWithText("Document name", substring = true).assertIsDisplayed()+        // Add is disabled until a recipient is typed.+        rule.onNodeWithText("Add").assertIsDisplayed()+        assertNull(shared)+    }++    @Test fun ownerOfflineShareFlow() {+        var shared: Triple<String, String, String>? = null+        var dismissed = false+        show(+            viewerProps().copy(+                isOwner = true,+                isOnline = false,+                members = emptyList(),+                onShare = { r, role, name, done ->+                    shared = Triple(r, role, name)+                    done(null)+                },+                onDismiss = { dismissed = true },+            ),+        )+        // Type recipient (clears the empty default first), then Add.+        val fields = rule.onAllNodes(hasSetTextAction())+        // Recipient field is the empty one; doc-name field holds "Doc".+        fields[1].performTextClearance()+        fields[1].performTextInput("dev9")+        rule.onNodeWithText("Add").performClick()+        val s = shared+        assertTrue(s != null)+        assertEquals("dev9", s!!.first)+        assertEquals(OfficeRoles.EDITOR, s!!.second)+        assertTrue(!dismissed)+    }++    @Test fun ownerOnlineCanRename() {+        var renamed: String? = null+        show(+            viewerProps().copy(+                isOwner = true,+                isOnline = true,+                onRename = { renamed = it },+            ),+        )+        val fields = rule.onAllNodes(hasSetTextAction())+        fields[0].performTextClearance()+        fields[0].performTextInput("Renamed")+        // Exact match: the doc-name field now contains "Renamed" (substring match).+        rule.onNodeWithText("Rename").performClick()+        assertEquals("Renamed", renamed)+    }++    @Test fun ownerSeesShareLinkButton() {+        show(+            viewerProps().copy(isOwner = true, isOnline = true),+            shareLink = "https://example.com/join/abc",+        )+        rule.onNodeWithText("Share link", substring = true).assertIsDisplayed()+    }++    @Test fun ownerRoleMenuSwitchesToViewer() {+        var shared: Triple<String, String, String>? = null+        show(+            viewerProps().copy(+                isOwner = true,+                isOnline = true,+                members = emptyList(),+                onShare = { r, role, name, _ -> shared = Triple(r, role, name) },+            ),+        )+        // Open the role menu (shows current "editor") and pick viewer.+        rule.onNodeWithText("editor").performClick()+        rule.onNodeWithText("viewer").performClick()+        val fields = rule.onAllNodes(hasSetTextAction())+        fields[1].performTextClearance()+        fields[1].performTextInput("dev9")+        rule.onNodeWithText("Add").performClick()+        assertEquals(OfficeRoles.VIEWER, shared?.second)+    }+}
office/src/test/java/com/vayunmathur/office/Slice4ShellTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4ShellTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4ShellTest.ktnew file mode 100644index 0000000000..6cb12b890e--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4ShellTest.kt@@ -0,0 +1,238 @@+package com.vayunmathur.office++import androidx.activity.ComponentActivity+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.material3.DrawerValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfBookmark+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.ParagraphStyle+import com.vayunmathur.office.ui.HeadingItem+import com.vayunmathur.office.util.OfficeViewModel+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Slice 4/4 shell tests (Robolectric + createComposeRule): error body,+ * selection/chrome holders, the overlays host fan-out, and the full+ * scaffold shell for a text document.+ */+@RunWith(AndroidJUnit4::class)+class Slice4ShellTest {++    @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++    private fun vm(doc: OdfDocument): OfficeViewModel =+        OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+            stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+        }++    private fun textDoc() = OdfDocument.TextDocument(+        "Notes.odt",+        listOf(+            OdfContentBlock.Paragraph(+                OdfParagraph(+                    listOf(OdfSpan("Title")),+                    style = ParagraphStyle.HEADING1)),+            OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("body")))),+        ),+        bookmarks = listOf(OdfBookmark("ch1", 1)),+    )++    // ---- ErrorBody ----++    @Test fun errorBodyShowsMessageAndOpens() {+        var opened = false+        rule.setContent { ErrorBody(message = "boom", onOpenDocument = { opened = true }) }+        rule.onNodeWithText("boom").assertIsDisplayed()+        rule.onNodeWithText("Open Document").performClick()+        assertTrue(opened)+    }++    // ---- Holders ----++    @Test fun selectionHolderMirrorsState() {+        val s = DocumentScreenState()+        val h = ScreenSelectionHolder(s)+        s.activeRunStart = 3+        s.activeCell = Triple(0, 1, 2)+        s.showSearch = true+        assertEquals(3, h.activeRunStart)+        assertEquals(Triple(0, 1, 2), h.activeCell)+        assertTrue(h.showSearch)+        h.activeSlide = 4+        assertEquals(4, s.activeSlide)+    }++    @Test fun screenSelectionSnapshot() {+        val sel = ScreenSelection(+            activeRunStart = 0, activeRunEnd = 1,+            activeTableBlock = -1, activeTableRow = -1, activeTableCol = -1,+            selStart = 0, selEnd = 2,+            activeCell = null, activeSlide = 0, activeSlideEl = -1,+        )+        assertEquals(0, sel.activeRunStart)+        assertEquals(-1, sel.activeTableBlock)+    }++    @Test fun chromeCollects() {+        val doc = textDoc()+        var chrome: DocumentChrome? = null+        rule.setContent {+            chrome = rememberDocumentChrome(viewModel = vm(doc), document = doc)+        }+        rule.waitForIdle()+        val c = chrome+        assertTrue(c != null)+        assertTrue(c!!.isTextDoc)+        assertTrue(!c.isSpreadsheet && !c.isPresentation)+        assertTrue(c.canEdit)+        assertEquals("Notes.odt", c.saveAsName)+        assertEquals(1, c.headings.size)+        assertEquals("Title", c.headings[0].text)+        assertEquals(1, c.bookmarks.size)+    }++    // ---- DocumentOverlays host ----++    @Test fun overlaysHostSilentWithFlagsOff() {+        val doc = textDoc()+        val viewModel = vm(doc)+        val state = DocumentOverlayState()+        var becameOnline: String? = null+        var backed = false+        rule.setContent {+            DocumentOverlays(+                state = state,+                document = doc,+                viewModel = viewModel,+                isPresentation = false,+                isOnline = false,+                focusedPara = -1,+                saveAsName = "Notes.odt",+                activeCell = mutableStateOf(null),+                activeSlide = mutableIntStateOf(0),+                activeSlideEl = mutableIntStateOf(-1),+                activeRunStart = mutableIntStateOf(-1),+                activeRunEnd = mutableIntStateOf(-1),+                selStart = mutableIntStateOf(0),+                selEnd = mutableIntStateOf(0),+                pendingReplace = mutableStateOf(null),+                listState = rememberLazyListState(),+                scope = rememberCoroutineScope(),+                launchers = rememberDocumentLaunchers(+                    viewModel,+                    DocumentScreenState(),+                    onPickImageBytes = { _, _ -> }),+                onBecameOnline = { becameOnline = it },+                onBack = { backed = true },+            )+        }+        rule.waitForIdle()+        assertEquals(null, becameOnline)+        assertTrue(!backed)+    }++    @Test fun overlaysHostMetadataDialog() {+        val doc = textDoc()+        val viewModel = vm(doc)+        val state = DocumentOverlayState().apply { showMetadata = true }+        rule.setContent {+            DocumentOverlays(+                state = state,+                document = doc,+                viewModel = viewModel,+                isPresentation = false,+                isOnline = false,+                focusedPara = -1,+                saveAsName = "Notes.odt",+                activeCell = mutableStateOf(null),+                activeSlide = mutableIntStateOf(0),+                activeSlideEl = mutableIntStateOf(-1),+                activeRunStart = mutableIntStateOf(-1),+                activeRunEnd = mutableIntStateOf(-1),+                selStart = mutableIntStateOf(0),+                selEnd = mutableIntStateOf(0),+                pendingReplace = mutableStateOf(null),+                listState = rememberLazyListState(),+                scope = rememberCoroutineScope(),+                launchers = rememberDocumentLaunchers(+                    viewModel,+                    DocumentScreenState(),+                    onPickImageBytes = { _, _ -> }),+                onBecameOnline = {},+                onBack = {},+            )+        }+        // Metadata dialog from the host (title "Info"; fields start empty since+        // metadata.title is null even though the document file is "Notes.odt").+        rule.onNodeWithText("Info").assertIsDisplayed()+        rule.onNodeWithText("Save").assertIsDisplayed()+    }++    // ---- DocumentScaffoldShell ----++    @Test fun scaffoldShellTextDoc() {+        val doc = textDoc()+        val viewModel = vm(doc)+        val s = DocumentScreenState()+        val activity = rule.activity+        rule.setContent {+            val chrome = rememberDocumentChrome(viewModel = viewModel, document = doc)+            DocumentScaffoldShell(+                s = s,+                document = doc,+                viewModel = viewModel,+                activity = activity,+                chrome = chrome,+                launchers = rememberDocumentLaunchers(+                    viewModel,+                    s,+                    onPickImageBytes = { _, _ -> }),+                scope = rememberCoroutineScope(),+                drawerState = com.vayunmathur.library.ui.rememberDrawerState(+                    DrawerValue.Closed),+                listState = rememberLazyListState(),+                onToggleSearch = { s.showSearch = !s.showSearch },+                onShowUnsavedDialog = { s.showUnsavedDialog = true },+                sel = ScreenSelection(+                    activeRunStart = -1, activeRunEnd = -1,+                    activeTableBlock = -1, activeTableRow = -1, activeTableCol = -1,+                    selStart = 0, selEnd = 0,+                    activeCell = null, activeSlide = 0, activeSlideEl = -1,+                ),+                onRunSelectionChange = { _, _, _, _ -> },+                onCellFocus = { _, _, _ -> },+                onCellSelected = { _, _, _ -> },+                onSlideChange = {},+                onSlideElementSelected = { _, _ -> },+                onBack = {},+            )+        }+        rule.waitForIdle()+        // App-bar title + document body render.+        rule.onNodeWithText("Notes.odt").assertIsDisplayed()+        rule.onNodeWithText("body", substring = true).assertExists()+    }++    @Test fun headingItemModel() {+        val h = HeadingItem("T", 2, 7)+        assertEquals("T", h.text)+        assertEquals(2, h.level)+        assertEquals(7, h.contentIndex)+    }+}
office/src/test/java/com/vayunmathur/office/odf/Slice4ImportExportTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/Slice4ImportExportTest.kt b/office/src/test/java/com/vayunmathur/office/odf/Slice4ImportExportTest.ktnew file mode 100644index 0000000000..6eb1fb1ed4--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/Slice4ImportExportTest.kt@@ -0,0 +1,241 @@+package com.vayunmathur.office.odf++import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import java.io.ByteArrayInputStream+import java.io.File+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertIs+import kotlin.test.assertTrue++/**+ * Slice 4/4 importer/writer tests (Robolectric): [DocumentImporter] routing via+ * registered content-resolver streams, and [OdfWriter] save round-trips through+ * real files. No network, no ViewModel.+ */+@RunWith(AndroidJUnit4::class)+class Slice4ImportExportTest {++    private val context: android.content.Context+        get() = ApplicationProvider.getApplicationContext()++    private fun uriFor(name: String, bytes: ByteArray): Uri {+        val uri = Uri.parse("content://com.vayunmathur.office.test/$name")+        shadowOf(context.contentResolver).registerInputStream(uri, ByteArrayInputStream(bytes))+        return uri+    }++    /**+     * content:// output backed by a real file: Robolectric's ContentResolver+     * does not serve file:// output streams, so save() targets go through a+     * registered test provider that opens [outTarget].+     */+    private var outTarget: File?+        get() = Slice4Provider.outTarget+        set(v) { Slice4Provider.outTarget = v }++    init {+        // Repo-standard fake-provider hookup (see communicate's CarrierVoicemailTest):+        // serves content:// output streams backed by [outTarget].+        org.robolectric.Robolectric.setupContentProvider(+            Slice4Provider::class.java,+            "com.vayunmathur.office.slice4test")+    }++    private fun contentUri(name: String): Uri =+        Uri.parse("content://com.vayunmathur.office.slice4test/$name")++    class Slice4Provider : android.content.ContentProvider() {+        companion object {+            @Volatile var outTarget: File? = null+        }++        override fun onCreate(): Boolean = true+        override fun openFile(uri: Uri, mode: String): android.os.ParcelFileDescriptor? {+            val test = outTarget ?: return null+            return android.os.ParcelFileDescriptor.open(+                test, android.os.ParcelFileDescriptor.MODE_READ_WRITE+                    or android.os.ParcelFileDescriptor.MODE_CREATE+                    or android.os.ParcelFileDescriptor.MODE_TRUNCATE)+        }+        override fun query(+            uri: Uri, projection: Array<String>?, selection: String?,+            selectionArgs: Array<String>?, sortOrder: String?,+        ): android.database.Cursor? = null+        override fun getType(uri: Uri): String? = null+        override fun insert(uri: Uri, values: android.content.ContentValues?): Uri? = null+        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0+        override fun update(+            uri: Uri, values: android.content.ContentValues?,+            selection: String?, selectionArgs: Array<String>?,+        ): Int = 0+    }++    private fun textOf(doc: OdfDocument.TextDocument): String =+        doc.content.filterIsInstance<OdfContentBlock.Paragraph>()+            .joinToString("\n") { it.paragraph.spans.joinToString("") { s -> s.text } }++    // ---- DocumentImporter.open ----++    @Test fun plainTextByExtension() {+        val doc = DocumentImporter.open(+            context, uriFor("n.txt", "hello\nworld".encodeToByteArray()), "n.txt")+        assertIs<OdfDocument.TextDocument>(doc)+        assertEquals("hello\nworld", textOf(doc))+    }++    @Test fun plainTextFallbackForUnknownExtension() {+        val doc = DocumentImporter.open(+            context, uriFor("n.xyz", "just text".encodeToByteArray()), "n.xyz")+        assertIs<OdfDocument.TextDocument>(doc)+        assertEquals("just text", textOf(doc))+    }++    @Test fun markdownByExtension() {+        val doc = DocumentImporter.open(+            context, uriFor("n.md", "# Title\n\nbody".encodeToByteArray()), "n.md")+        assertIs<OdfDocument.TextDocument>(doc)+        assertTrue(textOf(doc).contains("Title"), textOf(doc))+    }++    @Test fun csvByExtension() {+        val doc = DocumentImporter.open(+            context, uriFor("n.csv", "a,b\nc,d\n".encodeToByteArray()), "n.csv")+        assertIs<OdfDocument.Spreadsheet>(doc)+        assertEquals(2, doc.sheets[0].rows.size)+    }++    @Test fun tsvByExtension() {+        val doc = DocumentImporter.open(+            context, uriFor("n.tsv", "a\tb\n".encodeToByteArray()), "n.tsv")+        assertIs<OdfDocument.Spreadsheet>(doc)+    }++    @Test fun legacyBinaryRejected() {+        // OLE/CFB magic without extension info -> encrypted/legacy error.+        val ole = byteArrayOf(+            0xD0.toByte(), 0xCF.toByte(), 0x11.toByte(), 0xE0.toByte(),+            0xA1.toByte(), 0xB1.toByte(), 0x1A.toByte(), 0xE1.toByte())+        assertFailsWith<IllegalArgumentException> {+            DocumentImporter.open(context, uriFor("n.bin", ole), "n.bin")+        }+    }++    @Test fun legacyDocExtensionRejected() {+        assertFailsWith<IllegalArgumentException> {+            DocumentImporter.open(context, uriFor("n.doc", ByteArray(0)), "n.doc")+        }+    }++    @Test fun flatOdfSniffedFromBytes() {+        val flat = """<?xml version="1.0"?>+<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">+<office:body><office:text><text:p>sniffed</text:p></office:text></office:body>+</office:document>""".encodeToByteArray()+        // Unknown extension + flat-ODF bytes: the sniff falls back to ODF parsing,+        // which accepts single-XML flat documents, not just zip packages.+        val doc = DocumentImporter.open(context, uriFor("n.fodt", flat), "n.fodt")+        assertIs<OdfDocument.TextDocument>(doc)+        assertTrue(textOf(doc).contains("sniffed"), textOf(doc))+    }++    @Test fun htmlAndRtfByExtension() {+        val html = DocumentImporter.open(+            context, uriFor("n.html", "<p>web</p>".encodeToByteArray()), "n.html")+        assertIs<OdfDocument.TextDocument>(html)+        val rtf = DocumentImporter.open(+            context, uriFor("n.rtf", "{\\rtf1 rich}".encodeToByteArray()), "n.rtf")+        assertIs<OdfDocument.TextDocument>(rtf)+    }++    // ---- OdfWriter.save ----++    private fun sampleDoc() = OdfDocument.TextDocument(+        "Saved",+        listOf(+            OdfContentBlock.Paragraph(+                com.vayunmathur.library.ui.odf.OdfParagraph(+                    listOf(com.vayunmathur.library.ui.odf.OdfSpan("round trip")))),+        ),+        metadata = com.vayunmathur.library.ui.odf.OdfMetadata(title = "Saved"),+    )++    private fun zipEntries(zip: File): Set<String> {+        val names = mutableSetOf<String>()+        java.util.zip.ZipFile(zip).use { z ->+            val e = z.entries()+            while (e.hasMoreElements()) names.add(e.nextElement().name)+        }+        return names+    }++    @Test fun saveNewDocumentWritesValidPackage() {+        val out = File(context.cacheDir, "slice4-new.odt")+        out.delete()+        outTarget = out+        try {+            OdfWriter.save(context, null, sampleDoc(), contentUri("slice4-new.odt"))+            assertTrue(out.exists(), "save produced no file")+            assertTrue(out.length() > 100, "save wrote ${out.length()} bytes")+            val entries = zipEntries(out)+            assertTrue(entries.contains("mimetype"), entries.toString())+            assertTrue(entries.contains("content.xml"), entries.toString())+            assertTrue(entries.contains("META-INF/manifest.xml"), entries.toString())+            // content.xml carries our paragraph text.+            java.util.zip.ZipFile(out).use { z ->+                val xml = z.getInputStream(z.getEntry("content.xml")).bufferedReader().readText()+                assertTrue(xml.contains("round trip"), xml)+            }+        } finally {+            out.delete()+            outTarget = null+        }+    }++    @Test fun savePreservesSourceEntries() {+        val first = File(context.cacheDir, "slice4-first.odt")+        val second = File(context.cacheDir, "slice4-second.odt")+        first.delete()+        second.delete()+        outTarget = first+        try {+            OdfWriter.save(context, null, sampleDoc(), contentUri("slice4-first.odt"))+            shadowOf(context.contentResolver).registerInputStream(+                contentUri("slice4-first.odt"), first.inputStream())+            outTarget = second+            OdfWriter.save(+                context,+                contentUri("slice4-first.odt"),+                sampleDoc(),+                contentUri("slice4-second.odt"))+            val entries = zipEntries(second)+            assertTrue(entries.contains("content.xml"), entries.toString())+            assertTrue(entries.contains("META-INF/manifest.xml"), entries.toString())+        } finally {+            first.delete()+            second.delete()+            outTarget = null+        }+    }++    @Test fun saveAsDelegatesToSave() {+        val out = File(context.cacheDir, "slice4-saveas.odt")+        out.delete()+        outTarget = out+        try {+            OdfWriter.saveAs(context, null, sampleDoc(), contentUri("slice4-saveas.odt"))+            assertTrue(out.exists())+        } finally {+            out.delete()+            outTarget = null+        }+    }+}
office/src/test/java/com/vayunmathur/office/odf/Slice4MathLogicTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/odf/Slice4MathLogicTest.kt b/office/src/test/java/com/vayunmathur/office/odf/Slice4MathLogicTest.ktnew file mode 100644index 0000000000..0031fe48db--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/odf/Slice4MathLogicTest.kt@@ -0,0 +1,335 @@+package com.vayunmathur.office.odf++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 4/4 pure-logic tests: the math/formula/number-format helpers owned by+ * this slice (OdfMath, OmmlToMathml, ExcelNumFmt, ExcelFormula extras).+ */+class Slice4MathLogicTest {++    // ---- OdfMath.parse / toText ----++    @Test fun mathParsesSimpleRow() {+        val node = OdfMath.parse("<math><mi>x</mi><mo>+</mo><mn>2</mn></math>")+        assertNotNull(node)+        assertEquals("x+2", OdfMath.toText(node))+    }++    @Test fun mathParsesFraction() {+        val node = OdfMath.parse("<math><mfrac><mi>a</mi><mi>b</mi></mfrac></math>")+        assertNotNull(node)+        assertEquals("(a)/(b)", OdfMath.toText(node))+    }++    @Test fun mathParsesSupSub() {+        val sup = OdfMath.parse("<math><msup><mi>x</mi><mn>2</mn></msup></math>")+        assertEquals("x^2", OdfMath.toText(assertNotNull(sup)))+        val sub = OdfMath.parse("<math><msub><mi>x</mi><mi>i</mi></msub></math>")+        assertEquals("x_i", OdfMath.toText(assertNotNull(sub)))+    }++    @Test fun mathParsesSubSup() {+        val node = OdfMath.parse("<math><msubsup><mi>x</mi><mi>i</mi><mn>2</mn></msubsup></math>")+        assertEquals("x_i^2", OdfMath.toText(assertNotNull(node)))+    }++    @Test fun mathParsesSqrtAndRoot() {+        val sqrt = OdfMath.parse("<math><msqrt><mi>x</mi></msqrt></math>")+        assertEquals("√(x)", OdfMath.toText(assertNotNull(sqrt)))+        val root = OdfMath.parse("<math><mroot><mi>x</mi><mn>3</mn></mroot></math>")+        assertEquals("root[3](x)", OdfMath.toText(assertNotNull(root)))+    }++    @Test fun mathParsesFenced() {+        val node = OdfMath.parse("<math><mfenced open=\"[\" close=\"]\"><mi>x</mi></mfenced></math>")+        assertEquals("[x]", OdfMath.toText(assertNotNull(node)))+    }++    @Test fun mathParsesUnderOver() {+        val under = OdfMath.parse("<math><munder><mi>x</mi><mo>~</mo></munder></math>")+        assertEquals("x_~", OdfMath.toText(assertNotNull(under)))+        val over = OdfMath.parse("<math><mover><mi>x</mi><mo>^</mo></mover></math>")+        assertEquals("x^^", OdfMath.toText(assertNotNull(over)))+        val both = OdfMath.parse("<math><munderover><mo>∑</mo><mi>i</mi><mi>n</mi></munderover></math>")+        assertEquals("∑_i^n", OdfMath.toText(assertNotNull(both)))+    }++    @Test fun mathParsesTable() {+        val node = OdfMath.parse(+            "<math><mtable><mtr><mtd><mi>a</mi></mtd><mtd><mi>b</mi></mtd></mtr></mtable></math>")+        // mtr/mtd fall back to Row/TableRow text: "a, b".+        assertEquals("a, b", OdfMath.toText(assertNotNull(node)))+    }++    @Test fun mathParsesMultiscripts() {+        val node = OdfMath.parse(+            "<math><mmultiscripts><mi>x</mi><mi>i</mi><mn>2</mn></mmultiscripts></math>")+        assertEquals("x_i^2", OdfMath.toText(assertNotNull(node)))+    }++    @Test fun mathSkipsAnnotations() {+        val node = OdfMath.parse(+            "<math><semantics><mi>x</mi><annotation>ignore me</annotation></semantics></math>")+        assertEquals("x", OdfMath.toText(assertNotNull(node)))+    }++    @Test fun mathHandlesMspaceAndUnknownTags() {+        val node = OdfMath.parse("<math><mspace/><foo><mi>y</mi></foo></math>")+        assertEquals(" y", OdfMath.toText(assertNotNull(node)))+    }++    @Test fun mathReturnsNullWithoutMathTag() {+        assertNull(OdfMath.parse("<doc><mi>x</mi></doc>"))+    }++    @Test fun mathReturnsNullOnGarbage() {+        // Empty / non-XML input has no <math> tag -> null.+        assertNull(OdfMath.parse(""))+        assertNull(OdfMath.parse("just text"))+    }++    @Test fun mathToTextCoversNodeKinds() {+        assertIs<MathNode.Row>(OdfMath.parse("<math><mrow><mi>a</mi></mrow></math>"))+        // parse() always wraps in a top-level Row; the table is its first child.+        val table = OdfMath.parse("<math><mtable><mtr><mtd><mi>a</mi></mtd></mtr></mtable></math>")+        val row = assertNotNull(table) as MathNode.Row+        assertIs<MathNode.Table>(row.children[0])+        val fencedDefault = OdfMath.parse("<math><mfenced><mi>q</mi></mfenced></math>")+        assertEquals("(q)", OdfMath.toText(assertNotNull(fencedDefault)))+    }++    // ---- OmmlToMathml.convert ----++    @Test fun ommlConvertsRun() {+        val out = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:r><m:t>x+2</m:t></m:r></m:oMath>")+        assertNotNull(out)+        assertTrue(out.contains("<mi>x</mi>"), out)+        assertTrue(out.contains("<mo>+</mo>"), out)+        assertTrue(out.contains("<mn>2</mn>"), out)+    }++    @Test fun ommlReturnsNullWhenNoOMath() {+        assertNull(OmmlToMathml.convert("<w:p xmlns:w=\"x\"><w:r><w:t>hi</w:t></w:r></w:p>"))+    }++    @Test fun ommlConvertsFraction() {+        val out = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:f><m:num><m:r><m:t>a</m:t></m:r></m:num>" ++                "<m:den><m:r><m:t>b</m:t></m:r></m:den></m:f></m:oMath>")+        assertTrue(assertNotNull(out).contains("<mfrac>"), out)+    }++    @Test fun ommlConvertsSupSubAndSubSup() {+        val sup = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:sSup><m:e><m:r><m:t>x</m:t></m:r></m:e>" ++                "<m:sup><m:r><m:t>2</m:t></m:r></m:sup></m:sSup></m:oMath>")+        assertTrue(assertNotNull(sup).contains("<msup>"), sup)+        val sub = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:sSub><m:e><m:r><m:t>x</m:t></m:r></m:e>" ++                "<m:sub><m:r><m:t>i</m:t></m:r></m:sub></m:sSub></m:oMath>")+        assertTrue(assertNotNull(sub).contains("<msub>"), sub)+        val both = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:sSubSup><m:e><m:r><m:t>x</m:t></m:r></m:e>" ++                "<m:sub><m:r><m:t>i</m:t></m:r></m:sub>" ++                "<m:sup><m:r><m:t>2</m:t></m:r></m:sup></m:sSubSup></m:oMath>")+        assertTrue(assertNotNull(both).contains("<msubsup>"), both)+    }++    @Test fun ommlConvertsRadWithAndWithoutDegree() {+        val sqrt = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:rad><m:e><m:r><m:t>x</m:t></m:r></m:e></m:rad></m:oMath>")+        assertTrue(assertNotNull(sqrt).contains("<msqrt>"), sqrt)+        val root = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:rad><m:deg><m:r><m:t>3</m:t></m:r></m:deg>" ++                "<m:e><m:r><m:t>x</m:t></m:r></m:e></m:rad></m:oMath>")+        assertTrue(assertNotNull(root).contains("<mroot>"), root)+    }++    @Test fun ommlConvertsNaryDelimFuncMatrix() {+        val nary = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:nary><m:naryPr><m:chr m:val=\"∑\"/></m:naryPr>" ++                "<m:sub><m:r><m:t>i</m:t></m:r></m:sub>" ++                "<m:e><m:r><m:t>x</m:t></m:r></m:e></m:nary></m:oMath>")+        val naryOut = assertNotNull(nary)+        assertTrue(naryOut.contains("<munder>"), naryOut)+        val naryBoth = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:nary><m:sub><m:r><m:t>a</m:t></m:r></m:sub>" ++                "<m:sup><m:r><m:t>b</m:t></m:r></m:sup>" ++                "<m:e><m:r><m:t>c</m:t></m:r></m:e></m:nary></m:oMath>")+        assertTrue(assertNotNull(naryBoth).contains("<munderover>"))+        val narySupOnly = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:nary><m:sup><m:r><m:t>b</m:t></m:r></m:sup>" ++                "<m:e><m:r><m:t>c</m:t></m:r></m:e></m:nary></m:oMath>")+        assertTrue(assertNotNull(narySupOnly).contains("<mover>"))+        val delim = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:d><m:dPr><m:begChr m:val=\"[\"/>" ++                "<m:endChr m:val=\"]\"/></m:dPr>" ++                "<m:e><m:r><m:t>x</m:t></m:r></m:e></m:d></m:oMath>")+        assertTrue(assertNotNull(delim).contains("<mo>[</mo>"), delim)+        val func = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:func><m:fName><m:r><m:t>sin</m:t></m:r></m:fName>" ++                "<m:e><m:r><m:t>x</m:t></m:r></m:e></m:func></m:oMath>")+        assertTrue(assertNotNull(func).contains("sin"), func)+        val matrix = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:m><m:mr><m:e><m:r><m:t>a</m:t></m:r></m:e>" ++                "<m:e><m:r><m:t>b</m:t></m:r></m:e></m:mr></m:m></m:oMath>")+        assertTrue(assertNotNull(matrix).contains("<mtable>"), matrix)+    }++    @Test fun ommlClassifyTextNumbersAndOps() {+        val out = OmmlToMathml.convert(+            "<m:oMath xmlns:m=\"x\"><m:r><m:t>12.5 ab+% &lt;</m:t></m:r></m:oMath>")+        val s = assertNotNull(out)+        assertTrue(s.contains("<mn>12.5</mn>"), s)+        assertTrue(s.contains("<mi>ab</mi>"), s)+        assertTrue(s.contains("<mo>+</mo>"), s)+        assertTrue(s.contains("<mo>%</mo>"), s)+        // "&lt;" in the XML source decodes to '<', which the renderer re-escapes.+        assertTrue(s.contains("&lt;"), s)+    }++    // ---- ExcelNumFmt ----++    @Test fun numFmtBuiltinGeneralIsNull() {+        assertNull(ExcelNumFmt.forBuiltin(0))+        assertNull(ExcelNumFmt.parse("General"))+        assertNull(ExcelNumFmt.parse(""))+    }++    @Test fun numFmtBuiltinDecimals() {+        assertEquals(2, ExcelNumFmt.forBuiltin(2)?.decimals)+        assertEquals(0, ExcelNumFmt.forBuiltin(1)?.decimals)+    }++    @Test fun numFmtBuiltinGroupingAndPercent() {+        val grouped = ExcelNumFmt.forBuiltin(3)+        assertEquals(true, grouped?.grouping)+        val pct = ExcelNumFmt.forBuiltin(9)+        assertEquals(true, pct?.percent)+        val sci = ExcelNumFmt.forBuiltin(11)+        assertEquals(true, sci?.isScientific)+    }++    @Test fun numFmtBuiltinFraction() {+        assertEquals(true, ExcelNumFmt.forBuiltin(12)?.isFraction)+        assertEquals(2, ExcelNumFmt.forBuiltin(13)?.fractionDenominatorDigits)+    }++    @Test fun numFmtBuiltinDates() {+        assertTrue(ExcelNumFmt.isDateTimeBuiltin(14))+        assertTrue(ExcelNumFmt.isDateTimeBuiltin(45))+        assertTrue(ExcelNumFmt.isDateTimeBuiltin(27))+        assertTrue(ExcelNumFmt.isDateTimeBuiltin(50))+        assertTrue(!ExcelNumFmt.isDateTimeBuiltin(2))+        val d = ExcelNumFmt.forBuiltin(14)+        assertEquals(true, d?.isDate)+        // Locale/CJK builtins fall back to a default date pattern.+        assertEquals(true, ExcelNumFmt.forBuiltin(27)?.isDate)+        assertEquals(true, ExcelNumFmt.forBuiltin(50)?.isDate)+        assertNull(ExcelNumFmt.forBuiltin(999))+    }++    @Test fun numFmtCustomNumeric() {+        val f = ExcelNumFmt.parse("#,##0.00")+        assertEquals(2, f?.decimals)+        assertEquals(true, f?.grouping)+        val plain = ExcelNumFmt.parse("0")+        assertEquals(0, plain?.decimals)+    }++    @Test fun numFmtCustomDateTime() {+        val dt = ExcelNumFmt.parse("yyyy-mm-dd")+        assertEquals(true, dt?.isDate)+        assertTrue(dt?.dateTimeTokens?.any { it.kind == "year" } == true)+        assertTrue(dt?.dateTimeTokens?.any { it.kind == "month" } == true)+        assertTrue(dt?.dateTimeTokens?.any { it.kind == "day" } == true)+        val tm = ExcelNumFmt.parse("h:mm:ss")+        assertEquals(true, tm?.isTime)+        val ampm = ExcelNumFmt.parse("h:mm AM/PM")+        assertTrue(ampm?.dateTimeTokens?.any { it.kind == "am-pm" } == true)+    }++    @Test fun numFmtMinuteVsMonth() {+        // 'm' after an hour is minutes.+        val hm = ExcelNumFmt.parse("h:mm")+        val kinds = hm?.dateTimeTokens?.map { it.kind } ?: emptyList()+        assertTrue(kinds.contains("minutes"), kinds.toString())+        // 'mmm' is a textual month.+        val mmm = ExcelNumFmt.parse("d-mmm-yy")+        assertTrue(mmm?.dateTimeTokens?.any { it.kind == "month" && it.textual } == true)+    }++    @Test fun numFmtTextCodeIsNull() {+        assertNull(ExcelNumFmt.parse("@"))+    }++    @Test fun numFmtFirstSectionOnly() {+        val f = ExcelNumFmt.parse("0.00;[Red]-0.00")+        assertEquals(2, f?.decimals)+    }++    @Test fun numFmtCurrency() {+        val f = ExcelNumFmt.parse("\$#,##0.00")+        assertEquals("$", f?.currencySymbol)+        val euro = ExcelNumFmt.parse("[$€-407]#,##0.00")+        assertEquals("€", euro?.currencySymbol)+    }++    @Test fun numFmtQuotedLiteralNotDate() {+        // 0" days" is a number with a literal suffix, not a date.+        val f = ExcelNumFmt.parse("0\" days\"")+        assertEquals(false, f?.isDate)+        assertEquals(false, f?.isTime)+    }++    @Test fun numFmtDayOfWeekAndEscapes() {+        val dow = ExcelNumFmt.parse("ddd")+        assertTrue(dow?.dateTimeTokens?.any { it.kind == "day-of-week" } == true)+        val esc = ExcelNumFmt.parse("yyyy\\-mm\\-dd")+        assertTrue(esc?.dateTimeTokens?.any { it.kind == "text" } == true)+        val ap = ExcelNumFmt.parse("h:mm A/P")+        assertTrue(ap?.dateTimeTokens?.any { it.kind == "am-pm" } == true)+    }++    // ---- ExcelFormula.shift ----++    @Test fun formulaShiftMovesRelativeRefs() {+        assertEquals("B2", ExcelFormula.shift("A1", 1, 1))+        // Absolute parts stay; relative parts move ($A1 -> col fixed, row 1+5).+        assertEquals("\$A6", ExcelFormula.shift("\$A1", 5, 5))+        assertEquals("F\$1", ExcelFormula.shift("A\$1", 5, 5))+        assertEquals("A1", ExcelFormula.shift("A1", 0, 0))+    }++    @Test fun formulaShiftSkipsStringLiterals() {+        assertEquals("\"A1\"+B2", ExcelFormula.shift("\"A1\"+A1", 1, 1))+    }++    @Test fun formulaToOdfBasic() {+        assertEquals("of:=SUM([.A1:.A3])+[.B1]", ExcelFormula.toOdf("SUM(A1:A3)+B1"))+    }++    @Test fun formulaRoundTripWholeColumn() {+        val excel = "SUM(A:A)"+        val odf = ExcelFormula.toOdf(excel)+        assertEquals("=$excel", ExcelFormula.fromOdf(odf))+    }++    @Test fun formulaFromOdfPassThrough() {+        assertEquals("=1+2", ExcelFormula.fromOdf("of:=1+2"))+        assertEquals("=1,2", ExcelFormula.fromOdf("of:=1;2"))+    }++    @Test fun formulaMaxColLetters() {+        assertEquals("XFD", ExcelFormula.MAX_COL_LETTERS)+        assertEquals(1048576, ExcelFormula.MAX_ROWS)+        assertEquals(16384, ExcelFormula.MAX_COLS)+    }+}
office/src/test/java/com/vayunmathur/office/ui/Slice4DialogsTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/Slice4DialogsTest.kt b/office/src/test/java/com/vayunmathur/office/ui/Slice4DialogsTest.ktnew file mode 100644index 0000000000..223502fbb3--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/Slice4DialogsTest.kt@@ -0,0 +1,518 @@+package com.vayunmathur.office.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextClearance+import androidx.compose.ui.test.performTextInput+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.ChartType+import com.vayunmathur.library.ui.odf.OdfChart+import com.vayunmathur.library.ui.odf.OdfChartSeries+import com.vayunmathur.office.EnableOnlineDialog+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 4/4 dialog tests (Robolectric + createComposeRule): small self-contained+ * dialogs owned by this slice. Each test renders the dialog, interacts, and+ * asserts the callback contract. Text fields are located via [hasSetTextAction]+ * (labels are separate nodes from the editable field).+ */+@RunWith(AndroidJUnit4::class)+class Slice4DialogsTest {++    @get:Rule val rule = createComposeRule()++    // ---- ColorPickerDialog ----++    @Test fun colorPickerSelectsClearAndDismisses() {+        var picked: Long? = 123L+        var dismissed = false+        rule.setContent {+            ColorPickerDialog(+                title = "Text Color",+                onColorSelected = { picked = it },+                onDismiss = { dismissed = true })+        }+        rule.onNodeWithText("Text Color").assertIsDisplayed()+        // The null/"clear" swatch shows ∅.+        rule.onNodeWithText("∅").assertIsDisplayed()+        rule.onNodeWithText("∅").performClick()+        assertNull(picked)+        assertTrue(dismissed)+    }++    @Test fun colorPickerCancelDismissesWithoutPick() {+        var picked: Long? = null+        var dismissed = false+        rule.setContent {+            ColorPickerDialog(+                title = "Fill",+                onColorSelected = { picked = it },+                onDismiss = { dismissed = true })+        }+        rule.onNodeWithText("Cancel", substring = true).performClick()+        assertNull(picked)+        assertTrue(dismissed)+    }++    // ---- FontSizePickerDialog ----++    @Test fun fontSizePickerSelectsSize() {+        var picked: Float? = null+        var dismissed = false+        rule.setContent {+            FontSizePickerDialog(+                onSizeSelected = { picked = it },+                onDismiss = { dismissed = true })+        }+        rule.onNodeWithText("Font Size").assertIsDisplayed()+        rule.onNodeWithText("16").assertIsDisplayed()+        rule.onNodeWithText("24").performClick()+        assertEquals(24f, picked)+        assertTrue(dismissed)+    }++    // ---- SpecialCharsDialog ----++    @Test fun specialCharsPicksChar() {+        var picked: String? = null+        var dismissed = false+        rule.setContent {+            SpecialCharsDialog(+                onPick = { picked = it },+                onDismiss = { dismissed = true })+        }+        rule.onNodeWithText("Special Character").assertIsDisplayed()+        rule.onNodeWithText("©").assertIsDisplayed()+        rule.onNodeWithText("→").performClick()+        assertEquals("→", picked)+        assertTrue(dismissed)+    }++    // ---- FootnoteDialog ----+

Diff truncated.