1use std::fmt::{self, Debug};
4use std::rc::Rc;
5
6use waft_foundation::{App, Handle};
7
8use crate::framework::{
9 BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
10};
11use crate::widgets::notification_listener::NotificationListener;
12use crate::widgets::scroll_notification::ScrollNotification;
13use crate::widgets::scroll_position::ScrollMetricsNotification;
14
15pub type ScrollNotificationCallback = Rc<dyn Fn(&mut App, &dyn ScrollNotification)>;
22
23#[derive(Debug)]
25struct ScrollNotificationObserverScope {
26 scroll_notification_observer_state: Handle<ScrollNotificationObserverState>,
27 child: WidgetRef,
28}
29
30impl InheritedWidget for ScrollNotificationObserverScope {
31 fn child(&self) -> &WidgetRef {
32 &self.child
33 }
34
35 fn update_should_notify(&self, old: &ScrollNotificationObserverScope) -> bool {
36 self.scroll_notification_observer_state != old.scroll_notification_observer_state
37 }
38}
39
40#[derive(Debug)]
62pub struct ScrollNotificationObserver {
63 pub key: Option<KeyRef>,
64
65 pub child: WidgetRef,
67}
68
69impl ScrollNotificationObserver {
70 #[cfg_attr(debug_assertions, track_caller)]
72 pub fn new<K>(child: impl IntoWidget<K>) -> ScrollNotificationObserver {
73 ScrollNotificationObserver {
74 key: None,
75 child: child.into_widget(),
76 }
77 }
78
79 pub fn key(mut self, key: KeyRef) -> ScrollNotificationObserver {
81 self.key = Some(key);
82 self
83 }
84
85 pub fn maybe_of(
98 app: &mut App,
99 context: BuildContext,
100 ) -> Option<Handle<ScrollNotificationObserverState>> {
101 context
102 .depend_on_inherited_widget_of_exact_type::<ScrollNotificationObserverScope>(app)
103 .map(|scope| scope.scroll_notification_observer_state)
104 }
105
106 pub fn of(app: &mut App, context: BuildContext) -> Handle<ScrollNotificationObserverState> {
120 ScrollNotificationObserver::maybe_of(app, context).expect(
121 "ScrollNotificationObserver.of() was called with a context that does not contain a \
122 ScrollNotificationObserver widget.\n\
123 No ScrollNotificationObserver widget ancestor could be found starting from the \
124 context that was passed to ScrollNotificationObserver.of(). This can happen \
125 because you are using a widget that looks for a ScrollNotificationObserver \
126 ancestor, but no such ancestor exists.",
127 )
128 }
129}
130
131impl StatefulWidget for ScrollNotificationObserver {
132 type State = ScrollNotificationObserverState;
133
134 fn key(&self) -> Option<&KeyRef> {
135 self.key.as_ref()
136 }
137
138 fn create_state(&self) -> ScrollNotificationObserverState {
139 ScrollNotificationObserverState {
140 state: StateData::new(),
141 listeners: Some(Vec::new()),
142 }
143 }
144}
145
146pub struct ScrollNotificationObserverState {
154 state: StateData<ScrollNotificationObserver>,
155 listeners: Option<Vec<ScrollNotificationCallback>>,
156}
157
158impl ScrollNotificationObserverState {
159 fn debug_assert_not_disposed(self: Handle<Self>, app: &App) -> bool {
160 debug_assert!(
161 app.get(self).listeners.is_some(),
162 "A ScrollNotificationObserverState was used after being disposed. Once you have \
163 called dispose() on a ScrollNotificationObserverState, it can no longer be used."
164 );
165 true
166 }
167
168 pub fn add_listener(self: Handle<Self>, app: &mut App, listener: ScrollNotificationCallback) {
171 debug_assert!(self.debug_assert_not_disposed(app));
172 app.get_mut(self)
173 .listeners
174 .as_mut()
175 .expect("a live observer keeps its listeners")
176 .push(listener);
177 }
178
179 pub fn remove_listener(
181 self: Handle<Self>,
182 app: &mut App,
183 listener: &ScrollNotificationCallback,
184 ) {
185 debug_assert!(self.debug_assert_not_disposed(app));
186 let listeners = app
187 .get_mut(self)
188 .listeners
189 .as_mut()
190 .expect("a live observer keeps its listeners");
191 if let Some(index) = listeners
192 .iter()
193 .position(|entry| Rc::ptr_eq(entry, listener))
194 {
195 listeners.remove(index);
196 }
197 }
198
199 fn notify_listeners(self: Handle<Self>, app: &mut App, notification: &dyn ScrollNotification) {
200 debug_assert!(self.debug_assert_not_disposed(app));
201 let local_listeners = app
202 .get(self)
203 .listeners
204 .clone()
205 .expect("a live observer keeps its listeners");
206 if local_listeners.is_empty() {
207 return;
208 }
209
210 for entry in local_listeners {
211 let still_registered = app.get(self).listeners.as_ref().is_some_and(|listeners| {
213 listeners
214 .iter()
215 .any(|listener| Rc::ptr_eq(listener, &entry))
216 });
217 if still_registered {
218 entry(app, notification);
219 }
220 }
221 }
222}
223
224impl State for ScrollNotificationObserverState {
225 type Widget = ScrollNotificationObserver;
226 crate::state_accessors!();
227
228 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
229 let child = self.widget(app).child.clone();
230 NotificationListener::<ScrollMetricsNotification>::new(
231 NotificationListener::<dyn ScrollNotification>::new(
232 ScrollNotificationObserverScope {
233 scroll_notification_observer_state: self,
234 child,
235 }
236 .into_widget(),
237 )
238 .on_notification(move |app, notification| {
239 self.notify_listeners(app, notification);
240 false
241 })
242 .into_widget(),
243 )
244 .on_notification(move |app, notification: &ScrollMetricsNotification| {
245 let update = notification.as_scroll_update();
249 self.notify_listeners(app, &update);
250 false
251 })
252 .into_widget()
253 }
254
255 fn dispose(self: Handle<Self>, app: &mut App) {
256 debug_assert!(self.debug_assert_not_disposed(app));
257 app.get_mut(self).listeners = None;
258 }
259}
260
261impl Debug for ScrollNotificationObserverState {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 f.debug_struct("ScrollNotificationObserverState")
264 .field(
265 "listeners",
266 &self.listeners.as_ref().map(|listeners| listeners.len()),
267 )
268 .finish()
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use std::cell::RefCell;
275 use waft_foundation::AppCell;
276
277 use waft_painting::AxisDirection;
278
279 use super::*;
280 use crate::framework::{AnyElement, Element, Notification};
281 use crate::test_harness::Harness;
282 use crate::widgets::basic::SizedBox;
283 use crate::widgets::scroll_metrics::{FixedScrollMetrics, ScrollMetrics};
284 use crate::widgets::scroll_notification::ScrollUpdateNotification;
285
286 fn descendant(harness: &Harness, app: &App, depth: usize) -> AnyElement {
287 let mut element = harness.root.as_element();
288 for _ in 0..=depth {
289 element = element.children(app)[0];
290 }
291 element
292 }
293
294 fn metrics() -> Rc<dyn ScrollMetrics> {
295 Rc::new(FixedScrollMetrics::new(
296 Some(0.0),
297 Some(400.0),
298 Some(10.0),
299 Some(100.0),
300 AxisDirection::Down,
301 1.0,
302 ))
303 }
304
305 fn mount(app: &mut App) -> (Harness, BuildContext) {
307 let harness = Harness::mount(
308 app,
309 ScrollNotificationObserver::new(SizedBox::shrink()).into_widget(),
310 );
311 harness.pump(app);
312 let context = descendant(&harness, app, 4);
314 (harness, context)
315 }
316
317 #[test]
318 fn every_listener_sees_a_descendants_scroll_notification() {
319 let cell = AppCell::new();
320 let mut app = cell.borrow_mut();
321 let (_harness, context) = mount(&mut app);
322 let observer = ScrollNotificationObserver::of(&mut app, context);
323
324 let seen = Rc::new(RefCell::new(Vec::new()));
325 for label in ["first", "second"] {
326 let seen = seen.clone();
327 observer.add_listener(
328 &mut app,
329 Rc::new(move |_app, notification| {
330 seen.borrow_mut()
331 .push((label, notification.metrics().pixels()));
332 }),
333 );
334 }
335
336 ScrollUpdateNotification::new(metrics(), context).dispatch(&mut app, Some(context));
337
338 assert_eq!(*seen.borrow(), [("first", 10.0), ("second", 10.0)]);
339 }
340
341 #[test]
342 fn a_metrics_notification_arrives_as_a_scroll_update() {
343 let cell = AppCell::new();
344 let mut app = cell.borrow_mut();
345 let (_harness, context) = mount(&mut app);
346 let observer = ScrollNotificationObserver::of(&mut app, context);
347
348 let seen = Rc::new(RefCell::new(Vec::new()));
349 let recorded = seen.clone();
350 observer.add_listener(
351 &mut app,
352 Rc::new(move |_app, notification| {
353 recorded
354 .borrow_mut()
355 .push(notification.metrics().max_scroll_extent());
356 }),
357 );
358
359 ScrollMetricsNotification::new(metrics(), context).dispatch(&mut app, Some(context));
360
361 assert_eq!(*seen.borrow(), [400.0]);
362 }
363
364 #[test]
365 fn a_removed_listener_stops_hearing_notifications() {
366 let cell = AppCell::new();
367 let mut app = cell.borrow_mut();
368 let (_harness, context) = mount(&mut app);
369 let observer = ScrollNotificationObserver::of(&mut app, context);
370
371 let seen = Rc::new(RefCell::new(0));
372 let recorded = seen.clone();
373 let listener: ScrollNotificationCallback = Rc::new(move |_app, _notification| {
374 *recorded.borrow_mut() += 1;
375 });
376 observer.add_listener(&mut app, listener.clone());
377
378 ScrollUpdateNotification::new(metrics(), context).dispatch(&mut app, Some(context));
379 assert_eq!(*seen.borrow(), 1);
380
381 observer.remove_listener(&mut app, &listener);
382 ScrollUpdateNotification::new(metrics(), context).dispatch(&mut app, Some(context));
383 assert_eq!(*seen.borrow(), 1);
384 }
385}