1use std::cell::{Cell, RefCell};
5use std::collections::HashMap;
6use std::hash::Hash;
7use std::rc::Rc;
8
9use crabshell_reactive::{Memo, ReadSignal, Signal, untrack};
10
11use crate::animation::{Animate, Transition};
12use crate::cx::Cx;
13use crate::geometry::{Point, Size};
14use crate::prop::{IntoProp, Prop};
15use crate::style::Style;
16use crate::widgets::{
17 Column, Common, Element, ElementChild, ElementKind, Stack, Widget, visibility_methods,
18};
19
20pub(crate) const PIXELS_PER_NOTCH: f32 = 48.0;
22
23pub(crate) const BAR_WIDTH: f32 = 6.0;
25
26pub(crate) const BAR_MIN_LENGTH: f32 = 16.0;
29
30pub(crate) struct ScrollProps {
31 pub(crate) offset: Option<Signal<f32>>,
32 pub(crate) offset_x: Option<Signal<f32>>,
33 pub(crate) horizontal: Option<Prop<bool>>,
34 pub(crate) both: Option<Prop<bool>>,
35 pub(crate) kinetic: Option<Prop<bool>>,
36 pub(crate) overshoot: Option<Prop<bool>>,
37 pub(crate) mouse_drag: Option<Prop<bool>>,
38 pub(crate) scroll_bar: Option<Prop<Option<Style>>>,
39 pub(crate) shifts: Option<Rc<Cell<f32>>>,
42 pub(crate) moving: Option<Rc<Cell<bool>>>,
46}
47
48pub struct ScrollView {
59 pub(crate) scroll: ScrollProps,
60 common: Common,
61 child: Box<dyn Widget>,
62}
63
64impl ScrollView {
65 pub fn new(child: impl Widget) -> ScrollView {
67 ScrollView {
68 scroll: ScrollProps {
69 offset: None,
70 offset_x: None,
71 horizontal: None,
72 both: None,
73 kinetic: None,
74 overshoot: None,
75 mouse_drag: None,
76 scroll_bar: None,
77 shifts: None,
78 moving: None,
79 },
80 common: Common::default(),
81 child: Box::new(child),
82 }
83 }
84
85 pub fn offset(mut self, offset: Signal<f32>) -> ScrollView {
92 self.scroll.offset = Some(offset);
93 self
94 }
95
96 pub fn horizontal(mut self, horizontal: impl IntoProp<bool>) -> ScrollView {
101 self.scroll.horizontal = Some(horizontal.into_prop());
102 self
103 }
104
105 pub fn both(mut self, both: impl IntoProp<bool>) -> ScrollView {
112 self.scroll.both = Some(both.into_prop());
113 self
114 }
115
116 pub fn offset_x(mut self, offset: Signal<f32>) -> ScrollView {
122 self.scroll.offset_x = Some(offset);
123 self
124 }
125
126 pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> ScrollView {
131 self.scroll.kinetic = Some(kinetic.into_prop());
132 self
133 }
134
135 pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> ScrollView {
141 self.scroll.overshoot = Some(overshoot.into_prop());
142 self
143 }
144
145 pub fn mouse_drag(mut self, mouse_drag: impl IntoProp<bool>) -> ScrollView {
150 self.scroll.mouse_drag = Some(mouse_drag.into_prop());
151 self
152 }
153
154 pub fn scroll_bar(mut self, style: impl IntoProp<Option<Style>>) -> ScrollView {
167 self.scroll.scroll_bar = Some(style.into_prop());
168 self
169 }
170
171 pub fn style(mut self, style: impl IntoProp<Style>) -> ScrollView {
174 self.common.style = Some(style.into_prop());
175 self
176 }
177
178 visibility_methods!();
179}
180
181impl Widget for ScrollView {
182 fn into_element(self: Box<Self>) -> Element {
183 let ScrollView {
184 scroll,
185 common,
186 child,
187 } = *self;
188 Element {
189 name: "ScrollView",
190 common,
191 kind: ElementKind::Scroll(Box::new(scroll)),
192 children: vec![ElementChild::One(Box::new(child.into_element()))],
193 }
194 }
195}
196
197pub struct ListView {
222 build: Build,
224 props: ListProps,
225 common: Common,
226}
227
228type Build = Box<dyn FnOnce(&Cx, ListProps) -> Element>;
230
231struct ListProps {
232 row_height: Option<Prop<u32>>,
233 height: Option<Prop<u32>>,
234 current: Option<Prop<Option<usize>>>,
235 offset: Option<Signal<f32>>,
236 style: Option<Prop<Style>>,
237 scroll_bar: Option<Prop<Option<Style>>>,
238 kinetic: Option<Prop<bool>>,
239 overshoot: Option<Prop<bool>>,
240 mouse_drag: Option<Prop<bool>>,
241 horizontal: Option<Prop<bool>>,
242 highlight: Option<Prop<Option<Style>>>,
243}
244
245impl ListView {
246 pub const DEFAULT_ROW_HEIGHT: u32 = 24;
248 pub const DEFAULT_HEIGHT: u32 = 240;
250
251 pub fn new<T, K, W>(
254 items: impl FnMut() -> Vec<T> + 'static,
255 key: impl FnMut(&T) -> K + 'static,
256 view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
257 ) -> ListView
258 where
259 T: Clone + PartialEq + 'static,
260 K: Eq + Hash + 'static,
261 W: Widget,
262 {
263 ListView {
264 build: Box::new(move |cx, props| build(cx, props, items, key, view)),
265 props: ListProps {
266 row_height: None,
267 height: None,
268 current: None,
269 offset: None,
270 style: None,
271 scroll_bar: None,
272 kinetic: None,
273 overshoot: None,
274 mouse_drag: None,
275 horizontal: None,
276 highlight: None,
277 },
278 common: Common::default(),
279 }
280 }
281
282 pub fn horizontal(mut self, horizontal: impl IntoProp<bool>) -> ListView {
287 self.props.horizontal = Some(horizontal.into_prop());
288 self
289 }
290
291 pub fn row_height(mut self, height: impl IntoProp<u32>) -> ListView {
294 self.props.row_height = Some(height.into_prop());
295 self
296 }
297
298 pub fn height(mut self, height: impl IntoProp<u32>) -> ListView {
300 self.props.height = Some(height.into_prop());
301 self
302 }
303
304 pub fn current(mut self, index: impl IntoProp<Option<usize>>) -> ListView {
312 self.props.current = Some(index.into_prop());
313 self
314 }
315
316 pub fn highlight(mut self, style: impl IntoProp<Option<Style>>) -> ListView {
327 self.props.highlight = Some(style.into_prop());
328 self
329 }
330
331 pub fn offset(mut self, offset: Signal<f32>) -> ListView {
333 self.props.offset = Some(offset);
334 self
335 }
336
337 pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> ListView {
340 self.props.kinetic = Some(kinetic.into_prop());
341 self
342 }
343
344 pub fn mouse_drag(mut self, mouse_drag: impl IntoProp<bool>) -> ListView {
347 self.props.mouse_drag = Some(mouse_drag.into_prop());
348 self
349 }
350
351 pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> ListView {
354 self.props.overshoot = Some(overshoot.into_prop());
355 self
356 }
357
358 pub fn scroll_bar(mut self, style: impl IntoProp<Option<Style>>) -> ListView {
360 self.props.scroll_bar = Some(style.into_prop());
361 self
362 }
363
364 pub fn style(mut self, style: impl IntoProp<Style>) -> ListView {
366 self.props.style = Some(style.into_prop());
367 self
368 }
369
370 visibility_methods!();
371}
372
373impl Widget for ListView {
374 fn into_element(self: Box<Self>) -> Element {
375 let ListView {
376 build,
377 props,
378 common,
379 } = *self;
380 let mut once = Some((build, props));
381 let mut element = Box::new(Stack::new().children_keyed(
384 || vec![()],
385 |_| (),
386 move |cx, _| Built(once.take().map(|(build, props)| build(cx, props))),
387 ))
388 .into_element();
389 element.name = "ListView";
390 element.common = common;
391 element
392 }
393}
394
395pub(crate) struct Built(pub(crate) Option<Element>);
397
398impl Widget for Built {
399 fn into_element(self: Box<Self>) -> Element {
400 self
401 .0
402 .unwrap_or_else(|| Box::new(Stack::new()).into_element())
403 }
404}
405
406struct Lengths<K> {
408 index: HashMap<K, usize>,
410 measured: Vec<Option<f32>>,
412 pending: Vec<(usize, f32)>,
414 seek: Option<usize>,
417}
418
419fn starts(measured: &[Option<f32>], estimate: f32) -> Vec<f32> {
422 let mut starts = Vec::with_capacity(measured.len() + 1);
423 let mut at = 0.0;
424 starts.push(at);
425 for length in measured {
426 at += length.unwrap_or(estimate);
427 starts.push(at);
428 }
429 starts
430}
431
432pub(crate) fn keep_in_view(start: f32, end: f32, viewport: f32, now: f32) -> f32 {
435 if start < now {
436 start
437 } else if end > now + viewport {
438 end - viewport
439 } else {
440 now
441 }
442}
443
444fn build<T, K, W>(
445 cx: &Cx,
446 props: ListProps,
447 mut items: impl FnMut() -> Vec<T> + 'static,
448 key: impl FnMut(&T) -> K + 'static,
449 mut view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
450) -> Element
451where
452 T: Clone + PartialEq + 'static,
453 K: Eq + Hash + 'static,
454 W: Widget,
455{
456 let ListProps {
457 row_height,
458 height,
459 current,
460 offset,
461 style,
462 scroll_bar,
463 kinetic,
464 overshoot,
465 mouse_drag,
466 horizontal,
467 highlight: highlight_style,
468 } = props;
469 let offset = offset.unwrap_or_else(|| cx.signal(0.0));
470 let horizontal = cx.memo(prop_fn(horizontal, false));
471 let row_height = cx.memo(prop_fn(row_height, ListView::DEFAULT_ROW_HEIGHT));
472 let estimate = move || row_height.get().max(1) as f32;
473 let height = cx.memo(prop_fn(height, ListView::DEFAULT_HEIGHT));
474 let style = style.map(Prop::shared);
475 let inner = {
477 let style = style.clone();
478 cx.memo(move || {
479 let own = style.as_ref().map(|style| style()).unwrap_or_default();
480 let padding = own.padding.unwrap_or_default();
481 let border = own.border.map_or(0.0, |border| border.width.max(0.0));
482 let sides = if horizontal.get() {
483 padding.left + padding.right
484 } else {
485 padding.top + padding.bottom
486 };
487 (height.get() as f32 - sides as f32 - 2.0 * border).max(0.0)
488 })
489 };
490 let key = Rc::new(RefCell::new(key));
493 let lengths = Rc::new(RefCell::new(Lengths {
494 index: HashMap::new(),
495 measured: Vec::new(),
496 pending: Vec::new(),
497 seek: None,
498 }));
499 let remeasure = cx.signal(());
501 let measured = cx.signal(());
502 let changes = cx.signal(0_u64);
504 let all = cx.signal(Vec::<T>::new());
505 {
506 let (key, lengths) = (Rc::clone(&key), Rc::clone(&lengths));
507 cx.effect(move || {
508 let list = items();
509 let keys: Vec<K> = list.iter().map(|item| (key.borrow_mut())(item)).collect();
510 let mut lengths = lengths.borrow_mut();
511 let old = std::mem::take(&mut lengths.measured);
512 let mut index = HashMap::with_capacity(keys.len());
513 let mut measured = Vec::with_capacity(keys.len());
514 let mut moved = vec![None; old.len()];
516 for (at, item_key) in keys.into_iter().enumerate() {
517 let was = lengths.index.get(&item_key).copied();
518 if let Some(was) = was {
519 moved[was].get_or_insert(at);
520 }
521 measured.push(was.and_then(|was| old[was]));
522 index.entry(item_key).or_insert(at);
523 }
524 lengths.index = index;
525 lengths.measured = measured;
526 let pending = std::mem::take(&mut lengths.pending);
527 lengths.pending = pending
528 .into_iter()
529 .filter_map(|(was, length)| Some((moved.get(was).copied().flatten()?, length)))
530 .collect();
531 drop(lengths);
532 all.set(list);
533 changes.update(|n| *n += 1);
534 remeasure.set(());
535 });
536 }
537 {
539 let lengths = Rc::clone(&lengths);
540 let mut was = None;
541 cx.effect(move || {
542 let now = horizontal.get();
543 if was.replace(now).is_some_and(|was| was != now) {
544 lengths.borrow_mut().measured.fill(None);
545 remeasure.set(());
546 }
547 });
548 }
549 let count = cx.memo(move || all.with(Vec::len));
550 let starts = {
551 let lengths = Rc::clone(&lengths);
552 cx.memo(move || {
553 remeasure.get();
554 starts(&lengths.borrow().measured, estimate())
555 })
556 };
557 let total = move || starts.with(|starts| starts.last().copied().unwrap_or(0.0));
558 let shown = move || {
560 let most = (total() - inner.get()).max(0.0);
561 let offset = offset.get();
562 if offset.is_nan() {
563 0.0
564 } else {
565 offset.clamp(0.0, most)
566 }
567 };
568 let range = cx.memo(move || {
571 let top = shown();
572 let bottom = top + inner.get();
573 starts.with(|starts| {
574 let rows = starts.len() - 1;
575 let first = starts
576 .partition_point(|&start| start <= top)
577 .saturating_sub(2);
578 let last = (starts.partition_point(|&start| start < bottom) + 1).min(rows);
579 first..last.max(first)
580 })
581 });
582 let shifts = Rc::new(Cell::new(0.0));
585 {
586 let lengths = Rc::clone(&lengths);
587 let shifts = Rc::clone(&shifts);
588 cx.effect(move || {
589 measured.get();
590 let (old, top, estimate) = untrack(|| (starts.get(), shown(), estimate()));
591 let mut lengths = lengths.borrow_mut();
592 let mut changed = false;
593 let mut shift = 0.0;
594 for (at, length) in std::mem::take(&mut lengths.pending) {
595 let Some(slot) = lengths.measured.get_mut(at) else {
596 continue;
597 };
598 if *slot == Some(length) {
599 continue;
600 }
601 if old[at] < top {
602 shift += length - slot.unwrap_or(estimate);
603 }
604 *slot = Some(length);
605 changed = true;
606 }
607 let seek = lengths
608 .seek
609 .filter(|&at| lengths.measured.get(at).is_some_and(Option::is_some));
610 if seek.is_some() {
611 lengths.seek = None;
612 }
613 drop(lengths);
614 if !changed {
615 return;
616 }
617 remeasure.set(());
618 if shift != 0.0 {
619 shifts.set(shifts.get() + shift);
621 offset.set(top + shift);
622 }
623 if let Some(at) = seek {
624 untrack(|| {
625 let (start, end) = starts.with(|starts| (starts[at], starts[at + 1]));
626 let now = shown();
627 let next = keep_in_view(start, end, inner.get(), now);
628 if next != now {
629 offset.set(next);
630 }
631 });
632 }
633 });
634 }
635 let moving = Rc::new(Cell::new(false));
636 let current = current.map(Prop::shared);
637 if let Some(current) = current.clone() {
638 let lengths = Rc::clone(&lengths);
639 let moving = Rc::clone(&moving);
640 let mut asked = None;
641 cx.effect(move || {
642 let index = current();
643 let ask = (index, row_height.get(), inner.get());
646 let wanted = index.filter(|&index| index < count.get());
647 let fresh = asked.replace((ask, wanted.is_some())) != Some((ask, true));
648 let Some(index) = wanted else {
649 lengths.borrow_mut().seek = None;
650 return;
651 };
652 if !fresh || moving.get() {
655 lengths.borrow_mut().seek = None;
656 return;
657 }
658 let viewport = ask.2;
659 let (start, end) = untrack(|| starts.with(|starts| (starts[index], starts[index + 1])));
660 let now = untrack(shown);
661 let next = keep_in_view(start, end, viewport, now);
662 if next != now {
663 offset.set(next);
664 }
665 let mut lengths = lengths.borrow_mut();
666 let unmeasured = lengths.measured.get(index).is_some_and(Option::is_none);
667 lengths.seek = unmeasured.then_some(index);
668 });
669 }
670 let mut rows = Column::new().style(move || along(horizontal.get(), Style::new(), total()));
671 let cross = cx.signal(0.0_f32);
674 if let (Some(style), Some(current)) = (highlight_style, current) {
675 let spot = cx.memo(move || {
676 let index = current()?;
677 let (start, end) =
678 starts.with(|starts| Some((*starts.get(index)?, *starts.get(index + 1)?)))?;
679 let target = (index, changes.get());
680 let (length, across) = (end - start, cross.get());
681 Some(if horizontal.get() {
682 Spot {
683 at: Point::new(start, 0.0),
684 size: Size::new(length, across),
685 target,
686 }
687 } else {
688 Spot {
689 at: Point::new(0.0, start),
690 size: Size::new(across, length),
691 target,
692 }
693 })
694 });
695 rows = rows.child(highlight(cx, cx.memo(prop_fn(Some(style), None)), spot));
696 }
697 let rows = rows
698 .child(Stack::new().style(move || {
699 let first = starts.with(|starts| starts[range.get().start]);
700 along(horizontal.get(), Style::new(), first).shrink(0.0)
701 }))
702 .children_keyed(
703 move || {
704 let range = range.get();
705 all.with(|all| {
706 let end = range.end.min(all.len());
707 all[range.start.min(end)..end].to_vec()
708 })
709 },
710 {
711 let key = Rc::clone(&key);
712 move |item| (key.borrow_mut())(item)
713 },
714 move |cx, item| {
715 let own = (key.borrow_mut())(&item.get_untracked());
716 let lengths = Rc::clone(&lengths);
717 let measure = move |size: Size| {
718 let mut lengths = lengths.borrow_mut();
719 if let Some(&at) = lengths.index.get(&own) {
720 let length = if horizontal.try_get().unwrap_or_default() {
721 size.width
722 } else {
723 size.height
724 };
725 lengths.pending.push((at, length));
726 drop(lengths);
727 measured.try_set(());
728 }
729 };
730 let row = Stack::new()
731 .style(move || {
732 let least = row_height.get() as f32;
733 let style = Style::new().shrink(0.0);
734 if horizontal.get() {
735 style.min_width(least)
736 } else {
737 style.min_height(least)
738 }
739 })
740 .child(view(cx, item));
741 let mut row = Box::new(row).into_element();
742 row.common.measure = Some(Rc::new(measure));
743 Built(Some(row))
744 },
745 );
746 let mut rows = Box::new(rows).into_element();
747 rows.common.measure = Some(Rc::new(move |size: Size| {
748 let across = if horizontal.try_get().unwrap_or_default() {
749 size.height
750 } else {
751 size.width
752 };
753 if cross.try_get() != Some(across) {
754 cross.try_set(across);
755 }
756 }));
757 if let ElementKind::Flex(flex) = &mut rows.kind {
758 flex.column_binding = Some((move || !horizontal.get()).into_prop());
759 }
760 let mut scroll = ScrollView::new(Built(Some(rows)))
761 .offset(offset)
762 .horizontal(move || horizontal.get());
763 scroll.scroll.shifts = Some(shifts);
764 scroll.scroll.moving = Some(moving);
765 if let Some(bar) = scroll_bar {
766 scroll = scroll.scroll_bar(bar);
767 }
768 if let Some(kinetic) = kinetic {
769 scroll = scroll.kinetic(kinetic);
770 }
771 if let Some(overshoot) = overshoot {
772 scroll = scroll.overshoot(overshoot);
773 }
774 if let Some(mouse_drag) = mouse_drag {
775 scroll = scroll.mouse_drag(mouse_drag);
776 }
777 scroll = scroll.style(move || {
778 let own = style.as_ref().map(|style| style()).unwrap_or_default();
779 along(horizontal.get(), own, height.get() as f32)
780 });
781 Box::new(scroll).into_element()
782}
783
784pub(crate) fn along(horizontal: bool, style: Style, length: f32) -> Style {
787 if horizontal {
788 style.width(length)
789 } else {
790 style.height(length)
791 }
792}
793
794#[derive(Clone, Copy, PartialEq)]
797pub(crate) struct Spot {
798 pub(crate) at: Point,
799 pub(crate) size: Size,
800 pub(crate) target: (usize, u64),
804}
805
806#[derive(Clone, Copy, PartialEq, Default)]
808struct Frame {
809 at: Point,
810 size: Point,
812}
813
814impl Animate for Frame {
815 fn lerp(&self, to: &Frame, t: f32) -> Frame {
816 Frame {
817 at: self.at.lerp(&to.at, t),
818 size: self.size.lerp(&to.size, t),
819 }
820 }
821}
822
823pub(crate) fn highlight(cx: &Cx, style: Memo<Option<Style>>, spot: Memo<Option<Spot>>) -> Stack {
830 let slides = Rc::new(Cell::new(false));
833 let running: Rc<Cell<Option<ReadSignal<bool>>>> = Rc::new(Cell::new(None));
834 let (read, sliding) = (Rc::clone(&slides), Rc::clone(&running));
835 let (mut target, mut frame) = (None, Frame::default());
836 let animation = cx.animation(
837 move || {
838 let Some(spot) = spot.get() else {
840 target = None;
841 return frame;
842 };
843 let was = target.replace(spot.target);
844 let under_way = sliding.get().is_some_and(|running| running.get_untracked());
845 slides.set(was.is_some_and(|was| was != spot.target) || under_way);
846 frame = Frame {
847 at: spot.at,
848 size: Point::new(spot.size.width, spot.size.height),
849 };
850 frame
851 },
852 move || {
853 let transition = style.with(|style| style.and_then(|style| style.transition));
854 transition
855 .filter(|_| read.get())
856 .unwrap_or(Transition::new(0))
857 },
858 );
859 running.set(Some(animation.running()));
860 let shown = animation.value();
861 let shape = Stack::new().style(move || {
862 let own = style.get().unwrap_or_default();
863 let size = shown.get().size;
864 own.width(size.x).height(size.y)
865 });
866 Stack::new()
867 .visible(move || style.with(Option::is_some) && spot.with(Option::is_some))
868 .style(move || {
869 let at = shown.get().at;
870 Style::new().left(0.0).top(0.0).translate(at.x, at.y)
871 })
872 .child(shape)
873}
874
875pub(crate) fn prop_fn<T: Clone + 'static>(
877 prop: Option<Prop<T>>,
878 default: T,
879) -> impl FnMut() -> T + 'static {
880 let prop = prop.map(Prop::shared);
881 move || match prop.as_ref() {
882 Some(prop) => prop(),
883 None => default.clone(),
884 }
885}