1mod geometry;
4mod interaction;
5mod parallax;
6mod state;
7mod viewport;
8
9use std::{cell::RefCell, rc::Rc};
10
11use gpui::{
12 AccessibleAction, AnyElement, App, ElementId, Entity, ImageSource, InteractiveElement,
13 IntoElement, ParentElement, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement,
14 Styled, Window, div, prelude::FluentBuilder, px,
15};
16use gpui_base::TestSupportExt;
17use gpui_material_foundation::{animate, color, current_material_theme};
18use gpui_material_theme::{
19 ColorRole, Direction, LogicalEdges, MotionKind, MotionSpec, MotionSpeed,
20};
21
22use geometry::LayoutOptions;
23use interaction::{Interaction, focus_at_position, navigation_index};
24use viewport::Viewport;
25
26pub use parallax::CarouselParallax;
27pub use state::CarouselState;
28
29const WIDTH_TO_HEIGHT_MIN: f32 = 9. / 16.;
30const WIDTH_TO_HEIGHT_MAX: f32 = 16. / 9.;
31
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
34pub enum CarouselVariant {
35 #[default]
37 MultiBrowse,
38 Uncontained,
40 UncontainedMultiAspectRatio,
42 Hero,
44 CenteredHero,
46 FullScreen,
48}
49
50impl CarouselVariant {
51 pub(crate) fn is_vertical(self) -> bool {
52 self == Self::FullScreen
53 }
54
55 pub(crate) fn is_uncontained(self) -> bool {
56 matches!(self, Self::Uncontained | Self::UncontainedMultiAspectRatio)
57 }
58}
59
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
62pub enum CarouselAlignment {
63 #[default]
65 Start,
66 Center,
68}
69
70#[derive(Clone, Copy, Debug, PartialEq)]
72pub struct CarouselFlingContext {
73 pub start: f32,
75 pub position: f32,
77 pub item_count: usize,
79}
80
81#[derive(Clone, Default)]
83pub enum CarouselFling {
84 #[default]
86 Default,
87 Free,
89 Snap,
91 SingleAdvance,
93 Custom(Rc<dyn Fn(CarouselFlingContext) -> Option<usize>>),
95}
96
97impl CarouselFling {
98 pub fn custom(target: impl Fn(CarouselFlingContext) -> Option<usize> + 'static) -> Self {
100 Self::Custom(Rc::new(target))
101 }
102}
103
104fn nonnegative(value: Pixels) -> f32 {
105 nonnegative_f32(f32::from(value))
106}
107
108fn nonnegative_f32(value: f32) -> f32 {
109 if value.is_finite() { value.max(0.) } else { 0. }
110}
111
112type Activate = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
113
114enum Content {
115 Element(AnyElement),
116 Image(ImageSource),
117}
118
119pub struct CarouselItem {
121 id: SharedString,
122 label: SharedString,
123 aspect: f32,
124 disabled: bool,
125 content: Content,
126}
127
128impl CarouselItem {
129 pub fn new(
131 id: impl Into<SharedString>,
132 label: impl Into<SharedString>,
133 content: impl IntoElement,
134 ) -> Self {
135 Self {
136 id: id.into(),
137 label: label.into(),
138 aspect: 1.,
139 disabled: false,
140 content: Content::Element(content.into_any_element()),
141 }
142 }
143
144 pub fn image(
146 id: impl Into<SharedString>,
147 label: impl Into<SharedString>,
148 source: impl Into<ImageSource>,
149 ) -> Self {
150 Self {
151 id: id.into(),
152 label: label.into(),
153 aspect: 1.,
154 disabled: false,
155 content: Content::Image(source.into()),
156 }
157 }
158
159 pub fn aspect_ratio(mut self, width_over_height: f32) -> Self {
162 if width_over_height.is_finite() && width_over_height > 0. {
163 self.aspect = width_over_height.clamp(WIDTH_TO_HEIGHT_MIN, WIDTH_TO_HEIGHT_MAX);
164 }
165 self
166 }
167
168 pub fn disabled(mut self, disabled: bool) -> Self {
170 self.disabled = disabled;
171 self
172 }
173}
174
175#[derive(IntoElement)]
184pub struct Carousel {
185 id: ElementId,
186 label: SharedString,
187 items: Vec<CarouselItem>,
188 variant: CarouselVariant,
189 height: Pixels,
190 preferred_width: Pixels,
191 layout_options: LayoutOptions,
192 snap: Option<bool>,
193 fling: CarouselFling,
194 user_scroll_enabled: bool,
195 state: Option<Entity<CarouselState>>,
196 on_activate: Option<Activate>,
197}
198
199impl Carousel {
200 pub fn new(
205 id: impl Into<ElementId>,
206 label: impl Into<SharedString>,
207 items: impl IntoIterator<Item = CarouselItem>,
208 ) -> Self {
209 Self {
210 id: id.into(),
211 label: label.into(),
212 items: items.into_iter().collect(),
213 variant: CarouselVariant::default(),
214 height: px(220.),
215 preferred_width: px(192.),
216 layout_options: LayoutOptions::default(),
217 snap: None,
218 fling: CarouselFling::Default,
219 user_scroll_enabled: true,
220 state: None,
221 on_activate: None,
222 }
223 }
224
225 pub fn variant(mut self, variant: CarouselVariant) -> Self {
227 self.variant = variant;
228 self
229 }
230
231 pub fn height(mut self, height: Pixels) -> Self {
234 if f32::from(height).is_finite() && height > px(0.) {
235 self.height = height;
236 }
237 self
238 }
239
240 pub fn preferred_item_width(mut self, width: Pixels) -> Self {
242 if f32::from(width).is_finite() && width > px(0.) {
243 self.preferred_width = width;
244 }
245 self
246 }
247
248 pub fn snap_scrolling(mut self, snap: bool) -> Self {
250 self.snap = Some(snap);
251 self
252 }
253
254 pub fn alignment(mut self, alignment: CarouselAlignment) -> Self {
256 self.layout_options.alignment = Some(alignment);
257 self
258 }
259
260 pub fn item_spacing(mut self, gap: Pixels) -> Self {
262 self.layout_options.spacing = Some(nonnegative(gap));
263 self
264 }
265
266 pub fn content_padding(mut self, padding: LogicalEdges) -> Self {
268 self.layout_options.padding = Some(LogicalEdges {
269 start: nonnegative_f32(padding.start),
270 end: nonnegative_f32(padding.end),
271 top: nonnegative_f32(padding.top),
272 bottom: nonnegative_f32(padding.bottom),
273 });
274 self
275 }
276
277 pub fn small_item_widths(mut self, min: Pixels, max: Pixels) -> Self {
279 let (min, max) = (nonnegative(min), nonnegative(max));
280 if min > 0. && max >= min {
281 self.layout_options.small = (min, max);
282 }
283 self
284 }
285
286 pub fn fling_behavior(mut self, fling: CarouselFling) -> Self {
288 self.fling = fling;
289 self
290 }
291
292 pub fn user_scroll_enabled(mut self, enabled: bool) -> Self {
294 self.user_scroll_enabled = enabled;
295 self
296 }
297
298 pub fn state(mut self, state: &Entity<CarouselState>) -> Self {
300 self.state = Some(state.clone());
301 self
302 }
303
304 pub fn on_activate(
306 mut self,
307 callback: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
308 ) -> Self {
309 self.on_activate = Some(Rc::new(callback));
310 self
311 }
312}
313
314impl RenderOnce for Carousel {
315 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
316 let state = self.state.unwrap_or_else(|| {
317 window.use_keyed_state((self.id.clone(), "carousel-state"), cx, |_, _| {
318 CarouselState::new(0)
319 })
320 });
321 let (target, direct, focus) = state.update(cx, |state, cx| {
322 state.sync(&self.items, cx);
323 if !self.user_scroll_enabled {
324 state.cancel_input(cx);
325 }
326 (state.requested, state.direct, state.items.clone())
327 });
328 let theme = current_material_theme(window, cx);
329 let direction = theme.layout.direction;
330 let ring = color(theme.colors.color(ColorRole::Secondary));
331 let hover = color(theme.colors.color(ColorRole::OnSurface));
332 let surface = color(theme.colors.color(ColorRole::SurfaceContainer));
333 let reduced = cx.reduce_motion();
334 let motion = theme
335 .motion
336 .spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
337 let sample = animate(
338 (self.id.clone(), "carousel-position"),
339 target,
340 if direct { MotionSpec::Instant } else { motion },
341 window,
342 cx,
343 );
344 state.update(cx, |state, cx| state.sample(sample, cx));
345 let sample = state.read(cx).sampled;
346 let vertical = self.variant.is_vertical();
347 let shared_layout = Rc::new(RefCell::new(None));
348 let fling = match self.fling {
349 CarouselFling::Default if !self.variant.is_uncontained() || self.snap == Some(true) => {
350 CarouselFling::Snap
351 }
352 CarouselFling::Default => CarouselFling::Free,
353 explicit => explicit,
354 };
355 let wheel = Interaction {
356 layout: shared_layout.clone(),
357 focus: focus.clone(),
358 state: state.clone(),
359 vertical,
360 direction,
361 fling,
362 };
363 let keys = wheel.clone();
364 let previous = wheel.clone();
365 let next = wheel.clone();
366 let (backward, forward) = match (vertical, direction) {
367 (true, _) => (AccessibleAction::ScrollUp, AccessibleAction::ScrollDown),
368 (false, Direction::Ltr) => {
369 (AccessibleAction::ScrollLeft, AccessibleAction::ScrollRight)
370 }
371 (false, Direction::Rtl) => {
372 (AccessibleAction::ScrollRight, AccessibleAction::ScrollLeft)
373 }
374 };
375 let focused = focus.iter().position(|item| item.focus.is_focused(window));
376 let tab_stop = focus_at_position(&focus, target);
377
378 div()
379 .id(self.id.clone())
380 .test_support()
381 .role(Role::Region)
382 .aria_label(self.label)
383 .w_full()
384 .min_w_0()
385 .relative()
386 .overflow_hidden()
387 .when(self.user_scroll_enabled, move |region| {
388 region
389 .on_key_down(move |event, window, cx| {
390 if event.keystroke.modifiers.modified() {
391 return;
392 }
393 let current = keys.state.read(cx).requested;
394 if let Some(index) = navigation_index(
395 &keys.focus,
396 current,
397 &event.keystroke.key,
398 keys.vertical,
399 keys.direction,
400 ) {
401 keys.state
402 .update(cx, |state, cx| state.animate_scroll_to_item(index, cx));
403 keys.focus[index].focus.focus(window, cx);
404 window.refresh();
405 cx.stop_propagation();
406 }
407 })
408 .on_a11y_action(backward, move |_, window, cx| previous.page(-1, window, cx))
409 .on_a11y_action(forward, move |_, window, cx| next.page(1, window, cx))
410 .on_scroll(move |event, window, cx| wheel.on_scroll(event, window, cx))
411 })
412 .child(Viewport {
413 id: self.id,
414 variant: self.variant,
415 height: self.height,
416 preferred_width: self.preferred_width,
417 layout_options: self.layout_options,
418 user_scroll_enabled: self.user_scroll_enabled,
419 items: self.items.into_iter().map(Some).collect(),
420 focus,
421 focused,
422 tab_stop,
423 state,
424 sample,
425 direction,
426 ring,
427 hover,
428 surface,
429 activate: self.on_activate,
430 layout: shared_layout,
431 })
432 }
433}