1use std::cell::{Cell, RefCell};
5use std::collections::HashMap;
6use std::hash::Hash;
7use std::rc::Rc;
8
9use crabshell_reactive::{Memo, Signal, untrack};
10
11use crate::cx::Cx;
12use crate::geometry::{Point, Size};
13use crate::prop::{IntoProp, Prop};
14use crate::style::Style;
15use crate::widgets::{
16 Column, Common, Element, ElementChild, ElementKind, Stack, Widget, visibility_methods,
17};
18
19pub(crate) const PIXELS_PER_NOTCH: f32 = 48.0;
21
22pub(crate) const BAR_WIDTH: f32 = 6.0;
24
25pub(crate) const BAR_MIN_LENGTH: f32 = 16.0;
28
29pub(crate) struct ScrollProps {
30 pub(crate) offset: Option<Signal<f32>>,
31 pub(crate) horizontal: Option<Prop<bool>>,
32 pub(crate) kinetic: Option<Prop<bool>>,
33 pub(crate) overshoot: Option<Prop<bool>>,
34 pub(crate) scroll_bar: Option<Prop<Option<Style>>>,
35 pub(crate) shifts: Option<Rc<Cell<f32>>>,
38 pub(crate) moving: Option<Rc<Cell<bool>>>,
42}
43
44pub struct ScrollView {
55 pub(crate) scroll: ScrollProps,
56 common: Common,
57 child: Box<dyn Widget>,
58}
59
60impl ScrollView {
61 pub fn new(child: impl Widget) -> ScrollView {
63 ScrollView {
64 scroll: ScrollProps {
65 offset: None,
66 horizontal: None,
67 kinetic: None,
68 overshoot: None,
69 scroll_bar: None,
70 shifts: None,
71 moving: None,
72 },
73 common: Common::default(),
74 child: Box::new(child),
75 }
76 }
77
78 pub fn offset(mut self, offset: Signal<f32>) -> ScrollView {
83 self.scroll.offset = Some(offset);
84 self
85 }
86
87 pub fn horizontal(mut self, horizontal: impl IntoProp<bool>) -> ScrollView {
91 self.scroll.horizontal = Some(horizontal.into_prop());
92 self
93 }
94
95 pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> ScrollView {
100 self.scroll.kinetic = Some(kinetic.into_prop());
101 self
102 }
103
104 pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> ScrollView {
110 self.scroll.overshoot = Some(overshoot.into_prop());
111 self
112 }
113
114 pub fn scroll_bar(mut self, style: impl IntoProp<Option<Style>>) -> ScrollView {
122 self.scroll.scroll_bar = Some(style.into_prop());
123 self
124 }
125
126 pub fn style(mut self, style: impl IntoProp<Style>) -> ScrollView {
129 self.common.style = Some(style.into_prop());
130 self
131 }
132
133 visibility_methods!();
134}
135
136impl Widget for ScrollView {
137 fn into_element(self: Box<Self>) -> Element {
138 let ScrollView {
139 scroll,
140 common,
141 child,
142 } = *self;
143 Element {
144 name: "ScrollView",
145 common,
146 kind: ElementKind::Scroll(Box::new(scroll)),
147 children: vec![ElementChild::One(Box::new(child.into_element()))],
148 }
149 }
150}
151
152pub struct ListView {
177 build: Build,
179 props: ListProps,
180 common: Common,
181}
182
183type Build = Box<dyn FnOnce(&Cx, ListProps) -> Element>;
185
186struct ListProps {
187 row_height: Option<Prop<u32>>,
188 height: Option<Prop<u32>>,
189 current: Option<Prop<Option<usize>>>,
190 offset: Option<Signal<f32>>,
191 style: Option<Prop<Style>>,
192 scroll_bar: Option<Prop<Option<Style>>>,
193 kinetic: Option<Prop<bool>>,
194 overshoot: Option<Prop<bool>>,
195 horizontal: Option<Prop<bool>>,
196 highlight: Option<Prop<Option<Style>>>,
197}
198
199impl ListView {
200 pub const DEFAULT_ROW_HEIGHT: u32 = 24;
202 pub const DEFAULT_HEIGHT: u32 = 240;
204
205 pub fn new<T, K, W>(
208 items: impl FnMut() -> Vec<T> + 'static,
209 key: impl FnMut(&T) -> K + 'static,
210 view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
211 ) -> ListView
212 where
213 T: Clone + PartialEq + 'static,
214 K: Eq + Hash + 'static,
215 W: Widget,
216 {
217 ListView {
218 build: Box::new(move |cx, props| build(cx, props, items, key, view)),
219 props: ListProps {
220 row_height: None,
221 height: None,
222 current: None,
223 offset: None,
224 style: None,
225 scroll_bar: None,
226 kinetic: None,
227 overshoot: None,
228 horizontal: None,
229 highlight: None,
230 },
231 common: Common::default(),
232 }
233 }
234
235 pub fn horizontal(mut self, horizontal: impl IntoProp<bool>) -> ListView {
240 self.props.horizontal = Some(horizontal.into_prop());
241 self
242 }
243
244 pub fn row_height(mut self, height: impl IntoProp<u32>) -> ListView {
247 self.props.row_height = Some(height.into_prop());
248 self
249 }
250
251 pub fn height(mut self, height: impl IntoProp<u32>) -> ListView {
253 self.props.height = Some(height.into_prop());
254 self
255 }
256
257 pub fn current(mut self, index: impl IntoProp<Option<usize>>) -> ListView {
265 self.props.current = Some(index.into_prop());
266 self
267 }
268
269 pub fn highlight(mut self, style: impl IntoProp<Option<Style>>) -> ListView {
276 self.props.highlight = Some(style.into_prop());
277 self
278 }
279
280 pub fn offset(mut self, offset: Signal<f32>) -> ListView {
282 self.props.offset = Some(offset);
283 self
284 }
285
286 pub fn kinetic(mut self, kinetic: impl IntoProp<bool>) -> ListView {
289 self.props.kinetic = Some(kinetic.into_prop());
290 self
291 }
292
293 pub fn overshoot(mut self, overshoot: impl IntoProp<bool>) -> ListView {
296 self.props.overshoot = Some(overshoot.into_prop());
297 self
298 }
299
300 pub fn scroll_bar(mut self, style: impl IntoProp<Option<Style>>) -> ListView {
302 self.props.scroll_bar = Some(style.into_prop());
303 self
304 }
305
306 pub fn style(mut self, style: impl IntoProp<Style>) -> ListView {
308 self.props.style = Some(style.into_prop());
309 self
310 }
311
312 visibility_methods!();
313}
314
315impl Widget for ListView {
316 fn into_element(self: Box<Self>) -> Element {
317 let ListView {
318 build,
319 props,
320 common,
321 } = *self;
322 let mut once = Some((build, props));
323 let mut element = Box::new(Stack::new().children_keyed(
326 || vec![()],
327 |_| (),
328 move |cx, _| Built(once.take().map(|(build, props)| build(cx, props))),
329 ))
330 .into_element();
331 element.name = "ListView";
332 element.common = common;
333 element
334 }
335}
336
337pub(crate) struct Built(pub(crate) Option<Element>);
339
340impl Widget for Built {
341 fn into_element(self: Box<Self>) -> Element {
342 self
343 .0
344 .unwrap_or_else(|| Box::new(Stack::new()).into_element())
345 }
346}
347
348struct Lengths<K> {
350 index: HashMap<K, usize>,
352 measured: Vec<Option<f32>>,
354 pending: Vec<(usize, f32)>,
356 seek: Option<usize>,
359}
360
361fn starts(measured: &[Option<f32>], estimate: f32) -> Vec<f32> {
364 let mut starts = Vec::with_capacity(measured.len() + 1);
365 let mut at = 0.0;
366 starts.push(at);
367 for length in measured {
368 at += length.unwrap_or(estimate);
369 starts.push(at);
370 }
371 starts
372}
373
374pub(crate) fn keep_in_view(start: f32, end: f32, viewport: f32, now: f32) -> f32 {
377 if start < now {
378 start
379 } else if end > now + viewport {
380 end - viewport
381 } else {
382 now
383 }
384}
385
386fn build<T, K, W>(
387 cx: &Cx,
388 props: ListProps,
389 mut items: impl FnMut() -> Vec<T> + 'static,
390 key: impl FnMut(&T) -> K + 'static,
391 mut view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
392) -> Element
393where
394 T: Clone + PartialEq + 'static,
395 K: Eq + Hash + 'static,
396 W: Widget,
397{
398 let ListProps {
399 row_height,
400 height,
401 current,
402 offset,
403 style,
404 scroll_bar,
405 kinetic,
406 overshoot,
407 horizontal,
408 highlight: highlight_style,
409 } = props;
410 let offset = offset.unwrap_or_else(|| cx.signal(0.0));
411 let horizontal = cx.memo(prop_fn(horizontal, false));
412 let row_height = cx.memo(prop_fn(row_height, ListView::DEFAULT_ROW_HEIGHT));
413 let estimate = move || row_height.get().max(1) as f32;
414 let height = cx.memo(prop_fn(height, ListView::DEFAULT_HEIGHT));
415 let style = style.map(Prop::shared);
416 let inner = {
418 let style = style.clone();
419 cx.memo(move || {
420 let own = style.as_ref().map(|style| style()).unwrap_or_default();
421 let padding = own.padding.unwrap_or_default();
422 let border = own.border.map_or(0.0, |border| border.width.max(0.0));
423 let sides = if horizontal.get() {
424 padding.left + padding.right
425 } else {
426 padding.top + padding.bottom
427 };
428 (height.get() as f32 - sides as f32 - 2.0 * border).max(0.0)
429 })
430 };
431 let key = Rc::new(RefCell::new(key));
434 let lengths = Rc::new(RefCell::new(Lengths {
435 index: HashMap::new(),
436 measured: Vec::new(),
437 pending: Vec::new(),
438 seek: None,
439 }));
440 let remeasure = cx.signal(());
442 let measured = cx.signal(());
443 let changes = cx.signal(0_u64);
445 let all = cx.signal(Vec::<T>::new());
446 {
447 let (key, lengths) = (Rc::clone(&key), Rc::clone(&lengths));
448 cx.effect(move || {
449 let list = items();
450 let keys: Vec<K> = list.iter().map(|item| (key.borrow_mut())(item)).collect();
451 let mut lengths = lengths.borrow_mut();
452 let old = std::mem::take(&mut lengths.measured);
453 let mut index = HashMap::with_capacity(keys.len());
454 let mut measured = Vec::with_capacity(keys.len());
455 let mut moved = vec![None; old.len()];
457 for (at, item_key) in keys.into_iter().enumerate() {
458 let was = lengths.index.get(&item_key).copied();
459 if let Some(was) = was {
460 moved[was].get_or_insert(at);
461 }
462 measured.push(was.and_then(|was| old[was]));
463 index.entry(item_key).or_insert(at);
464 }
465 lengths.index = index;
466 lengths.measured = measured;
467 let pending = std::mem::take(&mut lengths.pending);
468 lengths.pending = pending
469 .into_iter()
470 .filter_map(|(was, length)| Some((moved.get(was).copied().flatten()?, length)))
471 .collect();
472 drop(lengths);
473 all.set(list);
474 changes.update(|n| *n += 1);
475 remeasure.set(());
476 });
477 }
478 {
480 let lengths = Rc::clone(&lengths);
481 let mut was = None;
482 cx.effect(move || {
483 let now = horizontal.get();
484 if was.replace(now).is_some_and(|was| was != now) {
485 lengths.borrow_mut().measured.fill(None);
486 remeasure.set(());
487 }
488 });
489 }
490 let count = cx.memo(move || all.with(Vec::len));
491 let starts = {
492 let lengths = Rc::clone(&lengths);
493 cx.memo(move || {
494 remeasure.get();
495 starts(&lengths.borrow().measured, estimate())
496 })
497 };
498 let total = move || starts.with(|starts| starts.last().copied().unwrap_or(0.0));
499 let shown = move || {
501 let most = (total() - inner.get()).max(0.0);
502 let offset = offset.get();
503 if offset.is_nan() {
504 0.0
505 } else {
506 offset.clamp(0.0, most)
507 }
508 };
509 let range = cx.memo(move || {
512 let top = shown();
513 let bottom = top + inner.get();
514 starts.with(|starts| {
515 let rows = starts.len() - 1;
516 let first = starts
517 .partition_point(|&start| start <= top)
518 .saturating_sub(2);
519 let last = (starts.partition_point(|&start| start < bottom) + 1).min(rows);
520 first..last.max(first)
521 })
522 });
523 let shifts = Rc::new(Cell::new(0.0));
526 {
527 let lengths = Rc::clone(&lengths);
528 let shifts = Rc::clone(&shifts);
529 cx.effect(move || {
530 measured.get();
531 let (old, top, estimate) = untrack(|| (starts.get(), shown(), estimate()));
532 let mut lengths = lengths.borrow_mut();
533 let mut changed = false;
534 let mut shift = 0.0;
535 for (at, length) in std::mem::take(&mut lengths.pending) {
536 let Some(slot) = lengths.measured.get_mut(at) else {
537 continue;
538 };
539 if *slot == Some(length) {
540 continue;
541 }
542 if old[at] < top {
543 shift += length - slot.unwrap_or(estimate);
544 }
545 *slot = Some(length);
546 changed = true;
547 }
548 let seek = lengths
549 .seek
550 .filter(|&at| lengths.measured.get(at).is_some_and(Option::is_some));
551 if seek.is_some() {
552 lengths.seek = None;
553 }
554 drop(lengths);
555 if !changed {
556 return;
557 }
558 remeasure.set(());
559 if shift != 0.0 {
560 shifts.set(shifts.get() + shift);
562 offset.set(top + shift);
563 }
564 if let Some(at) = seek {
565 untrack(|| {
566 let (start, end) = starts.with(|starts| (starts[at], starts[at + 1]));
567 let now = shown();
568 let next = keep_in_view(start, end, inner.get(), now);
569 if next != now {
570 offset.set(next);
571 }
572 });
573 }
574 });
575 }
576 let moving = Rc::new(Cell::new(false));
577 let current = current.map(Prop::shared);
578 if let Some(current) = current.clone() {
579 let lengths = Rc::clone(&lengths);
580 let moving = Rc::clone(&moving);
581 let mut asked = None;
582 cx.effect(move || {
583 let index = current();
584 let ask = (index, row_height.get(), inner.get());
587 let wanted = index.filter(|&index| index < count.get());
588 let fresh = asked.replace((ask, wanted.is_some())) != Some((ask, true));
589 let Some(index) = wanted else {
590 lengths.borrow_mut().seek = None;
591 return;
592 };
593 if !fresh || moving.get() {
596 lengths.borrow_mut().seek = None;
597 return;
598 }
599 let viewport = ask.2;
600 let (start, end) = untrack(|| starts.with(|starts| (starts[index], starts[index + 1])));
601 let now = untrack(shown);
602 let next = keep_in_view(start, end, viewport, now);
603 if next != now {
604 offset.set(next);
605 }
606 let mut lengths = lengths.borrow_mut();
607 let unmeasured = lengths.measured.get(index).is_some_and(Option::is_none);
608 lengths.seek = unmeasured.then_some(index);
609 });
610 }
611 let mut rows = Column::new().style(move || along(horizontal.get(), Style::new(), total()));
612 let cross = cx.signal(0.0_f32);
615 if let (Some(style), Some(current)) = (highlight_style, current) {
616 let spot = cx.memo(move || {
617 let index = current()?;
618 let (start, end) =
619 starts.with(|starts| Some((*starts.get(index)?, *starts.get(index + 1)?)))?;
620 let target = (index, changes.get());
621 let (length, across) = (end - start, cross.get());
622 Some(if horizontal.get() {
623 Spot {
624 at: Point::new(start, 0.0),
625 size: Size::new(length, across),
626 target,
627 }
628 } else {
629 Spot {
630 at: Point::new(0.0, start),
631 size: Size::new(across, length),
632 target,
633 }
634 })
635 });
636 rows = rows.child(highlight(cx, cx.memo(prop_fn(Some(style), None)), spot));
637 }
638 let rows = rows
639 .child(Stack::new().style(move || {
640 let first = starts.with(|starts| starts[range.get().start]);
641 along(horizontal.get(), Style::new(), first).shrink(0.0)
642 }))
643 .children_keyed(
644 move || {
645 let range = range.get();
646 all.with(|all| {
647 let end = range.end.min(all.len());
648 all[range.start.min(end)..end].to_vec()
649 })
650 },
651 {
652 let key = Rc::clone(&key);
653 move |item| (key.borrow_mut())(item)
654 },
655 move |cx, item| {
656 let own = (key.borrow_mut())(&item.get_untracked());
657 let lengths = Rc::clone(&lengths);
658 let measure = move |size: Size| {
659 let mut lengths = lengths.borrow_mut();
660 if let Some(&at) = lengths.index.get(&own) {
661 let length = if horizontal.try_get().unwrap_or_default() {
662 size.width
663 } else {
664 size.height
665 };
666 lengths.pending.push((at, length));
667 drop(lengths);
668 measured.try_set(());
669 }
670 };
671 let row = Stack::new()
672 .style(move || {
673 let least = row_height.get() as f32;
674 let style = Style::new().shrink(0.0);
675 if horizontal.get() {
676 style.min_width(least)
677 } else {
678 style.min_height(least)
679 }
680 })
681 .child(view(cx, item));
682 let mut row = Box::new(row).into_element();
683 row.common.measure = Some(Rc::new(measure));
684 Built(Some(row))
685 },
686 );
687 let mut rows = Box::new(rows).into_element();
688 rows.common.measure = Some(Rc::new(move |size: Size| {
689 let across = if horizontal.try_get().unwrap_or_default() {
690 size.height
691 } else {
692 size.width
693 };
694 if cross.try_get() != Some(across) {
695 cross.try_set(across);
696 }
697 }));
698 if let ElementKind::Flex(flex) = &mut rows.kind {
699 flex.column_binding = Some((move || !horizontal.get()).into_prop());
700 }
701 let mut scroll = ScrollView::new(Built(Some(rows)))
702 .offset(offset)
703 .horizontal(move || horizontal.get());
704 scroll.scroll.shifts = Some(shifts);
705 scroll.scroll.moving = Some(moving);
706 if let Some(bar) = scroll_bar {
707 scroll = scroll.scroll_bar(bar);
708 }
709 if let Some(kinetic) = kinetic {
710 scroll = scroll.kinetic(kinetic);
711 }
712 if let Some(overshoot) = overshoot {
713 scroll = scroll.overshoot(overshoot);
714 }
715 scroll = scroll.style(move || {
716 let own = style.as_ref().map(|style| style()).unwrap_or_default();
717 along(horizontal.get(), own, height.get() as f32)
718 });
719 Box::new(scroll).into_element()
720}
721
722fn along(horizontal: bool, style: Style, length: f32) -> Style {
725 if horizontal {
726 style.width(length)
727 } else {
728 style.height(length)
729 }
730}
731
732#[derive(Clone, Copy, PartialEq)]
735pub(crate) struct Spot {
736 pub(crate) at: Point,
737 pub(crate) size: Size,
738 pub(crate) target: (usize, u64),
741}
742
743pub(crate) fn highlight(cx: &Cx, style: Memo<Option<Style>>, spot: Memo<Option<Spot>>) -> Stack {
748 let place = cx.memo(move || spot.get().map(|spot| (spot.at, spot.target)));
750 let shape = Stack::new().style(move || {
751 let own = style.get().unwrap_or_default();
752 match spot.get() {
753 Some(spot) => own.width(spot.size.width).height(spot.size.height),
754 None => own,
755 }
756 });
757 let mut last = None;
758 Stack::new()
759 .visible(move || style.with(Option::is_some) && spot.with(Option::is_some))
760 .style(move || {
761 let Some((at, target)) = place.get() else {
763 return Style::new().left(0.0).top(0.0);
764 };
765 let moved = last.replace(target) != Some(target);
766 let mover = Style::new().left(0.0).top(0.0).translate(at.x, at.y);
767 match style.get().and_then(|style| style.transition) {
768 Some(transition) if moved => mover.transition(transition),
769 _ => mover,
770 }
771 })
772 .child(shape)
773}
774
775pub(crate) fn prop_fn<T: Clone + 'static>(
777 prop: Option<Prop<T>>,
778 default: T,
779) -> impl FnMut() -> T + 'static {
780 let prop = prop.map(Prop::shared);
781 move || match prop.as_ref() {
782 Some(prop) => prop(),
783 None => default.clone(),
784 }
785}