day_pieces/pullrefresh.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day_pieces::pullrefresh: pull-to-refresh for any Day scrollable, modeled on SwiftUI's
5//! `refreshable(action:)` (DESIGN.md §15; docs/extending.md).
6//!
7//! ```ignore
8//! let refreshing = Signal::new(false);
9//! pull_to_refresh(refreshing, scroll(rows)) // or list(items, …)
10//! .on_refresh(move || {
11//! let done = refreshing.setter();
12//! std::thread::spawn(move || { reload(); done.set(false); });
13//! })
14//! ```
15//!
16//! Semantics (the same contract as `UIRefreshControl` / `SwipeRefreshLayout.setRefreshing` /
17//! ArkUI `Refresh.refreshing`): the bound `refreshing: Signal<bool>` is TWO-WAY. A user pull sets
18//! it `true` and runs `on_refresh`; the app sets it `false` when its reload completes (from a
19//! thread via [`day_reactive::Signal::setter`], or inside `day::task`); the app may also set it
20//! `true` to begin a refresh programmatically. The piece's node additionally accepts
21//! `Event::ToggleChanged` as a synthetic begin/end, so dayscript's existing `toggle:` step drives
22//! it on every backend.
23//!
24//! Tiers ([`support`]):
25//! - **Native**: iOS (`UIRefreshControl` attached to the descendant `UIScrollView`), Android
26//! (the Android toolkit's `DayPullRefresh extends SwipeRefreshLayout`), HarmonyOS (`ARKUI_NODE_REFRESH`).
27//! The piece is a container: its realized native view hosts the scrollable as a Day child, using
28//! the `cx.native` + fill-layout + `cx.under` recipe.
29//! - **Emulated**, everywhere else: a pure-composition spinner overlay (`when(refreshing, …)`),
30//! with the pull gesture detected on AppKit (elastic-scroll overscroll) and GTK
31//! (`edge-overshot`); Qt and XAML are spinner + programmatic in v1.
32
33use std::rc::Rc;
34
35use crate::Decorated;
36use day_core::{BuildCx, Flex, Piece, RNode};
37use day_reactive::Signal;
38use day_spec::Event;
39
40pub use day_spec::controls::pullrefresh::*;
41
42/// How pull-to-refresh is realized on the compiled backend: `Native` (a real platform refresh
43/// control drives the gesture and indicator) or `Emulated` (composition overlay; gesture where the
44/// toolkit exposes overscroll). Never `Unsupported`: the emulated tier always works.
45pub fn support() -> day_spec::Support {
46 let support = day_core::capability(day_spec::Cap::PullRefresh);
47 if support == day_spec::Support::Unsupported {
48 day_spec::Support::Emulated
49 } else {
50 support
51 }
52}
53
54/// A scrollable wrapped with pull-to-refresh. Build with [`pull_to_refresh`].
55pub struct PullRefresh<P: Piece> {
56 refreshing: Signal<bool>,
57 child: P,
58 on_refresh: Option<Rc<dyn Fn()>>,
59}
60
61/// Wrap `child` (a `scroll(...)` or `list(...)`) with pull-to-refresh bound to `refreshing`.
62pub fn pull_to_refresh<P: Piece>(refreshing: Signal<bool>, child: P) -> PullRefresh<P> {
63 PullRefresh {
64 refreshing,
65 child,
66 on_refresh: None,
67 }
68}
69
70#[crate::builder(PullRefreshBuilder)]
71impl<P: Piece> PullRefresh<P> {
72 /// Run `f` when a refresh BEGINS (user pull, dayscript toggle, or programmatic
73 /// `refreshing.set(true)` routed through a pull). Start the reload here and set the bound
74 /// signal back to `false` when it completes.
75 pub fn on_refresh(mut self, f: impl Fn() + 'static) -> Self {
76 self.on_refresh = Some(Rc::new(f));
77 self
78 }
79}
80
81/// The begin path shared by every entry point: flip the signal (if not already refreshing) and run
82/// the app's `on_refresh` exactly once per begin.
83fn begin(refreshing: Signal<bool>, on_refresh: &Option<Rc<dyn Fn()>>) {
84 if !refreshing.get_untracked() {
85 refreshing.set(true);
86 if let Some(f) = on_refresh {
87 f();
88 }
89 }
90}
91
92/// Wire the piece's node: native/emulated pull begins arrive as `Event::Custom`; dayscript's
93/// `toggle:` step arrives as `Event::ToggleChanged` (synthetic begin/end on every backend).
94fn wire(cx: &mut BuildCx, node: RNode, refreshing: Signal<bool>, on_refresh: Option<Rc<dyn Fn()>>) {
95 cx.on(node, move |ev| match ev {
96 Event::Custom { .. } => begin(refreshing, &on_refresh),
97 Event::ToggleChanged(true) => begin(refreshing, &on_refresh),
98 Event::ToggleChanged(false) => refreshing.set(false),
99 _ => {}
100 });
101}
102
103impl<P: Piece> Piece for PullRefresh<P> {
104 fn build(self, cx: &mut BuildCx) -> RNode {
105 if support() == day_spec::Support::Native {
106 build_native(self, cx)
107 } else {
108 build_emulated(self, cx)
109 }
110 }
111}
112
113// ---------------------------------------------------------------------------
114// Native tier: the piece is a container; its realized native view (passthrough host on iOS,
115// SwipeRefreshLayout on Android, Refresh node on ArkUI) hosts the scrollable as a Day child.
116// FrameLayout places that single child at the container's full bounds; the native side owns the
117// refresh indicator. App-driven signal changes patch through (watch skips the initial value).
118// ---------------------------------------------------------------------------
119
120fn build_native<P: Piece>(piece: PullRefresh<P>, cx: &mut BuildCx) -> RNode {
121 use day_core::{FrameLayout, with_tree};
122 use day_reactive::watch;
123
124 let PullRefresh {
125 refreshing,
126 child,
127 on_refresh,
128 } = piece;
129 let node = cx.native(
130 KIND,
131 &RefreshProps {
132 refreshing: refreshing.get_untracked(),
133 },
134 Rc::new(FrameLayout {
135 width: None,
136 height: None,
137 }),
138 Flex {
139 grow_w: true,
140 grow_h: true,
141 ..Default::default()
142 },
143 day_core::Boundary::Yes,
144 );
145 cx.under(node, |cx| {
146 let _ = child.build(cx);
147 });
148 wire(cx, node, refreshing, on_refresh.clone());
149 // Two-way: app writes → native indicator. A native-initiated begin sets the signal, which
150 // patches back a redundant-but-idempotent SetRefreshing(true) (begin/setRefreshing while
151 // already refreshing is a no-op on every platform).
152 watch(
153 move || refreshing.get(),
154 move |now, _| {
155 let set = *now;
156 with_tree(|t| t.patch(node, Box::new(RefreshPatch::SetRefreshing(set)), false));
157 },
158 );
159 node
160}
161
162// ---------------------------------------------------------------------------
163// Emulated tier: pure composition, an overlay container whose first child is the scrollable
164// (optionally tweaked with per-backend overscroll observation) and whose second is a
165// `when(refreshing, spinner-chip)` overlay pinned top-center. No custom kind, no renderer: the
166// container is the same native panel as column/row, so this path works on every backend
167// (including mock) with zero native code.
168// ---------------------------------------------------------------------------
169
170fn build_emulated<P: Piece>(piece: PullRefresh<P>, cx: &mut BuildCx) -> RNode {
171 use crate::prelude::{Color, Decorate, spinner, when};
172 use day_core::{Alignment, Boundary, OverlayLayout};
173 use day_spec::props::ContainerProps;
174
175 let PullRefresh {
176 refreshing,
177 child,
178 on_refresh,
179 } = piece;
180 let node = cx.native(
181 day_spec::kinds::CONTAINER,
182 &ContainerProps::default(),
183 Rc::new(OverlayLayout {
184 align: Alignment::Top,
185 size_to_first: false,
186 }),
187 Flex {
188 grow_w: true,
189 grow_h: true,
190 ..Default::default()
191 },
192 Boundary::No,
193 );
194 cx.under(node, |cx| {
195 // The scrollable (fills: it grows in both axes), with the backend's overscroll
196 // observation attached where the toolkit exposes one (AppKit elastic scroll,
197 // GTK edge-overshot). The tweak runs at mount with the realized scroll node. The glue
198 // does not call into the reactive runtime from inside native dispatch: it emits a
199 // `pullrefresh:begin` Custom event on the host node through the backend's sink (queued,
200 // pumped at a safe point, and panic-contained), which `wire` below turns into the begin.
201 let host = day_core::rnode_to_id(node);
202 child
203 .tweak(move |child| {
204 day_core::with_tree(|tree| tree.attach_refresh(child, host));
205 })
206 .build(cx);
207 // The refresh indicator: a floating chip with the native indeterminate spinner, shown
208 // while `refreshing`, the emulated stand-in for the platform refresh header.
209 let _ = when(
210 move || refreshing.get(),
211 || {
212 spinner()
213 .padding(10.0)
214 .background(Color::rgba(0.5, 0.5, 0.55, 0.18))
215 .corner_radius(21.0)
216 .padding(10.0)
217 },
218 )
219 .build(cx);
220 });
221 wire(cx, node, refreshing, on_refresh);
222 node
223}
224
225// ---------------------------------------------------------------------------
226// Per-toolkit native renderers + emulated gesture glue: one file per backend, gated to its
227// feature + target (the webview convention).
228// ---------------------------------------------------------------------------
229
230// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
231
232/// Pull-to-refresh's conformance cases (docs/testing.md). The `toggle` step is the synthetic
233/// pull, on every backend.
234#[cfg(feature = "conformance")]
235pub mod conformance {
236 use crate::*;
237 use day_core::conformance::{Case, Drive};
238 use day_reactive::Signal;
239
240 use super::{KIND, pull_to_refresh};
241
242 /// A pull begins a refresh: `refreshing` goes true and `on_refresh` runs; the app ending it
243 /// sets it false.
244 #[day_macros::test(day_core)]
245 fn pullrefresh_begins_and_ends() -> Case {
246 Case::new()
247 .proves(KIND)
248 .page(|| {
249 let refreshing = Signal::new(false);
250 let runs = Signal::new(0i64);
251 column((
252 label(move || format!("refreshing {} runs {}", refreshing.get(), runs.get()))
253 .id(day_core::id!(pullrefresh::state)),
254 button("Done")
255 .action(move || refreshing.set(false))
256 .id(day_core::id!(pullrefresh::done)),
257 pull_to_refresh(refreshing, scroll(column((label("Row 1"), label("Row 2")))))
258 .on_refresh(move || runs.update(|n| *n += 1))
259 .id(day_core::id!(pullrefresh::pull))
260 .height(200.0),
261 ))
262 })
263 .drive(|d: Drive| async move {
264 d.toggle("pullrefresh::pull", true).await?;
265 d.assert_text("pullrefresh::state", "refreshing true runs 1")
266 .await?;
267 d.tap("pullrefresh::done").await?;
268 d.assert_text("pullrefresh::state", "refreshing false runs 1")
269 .await
270 })
271 }
272}
273
274/// Whether a user pull gesture can begin a refresh on this toolkit.
275pub fn gesture_support() -> day_spec::Support {
276 day_core::capability(day_spec::Cap::PullRefreshGesture)
277}