Skip to main content

day_pieces/
pager.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Native interactive horizontal paging. Slots have stable native identities; `order`
5//! chooses which slots participate and their reading order. Changing order never rebuilds
6//! a page. Apps must defer changing slot contents while `busy` is true. Native callbacks
7//! carry the presentation epoch, so delayed completions cannot select a recycled slot.
8use crate::Decorated;
9use day_core::{Boundary, BuildCx, Flex, Layout, LayoutOps, Piece, RNode};
10use day_reactive::{AnyBinding, Binding, Signal};
11use day_spec::{Event, Proposal, Rect, Size};
12use std::rc::Rc;
13
14pub use day_spec::controls::pager::*;
15
16/// A native interactive pager (docs/pager.md). Built by [`pager`].
17#[must_use]
18pub struct Pager {
19    state: Signal<PagerState>,
20    busy: Signal<bool>,
21    pages: Vec<day_core::AnyPiece>,
22    settled: Rc<dyn Fn(usize)>,
23    progress: Option<AnyBinding<f64>>,
24}
25pub fn pager(
26    state: Signal<PagerState>,
27    busy: Signal<bool>,
28    pages: Vec<day_core::AnyPiece>,
29    settled: impl Fn(usize) + 'static,
30) -> Pager {
31    Pager {
32        state,
33        busy,
34        pages,
35        settled: Rc::new(settled),
36        progress: None,
37    }
38}
39
40#[day_macros::builder(PagerBuilder)]
41impl Pager {
42    /// Follow the pager's position (docs/pager.md "Progress"): `progress` is the place in
43    /// reading order, in pages, so `0.0` is the first page and `1.5` is halfway from the
44    /// second to the third. A native pager writes it continuously while a page is dragged
45    /// (probe `Cap::PagerProgress`), which is what lets a page indicator track the finger;
46    /// everywhere else it steps to the selected page's position when the selection changes.
47    ///
48    /// ```ignore
49    /// let progress = Signal::new(0.0);
50    /// column((pager(state, busy, pages, settle).progress(progress), dots(progress)))
51    /// ```
52    pub fn progress(mut self, progress: impl Binding<f64>) -> Self {
53        self.progress = Some(AnyBinding::new(progress));
54        self
55    }
56}
57
58struct PageLayout;
59impl Layout for PageLayout {
60    fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
61        Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0))
62    }
63    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
64        for &child in children {
65            cx.place_child_native(
66                child,
67                Rect::new(0.0, 0.0, bounds.size.width, bounds.size.height),
68            );
69        }
70    }
71}
72impl Piece for Pager {
73    fn build(self, cx: &mut BuildCx) -> RNode {
74        use crate::prelude::*;
75        let Self {
76            state,
77            busy,
78            pages,
79            settled,
80            progress,
81        } = self;
82        let native = support() == day_spec::Support::Native;
83        let node = if native {
84            cx.native(
85                KIND,
86                &PagerProps {
87                    slots: pages.len(),
88                    track_progress: progress.is_some(),
89                },
90                Rc::new(PageLayout),
91                Flex {
92                    grow_w: true,
93                    grow_h: true,
94                    ..Default::default()
95                },
96                Boundary::Yes,
97            )
98        } else {
99            cx.native(
100                day_spec::kinds::CONTAINER,
101                &day_spec::props::ContainerProps::default(),
102                Rc::new(PageLayout),
103                Flex {
104                    grow_w: true,
105                    grow_h: true,
106                    ..Default::default()
107                },
108                Boundary::Yes,
109            )
110        };
111        cx.under(node, |cx| {
112            for (slot, page) in pages.into_iter().enumerate() {
113                // A stable native wrapper per slot, even when its content is a conditional.
114                let page = column((page,)).grow(Dimension::Both);
115                if native {
116                    page.build(cx);
117                } else {
118                    let child = page.build(cx);
119                    let show =
120                        move || state.get().selected == slot && state.get().order.contains(&slot);
121                    day_core::with_tree(|t| t.set_presented(child, show()));
122                    day_reactive::watch(show, move |visible, _| {
123                        day_core::with_tree(|t| t.set_presented(child, *visible));
124                    });
125                }
126            }
127        });
128        // The selected page's place in reading order is the progress at rest: where a toolkit
129        // reports nothing continuous, this is all of it.
130        if let Some(progress) = progress {
131            day_reactive::bind(
132                move || {
133                    let state = state.get();
134                    state.order.iter().position(|slot| *slot == state.selected)
135                },
136                move |at: &Option<usize>| {
137                    if let Some(at) = at {
138                        progress.set_if_changed(*at as f64);
139                    }
140                },
141            );
142        }
143        let track = progress;
144        cx.on(node, move |event| {
145            // Standard accessibility/automation selection uses logical positions. Native
146            // gestures report only settled slot identities on the epoch-tagged channel.
147            if let Event::SelectionChanged(index) = event {
148                if !busy.get_untracked()
149                    && *index >= 0
150                    && let Some(slot) = state.get_untracked().order.get(*index as usize).copied()
151                {
152                    settled(slot);
153                }
154                return;
155            }
156            if let Event::Custom { text, .. } = event {
157                let fields: Vec<_> = text.split_whitespace().collect();
158                if fields.len() < 2 {
159                    return;
160                }
161                let Ok(epoch) = fields[1].parse::<u64>() else {
162                    return;
163                };
164                if epoch != state.get_untracked().epoch {
165                    return;
166                }
167                match fields[0] {
168                    "progress" => {
169                        if let (Some(progress), Some(at)) =
170                            (&track, fields.get(2).and_then(|s| s.parse::<f64>().ok()))
171                            && at.is_finite()
172                        {
173                            progress.set_if_changed(at);
174                        }
175                    }
176                    "begin" => busy.set(true),
177                    "settle" => {
178                        if let Some(slot) = fields.get(2).and_then(|s| s.parse::<usize>().ok())
179                            && state.get_untracked().accepts(epoch, slot)
180                        {
181                            // Keep the ordering frozen through the commit callback.
182                            settled(slot);
183                        }
184                        busy.set(false);
185                    }
186                    _ => {}
187                }
188            }
189        });
190        if native {
191            day_reactive::Effect::new(move || {
192                let value = state.get();
193                day_core::with_tree(|tree| {
194                    tree.patch(node, Box::new(PagerPatch(value.clone())), false);
195                });
196            });
197        }
198        node
199    }
200}
201
202/// The pager's conformance cases (docs/testing.md). `select` is the synthetic settle on every
203/// backend: it reports a reading-order position, which the pager maps through `order` to a slot.
204#[cfg(feature = "conformance")]
205pub mod conformance {
206    use crate::*;
207    use day_core::conformance::{Case, Drive};
208    use day_reactive::Signal;
209
210    use super::{KIND, PagerState, pager};
211
212    /// Selecting a position commits that position's slot, and reversing the order maps the same
213    /// position to a different slot without rebuilding a page.
214    #[day_macros::test(day_core)]
215    fn pager_selection_commits_the_slot_in_reading_order() -> Case {
216        Case::new()
217            .proves(KIND)
218            .page(|| {
219                let state = Signal::new(PagerState {
220                    order: vec![0, 1, 2],
221                    selected: 0,
222                    epoch: 1,
223                });
224                let busy = Signal::new(false);
225                let committed = Signal::new(String::from("none"));
226                column((
227                    label(move || format!("slot {}", committed.get()))
228                        .id(day_core::id!(pager::pager_state)),
229                    button("Reverse")
230                        .action(move || {
231                            state.update(|s| {
232                                s.order.reverse();
233                                s.epoch += 1;
234                            });
235                        })
236                        .id(day_core::id!(pager::pager_reverse)),
237                    pager(
238                        state,
239                        busy,
240                        vec![
241                            label("Page A").any(),
242                            label("Page B").any(),
243                            label("Page C").any(),
244                        ],
245                        move |slot| {
246                            committed.set(slot.to_string());
247                            state.update(|s| s.selected = slot);
248                        },
249                    )
250                    .id(day_core::id!(pager::pager))
251                    .height(200.0),
252                ))
253            })
254            .drive(|d: Drive| async move {
255                d.select("pager::pager", 1).await?;
256                d.assert_text("pager::pager_state", "slot 1").await?;
257                d.tap("pager::pager_reverse").await?;
258                d.select("pager::pager", 0).await?;
259                d.assert_text("pager::pager_state", "slot 2").await
260            })
261    }
262
263    /// The progress binding rests on the selected page's place in reading order
264    /// (docs/pager.md "Progress").
265    #[day_macros::test(day_core)]
266    fn pager_progress_rests_on_the_selected_page() -> Case {
267        Case::new()
268            .proves(KIND)
269            .page(|| {
270                let state = Signal::new(PagerState {
271                    order: vec![0, 1, 2],
272                    selected: 0,
273                    epoch: 1,
274                });
275                let busy = Signal::new(false);
276                let progress = Signal::new(0.0_f64);
277                column((
278                    label(move || format!("at {:.1}", progress.get()))
279                        .id(day_core::id!(pager::progress_label)),
280                    pager(
281                        state,
282                        busy,
283                        vec![
284                            label("Page A").any(),
285                            label("Page B").any(),
286                            label("Page C").any(),
287                        ],
288                        move |slot| state.update(|s| s.selected = slot),
289                    )
290                    .progress(progress)
291                    .id(day_core::id!(pager::progress_pager))
292                    .height(200.0),
293                ))
294            })
295            .drive(|d: Drive| async move {
296                d.assert_text("pager::progress_label", "at 0.0").await?;
297                d.select("pager::progress_pager", 2).await?;
298                d.assert_text("pager::progress_label", "at 2.0").await?;
299                d.select("pager::progress_pager", 1).await?;
300                d.assert_text("pager::progress_label", "at 1.0").await
301            })
302    }
303}
304
305/// Whether the selected toolkit implements this control.
306#[must_use]
307pub fn support() -> day_spec::Support {
308    day_core::capability(day_spec::Cap::Pager)
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314    #[test]
315    fn recycled_slots_reject_stale_completions_and_absent_neighbors() {
316        let state = PagerState {
317            order: vec![2, 0],
318            selected: 2,
319            epoch: 4,
320        };
321        assert!(state.accepts(4, 0));
322        assert!(!state.accepts(3, 0));
323        assert!(!state.accepts(4, 1));
324    }
325}