Skip to main content

gpui_rhai/
retained_page.rs

1//! Presentation policy shared by retained tab panels and navigation visits.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use crate::{ComponentInstancePath, NodeId, RetainedUiTree, UiValue};
6
7pub(crate) const PAGE_VISIBLE: &str = "retained_page_visible";
8pub(crate) const NAVIGATION_DEPTH: &str = "navigation_depth";
9pub(crate) const NAVIGATION_BACK: &str = "navigation_back";
10
11/// One controlled navigation scope. Entry keys identify visits, not records.
12#[derive(Clone, Debug, Eq, PartialEq)]
13pub struct NavigationStackInfo {
14    /// Owning mounted view; local stack keys are not globally unique.
15    pub view_id: String,
16    /// Stable retained identity for this stack scope.
17    pub node: NodeId,
18    /// Accessible name supplied by its author.
19    pub label: String,
20    /// Controlled visit count, including the root.
21    pub depth: usize,
22    /// Whether a non-root pop can be proposed to a mounted handler.
23    pub can_pop: bool,
24    /// Whether this scope contains current keyboard focus.
25    pub focused: bool,
26}
27
28/// Transactional committed placement and the components that observe it.
29/// Construction is eager, so the first render reads false until placement.
30#[derive(Clone, Debug, Default)]
31pub(crate) struct PageVisibility {
32    values: BTreeMap<ComponentInstancePath, bool>,
33    readers: BTreeSet<ComponentInstancePath>,
34    motion_scopes: BTreeMap<String, BTreeSet<String>>,
35}
36
37impl PageVisibility {
38    pub fn read(&mut self, component: &ComponentInstancePath, track: bool) -> bool {
39        if track {
40            self.readers.insert(component.clone());
41        }
42        self.values.get(component).copied().unwrap_or(false)
43    }
44
45    pub fn reset_reader(&mut self, component: &ComponentInstancePath) {
46        self.readers.remove(component);
47    }
48
49    pub fn retain_scope(
50        &mut self,
51        root: &ComponentInstancePath,
52        active: &BTreeSet<ComponentInstancePath>,
53    ) {
54        self.readers
55            .retain(|path| !path.is_within(root) || path == root || active.contains(path));
56        self.values
57            .retain(|path, _| !path.is_within(root) || path == root || active.contains(path));
58    }
59
60    pub fn remove_scope(&mut self, root: &ComponentInstancePath, domain: &str) {
61        self.readers.retain(|path| !path.is_within(root));
62        self.values.retain(|path, _| !path.is_within(root));
63        self.motion_scopes
64            .retain(|path, _| !path.starts_with(domain));
65    }
66
67    pub fn reconcile(
68        &mut self,
69        tree: &RetainedUiTree,
70        root: &ComponentInstancePath,
71        domain: &str,
72        motions: &mut crate::MotionRuntime,
73        now: std::time::Instant,
74    ) -> BTreeSet<ComponentInstancePath> {
75        let mut next = BTreeMap::from([(
76            root.clone(),
77            tree.root_id()
78                .is_some_and(|node| tree.is_page_visible(node)),
79        )]);
80        let mut hidden = BTreeSet::new();
81        for (node, visible) in page_visibility(tree) {
82            for component in node.presented_components() {
83                next.entry(component.clone())
84                    .and_modify(|current| *current |= visible)
85                    .or_insert(visible);
86            }
87            if !visible {
88                hidden.insert(crate::motion::retained_node_path(domain, node.id()));
89            }
90        }
91        let previous = self.motion_scopes.entry(domain.to_owned()).or_default();
92        for scope in previous.difference(&hidden) {
93            motions.resume_node_scope(scope, now);
94        }
95        for scope in hidden.difference(previous) {
96            motions.suspend_node_scope(scope, now);
97        }
98        *previous = hidden;
99        let dirty = self
100            .readers
101            .iter()
102            .filter(|path| path.is_within(root))
103            .filter(|path| {
104                self.values.get(*path).copied().unwrap_or(false)
105                    != next.get(*path).copied().unwrap_or(false)
106            })
107            .cloned()
108            .collect();
109        self.values.retain(|path, _| !path.is_within(root));
110        self.values.extend(next);
111        dirty
112    }
113}
114
115/// The retained nodes page visibility tracks, with whether their pages
116/// permit presentation ([`RetainedUiTree::is_page_visible`]), found top down:
117/// every node a hidden page holds, and every page and node presenting a
118/// component. A visible subtree without one is passed over.
119fn page_visibility(tree: &RetainedUiTree) -> Vec<(&crate::RetainedNode, bool)> {
120    let mut nodes = Vec::new();
121    let mut stack = tree
122        .root_id()
123        .and_then(|id| tree.node(id))
124        .map(|root| (root, true))
125        .into_iter()
126        .collect::<Vec<_>>();
127    while let Some((node, above)) = stack.pop() {
128        if above && node.summary().pages == 0 {
129            continue;
130        }
131        let visible = above && node.attributes().get(PAGE_VISIBLE) != Some(&UiValue::Bool(false));
132        nodes.push((node, visible));
133        stack.extend(
134            node.children()
135                .filter_map(|child| tree.node(child.node()))
136                .map(|child| (child, visible)),
137        );
138    }
139    let reachable = tree
140        .root_id()
141        .and_then(|id| tree.node(id))
142        .map_or(0, |root| root.summary().nodes as usize);
143    if reachable != tree.len() {
144        // A node the walk from the root misses decides by its own ancestors.
145        return tree
146            .nodes()
147            .map(|node| (node, tree.is_page_visible(node.id())))
148            .collect();
149    }
150    nodes
151}
152
153impl RetainedUiTree {
154    /// Whether every retained-page ancestor permits presentation. This is not
155    /// a layout/paint query: ordinary clipping and display styles are separate.
156    #[must_use]
157    pub fn is_page_visible(&self, node: NodeId) -> bool {
158        let mut cursor = Some(node);
159        while let Some(id) = cursor {
160            let Some(retained) = self.node(id) else {
161                return false;
162            };
163            if retained.attributes().get(PAGE_VISIBLE) == Some(&UiValue::Bool(false)) {
164                return false;
165            }
166            cursor = retained.parent();
167        }
168        true
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175    use crate::{
176        ComponentStateSchema, MotionKey, MotionPreference, MotionProperty, MotionRuntime,
177        MotionSource, MotionTransition, RuntimeEngine, ScriptLifecycle, UiNode, UiRuntimeState,
178    };
179    use std::{
180        cell::RefCell,
181        rc::Rc,
182        time::{Duration, Instant},
183    };
184
185    const FORWARDED_LEAF: &str = r#"
186define_component(#{ metadata: #{ id: "test/leaf", "export": "Leaf", version: "0.2.2", runtime_api: #{ min_inclusive: 3, max_exclusive: 4 }, dependencies: [], capabilities: #{} },
187    schema: #{ props: #{}, state: #{ fields: #{ count: #{ schema: #{ type: "integer" }, "default": #{ type: "integer", value: 0 } } } }, events: #{}, slots: #{}, parts: [] }, render: Fn("leaf") });
188fn Leaf(props) { render_component("test/leaf", props) }
189fn increment(ctx, event) { ctx.set_state("count", ctx.get_state("count") + 1); }
190fn leaf(ctx, props) { text(`${ctx.is_visible()}:${ctx.get_state("count")}`).on_click(Fn("increment")) }
191"#;
192    const FORWARDING_PASS: &str = r#"
193define_component(#{ metadata: #{ id: "test/pass", "export": "Pass", version: "0.2.2", runtime_api: #{ min_inclusive: 3, max_exclusive: 4 }, dependencies: [], capabilities: #{} },
194    schema: #{ props: #{ content: #{ schema: #{ type: "node" }, required: true, sensitive: false } }, state: #{ fields: #{} }, events: #{}, slots: #{}, parts: [] }, render: Fn("pass") });
195fn Pass(props) { render_component("test/pass", props) }
196fn pass(ctx, props) { props.content }
197"#;
198    const DIRECT_OUTER: &str = r#"
199import "test/leaf" as leaf;
200define_component(#{ metadata: #{ id: "test/outer", "export": "Outer", version: "0.2.2", runtime_api: #{ min_inclusive: 3, max_exclusive: 4 }, dependencies: ["test/leaf"], capabilities: #{} },
201    schema: #{ props: #{}, state: #{ fields: #{} }, events: #{}, slots: #{}, parts: [] }, render: Fn("outer") });
202fn Outer(props) { render_component("test/outer", props) }
203fn outer(ctx, props) { leaf::Leaf(#{ key: "nested" }) }
204"#;
205    const FORWARDING_MAIN: &str = r#"
206import "test/leaf" as leaf;
207import "test/pass" as pass;
208import "test/outer" as outer;
209fn state_schema() { #{ fields: #{ visible: #{ schema: #{ type: "bool" }, "default": #{ type: "bool", value: true } } } } }
210fn view(ctx) { column([
211    pass::Pass(#{ key: "forward", content: leaf::Leaf(#{ key: "eager" }) }).with_key("forward").retained_page(ctx.get_state("visible")),
212    outer::Outer(#{ key: "outer" }).with_key("outer").retained_page(ctx.get_state("visible")),
213]).with_key("root") }
214"#;
215
216    #[test]
217    fn page_visibility_found_top_down_is_each_node_s_own() {
218        let page =
219            |visible: bool, children: Vec<UiNode>| UiNode::column(children).retained_page(visible);
220        let mut tree = RetainedUiTree::new();
221        tree.reconcile(UiNode::column(vec![
222            page(
223                true,
224                vec![UiNode::text("a"), page(false, vec![UiNode::text("b")])],
225            ),
226            page(false, vec![page(true, vec![UiNode::text("c")])]),
227            UiNode::text("d"),
228        ]))
229        .unwrap();
230        let found = page_visibility(&tree);
231        assert!(found.iter().any(|(_, visible)| !visible));
232        for (node, visible) in &found {
233            assert_eq!(*visible, tree.is_page_visible(node.id()), "{:?}", node.id());
234        }
235        // Every hidden node and every page is found; the walk passes over
236        // visible subtrees without one.
237        for node in tree.nodes() {
238            let tracked = !tree.is_page_visible(node.id())
239                || node.attributes().contains_key(PAGE_VISIBLE)
240                || node.presented_components().next().is_some();
241            assert!(
242                !tracked || found.iter().any(|(found, _)| found.id() == node.id()),
243                "{:?}",
244                node.id()
245            );
246        }
247        assert!(found.len() < tree.len());
248    }
249
250    #[test]
251    #[allow(clippy::too_many_lines)]
252    fn forwarding_and_direct_return_keep_every_construction_owners_visibility() {
253        let mut engine = RuntimeEngine::new();
254        let source = crate::EmbeddedScriptSource::new(BTreeMap::from([
255            (
256                crate::ModuleId::parse("test/leaf").unwrap(),
257                FORWARDED_LEAF.to_owned(),
258            ),
259            (
260                crate::ModuleId::parse("test/pass").unwrap(),
261                FORWARDING_PASS.to_owned(),
262            ),
263            (
264                crate::ModuleId::parse("test/outer").unwrap(),
265                DIRECT_OUTER.to_owned(),
266            ),
267        ]));
268        engine.set_module_resolver(crate::RestrictedModuleResolver::from_source(&source).unwrap());
269        let compiled = engine
270            .compile_self_contained_named("forwarding", FORWARDING_MAIN)
271            .unwrap();
272        let schema = engine.root_state_schema(&compiled).unwrap();
273        let root = ComponentInstancePath::root("View", "one");
274        let eager = root.child("Leaf", "eager");
275        let nested = root.child("Outer", "outer").child("Leaf", "nested");
276        let runtime = Rc::new(RefCell::new(UiRuntimeState::new()));
277        let mut lifecycle = ScriptLifecycle::new(
278            compiled,
279            runtime.clone(),
280            root.clone(),
281            Some("w".to_owned()),
282            BTreeMap::new(),
283            &schema,
284        )
285        .unwrap();
286        lifecycle.start(&mut engine).unwrap();
287        for owner in [&eager, &nested] {
288            assert!(
289                runtime.borrow_mut().page_visibility.read(owner, false),
290                "forwarded owner {owner} is placed, despite the outer visual marker"
291            );
292            assert!(runtime.borrow().dirty_components().contains(owner));
293        }
294        assert!(lifecycle.render_dirty(&mut engine).unwrap());
295        let crate::UiNodeKind::Box { children } = lifecycle.root().unwrap().kind() else {
296            unreachable!()
297        };
298        assert!(children.iter().all(
299            |node| matches!(node.kind(), crate::UiNodeKind::Text { text } if text == "true:0")
300        ));
301        let crate::UiEventHandler::Script(callback) = children[0].handler("click").unwrap().clone()
302        else {
303            unreachable!()
304        };
305        assert_eq!(
306            callback.component(),
307            Some(&eager),
308            "forwarding must not adopt the caller's callback/state owner"
309        );
310        let ids = lifecycle
311            .retained()
312            .nodes()
313            .map(crate::RetainedNode::id)
314            .collect::<Vec<_>>();
315        runtime
316            .borrow_mut()
317            .set_component_state_from_host(&root, "visible", UiValue::Bool(false))
318            .unwrap();
319        lifecycle.render_dirty(&mut engine).unwrap();
320        lifecycle.render_dirty(&mut engine).unwrap();
321        for owner in [&eager, &nested] {
322            assert!(!runtime.borrow_mut().page_visibility.read(owner, false));
323        }
324        let _ = lifecycle
325            .invoke_callback_transactional(&engine, &callback, UiValue::Null)
326            .unwrap();
327        lifecycle.render_dirty(&mut engine).unwrap();
328        assert_eq!(
329            runtime.borrow().component_state.get(&eager, "count"),
330            Some(&UiValue::Integer(1)),
331            "business callbacks remain active while hidden"
332        );
333        runtime
334            .borrow_mut()
335            .set_component_state_from_host(&root, "visible", UiValue::Bool(true))
336            .unwrap();
337        lifecycle.render_dirty(&mut engine).unwrap();
338        lifecycle.render_dirty(&mut engine).unwrap();
339        assert_eq!(
340            lifecycle
341                .retained()
342                .nodes()
343                .map(crate::RetainedNode::id)
344                .collect::<Vec<_>>(),
345            ids
346        );
347        for owner in [&eager, &nested] {
348            assert!(runtime.borrow_mut().page_visibility.read(owner, false));
349        }
350        let crate::UiNodeKind::Box { children } = lifecycle.root().unwrap().kind() else {
351            unreachable!()
352        };
353        assert!(matches!(children[0].kind(), crate::UiNodeKind::Text { text } if text == "true:1"));
354        let rejected = engine
355            .compile("fn view(ctx) { throw \"reject forwarding candidate\"; }")
356            .unwrap();
357        assert!(lifecycle.reload(&mut engine, rejected, &schema).is_err());
358        for owner in [&eager, &nested] {
359            assert!(runtime.borrow_mut().page_visibility.read(owner, false));
360        }
361    }
362
363    #[test]
364    fn hidden_page_motion_retains_active_time_through_view_suspend_and_resume() {
365        let mut engine = RuntimeEngine::new();
366        let compiled = engine.compile(r#"
367fn state_schema() { #{ fields: #{ visible: #{ schema: #{ type: "bool" }, "default": #{ type: "bool", value: true } } } } }
368fn view(ctx) { column([text("moving").with_key("moving").motion(motion_transition("opacity", 0.0, 1.0, #{ duration_ms: 1000, easing: "linear" }))]).with_key("page").retained_page(ctx.get_state("visible")) }
369"#).unwrap();
370        let schema = engine.root_state_schema(&compiled).unwrap();
371        let root = ComponentInstancePath::root("View", "one");
372        let now = Instant::now();
373        let clock = crate::ManualRuntimeClock::new(now);
374        let mut state = UiRuntimeState::new();
375        state.clock = clock.clock();
376        let runtime = Rc::new(RefCell::new(state));
377        let mut lifecycle = ScriptLifecycle::new(
378            compiled,
379            runtime.clone(),
380            root.clone(),
381            Some("w".to_owned()),
382            BTreeMap::new(),
383            &schema,
384        )
385        .unwrap();
386        lifecycle.start(&mut engine).unwrap();
387        let key = runtime
388            .borrow()
389            .motion_values
390            .keys()
391            .next()
392            .unwrap()
393            .clone();
394        clock.advance(Duration::from_millis(250));
395        runtime
396            .borrow_mut()
397            .set_component_state_from_host(&root, "visible", UiValue::Bool(false))
398            .unwrap();
399        lifecycle.render_dirty(&mut engine).unwrap();
400        clock.advance(Duration::from_millis(250));
401        lifecycle.suspend(&mut engine).unwrap();
402        assert!(
403            (runtime.borrow().motions.snapshot(clock.clock().now())[&key] - 0.25).abs() < 0.001,
404            "whole-view suspension must not resample already frozen page motion"
405        );
406        clock.advance(Duration::from_secs(5));
407        lifecycle.resume(&mut engine).unwrap();
408        assert!(
409            (runtime.borrow().motions.snapshot(clock.clock().now())[&key] - 0.25).abs() < 0.001
410        );
411        assert!(
412            !runtime
413                .borrow_mut()
414                .motions
415                .tick(clock.clock().now())
416                .needs_frame
417        );
418        clock.advance(Duration::from_secs(1));
419        runtime
420            .borrow_mut()
421            .set_component_state_from_host(&root, "visible", UiValue::Bool(true))
422            .unwrap();
423        lifecycle.render_dirty(&mut engine).unwrap();
424        clock.advance(Duration::from_millis(100));
425        assert!(
426            (runtime.borrow().motions.snapshot(clock.clock().now())[&key] - 0.35).abs() < 0.001
427        );
428    }
429
430    #[test]
431    fn nested_committed_visibility_tracks_readers_and_preserves_construction_owner() {
432        let root = ComponentInstancePath::root("View", "one");
433        let child = root.child("Panel", "caller-owned");
434        let mut visibility = PageVisibility::default();
435        let mut tree = RetainedUiTree::new();
436        let make = |outer, inner| {
437            UiNode::column(vec![
438                UiNode::column(vec![
439                    UiNode::text("child").with_component_root(child.clone()),
440                ])
441                .with_key("inner")
442                .retained_page(inner),
443            ])
444            .with_key("outer")
445            .retained_page(outer)
446        };
447        assert!(
448            !visibility.read(&child, true),
449            "placement is unknown during eager construction"
450        );
451        let now = Instant::now();
452        let mut motions = MotionRuntime::new(MotionPreference::Normal);
453        tree.reconcile(make(false, true)).unwrap();
454        assert!(
455            visibility
456                .reconcile(&tree, &root, "window:w/view:one/root", &mut motions, now)
457                .is_empty()
458        );
459        tree.reconcile(make(true, true)).unwrap();
460        assert!(
461            visibility
462                .reconcile(&tree, &root, "window:w/view:one/root", &mut motions, now)
463                .contains(&child)
464        );
465        assert!(visibility.read(&child, true));
466        tree.reconcile(make(true, false)).unwrap();
467        assert!(
468            visibility
469                .reconcile(&tree, &root, "window:w/view:one/root", &mut motions, now)
470                .contains(&child)
471        );
472        assert!(!visibility.read(&child, false));
473        assert_eq!(
474            tree.nodes().find_map(|node| node.component_root()),
475            Some(&child)
476        );
477    }
478
479    #[test]
480    fn invisible_motion_freezes_and_never_requests_frames_or_catches_up() {
481        let root = ComponentInstancePath::root("View", "one");
482        let mut visibility = PageVisibility::default();
483        let mut tree = RetainedUiTree::new();
484        tree.reconcile(UiNode::text("motion").with_key("page").retained_page(true))
485            .unwrap();
486        let domain = "window:w/view:one/root";
487        let path = crate::motion::retained_node_path(domain, tree.root_id().unwrap());
488        let key = MotionKey::for_node(&path, MotionProperty::Opacity);
489        let mut motions = MotionRuntime::new(MotionPreference::Normal);
490        let now = Instant::now();
491        let mut transition = MotionTransition::new(MotionProperty::Opacity, 0.0, 1.0, 1000);
492        transition.easing = crate::MotionEasing::Linear;
493        motions
494            .start(
495                ComponentInstancePath::root("UiNode", &path),
496                MotionSource::Transition(transition),
497                now,
498            )
499            .unwrap();
500        let hide = now + Duration::from_millis(250);
501        tree.reconcile(UiNode::text("motion").with_key("page").retained_page(false))
502            .unwrap();
503        visibility.reconcile(&tree, &root, domain, &mut motions, hide);
504        let frame = motions.tick_scope(now + Duration::from_secs(20), domain);
505        assert!(!frame.needs_frame);
506        assert!((frame.values[&key] - 0.25).abs() < 0.001);
507        let show = now + Duration::from_secs(25);
508        tree.reconcile(UiNode::text("motion").with_key("page").retained_page(true))
509            .unwrap();
510        visibility.reconcile(&tree, &root, domain, &mut motions, show);
511        assert!(
512            (motions
513                .sample(&key, show + Duration::from_millis(100))
514                .unwrap()
515                - 0.35)
516                .abs()
517                < 0.001
518        );
519    }
520
521    #[test]
522    fn root_visibility_invalidates_after_first_commit_and_rejected_reload_keeps_it() {
523        let mut engine = RuntimeEngine::new();
524        let compiled = engine
525            .compile("fn view(ctx) { text(`${ctx.is_visible()}`).with_key(\"root\") }")
526            .unwrap();
527        let runtime = Rc::new(RefCell::new(UiRuntimeState::new()));
528        let mut lifecycle = ScriptLifecycle::new(
529            compiled,
530            runtime.clone(),
531            ComponentInstancePath::root("View", "one"),
532            Some("w".to_owned()),
533            BTreeMap::new(),
534            &ComponentStateSchema::default(),
535        )
536        .unwrap();
537        lifecycle.start(&mut engine).unwrap();
538        assert!(
539            matches!(lifecycle.root().unwrap().kind(), crate::UiNodeKind::Text {text} if text == "false")
540        );
541        assert!(lifecycle.render_dirty(&mut engine).unwrap());
542        assert!(
543            matches!(lifecycle.root().unwrap().kind(), crate::UiNodeKind::Text {text} if text == "true")
544        );
545        let id = lifecycle.retained().root_id();
546        let candidate = engine
547            .compile("fn view(ctx) { throw \"rejected\"; text(\"bad\").retained_page(false) }")
548            .unwrap();
549        assert!(
550            lifecycle
551                .reload(&mut engine, candidate, &ComponentStateSchema::default())
552                .is_err()
553        );
554        assert_eq!(lifecycle.retained().root_id(), id);
555        assert!(
556            runtime
557                .borrow_mut()
558                .page_visibility
559                .read(lifecycle.root_path(), false)
560        );
561        assert!(
562            matches!(lifecycle.root().unwrap().kind(), crate::UiNodeKind::Text {text} if text == "true")
563        );
564    }
565}