Merge pull request #1785 from davep/promote-disabled

Promote disabled to `Widget` level
This commit is contained in:
Will McGugan
2023-02-21 09:56:01 +00:00
committed by GitHub
20 changed files with 555 additions and 156 deletions

View File

@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
## Unreleased ## Unreleased
### Added
- Added `Widget.disabled` https://github.com/Textualize/textual/pull/1785
### Fixed ### Fixed
- Numbers in a descendant-combined selector no longer cause an error https://github.com/Textualize/textual/issues/1836 - Numbers in a descendant-combined selector no longer cause an error https://github.com/Textualize/textual/issues/1836

View File

@@ -315,6 +315,8 @@ The `background: green` is only applied to the Button underneath the mouse curso
Here are some other pseudo classes: Here are some other pseudo classes:
- `:disabled` Matches widgets which are in a disabled state.
- `:enabled` Matches widgets which are in an enabled state.
- `:focus` Matches widgets which have input focus. - `:focus` Matches widgets which have input focus.
- `:focus-within` Matches widgets with a focused a child widget. - `:focus-within` Matches widgets with a focused a child widget.

View File

@@ -1,7 +1,7 @@
from __future__ import annotations
"""Simple version of 5x5, developed for/with Textual.""" """Simple version of 5x5, developed for/with Textual."""
from __future__ import annotations
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING, cast from typing import TYPE_CHECKING, cast
@@ -192,8 +192,7 @@ class Game(Screen):
Args: Args:
playable (bool): Should the game currently be playable? playable (bool): Should the game currently be playable?
""" """
for cell in self.query(GameCell): self.query_one(GameGrid).disabled = not playable
cell.disabled = not playable
def cell(self, row: int, col: int) -> GameCell: def cell(self, row: int, col: int) -> GameCell:
"""Get the cell at a given location. """Get the cell at a given location.

View File

@@ -241,6 +241,11 @@ class App(Generic[ReturnType], DOMNode):
background: $background; background: $background;
color: $text; color: $text;
} }
*:disabled {
opacity: 0.6;
text-opacity: 0.8;
}
""" """
SCREENS: dict[str, Screen | Callable[[], Screen]] = {} SCREENS: dict[str, Screen | Callable[[], Screen]] = {}

View File

@@ -872,6 +872,16 @@ class DOMNode(MessagePump):
else: else:
self.remove_class(*class_names) self.remove_class(*class_names)
def _update_styles(self) -> None:
"""Request an update of this node's styles.
Should be called whenever CSS classes / pseudo classes change.
"""
try:
self.app.update_styles(self)
except NoActiveAppError:
pass
def add_class(self, *class_names: str) -> None: def add_class(self, *class_names: str) -> None:
"""Add class names to this Node. """Add class names to this Node.
@@ -884,10 +894,7 @@ class DOMNode(MessagePump):
self._classes.update(class_names) self._classes.update(class_names)
if old_classes == self._classes: if old_classes == self._classes:
return return
try: self._update_styles()
self.app.update_styles(self)
except NoActiveAppError:
pass
def remove_class(self, *class_names: str) -> None: def remove_class(self, *class_names: str) -> None:
"""Remove class names from this Node. """Remove class names from this Node.
@@ -900,10 +907,7 @@ class DOMNode(MessagePump):
self._classes.difference_update(class_names) self._classes.difference_update(class_names)
if old_classes == self._classes: if old_classes == self._classes:
return return
try: self._update_styles()
self.app.update_styles(self)
except NoActiveAppError:
pass
def toggle_class(self, *class_names: str) -> None: def toggle_class(self, *class_names: str) -> None:
"""Toggle class names on this Node. """Toggle class names on this Node.
@@ -916,10 +920,7 @@ class DOMNode(MessagePump):
self._classes.symmetric_difference_update(class_names) self._classes.symmetric_difference_update(class_names)
if old_classes == self._classes: if old_classes == self._classes:
return return
try: self._update_styles()
self.app.update_styles(self)
except NoActiveAppError:
pass
def has_pseudo_class(self, *class_names: str) -> bool: def has_pseudo_class(self, *class_names: str) -> bool:
"""Check for pseudo classes (such as hover, focus etc) """Check for pseudo classes (such as hover, focus etc)

View File

@@ -159,11 +159,7 @@ class Screen(Widget):
@property @property
def focus_chain(self) -> list[Widget]: def focus_chain(self) -> list[Widget]:
"""Get widgets that may receive focus, in focus order. """A list of widgets that may receive focus, in focus order."""
Returns:
List of Widgets in focus order.
"""
widgets: list[Widget] = [] widgets: list[Widget] = []
add_widget = widgets.append add_widget = widgets.append
stack: list[Iterator[Widget]] = [iter(self.focusable_children)] stack: list[Iterator[Widget]] = [iter(self.focusable_children)]
@@ -177,7 +173,7 @@ class Screen(Widget):
else: else:
if node.is_container and node.can_focus_children: if node.is_container and node.can_focus_children:
push(iter(node.focusable_children)) push(iter(node.focusable_children))
if node.can_focus: if node.focusable:
add_widget(node) add_widget(node)
return widgets return widgets
@@ -314,7 +310,7 @@ class Screen(Widget):
# It may have been made invisible # It may have been made invisible
# Move to a sibling if possible # Move to a sibling if possible
for sibling in widget.visible_siblings: for sibling in widget.visible_siblings:
if sibling not in avoiding and sibling.can_focus: if sibling not in avoiding and sibling.focusable:
self.set_focus(sibling) self.set_focus(sibling)
break break
else: else:
@@ -351,7 +347,7 @@ class Screen(Widget):
self.focused.post_message_no_wait(events.Blur(self)) self.focused.post_message_no_wait(events.Blur(self))
self.focused = None self.focused = None
self.log.debug("focus was removed") self.log.debug("focus was removed")
elif widget.can_focus: elif widget.focusable:
if self.focused != widget: if self.focused != widget:
if self.focused is not None: if self.focused is not None:
# Blur currently focused widget # Blur currently focused widget
@@ -547,7 +543,7 @@ class Screen(Widget):
except errors.NoWidget: except errors.NoWidget:
self.set_focus(None) self.set_focus(None)
else: else:
if isinstance(event, events.MouseUp) and widget.can_focus: if isinstance(event, events.MouseUp) and widget.focusable:
if self.focused is not widget: if self.focused is not widget:
self.set_focus(widget) self.set_focus(widget)
event.stop() event.stop()

View File

@@ -225,6 +225,8 @@ class Widget(DOMNode):
"""Rich renderable may shrink.""" """Rich renderable may shrink."""
auto_links = Reactive(True) auto_links = Reactive(True)
"""Widget will highlight links automatically.""" """Widget will highlight links automatically."""
disabled = Reactive(False)
"""The disabled state of the widget. `True` if disabled, `False` if not."""
hover_style: Reactive[Style] = Reactive(Style, repaint=False) hover_style: Reactive[Style] = Reactive(Style, repaint=False)
highlight_link_id: Reactive[str] = Reactive("") highlight_link_id: Reactive[str] = Reactive("")
@@ -235,6 +237,7 @@ class Widget(DOMNode):
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
) -> None: ) -> None:
self._size = Size(0, 0) self._size = Size(0, 0)
self._container_size = Size(0, 0) self._container_size = Size(0, 0)
@@ -277,6 +280,7 @@ class Widget(DOMNode):
raise WidgetError("A widget can't be its own parent") raise WidgetError("A widget can't be its own parent")
self._add_children(*children) self._add_children(*children)
self.disabled = disabled
virtual_size = Reactive(Size(0, 0), layout=True) virtual_size = Reactive(Size(0, 0), layout=True)
auto_width = Reactive(True) auto_width = Reactive(True)
@@ -1173,6 +1177,20 @@ class Widget(DOMNode):
""" """
return self.virtual_region.grow(self.styles.margin) return self.virtual_region.grow(self.styles.margin)
@property
def _self_or_ancestors_disabled(self) -> bool:
"""Is this widget or any of its ancestors disabled?"""
return any(
node.disabled
for node in self.ancestors_with_self
if isinstance(node, Widget)
)
@property
def focusable(self) -> bool:
"""Can this widget currently receive focus?"""
return self.can_focus and not self._self_or_ancestors_disabled
@property @property
def focusable_children(self) -> list[Widget]: def focusable_children(self) -> list[Widget]:
"""Get the children which may be focused. """Get the children which may be focused.
@@ -2080,6 +2098,14 @@ class Widget(DOMNode):
Names of the pseudo classes. Names of the pseudo classes.
""" """
node = self
while isinstance(node, Widget):
if node.disabled:
yield "disabled"
break
node = node._parent
else:
yield "enabled"
if self.mouse_over: if self.mouse_over:
yield "hover" yield "hover"
if self.has_focus: if self.has_focus:
@@ -2127,11 +2153,15 @@ class Widget(DOMNode):
def watch_mouse_over(self, value: bool) -> None: def watch_mouse_over(self, value: bool) -> None:
"""Update from CSS if mouse over state changes.""" """Update from CSS if mouse over state changes."""
if self._has_hover_style: if self._has_hover_style:
self.app.update_styles(self) self._update_styles()
def watch_has_focus(self, value: bool) -> None: def watch_has_focus(self, value: bool) -> None:
"""Update from CSS if has focus state changes.""" """Update from CSS if has focus state changes."""
self.app.update_styles(self) self._update_styles()
def watch_disabled(self) -> None:
"""Update the styles of the widget and its children when disabled is toggled."""
self._update_styles()
def _size_updated( def _size_updated(
self, size: Size, virtual_size: Size, container_size: Size self, size: Size, virtual_size: Size, container_size: Size
@@ -2421,6 +2451,18 @@ class Widget(DOMNode):
""" """
self.app.capture_mouse(None) self.app.capture_mouse(None)
def check_message_enabled(self, message: Message) -> bool:
# Do the normal checking and get out if that fails.
if not super().check_message_enabled(message):
return False
# Otherwise, if this is a mouse event, the widget receiving the
# event must not be disabled at this moment.
return (
not self._self_or_ancestors_disabled
if isinstance(message, (events.MouseEvent, events.Enter, events.Leave))
else True
)
async def broker_event(self, event_name: str, event: events.Event) -> bool: async def broker_event(self, event_name: str, event: events.Event) -> bool:
return await self.app._broker_event(event_name, event, default_namespace=self) return await self.app._broker_event(event_name, event, default_namespace=self)
@@ -2479,11 +2521,11 @@ class Widget(DOMNode):
def _on_descendant_blur(self, event: events.DescendantBlur) -> None: def _on_descendant_blur(self, event: events.DescendantBlur) -> None:
if self._has_focus_within: if self._has_focus_within:
self.app.update_styles(self) self._update_styles()
def _on_descendant_focus(self, event: events.DescendantBlur) -> None: def _on_descendant_focus(self, event: events.DescendantBlur) -> None:
if self._has_focus_within: if self._has_focus_within:
self.app.update_styles(self) self._update_styles()
def _on_mouse_scroll_down(self, event: events.MouseScrollDown) -> None: def _on_mouse_scroll_down(self, event: events.MouseScrollDown) -> None:
if event.ctrl or event.shift: if event.ctrl or event.shift:

View File

@@ -39,11 +39,6 @@ class Button(Static, can_focus=True):
text-style: bold; text-style: bold;
} }
Button.-disabled {
opacity: 0.4;
text-opacity: 0.7;
}
Button:focus { Button:focus {
text-style: bold reverse; text-style: bold reverse;
} }
@@ -156,9 +151,6 @@ class Button(Static, can_focus=True):
variant = reactive("default") variant = reactive("default")
"""The variant name for the button.""" """The variant name for the button."""
disabled = reactive(False)
"""The disabled state of the button; `True` if disabled, `False` if not."""
class Pressed(Message, bubble=True): class Pressed(Message, bubble=True):
"""Event sent when a `Button` is pressed. """Event sent when a `Button` is pressed.
@@ -176,45 +168,35 @@ class Button(Static, can_focus=True):
def __init__( def __init__(
self, self,
label: TextType | None = None, label: TextType | None = None,
disabled: bool = False,
variant: ButtonVariant = "default", variant: ButtonVariant = "default",
*, *,
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
): ):
"""Create a Button widget. """Create a Button widget.
Args: Args:
label: The text that appears within the button. label: The text that appears within the button.
disabled: Whether the button is disabled or not.
variant: The variant of the button. variant: The variant of the button.
name: The name of the button. name: The name of the button.
id: The ID of the button in the DOM. id: The ID of the button in the DOM.
classes: The CSS classes of the button. classes: The CSS classes of the button.
disabled: Whether the button is disabled or not.
""" """
super().__init__(name=name, id=id, classes=classes) super().__init__(name=name, id=id, classes=classes, disabled=disabled)
if label is None: if label is None:
label = self.css_identifier_styled label = self.css_identifier_styled
self.label = self.validate_label(label) self.label = self.validate_label(label)
self.disabled = disabled
if disabled:
self.add_class("-disabled")
self.variant = self.validate_variant(variant) self.variant = self.validate_variant(variant)
def __rich_repr__(self) -> rich.repr.Result: def __rich_repr__(self) -> rich.repr.Result:
yield from super().__rich_repr__() yield from super().__rich_repr__()
yield "variant", self.variant, "default" yield "variant", self.variant, "default"
yield "disabled", self.disabled, False
def watch_mouse_over(self, value: bool) -> None:
"""Update from CSS if mouse over state changes."""
if self._has_hover_style and not self.disabled:
self.app.update_styles(self)
def validate_variant(self, variant: str) -> str: def validate_variant(self, variant: str) -> str:
if variant not in _VALID_BUTTON_VARIANTS: if variant not in _VALID_BUTTON_VARIANTS:
@@ -227,10 +209,6 @@ class Button(Static, can_focus=True):
self.remove_class(f"-{old_variant}") self.remove_class(f"-{old_variant}")
self.add_class(f"-{variant}") self.add_class(f"-{variant}")
def watch_disabled(self, disabled: bool) -> None:
self.set_class(disabled, "-disabled")
self.can_focus = not disabled
def validate_label(self, label: RenderableType) -> RenderableType: def validate_label(self, label: RenderableType) -> RenderableType:
"""Parse markup for self.label""" """Parse markup for self.label"""
if isinstance(label, str): if isinstance(label, str):
@@ -272,11 +250,11 @@ class Button(Static, can_focus=True):
def success( def success(
cls, cls,
label: TextType | None = None, label: TextType | None = None,
disabled: bool = False,
*, *,
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
) -> Button: ) -> Button:
"""Utility constructor for creating a success Button variant. """Utility constructor for creating a success Button variant.
@@ -292,22 +270,22 @@ class Button(Static, can_focus=True):
""" """
return Button( return Button(
label=label, label=label,
disabled=disabled,
variant="success", variant="success",
name=name, name=name,
id=id, id=id,
classes=classes, classes=classes,
disabled=disabled,
) )
@classmethod @classmethod
def warning( def warning(
cls, cls,
label: TextType | None = None, label: TextType | None = None,
disabled: bool = False,
*, *,
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
) -> Button: ) -> Button:
"""Utility constructor for creating a warning Button variant. """Utility constructor for creating a warning Button variant.
@@ -323,22 +301,22 @@ class Button(Static, can_focus=True):
""" """
return Button( return Button(
label=label, label=label,
disabled=disabled,
variant="warning", variant="warning",
name=name, name=name,
id=id, id=id,
classes=classes, classes=classes,
disabled=disabled,
) )
@classmethod @classmethod
def error( def error(
cls, cls,
label: TextType | None = None, label: TextType | None = None,
disabled: bool = False,
*, *,
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
) -> Button: ) -> Button:
"""Utility constructor for creating an error Button variant. """Utility constructor for creating an error Button variant.
@@ -354,9 +332,9 @@ class Button(Static, can_focus=True):
""" """
return Button( return Button(
label=label, label=label,
disabled=disabled,
variant="error", variant="error",
name=name, name=name,
id=id, id=id,
classes=classes, classes=classes,
disabled=disabled,
) )

View File

@@ -473,8 +473,9 @@ class DataTable(ScrollView, Generic[CellType], can_focus=True):
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
) -> None: ) -> None:
super().__init__(name=name, id=id, classes=classes) super().__init__(name=name, id=id, classes=classes, disabled=disabled)
self._data: dict[RowKey, dict[ColumnKey, CellType]] = {} self._data: dict[RowKey, dict[ColumnKey, CellType]] = {}
"""Contains the cells of the table, indexed by row key and column key. """Contains the cells of the table, indexed by row key and column key.
The final positioning of a cell on screen cannot be determined solely by this The final positioning of a cell on screen cannot be determined solely by this

View File

@@ -29,6 +29,7 @@ class DirectoryTree(Tree[DirEntry]):
name: The name of the widget, or None for no name. Defaults to None. name: The name of the widget, or None for no name. Defaults to None.
id: The ID of the widget in the DOM, or None for no ID. Defaults to None. id: The ID of the widget in the DOM, or None for no ID. Defaults to None.
classes: A space-separated list of classes, or None for no classes. Defaults to None. classes: A space-separated list of classes, or None for no classes. Defaults to None.
disabled: Whether the directory tree is disabled or not.
""" """
COMPONENT_CLASSES: ClassVar[set[str]] = { COMPONENT_CLASSES: ClassVar[set[str]] = {
@@ -87,6 +88,7 @@ class DirectoryTree(Tree[DirEntry]):
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
) -> None: ) -> None:
self.path = path self.path = path
super().__init__( super().__init__(
@@ -95,6 +97,7 @@ class DirectoryTree(Tree[DirEntry]):
name=name, name=name,
id=id, id=id,
classes=classes, classes=classes,
disabled=disabled,
) )
def process_label(self, label: TextType): def process_label(self, label: TextType):

View File

@@ -110,9 +110,6 @@ class Input(Widget, can_focus=True):
height: 1; height: 1;
min-height: 1; min-height: 1;
} }
Input.-disabled {
opacity: 0.6;
}
Input:focus { Input:focus {
border: tall $accent; border: tall $accent;
} }
@@ -179,6 +176,7 @@ class Input(Widget, can_focus=True):
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
) -> None: ) -> None:
"""Initialise the `Input` widget. """Initialise the `Input` widget.
@@ -190,8 +188,9 @@ class Input(Widget, can_focus=True):
name: Optional name for the input widget. name: Optional name for the input widget.
id: Optional ID for the widget. id: Optional ID for the widget.
classes: Optional initial classes for the widget. classes: Optional initial classes for the widget.
disabled: Whether the input is disabled or not.
""" """
super().__init__(name=name, id=id, classes=classes) super().__init__(name=name, id=id, classes=classes, disabled=disabled)
if value is not None: if value is not None:
self.value = value self.value = value
self.placeholder = placeholder self.placeholder = placeholder

View File

@@ -73,6 +73,7 @@ class ListView(Vertical, can_focus=True, can_focus_children=False):
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
) -> None: ) -> None:
""" """
Args: Args:
@@ -81,8 +82,11 @@ class ListView(Vertical, can_focus=True, can_focus_children=False):
name: The name of the widget. name: The name of the widget.
id: The unique ID of the widget used in CSS/query selection. id: The unique ID of the widget used in CSS/query selection.
classes: The CSS classes of the widget. classes: The CSS classes of the widget.
disabled: Whether the ListView is disabled or not.
""" """
super().__init__(*children, name=name, id=id, classes=classes) super().__init__(
*children, name=name, id=id, classes=classes, disabled=disabled
)
self._index = initial_index self._index = initial_index
def on_mount(self) -> None: def on_mount(self) -> None:

View File

@@ -36,6 +36,7 @@ class Static(Widget, inherit_bindings=False):
name: Name of widget. Defaults to None. name: Name of widget. Defaults to None.
id: ID of Widget. Defaults to None. id: ID of Widget. Defaults to None.
classes: Space separated list of class names. Defaults to None. classes: Space separated list of class names. Defaults to None.
disabled: Whether the static is disabled or not.
""" """
DEFAULT_CSS = """ DEFAULT_CSS = """
@@ -56,8 +57,9 @@ class Static(Widget, inherit_bindings=False):
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
) -> None: ) -> None:
super().__init__(name=name, id=id, classes=classes) super().__init__(name=name, id=id, classes=classes, disabled=disabled)
self.expand = expand self.expand = expand
self.shrink = shrink self.shrink = shrink
self.markup = markup self.markup = markup

View File

@@ -100,6 +100,7 @@ class Switch(Widget, can_focus=True):
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
): ):
"""Initialise the switch. """Initialise the switch.
@@ -109,8 +110,9 @@ class Switch(Widget, can_focus=True):
name: The name of the switch. name: The name of the switch.
id: The ID of the switch in the DOM. id: The ID of the switch in the DOM.
classes: The CSS classes of the switch. classes: The CSS classes of the switch.
disabled: Whether the switch is disabled or not.
""" """
super().__init__(name=name, id=id, classes=classes) super().__init__(name=name, id=id, classes=classes, disabled=disabled)
if value: if value:
self.slider_pos = 1.0 self.slider_pos = 1.0
self._reactive_value = value self._reactive_value = value

View File

@@ -43,8 +43,9 @@ class TextLog(ScrollView, can_focus=True):
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
) -> None: ) -> None:
super().__init__(name=name, id=id, classes=classes) super().__init__(name=name, id=id, classes=classes, disabled=disabled)
self.max_lines = max_lines self.max_lines = max_lines
self._start_line: int = 0 self._start_line: int = 0
self.lines: list[Strip] = [] self.lines: list[Strip] = []

View File

@@ -473,8 +473,9 @@ class Tree(Generic[TreeDataType], ScrollView, can_focus=True):
name: str | None = None, name: str | None = None,
id: str | None = None, id: str | None = None,
classes: str | None = None, classes: str | None = None,
disabled: bool = False,
) -> None: ) -> None:
super().__init__(name=name, id=id, classes=classes) super().__init__(name=name, id=id, classes=classes, disabled=disabled)
text_label = self.process_label(label) text_label = self.process_label(label)

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,84 @@
from textual.app import App, ComposeResult
from textual.containers import Vertical, Horizontal
from textual.widgets import (
Header,
Footer,
Button,
DataTable,
Input,
ListView,
ListItem,
Label,
Markdown,
MarkdownViewer,
Tree,
TextLog,
)
class WidgetDisableTestApp(App[None]):
CSS = """
Horizontal {
height: auto;
}
DataTable, ListView, Tree, TextLog {
height: 2;
}
Markdown, MarkdownViewer {
height: 1fr;
}
"""
@property
def data_table(self) -> DataTable:
data_table = DataTable[str]()
data_table.add_columns("Column 1", "Column 2", "Column 3", "Column 4")
data_table.add_rows(
[(str(n), str(n * 10), str(n * 100), str(n * 1000)) for n in range(100)]
)
return data_table
@property
def list_view(self) -> ListView:
return ListView(*[ListItem(Label(f"This is list item {n}")) for n in range(20)])
@property
def test_tree(self) -> Tree:
tree = Tree[None](label="This is a test tree")
for n in range(10):
tree.root.add_leaf(f"Leaf {n}")
tree.root.expand()
return tree
def compose(self) -> ComposeResult:
yield Header()
yield Vertical(
Horizontal(
Button(),
Button(variant="primary"),
Button(variant="success"),
Button(variant="warning"),
Button(variant="error"),
),
self.data_table,
self.list_view,
self.test_tree,
TextLog(),
Input(),
Input(placeholder="This is an empty input with a placeholder"),
Input("This is some text in an input"),
Markdown("# Hello, World!"),
MarkdownViewer("# Hello, World!"),
id="test-container",
)
yield Footer()
def on_mount(self) -> None:
self.query_one(TextLog).write("Hello, World!")
self.query_one("#test-container", Vertical).disabled = True
if __name__ == "__main__":
WidgetDisableTestApp().run()

View File

@@ -231,3 +231,7 @@ def test_auto_width_input(snap_compare):
def test_screen_switch(snap_compare): def test_screen_switch(snap_compare):
assert snap_compare(SNAPSHOT_APPS_DIR / "screen_switch.py", press=["a", "b"]) assert snap_compare(SNAPSHOT_APPS_DIR / "screen_switch.py", press=["a", "b"])
def test_disabled_widgets(snap_compare):
assert snap_compare(SNAPSHOT_APPS_DIR / "disable_widgets.py")

84
tests/test_disabled.py Normal file
View File

@@ -0,0 +1,84 @@
"""Test Widget.disabled."""
from textual.app import App, ComposeResult
from textual.containers import Vertical
from textual.widgets import (
Button,
DataTable,
DirectoryTree,
Input,
ListView,
Markdown,
MarkdownViewer,
Switch,
TextLog,
Tree,
)
class DisableApp(App[None]):
"""Application for testing Widget.disabled."""
def compose(self) -> ComposeResult:
"""Compose the child widgets."""
yield Vertical(
Button(),
DataTable(),
DirectoryTree("."),
Input(),
ListView(),
Switch(),
TextLog(),
Tree("Test"),
Markdown(),
MarkdownViewer(),
id="test-container",
)
async def test_all_initially_enabled() -> None:
"""All widgets should start out enabled."""
async with DisableApp().run_test() as pilot:
assert all(
not node.disabled for node in pilot.app.screen.query("#test-container > *")
)
async def test_enabled_widgets_have_enabled_pseudo_class() -> None:
"""All enabled widgets should have the :enabled pseudoclass."""
async with DisableApp().run_test() as pilot:
assert all(
node.has_pseudo_class("enabled") and not node.has_pseudo_class("disabled")
for node in pilot.app.screen.query("#test-container > *")
)
async def test_all_individually_disabled() -> None:
"""Post-disable all widgets should report being disabled."""
async with DisableApp().run_test() as pilot:
for node in pilot.app.screen.query("Vertical > *"):
node.disabled = True
assert all(
node.disabled for node in pilot.app.screen.query("#test-container > *")
)
async def test_disabled_widgets_have_disabled_pseudo_class() -> None:
"""All disabled widgets should have the :disabled pseudoclass."""
async with DisableApp().run_test() as pilot:
for node in pilot.app.screen.query("#test-container > *"):
node.disabled = True
assert all(
node.has_pseudo_class("disabled") and not node.has_pseudo_class("enabled")
for node in pilot.app.screen.query("#test-container > *")
)
async def test_disable_via_container() -> None:
"""All child widgets should appear (to CSS) as disabled by a container being disabled."""
async with DisableApp().run_test() as pilot:
pilot.app.screen.query_one("#test-container", Vertical).disabled = True
assert all(
node.has_pseudo_class("disabled") and not node.has_pseudo_class("enabled")
for node in pilot.app.screen.query("#test-container > *")
)