Skip to main content

aetna_core/tree/
identity.rs

1//! Identity, source, and interaction-flag modifiers for [`El`].
2
3use std::panic::Location;
4
5use super::geometry::Sides;
6use super::node::El;
7use super::semantics::{Kind, Source};
8
9/// Configuration for [`El::hover_alpha`] — the rest and peak alpha
10/// endpoints for a node whose opacity binds to the **subtree
11/// interaction envelope** (max of hover, focus, and press over the
12/// subtree rooted at this node).
13///
14/// `rest` is the drawn alpha when no descendant of this node is
15/// currently the active hover, focus, or press target. `peak` is the
16/// drawn alpha at full envelope. Linear interpolation between the two
17/// follows the eased subtree envelope (0..1).
18///
19/// Both fields are clamped to `[0.0, 1.0]` by [`El::hover_alpha`].
20/// Typical use is `rest < peak` ("reveal on interaction"), but the
21/// representation accepts `rest > peak` ("fade out on interaction") and
22/// sub-1.0 peaks for subtle affordances.
23#[derive(Clone, Copy, Debug, PartialEq)]
24pub struct HoverAlpha {
25    pub rest: f32,
26    pub peak: f32,
27}
28
29impl El {
30    pub fn new(kind: Kind) -> Self {
31        Self {
32            kind,
33            ..Default::default()
34        }
35    }
36
37    // ---- Identity / source ----
38    pub fn key(mut self, k: impl Into<String>) -> Self {
39        self.key = Some(k.into());
40        self
41    }
42
43    pub fn block_pointer(mut self) -> Self {
44        self.block_pointer = true;
45        self
46    }
47
48    /// Expand this node's pointer hit target without changing layout
49    /// or paint. Hover, press, cursor, tooltip, and click routing all
50    /// use the expanded target; [`UiEvent::target_rect`][crate::UiEvent::target_rect]
51    /// still reports the node's transformed visual rect from layout.
52    ///
53    /// Keep this conservative. It is for controls whose effective
54    /// interaction region is intentionally larger than their drawn
55    /// chrome, not for making unrelated gutters activate nearby UI.
56    pub fn hit_overflow(mut self, outset: impl Into<Sides>) -> Self {
57        self.hit_overflow = outset.into();
58        self
59    }
60
61    pub fn focusable(mut self) -> Self {
62        self.focusable = true;
63        self
64    }
65
66    /// Show the focus ring on this node even when focus arrived via
67    /// pointer click. Default focus-ring behavior follows the web
68    /// platform's `:focus-visible` rule — ring on Tab, no ring on
69    /// click. Widgets where the ring is meaningful regardless of
70    /// source — text input, text area — opt in here so clicking into
71    /// the field still raises the "now active" affordance. Implies
72    /// nothing about focusability; pair with `.focusable()`.
73    pub fn always_show_focus_ring(mut self) -> Self {
74        self.always_show_focus_ring = true;
75        self
76    }
77
78    /// Opt this node into the library's text-selection system. The
79    /// node must also carry an explicit `.key(...)`; selection requires
80    /// stable identity across rebuilds the same way focus does.
81    pub fn selectable(mut self) -> Self {
82        self.selectable = true;
83        self
84    }
85
86    /// Attach source-backed copy/hit-test text for this selectable
87    /// node. The node still needs `.selectable().key(...)`; this only
88    /// changes how selection offsets map to copied text.
89    pub fn selection_source(mut self, source: crate::selection::SelectionSource) -> Self {
90        self.selection_source = Some(source);
91        self
92    }
93
94    /// Opt this node into raw key capture when focused. While this
95    /// node is the focused target, the library's Tab/Enter/Escape
96    /// defaults are bypassed and raw `KeyDown` events are delivered for
97    /// the widget to interpret. Implies `focusable`.
98    pub fn capture_keys(mut self) -> Self {
99        self.capture_keys = true;
100        self.focusable = true;
101        self
102    }
103
104    /// Multiply this element's paint opacity by the nearest focusable
105    /// ancestor's focus envelope.
106    pub fn alpha_follows_focused_ancestor(mut self) -> Self {
107        self.alpha_follows_focused_ancestor = true;
108        self
109    }
110
111    /// Multiply this node's paint opacity by the runtime's caret blink
112    /// alpha.
113    pub fn blink_when_focused(mut self) -> Self {
114        self.blink_when_focused = true;
115        self
116    }
117
118    /// Borrow hover and press visual envelopes from the nearest
119    /// focusable ancestor.
120    pub fn state_follows_interactive_ancestor(mut self) -> Self {
121        self.state_follows_interactive_ancestor = true;
122        self
123    }
124
125    /// Bind this element's paint opacity to the subtree interaction
126    /// envelope — the `max` of hover, focus, and press for the subtree
127    /// rooted at this element.
128    ///
129    /// At rest (no descendant is the active hover, focus, or press
130    /// target) the element paints at `rest`. At full envelope it paints
131    /// at `peak`. Both are clamped to `[0.0, 1.0]`, with linear
132    /// interpolation in between following the eased envelope.
133    ///
134    /// "Subtree" matches CSS `:hover` semantics: hovering, focusing, or
135    /// pressing *any descendant* keeps the element revealed. A
136    /// hover-revealed close icon stays visible while the cursor moves
137    /// across the tab body or while the tab is keyboard-focused; an
138    /// action pill stays visible while the cursor moves between
139    /// focusable buttons inside it. The trigger isn't strictly
140    /// "hover" — focus and press also count — but `hover` is the
141    /// dominant case and the name reflects it.
142    ///
143    /// Layout-neutral — the element keeps its computed rect at all
144    /// times. Use for hover-revealed close buttons, secondary actions
145    /// on list rows, hover-only validation icons, and other
146    /// "show on interaction" patterns where the surrounding layout
147    /// shouldn't shift.
148    ///
149    /// # Beyond alpha
150    ///
151    /// For the other common hover affordances — Material-style lift
152    /// (`translate_y`), button-pop (`scale`), tint shift (`fill`) —
153    /// drive the prop from app code using
154    /// [`crate::BuildCx::is_hovering_within`] plus
155    /// [`Self::animate`]:
156    ///
157    /// ```ignore
158    /// fn build(&self, cx: &BuildCx) -> El {
159    ///     let lifted = cx.is_hovering_within("card");
160    ///     card([...])
161    ///         .key("card")
162    ///         .focusable()
163    ///         .translate(0.0, if lifted { -2.0 } else { 0.0 })
164    ///         .scale(if lifted { 1.02 } else { 1.0 })
165    ///         .animate(Timing::SPRING_QUICK)
166    /// }
167    /// ```
168    ///
169    /// `is_hovering_within` reads the same subtree predicate
170    /// `hover_alpha` consumes (CSS `:hover`-style cascade). `animate`
171    /// eases the prop between the two build values across frames, so
172    /// the transition is smooth without per-channel declarative API.
173    /// `hover_alpha` itself is the alpha-channel shorthand — it skips
174    /// the boolean-to-value conversion and the per-node `animate`
175    /// allocation, since alpha is the dominant hover affordance.
176    pub fn hover_alpha(mut self, rest: f32, peak: f32) -> Self {
177        self.hover_alpha = Some(HoverAlpha {
178            rest: rest.clamp(0.0, 1.0),
179            peak: peak.clamp(0.0, 1.0),
180        });
181        self
182    }
183
184    pub fn at(mut self, file: &'static str, line: u32) -> Self {
185        self.source = Source {
186            file,
187            line,
188            from_library: false,
189        };
190        self
191    }
192
193    /// Set source from a `Location` (used internally by
194    /// `#[track_caller]` constructors).
195    pub fn at_loc(mut self, loc: &'static Location<'static>) -> Self {
196        self.source = Source::from_caller(loc);
197        self
198    }
199
200    /// Mark this El as constructed inside an aetna library closure
201    /// where `#[track_caller]` doesn't reach user code (e.g. the
202    /// `.map(|item| ...)` body inside `tabs_list`, `radio_group`,
203    /// etc.). The lint pass uses this flag to walk blame attribution
204    /// upward to the nearest user-source ancestor instead of pointing
205    /// findings at aetna-core internals. User code never needs to call
206    /// this.
207    pub fn from_library(mut self) -> Self {
208        self.source.from_library = true;
209        self
210    }
211}