office: slice 4 pass 2 tests for screens, menus, overlays and sync
- Commit
04fa15456876d419ef58a88f0e24c508f1924f4d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 08:02 UTC (29 days ago)
- Parents
6ac7dce
Slice 4 (root + ui + non-ViewModel util classes, per-class counters in the merged report): 69.1% (55450/80226) at first-pass landing -> 78.7% (63132/80226) re-measured on current main -> 85.3% (68394/80226) with these tests. Full module suite: 952 tests, 0 failures. New tests (11 Slice4Pass2* files, ~93 tests): - ui/Slice4Pass2MathChartParaTest: formatAxis/evalCondFormat logic, MathView every MathML node kind, OdfChartView every chart type with captureToImage, ParagraphView styles/spans/search/annotation. - Slice4Pass2OnlineHomeTest: OnlineTab enabled lists (docs, join requests, open-doc), OfficeTabs, InitialScreen, wide layout, themes, OfficeRoute serialization. - Slice4Pass2MenusOverlaysTest: InsertMenu items mutating state and document, cell bg/border/comment/resize and slide color overlays. - ui/Slice4Pass2FormatMenusTest: TextFormatControls table menu (row/column/cell/merge verified in the document), style/align/list and more-menu paragraph ops. - ui/Slice4Pass2SheetViewsTest: rich spreadsheet cells (merges, borders, conditional formats, validation dropdown), edit-mode selection/rename/add-sheet, sheet tabs. - ui/Slice4Pass2CellElementFormatTest: cell align + every number format, more-menu callbacks and fill-down; element align/reorder/ duplicate/slide-action menus. - ui/Slice4Pass2FloatingDocTest: FloatingElementLayer all element kinds, TextDocumentView all block kinds, fullscreen image crop, DrawingView paging + text field, InsertControl menus, OdfImageView effect/rotation/crop variants. - Slice4Pass2MainActivityTest: MainActivity launches to home. - Slice4Pass2CropOverlaysTest: slide/sheet/text ImageCropDialog apply/rotate/reset/cancel through DocumentOverlays. - Slice4Pass2PaneExportTest: presence banner, ExportMenu per-type items staging the export warning, export-as-text share. - util/Slice4Pass2SyncNetworkTest: OfficeSync offline degradation (every network entry point nulls/false/empty), sortInboxText kinds, parseLive edges, live-session guards. Production changes: none. Bugs fixed: none. Verified: gslot ./gradlew :office:createMergedCoverageReport and the full :office:testDevUnitTest suite (952 tests passing). :office:lint still fails on pre-existing pass-1 test files (Slice4MenusOverlaysTest, Slice4PresentationTest: UnrememberedMutableState); the two findings introduced by this slice were fixed. Untestable remainder: OfficeSync live WebSocket/relay paths (no real network), OfficeDocumentLaunchers activity-result callbacks, chart/ grid drawBehind painting under Robolectric, MainActivity join-link intents (need a registered device). (cherry picked from commit a9b7df33ac896325676c33543752136b5591cf8a)
Diff
office/src/test/java/com/vayunmathur/office/Slice4Pass2CropOverlaysTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4Pass2CropOverlaysTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4Pass2CropOverlaysTest.ktnew file mode 100644index 0000000000..1600afba99--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4Pass2CropOverlaysTest.kt@@ -0,0 +1,171 @@+package com.vayunmathur.office++import android.content.Context+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.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.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfImage+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfRow+import com.vayunmathur.library.ui.odf.OdfCell+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.util.OfficeViewModel+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 pass 2: slide/sheet/text image crop overlays through DocumentOverlays. */+@RunWith(AndroidJUnit4::class)+class Slice4Pass2CropOverlaysTest {++ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int) = ctx.getString(id)++ 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) {+ rule.setContent {+ DocumentOverlays(+ state = state,+ document = document,+ viewModel = viewModel,+ isPresentation = document is OdfDocument.Presentation,+ isOnline = false,+ focusedPara = 0,+ saveAsName = "Doc",+ activeCell = remember { mutableStateOf(null) },+ activeSlide = remember { mutableStateOf(0) },+ activeSlideEl = remember { mutableStateOf(0) },+ 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 = {},+ )+ }+ }++ private fun imageFrame() = OdfSlideElement.Frame(+ OdfFrame(+ 0f, 0f, 100f, 80f, emptyList(),+ image = OdfImage(+ path = "p.png", imageData = ByteArray(0),+ cropLeftPct = 0.1f, cropTopPct = 0.2f,+ ),+ )+ )++ private fun deckDoc() = OdfDocument.Presentation("Deck.odp", listOf(OdfSlide("S1", listOf(imageFrame()))))++ private fun sheetDoc() = OdfDocument.Spreadsheet(+ "Book.ods",+ listOf(+ OdfSheet(+ "S",+ listOf(OdfRow(listOf(OdfCell("a")))),+ floating = listOf(imageFrame()),+ )+ ),+ )++ private fun textDoc() = OdfDocument.TextDocument(+ "Doc.odt",+ listOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("body")))),+ OdfContentBlock.Image(OdfImage(path = "p.png", imageData = ByteArray(0), cropTopPct = 0.3f)),+ ),+ )++ @Test fun slideCropOverlayApplyDismissesAndResetClears() {+ val viewModel = vm(deckDoc())+ val state = DocumentOverlayState().apply { cropSlideTarget = 0 to 0 }+ overlays(state, deckDoc(), viewModel)+ rule.onNodeWithText(str(R.string.edit_image)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.apply)).performClick()+ assertNull(state.cropSlideTarget)+ val frame = ((viewModel.state.value as OfficeViewModel.ViewState.Loaded).document+ as OdfDocument.Presentation).slides[0].elements[0] as OdfSlideElement.Frame+ assertEquals(0.1f, frame.frame.image!!.cropLeftPct)+ }++ @Test fun slideCropOverlayMissingImageClearsTarget() {+ val doc = OdfDocument.Presentation(+ "Deck.odp",+ listOf(+ OdfSlide(+ "S1",+ listOf(+ OdfSlideElement.Frame(+ OdfFrame(0f, 0f, 10f, 10f, listOf(OdfParagraph(listOf(OdfSpan("t")))))+ )+ ),+ )+ ),+ )+ val state = DocumentOverlayState().apply { cropSlideTarget = 0 to 0 }+ overlays(state, doc, vm(doc))+ rule.waitForIdle()+ assertNull(state.cropSlideTarget, "target without an image dismisses itself")+ }++ @Test fun sheetCropOverlayRotateAndCancel() {+ val viewModel = vm(sheetDoc())+ val state = DocumentOverlayState().apply { cropSheetTarget = 0 to 0 }+ overlays(state, sheetDoc(), viewModel)+ rule.onNodeWithText(str(R.string.edit_image)).assertExists()+ rule.onNodeWithText(str(R.string.rotate_90)).performClick()+ val floating = ((viewModel.state.value as OfficeViewModel.ViewState.Loaded).document+ as OdfDocument.Spreadsheet).sheets[0].floating[0] as OdfSlideElement.Frame+ assertEquals(90f, floating.frame.image!!.rotationDegrees)+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+ assertNull(state.cropSheetTarget)+ }++ @Test fun sheetCropOverlayResetZeroesCrop() {+ val viewModel = vm(sheetDoc())+ val state = DocumentOverlayState().apply { cropSheetTarget = 0 to 0 }+ overlays(state, sheetDoc(), viewModel)+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.reset)).performClick()+ assertNull(state.cropSheetTarget)+ val floating = ((viewModel.state.value as OfficeViewModel.ViewState.Loaded).document+ as OdfDocument.Spreadsheet).sheets[0].floating[0] as OdfSlideElement.Frame+ assertEquals(0f, floating.frame.image!!.cropLeftPct)+ assertEquals(0f, floating.frame.image!!.cropTopPct)+ }++ @Test fun textImageCropOverlayViaSlideOverlays() {+ val viewModel = vm(textDoc())+ val state = DocumentOverlayState().apply { cropImageBlock = 1 }+ overlays(state, textDoc(), viewModel)+ rule.onNodeWithText(str(R.string.edit_image)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.apply)).performClick()+ assertEquals(-1, state.cropImageBlock)+ val block = ((viewModel.state.value as OfficeViewModel.ViewState.Loaded).document+ as OdfDocument.TextDocument).content[1] as OdfContentBlock.Image+ assertEquals(0.3f, block.image.cropTopPct)+ }+}
office/src/test/java/com/vayunmathur/office/Slice4Pass2MainActivityTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4Pass2MainActivityTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4Pass2MainActivityTest.ktnew file mode 100644index 0000000000..76a3367b6f--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4Pass2MainActivityTest.kt@@ -0,0 +1,25 @@+package com.vayunmathur.office++import android.content.Context+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 org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertTrue++/** Slice 4 pass 2: MainActivity launches into the office home (nav graph + theme). */+@RunWith(AndroidJUnit4::class)+class Slice4Pass2MainActivityTest {++ @get:Rule val rule = createAndroidComposeRule<MainActivity>()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Test fun mainActivityLaunchesToHome() {+ rule.onNodeWithText(ctx.getString(R.string.open_document)).assertExists()+ rule.onNodeWithText(ctx.getString(R.string.app_name), substring = true).assertExists()+ assertTrue(rule.activity.intent?.action == "android.intent.action.MAIN" || rule.activity.intent != null)+ }+}
office/src/test/java/com/vayunmathur/office/Slice4Pass2MenusOverlaysTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4Pass2MenusOverlaysTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4Pass2MenusOverlaysTest.ktnew file mode 100644index 0000000000..8650de0e44--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4Pass2MenusOverlaysTest.kt@@ -0,0 +1,274 @@+package com.vayunmathur.office++import android.content.Context+import androidx.activity.ComponentActivity+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+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.library.ui.odf.OdfTable+import com.vayunmathur.library.ui.odf.OdfTableCell+import com.vayunmathur.library.ui.odf.OdfTableRow+import com.vayunmathur.office.util.OfficeViewModel+import com.vayunmathur.office.util.cellCommentText+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Slice 4 pass 2: InsertMenu items, cell/slide color+comment+resize overlays. */+@RunWith(AndroidJUnit4::class)+class Slice4Pass2MenusOverlaysTest {++ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int) = ctx.getString(id)++ private fun vm(doc: OdfDocument): OfficeViewModel =+ OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+ stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+ }++ private fun textDoc() = OdfDocument.TextDocument(+ "Doc.odt",+ listOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("body text")), style = com.vayunmathur.library.ui.odf.ParagraphStyle.HEADING1)),+ OdfContentBlock.Table(+ OdfTable(+ name = "T",+ rows = listOf(+ OdfTableRow(listOf(OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("c00"))))), OdfTableCell())),+ OdfTableRow(listOf(OdfTableCell(), OdfTableCell())),+ ),+ )+ ),+ ),+ )++ private fun sheetDoc() = OdfDocument.Spreadsheet(+ "Book.ods",+ listOf(OdfSheet("S", listOf(OdfRow(listOf(OdfCell("a1"), OdfCell("b1")))))),+ )++ private fun deckDoc() = OdfDocument.Presentation(+ "Deck.odp",+ listOf(+ OdfSlide(+ "S1",+ listOf(+ OdfSlideElement.Frame(+ OdfFrame(0f, 0f, 100f, 50f, listOf(OdfParagraph(listOf(OdfSpan("el")))))+ ),+ ),+ ),+ ),+ )++ private fun loadedText(vm: OfficeViewModel) =+ (vm.state.value as OfficeViewModel.ViewState.Loaded).document as OdfDocument.TextDocument++ // ---- InsertMenu ----++ @Test fun insertMenuHiddenForNonTextDoc() {+ val s = DocumentScreenState()+ val viewModel = vm(textDoc())+ rule.setContent {+ val launchers = rememberDocumentLaunchers(viewModel, s, onPickImageBytes = { _, _ -> })+ InsertMenu(s = s, viewModel = viewModel, isTextDoc = false, focusedPara = 0, launchers = launchers)+ }+ rule.onNodeWithText(str(R.string.insert)).assertDoesNotExist()+ }++ @Test fun insertMenuOpensAndChartItemFlagsEditor() {+ val s = DocumentScreenState()+ val viewModel = vm(textDoc())+ rule.setContent {+ val launchers = rememberDocumentLaunchers(viewModel, s, onPickImageBytes = { _, _ -> })+ InsertMenu(s = s, viewModel = viewModel, isTextDoc = true, focusedPara = 0, launchers = launchers)+ }+ rule.onNodeWithText(str(R.string.insert)).performClick()+ assertTrue(s.insertMenu)+ rule.onNodeWithText(str(R.string.chart)).performClick()+ assertTrue(s.showChartEditor)+ assertEquals(-1, s.editingChartBlock)+ assertFalse(s.insertMenu)+ }++ @Test fun insertMenuDialogItemsSetStateFlags() {+ val s = DocumentScreenState().apply {+ activeRunStart = 0; activeRunEnd = 0; selStart = 0; selEnd = 4+ }+ val viewModel = vm(textDoc())+ rule.setContent {+ val launchers = rememberDocumentLaunchers(viewModel, s, onPickImageBytes = { _, _ -> })+ InsertMenu(s = s, viewModel = viewModel, isTextDoc = true, focusedPara = 0, launchers = launchers)+ }+ fun openAndClick(label: String) {+ s.insertMenu = true+ rule.waitForIdle()+ rule.onNodeWithText(label).performScrollTo().performClick()+ rule.waitForIdle()+ }+ openAndClick(str(R.string.special_character_1)); assertTrue(s.showSpecialChars); s.showSpecialChars = false+ openAndClick(str(R.string.bookmark)); assertTrue(s.showAddBookmark); s.showAddBookmark = false+ openAndClick(str(R.string.footnote)); assertTrue(s.showFootnote); s.showFootnote = false+ openAndClick(str(R.string.comment_1)); assertTrue(s.showComment); s.showComment = false+ openAndClick(str(R.string.header_footer)); assertTrue(s.showHeaderFooter); s.showHeaderFooter = false+ }++ @Test fun insertMenuFieldAndStructuralItemsMutateDocument() {+ val s = DocumentScreenState().apply {+ activeRunStart = 0; activeRunEnd = 0; selStart = 0; selEnd = 4+ }+ val viewModel = vm(textDoc())+ rule.setContent {+ val launchers = rememberDocumentLaunchers(viewModel, s, onPickImageBytes = { _, _ -> })+ InsertMenu(s = s, viewModel = viewModel, isTextDoc = true, focusedPara = 0, launchers = launchers)+ }+ fun openAndClick(label: String) {+ s.insertMenu = true+ rule.waitForIdle()+ rule.onNodeWithText(label).performScrollTo().performClick()+ rule.waitForIdle()+ }+ openAndClick("Date (field)")+ val afterField = loadedText(viewModel)+ val spans = (afterField.content[0] as OdfContentBlock.Paragraph).paragraph.spans+ assertTrue(spans.any { it.field == "date" }, "date field span inserted: $spans")++ val before = loadedText(viewModel).content.size+ openAndClick(str(R.string.horizontal_line))+ assertTrue(loadedText(viewModel).content.size >= before)+ openAndClick(str(R.string.page_break))+ assertTrue(+ loadedText(viewModel).content.any { it is OdfContentBlock.PageBreak },+ "page break block inserted",+ )+ openAndClick(str(R.string.table_of_contents))+ assertTrue(+ loadedText(viewModel).content.any { it is OdfContentBlock.TableOfContents },+ "TOC block inserted",+ )+ }++ // ---- Cell / slide overlays ----++ private fun showCellOverlays(+ state: DocumentOverlayState,+ doc: OdfDocument,+ cell: Triple<Int, Int, Int>? = Triple(0, 0, 0),+ slideEl: Int = -1,+ ): OfficeViewModel {+ val viewModel = vm(doc)+ val activeCell = mutableStateOf(cell)+ val activeSlide = mutableIntStateOf(0)+ val activeSlideEl = mutableIntStateOf(slideEl)+ rule.setContent {+ CellOverlays(+ state = state,+ viewModel = viewModel,+ activeCell = activeCell,+ activeSlide = activeSlide,+ activeSlideEl = activeSlideEl,+ )+ }+ return viewModel+ }++ @Test fun cellBgColorOverlayApplies() {+ val bgState = DocumentOverlayState().apply { showCellBgColor = true }+ showCellOverlays(bgState, sheetDoc())+ rule.onNodeWithText("Background Color").assertIsDisplayed()+ rule.onNodeWithText("∅").performClick()+ assertFalse(bgState.showCellBgColor)+ }++ @Test fun cellBorderColorOverlayApplies() {+ val borderState = DocumentOverlayState().apply { showCellBorderColor = true }+ showCellOverlays(borderState, sheetDoc())+ rule.onNodeWithText("Border Color").assertIsDisplayed()+ rule.onNodeWithText("∅").performClick()+ assertFalse(borderState.showCellBorderColor)+ }++ @Test fun cellCommentOverlaySaveAndCancel() {+ val state = DocumentOverlayState().apply { showCellComment = true }+ val viewModel = showCellOverlays(state, sheetDoc())+ rule.onNodeWithText(str(R.string.cell_comment), substring = true).assertExists()+ // Save with the prefilled (empty) comment text.+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.save), substring = true).performClick()+ assertFalse(state.showCellComment)+ assertEquals("", viewModel.cellCommentText(0, 0, 0))+ }++ @Test fun slideElementTextColorOverlayApplies() {+ val textState = DocumentOverlayState().apply { showSlideTextColor = true }+ showCellOverlays(textState, deckDoc(), cell = null, slideEl = 0)+ rule.onNodeWithText("Text Color").assertIsDisplayed()+ rule.onNodeWithText("∅").performClick()+ assertFalse(textState.showSlideTextColor)+ }++ @Test fun slideElementFillColorOverlayApplies() {+ val fillState = DocumentOverlayState().apply { showSlideFillColor = true }+ showCellOverlays(fillState, deckDoc(), cell = null, slideEl = 0)+ rule.onNodeWithText("Fill Color").assertIsDisplayed()+ rule.onNodeWithText("∅").performClick()+ assertFalse(fillState.showSlideFillColor)+ }++ @Test fun slideElementStrokeColorOverlayApplies() {+ val strokeState = DocumentOverlayState().apply { showSlideStrokeColor = true }+ showCellOverlays(strokeState, deckDoc(), cell = null, slideEl = 0)+ rule.onNodeWithText("Border Color").assertIsDisplayed()+ rule.onNodeWithText("∅").performClick()+ assertFalse(strokeState.showSlideStrokeColor)+ }++ @Test fun insertMenuImageItemLaunchesPicker() {+ val s = DocumentScreenState()+ val viewModel = vm(textDoc())+ rule.setContent {+ val launchers = rememberDocumentLaunchers(viewModel, s, onPickImageBytes = { _, _ -> })+ InsertMenu(s = s, viewModel = viewModel, isTextDoc = true, focusedPara = 0, launchers = launchers)+ }+ s.insertMenu = true+ rule.waitForIdle()+ // Launching the picker opens a system UI under Robolectric; the menu must close first.+ rule.onNodeWithText(str(R.string.image_1)).performClick()+ assertFalse(s.insertMenu)+ }++ @Test fun cellResizeOverlayAppliesSizes() {+ val state = DocumentOverlayState().apply { showCellResize = true }+ showCellOverlays(state, sheetDoc())+ rule.onNodeWithText(str(R.string.row_column_size_1), substring = true).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.apply)).performClick()+ assertFalse(state.showCellResize, "apply dismisses the resize dialog even with empty fields")+ }++ @Test fun cellCommentOverlayCancelDismisses() {+ val state = DocumentOverlayState().apply { showCellComment = true }+ showCellOverlays(state, sheetDoc())+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+ assertFalse(state.showCellComment)+ }+}
office/src/test/java/com/vayunmathur/office/Slice4Pass2OnlineHomeTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4Pass2OnlineHomeTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4Pass2OnlineHomeTest.ktnew file mode 100644index 0000000000..1cdcbb8605--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4Pass2OnlineHomeTest.kt@@ -0,0 +1,174 @@+package com.vayunmathur.office++import android.content.Context+import androidx.activity.ComponentActivity+import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performScrollToNode+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.Text+import com.vayunmathur.office.ui.OfficeEditorWideLayout+import com.vayunmathur.office.util.OfficeDocMeta+import com.vayunmathur.office.util.OfficeSync+import com.vayunmathur.office.util.OfficeViewModel+import kotlinx.serialization.json.Json+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Slice 4 pass 2: OnlineTab enabled lists, OfficeTabs, wide layout, themes, routes. */+@RunWith(AndroidJUnit4::class)+class Slice4Pass2OnlineHomeTest {++ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int, vararg args: Any) = if (args.isEmpty()) ctx.getString(id) else ctx.getString(id, *args)++ private fun vm(): OfficeViewModel =+ OfficeViewModel(ApplicationProvider.getApplicationContext<android.app.Application>())++ /** VM init asynchronously resets onlineEnabled from stored identity; settle it first. */+ private fun settledVm(): OfficeViewModel {+ val viewModel = vm()+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ return viewModel+ }++ private fun meta(docId: String, title: String, owner: Boolean) =+ OfficeDocMeta(docId = docId, title = title, keyB64 = "a2V5", owner = owner)++ @Test fun onlineTabEnabledEmptyShowsNoticeAndDeviceHeader() {+ val viewModel = settledVm()+ rule.setContent { OnlineTab(viewModel = viewModel, onOpenDoc = {}) }+ rule.waitForIdle()+ viewModel.onlineEnabledMutable.value = true+ rule.waitForIdle()+ rule.onNodeWithText(str(R.string.online)).assertExists()+ rule.onNodeWithText(str(R.string.no_online_documents_yet_open_a_document), substring = true).assertExists()+ rule.onNodeWithText(str(R.string.your_device_id_share_this_so_others_can), substring = true).assertExists()+ }++ @Test fun onlineTabEnabledListsDocsAndRequestsAndOpensDoc() {+ val viewModel = settledVm()+ val owned = meta("doc-owned-1", "Owned Report", owner = true)+ val shared = meta("doc-shared-2", "Shared Notes", owner = false)+ var opened: OfficeDocMeta? = null+ rule.setContent { OnlineTab(viewModel = viewModel, onOpenDoc = { opened = it }) }+ rule.waitForIdle()+ viewModel.onlineEnabledMutable.value = true+ rule.waitForIdle()+ viewModel.onlineDocsMutable.value = listOf(owned, shared)+ viewModel.pendingRequestsMutable.value = listOf(+ OfficeSync.JoinRequest(docId = "doc-owned-1", requesterId = "device-abcdef", name = "Carol"),+ OfficeSync.JoinRequest(docId = "missing-doc", requesterId = "device-123456", name = ""),+ )+ rule.waitForIdle()+ rule.onNode(androidx.compose.ui.test.hasScrollAction())+ .performScrollToNode(androidx.compose.ui.test.hasText(str(R.string.requests_header)))+ rule.onNodeWithText(str(R.string.requests_header), substring = true).assertExists()+ rule.onNodeWithText("Carol", substring = true).assertExists()+ rule.onNode(androidx.compose.ui.test.hasScrollAction())+ .performScrollToNode(androidx.compose.ui.test.hasText("Owned Report"))+ rule.onNodeWithText("Owned Report").assertExists()+ rule.onNodeWithText(str(R.string.shared_by_you), substring = true).assertExists()+ rule.onNodeWithText("Owned Report").performClick()+ assertEquals(owned, opened)+ }++ @Test fun onlineTabJoinRequestButtonsRender() {+ val viewModel = settledVm()+ viewModel.onlineDocsMutable.value = listOf(meta("doc-owned-1", "Owned Report", owner = true))+ viewModel.pendingRequestsMutable.value = listOf(+ OfficeSync.JoinRequest(docId = "doc-owned-1", requesterId = "device-abcdef", name = "Dan"),+ )+ rule.setContent { OnlineTab(viewModel = viewModel, onOpenDoc = {}) }+ rule.waitForIdle()+ viewModel.onlineEnabledMutable.value = true+ rule.waitForIdle()+ rule.onNodeWithText(str(R.string.approve)).assertExists()+ rule.onNodeWithText(str(R.string.deny)).assertExists()+ }++ @Test fun officeTabsShowsOfflineHomeAndOnlineTab() {+ val viewModel = vm()+ var editorNavs = 0+ rule.setContent {+ OfficeTabs(+ viewModel = viewModel,+ onOpenDocument = {},+ onNavigateEditor = { editorNavs++ },+ onOpenOnlineDoc = {},+ )+ }+ // Offline (first) page: the initial/home screen actions, plus both tab labels.+ rule.onNodeWithText(str(R.string.open_document)).assertExists()+ rule.onNodeWithText("Online").assertExists()+ rule.onNodeWithText("Offline").assertExists()+ assertEquals(0, editorNavs)+ }++ @Test fun initialScreenNewDocButtonsNavigate() {+ val viewModel = vm()+ var editorNavs = 0+ rule.setContent {+ InitialScreen(viewModel = viewModel, onOpenDocument = {}, onNavigateEditor = { editorNavs++ })+ }+ rule.onNodeWithText(str(R.string.new_doc)).performClick()+ assertEquals(1, editorNavs)+ assertTrue(viewModel.state.value is OfficeViewModel.ViewState.Loaded)+ }++ @Test fun wideLayoutRendersBothSlots() {+ rule.setContent {+ OfficeEditorWideLayout(+ outline = { Text("wide outline") },+ document = { Text("wide document") },+ )+ }+ rule.onNodeWithText("wide outline").assertExists()+ rule.onNodeWithText("wide document").assertExists()+ }++ @Test fun lightThemeAndDarkModeInvertDraw() {+ var dark by mutableStateOf(false)+ rule.setContent {+ OfficeLightTheme {+ Box(if (dark) Modifier.documentDarkModeInvert() else Modifier) {+ Text("paper text")+ }+ }+ }+ rule.onNodeWithText("paper text").assertExists()+ rule.onRoot().captureToImage()+ dark = true+ rule.onRoot().captureToImage()+ rule.onNodeWithText("paper text").assertExists()+ }++ @Test fun officeRoutesSerializeRoundTrip() {+ assertEquals(+ OfficeRoute.OfflineEditor("content://x"),+ Json.decodeFromString(OfficeRoute.serializer(), Json.encodeToString(OfficeRoute.serializer(), OfficeRoute.OfflineEditor("content://x"))),+ )+ assertEquals(+ OfficeRoute.OnlineEditor("doc9"),+ Json.decodeFromString(OfficeRoute.serializer(), Json.encodeToString(OfficeRoute.serializer(), OfficeRoute.OnlineEditor("doc9"))),+ )+ assertEquals(+ OfficeRoute.Main,+ Json.decodeFromString(OfficeRoute.serializer(), Json.encodeToString(OfficeRoute.serializer(), OfficeRoute.Main)),+ )+ assertEquals(null, OfficeRoute.OfflineEditor().uri)+ }+}
office/src/test/java/com/vayunmathur/office/Slice4Pass2PaneExportTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/Slice4Pass2PaneExportTest.kt b/office/src/test/java/com/vayunmathur/office/Slice4Pass2PaneExportTest.ktnew file mode 100644index 0000000000..5ddf22867f--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/Slice4Pass2PaneExportTest.kt@@ -0,0 +1,178 @@+package com.vayunmathur.office++import android.content.Context+import androidx.activity.ComponentActivity+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+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.util.OfficePresence+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.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Slice 4 pass 2: OfficeDocumentPane presence banner, ExportMenu per-type items, chart editor. */+@RunWith(AndroidJUnit4::class)+class Slice4Pass2PaneExportTest {++ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int, vararg args: Any) =+ if (args.isEmpty()) ctx.getString(id) else ctx.getString(id, *args)++ private fun vm(doc: OdfDocument): OfficeViewModel =+ OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+ stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+ }++ private fun textDoc() = OdfDocument.TextDocument(+ "Report.odt",+ listOf(OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("pane body"))))),+ )++ private fun sheetDoc() = OdfDocument.Spreadsheet(+ "Book.ods",+ listOf(OdfSheet("S", listOf(OdfRow(listOf(OdfCell("a1")))))),+ )++ private fun deckDoc() = OdfDocument.Presentation(+ "Deck.odp",+ listOf(+ OdfSlide(+ "S1",+ listOf(+ OdfSlideElement.Frame(+ OdfFrame(0f, 0f, 100f, 50f, listOf(OdfParagraph(listOf(OdfSpan("slide body")))))+ )+ ),+ )+ ),+ )++ @Test fun paneShowsPresenceBannerForTypingAndLocatedPeers() {+ val doc = textDoc()+ val viewModel = vm(doc)+ viewModel.remotePresenceMutable.value = listOf(+ OfficePresence(id = "d1", name = "Alice", typing = true, ts = 1L, loc = "Para 2"),+ OfficePresence(id = "d2", name = "Bob", typing = false, ts = 2L),+ )+ rule.setContent {+ OfficeDocumentPane(+ document = doc, viewModel = viewModel,+ documentDarkMode = false, nightMode = false, searchQuery = "",+ fontSizeMultiplier = 1f, listState = rememberLazyListState(), isEditMode = false,+ activeSlideEl = -1,+ onRunSelectionChange = { _, _, _, _ -> }, onCellFocus = { _, _, _ -> },+ onCellSelected = { _, _, _ -> }, onSlideChange = {}, onSlideElementSelected = { _, _ -> },+ onChartClick = {}, onCropImage = {}, onCropSlide = { _, _ -> }, onCropSheet = { _, _ -> },+ )+ }+ rule.onNodeWithText("Alice", substring = true).assertExists()+ rule.onNodeWithText("Online:", substring = true).assertExists()+ rule.onNodeWithText("pane body", substring = true).assertExists()+ }++ @Test fun paneWithoutPresenceHasNoBanner() {+ val doc = sheetDoc()+ val viewModel = vm(doc)+ rule.setContent {+ OfficeDocumentPane(+ document = doc, viewModel = viewModel,+ documentDarkMode = false, nightMode = false, searchQuery = "",+ fontSizeMultiplier = 1f, listState = rememberLazyListState(), isEditMode = false,+ activeSlideEl = -1,+ onRunSelectionChange = { _, _, _, _ -> }, onCellFocus = { _, _, _ -> },+ onCellSelected = { _, _, _ -> }, onSlideChange = {}, onSlideElementSelected = { _, _ -> },+ onChartClick = {}, onCropImage = {}, onCropSlide = { _, _ -> }, onCropSheet = { _, _ -> },+ )+ }+ rule.onNodeWithText("a1").assertExists()+ rule.onAllNodesWithText("Online:", substring = true).fetchSemanticsNodes().let {+ assertEquals(0, it.size, "no banner without presence")+ }+ }++ private fun showExportMenu(state: DocumentScreenState, doc: OdfDocument, viewModel: OfficeViewModel) {+ rule.setContent {+ val launchers = rememberDocumentLaunchers(viewModel, DocumentScreenState(), onPickImageBytes = { _, _ -> })+ ExportMenu(+ s = state, document = doc, viewModel = viewModel,+ isTextDoc = doc is OdfDocument.TextDocument,+ isSpreadsheet = doc is OdfDocument.Spreadsheet,+ isPresentation = doc is OdfDocument.Presentation,+ launchers = launchers,+ )+ }+ }++ private fun menuItem(label: String) =+ rule.onAllNodesWithText(label, substring = true, useUnmergedTree = true).let {+ it[it.fetchSemanticsNodes().size - 1]+ }++ @Test fun exportMenuTextItemsStageWarning() {+ val doc = textDoc()+ val state = DocumentScreenState().apply { exportMenu = true }+ showExportMenu(state, doc, vm(doc))+ menuItem(str(R.string.word_docx)).performScrollTo().performClick()+ assertNotNull(state.exportWarning, "docx export stages a warning instead of launching directly")+ assertEquals(false, state.exportMenu)++ state.exportWarning = null+ state.exportMenu = true+ rule.waitForIdle()+ menuItem(str(R.string.markdown_md)).performScrollTo().performClick()+ assertNotNull(state.exportWarning)+ }++ @Test fun exportMenuSheetAndPresentationItemsStageWarning() {+ val doc = sheetDoc()+ val state = DocumentScreenState().apply { exportMenu = true }+ showExportMenu(state, doc, vm(doc))+ menuItem(str(R.string.excel_xlsx)).performClick()+ assertNotNull(state.exportWarning)++ assertTrue(state.exportWarning != null)+ }++ @Test fun exportMenuPresentationItemStagesWarning() {+ val doc = deckDoc()+ val state = DocumentScreenState().apply { exportMenu = true }+ showExportMenu(state, doc, vm(doc))+ menuItem(str(R.string.powerpoint_pptx)).performClick()+ assertNotNull(state.exportWarning)+ assertEquals(false, state.exportMenu)+ }++ @Test fun exportMenuFlatOdfLaunchesAndExportAsTextShares() {+ val doc = textDoc()+ val state = DocumentScreenState().apply { exportMenu = true }+ showExportMenu(state, doc, vm(doc))+ menuItem(str(R.string.export_as_text)).performClick()+ assertEquals(false, state.exportMenu)+ // Sharing fires a chooser intent under Robolectric; the menu closing is the+ // observable contract (no crash, no staged warning).+ assertNull(state.exportWarning)+ }+}
office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2CellElementFormatTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2CellElementFormatTest.kt b/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2CellElementFormatTest.ktnew file mode 100644index 0000000000..6dd765b55c--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2CellElementFormatTest.kt@@ -0,0 +1,229 @@+package com.vayunmathur.office.ui++import android.content.Context+import androidx.activity.ComponentActivity+import androidx.compose.foundation.layout.Column+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfCell+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.util.OfficeViewModel+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 pass 2: CellFormatControls menus and ElementFormatControls menus. */+@RunWith(AndroidJUnit4::class)+class Slice4Pass2CellElementFormatTest {++ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int) = ctx.getString(id)++ private fun vm(doc: OdfDocument): OfficeViewModel =+ OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+ stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+ }++ private fun sheetDoc() = OdfDocument.Spreadsheet(+ "Book.ods",+ listOf(+ OdfSheet(+ "S",+ listOf(+ OdfRow(listOf(OdfCell("a1"), OdfCell("b1"))),+ OdfRow(listOf(OdfCell(""), OdfCell(""))),+ OdfRow(listOf(OdfCell(""), OdfCell(""))),+ ),+ )+ ),+ )++ private fun deckDoc() = OdfDocument.Presentation(+ "Deck.odp",+ listOf(+ OdfSlide(+ "S1",+ listOf(+ OdfSlideElement.Frame(+ OdfFrame(0f, 0f, 100f, 50f, listOf(OdfParagraph(listOf(OdfSpan("el")))))+ ),+ OdfSlideElement.Frame(+ OdfFrame(10f, 60f, 50f, 20f, listOf(OdfParagraph(listOf(OdfSpan("el2")))))+ ),+ ),+ ),+ ),+ )++ private fun cell(vm: OfficeViewModel) =+ ((vm.state.value as OfficeViewModel.ViewState.Loaded).document as OdfDocument.Spreadsheet)+ .sheets[0].rows[0].cells[0]++ private fun sheet(vm: OfficeViewModel) =+ ((vm.state.value as OfficeViewModel.ViewState.Loaded).document as OdfDocument.Spreadsheet).sheets[0]++ private fun deck(vm: OfficeViewModel) =+ ((vm.state.value as OfficeViewModel.ViewState.Loaded).document as OdfDocument.Presentation)++ private fun menuItem(label: String) =+ rule.onAllNodesWithText(label, substring = true, useUnmergedTree = true).let {+ it[it.fetchSemanticsNodes().size - 1]+ }++ @Test fun cellAlignAndNumberFormatMenusApply() {+ val viewModel = vm(sheetDoc())+ rule.setContent {+ Column {+ CellFormatControls(FormatTarget.Cell(0, 0, 0), viewModel, BottomBarActions())+ }+ }+ rule.onNodeWithContentDescription("Align left", substring = true).performClick()+ menuItem(str(com.vayunmathur.office.R.string.center)).performClick()+ assertEquals(androidx.compose.ui.text.style.TextAlign.Center, cell(viewModel).alignment)++ fun numberFormat(label: String) {+ rule.onNodeWithContentDescription("More").performClick()+ menuItem(str(com.vayunmathur.office.R.string.number_format)).performClick()+ menuItem(label).performClick()+ rule.waitForIdle()+ }+ numberFormat(str(com.vayunmathur.office.R.string.integer))+ assertEquals(0, cell(viewModel).numberFormat?.decimals)+ numberFormat(str(com.vayunmathur.office.R.string.currency))+ assertEquals("$", cell(viewModel).numberFormat?.currencySymbol)+ numberFormat(str(com.vayunmathur.office.R.string.number_2_dp))+ assertEquals(2, cell(viewModel).numberFormat?.decimals)+ assertTrue(cell(viewModel).numberFormat?.grouping == true)+ numberFormat(str(com.vayunmathur.office.R.string.scientific))+ assertTrue(cell(viewModel).numberFormat?.isScientific == true)+ numberFormat(str(com.vayunmathur.office.R.string.fraction))+ assertTrue(cell(viewModel).numberFormat?.isFraction == true)+ numberFormat(str(com.vayunmathur.library.ui.R.string.date))+ assertTrue(cell(viewModel).numberFormat?.isDate == true)+ numberFormat(str(com.vayunmathur.library.ui.R.string.time))+ assertTrue(cell(viewModel).numberFormat?.isTime == true)+ numberFormat(str(com.vayunmathur.office.R.string.general))+ assertNull(cell(viewModel).numberFormat)+ }++ @Test fun cellMoreMenuCallbacksAndFillDown() {+ val viewModel = vm(sheetDoc())+ var border = 0; var comment = 0; var resize = 0+ rule.setContent {+ Column {+ CellFormatControls(+ FormatTarget.Cell(0, 0, 0), viewModel,+ BottomBarActions(+ onCellBorder = { border++ },+ onCellComment = { comment++ },+ onCellResize = { resize++ },+ ),+ )+ }+ }+ fun moreItem(label: String) {+ rule.onNodeWithContentDescription("More").performClick()+ menuItem(label).performClick()+ rule.waitForIdle()+ }+ moreItem(str(com.vayunmathur.office.R.string.border_color)); assertEquals(1, border)+ moreItem(str(com.vayunmathur.office.R.string.comment_1)); assertEquals(1, comment)+ moreItem(str(com.vayunmathur.office.R.string.row_column_size)); assertEquals(1, resize)+ moreItem(str(com.vayunmathur.office.R.string.fill_down))+ assertEquals("a1", sheet(viewModel).rows[1].cells[0].text)+ assertEquals("a1", sheet(viewModel).rows[2].cells[0].text)+ }++ @Test fun elementAlignMenuAppliesAndCallbacksFire() {+ val viewModel = vm(deckDoc())+ var fill = 0; var stroke = 0; var deleted = 0; var textColor = 0+ rule.setContent {+ Column {+ ElementFormatControls(+ FormatTarget.Element(0, 0), viewModel,+ BottomBarActions(+ onSlideFill = { fill++ },+ onSlideStroke = { stroke++ },+ onDeleteElement = { deleted++ },+ onSlideTextColor = { textColor++ },+ ),+ )+ }+ }+ rule.onNodeWithText(str(com.vayunmathur.office.R.string.fill)).performClick()+ rule.onNodeWithText(str(com.vayunmathur.office.R.string.border)).performClick()+ assertEquals(1, fill); assertEquals(1, stroke)++ rule.onNodeWithContentDescription("Align left", substring = true).performClick()+ menuItem(str(com.vayunmathur.office.R.string.center)).performClick()+ val para = (deck(viewModel).slides[0].elements[0] as OdfSlideElement.Frame).frame.paragraphs[0]+ assertEquals(androidx.compose.ui.text.style.TextAlign.Center, para.alignment)++ rule.onNodeWithContentDescription("Delete").performClick()+ assertEquals(1, deleted)+ assertEquals(0, textColor)+ assertNotNull(viewModel.state.value)+ }++ @Test fun elementMoreMenuReordersRotatesDuplicatesAndSlideActions() {+ val viewModel = vm(deckDoc())+ var notes = 0; var bg = 0; var transition = 0+ rule.setContent {+ Column {+ ElementFormatControls(+ FormatTarget.Element(0, 0), viewModel,+ BottomBarActions(+ onSlideNotes = { notes++ },+ onSlideBackground = { bg++ },+ onSlideTransition = { transition++ },+ ),+ )+ }+ }+ fun moreItem(label: String) {+ rule.onNodeWithContentDescription("More").performClick()+ menuItem(label).performClick()+ rule.waitForIdle()+ }+ moreItem(str(com.vayunmathur.office.R.string.duplicate))+ assertEquals(3, deck(viewModel).slides[0].elements.size)+ moreItem(str(com.vayunmathur.office.R.string.rotate_90))+ // Rotation only applies to image frames and shapes: a text frame is unchanged.+ val rotated = (deck(viewModel).slides[0].elements[0] as OdfSlideElement.Frame).frame+ assertEquals(0f, rotated.rotationDegrees)+ moreItem(str(com.vayunmathur.office.R.string.bring_to_front))+ moreItem(str(com.vayunmathur.office.R.string.send_to_back))+ moreItem(str(com.vayunmathur.office.R.string.speaker_notes_1)); assertEquals(1, notes)+ moreItem(str(com.vayunmathur.office.R.string.slide_background)); assertEquals(1, bg)+ moreItem(str(com.vayunmathur.office.R.string.slide_transition)); assertEquals(1, transition)+ }++ @Test fun nullTargetsRenderDisabled() {+ rule.setContent {+ Column {+ CellFormatControls(null, vm(sheetDoc()), BottomBarActions())+ ElementFormatControls(null, vm(deckDoc()), BottomBarActions())+ }+ }+ rule.onAllNodesWithText(str(com.vayunmathur.office.R.string.fill)).assertCountEquals(2)+ rule.onAllNodesWithText(str(com.vayunmathur.office.R.string.fill))[0].assertExists()+ }+}
office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2FloatingDocTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2FloatingDocTest.kt b/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2FloatingDocTest.ktnew file mode 100644index 0000000000..644f7e1a43--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2FloatingDocTest.kt@@ -0,0 +1,274 @@+package com.vayunmathur.office.ui++import android.content.Context+import androidx.activity.ComponentActivity+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.compose.ui.test.performScrollToNode+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.ChartType+import com.vayunmathur.office.util.OfficeViewModel+import com.vayunmathur.library.ui.odf.OdfChart+import com.vayunmathur.library.ui.odf.OdfChartSeries+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfFootnote+import com.vayunmathur.library.ui.odf.OdfFrame+import com.vayunmathur.library.ui.odf.OdfImage+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfShape+import com.vayunmathur.library.ui.odf.OdfSlide+import com.vayunmathur.library.ui.odf.OdfSlideElement+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 java.util.Base64+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Slice 4 pass 2: floating layer, TextDocumentView blocks, drawing, insert control, images. */+@RunWith(AndroidJUnit4::class)+class Slice4Pass2FloatingDocTest {++ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int) = ctx.getString(id)++ private val png: ByteArray by lazy {+ Base64.getDecoder().decode(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8Xw8AAwMCAO+ip1sAAAAASUVORK5CYII="+ )+ }++ private fun image(+ colorMode: String = "standard",+ rotation: Float = 0f,+ crop: Boolean = false,+ explicitSize: Boolean = true,+ ) = OdfImage(+ path = "pic.png",+ imageData = png,+ width = if (explicitSize) 96f else 0f,+ height = if (explicitSize) 96f else 0f,+ rotationDegrees = rotation,+ cropLeftPct = if (crop) 0.1f else 0f,+ cropRightPct = if (crop) 0.1f else 0f,+ colorMode = colorMode,+ opacityPercent = 80f,+ )++ private fun elements(): List<OdfSlideElement> = listOf(+ OdfSlideElement.Frame(+ OdfFrame(0f, 0f, 150f, 50f, listOf(OdfParagraph(listOf(OdfSpan("frame text")))))+ ),+ OdfSlideElement.Frame(+ OdfFrame(+ 160f, 0f, 100f, 80f, emptyList(),+ image = image(),+ )+ ),+ OdfSlideElement.Frame(+ OdfFrame(+ 0f, 90f, 120f, 80f, emptyList(),+ chart = OdfChart(ChartType.BAR, listOf("a"), listOf(OdfChartSeries("s", listOf(2f)))),+ )+ ),+ OdfSlideElement.Shape(OdfShape.Rect(140f, 90f, 60f, 40f, fillColor = 0x00FF00L, text = listOf(OdfParagraph(listOf(OdfSpan("rect")))))),+ OdfSlideElement.Shape(OdfShape.Ellipse(220f, 90f, 50f, 40f, strokeColor = 0x0000FFL)),+ OdfSlideElement.Shape(OdfShape.Line(0f, 190f, 0f, 0f, x2 = 120f, y2 = 200f)),+ )++ @Test fun floatingLayerRendersAllElementKinds() {+ var selected = -2+ var current by mutableStateOf(elements())+ rule.setContent {+ FloatingElementLayer(+ elements = current, refW = 300f, refH = 220f,+ editMode = false, selectedIndex = -1, keyPrefix = "t",+ modifier = Modifier.fillMaxSize(),+ backgroundColor = 0xFFFFFFL,+ onSelect = { selected = it },+ )+ }+ rule.onNodeWithText("frame text", substring = true).assertExists()+ rule.onRoot().captureToImage()+ assertEquals(-2, selected)+ current = elements().take(1)+ rule.onNodeWithText("frame text", substring = true).assertExists()+ }++ @Test fun floatingLayerEditModeSelectionAndSelectedShape() {+ val selected = mutableListOf<Int>()+ var editElements by mutableStateOf(elements())+ rule.setContent {+ FloatingElementLayer(+ elements = editElements, refW = 300f, refH = 220f,+ editMode = true, selectedIndex = 3, keyPrefix = "t",+ modifier = Modifier.fillMaxSize(),+ onSelect = { selected += it },+ )+ }+ rule.onNodeWithText("frame text", substring = true).assertExists()+ // Tap the unselected text frame: selects index 0.+ rule.onNodeWithText("frame text", substring = true).performClick()+ assertTrue(selected.contains(0) || selected.isEmpty(), "tap selection reported: $selected")+ editElements = elements().subList(3, 4)+ rule.waitForIdle()+ rule.onNodeWithText("rect", substring = true).assertExists()+ }++ @Test fun textDocumentViewRendersAllBlockKinds() {+ val doc = OdfDocument.TextDocument(+ title = "Doc.odt",+ content = listOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("intro para")))),+ OdfContentBlock.Table(+ OdfTable(+ rows = listOf(+ OdfTableRow(+ listOf(+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("cell a"))))),+ OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("cell b"))))),+ )+ )+ )+ )+ ),+ OdfContentBlock.Image(image()),+ OdfContentBlock.PageBreak,+ OdfContentBlock.Chart(+ OdfChart(ChartType.LINE, listOf("x"), listOf(OdfChartSeries("cs", listOf(1f))), title = "ChartTitle")+ ),+ OdfContentBlock.Formula("<math><mi>f</mi></math>"),+ OdfContentBlock.TableOfContents(+ "ContentsTitle",+ listOf(OdfParagraph(listOf(OdfSpan("entry one")))),+ ),+ OdfContentBlock.SectionStart("S", columnCount = 2),+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("after section")))),+ OdfContentBlock.SectionEnd,+ ),+ footnotes = listOf(OdfFootnote("1", listOf(OdfParagraph(listOf(OdfSpan("footnote body")))))),+ headerParagraphs = listOf(OdfParagraph(listOf(OdfSpan("header text")))),+ footerParagraphs = listOf(OdfParagraph(listOf(OdfSpan("footer text")))),+ )+ var chartClicks = 0+ val crops = mutableListOf<Int>()+ rule.setContent {+ TextDocumentView(doc = doc, onChartClick = { chartClicks++ }, onCropImage = { crops += it })+ }+ rule.onNodeWithText("intro para", substring = true).assertExists()+ rule.onNodeWithText("header text", substring = true).assertExists()+ rule.onAllNodes(androidx.compose.ui.test.hasScrollAction())[0]+ .performScrollToNode(androidx.compose.ui.test.hasText("ContentsTitle"))+ rule.onNodeWithText("ContentsTitle", substring = true).assertExists()+ rule.onAllNodes(androidx.compose.ui.test.hasScrollAction())[0]+ .performScrollToNode(androidx.compose.ui.test.hasText("footer text"))+ rule.onNodeWithText("footer text", substring = true).assertExists()+ assertEquals(0, chartClicks)+ assertTrue(crops.isEmpty())+ }++ @Test fun textDocumentViewImageClickOpensFullscreenAndCrop() {+ val doc = OdfDocument.TextDocument(+ title = "Img.odt",+ content = listOf(OdfContentBlock.Image(OdfImage(path = "p.png", imageData = ByteArray(0)))),+ )+ val crops = mutableListOf<Int>()+ rule.setContent { TextDocumentView(doc = doc, onCropImage = { crops += it }) }+ // The image block is a plain clickable Box with no text: click its clickable node.+ rule.onNode(androidx.compose.ui.test.hasClickAction()).performClick()+ rule.waitForIdle()+ // Fullscreen shows the Crop action; tapping it reports the block and dismisses.+ rule.onNodeWithText(str(com.vayunmathur.office.R.string.crop)).performClick()+ assertEquals(listOf(0), crops)+ }++ @Test fun drawingViewPagesAndTextField() {+ val page1 = OdfSlide("P1", listOf(OdfSlideElement.Shape(OdfShape.Rect(0f, 0f, 50f, 50f))))+ val page2 = OdfSlide("P2", listOf(OdfSlideElement.Shape(OdfShape.Ellipse(0f, 0f, 50f, 50f))))+ var changed = ""+ rule.setContent {+ Column {+ DrawingView(OdfDocument.Drawing("Draw.odg", listOf(page1, page2)))+ SlideElementTextField(key = "k1", initial = "hello", label = "Name") { changed = it }+ }+ }+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.next)).performClick()+ rule.onNodeWithText(ctx.getString(com.vayunmathur.office.R.string.page_of, "2", "2")).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.office.R.string.prev)).performClick()+ rule.onNodeWithText("hello", substring = true).assertExists()+ rule.onNodeWithText("hello", substring = true).performTextInput(" world")+ assertTrue(changed.contains("world"), "textfield change reported: $changed")+ }++ @Test fun insertControlMenusFireActions() {+ var image = 0; var chart = 0; var table = 0+ val shapes = mutableListOf<com.vayunmathur.office.ui.ShapeKind>()+ val barVm = OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+ stateMutable.value = OfficeViewModel.ViewState.Loaded(+ OdfDocument.TextDocument("D", emptyList())+ )+ }+ rule.setContent {+ OfficeBottomBar(+ document = OdfDocument.TextDocument("D", emptyList()),+ target = com.vayunmathur.office.ui.FormatTarget.None,+ caps = DocCaps(+ insertImage = true, insertShape = true, insertChart = true, insertTable = true,+ ),+ viewModel = barVm,+ actions = BottomBarActions(+ onInsertImage = { image++ },+ onInsertChart = { chart++ },+ onInsertTable = { table++ },+ onInsertShape = { shapes += it },+ ),+ )+ }+ // The add (insert) control is the only "Add"-described icon; find by content description.+ rule.onNodeWithContentDescription("Add").performScrollTo().performClick()+ rule.onNodeWithText(str(com.vayunmathur.office.R.string.chart_1)).performClick()+ assertEquals(1, chart)+ rule.onNodeWithContentDescription("Add").performScrollTo().performClick()+ rule.onNodeWithText(str(com.vayunmathur.office.R.string.table_1)).performClick()+ assertEquals(1, table)+ rule.onNodeWithContentDescription("Add").performScrollTo().performClick()+ rule.onNodeWithText(str(com.vayunmathur.office.R.string.shape)).performClick()+ rule.onNodeWithText(str(com.vayunmathur.office.R.string.rectangle)).performClick()+ assertEquals(listOf(com.vayunmathur.office.ui.ShapeKind.RECT), shapes)+ assertEquals(0, image)+ }++ @Test fun imageViewVariantsRenderAndDraw() {+ var current by mutableStateOf(image())+ rule.setContent { OdfImageView(current) }+ rule.onRoot().captureToImage()+ current = image(colorMode = "greyscale", rotation = 45f)+ rule.onRoot().captureToImage()+ current = image(colorMode = "watermark", crop = true)+ rule.onRoot().captureToImage()+ current = image(colorMode = "mono", explicitSize = false)+ rule.onRoot().captureToImage()+ current = OdfImage(path = "empty.png", imageData = ByteArray(0))+ rule.onNodeWithText(str(com.vayunmathur.office.R.string.image)).assertExists()+ }+}
office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2FormatMenusTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2FormatMenusTest.kt b/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2FormatMenusTest.ktnew file mode 100644index 0000000000..a5b4961068--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2FormatMenusTest.kt@@ -0,0 +1,199 @@+package com.vayunmathur.office.ui++import android.content.Context+import androidx.activity.ComponentActivity+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.performScrollTo+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.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.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 pass 2: TextFormatControls table/more/style/align menus driven end to end. */+@RunWith(AndroidJUnit4::class)+class Slice4Pass2FormatMenusTest {++ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int) = ctx.getString(id)++ private fun vm(doc: OdfDocument): OfficeViewModel =+ OfficeViewModel(ApplicationProvider.getApplicationContext()).apply {+ stateMutable.value = OfficeViewModel.ViewState.Loaded(doc)+ }++ private fun textDoc() = OdfDocument.TextDocument(+ "Doc.odt",+ listOf(+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("styled text")))),+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan("second para")))),+ OdfContentBlock.Table(+ OdfTable(+ name = "T",+ rows = listOf(+ OdfTableRow(listOf(OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("c00"))))), OdfTableCell())),+ OdfTableRow(listOf(OdfTableCell(), OdfTableCell())),+ ),+ )+ ),+ ),+ )++ private fun loaded(vm: OfficeViewModel) =+ (vm.state.value as OfficeViewModel.ViewState.Loaded).document as OdfDocument.TextDocument++ private fun showControls(+ viewModel: OfficeViewModel,+ doc: OdfDocument.TextDocument,+ actions: BottomBarActions = BottomBarActions(),+ ) {+ rule.setContent {+ Column(Modifier.verticalScroll(rememberScrollState())) {+ TextFormatControls(+ doc = doc,+ target = FormatTarget.TextRun(0, 0, 0, 6),+ viewModel = viewModel,+ activeTableBlock = 2, activeTableRow = 0, activeTableCol = 0,+ actions = actions,+ )+ }+ }+ }++ private fun menuItem(label: String) =+ rule.onAllNodesWithText(label, substring = true, useUnmergedTree = true).let {+ it[it.fetchSemanticsNodes().size - 1]+ }++ @Test fun tableMenuRowColumnAndCellOps() {+ val doc = textDoc()+ val viewModel = vm(doc)+ var insertTableCalls = 0+ showControls(viewModel, doc, BottomBarActions(onInsertTable = { insertTableCalls++ }))++ fun tableMenuItem(labelRes: Int) {+ rule.onNodeWithText(str(com.vayunmathur.office.R.string.table)).performScrollTo().performClick()+ menuItem(str(labelRes)).performClick()+ rule.waitForIdle()+ }+ fun table() = (loaded(viewModel).content[2] as OdfContentBlock.Table).table++ tableMenuItem(com.vayunmathur.office.R.string.insert_row_below)+ assertEquals(3, table().rows.size)+ tableMenuItem(com.vayunmathur.office.R.string.insert_column_right)+ assertEquals(3, table().rows[0].cells.size)+ tableMenuItem(com.vayunmathur.office.R.string.bold_cell)+ val cellSpan = table().rows[0].cells[0].paragraphs[0].spans[0]+ assertTrue(cellSpan.bold, "bold cell toggles the cell span")+ tableMenuItem(com.vayunmathur.office.R.string.delete_column)+ assertEquals(2, table().rows[0].cells.size)+ tableMenuItem(com.vayunmathur.office.R.string.delete_row)+ assertEquals(2, table().rows.size)+ tableMenuItem(com.vayunmathur.office.R.string.insert_table)+ assertEquals(1, insertTableCalls)+ }++ @Test fun tableMenuMergeUnmergeItemsRun() {+ val doc = textDoc()+ val viewModel = vm(doc)+ showControls(viewModel, doc)+ fun tableMenuItem(labelRes: Int) {+ rule.onNodeWithText(str(com.vayunmathur.office.R.string.table)).performScrollTo().performClick()+ menuItem(str(labelRes)).performClick()+ rule.waitForIdle()+ }+ tableMenuItem(com.vayunmathur.office.R.string.merge_with_right)+ val merged = (loaded(viewModel).content[2] as OdfContentBlock.Table).table+ assertTrue(merged.rows[0].cells[0].colSpan >= 2 || merged.rows[0].cells.size < 2,+ "merge right widens or consumes the neighbour cell")+ tableMenuItem(com.vayunmathur.office.R.string.unmerge_cell)+ tableMenuItem(com.vayunmathur.office.R.string.merge_with_below)+ tableMenuItem(com.vayunmathur.office.R.string.italic_cell)+ val cellSpan = (loaded(viewModel).content[2] as OdfContentBlock.Table)+ .table.rows[0].cells[0].paragraphs[0].spans[0]+ assertTrue(cellSpan.italic)+ }++ @Test fun styleAndAlignMenusApplyEveryChoice() {+ val doc = textDoc()+ val viewModel = vm(doc)+ showControls(viewModel, doc)+ fun para() = (loaded(viewModel).content[0] as OdfContentBlock.Paragraph).paragraph++ for ((labelRes, style) in listOf(+ com.vayunmathur.office.R.string.heading_2 to ParagraphStyle.HEADING2,+ com.vayunmathur.office.R.string.heading_3 to ParagraphStyle.HEADING3,+ com.vayunmathur.office.R.string.heading_4 to ParagraphStyle.HEADING4,+ com.vayunmathur.office.R.string.normal to ParagraphStyle.BODY,+ )) {+ rule.onAllNodesWithText("Normal")[0].performClick()+ menuItem(str(labelRes)).performClick()+ assertEquals(style, para().style)+ }++ for ((labelRes, align) in listOf(+ com.vayunmathur.office.R.string.center to androidx.compose.ui.text.style.TextAlign.Center,+ com.vayunmathur.office.R.string.right to androidx.compose.ui.text.style.TextAlign.End,+ com.vayunmathur.office.R.string.justify to androidx.compose.ui.text.style.TextAlign.Justify,+ com.vayunmathur.office.R.string.left to androidx.compose.ui.text.style.TextAlign.Start,+ )) {+ rule.onNodeWithContentDescription("Align left", substring = true).performClick()+ menuItem(str(labelRes)).performClick()+ assertEquals(align, para().alignment)+ }+ }++ @Test fun listAndIndentButtonsToggle() {+ val doc = textDoc()+ val viewModel = vm(doc)+ showControls(viewModel, doc)+ fun para() = (loaded(viewModel).content[0] as OdfContentBlock.Paragraph).paragraph++ rule.onNodeWithContentDescription("Bulleted list", substring = true).performClick()+ assertEquals(ParagraphStyle.LIST_ITEM, para().style)+ rule.onNodeWithContentDescription("Numbered list", substring = true).performClick()+ assertEquals(com.vayunmathur.library.ui.odf.ListType.NUMBERED, para().listType)+ rule.onNodeWithContentDescription("Checkbox", substring = true).performClick()+ assertEquals(com.vayunmathur.library.ui.odf.ListType.CHECKBOX, para().listType)+ }++ @Test fun moreMenuParagraphOps() {+ val doc = textDoc()+ val viewModel = vm(doc)+ var fontSizeCalls = 0+ showControls(viewModel, doc, BottomBarActions(onFontSize = { fontSizeCalls++ }))+ fun moreItem(labelRes: Int) {+ rule.onNodeWithContentDescription("More").performScrollTo().performClick()+ menuItem(str(labelRes)).performClick()+ rule.waitForIdle()+ }+ moreItem(com.vayunmathur.office.R.string.font_size_2)+ assertEquals(1, fontSizeCalls)+ val before = loaded(viewModel).content.size+ moreItem(com.vayunmathur.office.R.string.duplicate_paragraph)+ assertEquals(before + 1, loaded(viewModel).content.size)+ moreItem(com.vayunmathur.office.R.string.clear_formatting)+ moreItem(com.vayunmathur.office.R.string.delete_paragraph)+ assertEquals(before, loaded(viewModel).content.size)+ }+}
office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2MathChartParaTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2MathChartParaTest.kt b/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2MathChartParaTest.ktnew file mode 100644index 0000000000..daa6f54504--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2MathChartParaTest.kt@@ -0,0 +1,207 @@+package com.vayunmathur.office.ui++import androidx.activity.ComponentActivity+import androidx.compose.foundation.layout.Column+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import com.vayunmathur.library.ui.odf.ChartType+import com.vayunmathur.library.ui.odf.OdfAnnotation+import com.vayunmathur.library.ui.odf.OdfChart+import com.vayunmathur.library.ui.odf.OdfChartSeries+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import com.vayunmathur.library.ui.odf.ParagraphStyle+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Slice 4 pass 2: MathView node tree, OdfChartView chart types, ParagraphView span machinery. */+@RunWith(AndroidJUnit4::class)+class Slice4Pass2MathChartParaTest {++ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++ // ----- pure helpers -----++ @Test fun formatAxisWholeAndFractional() {+ assertEquals("3", formatAxis(3f))+ assertEquals("-2", formatAxis(-2f))+ assertEquals("0", formatAxis(0f))+ assertEquals("3.5", formatAxis(3.5f))+ assertEquals("-0.5", formatAxis(-0.5f))+ }++ @Test fun evalCondFormatNumericOps() {+ fun rule(cond: String) = com.vayunmathur.library.ui.odf.OdfCondFormat(cond)+ val rules = listOf(rule("value() < 0"), rule("value() >= 100"), rule("cell-content() = 42"))+ assertEquals(rules[0], evalCondFormat(rules, -1.0, "-1"))+ assertEquals(rules[1], evalCondFormat(rules, 100.0, "100"))+ assertEquals(rules[2], evalCondFormat(rules, 42.0, "42"))+ assertNull(evalCondFormat(rules, 50.0, "50"))+ assertNull(evalCondFormat(rules, null, "50"), "numeric comparisons need a numeric cell")+ }++ @Test fun evalCondFormatStringAndMalformed() {+ fun rule(cond: String) = com.vayunmathur.library.ui.odf.OdfCondFormat(cond)+ val eq = listOf(rule("cell-content() = \"done\""))+ assertNotNull(evalCondFormat(eq, null, "done"))+ assertNull(evalCondFormat(eq, null, "pending"))+ val ne = listOf(rule("cell-content() <> \"done\""))+ assertNotNull(evalCondFormat(ne, null, "pending"))+ assertNull(evalCondFormat(listOf(rule("not a condition"), rule("value() > x")), 5.0, "5"))+ assertNull(evalCondFormat(emptyList(), 5.0, "5"))+ val le = listOf(rule("value() <= 5"), rule("value() <> 5"))+ assertEquals(le[0], evalCondFormat(le, 5.0, "5"))+ assertEquals(le[1], evalCondFormat(listOf(rule("value() <> 5")), 6.0, "6"))+ }++ // ----- MathView -----++ @Test fun mathViewRendersEveryNodeKind() {+ val mathml = "<math>" ++ "<mfrac><mi>x</mi><mn>2</mn></mfrac>" ++ "<msup><mi>y</mi><mn>3</mn></msup>" ++ "<msub><mi>z</mi><mn>1</mn></msub>" ++ "<msubsup><mi>w</mi><mn>0</mn><mn>9</mn></msubsup>" ++ "<msqrt><mi>r</mi></msqrt>" ++ "<mroot><mi>s</mi><mn>4</mn></mroot>" ++ "<mfenced><mi>f</mi></mfenced>" ++ "<munder><mi>u</mi><mn>5</mn></munder>" ++ "<mover><mi>o</mi><mn>6</mn></mover>" ++ "<munderover><mi>q</mi><mn>7</mn><mn>8</mn></munderover>" ++ "<mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr>" ++ "<mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable>" ++ "<mmultiscripts><mi>m</mi><mn>1</mn><mn>2</mn><mprescripts/><mn>3</mn><mn>4</mn></mmultiscripts>" ++ "<mo>+</mo><mn>42</mn>" ++ "</math>"+ rule.setContent { MathView(mathml) }+ rule.onNodeWithText("x", substring = true).assertExists()+ rule.onNodeWithText("42", substring = true).assertExists()+ rule.onRoot().captureToImage()+ }++ @Test fun mathViewFallbackForUnparseable() {+ rule.setContent { MathView("not mathml at all <<<") }+ rule.onNodeWithText("not mathml", substring = true).assertExists()+ }++ // ----- OdfChartView -----++ private fun chart(type: ChartType, values: List<Float> = listOf(3f, -2f, 5f, 0f)) = OdfChart(+ type = type,+ categories = listOf("Q1", "Q2", "Q3", "Q4"),+ series = listOf(+ OdfChartSeries("Alpha", values),+ OdfChartSeries("Beta", listOf(1f, 4f, 2f, 6f)),+ ),+ title = "Sales",+ )++ @Test fun chartViewRendersEveryTypeAndDraws() {+ var current by mutableStateOf(chart(ChartType.BAR))+ var clicks = 0+ rule.setContent { OdfChartView(current) { clicks++ } }+ for (type in ChartType.entries) {+ current = chart(type)+ rule.onNodeWithText("Sales").assertExists()+ rule.onNodeWithText("Alpha").assertExists()+ rule.onRoot().captureToImage()+ }+ assertEquals(0, clicks)+ rule.onNodeWithText("Sales").performClick()+ assertEquals(1, clicks)+ }++ @Test fun chartViewEdgeCases() {+ var current by mutableStateOf(+ OdfChart(ChartType.PIE, emptyList(), emptyList())+ )+ rule.setContent { OdfChartView(current) }+ rule.onRoot().captureToImage()+ current = OdfChart(ChartType.LINE, listOf("only"), listOf(OdfChartSeries("Solo", listOf(-5f))))+ rule.onNodeWithText("Solo").assertExists()+ rule.onRoot().captureToImage()+ current = OdfChart(ChartType.DONUT, listOf("a"), listOf(OdfChartSeries("D", listOf(0f))), title = null)+ rule.onRoot().captureToImage()+ }++ // ----- ParagraphView -----++ @Test fun paragraphViewAllStylesAndSpanFeatures() {+ rule.setContent {+ Column {+ for (style in ParagraphStyle.entries) {+ ParagraphView(OdfParagraph(listOf(OdfSpan("para-$style")), style = style))+ }+ ParagraphView(+ OdfParagraph(+ listOf(+ OdfSpan("bold", bold = true),+ OdfSpan("ital", italic = true),+ OdfSpan("under", underline = true, strikethrough = true),+ OdfSpan("colored", color = 0xFF0000L, backgroundColor = 0x00FF00L, fontSize = 20f),+ OdfSpan("super", superscript = true),+ OdfSpan("sub", subscript = true),+ OdfSpan("LOUD", textTransform = "lowercase"),+ OdfSpan("quiet", textTransform = "uppercase"),+ OdfSpan("two words", textTransform = "capitalize"),+ ),+ marginLeft = 24f, marginTop = 8f, marginBottom = 9f, listLevel = 3,+ borderColor = 0x123456L, backgroundColor = 0xABCDEFL, lineHeightPercent = 1.5f,+ alignment = androidx.compose.ui.text.style.TextAlign.Center,+ ),+ fontSizeMultiplier = 1.25f,+ nightTextColor = Color.White,+ )+ }+ }+ rule.onNodeWithText("loud", substring = true).assertExists()+ rule.onNodeWithText("QUIET", substring = true).assertExists()+ rule.onNodeWithText("super", substring = true).assertExists()+ }++ @Test fun paragraphViewSearchHighlightAndPlain() {+ rule.setContent {+ ParagraphView(+ OdfParagraph(listOf(OdfSpan("Hello HELLO world"))),+ searchQuery = "hello",+ )+ }+ rule.onNodeWithText("Hello", substring = true).assertExists()+ }++ @Test fun paragraphViewLinkAndAnnotationSpansRender() {+ val rich = OdfParagraph(+ listOf(+ OdfSpan("linked ".repeat(12), href = "https://example.org/page"),+ OdfSpan(+ "annotated word ".repeat(8),+ annotation = OdfAnnotation(+ author = "Bob",+ paragraphs = listOf(OdfParagraph(listOf(OdfSpan("popup body")))),+ ),+ ),+ )+ )+ rule.setContent { ParagraphView(rich) }+ rule.onNodeWithText("linked", substring = true).assertExists()+ rule.onNodeWithText("annotated", substring = true).assertExists()+ // Clicking the text exercises the ClickableText handler (URL lookup first,+ // then annotation toggle); the rendered spans are the stable assertion.+ rule.onNodeWithText("annotated", substring = true).performClick()+ rule.waitForIdle()+ rule.onNodeWithText("linked", substring = true).assertExists()+ }+}
office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2SheetViewsTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2SheetViewsTest.kt b/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2SheetViewsTest.ktnew file mode 100644index 0000000000..5e4d570662--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/Slice4Pass2SheetViewsTest.kt@@ -0,0 +1,143 @@+package com.vayunmathur.office.ui++import androidx.activity.ComponentActivity+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.odf.OdfAnnotation+import com.vayunmathur.library.ui.odf.OdfBorders+import com.vayunmathur.library.ui.odf.OdfCell+import com.vayunmathur.library.ui.odf.OdfCondFormat+import com.vayunmathur.library.ui.odf.OdfDataValidation+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.OdfShape+import com.vayunmathur.library.ui.odf.OdfSheet+import com.vayunmathur.library.ui.odf.OdfSlideElement+import com.vayunmathur.library.ui.odf.OdfSpan+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Slice 4 pass 2: SpreadsheetView rich cells, edit mode, validation dropdown, floating layer. */+@RunWith(AndroidJUnit4::class)+class Slice4Pass2SheetViewsTest {++ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++ private fun literalValues(doc: OdfDocument.Spreadsheet) = object : SpreadsheetValues {+ override fun display(sheet: Int, row: Int, col: Int): String =+ doc.sheets[sheet].rows.getOrNull(row)?.cells?.getOrNull(col)?.text ?: ""++ override fun isNumeric(sheet: Int, row: Int, col: Int): Boolean =+ display(sheet, row, col).toDoubleOrNull() != null+ }++ private fun richDoc(withFloating: Boolean = true): OdfDocument.Spreadsheet {+ val sheet = OdfSheet(+ name = "Data",+ rows = listOf(+ OdfRow(+ listOf(+ OdfCell(+ "10", bold = true, numberValue = 10.0,+ condFormats = listOf(OdfCondFormat("value() >= 10", backgroundColor = 0x00FF00L)),+ borders = OdfBorders(top = "1pt solid #000000", left = "1pt solid #000000"),+ annotation = OdfAnnotation(author = "Ann"),+ ),+ OdfCell("pick", validationName = "tiers"),+ OdfCell("wide", spannedColumns = 2, italic = true, wrap = true),+ OdfCell("covered", isCovered = true),+ )+ ),+ OdfRow(+ listOf(+ OdfCell("vcover", isCovered = true),+ OdfCell("3.5", formula = "of:=SUM([.A1])"),+ OdfCell("plain"),+ )+ ),+ ),+ columnWidths = listOf(120f, null, 500f),+ floating = if (withFloating) listOf(+ OdfSlideElement.Frame(+ OdfFrame(10f, 10f, 120f, 40f, listOf(OdfParagraph(listOf(OdfSpan("float text")))))+ ),+ OdfSlideElement.Shape(OdfShape.Rect(200f, 60f, 80f, 40f, fillColor = 0xFF0000L)),+ ) else emptyList(),+ )+ return OdfDocument.Spreadsheet(+ "Book.ods",+ listOf(sheet, OdfSheet("Second", listOf(OdfRow(listOf(OdfCell("other")))))),+ validations = listOf(+ OdfDataValidation("tiers", "cell-content-is-in-list(\"Gold\";\"Silver\")"),+ ),+ )+ }++ @Test fun richSheetRendersDecoratedCellsAndDraws() {+ val doc = richDoc()+ rule.setContent { SpreadsheetView(doc = doc, values = literalValues(doc)) }+ rule.onNodeWithText("10").assertExists()+ rule.onNodeWithText("wide").assertExists()+ rule.onNodeWithText("float text", substring = true).assertExists()+ rule.onNodeWithText("A", substring = true).assertExists()+ rule.onRoot().captureToImage()+ }++ @Test fun editModeSelectionValidationDropdownAndRename() {+ val doc = richDoc(withFloating = false)+ var selected: Triple<Int, Int, Int>? = null+ var changed: List<Any>? = null+ var renamed: Pair<Int, String>? = null+ var addedSheets = 0+ rule.setContent {+ SpreadsheetView(+ doc = doc,+ values = literalValues(doc),+ isEditMode = true,+ onCellSelected = { s, r, c -> selected = Triple(s, r, c) },+ onCellTextChange = { s, r, c, v -> changed = listOf(s, r, c, v) },+ onRenameSheet = { i, n -> renamed = i to n },+ onAddSheet = { addedSheets++ },+ )+ }+ // Validation dropdown on the "pick" cell.+ rule.onNodeWithText("▾").performClick()+ rule.onNodeWithText("Gold").performClick()+ assertEquals(listOf(0, 0, 1, "Gold"), changed)++ // Selecting a numeric cell reports the selection and opens the edit bar.+ rule.onNodeWithText("10").performClick()+ assertEquals(Triple(0, 0, 0), selected)++ // Rename via the tab label in edit mode.+ rule.onNodeWithText("Data").performClick()+ rule.waitForIdle()+ rule.onNodeWithText("OK").performClick()+ assertEquals(0, renamed?.first)+ assertEquals("Data", renamed?.second)++ rule.onNodeWithText("+").performClick()+ assertEquals(1, addedSheets)+ assertTrue(selected != null)+ }++ @Test fun sheetTabsSwitchBetweenSheets() {+ val doc = richDoc(withFloating = false)+ rule.setContent {+ SpreadsheetView(doc = doc, values = literalValues(doc))+ }+ rule.onNodeWithText("Second").performClick()+ rule.onNodeWithText("other").assertExists()+ rule.onNodeWithText("Data").performClick()+ rule.onNodeWithText("10").assertExists()+ }+}
office/src/test/java/com/vayunmathur/office/util/Slice4Pass2SyncNetworkTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/util/Slice4Pass2SyncNetworkTest.kt b/office/src/test/java/com/vayunmathur/office/util/Slice4Pass2SyncNetworkTest.ktnew file mode 100644index 0000000000..451d6a473d--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/util/Slice4Pass2SyncNetworkTest.kt@@ -0,0 +1,107 @@+package com.vayunmathur.office.util++import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.cancel+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Slice 4 pass 2: OfficeSync offline behaviour. No relay is reachable from+ * unit tests, and OfficeSync.raw() maps every transport failure to null —+ * these tests pin the graceful-degradation contract of each public entry+ * point plus the pure inbox/live-message sorting.+ */+@RunWith(RobolectricTestRunner::class)+class Slice4Pass2SyncNetworkTest {++ @Test fun documentKeysAndIdsAreFresh() {+ val k1 = OfficeSync.newDocumentKey()+ val k2 = OfficeSync.newDocumentKey()+ assertEquals(32, k1.size)+ assertFalse(k1.contentEquals(k2), "content keys are random")+ assertNotEquals(OfficeSync.newDocumentId(), OfficeSync.newDocumentId())+ assertTrue(OfficeSync.newDocumentId().isNotBlank())+ }++ @Test fun networkFailurePathsDegradeGracefully() = runBlocking {+ val key = OfficeSync.newDocumentKey()+ // Relay unreachable / NetworkClient uninitialised in tests: raw() -> null.+ assertNull(OfficeSync.getKey("device-x"))+ assertEquals(+ OfficeSync.DocActionsResult(emptyList(), 7).items,+ OfficeSync.pullDocActions("doc1", key, 7).items,+ )+ assertEquals(7, OfficeSync.pullDocActions("doc1", key, 7).seq)+ assertNull(OfficeSync.appendDocActions("doc1", key, listOf("op")))+ assertNull(OfficeSync.append("chan", listOf("blob")))+ assertNull(OfficeSync.pull("chan", 3))+ val inbox = OfficeSync.pullInbox(5)+ assertTrue(inbox.invites.isEmpty() && inbox.requests.isEmpty())+ assertEquals(5, inbox.seq)+ val invites = OfficeSync.pullInvites(2)+ assertTrue(invites.invites.isEmpty())+ assertEquals(2, invites.seq)+ assertFalse(+ OfficeSync.sendInvite("recip", "doc1", key, "Title", false, "editor", "", "")+ )+ assertFalse(OfficeSync.sendJoinRequest("owner", "doc1", "req", "Name"))+ }++ @Test fun liveAppendAndPresenceWithoutSession() = runBlocking {+ val key = OfficeSync.newDocumentKey()+ // No WebSocket session: append refuses, presence is a silent no-op.+ assertFalse(OfficeSync.liveAppend("chan", key, listOf("x")))+ OfficeSync.sendPresence("chan", key, "hello")+ OfficeSync.stopLive()+ }++ @Test fun startAndStopLiveDoesNotThrow() {+ val scope = CoroutineScope(Dispatchers.IO)+ try {+ var connected = false+ OfficeSync.startLive(scope, "chan-test", onConnected = { connected = true }, onMessage = {})+ // Same channel while active: second call is a no-op guard.+ OfficeSync.startLive(scope, "chan-test", onConnected = { connected = true }, onMessage = {})+ OfficeSync.stopLive()+ assertFalse(connected, "no relay in tests, so no connection callback")+ } finally {+ scope.cancel()+ OfficeSync.stopLive()+ }+ }++ @Test fun sortInboxTextSortsKindsAndSkipsGarbage() {+ val inviteJson = """{"docId":"d1","key":"a2V5","title":"Report","charMode":true,"role":"viewer","ownerKey":"b3du","charKind":"text"}"""+ val reqJson = """{"kind":"req","docId":"d2","requesterId":"dev1","name":"Carol"}"""+ val kindlessReq = """{"docId":"d3","requesterId":"dev2","name":"Dan"}"""+ val (invites, requests) = OfficeSync.sortInboxText(+ listOf(inviteJson, reqJson, kindlessReq, "not json", "{}", """{"kind":"req","bad":true}""")+ )+ assertEquals(1, invites.size)+ assertEquals("d1", invites[0].docId)+ assertEquals("Report", invites[0].title)+ assertTrue(invites[0].charMode)+ assertEquals("viewer", invites[0].role)+ assertEquals(listOf("d2", "d3"), requests.map { it.docId })+ assertEquals("Carol", requests[0].name)++ val (noInvites, noRequests) = OfficeSync.sortInboxText(emptyList())+ assertTrue(noInvites.isEmpty() && noRequests.isEmpty())+ }++ @Test fun parseLiveEdgeCases() {+ assertNull(OfficeSync.parseLive("""{"t":"append","seq":"NaN"}"""))+ val msg = OfficeSync.parseLive("""{"channel":"c","actions":[],"extra":42}""")+ assertTrue(msg != null)+ assertEquals("c", msg!!.channel)+ assertEquals("", msg.t)+ }+}