use std::any::Any;
use std::cell::Cell;
use std::fmt::{self, Debug};
use std::rc::Rc;
use waft_foundation::{App, Handle};
use waft_gestures::{DragEndDetails, DragStartDetails, DragUpdateDetails};
use waft_rendering::ScrollDirection;
use crate::framework::{BuildContext, Element, Notification, NotificationNode, NotificationTarget};
use crate::widgets::scroll_metrics::ScrollMetrics;
#[derive(Debug, Default)]
pub struct ViewportNotificationData {
depth: Cell<u32>,
}
impl ViewportNotificationData {
pub fn new() -> ViewportNotificationData {
ViewportNotificationData::default()
}
pub fn with_depth(depth: u32) -> ViewportNotificationData {
ViewportNotificationData {
depth: Cell::new(depth),
}
}
pub fn depth_cell(&self) -> &Cell<u32> {
&self.depth
}
}
pub trait ViewportNotificationMixin: Notification {
fn viewport_notification_data(&self) -> &ViewportNotificationData;
fn depth(&self) -> u32 {
self.viewport_notification_data().depth.get()
}
fn debug_fill_description(&self, description: &mut Vec<String>) {
let depth = self.depth();
let locality = if depth == 0 { "local" } else { "remote" };
description.push(format!("depth: {depth} ({locality})"));
}
}
pub trait ViewportElementMixin: Element {
fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
let this = self.as_element();
let parent_tree = this
.parent(app)
.and_then(|parent| parent.notification_tree(app));
this.set_notification_tree(app, Some(Rc::new(NotificationNode::new(parent_tree, this))));
}
fn on_notification(self: Handle<Self>, app: &mut App, notification: &dyn Notification) -> bool {
let _ = app;
if let Some(depth) = notification.viewport_depth() {
depth.set(depth.get() + 1);
}
false
}
}
pub struct ScrollNotificationData {
pub metrics: Rc<dyn ScrollMetrics>,
pub context: Option<BuildContext>,
}
pub trait ScrollNotification: ViewportNotificationMixin {
fn scroll_notification_data(&self) -> &ScrollNotificationData;
fn metrics(&self) -> &Rc<dyn ScrollMetrics> {
&self.scroll_notification_data().metrics
}
fn context(&self) -> Option<BuildContext> {
self.scroll_notification_data().context
}
}
impl NotificationTarget for dyn ScrollNotification {
fn cast(notification: &dyn Notification) -> Option<&dyn ScrollNotification> {
notification.as_scroll_notification()
}
}
fn fill_scroll_description(notification: &dyn ScrollNotification, description: &mut Vec<String>) {
ViewportNotificationMixin::debug_fill_description(notification, description);
description.push(format!("{:?}", notification.metrics()));
}
pub struct ScrollStartNotification {
viewport_notification: ViewportNotificationData,
scroll_notification: ScrollNotificationData,
pub drag_details: Option<DragStartDetails>,
}
impl ScrollStartNotification {
pub fn new(
metrics: Rc<dyn ScrollMetrics>,
context: Option<BuildContext>,
) -> ScrollStartNotification {
ScrollStartNotification {
viewport_notification: ViewportNotificationData::new(),
scroll_notification: ScrollNotificationData { metrics, context },
drag_details: None,
}
}
pub fn drag_details(mut self, drag_details: DragStartDetails) -> ScrollStartNotification {
self.drag_details = Some(drag_details);
self
}
}
impl Notification for ScrollStartNotification {
fn as_any(&self) -> &dyn Any {
self
}
fn viewport_depth(&self) -> Option<&Cell<u32>> {
Some(&self.viewport_notification.depth)
}
fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
Some(self)
}
}
impl ViewportNotificationMixin for ScrollStartNotification {
fn viewport_notification_data(&self) -> &ViewportNotificationData {
&self.viewport_notification
}
}
impl ScrollNotification for ScrollStartNotification {
fn scroll_notification_data(&self) -> &ScrollNotificationData {
&self.scroll_notification
}
}
impl Debug for ScrollStartNotification {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut description = Vec::new();
fill_scroll_description(self, &mut description);
if let Some(drag_details) = &self.drag_details {
description.push(format!("{drag_details:?}"));
}
write!(f, "ScrollStartNotification({})", description.join(", "))
}
}
pub struct ScrollUpdateNotification {
viewport_notification: ViewportNotificationData,
scroll_notification: ScrollNotificationData,
pub drag_details: Option<DragUpdateDetails>,
pub scroll_delta: Option<f64>,
}
impl ScrollUpdateNotification {
pub fn new(metrics: Rc<dyn ScrollMetrics>, context: BuildContext) -> ScrollUpdateNotification {
ScrollUpdateNotification {
viewport_notification: ViewportNotificationData::new(),
scroll_notification: ScrollNotificationData {
metrics,
context: Some(context),
},
drag_details: None,
scroll_delta: None,
}
}
pub fn drag_details(mut self, drag_details: DragUpdateDetails) -> ScrollUpdateNotification {
self.drag_details = Some(drag_details);
self
}
pub fn scroll_delta(mut self, scroll_delta: f64) -> ScrollUpdateNotification {
self.scroll_delta = Some(scroll_delta);
self
}
pub fn with_depth(mut self, depth: u32) -> ScrollUpdateNotification {
self.viewport_notification = ViewportNotificationData::with_depth(depth);
self
}
}
impl Notification for ScrollUpdateNotification {
fn as_any(&self) -> &dyn Any {
self
}
fn viewport_depth(&self) -> Option<&Cell<u32>> {
Some(&self.viewport_notification.depth)
}
fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
Some(self)
}
}
impl ViewportNotificationMixin for ScrollUpdateNotification {
fn viewport_notification_data(&self) -> &ViewportNotificationData {
&self.viewport_notification
}
}
impl ScrollNotification for ScrollUpdateNotification {
fn scroll_notification_data(&self) -> &ScrollNotificationData {
&self.scroll_notification
}
}
impl Debug for ScrollUpdateNotification {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut description = Vec::new();
fill_scroll_description(self, &mut description);
description.push(match self.scroll_delta {
Some(scroll_delta) => format!("scrollDelta: {scroll_delta:?}"),
None => "scrollDelta: null".to_string(),
});
if let Some(drag_details) = &self.drag_details {
description.push(format!("{drag_details:?}"));
}
write!(f, "ScrollUpdateNotification({})", description.join(", "))
}
}
pub struct OverscrollNotification {
viewport_notification: ViewportNotificationData,
scroll_notification: ScrollNotificationData,
pub drag_details: Option<DragUpdateDetails>,
pub overscroll: f64,
pub velocity: f64,
}
impl OverscrollNotification {
pub fn new(
metrics: Rc<dyn ScrollMetrics>,
context: BuildContext,
overscroll: f64,
) -> OverscrollNotification {
debug_assert!(overscroll.is_finite());
debug_assert!(overscroll != 0.0);
OverscrollNotification {
viewport_notification: ViewportNotificationData::new(),
scroll_notification: ScrollNotificationData {
metrics,
context: Some(context),
},
drag_details: None,
overscroll,
velocity: 0.0,
}
}
pub fn drag_details(mut self, drag_details: DragUpdateDetails) -> OverscrollNotification {
self.drag_details = Some(drag_details);
self
}
pub fn velocity(mut self, velocity: f64) -> OverscrollNotification {
self.velocity = velocity;
self
}
}
impl Notification for OverscrollNotification {
fn as_any(&self) -> &dyn Any {
self
}
fn viewport_depth(&self) -> Option<&Cell<u32>> {
Some(&self.viewport_notification.depth)
}
fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
Some(self)
}
}
impl ViewportNotificationMixin for OverscrollNotification {
fn viewport_notification_data(&self) -> &ViewportNotificationData {
&self.viewport_notification
}
}
impl ScrollNotification for OverscrollNotification {
fn scroll_notification_data(&self) -> &ScrollNotificationData {
&self.scroll_notification
}
}
impl Debug for OverscrollNotification {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut description = Vec::new();
fill_scroll_description(self, &mut description);
description.push(format!("overscroll: {:.1}", self.overscroll));
description.push(format!("velocity: {:.1}", self.velocity));
if let Some(drag_details) = &self.drag_details {
description.push(format!("{drag_details:?}"));
}
write!(f, "OverscrollNotification({})", description.join(", "))
}
}
pub struct ScrollEndNotification {
viewport_notification: ViewportNotificationData,
scroll_notification: ScrollNotificationData,
pub drag_details: Option<DragEndDetails>,
}
impl ScrollEndNotification {
pub fn new(metrics: Rc<dyn ScrollMetrics>, context: BuildContext) -> ScrollEndNotification {
ScrollEndNotification {
viewport_notification: ViewportNotificationData::new(),
scroll_notification: ScrollNotificationData {
metrics,
context: Some(context),
},
drag_details: None,
}
}
pub fn drag_details(mut self, drag_details: DragEndDetails) -> ScrollEndNotification {
self.drag_details = Some(drag_details);
self
}
}
impl Notification for ScrollEndNotification {
fn as_any(&self) -> &dyn Any {
self
}
fn viewport_depth(&self) -> Option<&Cell<u32>> {
Some(&self.viewport_notification.depth)
}
fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
Some(self)
}
}
impl ViewportNotificationMixin for ScrollEndNotification {
fn viewport_notification_data(&self) -> &ViewportNotificationData {
&self.viewport_notification
}
}
impl ScrollNotification for ScrollEndNotification {
fn scroll_notification_data(&self) -> &ScrollNotificationData {
&self.scroll_notification
}
}
impl Debug for ScrollEndNotification {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut description = Vec::new();
fill_scroll_description(self, &mut description);
if let Some(drag_details) = &self.drag_details {
description.push(format!("{drag_details:?}"));
}
write!(f, "ScrollEndNotification({})", description.join(", "))
}
}
pub struct UserScrollNotification {
viewport_notification: ViewportNotificationData,
scroll_notification: ScrollNotificationData,
pub direction: ScrollDirection,
}
impl UserScrollNotification {
pub fn new(
metrics: Rc<dyn ScrollMetrics>,
context: BuildContext,
direction: ScrollDirection,
) -> UserScrollNotification {
UserScrollNotification {
viewport_notification: ViewportNotificationData::new(),
scroll_notification: ScrollNotificationData {
metrics,
context: Some(context),
},
direction,
}
}
}
impl Notification for UserScrollNotification {
fn as_any(&self) -> &dyn Any {
self
}
fn viewport_depth(&self) -> Option<&Cell<u32>> {
Some(&self.viewport_notification.depth)
}
fn as_scroll_notification(&self) -> Option<&dyn ScrollNotification> {
Some(self)
}
}
impl ViewportNotificationMixin for UserScrollNotification {
fn viewport_notification_data(&self) -> &ViewportNotificationData {
&self.viewport_notification
}
}
impl ScrollNotification for UserScrollNotification {
fn scroll_notification_data(&self) -> &ScrollNotificationData {
&self.scroll_notification
}
}
impl Debug for UserScrollNotification {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut description = Vec::new();
fill_scroll_description(self, &mut description);
description.push(format!("direction: {:?}", self.direction));
write!(f, "UserScrollNotification({})", description.join(", "))
}
}
pub type ScrollNotificationPredicate = Rc<dyn Fn(&dyn ScrollNotification) -> bool>;
pub fn default_scroll_notification_predicate(notification: &dyn ScrollNotification) -> bool {
notification.depth() == 0
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use waft_foundation::AppCell;
use waft_painting::AxisDirection;
use super::*;
use crate::framework::{
AnyElement, ComponentElement, ComponentElementData, ElementData, IntoWidget, KeyRef,
ProxyElement, Slot, Widget, WidgetKind, WidgetRef, component_element_overrides,
downcast_widget,
};
use crate::test_harness::Harness;
use crate::widgets::basic::{Builder, SizedBox};
use crate::widgets::notification_listener::NotificationListener;
use crate::widgets::scroll_metrics::FixedScrollMetrics;
#[derive(Debug)]
struct TestViewport {
child: WidgetRef,
}
fn viewport<K>(child: impl IntoWidget<K>) -> WidgetRef {
Rc::new(TestViewport {
child: child.into_widget(),
})
}
impl Widget for TestViewport {
fn key(&self) -> Option<&KeyRef> {
None
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
let element = app.create(TestViewportElement {
element: ElementData::new(this),
component: ComponentElementData::default(),
});
element.as_element()
}
fn as_any(&self) -> &dyn Any {
self
}
fn widget_type(&self) -> std::any::TypeId {
std::any::TypeId::of::<TestViewport>()
}
fn kind(&self) -> WidgetKind {
WidgetKind::Other
}
}
struct TestViewportElement {
element: ElementData,
component: ComponentElementData,
}
impl ComponentElement for TestViewportElement {
fn component_data(self: Handle<Self>, app: &App) -> &ComponentElementData {
&app.get(self).component
}
fn component_data_mut(self: Handle<Self>, app: &mut App) -> &mut ComponentElementData {
&mut app.get_mut(self).component
}
fn build(self: Handle<Self>, app: &mut App) -> WidgetRef {
self.proxied_child(app)
}
}
impl ProxyElement for TestViewportElement {
fn proxied_child(self: Handle<Self>, app: &App) -> WidgetRef {
downcast_widget::<TestViewport>(&**self.as_element().widget(app))
.expect("a TestViewportElement holds its TestViewport")
.child
.clone()
}
fn notify_clients(self: Handle<Self>, _app: &mut App, _old_widget: WidgetRef) {}
}
impl ViewportElementMixin for TestViewportElement {}
impl Element for TestViewportElement {
crate::element_accessors!();
component_element_overrides!();
fn mount(
self: Handle<Self>,
app: &mut App,
parent: Option<AnyElement>,
new_slot: Option<Slot>,
) {
ComponentElement::mount(self, app, parent, new_slot);
}
fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
ProxyElement::update(self, app, new_widget);
}
fn perform_rebuild(self: Handle<Self>, app: &mut App) {
ComponentElement::perform_rebuild(self, app);
}
fn attach_notification_tree(self: Handle<Self>, app: &mut App) {
ViewportElementMixin::attach_notification_tree(self, app);
}
fn on_notification(
self: Handle<Self>,
app: &mut App,
notification: &dyn Notification,
) -> bool {
ViewportElementMixin::on_notification(self, app, notification)
}
}
fn test_metrics() -> Rc<dyn ScrollMetrics> {
Rc::new(FixedScrollMetrics::new(
Some(0.0),
Some(400.0),
Some(20.0),
Some(600.0),
AxisDirection::Down,
3.0,
))
}
type Log = Rc<RefCell<Vec<(&'static str, u32)>>>;
fn listener(log: &Log, name: &'static str, child: WidgetRef) -> WidgetRef {
let log = Rc::clone(log);
NotificationListener::<ScrollUpdateNotification>::new(child)
.on_notification(move |_app, notification| {
log.borrow_mut().push((name, notification.depth()));
false
})
.into_widget()
}
#[test]
fn a_family_listener_receives_every_kind_of_scroll_notification() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let seen: Rc<RefCell<Vec<String>>> = Rc::default();
let dispatcher = Builder::new(|app, context| {
ScrollStartNotification::new(test_metrics(), Some(context))
.dispatch(app, Some(context));
ScrollUpdateNotification::new(test_metrics(), context)
.scroll_delta(4.0)
.dispatch(app, Some(context));
ScrollEndNotification::new(test_metrics(), context).dispatch(app, Some(context));
SizedBox::shrink().into_widget()
});
let tree = NotificationListener::<dyn ScrollNotification>::new(dispatcher)
.on_notification({
let seen = Rc::clone(&seen);
move |_app, notification| {
seen.borrow_mut().push(format!("{notification:?}"));
false
}
})
.into_widget();
let harness = Harness::mount(&mut app, tree);
harness.pump(&mut app);
let seen = seen.borrow();
assert_eq!(seen.len(), 3);
assert!(
seen[0].starts_with("ScrollStartNotification"),
"{}",
seen[0]
);
assert!(
seen[1].starts_with("ScrollUpdateNotification"),
"{}",
seen[1]
);
assert!(seen[2].starts_with("ScrollEndNotification"), "{}", seen[2]);
}
#[test]
fn a_scroll_update_notification_bubbles_and_each_viewport_adds_to_its_depth() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let log: Log = Rc::default();
let dispatcher = Builder::new(|app, context| {
ScrollUpdateNotification::new(test_metrics(), context)
.scroll_delta(4.0)
.dispatch(app, Some(context));
SizedBox::shrink().into_widget()
});
let tree = listener(
&log,
"outer",
viewport(listener(
&log,
"middle",
viewport(listener(&log, "inner", dispatcher.into_widget())),
)),
);
let harness = Harness::mount(&mut app, tree);
harness.pump(&mut app);
assert_eq!(
*log.borrow(),
vec![("inner", 0), ("middle", 1), ("outer", 2)]
);
}
#[test]
fn a_notification_reports_its_depth_and_its_metrics() {
let notification = ScrollUpdateNotification::new(
test_metrics(),
{
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = Harness::mount(&mut app, SizedBox::shrink().into_widget());
harness.root.as_element()
},
)
.scroll_delta(4.0)
.with_depth(2);
assert_eq!(notification.depth(), 2);
assert!(default_scroll_notification_predicate(
&ScrollUpdateNotification::new(
test_metrics(),
notification.context().expect("a context was given"),
)
));
assert!(!default_scroll_notification_predicate(¬ification));
assert_eq!(
format!("{notification:?}"),
"ScrollUpdateNotification(depth: 2 (remote), \
FixedScrollMetrics(20.0..[600.0]..380.0), scrollDelta: 4.0)"
);
}
#[test]
fn the_overscroll_notification_reports_its_overscroll_and_velocity() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = Harness::mount(&mut app, SizedBox::shrink().into_widget());
let context = harness.root.as_element();
let notification =
OverscrollNotification::new(test_metrics(), context, -12.0).velocity(3.0);
assert_eq!(notification.overscroll, -12.0);
assert_eq!(
format!("{notification:?}"),
"OverscrollNotification(depth: 0 (local), \
FixedScrollMetrics(20.0..[600.0]..380.0), overscroll: -12.0, velocity: 3.0)"
);
let user_scroll =
UserScrollNotification::new(test_metrics(), context, ScrollDirection::Reverse);
assert_eq!(
format!("{user_scroll:?}"),
"UserScrollNotification(depth: 0 (local), \
FixedScrollMetrics(20.0..[600.0]..380.0), direction: Reverse)"
);
}
}