Skip to content

Commit ec7425c

Browse files
committed
test for trap_focus
1 parent 20a2db9 commit ec7425c

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](http://keepachangelog.com/)
66
and this project adheres to [Semantic Versioning](http://semver.org/).
77

8+
## [6.5.1] - Unreleased
9+
10+
### Added
11+
12+
- Added `DOMNode.trap_focus`
13+
814
## [6.4.0] - 2025-10-22
915

1016
### Fixed

tests/test_focus.py

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from textual.app import App, ComposeResult
2-
from textual.containers import Container, ScrollableContainer
2+
from textual.containers import Container, ScrollableContainer, Vertical
33
from textual.widget import Widget
44
from textual.widgets import Button, Label
55
from textual.widgets._placeholder import Placeholder
@@ -507,3 +507,43 @@ def compose(self) -> ComposeResult:
507507
assert isinstance(app.focused, Focusable)
508508
# Check focus chain
509509
assert app.screen.focus_chain == [app.query_one(Focusable)]
510+
511+
512+
async def test_trap_focus():
513+
class TrapApp(App):
514+
CSS = """
515+
Screen {
516+
layout: horizontal;
517+
}
518+
"""
519+
520+
def compose(self) -> ComposeResult:
521+
with Vertical(id="left"):
522+
yield Button("1", id="one")
523+
yield Button("2", id="two")
524+
with Vertical(id="right"):
525+
yield Button("A", id="a")
526+
yield Button("B", id="b")
527+
528+
app = TrapApp()
529+
async with app.run_test():
530+
focus_ids = [node.id for node in app.screen.focus_chain]
531+
assert focus_ids == ["one", "two", "a", "b"]
532+
533+
# Trap the focus on the left container
534+
# Since Button#one is focused, the focus chain will be limited to the left vertical
535+
app.screen.query_one("#left").trap_focus()
536+
focus_ids = [node.id for node in app.screen.focus_chain]
537+
assert focus_ids == ["one", "two"]
538+
539+
# Trap focus on the right container
540+
# Since the right containers doesn't contain a focused widget, we would expect no change
541+
app.screen.query_one("#right").trap_focus()
542+
focus_ids = [node.id for node in app.screen.focus_chain]
543+
assert focus_ids == ["one", "two"]
544+
545+
# Untrap the focus on the left container
546+
# Should restore original focus chain
547+
app.screen.query_one("#left").trap_focus(False)
548+
focus_ids = [node.id for node in app.screen.focus_chain]
549+
assert focus_ids == ["one", "two", "a", "b"]

0 commit comments

Comments
 (0)