use crate::Container;
use mitsuami_core::{
Align, Children, Element, ElementBuilder, FlexDirection, NodeId, Point, Prop, ScrollAxes, Tweak, Ui, UiEvent, View,
WidgetKind,
};
use mitsuami_reactive::IntoValue;
pub struct ScrollView {
outer: Element,
content: Container,
}
impl ElementBuilder for ScrollView {
fn element(&mut self) -> &mut Element {
&mut self.outer
}
}
impl View for ScrollView {
fn build(mut self, ui: &Ui) -> NodeId {
self.outer.add_children(self.content);
self.outer.build(ui)
}
}
impl Default for ScrollView {
fn default() -> ScrollView {
ScrollView::new()
}
}
impl ScrollView {
pub fn new() -> ScrollView {
ScrollView::with_axes(ScrollAxes::Vertical)
}
pub fn horizontal() -> ScrollView {
ScrollView::with_axes(ScrollAxes::Horizontal)
}
pub fn both() -> ScrollView {
ScrollView::with_axes(ScrollAxes::Both)
}
fn with_axes(axes: ScrollAxes) -> ScrollView {
let outer = Element::new(WidgetKind::ScrollView);
ScrollView { outer, content: Container::new().shrink(0.0) }.axes(axes)
}
pub fn axes(mut self, axes: ScrollAxes) -> ScrollView {
self.outer.prop(axes.into_value(), Prop::ScrollAxes);
self.outer.style.scroll_x = axes.horizontal();
self.outer.style.scroll_y = axes.vertical();
self.outer.style.flex_direction =
if axes == ScrollAxes::Horizontal { FlexDirection::Row } else { FlexDirection::Column };
let content = &mut self.content.0.style;
content.flex_direction =
if axes == ScrollAxes::Horizontal { FlexDirection::Row } else { FlexDirection::Column };
content.align_self = (axes == ScrollAxes::Both).then_some(Align::Start);
self
}
pub fn children(mut self, children: impl Children) -> ScrollView {
self.content = self.content.children(children);
self
}
pub fn child(self, child: impl View) -> ScrollView {
self.children(child)
}
pub fn scroll_bars(mut self, show: impl IntoValue<bool>) -> ScrollView {
self.outer.prop(show.into_value(), Prop::ScrollBars);
self
}
pub fn native(mut self, tweak: Tweak<ScrollView>) -> ScrollView {
tweak.apply(&mut self.outer);
self
}
pub fn on_scroll(mut self, handler: impl Fn(Point) + 'static) -> ScrollView {
self.outer.on(move |event| {
if let UiEvent::Scrolled(offset) = event {
handler(*offset);
}
});
self
}
}
impl ScrollView {
#[doc(hidden)]
pub fn __tag() -> ScrollView {
ScrollView::new()
}
#[doc(hidden)]
pub fn __children<C: Children>(self, children: impl FnOnce() -> C) -> ScrollView {
self.children(children())
}
}