use crate::widget::{Id, Operation};
use crate::{Rectangle, Vector};
pub trait Scrollable {
fn snap_to(&mut self, offset: RelativeOffset);
fn scroll_to(&mut self, offset: AbsoluteOffset);
}
pub fn snap_to<T>(target: Id, offset: RelativeOffset) -> impl Operation<T> {
struct SnapTo {
target: Id,
offset: RelativeOffset,
}
impl<T> Operation<T> for SnapTo {
fn container(
&mut self,
_id: Option<&Id>,
_bounds: Rectangle,
operate_on_children: &mut dyn FnMut(&mut dyn Operation<T>),
) {
operate_on_children(self);
}
fn scrollable(
&mut self,
state: &mut dyn Scrollable,
id: Option<&Id>,
_bounds: Rectangle,
_translation: Vector,
) {
if Some(&self.target) == id {
state.snap_to(self.offset);
}
}
}
SnapTo { target, offset }
}
pub fn scroll_to<T>(target: Id, offset: AbsoluteOffset) -> impl Operation<T> {
struct ScrollTo {
target: Id,
offset: AbsoluteOffset,
}
impl<T> Operation<T> for ScrollTo {
fn container(
&mut self,
_id: Option<&Id>,
_bounds: Rectangle,
operate_on_children: &mut dyn FnMut(&mut dyn Operation<T>),
) {
operate_on_children(self);
}
fn scrollable(
&mut self,
state: &mut dyn Scrollable,
id: Option<&Id>,
_bounds: Rectangle,
_translation: Vector,
) {
if Some(&self.target) == id {
state.scroll_to(self.offset);
}
}
}
ScrollTo { target, offset }
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct AbsoluteOffset {
pub x: f32,
pub y: f32,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct RelativeOffset {
pub x: f32,
pub y: f32,
}
impl RelativeOffset {
pub const START: Self = Self { x: 0.0, y: 0.0 };
pub const END: Self = Self { x: 1.0, y: 1.0 };
}