Skip to main content

fc_ui/capabilities/scroll/
scrollable.rs

1//! Scrollable component with visible scrollbars.
2
3use crate::capabilities::scroll::scrollbar::{Scrollbar, ScrollbarAxis, ScrollbarState};
4use gpui::{
5    div, relative, AnyElement, App, Bounds, Element, ElementId, GlobalElementId,
6    InspectorElementId, InteractiveElement, Interactivity, IntoElement, LayoutId, ParentElement,
7    Pixels, Position, ScrollHandle, SharedString, StatefulInteractiveElement, Style,
8    StyleRefinement, Styled, Window,
9};
10
11/// A scroll view with visible scrollbars
12pub struct Scrollable<E> {
13    id: ElementId,
14    element: Option<E>,
15    axis: ScrollbarAxis,
16    always_show_scrollbars: bool,
17    external_scroll_handle: Option<ScrollHandle>,
18}
19
20impl<E> Scrollable<E>
21where
22    E: Element,
23{
24    pub(crate) fn new(axis: ScrollbarAxis, element: E) -> Self {
25        let id = ElementId::Name(SharedString::from(format!("scrollable-{:?}", element.id())));
26
27        Self {
28            element: Some(element),
29            id,
30            axis,
31            always_show_scrollbars: false,
32            external_scroll_handle: None,
33        }
34    }
35
36    pub fn vertical(element: E) -> Self {
37        Self::new(ScrollbarAxis::Vertical, element)
38    }
39
40    pub fn horizontal(element: E) -> Self {
41        Self::new(ScrollbarAxis::Horizontal, element)
42    }
43
44    pub fn both(element: E) -> Self {
45        Self::new(ScrollbarAxis::Both, element)
46    }
47
48    pub fn always_show_scrollbars(mut self) -> Self {
49        self.always_show_scrollbars = true;
50        self
51    }
52
53    pub fn with_scroll_handle(mut self, handle: ScrollHandle) -> Self {
54        self.external_scroll_handle = Some(handle);
55        self
56    }
57
58    fn with_element_state<R>(
59        &mut self,
60        id: &GlobalElementId,
61        window: &mut Window,
62        cx: &mut App,
63        f: impl FnOnce(&mut Self, &mut ScrollViewState, &mut Window, &mut App) -> R,
64    ) -> R {
65        window.with_optional_element_state::<ScrollViewState, _>(
66            Some(id),
67            |element_state, window| {
68                let mut element_state = element_state.unwrap().unwrap_or_default();
69                let result = f(self, &mut element_state, window, cx);
70                (result, Some(element_state))
71            },
72        )
73    }
74}
75
76pub struct ScrollViewState {
77    state: ScrollbarState,
78    handle: ScrollHandle,
79}
80
81impl Default for ScrollViewState {
82    fn default() -> Self {
83        Self {
84            handle: ScrollHandle::new(),
85            state: ScrollbarState::default(),
86        }
87    }
88}
89
90impl<E> ParentElement for Scrollable<E>
91where
92    E: Element + ParentElement,
93{
94    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
95        self.element
96            .as_mut()
97            .expect("Scrollable: children must be added before the element is rendered")
98            .extend(elements);
99    }
100}
101
102impl<E> Styled for Scrollable<E>
103where
104    E: Element + Styled,
105{
106    fn style(&mut self) -> &mut StyleRefinement {
107        self.element
108            .as_mut()
109            .expect("Scrollable: styling must be applied before the element is rendered")
110            .style()
111    }
112}
113
114impl<E> InteractiveElement for Scrollable<E>
115where
116    E: Element + InteractiveElement,
117{
118    fn interactivity(&mut self) -> &mut Interactivity {
119        self.element
120            .as_mut()
121            .expect("Scrollable: interaction handlers must be registered before the element is rendered")
122            .interactivity()
123    }
124}
125
126impl<E> StatefulInteractiveElement for Scrollable<E> where E: Element + StatefulInteractiveElement {}
127
128impl<E> IntoElement for Scrollable<E>
129where
130    E: Element,
131{
132    type Element = Self;
133
134    fn into_element(self) -> Self::Element {
135        self
136    }
137}
138
139impl<E> Element for Scrollable<E>
140where
141    E: Element,
142{
143    type RequestLayoutState = AnyElement;
144    type PrepaintState = ();
145
146    fn id(&self) -> Option<ElementId> {
147        Some(self.id.clone())
148    }
149
150    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
151        None
152    }
153
154    fn request_layout(
155        &mut self,
156        id: Option<&GlobalElementId>,
157        _: Option<&InspectorElementId>,
158        window: &mut Window,
159        cx: &mut App,
160    ) -> (LayoutId, Self::RequestLayoutState) {
161        let style = Style {
162            flex_grow: 1.0,
163            position: Position::Relative,
164            size: gpui::Size {
165                width: relative(1.0).into(),
166                height: relative(1.0).into(),
167            },
168            ..Style::default()
169        };
170
171        let axis = self.axis;
172        let scroll_id = self.id.clone();
173        let content = self.element.take().map(|c| c.into_any_element());
174        let always_show = self.always_show_scrollbars;
175
176        self.with_element_state(
177            id.unwrap(),
178            window,
179            cx,
180            |scrollable, element_state, window, cx| {
181                let scroll_handle =
182                    if let Some(ref external_handle) = scrollable.external_scroll_handle {
183                        external_handle
184                    } else {
185                        &element_state.handle
186                    };
187
188                let mut scrollbar = Scrollbar::new(axis, &element_state.state, scroll_handle);
189                if always_show {
190                    scrollbar = scrollbar.always_visible();
191                }
192
193                let mut element = div()
194                    .relative()
195                    .size_full()
196                    .overflow_hidden()
197                    .child(
198                        div()
199                            .id(scroll_id)
200                            .track_scroll(scroll_handle)
201                            .overflow_scroll()
202                            .relative()
203                            .size_full()
204                            .child(div().children(content)),
205                    )
206                    .child(
207                        div()
208                            .absolute()
209                            .top_0()
210                            .left_0()
211                            .right_0()
212                            .bottom_0()
213                            .child(scrollbar),
214                    )
215                    .into_any_element();
216
217                let element_id = element.request_layout(window, cx);
218                let layout_id = window.request_layout(style, vec![element_id], cx);
219
220                (layout_id, element)
221            },
222        )
223    }
224
225    fn prepaint(
226        &mut self,
227        _: Option<&GlobalElementId>,
228        _: Option<&InspectorElementId>,
229        _: Bounds<Pixels>,
230        element: &mut Self::RequestLayoutState,
231        window: &mut Window,
232        cx: &mut App,
233    ) -> Self::PrepaintState {
234        element.prepaint(window, cx);
235    }
236
237    fn paint(
238        &mut self,
239        _: Option<&GlobalElementId>,
240        _: Option<&InspectorElementId>,
241        _: Bounds<Pixels>,
242        element: &mut Self::RequestLayoutState,
243        _: &mut Self::PrepaintState,
244        window: &mut Window,
245        cx: &mut App,
246    ) {
247        element.paint(window, cx)
248    }
249}
250
251pub fn scrollable_vertical<E>(element: E) -> Scrollable<E>
252where
253    E: Element,
254{
255    Scrollable::vertical(element)
256}
257
258pub fn scrollable_horizontal<E>(element: E) -> Scrollable<E>
259where
260    E: Element,
261{
262    Scrollable::horizontal(element)
263}
264
265pub fn scrollable_both<E>(element: E) -> Scrollable<E>
266where
267    E: Element,
268{
269    Scrollable::both(element)
270}