euv_core/scene/tree/impl.rs
1use super::*;
2
3/// Default scene tree with a pre-created root `View` node.
4impl Default for SceneTree {
5 /// Allocates a new `SceneTree` containing a root container node.
6 ///
7 /// # Returns
8 ///
9 /// - `Self` - Initialized scene tree.
10 fn default() -> Self {
11 let root_style: Style = Style::default()
12 .column()
13 .width(Length::Percent(100.0))
14 .height(Length::Percent(100.0));
15 let root_node: SceneNode = SceneNode::new(1, NodeKind::View, root_style);
16 Self {
17 nodes: vec![root_node],
18 free_list: Vec::new(),
19 root: NodeId::new(0, 1),
20 focus: FocusManager::default(),
21 revision: 1,
22 transitions: Vec::new(),
23 caret_visible: true,
24 }
25 }
26}
27
28/// Core retained scene graph mutation and traversal operations.
29impl SceneTree {
30 /// Allocates a new node of `kind` with initial `style`.
31 ///
32 /// # Arguments
33 ///
34 /// - `&Self` - Mutable scene tree.
35 /// - `NodeKind` - Semantic node kind.
36 /// - `Style` - Initial style.
37 ///
38 /// # Returns
39 ///
40 /// - `NodeId` - Generation-checked node handle.
41 pub fn create_node(&mut self, kind: NodeKind, style: Style) -> NodeId {
42 let id: NodeId = if let Some(index) = self.get_mut_free_list().pop() {
43 let slot: &mut SceneNode = &mut self.get_mut_nodes()[index as usize];
44 let next_gen: u32 = slot.get_generation().wrapping_add(1).max(1);
45 *slot = SceneNode::new(next_gen, kind, style);
46 NodeId::new(index, next_gen)
47 } else {
48 let index: u32 = self.get_nodes().len() as u32;
49 self.get_mut_nodes().push(SceneNode::new(1, kind, style));
50 NodeId::new(index, 1)
51 };
52 let next_rev: u64 = self.get_revision().wrapping_add(1);
53 self.set_revision(next_rev);
54 id
55 }
56
57 /// Creates a container `View` node.
58 ///
59 /// # Arguments
60 ///
61 /// - `&Self` - Mutable scene tree.
62 /// - `Style` - Initial box style.
63 ///
64 /// # Returns
65 ///
66 /// - `NodeId` - Created node handle.
67 pub fn create_view(&mut self, style: Style) -> NodeId {
68 self.create_node(NodeKind::View, style)
69 }
70
71 /// Creates a `Text` node holding `content`.
72 ///
73 /// # Arguments
74 ///
75 /// - `&Self` - Mutable scene tree.
76 /// - `String` - Initial UTF-8 text.
77 /// - `Style` - Initial text and box style.
78 ///
79 /// # Returns
80 ///
81 /// - `NodeId` - Created text node handle.
82 pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
83 self.create_node(NodeKind::Text(content), style)
84 }
85
86 /// Creates an editable `Input` node.
87 ///
88 /// # Arguments
89 ///
90 /// - `&Self` - Mutable scene tree.
91 /// - `InputNodeState` - Initial input state.
92 /// - `Style` - Initial input style.
93 ///
94 /// # Returns
95 ///
96 /// - `NodeId` - Created input node handle.
97 pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
98 self.create_node(NodeKind::Input(state), style)
99 }
100
101 /// Creates an `Image` node displaying `buffer`.
102 ///
103 /// # Arguments
104 ///
105 /// - `&Self` - Mutable scene tree.
106 /// - `ImageBuffer` - Decoded RGBA8 image buffer.
107 /// - `Style` - Initial image style.
108 ///
109 /// # Returns
110 ///
111 /// - `NodeId` - Created image node handle.
112 pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
113 self.create_node(NodeKind::Image(buffer), style)
114 }
115
116 /// Creates a `ScrollView` container with `Overflow::Scroll`.
117 ///
118 /// # Arguments
119 ///
120 /// - `&Self` - Mutable scene tree.
121 /// - `Style` - Initial scroll container style.
122 ///
123 /// # Returns
124 ///
125 /// - `NodeId` - Created scroll view handle.
126 pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
127 self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
128 }
129
130 /// Creates a custom `Canvas` node bound to `painter`.
131 ///
132 /// # Arguments
133 ///
134 /// - `&Self` - Mutable scene tree.
135 /// - `Style` - Initial canvas style.
136 /// - `CanvasDrawCallback` - Draw callback invoked on each paint pass.
137 ///
138 /// # Returns
139 ///
140 /// - `NodeId` - Created canvas node handle.
141 pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
142 let id: NodeId = self.create_node(NodeKind::Canvas, style);
143 if let Some(node) = self.get_node_mut(id) {
144 node.set_canvas_painter(Some(painter));
145 }
146 id
147 }
148
149 /// Creates an overlay `Portal` node rendered in the top stacking context.
150 ///
151 /// # Arguments
152 ///
153 /// - `&Self` - Mutable scene tree.
154 /// - `Style` - Initial portal style.
155 ///
156 /// # Returns
157 ///
158 /// - `NodeId` - Created portal node handle.
159 pub fn create_portal(&mut self, style: Style) -> NodeId {
160 self.create_node(NodeKind::Portal, style)
161 }
162
163 /// Creates a logical `Fragment` grouping node.
164 ///
165 /// # Arguments
166 ///
167 /// - `&Self` - Mutable scene tree.
168 ///
169 /// # Returns
170 ///
171 /// - `NodeId` - Created fragment node handle.
172 pub fn create_fragment(&mut self) -> NodeId {
173 self.create_node(NodeKind::Fragment, Style::default())
174 }
175
176 /// Returns an immutable reference to a live node matching `id`.
177 ///
178 /// # Arguments
179 ///
180 /// - `&Self` - Scene tree reference.
181 /// - `NodeId` - Node handle.
182 ///
183 /// # Returns
184 ///
185 /// - `Option<&SceneNode>` - Live node reference if valid.
186 #[must_use]
187 pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
188 let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
189 if node.get_alive() && node.get_generation() == id.get_generation() {
190 Some(node)
191 } else {
192 None
193 }
194 }
195
196 /// Returns a mutable reference to a live node matching `id`.
197 ///
198 /// # Arguments
199 ///
200 /// - `&Self` - Mutable scene tree.
201 /// - `NodeId` - Node handle.
202 ///
203 /// # Returns
204 ///
205 /// - `Option<&mut SceneNode>` - Mutable live node reference if valid.
206 pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
207 let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
208 if node.get_alive() && node.get_generation() == id.get_generation() {
209 Some(node)
210 } else {
211 None
212 }
213 }
214
215 /// Returns total count of live scene nodes.
216 ///
217 /// # Arguments
218 ///
219 /// - `&Self` - Scene tree reference.
220 ///
221 /// # Returns
222 ///
223 /// - `usize` - Number of live nodes in the arena.
224 #[must_use]
225 pub fn live_node_count(&self) -> usize {
226 self.get_nodes()
227 .iter()
228 .filter(|node: &&SceneNode| node.get_alive())
229 .count()
230 }
231
232 /// Appends `child` to `parent` and marks layout and paint dirty upward.
233 ///
234 /// # Arguments
235 ///
236 /// - `&Self` - Mutable scene tree.
237 /// - `NodeId` - Parent container node.
238 /// - `NodeId` - Child node to attach.
239 pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
240 if parent == child {
241 return;
242 }
243 let prev_parent: Option<NodeId> = self.get_node(child).and_then(SceneNode::parent_id);
244 if let Some(old_parent) = prev_parent
245 && let Some(old_node) = self.get_node_mut(old_parent)
246 {
247 old_node
248 .get_mut_children()
249 .retain(|item: &NodeId| *item != child);
250 if old_parent != parent {
251 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
252 }
253 }
254 if let Some(child_node) = self.get_node_mut(child) {
255 child_node.set_parent(Some(parent));
256 } else {
257 return;
258 }
259 if let Some(parent_node) = self.get_node_mut(parent) {
260 parent_node.get_mut_children().push(child);
261 }
262 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
263 }
264
265 /// Appends multiple `children` to `parent` in a single dirty-marking pass with pre-reserved capacity.
266 ///
267 /// # Arguments
268 ///
269 /// - `&Self` - Mutable scene tree.
270 /// - `NodeId` - Parent container node.
271 /// - `&[NodeId]` - Ordered child nodes to append.
272 pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
273 if children.is_empty() || self.get_node(parent).is_none() {
274 return;
275 }
276 let mut attached: Vec<NodeId> = Vec::with_capacity(children.len());
277 for child in children.iter().copied() {
278 if child == parent {
279 continue;
280 }
281 let prev_parent: Option<NodeId> = self
282 .get_node(child)
283 .and_then(|node: &SceneNode| node.parent_id());
284 if let Some(old_parent) = prev_parent {
285 if let Some(old_node) = self.get_node_mut(old_parent) {
286 old_node
287 .get_mut_children()
288 .retain(|id: &NodeId| *id != child);
289 }
290 if old_parent != parent {
291 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
292 }
293 }
294 if let Some(child_node) = self.get_node_mut(child) {
295 child_node.set_parent(Some(parent));
296 attached.push(child);
297 }
298 }
299 if attached.is_empty() {
300 return;
301 }
302 if let Some(parent_node) = self.get_node_mut(parent) {
303 parent_node.get_mut_children().extend(attached);
304 }
305 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
306 }
307
308 /// Replaces all children of `parent` with `new_children`, disposing previous subtrees cleanly.
309 ///
310 /// # Arguments
311 ///
312 /// - `&Self` - Mutable scene tree.
313 /// - `NodeId` - Parent container node.
314 /// - `Vec<NodeId>` - Replacement ordered children.
315 pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
316 let old_children: Vec<NodeId> = match self.get_node_mut(parent) {
317 Some(node) => take(node.get_mut_children()),
318 None => return,
319 };
320 for old_child in old_children.into_iter() {
321 if !new_children.contains(&old_child) {
322 self.dispose_subtree(old_child);
323 }
324 }
325 for child in new_children.iter().copied() {
326 if let Some(child_node) = self.get_node_mut(child) {
327 child_node.set_parent(Some(parent));
328 }
329 }
330 if let Some(parent_node) = self.get_node_mut(parent) {
331 parent_node.set_children(new_children);
332 }
333 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
334 }
335
336 /// Surgically updates a node's `Style`, only marking layout dirty when `LayoutStyle` changed.
337 ///
338 /// # Arguments
339 ///
340 /// - `&Self` - Mutable scene tree.
341 /// - `NodeId` - Target node handle.
342 /// - `Style` - Replacement compiled style.
343 pub fn set_style(&mut self, id: NodeId, style: Style) {
344 let dirty_mask: u16 = match self.get_node_mut(id) {
345 Some(node) => {
346 let prev: Style = node.get_style();
347 if prev == style {
348 return;
349 }
350 let mut mask: u16 = DIRTY_PAINT;
351 if prev.get_layout() != style.get_layout() || prev.get_text() != style.get_text() {
352 mask |= DIRTY_LAYOUT | DIRTY_TEXT;
353 }
354 node.set_style(style);
355 mask
356 }
357 None => return,
358 };
359 self.mark_dirty(id, dirty_mask);
360 }
361
362 /// Surgically updates the UTF-8 string of a `NodeKind::Text` node.
363 ///
364 /// # Arguments
365 ///
366 /// - `&Self` - Mutable scene tree.
367 /// - `NodeId` - Target text node handle.
368 /// - `String` - Replacement text string.
369 pub fn set_text(&mut self, id: NodeId, text: String) {
370 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
371 Some(node) => {
372 let layout: LayoutStyle = node.get_style().get_layout();
373 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
374 && matches!(layout.get_height(), Length::Px(_));
375 match node.get_mut_kind() {
376 NodeKind::Text(current) => {
377 if *current == text {
378 (false, has_fixed)
379 } else {
380 *current = text;
381 (true, has_fixed)
382 }
383 }
384 _ => (false, false),
385 }
386 }
387 None => (false, false),
388 };
389 if changed {
390 let mask: u16 = if fixed_size {
391 DIRTY_PAINT
392 } else {
393 DIRTY_TEXT_CHANGE_MASK
394 };
395 self.mark_dirty(id, mask);
396 }
397 }
398
399 /// Updates scroll offset on a scroll container without triggering full subtree re-layout.
400 ///
401 /// # Arguments
402 ///
403 /// - `&Self` - Mutable scene tree.
404 /// - `NodeId` - Target scroll container handle.
405 /// - `Point` - New scroll offset clamped to content bounds.
406 pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
407 let changed: bool = match self.get_node_mut(id) {
408 Some(node) => {
409 let layout_box: LayoutBox = node.get_layout_box();
410 let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
411 && layout_box.get_content_size().get_height() <= 0.0
412 && layout_box.get_content_bounds().get_width() <= 0.0
413 && layout_box.get_content_bounds().get_height() <= 0.0;
414 let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
415 Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
416 } else {
417 let max_x: f32 = (layout_box.get_content_size().get_width()
418 - layout_box.get_content_bounds().get_width())
419 .max(0.0);
420 let max_y: f32 = (layout_box.get_content_size().get_height()
421 - layout_box.get_content_bounds().get_height())
422 .max(0.0);
423 Point::new(
424 offset.get_x().clamp(0.0, max_x),
425 offset.get_y().clamp(0.0, max_y),
426 )
427 };
428 if layout_box.get_scroll_offset() == clamped {
429 false
430 } else {
431 node.get_mut_layout_box().set_scroll_offset(clamped);
432 true
433 }
434 }
435 None => false,
436 };
437 if changed {
438 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_PAINT);
439 }
440 }
441
442 /// Records virtualized scroll progress `(scroll_y, content_height)` on `id` for overlay scrollbar rendering.
443 ///
444 /// # Arguments
445 ///
446 /// - `&Self` - Mutable scene tree.
447 /// - `NodeId` - Target virtualized scroll container.
448 /// - `f32` - Active virtual vertical scroll offset in logical pixels.
449 /// - `f32` - Full virtualized content height in logical pixels.
450 pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
451 let changed: bool = match self.get_node_mut(id) {
452 Some(node) => {
453 let next: Option<(f32, f32)> = Some((scroll_y.max(0.0), content_height.max(1.0)));
454 if node.virtual_scroll_metrics() == next {
455 false
456 } else {
457 node.set_virtual_scroll(next);
458 true
459 }
460 }
461 None => false,
462 };
463 if changed {
464 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_PAINT);
465 }
466 }
467
468 /// Computes screen-space logical bounds for `id` after applying ancestor scroll offsets and transforms.
469 ///
470 /// # Arguments
471 ///
472 /// - `&Self` - Scene tree reference.
473 /// - `NodeId` - Target node handle.
474 ///
475 /// # Returns
476 ///
477 /// - `Option<Rect>` - Screen-space rectangle if the node is alive.
478 #[must_use]
479 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
480 let node: &SceneNode = self.get_node(id)?;
481 let raw: Rect = node.get_layout_box().get_bounds();
482 let off: Point = self.ancestor_scroll_offset(id);
483 let tr: Transform2D = node.get_style().get_paint().get_transform();
484 let mut tx: f32 = tr.get_translate_x();
485 let mut ty: f32 = tr.get_translate_y();
486 let mut cursor: Option<NodeId> = node.parent_id();
487 while let Some(pid) = cursor {
488 if let Some(pnode) = self.get_node(pid) {
489 let ptr: Transform2D = pnode.get_style().get_paint().get_transform();
490 tx += ptr.get_translate_x();
491 ty += ptr.get_translate_y();
492 if matches!(pnode.get_kind(), NodeKind::Portal)
493 || pnode.get_style().get_layout().get_position() == Position::Fixed
494 {
495 break;
496 }
497 cursor = pnode.parent_id();
498 } else {
499 break;
500 }
501 }
502 Some(Rect::new(
503 raw.get_x() - off.get_x() + tx,
504 raw.get_y() - off.get_y() + ty,
505 raw.get_width() * tr.get_scale_x(),
506 raw.get_height() * tr.get_scale_y(),
507 ))
508 }
509
510 /// Starts or smoothly retargets a paint/transform transition on `transition.get_node()`.
511 ///
512 /// # Arguments
513 ///
514 /// - `&Self` - Mutable scene tree.
515 /// - `NodeTransition` - Transition specification to run.
516 pub fn start_transition(&mut self, mut transition: NodeTransition) {
517 let target: NodeId = transition.get_node();
518 let had_active: bool = self
519 .get_transitions()
520 .iter()
521 .any(|tr: &NodeTransition| tr.get_node() == target);
522 self.get_mut_transitions()
523 .retain(|tr: &NodeTransition| tr.get_node() != target);
524 if had_active && let Some(node) = self.get_node(target) {
525 let paint: PaintStyle = node.get_style().get_paint();
526 let tr: Transform2D = paint.get_transform();
527 let cur_op: f32 = paint.get_opacity();
528 let cur_tx: f32 = tr.get_translate_x();
529 let cur_ty: f32 = tr.get_translate_y();
530 let cur_sc: f32 = tr.get_scale_x();
531 let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
532 .hypot(transition.get_to_ty() - transition.get_from_ty())
533 .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
534 let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
535 .hypot(transition.get_to_ty() - cur_ty)
536 .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
537 if full_dist > 0.01 {
538 let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
539 transition.set_duration((transition.get_duration() * ratio).max(0.05));
540 }
541 transition.set_from_opacity(cur_op);
542 transition.set_from_tx(cur_tx);
543 transition.set_from_ty(cur_ty);
544 transition.set_from_scale(cur_sc);
545 }
546 let (opacity, transform): (f32, Transform2D) = transition.sample();
547 let mut unhidden: bool = false;
548 if let Some(node) = self.get_node_mut(target) {
549 let mut style: Style = node.get_style();
550 if !transition.get_hide_on_complete()
551 && style.get_layout().get_display() == Display::None
552 {
553 style.get_mut_layout().set_display(Display::Flex);
554 unhidden = true;
555 }
556 style.get_mut_paint().set_opacity(opacity);
557 style.get_mut_paint().set_transform(transform);
558 node.set_style(style);
559 }
560 if unhidden {
561 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
562 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
563 } else {
564 self.mark_dirty(target, DIRTY_PAINT);
565 }
566 self.get_mut_transitions().push(transition);
567 }
568
569 /// Advances all active transitions by `dt_secs` and returns `true` if any node updated.
570 ///
571 /// # Arguments
572 ///
573 /// - `&Self` - Mutable scene tree.
574 /// - `f32` - Elapsed frame time in seconds.
575 ///
576 /// # Returns
577 ///
578 /// - `bool` - Whether at least one transition ticked on this frame.
579 pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
580 if self.get_transitions().is_empty() {
581 return false;
582 }
583 let step: f32 = dt_secs.clamp(0.001, 0.05);
584 let mut active: Vec<NodeTransition> = take(self.get_mut_transitions());
585 let mut remaining: Vec<NodeTransition> = Vec::with_capacity(active.len());
586 let mut any_updated: bool = false;
587 for mut tr in active.drain(..) {
588 let target: NodeId = tr.get_node();
589 if self.get_node(target).is_none() {
590 continue;
591 }
592 let total_span: f32 = tr.get_delay() + tr.get_duration();
593 let prev_elapsed: f32 = tr.get_elapsed();
594 let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
595 tr.set_elapsed(next_elapsed);
596 let done: bool = tr.is_complete();
597 let in_hold: bool = prev_elapsed > 0.0 && next_elapsed <= tr.get_delay() && !done;
598 if !in_hold {
599 let (opacity, transform): (f32, Transform2D) = tr.sample();
600 let hide: bool = done && tr.get_hide_on_complete();
601 if let Some(node) = self.get_node_mut(target) {
602 let mut style: Style = node.get_style();
603 style.get_mut_paint().set_opacity(opacity);
604 style.get_mut_paint().set_transform(transform);
605 if hide {
606 style.get_mut_layout().set_display(Display::None);
607 }
608 node.set_style(style);
609 }
610 if hide {
611 self.clear_subtree_hover(target);
612 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
613 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
614 } else {
615 self.mark_dirty(target, DIRTY_PAINT);
616 }
617 any_updated = true;
618 }
619 if !done {
620 remaining.push(tr);
621 }
622 }
623 self.set_transitions(remaining);
624 any_updated
625 }
626
627 /// Clears transient hover/active flags throughout the subtree rooted at `root` when an overlay hides.
628 ///
629 /// # Arguments
630 ///
631 /// - `&Self` - Mutable scene tree.
632 /// - `NodeId` - Root node being hidden.
633 fn clear_subtree_hover(&mut self, root: NodeId) {
634 let mut stack: Vec<NodeId> = vec![root];
635 while let Some(id) = stack.pop() {
636 let children: Vec<NodeId> = match self.get_node_mut(id) {
637 Some(node) => {
638 node.get_mut_interaction().set_hovered(false);
639 node.get_mut_interaction().set_pressed(false);
640 node.get_children().clone()
641 }
642 None => continue,
643 };
644 stack.extend(children);
645 }
646 }
647
648 /// Returns `true` while one or more node transitions are still running.
649 ///
650 /// # Arguments
651 ///
652 /// - `&Self` - Scene tree reference.
653 ///
654 /// # Returns
655 ///
656 /// - `bool` - Whether animations are active.
657 #[must_use]
658 pub fn has_active_transitions(&self) -> bool {
659 !self.get_transitions().is_empty()
660 }
661
662 /// Attaches a `Lifecycle` hook observer onto `id` for mount, activate, freeze, resume, unmount, and destroy dispatch.
663 ///
664 /// # Arguments
665 ///
666 /// - `&Self` - Mutable scene tree.
667 /// - `NodeId` - Target scene node handle.
668 /// - `Rc<dyn Lifecycle>` - Shared lifecycle hook observer.
669 pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
670 if let Some(node) = self.get_node_mut(id) {
671 node.add_lifecycle(hook);
672 }
673 }
674
675 /// Collects all `(NodeId, Rc<dyn Lifecycle>)` observers in the subtree rooted at `root`.
676 ///
677 /// # Arguments
678 ///
679 /// - `&Self` - Scene tree reference.
680 /// - `NodeId` - Subtree root handle.
681 ///
682 /// # Returns
683 ///
684 /// - `Vec<(NodeId, Rc<dyn Lifecycle>)>` - Ordered observers in pre-order traversal.
685 #[must_use]
686 pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
687 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
688 let mut stack: Vec<NodeId> = vec![root];
689 while let Some(current) = stack.pop() {
690 if let Some(node) = self.get_node(current) {
691 for hook in node.lifecycle_observers().into_iter() {
692 out.push((current, hook));
693 }
694 for child in node.get_children().iter().rev().copied() {
695 stack.push(child);
696 }
697 }
698 }
699 out
700 }
701
702 /// Cancels any active paint/transform transitions targeting nodes within the subtree rooted at `root`.
703 ///
704 /// # Arguments
705 ///
706 /// - `&Self` - Mutable scene tree.
707 /// - `NodeId` - Subtree root handle.
708 pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
709 if self.get_transitions().is_empty() {
710 return;
711 }
712 let mut ids: HashSet<NodeId> = HashSet::new();
713 let mut stack: Vec<NodeId> = vec![root];
714 while let Some(current) = stack.pop() {
715 if ids.insert(current)
716 && let Some(node) = self.get_node(current)
717 {
718 for child in node.get_children().iter().copied() {
719 stack.push(child);
720 }
721 }
722 }
723 self.get_mut_transitions()
724 .retain(|tr: &NodeTransition| !ids.contains(&tr.get_node()));
725 }
726
727 /// Attaches a reactive `Scope` to `id` so it automatically disposes when the node unmounts.
728 ///
729 /// # Arguments
730 ///
731 /// - `&Self` - Mutable scene tree.
732 /// - `NodeId` - Target node handle.
733 /// - `Scope` - Reactive ownership scope.
734 pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
735 if let Some(node) = self.get_node_mut(id) {
736 if let Some(existing) = node.owned_scope() {
737 existing.enter(|| {
738 on_cleanup(move || {
739 scope.dispose();
740 });
741 });
742 } else {
743 node.set_scope(Some(scope));
744 }
745 }
746 }
747
748 /// Marks `id` dirty with `mask` and propagates subtree dirty bits to ancestors in O(depth).
749 ///
750 /// # Arguments
751 ///
752 /// - `&Self` - Mutable scene tree.
753 /// - `NodeId` - Mutated node handle.
754 /// - `u16` - Dirty flag bits to set.
755 pub fn mark_dirty(&mut self, id: NodeId, mask: u16) {
756 let mut parent_opt: Option<NodeId> = match self.get_node_mut(id) {
757 Some(node) => {
758 node.get_mut_dirty().insert(mask);
759 node.parent_id()
760 }
761 None => return,
762 };
763 let mut ancestor_mask: u16 = DIRTY_NONE;
764 if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
765 ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
766 }
767 if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
768 ancestor_mask |= DIRTY_SUBTREE_PAINT;
769 }
770 while let Some(ancestor_id) = parent_opt {
771 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
772 let already: bool =
773 (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
774 ancestor.get_mut_dirty().insert(ancestor_mask);
775 if already {
776 break;
777 }
778 parent_opt = ancestor.parent_id();
779 } else {
780 break;
781 }
782 }
783 let next_rev: u64 = self.get_revision().wrapping_add(1);
784 self.set_revision(next_rev);
785 }
786
787 /// Computes accumulated ancestor scroll offset for `id` (zero for top-layer `Portal`/`Fixed` nodes).
788 ///
789 /// # Arguments
790 ///
791 /// - `&Self` - Scene tree reference.
792 /// - `NodeId` - Target node handle.
793 ///
794 /// # Returns
795 ///
796 /// - `Point` - Total scroll offset applied to `id`.
797 fn ancestor_scroll_offset(&self, id: NodeId) -> Point {
798 let Some(start) = self.get_node(id) else {
799 return Point::default();
800 };
801 if matches!(start.get_kind(), NodeKind::Portal)
802 || start.get_style().get_layout().get_position() == Position::Fixed
803 {
804 return Point::default();
805 }
806 let mut sx: f32 = 0.0;
807 let mut sy: f32 = 0.0;
808 let mut cursor: Option<NodeId> = start.parent_id();
809 while let Some(pid) = cursor {
810 if let Some(pnode) = self.get_node(pid) {
811 let off: Point = pnode.get_layout_box().get_scroll_offset();
812 sx += off.get_x();
813 sy += off.get_y();
814 if matches!(pnode.get_kind(), NodeKind::Portal)
815 || pnode.get_style().get_layout().get_position() == Position::Fixed
816 {
817 break;
818 }
819 cursor = pnode.parent_id();
820 } else {
821 break;
822 }
823 }
824 Point::new(sx, sy)
825 }
826
827 /// Returns `true` when `id` and every ancestor up to the root are alive, non-`Display::None`, and have positive opacity.
828 ///
829 /// # Arguments
830 ///
831 /// - `&Self` - Scene tree reference.
832 /// - `NodeId` - Target node handle.
833 ///
834 /// # Returns
835 ///
836 /// - `bool` - Whether the node is visibly rendered in the scene.
837 #[must_use]
838 pub fn is_node_visible(&self, id: NodeId) -> bool {
839 let mut cursor: Option<NodeId> = Some(id);
840 while let Some(cur) = cursor {
841 let Some(node) = self.get_node(cur) else {
842 return false;
843 };
844 if node.get_style().get_layout().get_display() == Display::None
845 || node.get_style().get_paint().get_opacity() <= 0.0
846 {
847 return false;
848 }
849 cursor = node.parent_id();
850 }
851 true
852 }
853
854 /// Collects the tight physical damage region from dirty paint/scroll nodes and clears paint dirty flags.
855 ///
856 /// # Arguments
857 ///
858 /// - `&Self` - Mutable scene tree.
859 /// - `f32` - Active display scale factor.
860 ///
861 /// # Returns
862 ///
863 /// - `DamageRegion` - Minimal damaged region, full damage on structural/layout change, or clean when idle.
864 pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
865 let mut full: bool = false;
866 let mut dirty_ids: Vec<(NodeId, Rect, f32)> = Vec::new();
867 for (idx, node) in self.get_nodes().iter().enumerate() {
868 if !node.get_alive() {
869 continue;
870 }
871 let bits: u16 = node.get_dirty().get_bits();
872 if (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
873 full = true;
874 break;
875 }
876 if (bits & (DIRTY_PAINT | DIRTY_SCROLL)) != 0 {
877 let b: Rect = node.get_layout_box().get_bounds();
878 if b.get_width() > 0.0 && b.get_height() > 0.0 {
879 let mut margin: f32 = 10.0;
880 if let Some(shadow) = node.get_style().get_paint().box_shadow() {
881 margin = margin.max(
882 shadow.get_blur_radius()
883 + shadow.get_spread_radius()
884 + shadow.get_offset_x().abs().max(shadow.get_offset_y().abs())
885 + 4.0,
886 );
887 }
888 let nid: NodeId = NodeId::new(idx as u32, node.get_generation());
889 dirty_ids.push((nid, b, margin));
890 } else if (bits & DIRTY_PAINT) != 0 {
891 full = true;
892 break;
893 }
894 }
895 }
896 let mut damage: DamageRegion = if full {
897 DamageRegion::full()
898 } else {
899 let mut region: DamageRegion = DamageRegion::default();
900 for (nid, raw_bounds, margin) in dirty_ids.into_iter() {
901 let off: Point = self.ancestor_scroll_offset(nid);
902 let base_phys: Rect = Rect::new(
903 ((raw_bounds.get_x() - off.get_x() - margin) * scale).floor(),
904 ((raw_bounds.get_y() - off.get_y() - margin) * scale).floor(),
905 ((raw_bounds.get_width() + margin * 2.0) * scale).ceil(),
906 ((raw_bounds.get_height() + margin * 2.0) * scale).ceil(),
907 );
908 region.add_rect(base_phys);
909 if let Some(screen_bounds) = self.node_screen_bounds(nid) {
910 let shifted_phys: Rect = Rect::new(
911 ((screen_bounds.get_x() - margin) * scale).floor(),
912 ((screen_bounds.get_y() - margin) * scale).floor(),
913 ((screen_bounds.get_width() + margin * 2.0) * scale).ceil(),
914 ((screen_bounds.get_height() + margin * 2.0) * scale).ceil(),
915 );
916 region.add_rect(shifted_phys);
917 }
918 }
919 region
920 };
921 let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
922 for node in self.get_mut_nodes().iter_mut() {
923 if node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0 {
924 node.get_mut_dirty().remove(clear_mask);
925 }
926 }
927 if full {
928 damage.set_full_damage(true);
929 }
930 damage
931 }
932
933 /// Recursively detaches and recycles `id`, returning all owned `Scope`s and `Lifecycle` observers for borrow-safe finalization.
934 ///
935 /// # Arguments
936 ///
937 /// - `&Self` - Mutable scene tree.
938 /// - `NodeId` - Subtree root handle to dispose.
939 ///
940 /// # Returns
941 ///
942 /// - `DisposedSubtreePayload` - Collected scopes and lifecycle observers to finalize outside any borrow.
943 pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
944 if id == self.get_root() {
945 return (Vec::new(), Vec::new());
946 }
947 self.cancel_subtree_transitions(id);
948 let mut stack: Vec<NodeId> = vec![id];
949 let mut scopes: Vec<Scope> = Vec::new();
950 let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
951 while let Some(current) = stack.pop() {
952 let children_opt: Option<Vec<NodeId>> = match self.get_node_mut(current) {
953 Some(node) => {
954 node.set_alive(false);
955 if let Some(scope) = node.owned_scope() {
956 scopes.push(scope);
957 }
958 for hook in node.take_lifecycles().into_iter() {
959 observers.push((current, hook));
960 }
961 node.set_scope(None);
962 node.set_parent(None);
963 node.set_canvas_painter(None);
964 node.set_handlers(EventHandlers::default());
965 let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
966 node.set_generation(next_gen);
967 Some(take(node.get_mut_children()))
968 }
969 None => None,
970 };
971 let Some(children) = children_opt else {
972 continue;
973 };
974 self.get_mut_free_list().push(current.get_index());
975 for child in children.into_iter() {
976 stack.push(child);
977 }
978 }
979 (scopes, observers)
980 }
981
982 /// Recursively removes and disposes `id`, recycling all arena slots, running lifecycle hooks, and disposing scopes.
983 ///
984 /// # Arguments
985 ///
986 /// - `&Self` - Mutable scene tree.
987 /// - `NodeId` - Subtree root handle to dispose.
988 pub fn dispose_subtree(&mut self, id: NodeId) {
989 let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
990 finalize_disposed_subtree(scopes, observers);
991 }
992
993 /// Updates keyboard focus to `target`, emitting `Blur` and `Focus` events.
994 ///
995 /// # Arguments
996 ///
997 /// - `&Self` - Mutable scene tree.
998 /// - `Option<NodeId>` - Newly focused node, or `None` to clear focus.
999 ///
1000 /// # Returns
1001 ///
1002 /// - `Vec<(UiEventHandler, UiEvent)>` - Callbacks to invoke outside the tree borrow.
1003 pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
1004 let prev: Option<NodeId> = self.get_focus().focused_node();
1005 if prev == target {
1006 return Vec::new();
1007 }
1008 let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
1009 if let Some(old_id) = prev {
1010 if let Some(old_node) = self.get_node_mut(old_id) {
1011 old_node.get_mut_interaction().set_focused(false);
1012 if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
1013 callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
1014 }
1015 }
1016 self.mark_dirty(old_id, DIRTY_PAINT);
1017 }
1018 self.get_mut_focus().set_focused(target);
1019 if let Some(new_id) = target {
1020 if let Some(new_node) = self.get_node_mut(new_id) {
1021 new_node.get_mut_interaction().set_focused(true);
1022 if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
1023 callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
1024 }
1025 }
1026 self.mark_dirty(new_id, DIRTY_PAINT);
1027 }
1028 callbacks
1029 }
1030}
1031
1032/// Shared scene handle operations enabling surgical reactive node updates.
1033impl SceneHandle {
1034 /// Creates a new `SceneHandle` wrapping a fresh `SceneTree`.
1035 ///
1036 /// # Returns
1037 ///
1038 /// - `Self` - Shared scene handle.
1039 #[must_use]
1040 pub fn new_tree() -> Self {
1041 Self {
1042 inner: Rc::new(RefCell::new(SceneTree::default())),
1043 }
1044 }
1045
1046 /// Updates virtualized scroll metrics `(scroll_y, content_height)` on `id` for accurate scrollbar thumbs.
1047 ///
1048 /// # Arguments
1049 ///
1050 /// - `&Self` - Scene handle reference.
1051 /// - `NodeId` - Target virtualized scroll container.
1052 /// - `f32` - Active virtual vertical scroll offset in logical pixels.
1053 /// - `f32` - Total virtualized content height in logical pixels.
1054 pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
1055 self.with_write(
1056 |tree: &mut SceneTree| {
1057 tree.set_virtual_scroll(id, scroll_y, content_height);
1058 },
1059 (),
1060 );
1061 }
1062
1063 /// Computes screen-space logical bounds for `id` subtracting ancestor scroll offsets.
1064 ///
1065 /// # Arguments
1066 ///
1067 /// - `&Self` - Scene handle reference.
1068 /// - `NodeId` - Target node handle.
1069 ///
1070 /// # Returns
1071 ///
1072 /// - `Option<Rect>` - Screen-space bounds if the node is alive.
1073 #[must_use]
1074 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
1075 self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
1076 }
1077
1078 /// Starts or replaces a smooth paint/transform transition on the target node.
1079 ///
1080 /// # Arguments
1081 ///
1082 /// - `&Self` - Scene handle reference.
1083 /// - `NodeTransition` - Transition specification to run.
1084 pub fn start_transition(&self, transition: NodeTransition) {
1085 self.with_write(
1086 |tree: &mut SceneTree| {
1087 tree.start_transition(transition);
1088 },
1089 (),
1090 );
1091 }
1092
1093 /// Marks `id` dirty with `mask` for incremental repainting.
1094 ///
1095 /// # Arguments
1096 ///
1097 /// - `&Self` - Scene handle reference.
1098 /// - `NodeId` - Target node handle.
1099 /// - `u16` - Dirty flag bits.
1100 pub fn mark_dirty(&self, id: NodeId, mask: u16) {
1101 self.with_write(
1102 |tree: &mut SceneTree| {
1103 tree.mark_dirty(id, mask);
1104 },
1105 (),
1106 );
1107 }
1108
1109 /// Replaces all children of `parent` and finalizes disposed scopes and `Lifecycle` hooks outside the tree borrow.
1110 ///
1111 /// # Arguments
1112 ///
1113 /// - `&Self` - Scene handle reference.
1114 /// - `NodeId` - Parent container node.
1115 /// - `Vec<NodeId>` - Replacement ordered children.
1116 pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
1117 let (scopes, observers): DisposedSubtreePayload = self.with_write(
1118 |tree: &mut SceneTree| {
1119 let old_children: Vec<NodeId> = match tree.get_node_mut(parent) {
1120 Some(node) => take(node.get_mut_children()),
1121 None => return (Vec::new(), Vec::new()),
1122 };
1123 let mut all_scopes: Vec<Scope> = Vec::new();
1124 let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1125 for old_child in old_children.into_iter() {
1126 if !new_children.contains(&old_child) {
1127 let (sc, ob): DisposedSubtreePayload =
1128 tree.dispose_subtree_collect(old_child);
1129 all_scopes.extend(sc);
1130 all_obs.extend(ob);
1131 }
1132 }
1133 for child in new_children.iter().copied() {
1134 if let Some(child_node) = tree.get_node_mut(child) {
1135 child_node.set_parent(Some(parent));
1136 }
1137 }
1138 if let Some(parent_node) = tree.get_node_mut(parent) {
1139 parent_node.set_children(new_children);
1140 }
1141 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1142 (all_scopes, all_obs)
1143 },
1144 (Vec::new(), Vec::new()),
1145 );
1146 finalize_disposed_subtree(scopes, observers);
1147 }
1148
1149 /// Removes `child` from `parent`, disposes its subtree, and invokes `on_unmount`/`on_destroy` outside any scene borrow.
1150 ///
1151 /// # Arguments
1152 ///
1153 /// - `&Self` - Scene handle reference.
1154 /// - `NodeId` - Parent container handle.
1155 /// - `NodeId` - Child subtree root handle to remove and destroy.
1156 pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
1157 let (scopes, observers): DisposedSubtreePayload = self.with_write(
1158 |tree: &mut SceneTree| {
1159 if let Some(pnode) = tree.get_node_mut(parent) {
1160 pnode.get_mut_children().retain(|id: &NodeId| *id != child);
1161 }
1162 let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
1163 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1164 out
1165 },
1166 (Vec::new(), Vec::new()),
1167 );
1168 finalize_disposed_subtree(scopes, observers);
1169 }
1170
1171 /// Freezes a subtree visually (`Display::None`), cancels its transitions, and dispatches `Lifecycle::on_freeze` outside any scene borrow.
1172 ///
1173 /// # Arguments
1174 ///
1175 /// - `&Self` - Scene handle reference.
1176 /// - `NodeId` - Subtree root handle to freeze.
1177 pub fn freeze_subtree(&self, root: NodeId) {
1178 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
1179 |tree: &mut SceneTree| {
1180 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
1181 tree.cancel_subtree_transitions(root);
1182 if let Some(node) = tree.get_node_mut(root) {
1183 let mut st: Style = node.get_style();
1184 st.get_mut_layout().set_display(Display::None);
1185 node.set_style(st);
1186 }
1187 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
1188 obs
1189 },
1190 Vec::new(),
1191 );
1192 dispatch_lifecycle_freeze(&observers);
1193 }
1194
1195 /// Freezes a subtree immediately for lifecycle/effects while animating its visual exit to `Display::None`.
1196 ///
1197 /// # Arguments
1198 ///
1199 /// - `&Self` - Scene handle reference.
1200 /// - `NodeId` - Subtree root handle to freeze and animate out.
1201 /// - `NodeTransition` - Exit transition specification (`hide_on_complete` is enforced).
1202 pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
1203 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
1204 |tree: &mut SceneTree| {
1205 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
1206 tree.cancel_subtree_transitions(root);
1207 if let Some(node) = tree.get_node_mut(root) {
1208 let mut st: Style = node.get_style();
1209 st.get_mut_layout()
1210 .set_position(Position::Absolute)
1211 .set_top(Some(0.0))
1212 .set_right(Some(0.0))
1213 .set_bottom(None)
1214 .set_left(Some(0.0))
1215 .set_z_index(0);
1216 st.get_mut_paint().set_pointer_events(PointerEvents::None);
1217 node.set_style(st);
1218 }
1219 tree.start_transition(exit_transition.with_hide_on_complete(true));
1220 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
1221 obs
1222 },
1223 Vec::new(),
1224 );
1225 dispatch_lifecycle_freeze(&observers);
1226 }
1227
1228 /// Resumes a previously frozen subtree (`Display::Flex`) and dispatches `Lifecycle::on_resume` outside any scene borrow.
1229 ///
1230 /// # Arguments
1231 ///
1232 /// - `&Self` - Scene handle reference.
1233 /// - `NodeId` - Subtree root handle to resume.
1234 pub fn resume_subtree(&self, root: NodeId) {
1235 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
1236 |tree: &mut SceneTree| {
1237 if let Some(node) = tree.get_node_mut(root) {
1238 let mut st: Style = node.get_style();
1239 if st.get_layout().get_display() == Display::None {
1240 st.get_mut_layout().set_display(Display::Flex);
1241 node.set_style(st);
1242 }
1243 }
1244 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
1245 tree.collect_subtree_lifecycles(root)
1246 },
1247 Vec::new(),
1248 );
1249 dispatch_lifecycle_resume(&observers);
1250 }
1251
1252 /// Dispatches `Lifecycle::on_activate` across all observers in the subtree rooted at `root`.
1253 ///
1254 /// # Arguments
1255 ///
1256 /// - `&Self` - Scene handle reference.
1257 /// - `NodeId` - Subtree root handle becoming active.
1258 pub fn activate_subtree(&self, root: NodeId) {
1259 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
1260 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
1261 Vec::new(),
1262 );
1263 dispatch_lifecycle_activate(&observers);
1264 }
1265
1266 /// Dispatches `Lifecycle::on_update` across all observers in the subtree rooted at `root`.
1267 ///
1268 /// # Arguments
1269 ///
1270 /// - `&Self` - Scene handle reference.
1271 /// - `NodeId` - Subtree root handle receiving updates.
1272 pub fn update_subtree(&self, root: NodeId) {
1273 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
1274 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
1275 Vec::new(),
1276 );
1277 dispatch_lifecycle_update(&observers);
1278 }
1279
1280 /// Returns `true` if any node transition is currently active.
1281 ///
1282 /// # Arguments
1283 ///
1284 /// - `&Self` - Scene handle reference.
1285 ///
1286 /// # Returns
1287 ///
1288 /// - `bool` - Whether animations are running.
1289 #[must_use]
1290 pub fn has_active_transitions(&self) -> bool {
1291 self.with_read(SceneTree::has_active_transitions, false)
1292 }
1293
1294 /// Executes `operation` with immutable access to the underlying `SceneTree`.
1295 ///
1296 /// # Arguments
1297 ///
1298 /// - `&Self` - Scene handle.
1299 /// - `F` - Reader closure.
1300 /// - `R` - Fallback if re-entrantly borrowed.
1301 ///
1302 /// # Returns
1303 ///
1304 /// - `R` - Closure result or fallback.
1305 pub fn with_read<F, R>(&self, operation: F, fallback: R) -> R
1306 where
1307 F: FnOnce(&SceneTree) -> R,
1308 {
1309 let Self { inner } = self;
1310 match inner.try_borrow() {
1311 Ok(guard) => operation(&guard),
1312 Err(_) => fallback,
1313 }
1314 }
1315
1316 /// Executes `operation` with mutable access to the underlying `SceneTree`.
1317 ///
1318 /// # Arguments
1319 ///
1320 /// - `&Self` - Scene handle.
1321 /// - `F` - Mutation closure.
1322 /// - `R` - Fallback if re-entrantly borrowed.
1323 ///
1324 /// # Returns
1325 ///
1326 /// - `R` - Closure result or fallback.
1327 pub fn with_write<F, R>(&self, operation: F, fallback: R) -> R
1328 where
1329 F: FnOnce(&mut SceneTree) -> R,
1330 {
1331 let Self { inner } = self;
1332 match inner.try_borrow_mut() {
1333 Ok(mut guard) => operation(&mut guard),
1334 Err(_) => fallback,
1335 }
1336 }
1337
1338 /// Binds a reactive text expression to `node_id` via a surgical `Effect`.
1339 ///
1340 /// # Arguments
1341 ///
1342 /// - `&Self` - Scene handle.
1343 /// - `NodeId` - Target text node.
1344 /// - `F` - Reactive text producer closure.
1345 ///
1346 /// # Returns
1347 ///
1348 /// - `Effect` - Registered reactive effect.
1349 pub fn bind_text<F>(&self, node_id: NodeId, mut producer: F) -> Effect
1350 where
1351 F: FnMut() -> String + 'static,
1352 {
1353 let handle: Self = self.clone();
1354 Effect::new(move || {
1355 let value: String = producer();
1356 handle.with_write(
1357 |tree: &mut SceneTree| {
1358 tree.set_text(node_id, value);
1359 },
1360 (),
1361 );
1362 })
1363 }
1364
1365 /// Binds a reactive `Style` expression to `node_id` via a surgical `Effect`.
1366 ///
1367 /// # Arguments
1368 ///
1369 /// - `&Self` - Scene handle.
1370 /// - `NodeId` - Target node.
1371 /// - `F` - Reactive style producer closure.
1372 ///
1373 /// # Returns
1374 ///
1375 /// - `Effect` - Registered reactive effect.
1376 pub fn bind_style<F>(&self, node_id: NodeId, mut producer: F) -> Effect
1377 where
1378 F: FnMut() -> Style + 'static,
1379 {
1380 let handle: Self = self.clone();
1381 Effect::new(move || {
1382 let style: Style = producer();
1383 handle.with_write(
1384 |tree: &mut SceneTree| {
1385 tree.set_style(node_id, style);
1386 },
1387 (),
1388 );
1389 })
1390 }
1391}
1392
1393/// High-level declarative building helpers on `Context`.
1394impl Context {
1395 /// Creates a new `Context` with reactive viewport, theme, and safe-area signals.
1396 ///
1397 /// # Arguments
1398 ///
1399 /// - `SceneHandle` - Shared scene handle.
1400 /// - `PlatformKind` - Active platform kind.
1401 ///
1402 /// # Returns
1403 ///
1404 /// - `Self` - Constructed build context.
1405 #[must_use]
1406 pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
1407 Self {
1408 scene,
1409 breakpoint: Signal::new(Breakpoint::Expanded),
1410 viewport_size: Signal::new(Size::new(1200.0, 800.0)),
1411 theme_mode: Signal::new(ThemeMode::Light),
1412 platform,
1413 safe_area: Signal::new(SafeAreaInsets::default()),
1414 gesture: Signal::new(None),
1415 swipe_drag_offset: Signal::new(0.0),
1416 system_back: Signal::new(0),
1417 dynamic_hub: DynamicUpdateHub::new(),
1418 fps_limit: Signal::new(None),
1419 live_fps: Signal::new(60.0),
1420 display_refresh_rate: Signal::new(60.0),
1421 active_touches: Signal::new(Vec::new()),
1422 exit_requested: Signal::new(false),
1423 clock_ms: Rc::new(Cell::new(0)),
1424 }
1425 }
1426
1427 /// Returns the monotonic runtime elapsed clock in milliseconds.
1428 ///
1429 /// # Arguments
1430 ///
1431 /// - `&Self` - Context reference.
1432 ///
1433 /// # Returns
1434 ///
1435 /// - `u64` - Elapsed runtime time in milliseconds.
1436 #[must_use]
1437 pub fn elapsed_ms(&self) -> u64 {
1438 let Self { clock_ms, .. } = self;
1439 clock_ms.get()
1440 }
1441
1442 /// Advances the context's monotonic runtime clock by `delta_ms` milliseconds.
1443 ///
1444 /// # Arguments
1445 ///
1446 /// - `&Self` - Context reference.
1447 /// - `u64` - Milliseconds elapsed since the previous frame.
1448 pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
1449 let Self { clock_ms, .. } = self;
1450 clock_ms.set(clock_ms.get().saturating_add(delta_ms));
1451 }
1452
1453 /// Requests graceful OS-level application termination across all platforms.
1454 ///
1455 /// # Arguments
1456 ///
1457 /// - `&Self` - Context reference.
1458 pub fn request_exit(&self) {
1459 let _: bool = self.get_exit_requested().set_if_changed(true);
1460 let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
1461 }
1462
1463 /// Creates a `View` node with the given style.
1464 ///
1465 /// # Arguments
1466 ///
1467 /// - `&Self` - Build context.
1468 /// - `Style` - Initial style.
1469 ///
1470 /// # Returns
1471 ///
1472 /// - `NodeId` - Created node handle.
1473 pub fn view(&mut self, style: Style) -> NodeId {
1474 self.get_scene().with_write(
1475 |tree: &mut SceneTree| tree.create_view(style),
1476 NodeId::default(),
1477 )
1478 }
1479
1480 /// Creates a `Text` node with static initial text.
1481 ///
1482 /// # Arguments
1483 ///
1484 /// - `&Self` - Build context.
1485 /// - `String` - Text content.
1486 /// - `Style` - Text style.
1487 ///
1488 /// # Returns
1489 ///
1490 /// - `NodeId` - Created node handle.
1491 pub fn text(&mut self, content: String, style: Style) -> NodeId {
1492 self.get_scene().with_write(
1493 |tree: &mut SceneTree| tree.create_text(content, style),
1494 NodeId::default(),
1495 )
1496 }
1497
1498 /// Creates a reactive `Text` node whose content updates surgically whenever tracked signals change.
1499 ///
1500 /// # Arguments
1501 ///
1502 /// - `&Self` - Build context.
1503 /// - `Style` - Text style.
1504 /// - `F` - Reactive text producer.
1505 ///
1506 /// # Returns
1507 ///
1508 /// - `NodeId` - Created reactive text node handle.
1509 pub fn reactive_text<F>(&mut self, style: Style, producer: F) -> NodeId
1510 where
1511 F: FnMut() -> String + 'static,
1512 {
1513 let node_id: NodeId = self.text(String::new(), style);
1514 let handle: SceneHandle = self.get_scene().clone();
1515 let (scope, _): (Scope, Effect) =
1516 Scope::run(|_: Scope| handle.bind_text(node_id, producer));
1517 self.get_scene().with_write(
1518 |tree: &mut SceneTree| {
1519 tree.attach_scope(node_id, scope);
1520 },
1521 (),
1522 );
1523 node_id
1524 }
1525
1526 /// Creates a `ScrollView` node with the given style.
1527 ///
1528 /// # Arguments
1529 ///
1530 /// - `&Self` - Build context.
1531 /// - `Style` - Scroll container style.
1532 ///
1533 /// # Returns
1534 ///
1535 /// - `NodeId` - Created scroll view handle.
1536 pub fn scroll_view(&mut self, style: Style) -> NodeId {
1537 self.get_scene().with_write(
1538 |tree: &mut SceneTree| tree.create_scroll_view(style),
1539 NodeId::default(),
1540 )
1541 }
1542
1543 /// Creates an `Input` node with initial state and style.
1544 ///
1545 /// # Arguments
1546 ///
1547 /// - `&Self` - Build context.
1548 /// - `InputNodeState` - Initial input state.
1549 /// - `Style` - Input style.
1550 ///
1551 /// # Returns
1552 ///
1553 /// - `NodeId` - Created input handle.
1554 pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
1555 self.get_scene().with_write(
1556 |tree: &mut SceneTree| tree.create_input(state, style),
1557 NodeId::default(),
1558 )
1559 }
1560
1561 /// Creates an `Image` node with decoded RGBA8 pixel data.
1562 ///
1563 /// # Arguments
1564 ///
1565 /// - `&Self` - Build context.
1566 /// - `ImageBuffer` - Image buffer.
1567 /// - `Style` - Image style.
1568 ///
1569 /// # Returns
1570 ///
1571 /// - `NodeId` - Created image handle.
1572 pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
1573 self.get_scene().with_write(
1574 |tree: &mut SceneTree| tree.create_image(buffer, style),
1575 NodeId::default(),
1576 )
1577 }
1578
1579 /// Creates a `Canvas` node bound to a custom draw callback.
1580 ///
1581 /// # Arguments
1582 ///
1583 /// - `&Self` - Build context.
1584 /// - `Style` - Canvas style.
1585 /// - `F` - Draw callback receiving node bounds and mutable `DisplayList`.
1586 ///
1587 /// # Returns
1588 ///
1589 /// - `NodeId` - Created canvas handle.
1590 pub fn canvas<F>(&mut self, style: Style, painter: F) -> NodeId
1591 where
1592 F: FnMut(Rect, &mut DisplayList) + 'static,
1593 {
1594 let cb: CanvasDrawCallback = Rc::new(RefCell::new(painter));
1595 self.get_scene().with_write(
1596 |tree: &mut SceneTree| tree.create_canvas(style, cb),
1597 NodeId::default(),
1598 )
1599 }
1600
1601 /// Creates an overlay `Portal` node.
1602 ///
1603 /// # Arguments
1604 ///
1605 /// - `&Self` - Build context.
1606 /// - `Style` - Portal style.
1607 ///
1608 /// # Returns
1609 ///
1610 /// - `NodeId` - Created portal handle.
1611 pub fn portal(&mut self, style: Style) -> NodeId {
1612 self.get_scene().with_write(
1613 |tree: &mut SceneTree| tree.create_portal(style),
1614 NodeId::default(),
1615 )
1616 }
1617
1618 /// Creates a transparent logical `Fragment` grouping container for sibling nodes.
1619 ///
1620 /// # Arguments
1621 ///
1622 /// - `&Self` - Build context.
1623 ///
1624 /// # Returns
1625 ///
1626 /// - `NodeId` - Created fragment handle.
1627 pub fn fragment(&mut self) -> NodeId {
1628 self.get_scene().with_write(
1629 |tree: &mut SceneTree| tree.create_fragment(),
1630 NodeId::default(),
1631 )
1632 }
1633
1634 /// Appends `child` to `parent`.
1635 ///
1636 /// # Arguments
1637 ///
1638 /// - `&Self` - Build context.
1639 /// - `NodeId` - Parent container.
1640 /// - `NodeId` - Child node.
1641 pub fn append(&mut self, parent: NodeId, child: NodeId) {
1642 self.get_scene().with_write(
1643 |tree: &mut SceneTree| {
1644 tree.append_child(parent, child);
1645 },
1646 (),
1647 );
1648 }
1649
1650 /// Appends a slice of `children` to `parent` under a single scene write lock and dirty pass.
1651 ///
1652 /// # Arguments
1653 ///
1654 /// - `&Self` - Build context.
1655 /// - `NodeId` - Parent container.
1656 /// - `&[NodeId]` - Ordered child node slice.
1657 pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
1658 if children.is_empty() {
1659 return;
1660 }
1661 self.get_scene().with_write(
1662 |tree: &mut SceneTree| {
1663 tree.append_children(parent, children);
1664 },
1665 (),
1666 );
1667 }
1668
1669 /// Binds a reactive `Style` closure to `node_id` and attaches its disposal `Scope` automatically.
1670 ///
1671 /// # Arguments
1672 ///
1673 /// - `&Self` - Build context.
1674 /// - `NodeId` - Target scene node.
1675 /// - `F` - Reactive `Style` producer closure.
1676 pub fn bind_style<F>(&mut self, node_id: NodeId, producer: F)
1677 where
1678 F: FnMut() -> Style + 'static,
1679 {
1680 let handle: SceneHandle = self.get_scene().clone();
1681 let (scope, _): (Scope, Effect) =
1682 Scope::run(|_: Scope| handle.bind_style(node_id, producer));
1683 self.get_scene().with_write(
1684 |tree: &mut SceneTree| {
1685 tree.attach_scope(node_id, scope);
1686 },
1687 (),
1688 );
1689 }
1690
1691 /// Registers a pointer-enter handler on `node_id`.
1692 ///
1693 /// # Arguments
1694 ///
1695 /// - `&Self` - Build context.
1696 /// - `NodeId` - Target node handle.
1697 /// - `F` - Pointer-enter callback closure.
1698 pub fn on_pointer_enter<F>(&mut self, node_id: NodeId, callback: F)
1699 where
1700 F: FnMut(&UiEvent) + 'static,
1701 {
1702 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1703 self.get_scene().with_write(
1704 |tree: &mut SceneTree| {
1705 if let Some(node) = tree.get_node_mut(node_id) {
1706 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
1707 }
1708 },
1709 (),
1710 );
1711 }
1712
1713 /// Registers a pointer-leave handler on `node_id`.
1714 ///
1715 /// # Arguments
1716 ///
1717 /// - `&Self` - Build context.
1718 /// - `NodeId` - Target node handle.
1719 /// - `F` - Pointer-leave callback closure.
1720 pub fn on_pointer_leave<F>(&mut self, node_id: NodeId, callback: F)
1721 where
1722 F: FnMut(&UiEvent) + 'static,
1723 {
1724 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1725 self.get_scene().with_write(
1726 |tree: &mut SceneTree| {
1727 if let Some(node) = tree.get_node_mut(node_id) {
1728 node.get_mut_handlers().set_on_pointer_leave(Some(handler));
1729 }
1730 },
1731 (),
1732 );
1733 }
1734
1735 /// Registers a focus-gained handler on `node_id` and marks it focusable.
1736 ///
1737 /// # Arguments
1738 ///
1739 /// - `&Self` - Build context.
1740 /// - `NodeId` - Target node handle.
1741 /// - `F` - Focus callback closure receiving `UiEventKind::Focus`.
1742 pub fn on_focus<F>(&mut self, node_id: NodeId, callback: F)
1743 where
1744 F: FnMut(&UiEvent) + 'static,
1745 {
1746 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1747 self.get_scene().with_write(
1748 |tree: &mut SceneTree| {
1749 if let Some(node) = tree.get_node_mut(node_id) {
1750 node.get_mut_handlers().set_on_focus(Some(handler));
1751 node.get_mut_interaction().set_focusable(true);
1752 }
1753 },
1754 (),
1755 );
1756 }
1757
1758 /// Registers a focus-lost handler on `node_id`.
1759 ///
1760 /// # Arguments
1761 ///
1762 /// - `&Self` - Build context.
1763 /// - `NodeId` - Target node handle.
1764 /// - `F` - Blur callback closure receiving `UiEventKind::Blur`.
1765 pub fn on_blur<F>(&mut self, node_id: NodeId, callback: F)
1766 where
1767 F: FnMut(&UiEvent) + 'static,
1768 {
1769 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1770 self.get_scene().with_write(
1771 |tree: &mut SceneTree| {
1772 if let Some(node) = tree.get_node_mut(node_id) {
1773 node.get_mut_handlers().set_on_blur(Some(handler));
1774 }
1775 },
1776 (),
1777 );
1778 }
1779
1780 /// Configures whether `node_id` participates in keyboard focus navigation.
1781 ///
1782 /// # Arguments
1783 ///
1784 /// - `&Self` - Build context.
1785 /// - `NodeId` - Target node handle.
1786 /// - `bool` - Whether keyboard focus is enabled.
1787 pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
1788 self.get_scene().with_write(
1789 |tree: &mut SceneTree| {
1790 if let Some(node) = tree.get_node_mut(node_id) {
1791 node.get_mut_interaction().set_focusable(focusable);
1792 }
1793 },
1794 (),
1795 );
1796 }
1797
1798 /// Registers a click handler on `node_id` and sets pointer cursor automatically.
1799 ///
1800 /// # Arguments
1801 ///
1802 /// - `&Self` - Build context.
1803 /// - `NodeId` - Target node.
1804 /// - `F` - Click callback closure.
1805 pub fn on_click<F>(&mut self, node_id: NodeId, callback: F)
1806 where
1807 F: FnMut(&UiEvent) + 'static,
1808 {
1809 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1810 self.get_scene().with_write(
1811 |tree: &mut SceneTree| {
1812 if let Some(node) = tree.get_node_mut(node_id) {
1813 node.get_mut_handlers().set_on_click(Some(handler));
1814 node.get_mut_interaction().set_focusable(true);
1815 if node.get_style().get_paint().get_cursor() == CursorIcon::Default {
1816 let mut style: Style = node.get_style();
1817 style.get_mut_paint().set_cursor(CursorIcon::Pointer);
1818 node.set_style(style);
1819 }
1820 }
1821 },
1822 (),
1823 );
1824 }
1825
1826 /// Registers a change handler on an `Input` node.
1827 ///
1828 /// # Arguments
1829 ///
1830 /// - `&Self` - Build context.
1831 /// - `NodeId` - Target input node.
1832 /// - `F` - Change callback closure.
1833 pub fn on_change<F>(&mut self, node_id: NodeId, callback: F)
1834 where
1835 F: FnMut(&UiEvent) + 'static,
1836 {
1837 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1838 self.get_scene().with_write(
1839 |tree: &mut SceneTree| {
1840 if let Some(node) = tree.get_node_mut(node_id) {
1841 node.get_mut_handlers().set_on_change(Some(handler));
1842 }
1843 },
1844 (),
1845 );
1846 }
1847
1848 /// Attaches semantic accessibility properties to `node_id`.
1849 ///
1850 /// # Arguments
1851 ///
1852 /// - `&Self` - Build context.
1853 /// - `NodeId` - Target scene node.
1854 /// - `A11yProps` - Semantic role, label, hint, and state metadata.
1855 pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
1856 self.get_scene().with_write(
1857 |tree: &mut SceneTree| {
1858 if let Some(node) = tree.get_node_mut(node_id) {
1859 node.set_a11y(Some(props));
1860 }
1861 },
1862 (),
1863 );
1864 }
1865
1866 /// Registers a scroll handler on a scrollable container node.
1867 ///
1868 /// # Arguments
1869 ///
1870 /// - `&Self` - Build context.
1871 /// - `NodeId` - Target scroll container node.
1872 /// - `F` - Scroll callback closure receiving `UiEventKind::Scroll(delta)`.
1873 pub fn on_scroll<F>(&mut self, node_id: NodeId, callback: F)
1874 where
1875 F: FnMut(&UiEvent) + 'static,
1876 {
1877 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1878 self.get_scene().with_write(
1879 |tree: &mut SceneTree| {
1880 if let Some(node) = tree.get_node_mut(node_id) {
1881 node.get_mut_handlers().set_on_scroll(Some(handler));
1882 }
1883 },
1884 (),
1885 );
1886 }
1887
1888 /// Registers a pointer-down handler on `node_id` for draggable interactive controls.
1889 ///
1890 /// # Arguments
1891 ///
1892 /// - `&Self` - Build context.
1893 /// - `NodeId` - Target node handle.
1894 /// - `F` - Pointer-down callback closure.
1895 pub fn on_pointer_down<F>(&mut self, node_id: NodeId, callback: F)
1896 where
1897 F: FnMut(&UiEvent) + 'static,
1898 {
1899 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1900 self.get_scene().with_write(
1901 |tree: &mut SceneTree| {
1902 if let Some(node) = tree.get_node_mut(node_id) {
1903 node.get_mut_handlers().set_on_pointer_down(Some(handler));
1904 if node.get_style().get_paint().get_cursor() == CursorIcon::Default {
1905 let mut style: Style = node.get_style();
1906 style.get_mut_paint().set_cursor(CursorIcon::Pointer);
1907 node.set_style(style);
1908 }
1909 }
1910 },
1911 (),
1912 );
1913 }
1914
1915 /// Registers a pointer-move handler on `node_id` receiving captured drag coordinates while pressed.
1916 ///
1917 /// # Arguments
1918 ///
1919 /// - `&Self` - Build context.
1920 /// - `NodeId` - Target node handle.
1921 /// - `F` - Pointer-move callback closure.
1922 pub fn on_pointer_move<F>(&mut self, node_id: NodeId, callback: F)
1923 where
1924 F: FnMut(&UiEvent) + 'static,
1925 {
1926 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1927 self.get_scene().with_write(
1928 |tree: &mut SceneTree| {
1929 if let Some(node) = tree.get_node_mut(node_id) {
1930 node.get_mut_handlers().set_on_pointer_move(Some(handler));
1931 }
1932 },
1933 (),
1934 );
1935 }
1936
1937 /// Registers a pointer-up handler on `node_id` invoked when drag capture releases.
1938 ///
1939 /// # Arguments
1940 ///
1941 /// - `&Self` - Build context.
1942 /// - `NodeId` - Target node handle.
1943 /// - `F` - Pointer-up callback closure.
1944 pub fn on_pointer_up<F>(&mut self, node_id: NodeId, callback: F)
1945 where
1946 F: FnMut(&UiEvent) + 'static,
1947 {
1948 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1949 self.get_scene().with_write(
1950 |tree: &mut SceneTree| {
1951 if let Some(node) = tree.get_node_mut(node_id) {
1952 node.get_mut_handlers().set_on_pointer_up(Some(handler));
1953 }
1954 },
1955 (),
1956 );
1957 }
1958
1959 /// Registers a hover handler on `node_id` invoked on both `PointerEnter` and `PointerLeave`.
1960 ///
1961 /// # Arguments
1962 ///
1963 /// - `&Self` - Build context.
1964 /// - `NodeId` - Target node handle.
1965 /// - `F` - Hover callback closure receiving `UiEventKind::PointerEnter` or `PointerLeave`.
1966 pub fn on_hover<F>(&mut self, node_id: NodeId, callback: F)
1967 where
1968 F: FnMut(&UiEvent) + 'static,
1969 {
1970 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1971 let leave_handler: UiEventHandler = handler.clone();
1972 self.get_scene().with_write(
1973 |tree: &mut SceneTree| {
1974 if let Some(node) = tree.get_node_mut(node_id) {
1975 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
1976 node.get_mut_handlers()
1977 .set_on_pointer_leave(Some(leave_handler));
1978 }
1979 },
1980 (),
1981 );
1982 }
1983
1984 /// Registers a keyboard key-down handler on `node_id` and marks it focusable.
1985 ///
1986 /// # Arguments
1987 ///
1988 /// - `&Self` - Build context.
1989 /// - `NodeId` - Target node handle.
1990 /// - `F` - Key-down callback closure receiving `UiEventKind::KeyDown`.
1991 pub fn on_key<F>(&mut self, node_id: NodeId, callback: F)
1992 where
1993 F: FnMut(&UiEvent) + 'static,
1994 {
1995 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1996 self.get_scene().with_write(
1997 |tree: &mut SceneTree| {
1998 if let Some(node) = tree.get_node_mut(node_id) {
1999 node.get_mut_handlers().set_on_key_down(Some(handler));
2000 node.get_mut_interaction().set_focusable(true);
2001 }
2002 },
2003 (),
2004 );
2005 }
2006
2007 /// Records virtualized scroll progress on `node_id` so the overlay scrollbar tracks accurately.
2008 ///
2009 /// # Arguments
2010 ///
2011 /// - `&Self` - Build context.
2012 /// - `NodeId` - Target virtualized scroll container.
2013 /// - `f32` - Active virtual vertical scroll offset in logical pixels.
2014 /// - `f32` - Full virtualized content height in logical pixels.
2015 pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
2016 self.get_scene()
2017 .set_virtual_scroll(node_id, scroll_y, content_height);
2018 }
2019
2020 /// Sets the concrete inner pixel scroll offset on `node_id` (used by virtualized lists for sub-pixel alignment).
2021 ///
2022 /// # Arguments
2023 ///
2024 /// - `&Self` - Build context.
2025 /// - `NodeId` - Target scroll container.
2026 /// - `Point` - Scroll offset `(x, y)` in logical pixels.
2027 pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
2028 self.get_scene().with_write(
2029 |tree: &mut SceneTree| {
2030 tree.set_scroll_offset(node_id, offset);
2031 },
2032 (),
2033 );
2034 }
2035
2036 /// Starts a smooth paint/transform transition on `transition.get_node()`.
2037 ///
2038 /// # Arguments
2039 ///
2040 /// - `&Self` - Build context.
2041 /// - `NodeTransition` - Transition specification.
2042 pub fn start_transition(&mut self, transition: NodeTransition) {
2043 self.get_scene().start_transition(transition);
2044 }
2045
2046 /// Mounts a reactive dynamic subtree whose children rebuild cleanly inside an isolated `Scope`.
2047 ///
2048 /// # Arguments
2049 ///
2050 /// - `&Self` - Build context.
2051 /// - `NodeId` - Host container node.
2052 /// - `F` - Reactive zero-`ctx` builder returning child `NodeId` values.
2053 pub fn bind_children<F>(&mut self, host: NodeId, mut builder: F)
2054 where
2055 F: FnMut() -> Vec<NodeId> + 'static,
2056 {
2057 let ctx_clone: Self = self.clone();
2058 let handle: SceneHandle = self.get_scene().clone();
2059 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2060 Effect::new(move || {
2061 let (child_scope, children): (Scope, Vec<NodeId>) =
2062 Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
2063 let first_opt: Option<NodeId> = children.first().copied();
2064 handle.replace_children_safe(host, children);
2065 if let Some(first) = first_opt {
2066 handle.with_write(
2067 |tree: &mut SceneTree| {
2068 tree.attach_scope(first, child_scope);
2069 },
2070 (),
2071 );
2072 }
2073 })
2074 });
2075 self.get_scene().with_write(
2076 |tree: &mut SceneTree| {
2077 tree.attach_scope(host, scope);
2078 },
2079 (),
2080 );
2081 }
2082}
2083
2084/// Restores the previously bound ambient `Context` when leaving scope.
2085impl Drop for ContextGuard {
2086 /// Restores the saved thread-local `Context`.
2087 ///
2088 /// # Arguments
2089 ///
2090 /// - `&Self` - Mutable scope guard being dropped.
2091 fn drop(&mut self) {
2092 let Self { previous } = self;
2093 let restored: Option<Context> = previous.take();
2094 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
2095 *slot.borrow_mut() = restored;
2096 });
2097 }
2098}
2099
2100/// `NodeRefTarget` implementation storing a `NodeId` directly into a mutable local binding.
2101impl NodeRefTarget for NodeId {
2102 /// Assigns `id` to `self`.
2103 ///
2104 /// # Arguments
2105 ///
2106 /// - `&Self` - Target `NodeId` slot.
2107 /// - `NodeId` - Mounted node handle.
2108 fn bind_node_ref(&mut self, id: NodeId) {
2109 *self = id;
2110 }
2111}
2112
2113/// `NodeRefTarget` implementation storing a `NodeId` into an `Option<NodeId>`.
2114impl NodeRefTarget for Option<NodeId> {
2115 /// Assigns `Some(id)` to `self`.
2116 ///
2117 /// # Arguments
2118 ///
2119 /// - `&Self` - Target optional `NodeId` slot.
2120 /// - `NodeId` - Mounted node handle.
2121 fn bind_node_ref(&mut self, id: NodeId) {
2122 *self = Some(id);
2123 }
2124}
2125
2126/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<NodeId>`.
2127impl NodeRefTarget for Cell<NodeId> {
2128 /// Sets `self` to `id`.
2129 ///
2130 /// # Arguments
2131 ///
2132 /// - `&Self` - Target `Cell<NodeId>`.
2133 /// - `NodeId` - Mounted node handle.
2134 fn bind_node_ref(&mut self, id: NodeId) {
2135 self.set(id);
2136 }
2137}
2138
2139/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<NodeId>>`.
2140impl NodeRefTarget for Rc<Cell<NodeId>> {
2141 /// Sets the shared cell value to `id`.
2142 ///
2143 /// # Arguments
2144 ///
2145 /// - `&Self` - Target shared `Cell<NodeId>`.
2146 /// - `NodeId` - Mounted node handle.
2147 fn bind_node_ref(&mut self, id: NodeId) {
2148 self.set(id);
2149 }
2150}
2151
2152/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<Option<NodeId>>`.
2153impl NodeRefTarget for Cell<Option<NodeId>> {
2154 /// Sets `self` to `Some(id)`.
2155 ///
2156 /// # Arguments
2157 ///
2158 /// - `&Self` - Target `Cell<Option<NodeId>>`.
2159 /// - `NodeId` - Mounted node handle.
2160 fn bind_node_ref(&mut self, id: NodeId) {
2161 self.set(Some(id));
2162 }
2163}
2164
2165/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<Option<NodeId>>>`.
2166impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
2167 /// Sets the shared cell value to `Some(id)`.
2168 ///
2169 /// # Arguments
2170 ///
2171 /// - `&Self` - Target shared `Cell<Option<NodeId>>`.
2172 /// - `NodeId` - Mounted node handle.
2173 fn bind_node_ref(&mut self, id: NodeId) {
2174 self.set(Some(id));
2175 }
2176}
2177
2178/// `TextNodeContent` implementation mounting an owned `String` as a static text node.
2179impl TextNodeContent for String {
2180 /// Mounts a static text scene node from this `String`.
2181 ///
2182 /// # Arguments
2183 ///
2184 /// - `Self` - Owned text string.
2185 /// - `&mut Context` - Active scene build context.
2186 /// - `Style` - Resolved text style.
2187 ///
2188 /// # Returns
2189 ///
2190 /// - `NodeId` - Mounted text node handle.
2191 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
2192 ctx.text(self, style)
2193 }
2194}
2195
2196/// `TextNodeContent` implementation mounting a string slice as a static text node.
2197impl TextNodeContent for &str {
2198 /// Mounts a static text scene node from this `&str`.
2199 ///
2200 /// # Arguments
2201 ///
2202 /// - `Self` - Borrowed text slice.
2203 /// - `&mut Context` - Active scene build context.
2204 /// - `Style` - Resolved text style.
2205 ///
2206 /// # Returns
2207 ///
2208 /// - `NodeId` - Mounted text node handle.
2209 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
2210 ctx.text(self.to_string(), style)
2211 }
2212}
2213
2214/// `TextNodeContent` implementation mounting a borrowed `&String` as a static text node.
2215impl TextNodeContent for &String {
2216 /// Mounts a static text scene node from this `&String`.
2217 ///
2218 /// # Arguments
2219 ///
2220 /// - `Self` - Borrowed string reference.
2221 /// - `&mut Context` - Active scene build context.
2222 /// - `Style` - Resolved text style.
2223 ///
2224 /// # Returns
2225 ///
2226 /// - `NodeId` - Mounted text node handle.
2227 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
2228 ctx.text(self.clone(), style)
2229 }
2230}
2231
2232/// `TextNodeContent` implementation mounting a `Cow<str>` as a static text node.
2233impl TextNodeContent for Cow<'_, str> {
2234 /// Mounts a static text scene node from this `Cow<str>`.
2235 ///
2236 /// # Arguments
2237 ///
2238 /// - `Self` - Copy-on-write string value.
2239 /// - `&mut Context` - Active scene build context.
2240 /// - `Style` - Resolved text style.
2241 ///
2242 /// # Returns
2243 ///
2244 /// - `NodeId` - Mounted text node handle.
2245 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
2246 ctx.text(self.into_owned(), style)
2247 }
2248}
2249
2250/// `TextNodeContent` implementation mounting any `FnMut() -> S` closure or function item as a reactive text node.
2251impl<F, S> TextNodeContent for F
2252where
2253 F: FnMut() -> S + 'static,
2254 S: Into<String>,
2255{
2256 /// Mounts a reactive text scene node bound to this closure or function item.
2257 ///
2258 /// # Arguments
2259 ///
2260 /// - `Self` - Reactive text producer closure.
2261 /// - `&mut Context` - Active scene build context.
2262 /// - `Style` - Resolved text style.
2263 ///
2264 /// # Returns
2265 ///
2266 /// - `NodeId` - Mounted reactive text node handle.
2267 fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
2268 ctx.reactive_text(style, move || self().into())
2269 }
2270}