Guide API
Skip to main content

tvision_rs/widgets/
page_stack.rs

1//! `PageStack`, a content multiplexer (documented on the type).
2
3use crate::command::Command;
4use crate::event::Event;
5use crate::view::{Context, Group, Rect, View, ViewId};
6
7/// A content multiplexer: a group of child "page" Views of which exactly one is
8/// visible at a time.
9///
10/// Paired with a [`TabBar`](crate::widgets::TabBar): the bar broadcasts
11/// [`Command::TAB_BAR_CHANGED`], this stack (bound to the bar's id) switches the
12/// visible page through the pump broker, the way a
13/// [`Scroller`](crate::widgets::Scroller) reacts to its `ScrollBar`.
14///
15/// # Turbo Vision heritage
16/// **tvision-rs extension**: no Turbo Vision counterpart. Classic Turbo Vision has no
17/// notebook or tab-page container, only `TGroup` plus `sfVisible` /
18/// `show()` / `hide()`; `PageStack` packages exactly that.
19pub struct PageStack {
20    group: Group,
21    pages: Vec<ViewId>,
22    active: usize,
23    /// The bound TabBar id; a `TAB_BAR_CHANGED` from it triggers a page switch.
24    tab_bar: Option<ViewId>,
25}
26
27impl PageStack {
28    /// Empty stack at `bounds`.
29    pub fn new(bounds: Rect) -> Self {
30        PageStack {
31            group: Group::new(bounds),
32            pages: Vec::new(),
33            active: 0,
34            tab_bar: None,
35        }
36    }
37
38    /// Bind the `TabBar` whose broadcasts drive this stack.
39    pub fn bind_tab_bar(&mut self, id: ViewId) {
40        self.tab_bar = Some(id);
41    }
42
43    /// Insert a page; returns its id. All pages after the first start hidden.
44    /// Lay each page at the stack's full local extent before inserting.
45    pub fn insert_page(&mut self, view: Box<dyn View>) -> ViewId {
46        let id = self.group.insert(view);
47        self.pages.push(id);
48        if self.pages.len() > 1
49            && let Some(v) = self.group.child_mut(id)
50        {
51            v.state_mut().state.visible = false;
52        }
53        id
54    }
55
56    /// The active page index.
57    pub fn active(&self) -> usize {
58        self.active
59    }
60
61    /// Whether the page with `id` is currently visible. Returns `false` if the
62    /// id is not a direct child of this stack's group. Test-only assertion
63    /// helper (used by this module's unit tests and the program-level
64    /// integration test).
65    #[cfg(test)]
66    pub(crate) fn page_visible(&mut self, id: ViewId) -> bool {
67        self.group
68            .child_mut(id)
69            .map(|v| v.state().state.visible)
70            .unwrap_or(false)
71    }
72
73    /// Show page `idx`, hide the rest, move focus to it.
74    pub fn set_active(&mut self, idx: usize, ctx: &mut Context) {
75        if idx >= self.pages.len() {
76            return;
77        }
78        // Copy ids to avoid borrowing self.pages and self.group simultaneously.
79        let pages = self.pages.clone();
80        for (i, &pid) in pages.iter().enumerate() {
81            self.group.set_visible_descendant(pid, i == idx, ctx);
82        }
83        self.group.focus_child(self.pages[idx], ctx);
84        self.active = idx;
85    }
86}
87
88#[crate::delegate(to = group, skip(as_any_mut, handle_event, apply_page_sync))]
89impl View for PageStack {
90    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
91        Some(self)
92    }
93
94    /// Activate page `idx`, hiding all others. Called by the pump's
95    /// `PageStackSync` arm via virtual dispatch (no downcast).
96    fn apply_page_sync(&mut self, idx: usize, ctx: &mut Context) {
97        self.set_active(idx, ctx);
98    }
99
100    /// React to the bound `TabBar`'s broadcast by queuing a pump sync; then route
101    /// the event into the group as usual.
102    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
103        // `source.is_some()` guards against an unbound stack (tab_bar == None)
104        // matching its own None via `source == self.tab_bar` (None == None).
105        // We then read the bound id off `self.tab_bar` (mirroring the scroller,
106        // which passes its bound `h/v_scroll_bar` rather than re-unwrapping
107        // `source`) — keeping `request_sync_page_stack`'s `tab_bar: ViewId`.
108        if let Event::Broadcast { command, source } = *ev
109            && command == Command::TAB_BAR_CHANGED
110            && source.is_some()
111            && source == self.tab_bar
112            && let Some(tab_id) = self.tab_bar
113            && let Some(ps_id) = self.group.state().id()
114        {
115            ctx.request_sync_page_stack(ps_id, tab_id);
116        }
117        self.group.handle_event(ev, ctx);
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124    use crate::timer::TimerQueue;
125    use crate::view::{Deferred, DrawCtx, ViewState};
126    use std::collections::VecDeque;
127
128    struct Page {
129        st: ViewState,
130    }
131
132    impl Page {
133        fn boxed(b: Rect) -> Box<dyn View> {
134            let mut st = ViewState::new(b);
135            st.options.selectable = true;
136            Box::new(Page { st })
137        }
138    }
139
140    impl View for Page {
141        fn state(&self) -> &ViewState {
142            &self.st
143        }
144
145        fn state_mut(&mut self) -> &mut ViewState {
146            &mut self.st
147        }
148
149        fn draw(&mut self, _c: &mut DrawCtx) {}
150    }
151
152    fn ctx_run<R>(f: impl FnOnce(&mut Context) -> R) -> R {
153        let mut out = VecDeque::new();
154        let mut timers = TimerQueue::new();
155        let mut d: Vec<Deferred> = vec![];
156        let mut ctx = Context::new(&mut out, &mut timers, 0, &mut d);
157        f(&mut ctx)
158    }
159
160    #[test]
161    fn first_page_visible_rest_hidden_after_insert() {
162        let mut ps = PageStack::new(Rect::new(0, 0, 20, 10));
163        let p0 = ps.insert_page(Page::boxed(Rect::new(0, 0, 20, 10)));
164        let p1 = ps.insert_page(Page::boxed(Rect::new(0, 0, 20, 10)));
165        assert!(ps.page_visible(p0), "first page is visible");
166        assert!(!ps.page_visible(p1), "second page is hidden");
167    }
168
169    #[test]
170    fn set_active_shows_one_hides_rest() {
171        let mut ps = PageStack::new(Rect::new(0, 0, 20, 10));
172        let p0 = ps.insert_page(Page::boxed(Rect::new(0, 0, 20, 10)));
173        let p1 = ps.insert_page(Page::boxed(Rect::new(0, 0, 20, 10)));
174        ctx_run(|ctx| ps.set_active(1, ctx));
175        assert_eq!(ps.active(), 1);
176        assert!(
177            !ps.page_visible(p0),
178            "page 0 hidden after switching to page 1"
179        );
180        assert!(ps.page_visible(p1), "page 1 visible after switching to it");
181    }
182
183    #[test]
184    fn set_active_out_of_range_is_no_op() {
185        let mut ps = PageStack::new(Rect::new(0, 0, 20, 10));
186        ps.insert_page(Page::boxed(Rect::new(0, 0, 20, 10)));
187        ctx_run(|ctx| ps.set_active(5, ctx));
188        assert_eq!(ps.active(), 0, "out-of-range index leaves active unchanged");
189    }
190
191    #[test]
192    fn handle_event_queues_page_stack_sync_on_tab_bar_changed() {
193        use crate::command::Command;
194        use crate::view::ViewId;
195
196        let bounds = Rect::new(0, 0, 20, 10);
197        // Build a group to host the PageStack so it gets an id.
198        let mut group = Group::new(bounds);
199        let mut ps = PageStack::new(bounds);
200        ps.insert_page(Page::boxed(bounds));
201        ps.insert_page(Page::boxed(bounds));
202
203        // Mint a fake tab_bar id (non-null).
204        let fake_tab_bar = ViewId::next();
205        ps.bind_tab_bar(fake_tab_bar);
206
207        let ps_id = group.insert(Box::new(ps));
208
209        let mut out = VecDeque::new();
210        let mut timers = TimerQueue::new();
211        let mut deferred: Vec<Deferred> = vec![];
212        {
213            let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
214            let mut ev = Event::Broadcast {
215                command: Command::TAB_BAR_CHANGED,
216                source: Some(fake_tab_bar),
217            };
218            group
219                .find_mut(ps_id)
220                .unwrap()
221                .handle_event(&mut ev, &mut ctx);
222        }
223        assert!(
224            deferred
225                .iter()
226                .any(|d| matches!(d, Deferred::PageStackSync { .. })),
227            "TAB_BAR_CHANGED from bound tab_bar must queue PageStackSync"
228        );
229    }
230
231    #[test]
232    fn handle_event_ignores_tab_bar_changed_from_unknown_source() {
233        use crate::command::Command;
234        use crate::view::ViewId;
235
236        let bounds = Rect::new(0, 0, 20, 10);
237        let mut group = Group::new(bounds);
238        let mut ps = PageStack::new(bounds);
239        ps.insert_page(Page::boxed(bounds));
240
241        // Bind to one id but broadcast from a different one.
242        let bound_bar = ViewId::next();
243        let other_bar = ViewId::next();
244        ps.bind_tab_bar(bound_bar);
245
246        let ps_id = group.insert(Box::new(ps));
247
248        let mut out = VecDeque::new();
249        let mut timers = TimerQueue::new();
250        let mut deferred: Vec<Deferred> = vec![];
251        {
252            let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
253            let mut ev = Event::Broadcast {
254                command: Command::TAB_BAR_CHANGED,
255                source: Some(other_bar),
256            };
257            group
258                .find_mut(ps_id)
259                .unwrap()
260                .handle_event(&mut ev, &mut ctx);
261        }
262        assert!(
263            !deferred
264                .iter()
265                .any(|d| matches!(d, Deferred::PageStackSync { .. })),
266            "broadcast from a different source must NOT queue PageStackSync"
267        );
268    }
269
270    // -----------------------------------------------------------------------
271    // Snapshot tests — show-one / hide-rest at the pixel level
272    // -----------------------------------------------------------------------
273
274    /// Build a 20×3 `PageStack` with two `StaticText` pages ("PAGE ZERO" /
275    /// "PAGE ONE"), switch to `active`, render through a `HeadlessBackend`, and
276    /// return the snapshot. Only the active page's text must appear.
277    fn render(active: usize) -> String {
278        use crate::backend::{HeadlessBackend, Renderer};
279        use crate::screen::Buffer;
280        use crate::theme::Theme;
281        use crate::widgets::StaticText;
282
283        let theme = Theme::classic_blue();
284        let bounds = Rect::new(0, 0, 20, 3);
285        let mut ps = PageStack::new(bounds);
286        ps.insert_page(Box::new(StaticText::new(bounds, "PAGE ZERO")));
287        ps.insert_page(Box::new(StaticText::new(bounds, "PAGE ONE")));
288        // Switch via the public API (needs a Context for the focus/visibility ops).
289        ctx_run(|ctx| ps.set_active(active, ctx));
290
291        let (backend, screen) = HeadlessBackend::new(20, 3);
292        let mut r = Renderer::new(Box::new(backend));
293        r.render(|buf: &mut Buffer| {
294            ps.draw(&mut DrawCtx::new(buf, &theme, bounds, bounds.a));
295        });
296        screen.snapshot()
297    }
298
299    #[test]
300    fn snapshot_first_page_active() {
301        insta::assert_snapshot!(render(0));
302    }
303
304    #[test]
305    fn snapshot_second_page_active() {
306        insta::assert_snapshot!(render(1));
307    }
308}