use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::hash::Hash;
use std::rc::Rc;
use crabshell_reactive::{Memo, Signal, untrack};
use crate::cx::Cx;
use crate::geometry::{Point, Size};
use crate::prop::{IntoProp, Prop};
use crate::style::Style;
use crate::widgets::{
Column, Common, Element, ElementChild, ElementKind, Stack, Widget, visibility_methods,
};
pub(crate) const PIXELS_PER_NOTCH: f32 = 48.0;
pub(crate) const BAR_WIDTH: f32 = 6.0;
pub(crate) const BAR_MIN_LENGTH: f32 = 16.0;
pub(crate) struct ScrollProps {
pub(crate) offset: Option<Signal<f32>>,
pub(crate) horizontal: Option<Prop<bool>>,
pub(crate) kinetic: Option<Prop<bool>>,
pub(crate) overshoot: Option<Prop<bool>>,
pub(crate) scroll_bar: Option<Prop<Option<Style>>>,
pub(crate) shifts: Option<Rc<Cell<f32>>>,
pub(crate) moving: Option<Rc<Cell<bool>>>,
}
pub struct ScrollView {
pub(crate) scroll: ScrollProps,
common: Common,
child: Box<dyn Widget>,
}
impl ScrollView {
pub fn new(child: impl Widget) -> ScrollView {
ScrollView {
scroll: ScrollProps {
offset: None,
horizontal: None,
kinetic: None,
overshoot: None,
scroll_bar: None,
shifts: None,
moving: None,
},
common: Common::default(),
child: Box::new(child),
}
}
pub fn offset(mut self, offset: Signal<f32>) -> ScrollView {
self.scroll.offset = Some(offset);
self
}
pub fn horizontal(mut self, horizontal: impl IntoProp<bool>) -> ScrollView {
self.scroll.horizontal = Some(horizontal.into_prop());
self
}
pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> ScrollView {
self.scroll.kinetic = Some(kinetic.into_prop());
self
}
pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> ScrollView {
self.scroll.overshoot = Some(overshoot.into_prop());
self
}
pub fn scroll_bar(mut self, style: impl IntoProp<Option<Style>>) -> ScrollView {
self.scroll.scroll_bar = Some(style.into_prop());
self
}
pub fn style(mut self, style: impl IntoProp<Style>) -> ScrollView {
self.common.style = Some(style.into_prop());
self
}
visibility_methods!();
}
impl Widget for ScrollView {
fn into_element(self: Box<Self>) -> Element {
let ScrollView {
scroll,
common,
child,
} = *self;
Element {
name: "ScrollView",
common,
kind: ElementKind::Scroll(Box::new(scroll)),
children: vec![ElementChild::One(Box::new(child.into_element()))],
}
}
}
pub struct ListView {
build: Build,
props: ListProps,
common: Common,
}
type Build = Box<dyn FnOnce(&Cx, ListProps) -> Element>;
struct ListProps {
row_height: Option<Prop<u32>>,
height: Option<Prop<u32>>,
current: Option<Prop<Option<usize>>>,
offset: Option<Signal<f32>>,
style: Option<Prop<Style>>,
scroll_bar: Option<Prop<Option<Style>>>,
kinetic: Option<Prop<bool>>,
overshoot: Option<Prop<bool>>,
horizontal: Option<Prop<bool>>,
highlight: Option<Prop<Option<Style>>>,
}
impl ListView {
pub const DEFAULT_ROW_HEIGHT: u32 = 24;
pub const DEFAULT_HEIGHT: u32 = 240;
pub fn new<T, K, W>(
items: impl FnMut() -> Vec<T> + 'static,
key: impl FnMut(&T) -> K + 'static,
view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
) -> ListView
where
T: Clone + PartialEq + 'static,
K: Eq + Hash + 'static,
W: Widget,
{
ListView {
build: Box::new(move |cx, props| build(cx, props, items, key, view)),
props: ListProps {
row_height: None,
height: None,
current: None,
offset: None,
style: None,
scroll_bar: None,
kinetic: None,
overshoot: None,
horizontal: None,
highlight: None,
},
common: Common::default(),
}
}
pub fn horizontal(mut self, horizontal: impl IntoProp<bool>) -> ListView {
self.props.horizontal = Some(horizontal.into_prop());
self
}
pub fn row_height(mut self, height: impl IntoProp<u32>) -> ListView {
self.props.row_height = Some(height.into_prop());
self
}
pub fn height(mut self, height: impl IntoProp<u32>) -> ListView {
self.props.height = Some(height.into_prop());
self
}
pub fn current(mut self, index: impl IntoProp<Option<usize>>) -> ListView {
self.props.current = Some(index.into_prop());
self
}
pub fn highlight(mut self, style: impl IntoProp<Option<Style>>) -> ListView {
self.props.highlight = Some(style.into_prop());
self
}
pub fn offset(mut self, offset: Signal<f32>) -> ListView {
self.props.offset = Some(offset);
self
}
pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> ListView {
self.props.kinetic = Some(kinetic.into_prop());
self
}
pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> ListView {
self.props.overshoot = Some(overshoot.into_prop());
self
}
pub fn scroll_bar(mut self, style: impl IntoProp<Option<Style>>) -> ListView {
self.props.scroll_bar = Some(style.into_prop());
self
}
pub fn style(mut self, style: impl IntoProp<Style>) -> ListView {
self.props.style = Some(style.into_prop());
self
}
visibility_methods!();
}
impl Widget for ListView {
fn into_element(self: Box<Self>) -> Element {
let ListView {
build,
props,
common,
} = *self;
let mut once = Some((build, props));
let mut element = Box::new(Stack::new().children_keyed(
|| vec![()],
|_| (),
move |cx, _| Built(once.take().map(|(build, props)| build(cx, props))),
))
.into_element();
element.name = "ListView";
element.common = common;
element
}
}
pub(crate) struct Built(pub(crate) Option<Element>);
impl Widget for Built {
fn into_element(self: Box<Self>) -> Element {
self
.0
.unwrap_or_else(|| Box::new(Stack::new()).into_element())
}
}
struct Lengths<K> {
index: HashMap<K, usize>,
measured: Vec<Option<f32>>,
pending: Vec<(usize, f32)>,
seek: Option<usize>,
}
fn starts(measured: &[Option<f32>], estimate: f32) -> Vec<f32> {
let mut starts = Vec::with_capacity(measured.len() + 1);
let mut at = 0.0;
starts.push(at);
for length in measured {
at += length.unwrap_or(estimate);
starts.push(at);
}
starts
}
pub(crate) fn keep_in_view(start: f32, end: f32, viewport: f32, now: f32) -> f32 {
if start < now {
start
} else if end > now + viewport {
end - viewport
} else {
now
}
}
fn build<T, K, W>(
cx: &Cx,
props: ListProps,
mut items: impl FnMut() -> Vec<T> + 'static,
key: impl FnMut(&T) -> K + 'static,
mut view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
) -> Element
where
T: Clone + PartialEq + 'static,
K: Eq + Hash + 'static,
W: Widget,
{
let ListProps {
row_height,
height,
current,
offset,
style,
scroll_bar,
kinetic,
overshoot,
horizontal,
highlight: highlight_style,
} = props;
let offset = offset.unwrap_or_else(|| cx.signal(0.0));
let horizontal = cx.memo(prop_fn(horizontal, false));
let row_height = cx.memo(prop_fn(row_height, ListView::DEFAULT_ROW_HEIGHT));
let estimate = move || row_height.get().max(1) as f32;
let height = cx.memo(prop_fn(height, ListView::DEFAULT_HEIGHT));
let style = style.map(Prop::shared);
let inner = {
let style = style.clone();
cx.memo(move || {
let own = style.as_ref().map(|style| style()).unwrap_or_default();
let padding = own.padding.unwrap_or_default();
let border = own.border.map_or(0.0, |border| border.width.max(0.0));
let sides = if horizontal.get() {
padding.left + padding.right
} else {
padding.top + padding.bottom
};
(height.get() as f32 - sides as f32 - 2.0 * border).max(0.0)
})
};
let key = Rc::new(RefCell::new(key));
let lengths = Rc::new(RefCell::new(Lengths {
index: HashMap::new(),
measured: Vec::new(),
pending: Vec::new(),
seek: None,
}));
let remeasure = cx.signal(());
let measured = cx.signal(());
let changes = cx.signal(0_u64);
let all = cx.signal(Vec::<T>::new());
{
let (key, lengths) = (Rc::clone(&key), Rc::clone(&lengths));
cx.effect(move || {
let list = items();
let keys: Vec<K> = list.iter().map(|item| (key.borrow_mut())(item)).collect();
let mut lengths = lengths.borrow_mut();
let old = std::mem::take(&mut lengths.measured);
let mut index = HashMap::with_capacity(keys.len());
let mut measured = Vec::with_capacity(keys.len());
let mut moved = vec![None; old.len()];
for (at, item_key) in keys.into_iter().enumerate() {
let was = lengths.index.get(&item_key).copied();
if let Some(was) = was {
moved[was].get_or_insert(at);
}
measured.push(was.and_then(|was| old[was]));
index.entry(item_key).or_insert(at);
}
lengths.index = index;
lengths.measured = measured;
let pending = std::mem::take(&mut lengths.pending);
lengths.pending = pending
.into_iter()
.filter_map(|(was, length)| Some((moved.get(was).copied().flatten()?, length)))
.collect();
drop(lengths);
all.set(list);
changes.update(|n| *n += 1);
remeasure.set(());
});
}
{
let lengths = Rc::clone(&lengths);
let mut was = None;
cx.effect(move || {
let now = horizontal.get();
if was.replace(now).is_some_and(|was| was != now) {
lengths.borrow_mut().measured.fill(None);
remeasure.set(());
}
});
}
let count = cx.memo(move || all.with(Vec::len));
let starts = {
let lengths = Rc::clone(&lengths);
cx.memo(move || {
remeasure.get();
starts(&lengths.borrow().measured, estimate())
})
};
let total = move || starts.with(|starts| starts.last().copied().unwrap_or(0.0));
let shown = move || {
let most = (total() - inner.get()).max(0.0);
let offset = offset.get();
if offset.is_nan() {
0.0
} else {
offset.clamp(0.0, most)
}
};
let range = cx.memo(move || {
let top = shown();
let bottom = top + inner.get();
starts.with(|starts| {
let rows = starts.len() - 1;
let first = starts
.partition_point(|&start| start <= top)
.saturating_sub(2);
let last = (starts.partition_point(|&start| start < bottom) + 1).min(rows);
first..last.max(first)
})
});
let shifts = Rc::new(Cell::new(0.0));
{
let lengths = Rc::clone(&lengths);
let shifts = Rc::clone(&shifts);
cx.effect(move || {
measured.get();
let (old, top, estimate) = untrack(|| (starts.get(), shown(), estimate()));
let mut lengths = lengths.borrow_mut();
let mut changed = false;
let mut shift = 0.0;
for (at, length) in std::mem::take(&mut lengths.pending) {
let Some(slot) = lengths.measured.get_mut(at) else {
continue;
};
if *slot == Some(length) {
continue;
}
if old[at] < top {
shift += length - slot.unwrap_or(estimate);
}
*slot = Some(length);
changed = true;
}
let seek = lengths
.seek
.filter(|&at| lengths.measured.get(at).is_some_and(Option::is_some));
if seek.is_some() {
lengths.seek = None;
}
drop(lengths);
if !changed {
return;
}
remeasure.set(());
if shift != 0.0 {
shifts.set(shifts.get() + shift);
offset.set(top + shift);
}
if let Some(at) = seek {
untrack(|| {
let (start, end) = starts.with(|starts| (starts[at], starts[at + 1]));
let now = shown();
let next = keep_in_view(start, end, inner.get(), now);
if next != now {
offset.set(next);
}
});
}
});
}
let moving = Rc::new(Cell::new(false));
let current = current.map(Prop::shared);
if let Some(current) = current.clone() {
let lengths = Rc::clone(&lengths);
let moving = Rc::clone(&moving);
let mut asked = None;
cx.effect(move || {
let index = current();
let ask = (index, row_height.get(), inner.get());
let wanted = index.filter(|&index| index < count.get());
let fresh = asked.replace((ask, wanted.is_some())) != Some((ask, true));
let Some(index) = wanted else {
lengths.borrow_mut().seek = None;
return;
};
if !fresh || moving.get() {
lengths.borrow_mut().seek = None;
return;
}
let viewport = ask.2;
let (start, end) = untrack(|| starts.with(|starts| (starts[index], starts[index + 1])));
let now = untrack(shown);
let next = keep_in_view(start, end, viewport, now);
if next != now {
offset.set(next);
}
let mut lengths = lengths.borrow_mut();
let unmeasured = lengths.measured.get(index).is_some_and(Option::is_none);
lengths.seek = unmeasured.then_some(index);
});
}
let mut rows = Column::new().style(move || along(horizontal.get(), Style::new(), total()));
let cross = cx.signal(0.0_f32);
if let (Some(style), Some(current)) = (highlight_style, current) {
let spot = cx.memo(move || {
let index = current()?;
let (start, end) =
starts.with(|starts| Some((*starts.get(index)?, *starts.get(index + 1)?)))?;
let target = (index, changes.get());
let (length, across) = (end - start, cross.get());
Some(if horizontal.get() {
Spot {
at: Point::new(start, 0.0),
size: Size::new(length, across),
target,
}
} else {
Spot {
at: Point::new(0.0, start),
size: Size::new(across, length),
target,
}
})
});
rows = rows.child(highlight(cx, cx.memo(prop_fn(Some(style), None)), spot));
}
let rows = rows
.child(Stack::new().style(move || {
let first = starts.with(|starts| starts[range.get().start]);
along(horizontal.get(), Style::new(), first).shrink(0.0)
}))
.children_keyed(
move || {
let range = range.get();
all.with(|all| {
let end = range.end.min(all.len());
all[range.start.min(end)..end].to_vec()
})
},
{
let key = Rc::clone(&key);
move |item| (key.borrow_mut())(item)
},
move |cx, item| {
let own = (key.borrow_mut())(&item.get_untracked());
let lengths = Rc::clone(&lengths);
let measure = move |size: Size| {
let mut lengths = lengths.borrow_mut();
if let Some(&at) = lengths.index.get(&own) {
let length = if horizontal.try_get().unwrap_or_default() {
size.width
} else {
size.height
};
lengths.pending.push((at, length));
drop(lengths);
measured.try_set(());
}
};
let row = Stack::new()
.style(move || {
let least = row_height.get() as f32;
let style = Style::new().shrink(0.0);
if horizontal.get() {
style.min_width(least)
} else {
style.min_height(least)
}
})
.child(view(cx, item));
let mut row = Box::new(row).into_element();
row.common.measure = Some(Rc::new(measure));
Built(Some(row))
},
);
let mut rows = Box::new(rows).into_element();
rows.common.measure = Some(Rc::new(move |size: Size| {
let across = if horizontal.try_get().unwrap_or_default() {
size.height
} else {
size.width
};
if cross.try_get() != Some(across) {
cross.try_set(across);
}
}));
if let ElementKind::Flex(flex) = &mut rows.kind {
flex.column_binding = Some((move || !horizontal.get()).into_prop());
}
let mut scroll = ScrollView::new(Built(Some(rows)))
.offset(offset)
.horizontal(move || horizontal.get());
scroll.scroll.shifts = Some(shifts);
scroll.scroll.moving = Some(moving);
if let Some(bar) = scroll_bar {
scroll = scroll.scroll_bar(bar);
}
if let Some(kinetic) = kinetic {
scroll = scroll.kinetic(kinetic);
}
if let Some(overshoot) = overshoot {
scroll = scroll.overshoot(overshoot);
}
scroll = scroll.style(move || {
let own = style.as_ref().map(|style| style()).unwrap_or_default();
along(horizontal.get(), own, height.get() as f32)
});
Box::new(scroll).into_element()
}
fn along(horizontal: bool, style: Style, length: f32) -> Style {
if horizontal {
style.width(length)
} else {
style.height(length)
}
}
#[derive(Clone, Copy, PartialEq)]
pub(crate) struct Spot {
pub(crate) at: Point,
pub(crate) size: Size,
pub(crate) target: (usize, u64),
}
pub(crate) fn highlight(cx: &Cx, style: Memo<Option<Style>>, spot: Memo<Option<Spot>>) -> Stack {
let place = cx.memo(move || spot.get().map(|spot| (spot.at, spot.target)));
let shape = Stack::new().style(move || {
let own = style.get().unwrap_or_default();
match spot.get() {
Some(spot) => own.width(spot.size.width).height(spot.size.height),
None => own,
}
});
let mut last = None;
Stack::new()
.visible(move || style.with(Option::is_some) && spot.with(Option::is_some))
.style(move || {
let Some((at, target)) = place.get() else {
return Style::new().left(0.0).top(0.0);
};
let moved = last.replace(target) != Some(target);
let mover = Style::new().left(0.0).top(0.0).translate(at.x, at.y);
match style.get().and_then(|style| style.transition) {
Some(transition) if moved => mover.transition(transition),
_ => mover,
}
})
.child(shape)
}
pub(crate) fn prop_fn<T: Clone + 'static>(
prop: Option<Prop<T>>,
default: T,
) -> impl FnMut() -> T + 'static {
let prop = prop.map(Prop::shared);
move || match prop.as_ref() {
Some(prop) => prop(),
None => default.clone(),
}
}