object-tree 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of object-tree might be problematic. Click here for more details.

core/__init__.py ADDED
@@ -0,0 +1,68 @@
1
+ """object-tree core: a zero-dependency framework for nested selection and inspection.
2
+
3
+ Provides the object tree model (:class:`InspectableObject`, :class:`Property`),
4
+ selection state, inspector stack, viewport system with spatial hit-testing,
5
+ interaction controller, and an adapter protocol for importing external data.
6
+ """
7
+
8
+ from .adapter import DictAdapter, InspectableAdapter, adapt
9
+ from .hittest import (
10
+ CircleRegion,
11
+ PolygonRegion,
12
+ RectRegion,
13
+ hit_test,
14
+ point_in_circle,
15
+ point_in_polygon,
16
+ point_in_rect,
17
+ )
18
+ from .inspector import BoxSpec, InspectorSystem
19
+ from .interaction import InteractionController
20
+ from .node import PROPERTY_TYPES, InspectableObject, Property
21
+ from .selection import SelectionState
22
+ from .viewport import (
23
+ AncestorSelectedRule,
24
+ AndRule,
25
+ BooleanRule,
26
+ NotRule,
27
+ OrRule,
28
+ ParentSelectedRule,
29
+ Rule,
30
+ SameGroupRule,
31
+ SelfOrAncestorSelectedRule,
32
+ SiblingSelectedRule,
33
+ ViewportElement,
34
+ )
35
+ from .viewport_system import HitResult, ViewportSystem
36
+
37
+ __all__ = [
38
+ "InspectableObject",
39
+ "Property",
40
+ "PROPERTY_TYPES",
41
+ "SelectionState",
42
+ "InspectorSystem",
43
+ "BoxSpec",
44
+ "ViewportElement",
45
+ "ViewportSystem",
46
+ "HitResult",
47
+ "RectRegion",
48
+ "CircleRegion",
49
+ "PolygonRegion",
50
+ "Rule",
51
+ "BooleanRule",
52
+ "ParentSelectedRule",
53
+ "SelfOrAncestorSelectedRule",
54
+ "SiblingSelectedRule",
55
+ "AncestorSelectedRule",
56
+ "SameGroupRule",
57
+ "AndRule",
58
+ "OrRule",
59
+ "NotRule",
60
+ "InteractionController",
61
+ "point_in_rect",
62
+ "point_in_circle",
63
+ "point_in_polygon",
64
+ "hit_test",
65
+ "InspectableAdapter",
66
+ "DictAdapter",
67
+ "adapt",
68
+ ]
core/adapter.py ADDED
@@ -0,0 +1,83 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass, field
3
+ from typing import Any, Dict, List, Optional, Protocol, Tuple
4
+
5
+ from .node import InspectableObject, Property
6
+
7
+
8
+ class InspectableAdapter(Protocol):
9
+ """Protocol for adapting external data sources to :class:`InspectableObject`.
10
+
11
+ Implement this protocol on any wrapper type to convert it into the
12
+ object-tree representation via :func:`adapt`.
13
+ """
14
+ def get_name(self) -> str: ...
15
+ def get_parent(self) -> Optional[Any]: ...
16
+ def get_children(self) -> List[Any]: ...
17
+ def get_properties(self) -> Dict[str, Tuple[str, Any]]: ...
18
+ def get_show_parent_box(self) -> bool: ...
19
+
20
+
21
+ def adapt(adapter: InspectableAdapter) -> InspectableObject:
22
+ """Recursively convert an :class:`InspectableAdapter` into an :class:`InspectableObject` tree.
23
+
24
+ The resulting tree mirrors the structure returned by the adapter's
25
+ ``get_children()`` method.
26
+ """
27
+ name = adapter.get_name()
28
+ props = adapter.get_properties()
29
+
30
+ node = InspectableObject(
31
+ name=name,
32
+ show_parent_box=adapter.get_show_parent_box(),
33
+ )
34
+ for prop_name, (prop_type, prop_value) in props.items():
35
+ node.add_property(Property(name=prop_name, type=prop_type, value=prop_value))
36
+
37
+ for child_src in adapter.get_children():
38
+ child_node = adapt(child_src)
39
+ node.add_child(child_node)
40
+
41
+ return node
42
+
43
+
44
+ class DictAdapter:
45
+ """Adapts a plain ``dict`` tree to the :class:`InspectableAdapter` protocol.
46
+
47
+ Expected dict structure::
48
+
49
+ {
50
+ "name": str,
51
+ "show_parent_box": bool,
52
+ "properties": {"key": (type_str, value), ...},
53
+ "children": [<recursive dict>, ...],
54
+ }
55
+ """
56
+
57
+ def __init__(self, data: dict):
58
+ self._data = data
59
+
60
+ def get_name(self) -> str:
61
+ return self._data.get("name", "Unnamed")
62
+
63
+ def get_parent(self) -> Optional[Any]:
64
+ parent = self._data.get("parent")
65
+ if parent is not None:
66
+ return DictAdapter(parent)
67
+ return None
68
+
69
+ def get_children(self) -> List[Any]:
70
+ return [DictAdapter(c) for c in self._data.get("children", [])]
71
+
72
+ def get_properties(self) -> Dict[str, Tuple[str, Any]]:
73
+ raw = self._data.get("properties", {})
74
+ result: Dict[str, Tuple[str, Any]] = {}
75
+ for key, val in raw.items():
76
+ if isinstance(val, tuple) and len(val) == 2:
77
+ result[key] = (val[0], val[1])
78
+ else:
79
+ result[key] = (type(val).__name__, val)
80
+ return result
81
+
82
+ def get_show_parent_box(self) -> bool:
83
+ return self._data.get("show_parent_box", True)
core/hittest.py ADDED
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+ from typing import Tuple
3
+
4
+ from .viewport import CircleRegion, PolygonRegion, RectRegion
5
+
6
+
7
+ def point_in_rect(px: float, py: float, rect: RectRegion) -> bool:
8
+ """Return True if (*px*, *py*) lies inside the axis-aligned rectangle."""
9
+ return rect.x <= px <= rect.x + rect.width and rect.y <= py <= rect.y + rect.height
10
+
11
+
12
+ def point_in_circle(px: float, py: float, circle: CircleRegion) -> bool:
13
+ """Return True if (*px*, *py*) lies inside or on the circle."""
14
+ dx = px - circle.cx
15
+ dy = py - circle.cy
16
+ return dx * dx + dy * dy <= circle.radius * circle.radius
17
+
18
+
19
+ def point_in_polygon(px: float, py: float, polygon: PolygonRegion) -> bool:
20
+ """Ray-cast point-in-polygon test. Returns True for interior points."""
21
+ inside = False
22
+ n = len(polygon.points)
23
+ j = n - 1
24
+ for i in range(n):
25
+ xi, yi = polygon.points[i]
26
+ xj, yj = polygon.points[j]
27
+ if ((yi > py) != (yj > py)) and (px < (xj - xi) * (py - yi) / (yj - yi) + xi):
28
+ inside = not inside
29
+ j = i
30
+ return inside
31
+
32
+
33
+ def hit_test(px: float, py: float, region: RectRegion | CircleRegion | PolygonRegion) -> bool:
34
+ """Dispatch point-in-region test based on the region type.
35
+
36
+ Supports :class:`RectRegion`, :class:`CircleRegion`, and :class:`PolygonRegion`.
37
+ Raises ``TypeError`` for unknown region types.
38
+ """
39
+ if isinstance(region, RectRegion):
40
+ return point_in_rect(px, py, region)
41
+ elif isinstance(region, CircleRegion):
42
+ return point_in_circle(px, py, region)
43
+ elif isinstance(region, PolygonRegion):
44
+ return point_in_polygon(px, py, region)
45
+ raise TypeError(f"Unknown region type: {type(region).__name__}")
core/inspector.py ADDED
@@ -0,0 +1,66 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass, field
3
+ from typing import List, Optional
4
+
5
+ from .node import InspectableObject
6
+
7
+
8
+ @dataclass
9
+ class BoxSpec:
10
+ """Describes one box in the inspector stack.
11
+
12
+ Attributes:
13
+ object: The source InspectableObject.
14
+ path_names: Full path from root to this object (e.g. ``["Square 2", "Circle"]``).
15
+ properties: Snapshot of the object's properties keyed by name.
16
+ """
17
+ object: InspectableObject
18
+ path_names: List[str] = field(default_factory=list)
19
+ properties: dict = field(default_factory=dict)
20
+
21
+ @classmethod
22
+ def from_object(cls, obj: InspectableObject) -> BoxSpec:
23
+ """Build a BoxSpec by snapshotting *obj*'s path and properties."""
24
+ return cls(
25
+ object=obj,
26
+ path_names=obj.path_names(),
27
+ properties={k: v for k, v in obj.properties.items()},
28
+ )
29
+
30
+
31
+ class InspectorSystem:
32
+ """Walks the object tree to produce an ordered inspection stack.
33
+
34
+ The stack walks upward from the selected object through ``show_parent_box``
35
+ ancestors, optionally reversing so root appears first (ascending order).
36
+
37
+ Attributes:
38
+ ascending: If True, the stack is ordered root-to-leaf.
39
+ """
40
+
41
+ def __init__(self, ascending: bool = True):
42
+ self.ascending = ascending
43
+
44
+ def get_box_stack(self, obj: Optional[InspectableObject]) -> List[BoxSpec]:
45
+ """Build the inspector stack for *obj*.
46
+
47
+ Walks up the parent chain while ``show_parent_box`` is True,
48
+ returning a list of :class:`BoxSpec` objects. The order respects
49
+ ``self.ascending``.
50
+ """
51
+ if obj is None:
52
+ return []
53
+ boxes: List[BoxSpec] = []
54
+ cursor: Optional[InspectableObject] = obj
55
+ while cursor is not None:
56
+ boxes.append(BoxSpec.from_object(cursor))
57
+ if not cursor.show_parent_box:
58
+ break
59
+ cursor = cursor.parent
60
+ if self.ascending:
61
+ boxes.reverse()
62
+ return boxes
63
+
64
+ def set_ascending(self, ascending: bool) -> None:
65
+ """Toggle the stack ordering for subsequent ``get_box_stack`` calls."""
66
+ self.ascending = ascending
core/interaction.py ADDED
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass, field
3
+ from typing import Callable, List, Optional
4
+
5
+ from .inspector import BoxSpec, InspectorSystem
6
+ from .node import InspectableObject
7
+ from .selection import SelectionState
8
+ from .viewport_system import ViewportSystem
9
+
10
+
11
+ @dataclass
12
+ class InteractionController:
13
+ """Orchestrates click handling between the viewport, selection, and inspector.
14
+
15
+ Wires together :class:`ViewportSystem`, :class:`SelectionState`, and
16
+ :class:`InspectorSystem` so that a single click can hit-test, update
17
+ selection, refresh the viewport, and notify a callback.
18
+
19
+ Attributes:
20
+ selection: Shared selection state.
21
+ viewport: Viewport system for hit-testing.
22
+ inspector: Inspector system for building the inspection stack.
23
+ on_selection_changed: Optional callback invoked after every selection change.
24
+ """
25
+ selection: SelectionState
26
+ viewport: ViewportSystem
27
+ inspector: InspectorSystem
28
+ on_selection_changed: Optional[Callable[[], None]] = None
29
+
30
+ def handle_click(self, px: float, py: float) -> Optional[InspectableObject]:
31
+ """Hit-test at (*px*, *py*), update selection, refresh, and notify.
32
+
33
+ Returns the newly selected object (or ``None`` if deselected).
34
+ """
35
+ hit = self.viewport.hit_test(px, py)
36
+ if hit is not None:
37
+ self.selection.select(hit.target)
38
+ else:
39
+ self.selection.deselect()
40
+ self.viewport.refresh()
41
+ if self.on_selection_changed is not None:
42
+ self.on_selection_changed()
43
+ return self.selection.current
44
+
45
+ def get_inspector_stack(self) -> List[BoxSpec]:
46
+ """Build the inspector stack for the currently selected object."""
47
+ return self.inspector.get_box_stack(self.selection.current)
48
+
49
+ def get_clickable_at(self, px: float, py: float) -> Optional[InspectableObject]:
50
+ """Return the clickable object at (*px*, *py*) without changing selection."""
51
+ hit = self.viewport.hit_test(px, py)
52
+ if hit is not None:
53
+ return hit.target
54
+ return None
55
+
56
+ def select_object(self, obj: Optional[InspectableObject]) -> None:
57
+ """Programmatically select *obj*, refresh the viewport, and notify."""
58
+ self.selection.select(obj)
59
+ self.viewport.refresh()
60
+ if self.on_selection_changed is not None:
61
+ self.on_selection_changed()
core/node.py ADDED
@@ -0,0 +1,119 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass, field
3
+ from typing import Any, Optional
4
+
5
+
6
+ PROPERTY_TYPES = {"Literal", "Float", "Int", "Bool", "Color", "Vector2", "Vector3"}
7
+
8
+
9
+ @dataclass
10
+ class Property:
11
+ """A named, typed value attached to an InspectableObject.
12
+
13
+ Attributes:
14
+ name: Display name for the property.
15
+ type: One of PROPERTY_TYPES (e.g. ``"Literal"``, ``"Float"``, ``"Color"``).
16
+ value: Current runtime value.
17
+ default: Optional default value.
18
+ """
19
+ name: str
20
+ type: str
21
+ value: Any = None
22
+ default: Any = None
23
+
24
+ def __post_init__(self):
25
+ if self.type not in PROPERTY_TYPES:
26
+ raise ValueError(f"Unknown property type '{self.type}'. Valid: {PROPERTY_TYPES}")
27
+
28
+
29
+ @dataclass
30
+ class InspectableObject:
31
+ """A node in the inspectable object tree.
32
+
33
+ Each object has a name, optional parent/children, and a dict of
34
+ ``Property`` instances. The ``show_parent_box`` flag controls whether
35
+ the inspector should walk up to parents when building the inspection
36
+ stack.
37
+
38
+ Attributes:
39
+ name: Human-readable label.
40
+ parent: Parent node (set automatically by ``add_child``).
41
+ children: Direct child nodes.
42
+ properties: Keyed by property name.
43
+ show_parent_box: If True, the inspector includes this object's
44
+ parent when computing the inspection stack.
45
+ """
46
+ name: str
47
+ parent: Optional[InspectableObject] = None
48
+ children: list[InspectableObject] = field(default_factory=list)
49
+ properties: dict[str, Property] = field(default_factory=dict)
50
+ show_parent_box: bool = True
51
+
52
+ def __hash__(self):
53
+ return id(self)
54
+
55
+ def add_child(self, child: InspectableObject) -> None:
56
+ """Append *child* to ``children`` and set ``child.parent = self``."""
57
+ child.parent = self
58
+ self.children.append(child)
59
+
60
+ def remove_child(self, child: InspectableObject) -> None:
61
+ """Remove *child* from ``children`` and clear its parent link."""
62
+ if child in self.children:
63
+ child.parent = None
64
+ self.children.remove(child)
65
+
66
+ def add_property(self, prop: Property) -> None:
67
+ """Register *prop* under ``self.properties[prop.name]``."""
68
+ self.properties[prop.name] = prop
69
+
70
+ def get_property(self, name: str) -> Optional[Property]:
71
+ """Look up a property by name, or return ``None``."""
72
+ return self.properties.get(name)
73
+
74
+ def is_ancestor_of(self, other: InspectableObject) -> bool:
75
+ """Return True if ``self`` is an ancestor of *other*."""
76
+ cursor = other.parent
77
+ while cursor is not None:
78
+ if cursor is self:
79
+ return True
80
+ cursor = cursor.parent
81
+ return False
82
+
83
+ def is_descendant_of(self, other: InspectableObject) -> bool:
84
+ """Return True if ``self`` is a descendant of *other*."""
85
+ return other.is_ancestor_of(self)
86
+
87
+ def is_sibling_of(self, other: InspectableObject) -> bool:
88
+ """Return True if ``self`` and *other* share the same parent."""
89
+ return self is not other and self.parent is not None and self.parent is other.parent
90
+
91
+ def root(self) -> InspectableObject:
92
+ """Walk up the parent chain to the tree root."""
93
+ cursor = self
94
+ while cursor.parent is not None:
95
+ cursor = cursor.parent
96
+ return cursor
97
+
98
+ def depth(self) -> int:
99
+ """Number of ancestors between ``self`` and the root."""
100
+ d = 0
101
+ cursor = self
102
+ while cursor.parent is not None:
103
+ cursor = cursor.parent
104
+ d += 1
105
+ return d
106
+
107
+ def path(self) -> list[InspectableObject]:
108
+ """Full ancestry from root to ``self`` (inclusive)."""
109
+ result: list[InspectableObject] = []
110
+ cursor: Optional[InspectableObject] = self
111
+ while cursor is not None:
112
+ result.append(cursor)
113
+ cursor = cursor.parent
114
+ result.reverse()
115
+ return result
116
+
117
+ def path_names(self) -> list[str]:
118
+ """``.name`` of each node in ``.path()``."""
119
+ return [obj.name for obj in self.path()]
core/selection.py ADDED
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass, field
3
+ from typing import Optional, Set
4
+
5
+ from .node import InspectableObject
6
+
7
+
8
+ @dataclass
9
+ class SelectionState:
10
+ """Tracks the currently selected object and optional multi-selection set.
11
+
12
+ Maintains both a primary ``current`` selection (with ``previous`` for
13
+ undo/awareness) and an independent ``multi`` set for secondary highlights.
14
+
15
+ Attributes:
16
+ current: The primary selected object, or ``None``.
17
+ previous: The object that was ``current`` before the last ``select()`` call.
18
+ multi: Optional set of additionally highlighted objects.
19
+ """
20
+ current: Optional[InspectableObject] = None
21
+ previous: Optional[InspectableObject] = None
22
+ _multi: Optional[Set[InspectableObject]] = None
23
+
24
+ @property
25
+ def multi(self) -> Optional[Set[InspectableObject]]:
26
+ """The multi-selection set (read-only; use ``toggle_multi`` / ``clear_multi``)."""
27
+ return self._multi
28
+
29
+ @multi.setter
30
+ def multi(self, value: Optional[Set[InspectableObject]]) -> None:
31
+ self._multi = value
32
+
33
+ def select(self, obj: Optional[InspectableObject]) -> None:
34
+ """Set *obj* as the primary selection, moving the old ``current`` to ``previous``."""
35
+ self.previous = self.current
36
+ self.current = obj
37
+
38
+ def deselect(self) -> None:
39
+ """Clear the primary selection (shorthand for ``select(None)``)."""
40
+ self.select(None)
41
+
42
+ def is_selected(self, obj: InspectableObject) -> bool:
43
+ """Return True if *obj* is the primary selection."""
44
+ return self.current is obj
45
+
46
+ def toggle_multi(self, obj: InspectableObject) -> None:
47
+ """Add or remove *obj* from the multi-selection set."""
48
+ if self._multi is None:
49
+ self._multi = {obj} if self.current is not None else set()
50
+ if obj in self._multi:
51
+ self._multi.discard(obj)
52
+ if not self._multi:
53
+ self._multi = None
54
+ else:
55
+ self._multi.add(obj)
56
+
57
+ def clear_multi(self) -> None:
58
+ """Empty the multi-selection set."""
59
+ self._multi = None
60
+
61
+ def editing_group_root(self) -> Optional[InspectableObject]:
62
+ """Root of the tree containing ``current``, or ``None``."""
63
+ if self.current is None:
64
+ return None
65
+ return self.current.root()
66
+
67
+ def is_within_same_group(self, obj: InspectableObject) -> bool:
68
+ """Return True if *obj* shares the same root tree as ``current``."""
69
+ group = self.editing_group_root()
70
+ if group is None:
71
+ return False
72
+ return obj.root() is group
core/viewport.py ADDED
@@ -0,0 +1,169 @@
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass, field
3
+ from typing import List, Optional, Protocol, Union
4
+
5
+ from .node import InspectableObject
6
+ from .selection import SelectionState
7
+
8
+
9
+ @dataclass
10
+ class RectRegion:
11
+ """An axis-aligned rectangular click region."""
12
+ x: float
13
+ y: float
14
+ width: float
15
+ height: float
16
+
17
+
18
+ @dataclass
19
+ class CircleRegion:
20
+ """A circular click region defined by centre and radius."""
21
+ cx: float
22
+ cy: float
23
+ radius: float
24
+
25
+
26
+ @dataclass
27
+ class PolygonRegion:
28
+ """An arbitrary polygon click region defined by a list of (x, y) vertices."""
29
+ points: list[tuple[float, float]]
30
+
31
+
32
+ ClickRegion = Union[RectRegion, CircleRegion, PolygonRegion]
33
+
34
+
35
+ class Rule(Protocol):
36
+ """Protocol for visibility/selectability rules.
37
+
38
+ A rule is a callable that takes the current :class:`SelectionState`
39
+ and the target :class:`InspectableObject` and returns ``True`` if the
40
+ condition is met.
41
+ """
42
+ def __call__(self, selection: SelectionState, obj: InspectableObject) -> bool: ...
43
+
44
+
45
+ @dataclass
46
+ class BooleanRule:
47
+ """Always returns a fixed boolean value."""
48
+ flag: bool
49
+
50
+ def __call__(self, selection: SelectionState, obj: InspectableObject) -> bool:
51
+ return self.flag
52
+
53
+
54
+ @dataclass
55
+ class ParentSelectedRule:
56
+ """True when the object's immediate parent is selected."""
57
+ def __call__(self, selection: SelectionState, obj: InspectableObject) -> bool:
58
+ if obj.parent is None:
59
+ return False
60
+ return selection.is_selected(obj.parent)
61
+
62
+
63
+ @dataclass
64
+ class SelfOrAncestorSelectedRule:
65
+ """True when the object itself (or any ancestor of it) is the primary selection."""
66
+ def __call__(self, selection: SelectionState, obj: InspectableObject) -> bool:
67
+ cursor: Optional[InspectableObject] = selection.current
68
+ while cursor is not None:
69
+ if cursor is obj:
70
+ return True
71
+ cursor = cursor.parent
72
+ return False
73
+
74
+
75
+ @dataclass
76
+ class SiblingSelectedRule:
77
+ """True when a sibling (same parent) of the object is the primary selection."""
78
+ def __call__(self, selection: SelectionState, obj: InspectableObject) -> bool:
79
+ if obj.parent is None or selection.current is None:
80
+ return False
81
+ return (
82
+ selection.current is not obj
83
+ and selection.current.parent is obj.parent
84
+ )
85
+
86
+
87
+ @dataclass
88
+ class AncestorSelectedRule:
89
+ """True when any ancestor (parent, grandparent, ...) is the primary selection."""
90
+ def __call__(self, selection: SelectionState, obj: InspectableObject) -> bool:
91
+ cursor: Optional[InspectableObject] = obj.parent
92
+ while cursor is not None:
93
+ if selection.is_selected(cursor):
94
+ return True
95
+ cursor = cursor.parent
96
+ return False
97
+
98
+
99
+ @dataclass
100
+ class SameGroupRule:
101
+ """True when the object is in the same root tree as the primary selection."""
102
+ def __call__(self, selection: SelectionState, obj: InspectableObject) -> bool:
103
+ return selection.is_within_same_group(obj)
104
+
105
+
106
+ @dataclass
107
+ class AndRule:
108
+ """True only when **all** sub-rules return True."""
109
+ rules: List[Rule]
110
+
111
+ def __call__(self, selection: SelectionState, obj: InspectableObject) -> bool:
112
+ return all(r(selection, obj) for r in self.rules)
113
+
114
+
115
+ @dataclass
116
+ class OrRule:
117
+ """True when **any** sub-rule returns True."""
118
+ rules: List[Rule]
119
+
120
+ def __call__(self, selection: SelectionState, obj: InspectableObject) -> bool:
121
+ return any(r(selection, obj) for r in self.rules)
122
+
123
+
124
+ @dataclass
125
+ class NotRule:
126
+ """Inverts the result of a single sub-rule."""
127
+ rule: Rule
128
+
129
+ def __call__(self, selection: SelectionState, obj: InspectableObject) -> bool:
130
+ return not self.rule(selection, obj)
131
+
132
+
133
+ @dataclass
134
+ class ViewportElement:
135
+ """Binds an :class:`InspectableObject` to its on-screen representation.
136
+
137
+ Controls visibility, selectability, and the click region used for
138
+ hit-testing.
139
+
140
+ Attributes:
141
+ target: The backing data object.
142
+ click_region: Spatial region for hit-testing (or ``None`` to disable clicks).
143
+ visible: Static visibility flag (used when ``visible_rules`` is empty).
144
+ selectable: Static selectability flag (used when ``selectable_rules`` is empty).
145
+ visible_rules: Dynamic rules governing visibility.
146
+ selectable_rules: Dynamic rules governing selectability.
147
+ """
148
+ target: InspectableObject
149
+ click_region: Optional[ClickRegion] = None
150
+ visible: bool = False
151
+ selectable: bool = False
152
+ visible_rules: list[Rule] = field(default_factory=list)
153
+ selectable_rules: list[Rule] = field(default_factory=list)
154
+
155
+ def evaluate_visibility(self, selection: SelectionState) -> bool:
156
+ """Evaluate dynamic visibility rules, falling back to the static ``visible`` flag."""
157
+ if not self.visible_rules:
158
+ return self.visible
159
+ return all(rule(selection, self.target) for rule in self.visible_rules)
160
+
161
+ def evaluate_selectability(self, selection: SelectionState) -> bool:
162
+ """Evaluate dynamic selectability rules, falling back to the static ``selectable`` flag."""
163
+ if not self.selectable_rules:
164
+ return self.selectable
165
+ return all(rule(selection, self.target) for rule in self.selectable_rules)
166
+
167
+ def is_clickable(self, selection: SelectionState) -> bool:
168
+ """An element is clickable when it is both visible and selectable."""
169
+ return self.evaluate_visibility(selection) and self.evaluate_selectability(selection)