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