1use std::cell::Cell;
4
5use ailloli_ui_core::event::{Event, PointerEvent};
6use ailloli_ui_core::geometry::{Constraints, Rect, Size};
7use ailloli_ui_core::scroll::{
8 ScrollAxes, ScrollBehavior, ScrollMetrics, ScrollState, ScrollbarAxis, ScrollbarGeometry,
9 ScrollbarGeometrySpec,
10};
11use ailloli_ui_core::style::FlexItemStyle;
12use ailloli_ui_core::{Color, Offset};
13use ailloli_ui_runtime::component::reactive::with_untracked_reads;
14use ailloli_ui_runtime::component::{ComponentNode, Context, IntoView, Signal, View, Widget};
15use ailloli_ui_runtime::input::EventCtx;
16use ailloli_ui_runtime::layout::LayoutEngine;
17use ailloli_ui_runtime::layout::{
18 ChildLayout, LayoutChild, LayoutCtx, LayoutResult, VirtualViewport,
19};
20use ailloli_ui_runtime::scene::PaintCtx;
21use ailloli_ui_runtime::{DrawCmd, DrawRRect, Invalidation};
22
23use crate::scrollbar::{thumb_color_for_state, ScrollbarInteraction};
24use crate::transactional_layout::TransactionalLayoutPending;
25
26#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct ScrollbarStyle {
42 pub track_color: Color,
44 pub thumb_color: Color,
46 pub thickness: f32,
48 pub min_thumb_len: f32,
50 pub inset: f32,
52 pub radius: f32,
54}
55
56impl Default for ScrollbarStyle {
58 fn default() -> Self {
59 Self {
60 track_color: Color::rgba(148, 163, 184, 0.16),
61 thumb_color: Color::rgba(148, 163, 184, 0.56),
62 thickness: 6.0,
63 min_thumb_len: 24.0,
64 inset: 3.0,
65 radius: 3.0,
66 }
67 }
68}
69
70pub struct ScrollView<A = ()> {
86 axes: ScrollAxes,
88 initial_offset: Offset,
90 behavior: ScrollBehavior,
92 follow_end: bool,
94 scrollbars: bool,
96 scrollbar_style: ScrollbarStyle,
98 child: Option<View<A>>,
100}
101
102impl<A: 'static> Default for ScrollView<A> {
104 fn default() -> Self {
105 Self::new()
106 }
107}
108
109impl<A: 'static> ScrollView<A> {
110 pub fn new() -> Self {
120 Self::vertical()
121 }
122
123 pub fn vertical() -> Self {
135 Self {
136 axes: ScrollAxes::VERTICAL,
137 initial_offset: Offset::default(),
138 behavior: ScrollBehavior::new(ScrollAxes::VERTICAL),
139 follow_end: false,
140 scrollbars: true,
141 scrollbar_style: ScrollbarStyle::default(),
142 child: None,
143 }
144 }
145
146 pub fn horizontal() -> Self {
158 Self {
159 axes: ScrollAxes::HORIZONTAL,
160 initial_offset: Offset::default(),
161 behavior: ScrollBehavior::new(ScrollAxes::HORIZONTAL),
162 follow_end: false,
163 scrollbars: true,
164 scrollbar_style: ScrollbarStyle::default(),
165 child: None,
166 }
167 }
168
169 pub fn both() -> Self {
179 Self {
180 axes: ScrollAxes::BOTH,
181 initial_offset: Offset::default(),
182 behavior: ScrollBehavior::new(ScrollAxes::BOTH),
183 follow_end: false,
184 scrollbars: true,
185 scrollbar_style: ScrollbarStyle::default(),
186 child: None,
187 }
188 }
189
190 pub fn initial_offset(mut self, offset: Offset) -> Self {
204 self.initial_offset = self.axes.filter_offset(offset);
205 self
206 }
207
208 pub fn initial_scroll_y(self, scroll_y: f32) -> Self {
220 self.initial_offset(Offset::new(0.0, scroll_y.max(0.0)))
221 }
222
223 pub fn scroll_y(mut self, scroll_y: f32) -> Self {
237 self.initial_offset.y = (-scroll_y).max(0.0);
238 self
239 }
240
241 pub fn wheel_line_px(mut self, line_px: f32) -> Self {
254 self.behavior = self.behavior.with_line_px(line_px);
255 self
256 }
257
258 pub fn follow_end(mut self, enabled: bool) -> Self {
271 self.follow_end = enabled;
272 self
273 }
274
275 pub fn scrollbars(mut self, enabled: bool) -> Self {
288 self.scrollbars = enabled;
289 self
290 }
291
292 pub fn scrollbar_style(mut self, style: ScrollbarStyle) -> Self {
303 self.scrollbar_style = style;
304 self
305 }
306
307 pub fn child(mut self, child: impl IntoView<A>) -> Self {
317 self.child = Some(child.into_view());
318 self
319 }
320}
321
322struct ScrollViewComponent<A> {
324 axes: ScrollAxes,
326 initial_offset: Offset,
328 behavior: ScrollBehavior,
330 follow_end: bool,
332 scrollbars: bool,
334 scrollbar_style: ScrollbarStyle,
336 child: Option<View<A>>,
338}
339
340impl<A: 'static> ComponentNode<A> for ScrollViewComponent<A> {
342 fn build(&self, context: &mut Context<A>) -> View<A> {
343 let state = context.signal_with_invalidation(
344 ScrollState::with_offset(self.initial_offset),
345 Invalidation::Paint,
346 );
347 let follow_end_active =
348 context.signal_with_invalidation(self.follow_end, Invalidation::Paint);
349 let scrollbar_interaction =
350 context.signal_with_invalidation(ScrollbarInteraction::default(), Invalidation::Paint);
351 let mut children = Vec::new();
352 if let Some(child) = self.child.clone() {
353 children.push(child);
354 }
355
356 View::node(
357 ScrollViewWidget {
358 axes: self.axes,
359 state,
360 behavior: self.behavior,
361 follow_end: self.follow_end,
362 follow_end_active,
363 scrollbars: self.scrollbars,
364 scrollbar_style: self.scrollbar_style,
365 scrollbar_interaction,
366 pending_layout: Cell::new(None),
367 },
368 children,
369 )
370 }
371}
372
373struct ScrollViewWidget {
375 axes: ScrollAxes,
377 state: Signal<ScrollState>,
379 behavior: ScrollBehavior,
381 follow_end: bool,
383 follow_end_active: Signal<bool>,
385 scrollbars: bool,
387 scrollbar_style: ScrollbarStyle,
389 scrollbar_interaction: Signal<ScrollbarInteraction>,
391 pending_layout: Cell<Option<TransactionalLayoutPending<PendingScrollViewLayout>>>,
393}
394
395#[derive(Clone, Copy)]
397struct PendingScrollViewLayout {
398 state: Option<ScrollState>,
400 follow_end_active: Option<bool>,
402 scrollbar_interaction: Option<ScrollbarInteraction>,
404}
405
406impl<A: 'static> Widget<A> for ScrollViewWidget {
408 fn debug_name(&self) -> &'static str {
409 "ScrollView"
410 }
411
412 fn layout(
413 &self,
414 engine: &mut LayoutEngine<'_, A>,
415 ctx: &mut LayoutCtx<'_>,
416 children: &mut [LayoutChild],
417 constraints: Constraints,
418 ) -> LayoutResult {
419 let mut child_layouts = Vec::new();
420 let mut state = with_untracked_reads(|| self.state.read());
424 let mut next_follow_end_active = None;
425 let mut persist_state = false;
426 let constraints_max = constraints.max_size();
427 let mut size = finite_or_zero_size(constraints_max);
428
429 if let Some(child) = children.first_mut() {
430 let child_constraints = self.child_constraints(constraints_max);
431 let viewport_hint_size = finite_or_zero_size(constraints_max);
432 let previous_viewport = ctx.replace_virtual_viewport(Some(VirtualViewport::new(
433 Rect::new(
434 state.offset.x,
435 state.offset.y,
436 viewport_hint_size.w,
437 viewport_hint_size.h,
438 ),
439 0.0,
440 )));
441 let mut r = child.layout(engine, ctx, child_constraints);
442 ctx.replace_virtual_viewport(previous_viewport);
443 size = viewport_size(constraints_max, r.size);
444 if self.has_bounded_scroll_viewport(constraints_max) {
445 let metrics = ScrollMetrics::new(size, r.size);
446 let (next_state, next_follow) = self.sync_scroll_state_for_layout(state, metrics);
447 if !same_offset(state.offset, next_state.offset) {
448 let previous_viewport =
449 ctx.replace_virtual_viewport(Some(VirtualViewport::new(
450 Rect::new(next_state.offset.x, next_state.offset.y, size.w, size.h),
451 0.0,
452 )));
453 r = child.layout(engine, ctx, child_constraints);
454 ctx.replace_virtual_viewport(previous_viewport);
455 }
456 state = next_state;
457 next_follow_end_active = next_follow;
458 persist_state = true;
459 } else {
460 state = ScrollState::new();
468 }
469 child_layouts.push(ChildLayout {
470 offset: Offset::new(-state.offset.x, -state.offset.y),
471 size: r.size,
472 paint_bounds: Rect::new(0.0, 0.0, r.size.w, r.size.h),
473 visual_bounds: r.visual_bounds,
474 });
475 }
476 let viewport = Rect::new(0.0, 0.0, size.w, size.h);
477
478 let scrollbar_geometries = if self.scrollbars {
479 let metrics = child_layouts
480 .first()
481 .map(|child| ScrollMetrics::new(size, child.size));
482 metrics
483 .map(|metrics| {
484 scrollbars_for(viewport, metrics, state, self.axes, self.scrollbar_style)
485 })
486 .unwrap_or_default()
487 } else {
488 Vec::new()
489 };
490 let mut interaction = with_untracked_reads(|| self.scrollbar_interaction.read());
495 let interaction_changed = interaction.reconcile(ctx.layout_pass(), &scrollbar_geometries);
496 if ctx.layout_pass().is_committed() {
497 let retained_state = with_untracked_reads(|| self.state.read());
498 self.pending_layout.set(TransactionalLayoutPending::new(
499 ctx,
500 PendingScrollViewLayout {
501 state: (persist_state && !same_offset(retained_state.offset, state.offset))
502 .then_some(state),
503 follow_end_active: next_follow_end_active,
504 scrollbar_interaction: interaction_changed.then_some(interaction),
505 },
506 ));
507 }
508
509 LayoutResult {
510 size,
511 children: child_layouts,
512 paint_bounds: viewport,
513 visual_bounds: viewport,
514 overlay_hit_bounds: scrollbar_geometries
515 .iter()
516 .map(|geometry| geometry.hit_track)
517 .collect(),
518 clip: Some(ailloli_ui_core::ClipShape::Rect(viewport)),
519 is_window_root_clip: false,
520 artifact: None,
521 }
522 }
523
524 fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
525 let Some(pending) = self
526 .pending_layout
527 .take()
528 .and_then(|pending| pending.into_committed(ctx))
529 else {
530 return;
531 };
532 if let Some(state) = pending.state {
533 self.state.set(state);
534 }
535 if let Some(active) = pending.follow_end_active {
536 self.follow_end_active.set(active);
537 }
538 if let Some(interaction) = pending.scrollbar_interaction {
539 self.scrollbar_interaction.set(interaction);
540 }
541 }
542
543 fn paint(&self, _ctx: &mut PaintCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {}
544
545 fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
546 if !self.scrollbars {
547 return;
548 }
549 let Some(child) = layout.children.first() else {
550 return;
551 };
552
553 let metrics = ScrollMetrics::new(layout.size, child.size);
554 let state = self.state.read();
555 let geometries = scrollbars_for(bounds, metrics, state, self.axes, self.scrollbar_style);
556 paint_scrollbars(
557 ctx,
558 &geometries,
559 self.scrollbar_style,
560 self.scrollbar_interaction.read(),
561 );
562 }
563
564 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, layout: &LayoutResult) {
565 let Some(child) = layout.children.first() else {
566 return;
567 };
568
569 let metrics = ScrollMetrics::new(layout.size, child.size);
570 if self.scrollbars {
571 let geometries = scrollbars_for(
572 bounds,
573 metrics,
574 self.state.read(),
575 self.axes,
576 self.scrollbar_style,
577 );
578 let mut interaction = self.scrollbar_interaction.read();
579 let response = interaction.handle_event(ctx, event, &geometries);
580 if response.state_changed {
581 self.scrollbar_interaction.set(interaction);
582 }
583 let mut scrolled = false;
584 if let Some((axis, target)) = response.scroll_to {
585 let state = self.state.read();
586 let target = match axis {
587 ScrollbarAxis::Horizontal => Offset::new(target, state.offset.y),
588 ScrollbarAxis::Vertical => Offset::new(state.offset.x, target),
589 };
590 let outcome = state.scroll_to(target, metrics, self.axes);
591 if outcome.changed {
592 self.state.set(outcome.state());
593 self.sync_follow_end_after_manual_scroll(outcome.after, outcome.max_offset);
594 scrolled = true;
595 }
596 }
597 if response.repaint || scrolled {
598 if scrolled {
599 ctx.request_layout();
600 } else {
601 ctx.request_repaint();
602 }
603 }
604 if response.consumed {
605 ctx.stop_propagation();
606 return;
607 }
608 }
609
610 if let Event::Pointer(PointerEvent::Wheel {
611 delta, modifiers, ..
612 }) = event
613 {
614 let state = self.state.read();
615 let outcome = state.scroll_by(
616 self.behavior.wheel_delta_with_modifiers(*delta, *modifiers),
617 metrics,
618 self.axes,
619 );
620 if outcome.changed {
621 self.state.set(outcome.state());
622 self.sync_follow_end_after_manual_scroll(outcome.after, outcome.max_offset);
623 ctx.request_layout();
624 ctx.stop_propagation();
625 }
626 }
627 }
628}
629
630impl<A: 'static> IntoView<A> for ScrollView<A> {
632 fn into_view(self) -> View<A> {
633 View::component(ScrollViewComponent {
634 axes: self.axes,
635 initial_offset: self.initial_offset,
636 behavior: self.behavior,
637 follow_end: self.follow_end,
638 scrollbars: self.scrollbars,
639 scrollbar_style: self.scrollbar_style,
640 child: self.child,
641 })
642 .with_flex_item(FlexItemStyle::new().flex_shrink(1.0))
646 }
647}
648
649impl ScrollViewWidget {
651 fn has_bounded_scroll_viewport(&self, viewport: Size) -> bool {
653 (!self.axes.horizontal || viewport.w.is_finite())
654 && (!self.axes.vertical || viewport.h.is_finite())
655 }
656
657 fn sync_scroll_state_for_layout(
659 &self,
660 state: ScrollState,
661 metrics: ScrollMetrics,
662 ) -> (ScrollState, Option<bool>) {
663 if !self.follow_end {
664 let clamped = state.clamp_to(metrics, self.axes);
665 return (clamped.state(), None);
666 }
667
668 let max_offset = self.axes.filter_offset(metrics.max_offset());
669 let follow_active = with_untracked_reads(|| self.follow_end_active.read());
670 let mut next_follow_active = follow_active;
671 let target = if follow_active {
672 ScrollState::with_offset(max_offset)
673 } else {
674 let clamped = state.clamp_to(metrics, self.axes).state();
675 if offset_at_end(clamped.offset, max_offset, self.axes) {
676 next_follow_active = true;
677 }
678 clamped
679 };
680 (
681 target,
682 (next_follow_active != follow_active).then_some(next_follow_active),
683 )
684 }
685
686 fn sync_follow_end_after_manual_scroll(&self, offset: Offset, max_offset: Offset) {
688 if !self.follow_end {
689 return;
690 }
691 self.set_follow_end_active(offset_at_end(offset, max_offset, self.axes));
692 }
693
694 fn set_follow_end_active(&self, active: bool) {
696 if with_untracked_reads(|| self.follow_end_active.read()) != active {
697 self.follow_end_active.set(active);
698 }
699 }
700
701 fn child_constraints(&self, viewport: Size) -> Constraints {
703 Constraints::loose(
704 if self.axes.horizontal {
705 f32::INFINITY
706 } else {
707 viewport.w
708 },
709 if self.axes.vertical {
710 f32::INFINITY
711 } else {
712 viewport.h
713 },
714 )
715 }
716}
717
718const FOLLOW_END_EPSILON: f32 = 1.0;
720
721fn offset_at_end(offset: Offset, max_offset: Offset, axes: ScrollAxes) -> bool {
723 (!axes.horizontal || offset.x >= max_offset.x - FOLLOW_END_EPSILON)
724 && (!axes.vertical || offset.y >= max_offset.y - FOLLOW_END_EPSILON)
725}
726
727fn same_offset(a: Offset, b: Offset) -> bool {
729 (a.x - b.x).abs() < 0.001 && (a.y - b.y).abs() < 0.001
730}
731
732fn finite_or_zero_size(size: Size) -> Size {
734 Size::new(
735 if size.w.is_finite() { size.w } else { 0.0 },
736 if size.h.is_finite() { size.h } else { 0.0 },
737 )
738}
739
740fn viewport_size(constraints_max: Size, content: Size) -> Size {
742 Size::new(
743 finite_or_content(constraints_max.w, content.w),
744 finite_or_content(constraints_max.h, content.h),
745 )
746}
747
748fn finite_or_content(max: f32, content: f32) -> f32 {
750 if max.is_finite() {
751 max
752 } else {
753 content
754 }
755}
756
757fn paint_scrollbars(
759 ctx: &mut PaintCtx<'_>,
760 geometries: &[ScrollbarGeometry],
761 style: ScrollbarStyle,
762 interaction: ScrollbarInteraction,
763) {
764 for geometry in geometries.iter().copied() {
765 push_scrollbar(ctx, geometry, style, interaction);
766 }
767}
768
769fn push_scrollbar(
771 ctx: &mut PaintCtx<'_>,
772 geometry: ScrollbarGeometry,
773 style: ScrollbarStyle,
774 interaction: ScrollbarInteraction,
775) {
776 ctx.push(DrawCmd::RRect(DrawRRect {
777 rect: geometry.track,
778 radius: style.radius,
779 color: style.track_color,
780 }));
781 ctx.push(DrawCmd::RRect(DrawRRect {
782 rect: geometry.thumb,
783 radius: style.radius,
784 color: thumb_color_for_state(
785 style.thumb_color,
786 interaction.visual_state(geometry.axis, ctx.is_hovered()),
787 ),
788 }));
789}
790
791fn scrollbars_for(
793 bounds: Rect,
794 metrics: ScrollMetrics,
795 state: ScrollState,
796 axes: ScrollAxes,
797 style: ScrollbarStyle,
798) -> Vec<ScrollbarGeometry> {
799 let max = metrics.max_offset();
800 let show_horizontal = axes.horizontal && max.x > 0.5;
801 let show_vertical = axes.vertical && max.y > 0.5;
802 let reserve = style.thickness + style.inset;
803 let mut geometries = Vec::with_capacity(2);
804 if show_vertical {
805 let spec = ScrollbarGeometrySpec::new(ScrollbarAxis::Vertical, bounds, metrics, state)
806 .with_paint_metrics(style.thickness, style.min_thumb_len, style.inset)
807 .with_end_reserve(if show_horizontal { reserve } else { 0.0 });
808 if let Some(geometry) = spec.resolve() {
809 geometries.push(geometry);
810 }
811 }
812 if show_horizontal {
813 let spec = ScrollbarGeometrySpec::new(ScrollbarAxis::Horizontal, bounds, metrics, state)
814 .with_paint_metrics(style.thickness, style.min_thumb_len, style.inset)
815 .with_end_reserve(if show_vertical { reserve } else { 0.0 });
816 if let Some(geometry) = spec.resolve() {
817 geometries.push(geometry);
818 }
819 }
820 geometries
821}