office: keyboard focus traversal for the document editor
- Commit
a100c3825f5616e353d056c397c5e073343e0f34- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 17:56 UTC (14 days ago)
- Parents
1e647f1
The editor was pointer-driven: no Tab handling, no visible focus. The root key handler now traverses in visual order (top bar and title, menu bar, body segments in document order, bottom toolbar) with Escape returning focus to the body - first paragraph run, or first table cell/image/chart. Stops carry a 2dp primary focus ring that costs no layout shift. Traversal is swallowed while a dialog or menu owns the keyboard (same overlay guard as the existing shortcuts); Ctrl/Alt+Tab stays with the OS. EditorBaseButtons keep their deliberate canFocus=false (IME preservation) - Bold/Italic remain on Ctrl/Meta+B/I. Verified: office 1089 tests pass incl. new traversal-order, Shift-Tab, Escape and suppression tests.
Diff
office/src/main/java/com/vayunmathur/office/ui/DocumentScaffoldBody.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/DocumentScaffoldBody.kt b/office/src/main/java/com/vayunmathur/office/ui/DocumentScaffoldBody.ktindex cd0a459d44..0793ef04f5 100644--- a/office/src/main/java/com/vayunmathur/office/ui/DocumentScaffoldBody.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/DocumentScaffoldBody.kt@@ -36,6 +36,7 @@ import com.vayunmathur.library.ui.ModalNavigationDrawer import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.isExpandedWidth+import androidx.compose.ui.focus.FocusRequester import com.vayunmathur.library.ui.odf.OdfDocument import com.vayunmathur.office.ui.OfficeEditorWideLayout import com.vayunmathur.office.platform.OfficeViewModel@@ -65,6 +66,8 @@ internal fun DocumentScaffoldBody( onSlideChange: (Int) -> Unit, onSlideElementSelected: (Int, Int) -> Unit, modifier: Modifier = Modifier,+ bodyFocusRequester: FocusRequester? = null,+ onBodyFocusChanged: (Boolean) -> Unit = {}, ) { Column(Modifier.fillMaxSize().padding(contentPadding)) { ScaffoldMenuBars(@@ -86,6 +89,8 @@ internal fun DocumentScaffoldBody( onSlideChange = onSlideChange, onSlideElementSelected = onSlideElementSelected, modifier = modifier,+ bodyFocusRequester = bodyFocusRequester,+ onBodyFocusChanged = onBodyFocusChanged, ) } }@@ -154,6 +159,8 @@ internal fun DocumentEditorPane( onSlideChange: (Int) -> Unit, onSlideElementSelected: (Int, Int) -> Unit, modifier: Modifier = Modifier,+ bodyFocusRequester: FocusRequester? = null,+ onBodyFocusChanged: (Boolean) -> Unit = {}, ) { Column(modifier) { val showOutline = isExpandedWidth() && chrome.isTextDoc &&@@ -173,7 +180,9 @@ internal fun DocumentEditorPane( listState = listState, onRunSelectionChange = onRunSelectionChange, onCellFocus = onCellFocus, onCellSelected = onCellSelected, onSlideChange = onSlideChange, onSlideElementSelected = onSlideElementSelected,- modifier = Modifier.fillMaxSize())+ modifier = Modifier.fillMaxSize(),+ bodyFocusRequester = bodyFocusRequester,+ onBodyFocusChanged = onBodyFocusChanged) }, ) } else {@@ -182,7 +191,9 @@ internal fun DocumentEditorPane( listState = listState, onRunSelectionChange = onRunSelectionChange, onCellFocus = onCellFocus, onCellSelected = onCellSelected, onSlideChange = onSlideChange, onSlideElementSelected = onSlideElementSelected,- modifier = Modifier.fillMaxSize())+ modifier = Modifier.fillMaxSize(),+ bodyFocusRequester = bodyFocusRequester,+ onBodyFocusChanged = onBodyFocusChanged) } } }@@ -201,6 +212,8 @@ internal fun EditorDocumentPane( onSlideChange: (Int) -> Unit, onSlideElementSelected: (Int, Int) -> Unit, modifier: Modifier = Modifier,+ bodyFocusRequester: FocusRequester? = null,+ onBodyFocusChanged: (Boolean) -> Unit = {}, ) { val activeSlideEl by s.activeSlideElState OfficeDocumentPane(@@ -223,6 +236,8 @@ internal fun EditorDocumentPane( onCropSlide = { si, e -> s.cropSlideTarget = si to e }, onCropSheet = { si, e -> s.cropSheetTarget = si to e }, modifier = modifier,+ bodyFocusRequester = bodyFocusRequester,+ onBodyFocusChanged = onBodyFocusChanged, ) }
office/src/main/java/com/vayunmathur/office/ui/DocumentScaffoldShell.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/DocumentScaffoldShell.kt b/office/src/main/java/com/vayunmathur/office/ui/DocumentScaffoldShell.ktindex 49bd125a0d..8eb4019411 100644--- a/office/src/main/java/com/vayunmathur/office/ui/DocumentScaffoldShell.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/DocumentScaffoldShell.kt@@ -17,7 +17,12 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember import androidx.compose.ui.Modifier+import androidx.compose.foundation.focusable+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp@@ -67,13 +72,25 @@ internal fun DocumentScaffoldShell( onSlideChange: (Int) -> Unit, onSlideElementSelected: (Int, Int) -> Unit, onBack: () -> Unit,+ bodyFocusRequester: FocusRequester? = null,+ onBodyFocusChanged: (Boolean) -> Unit = {}, ) { AppScaffold(- title = { Text(- document.title,- maxLines = 1,- overflow = TextOverflow.Ellipsis,- style = MaterialTheme.typography.titleSmall) },+ title = {+ // Title is the first keyboard stop after Back (visual order): a+ // focusable, ringed label so Tab can land on it and continue into+ // the body. Pointer/touch behaviour is unchanged (not clickable).+ var titleFocused by remember { mutableStateOf(false) }+ Text(+ document.title,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ style = MaterialTheme.typography.titleSmall,+ modifier = Modifier+ .onFocusChanged { titleFocused = it.isFocused }+ .officeFocusRing(titleFocused)+ .focusable())+ }, navigationIcon = { IconButton(onClick = { if (!chrome.isOnline && chrome.hasUnsavedChanges) onShowUnsavedDialog() else onBack()@@ -111,6 +128,8 @@ internal fun DocumentScaffoldShell( onCellSelected = onCellSelected, onSlideChange = onSlideChange, onSlideElementSelected = onSlideElementSelected,+ bodyFocusRequester = bodyFocusRequester,+ onBodyFocusChanged = onBodyFocusChanged, ) } }
office/src/main/java/com/vayunmathur/office/ui/DocumentScreen.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/DocumentScreen.kt b/office/src/main/java/com/vayunmathur/office/ui/DocumentScreen.ktindex 2a2b1640dd..59e6ebc1a1 100644--- a/office/src/main/java/com/vayunmathur/office/ui/DocumentScreen.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/DocumentScreen.kt@@ -5,9 +5,16 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusDirection+import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.platform.LocalFocusManager import com.vayunmathur.library.ui.DrawerValue import com.vayunmathur.library.ui.EditorFormat import com.vayunmathur.library.ui.ExperimentalMaterial3Api@@ -72,6 +79,14 @@ fun DocumentScreen( formatter?.toggle(format) return formatter != null }+ // Keyboard focus traversal (Tab/Shift-Tab/Escape), at the same editor root+ // and with the same anyDialogOpen + open-menu suppression as the Ctrl/Meta+ // shortcuts below. Stops are every focusable in visual order (top bar incl.+ // the title, menu bar, body segments, bottom toolbar); Escape returns+ // focus to the first body stop unless the body already has it.+ val focusManager = LocalFocusManager.current+ val bodyFocusRequester = remember { FocusRequester() }+ var bodyHasFocus by remember { mutableStateOf(false) } Box( Modifier.fillMaxSize().onPreviewKeyEvent { event -> handleOfficeDocumentKey(@@ -88,6 +103,15 @@ fun DocumentScreen( }, onToggleBold = { toggleFormat(EditorFormat.BOLD) }, onToggleItalic = { toggleFormat(EditorFormat.ITALIC) },+ ) || handleOfficeFocusTraversalKey(+ event = event,+ dialogOpen = anyOverlayOpen,+ onNext = { focusManager.moveFocus(FocusDirection.Next) },+ onPrevious = { focusManager.moveFocus(FocusDirection.Previous) },+ onEscapeToBody = {+ if (bodyHasFocus) false+ else runCatching { bodyFocusRequester.requestFocus() }.isSuccess+ }, ) }, ) {@@ -114,6 +138,8 @@ fun DocumentScreen( focusedPara = focusedPara, onBack = onBack, onBecameOnline = onBecameOnline,+ bodyFocusRequester = bodyFocusRequester,+ onBodyFocusChanged = { bodyHasFocus = it }, ) } }
office/src/main/java/com/vayunmathur/office/ui/DocumentScreenShell.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/DocumentScreenShell.kt b/office/src/main/java/com/vayunmathur/office/ui/DocumentScreenShell.ktindex 97092e1c4e..1c7d3b0cf1 100644--- a/office/src/main/java/com/vayunmathur/office/ui/DocumentScreenShell.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/DocumentScreenShell.kt@@ -18,6 +18,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp@@ -119,6 +120,8 @@ internal fun DocumentDrawerShell( focusedPara: Int, onBack: () -> Unit, onBecameOnline: (String) -> Unit,+ bodyFocusRequester: FocusRequester? = null,+ onBodyFocusChanged: (Boolean) -> Unit = {}, ) { ModalNavigationDrawer( drawerState = drawerState,@@ -147,6 +150,8 @@ internal fun DocumentDrawerShell( onSlideChange = onSlideChange, onSlideElementSelected = onSlideElementSelected, onBack = onBack,+ bodyFocusRequester = bodyFocusRequester,+ onBodyFocusChanged = onBodyFocusChanged, ) DrawerScreenOverlays( s = s,
office/src/main/java/com/vayunmathur/office/ui/OdfChartViews.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/OdfChartViews.kt b/office/src/main/java/com/vayunmathur/office/ui/OdfChartViews.ktindex 1522939866..ff80d11bd3 100644--- a/office/src/main/java/com/vayunmathur/office/ui/OdfChartViews.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/OdfChartViews.kt@@ -38,11 +38,16 @@ private val chartPalette = listOf( internal fun formatAxis(v: Float): String = if (v == v.toLong().toFloat()) v.toLong().toString() else "%.1f".format(v) @Composable-internal fun OdfChartView(chart: OdfChart, onClick: () -> Unit = {}) {+internal fun OdfChartView(chart: OdfChart, onClick: () -> Unit = {}) =+ OdfChartView(chart, onClick, Modifier)++/** [modifier] overload (kept separate so trailing-lambda call sites keep binding to onClick). */+@Composable+internal fun OdfChartView(chart: OdfChart, onClick: () -> Unit, modifier: Modifier) { val onSurface = MaterialTheme.colorScheme.onSurface val gridColor = MaterialTheme.colorScheme.outlineVariant val surfaceColor = MaterialTheme.colorScheme.surface- Column(Modifier.fillMaxWidth().clickable { onClick() }.padding(vertical = 12.dp)) {+ Column(Modifier.fillMaxWidth().then(modifier).clickable { onClick() }.padding(vertical = 12.dp)) { chart.title?.let { Text( it, style = MaterialTheme.typography.titleSmall,
office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentKeys.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentKeys.kt b/office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentKeys.ktindex de6a72a29e..3ab86d42bb 100644--- a/office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentKeys.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentKeys.kt@@ -3,8 +3,10 @@ package com.vayunmathur.office.ui import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.KeyEventType+import androidx.compose.ui.input.key.isAltPressed import androidx.compose.ui.input.key.isCtrlPressed import androidx.compose.ui.input.key.isMetaPressed+import androidx.compose.ui.input.key.isShiftPressed import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.type @@ -35,6 +37,47 @@ internal fun handleOfficeDocumentKey( } } +/**+ * Keyboard focus traversal for the document editor: Tab moves to the next+ * interactive stop, Shift-Tab to the previous one, and Escape returns focus+ * to the document body. Stops follow the focus tree, which the editor+ * composes in visual order (top bar, menu bar, body segments in document+ * order, bottom toolbar), so moving focus with+ * [androidx.compose.ui.focus.FocusManager.moveFocus] walks them visually.+ *+ * Like [handleOfficeDocumentKey] this is key-down only and is suppressed+ * while a dialog or menu owns the keyboard ([dialogOpen], the same+ * `anyDialogOpen()` + open-menu guard the shortcuts use): Tab is swallowed+ * (consumed, no movement — otherwise Compose's default Tab handling would+ * move editor focus behind the overlay), while Escape is left unconsumed so+ * the overlay's own dismissal handling still wins. A callback+ * that declines (returns false — e.g. Escape while the body already has+ * focus, or no focusable stop in that direction) leaves the event+ * unconsumed so default handling still applies. Ctrl/Meta/Alt+Tab is left+ * to the window/OS (tab/app switching), never consumed here.+ */+internal fun handleOfficeFocusTraversalKey(+ event: KeyEvent,+ dialogOpen: Boolean,+ onNext: () -> Boolean,+ onPrevious: () -> Boolean,+ onEscapeToBody: () -> Boolean,+): Boolean {+ if (event.type != KeyEventType.KeyDown) return false+ if (dialogOpen) {+ return event.key == Key.Tab &&+ !event.isCtrlPressed && !event.isMetaPressed && !event.isAltPressed+ }+ return when (event.key) {+ Key.Tab -> {+ if (event.isCtrlPressed || event.isMetaPressed || event.isAltPressed) false+ else if (event.isShiftPressed) onPrevious() else onNext()+ }+ Key.Escape -> onEscapeToBody()+ else -> false+ }+}+ /** True while any hoisted dialog/crop/export overlay of the document screen is showing. */ internal fun DocumentOverlayState.anyDialogOpen(): Boolean = showMetadata || showShareDialog || showEnableOnlineDialog || showUnsavedDialog ||
office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentPane.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentPane.kt b/office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentPane.ktindex bd78f67183..85085cddfa 100644--- a/office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentPane.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/OfficeDocumentPane.kt@@ -11,6 +11,7 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp@@ -94,6 +95,8 @@ fun OfficeDocumentPane( onCropSlide: (Int, Int) -> Unit, onCropSheet: (Int, Int) -> Unit, modifier: Modifier = Modifier,+ bodyFocusRequester: FocusRequester? = null,+ onBodyFocusChanged: (Boolean) -> Unit = {}, ) { Box(modifier) { val presence by viewModel.remotePresence.collectAsState()@@ -108,7 +111,8 @@ fun OfficeDocumentPane( when (document) { is OdfDocument.TextDocument -> TextPane( document, viewModel, searchQuery, fontSizeMultiplier, listState,- presence, onRunSelectionChange, onCellFocus, onChartClick, onCropImage)+ presence, onRunSelectionChange, onCellFocus, onChartClick, onCropImage,+ bodyFocusRequester, onBodyFocusChanged) is OdfDocument.Spreadsheet -> SheetPane( document, viewModel, searchQuery, fontSizeMultiplier, isEditMode, onCellSelected, onCropSheet)@@ -159,6 +163,8 @@ private fun TextPane( onCellFocus: (Int, Int, Int) -> Unit, onChartClick: (Int) -> Unit, onCropImage: (Int) -> Unit,+ bodyFocusRequester: FocusRequester? = null,+ onBodyFocusChanged: (Boolean) -> Unit = {}, ) { val remoteCarets = presence.mapNotNull { p -> p.caret?.let { com.vayunmathur.library.ui.odf.RemoteCaret(@@ -184,7 +190,9 @@ private fun TextPane( onCellTextChange = { bi, r, c, text -> viewModel.updateTextTableCell(bi, r, c, text) }, onCellFocus = { bi, r, c -> onCellFocus(bi, r, c) }, onChartClick = { bi -> onChartClick(bi) },- onCropImage = { bi -> onCropImage(bi) })+ onCropImage = { bi -> onCropImage(bi) },+ bodyFocusRequester = bodyFocusRequester,+ onBodyFocusChanged = onBodyFocusChanged) } /** Spreadsheet pane. */
office/src/main/java/com/vayunmathur/office/ui/TextDocumentView.kt
diff --git a/office/src/main/java/com/vayunmathur/office/ui/TextDocumentView.kt b/office/src/main/java/com/vayunmathur/office/ui/TextDocumentView.ktindex 364c5c41bd..b56f99dda0 100644--- a/office/src/main/java/com/vayunmathur/office/ui/TextDocumentView.kt+++ b/office/src/main/java/com/vayunmathur/office/ui/TextDocumentView.kt@@ -41,6 +41,9 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor@@ -64,6 +67,22 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import com.vayunmathur.office.platform.firstSpan+/**+ * Visible keyboard-focus indication for the editor's non-Material stops+ * (paragraph runs, table cells, image/chart blocks, the title): a 2dp ring in+ * the theme's primary colour — the same colour the editor uses for the caret+ * and active toolbar state — drawn only while the stop holds focus. The+ * transparent unfocused border keeps the ring from shifting layout, and+ * pointer/touch interaction is untouched (a tap still shows the caret, the+ * ring appears only as focus state).+ */+@Composable+internal fun Modifier.officeFocusRing(focused: Boolean): Modifier =+ border(+ 2.dp,+ if (focused) MaterialTheme.colorScheme.primary else Color.Transparent,+ RoundedCornerShape(6.dp))+ // --- Text Document (continuous editor) --- internal sealed class DocSegment {@@ -126,13 +145,32 @@ fun TextDocumentView( onCellFocus: (Int, Int, Int) -> Unit = { _, _, _ -> }, onChartClick: (Int) -> Unit = {}, onCropImage: (Int) -> Unit = {},- remoteCarets: List<com.vayunmathur.library.ui.odf.RemoteCaret> = emptyList()+ remoteCarets: List<com.vayunmathur.library.ui.odf.RemoteCaret> = emptyList(),+ // Keyboard focus: [bodyFocusRequester] lands on the first interactive body+ // stop (first paragraph run, else first table cell / image / chart) so the+ // screen's Escape handler can return focus to the body; [onBodyFocusChanged]+ // reports whether any body stop currently holds focus (hasFocus).+ bodyFocusRequester: FocusRequester? = null,+ onBodyFocusChanged: (Boolean) -> Unit = {} ) { val segments = remember(doc.content) { buildSegments(doc.content) }+ // First interactive stop in document (visual) order: paragraph runs and+ // table/image/chart blocks are stops; page breaks, formulas, TOCs and+ // section markers are not interactive.+ val firstStopSegment = segments.indexOfFirst { seg ->+ when (seg) {+ is DocSegment.Paragraphs -> true+ is DocSegment.Block -> when (doc.content[seg.index]) {+ is OdfContentBlock.Table, is OdfContentBlock.Image, is OdfContentBlock.Chart -> true+ else -> false+ }+ }+ } LazyColumn( state = listState, modifier = Modifier.fillMaxSize().padding(horizontal = 20.dp, vertical = 12.dp)+ .onFocusChanged { onBodyFocusChanged(it.hasFocus) } ) { if (doc.headerParagraphs.isNotEmpty()) { // Header stays one composed block: its paragraphs render inside a@@ -157,31 +195,58 @@ fun TextDocumentView( contentType = { si -> segments[si].lazyContentType(doc.content) }, ) { si -> when (val seg = segments[si]) {- is DocSegment.Paragraphs -> ContinuousParagraphEditor(- doc, seg.start, seg.endInclusive, fontSizeMultiplier, onRunSelectionChange, onRunTextChange,- modifier = Modifier.fillMaxWidth(),- onEnter = { gPos -> onRunEnter(seg.start, seg.endInclusive, gPos) },- onBackspace = { gPos -> onRunBackspace(seg.start, seg.endInclusive, gPos) },- onToggleCheckbox = onToggleCheckbox,- onDeletePrevBlock = { onDeletePrevBlock(seg.start) },- remoteCarets = remoteCarets,- )+ is DocSegment.Paragraphs -> {+ var segmentFocused by remember { mutableStateOf(false) }+ ContinuousParagraphEditor(+ doc, seg.start, seg.endInclusive, fontSizeMultiplier, onRunSelectionChange, onRunTextChange,+ modifier = Modifier.fillMaxWidth().officeFocusRing(segmentFocused),+ onEnter = { gPos -> onRunEnter(seg.start, seg.endInclusive, gPos) },+ onBackspace = { gPos -> onRunBackspace(seg.start, seg.endInclusive, gPos) },+ onToggleCheckbox = onToggleCheckbox,+ onDeletePrevBlock = { onDeletePrevBlock(seg.start) },+ onFocusChangedCb = { segmentFocused = it },+ focusRequester = if (si == firstStopSegment) bodyFocusRequester else null,+ remoteCarets = remoteCarets,+ )+ } is DocSegment.Block -> when (val block = doc.content[seg.index]) { is OdfContentBlock.Table -> TableView( block.table, seg.index, fontSizeMultiplier, onCellTextChange,- onCellFocus)+ onCellFocus,+ firstCellFocusRequester = if (si == firstStopSegment) bodyFocusRequester else null) is OdfContentBlock.Image -> { var fullScreen by remember { mutableStateOf(false) }+ var imageFocused by remember { mutableStateOf(false) } if (fullScreen) FullScreenImage( block.image, onCrop = { fullScreen = false; onCropImage(seg.index) }) { fullScreen = false }- else Box(modifier = Modifier.clickable { fullScreen = true }) { OdfImageView(block.image) }+ else Box(+ modifier = Modifier+ .then(+ if (si == firstStopSegment && bodyFocusRequester != null) {+ Modifier.focusRequester(bodyFocusRequester)+ } else Modifier)+ .onFocusChanged { imageFocused = it.isFocused }+ .officeFocusRing(imageFocused)+ .clickable { fullScreen = true }) { OdfImageView(block.image) } } is OdfContentBlock.PageBreak -> PageBreakView()- is OdfContentBlock.Chart -> OdfChartView(block.chart, onClick = { onChartClick(seg.index) })+ is OdfContentBlock.Chart -> {+ var chartFocused by remember { mutableStateOf(false) }+ OdfChartView(+ block.chart,+ onClick = { onChartClick(seg.index) },+ modifier = Modifier+ .then(+ if (si == firstStopSegment && bodyFocusRequester != null) {+ Modifier.focusRequester(bodyFocusRequester)+ } else Modifier)+ .onFocusChanged { chartFocused = it.isFocused }+ .officeFocusRing(chartFocused))+ } is OdfContentBlock.Formula -> MathView(block.mathml) is OdfContentBlock.TableOfContents -> { Column(Modifier.fillMaxWidth().padding(vertical = 8.dp)) {@@ -294,8 +359,13 @@ private fun TableView( blockIndex: Int, fontSizeMultiplier: Float = 1f, onCellTextChange: (Int, Int, Int, String) -> Unit = { _, _, _, _ -> },- onCellFocus: (Int, Int, Int) -> Unit = { _, _, _ -> }+ onCellFocus: (Int, Int, Int) -> Unit = { _, _, _ -> },+ firstCellFocusRequester: FocusRequester? = null ) {+ // First editable cell in row-major (visual) order, for Escape-to-body.+ val firstCell: Pair<Int, Int>? = table.rows.indices.firstNotNullOfOrNull { r ->+ table.rows[r].cells.indexOfFirst { !it.isCovered }.takeIf { it >= 0 }?.let { c -> r to c }+ } val onSurface = MaterialTheme.colorScheme.onSurface fun colWidthDp(start: Int, span: Int): androidx.compose.ui.unit.Dp { var w = 0f@@ -331,7 +401,8 @@ private fun TableView( cell, onSurface, fontSizeMultiplier,- onFocus = { onCellFocus(blockIndex, r, c) })+ onFocus = { onCellFocus(blockIndex, r, c) },+ focusRequester = if (firstCell == (r to c)) firstCellFocusRequester else null) { txt -> onCellTextChange(blockIndex, r, c, txt) } } }@@ -350,7 +421,9 @@ private fun EditableCell( onSurface: Color, mult: Float, onFocus: () -> Unit,+ focusRequester: FocusRequester? = null, onChange: (String) -> Unit) {+ var cellFocused by remember { mutableStateOf(false) } val plain = cell.paragraphs.joinToString("\n") { p -> p.spans.joinToString("") { it.text } } var tfv by remember { mutableStateOf(TextFieldValue(plain)) } if (tfv.text != plain) tfv = TextFieldValue(plain, TextRange(tfv.selection.end.coerceIn(0, plain.length)))@@ -369,6 +442,9 @@ private fun EditableCell( onValueChange = { nv -> val changed = nv.text != tfv.text; tfv = nv; if (changed) onChange(nv.text) }, textStyle = style, cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),- modifier = Modifier.fillMaxWidth().onFocusChanged { if (it.isFocused) onFocus() }+ modifier = Modifier.fillMaxWidth()+ .then(if (focusRequester != null) Modifier.focusRequester(focusRequester) else Modifier)+ .onFocusChanged { cellFocused = it.isFocused; if (it.isFocused) onFocus() }+ .officeFocusRing(cellFocused) ) }
office/src/test/java/com/vayunmathur/office/ui/OfficeDocumentKeysTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/OfficeDocumentKeysTest.kt b/office/src/test/java/com/vayunmathur/office/ui/OfficeDocumentKeysTest.ktindex 6096c4d0e8..37bd008d1f 100644--- a/office/src/test/java/com/vayunmathur/office/ui/OfficeDocumentKeysTest.kt+++ b/office/src/test/java/com/vayunmathur/office/ui/OfficeDocumentKeysTest.kt@@ -72,6 +72,80 @@ class OfficeDocumentKeysTest { assertFalse(handle(event(AndroidKeyEvent.KEYCODE_S, ctrl, AndroidKeyEvent.ACTION_UP)).first) } + // ---- Focus traversal (Tab / Shift-Tab / Escape) ----++ private class FocusSink {+ var next = 0+ var previous = 0+ var escape = 0+ var nextResult = true+ var escapeResult = true+ }++ private fun traverse(+ e: KeyEvent, dialogOpen: Boolean = false, sink: FocusSink = FocusSink(),+ ): Pair<Boolean, FocusSink> {+ val handled = handleOfficeFocusTraversalKey(+ event = e,+ dialogOpen = dialogOpen,+ onNext = { sink.next++; sink.nextResult },+ onPrevious = { sink.previous++; true },+ onEscapeToBody = { sink.escape++; sink.escapeResult },+ )+ return handled to sink+ }++ private val shift = AndroidKeyEvent.META_SHIFT_ON++ @Test+ fun tabMovesNextAndShiftTabMovesPrevious() {+ val (_, tabSink) = traverse(event(AndroidKeyEvent.KEYCODE_TAB))+ assertEquals(1, tabSink.next)+ assertEquals(0, tabSink.previous)+ val (_, shiftSink) = traverse(event(AndroidKeyEvent.KEYCODE_TAB, shift))+ assertEquals(0, shiftSink.next)+ assertEquals(1, shiftSink.previous)+ }++ @Test+ fun escapeReturnsToBody() {+ val (handled, sink) = traverse(event(AndroidKeyEvent.KEYCODE_ESCAPE))+ assertTrue(handled)+ assertEquals(1, sink.escape)+ }++ @Test+ fun traversalSuppressedWhileDialogOrMenuOpen() {+ // Tab is swallowed (consumed, no movement) so Compose's default Tab+ // handling cannot move editor focus behind the overlay...+ val (tabHandled, tabSink) = traverse(event(AndroidKeyEvent.KEYCODE_TAB), dialogOpen = true)+ assertTrue(tabHandled)+ assertEquals(0, tabSink.next + tabSink.previous + tabSink.escape)+ // ...while Escape is left to the overlay's own dismissal handling.+ val (escHandled, escSink) = traverse(event(AndroidKeyEvent.KEYCODE_ESCAPE), dialogOpen = true)+ assertFalse(escHandled)+ assertEquals(0, escSink.escape)+ }++ @Test+ fun decliningTraversalIsNotConsumed() {+ val sink = FocusSink().apply { nextResult = false; escapeResult = false }+ assertFalse(traverse(event(AndroidKeyEvent.KEYCODE_TAB), sink = sink).first)+ assertFalse(traverse(event(AndroidKeyEvent.KEYCODE_ESCAPE), sink = sink).first)+ assertEquals(1, sink.next)+ assertEquals(1, sink.escape)+ }++ @Test+ fun traversalIgnoresOtherKeysKeyUpAndModifiedTab() {+ assertFalse(traverse(event(AndroidKeyEvent.KEYCODE_A)).first)+ assertFalse(traverse(event(AndroidKeyEvent.KEYCODE_TAB, 0, AndroidKeyEvent.ACTION_UP)).first)+ // Ctrl/Meta+Tab belongs to the window/OS, not the editor.+ assertFalse(traverse(event(AndroidKeyEvent.KEYCODE_TAB, ctrl)).first)+ assertFalse(traverse(event(AndroidKeyEvent.KEYCODE_TAB, meta)).first)+ assertEquals(0, traverse(event(AndroidKeyEvent.KEYCODE_X)).second.next)+ }+ @Test fun anyDialogOpenReflectsOverlayFlags() { val state = DocumentScreenState()
office/src/test/java/com/vayunmathur/office/ui/TextDocumentFocusTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/ui/TextDocumentFocusTest.kt b/office/src/test/java/com/vayunmathur/office/ui/TextDocumentFocusTest.ktnew file mode 100644index 0000000000..dbd25040f8--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/ui/TextDocumentFocusTest.kt@@ -0,0 +1,198 @@+package com.vayunmathur.office.ui++import androidx.compose.foundation.focusable+import androidx.compose.foundation.layout.Column+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusDirection+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.input.key.Key+import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.platform.LocalFocusManager+import androidx.compose.ui.test.assertIsFocused+import androidx.compose.ui.test.assertIsNotFocused+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performKeyInput+import androidx.compose.ui.test.pressKey+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+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 org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Keyboard focus traversal for the text-document editor (Robolectric ++ * createComposeRule, same level as [Slice4DocumentViewsTest]): the harness+ * composes the stops in the screen's visual order — title, body segments,+ * toolbar action — under the same root preview-key wiring [DocumentScreen]+ * uses ([handleOfficeFocusTraversalKey] + FocusManager + the body's+ * Escape-target requester), with [TextDocumentView] itself production.+ *+ * Traversal order under test: title -> first paragraph run -> table cell ->+ * second paragraph run -> toolbar action (document/visual order, no wrap at+ * the ends).+ */+@RunWith(AndroidJUnit4::class)+class TextDocumentFocusTest {++ @get:Rule val rule = createComposeRule()++ private fun para(text: String) =+ OdfContentBlock.Paragraph(OdfParagraph(listOf(OdfSpan(text))))++ private fun doc(): OdfDocument.TextDocument {+ val cell = OdfTableCell(listOf(OdfParagraph(listOf(OdfSpan("cellone")))))+ val table = OdfTable(rows = listOf(OdfTableRow(listOf(cell))))+ return OdfDocument.TextDocument(+ "Doc",+ listOf(para("first"), OdfContentBlock.Table(table), para("second")),+ )+ }++ private class HarnessState {+ lateinit var titleRequester: FocusRequester+ lateinit var toolbarRequester: FocusRequester+ lateinit var bodyRequester: FocusRequester+ var bodyHasFocus = false+ var dialogOpen = false+ }++ private fun setEditor(state: HarnessState) {+ rule.setContent {+ val focusManager = LocalFocusManager.current+ val titleRequester = remember { FocusRequester() }+ val toolbarRequester = remember { FocusRequester() }+ val bodyRequester = remember { FocusRequester() }+ state.titleRequester = titleRequester+ state.toolbarRequester = toolbarRequester+ state.bodyRequester = bodyRequester+ var titleFocused by remember { mutableStateOf(false) }+ Column(+ Modifier.onPreviewKeyEvent { event ->+ handleOfficeFocusTraversalKey(+ event = event,+ dialogOpen = state.dialogOpen,+ onNext = { focusManager.moveFocus(FocusDirection.Next) },+ onPrevious = { focusManager.moveFocus(FocusDirection.Previous) },+ onEscapeToBody = {+ if (state.bodyHasFocus) false+ else runCatching { bodyRequester.requestFocus() }.isSuccess+ },+ )+ },+ ) {+ Text(+ "DocTitle",+ modifier = Modifier+ .focusRequester(titleRequester)+ .onFocusChanged { titleFocused = it.isFocused }+ .officeFocusRing(titleFocused)+ .focusable(),+ )+ TextDocumentView(+ doc = doc(),+ bodyFocusRequester = bodyRequester,+ onBodyFocusChanged = { state.bodyHasFocus = it },+ )+ TextButton(+ onClick = {},+ modifier = Modifier.focusRequester(toolbarRequester),+ ) { Text("ToolbarAction") }+ }+ }+ rule.waitForIdle()+ }++ @Test fun tabTraversesTitleBodySegmentsToolbarInVisualOrder() {+ val state = HarnessState()+ setEditor(state)++ rule.runOnIdle { state.titleRequester.requestFocus() }+ rule.onNodeWithText("DocTitle").assertIsFocused()++ // Tab: title -> first paragraph run.+ rule.onNodeWithText("DocTitle").performKeyInput { pressKey(Key.Tab) }+ rule.waitForIdle()+ rule.onNodeWithText("first").assertIsFocused()+ rule.onNodeWithText("DocTitle").assertIsNotFocused()++ // Tab: first run -> table cell.+ rule.onNodeWithText("first").performKeyInput { pressKey(Key.Tab) }+ rule.waitForIdle()+ rule.onNodeWithText("cellone").assertIsFocused()++ // Tab: cell -> second paragraph run -> toolbar action.+ rule.onNodeWithText("cellone").performKeyInput { pressKey(Key.Tab) }+ rule.waitForIdle()+ rule.onNodeWithText("second").assertIsFocused()+ rule.onNodeWithText("second").performKeyInput { pressKey(Key.Tab) }+ rule.waitForIdle()+ rule.onNodeWithText("ToolbarAction").assertIsFocused()++ // Shift-Tab walks back: toolbar -> second run.+ rule.onNodeWithText("ToolbarAction").performKeyInput {+ keyDown(Key.ShiftLeft)+ pressKey(Key.Tab)+ keyUp(Key.ShiftLeft)+ }+ rule.waitForIdle()+ rule.onNodeWithText("second").assertIsFocused()+ rule.onNodeWithText("ToolbarAction").assertIsNotFocused()+ }++ @Test fun escapeFromToolbarReturnsFocusToBody() {+ val state = HarnessState()+ setEditor(state)++ rule.runOnIdle { state.toolbarRequester.requestFocus() }+ rule.onNodeWithText("ToolbarAction").assertIsFocused()++ rule.onNodeWithText("ToolbarAction").performKeyInput { pressKey(Key.Escape) }+ rule.waitForIdle()+ // Body's first stop (first paragraph run) owns focus again.+ rule.onNodeWithText("first").assertIsFocused()+ rule.onNodeWithText("ToolbarAction").assertIsNotFocused()+ }++ @Test fun escapeInBodyIsNotConsumed() {+ val state = HarnessState()+ setEditor(state)++ rule.runOnIdle { state.bodyRequester.requestFocus() }+ rule.onNodeWithText("first").assertIsFocused()+ // Escape with the body already focused declines in the harness+ // callback (production DocumentScreen does the same), so the event+ // is left for other handlers and focus stays in the body.+ rule.onNodeWithText("first").performKeyInput { pressKey(Key.Escape) }+ rule.waitForIdle()+ rule.onNodeWithText("first").assertIsFocused()+ }++ @Test fun traversalSuppressedWhileDialogOpen() {+ val state = HarnessState()+ setEditor(state)+ state.dialogOpen = true++ rule.runOnIdle { state.titleRequester.requestFocus() }+ rule.onNodeWithText("DocTitle").assertIsFocused()+ rule.onNodeWithText("DocTitle").performKeyInput { pressKey(Key.Tab) }+ rule.waitForIdle()+ // The dialog/menu keeps the keyboard: focus does not move.+ rule.onNodeWithText("DocTitle").assertIsFocused()+ rule.onNodeWithText("first").assertIsNotFocused()+ }+}