1use std::time::Duration;
5
6use gpui::{
7 AnyElement, App, AppContext as _, Axis, Context, DragMoveEvent, ElementId, Empty, Entity,
8 EntityId, EventEmitter, FocusHandle, InteractiveElement, IntoElement, KeyBinding, MouseButton,
9 ParentElement, Pixels, Point, Render, RenderOnce, Role, SharedString,
10 StatefulInteractiveElement, StyleRefinement, Styled, Task, Window, div, px,
11};
12
13use crate::{
14 Button, Direction, TestSupportExt as _,
15 actions::{SelectDown, SelectFirst, SelectLast, SelectLeft, SelectRight, SelectUp},
16};
17
18pub(crate) fn init(cx: &mut App) {
19 cx.bind_keys([
20 KeyBinding::new("left", SelectLeft, Some("Carousel && axis == horizontal")),
21 KeyBinding::new("right", SelectRight, Some("Carousel && axis == horizontal")),
22 KeyBinding::new("up", SelectUp, Some("Carousel && axis == vertical")),
23 KeyBinding::new("down", SelectDown, Some("Carousel && axis == vertical")),
24 KeyBinding::new("home", SelectFirst, Some("Carousel")),
25 KeyBinding::new("end", SelectLast, Some("Carousel")),
26 ]);
27}
28
29#[derive(Clone, Debug, Eq, PartialEq)]
30pub enum CarouselEvent {
31 Change(usize),
32}
33
34pub struct CarouselState {
44 labels: Vec<SharedString>,
45 selected: Option<usize>,
46 per_view: usize,
47 looping: bool,
48 axis: Axis,
49 direction: Direction,
50 focus: FocusHandle,
51 slide_focus: Vec<FocusHandle>,
52 drag_origin: Point<Pixels>,
53 drag_committed: bool,
54 hovered: bool,
55 autoplay: Option<Task<()>>,
56}
57
58impl CarouselState {
59 pub fn new<L: Into<SharedString>>(
60 labels: impl IntoIterator<Item = L>,
61 cx: &mut Context<Self>,
62 ) -> Self {
63 let labels: Vec<_> = labels.into_iter().map(Into::into).collect();
64 Self {
65 selected: (!labels.is_empty()).then_some(0),
66 slide_focus: labels.iter().map(|_| cx.focus_handle()).collect(),
67 labels,
68 per_view: 1,
69 looping: false,
70 axis: Axis::Horizontal,
71 direction: Direction::Ltr,
72 focus: cx.focus_handle(),
73 drag_origin: Point::default(),
74 drag_committed: false,
75 hovered: false,
76 autoplay: None,
77 }
78 }
79
80 pub fn looping(mut self, looping: bool) -> Self {
81 self.looping = looping;
82 self
83 }
84 pub fn slides_per_view(mut self, count: usize) -> Self {
86 assert!(count > 0, "A carousel view shows at least one slide");
87 self.per_view = count;
88 self.selected = self.selected.map(|index| index.min(self.last_start()));
89 self
90 }
91 pub fn set_slides_per_view(
94 &mut self,
95 count: usize,
96 window: &mut Window,
97 cx: &mut Context<Self>,
98 ) -> bool {
99 assert!(count > 0, "A carousel view shows at least one slide");
100 if self.per_view == count {
101 return false;
102 }
103 let previous = self.visible_range();
104 self.per_view = count;
105 let Some(selected) = self.selected else {
106 return true;
107 };
108 let start = selected.min(self.last_start());
109 self.release_hidden_focus(previous, start, window, cx);
110 self.selected = Some(start);
111 if start != selected {
112 cx.emit(CarouselEvent::Change(start));
113 }
114 cx.notify();
115 window.refresh();
116 true
117 }
118 pub fn selected_index(&self) -> Option<usize> {
120 self.selected
121 }
122 pub fn visible_range(&self) -> std::ops::Range<usize> {
124 self.selected.map_or(0..0, |start| {
125 start..(start + self.per_view).min(self.labels.len())
126 })
127 }
128 pub fn snap_count(&self) -> usize {
130 if self.labels.is_empty() {
131 0
132 } else {
133 self.last_start() + 1
134 }
135 }
136 pub fn labels(&self) -> &[SharedString] {
137 &self.labels
138 }
139 pub fn focus_handle(&self) -> &FocusHandle {
140 &self.focus
141 }
142 pub fn can_previous(&self) -> bool {
143 self.snap_count() > 1 && (self.looping || self.selected.is_some_and(|index| index > 0))
144 }
145 pub fn can_next(&self) -> bool {
146 self.snap_count() > 1
147 && (self.looping || self.selected.is_some_and(|index| index < self.last_start()))
148 }
149 fn last_start(&self) -> usize {
150 self.labels.len().saturating_sub(self.per_view)
151 }
152 fn release_hidden_focus(
153 &self,
154 previous: std::ops::Range<usize>,
155 start: usize,
156 window: &mut Window,
157 cx: &mut App,
158 ) {
159 let next = start..start + self.per_view;
160 if previous
161 .filter(|index| !next.contains(index))
162 .any(|index| self.slide_focus[index].contains_focused(window, cx))
163 {
164 self.focus.focus(window, cx);
165 }
166 }
167
168 pub fn select(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) -> bool {
172 if index >= self.snap_count() || self.selected == Some(index) {
173 return false;
174 }
175 self.release_hidden_focus(self.visible_range(), index, window, cx);
176 self.selected = Some(index);
177 cx.emit(CarouselEvent::Change(index));
178 cx.notify();
179 window.refresh();
180 true
181 }
182
183 pub fn previous(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
184 self.advance(false, window, cx)
185 }
186 pub fn next(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
187 self.advance(true, window, cx)
188 }
189 fn advance(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
190 let Some(index) = self.selected else {
191 return false;
192 };
193 if if forward {
194 !self.can_next()
195 } else {
196 !self.can_previous()
197 } {
198 return false;
199 }
200 let snaps = self.snap_count();
201 let next = if forward {
202 (index + 1) % snaps
203 } else {
204 (index + snaps - 1) % snaps
205 };
206 self.select(next, window, cx)
207 }
208
209 pub fn set_autoplay(
216 &mut self,
217 interval: Option<Duration>,
218 window: &mut Window,
219 cx: &mut Context<Self>,
220 ) {
221 self.autoplay = interval.map(|interval| {
222 cx.spawn_in(window, async move |state, cx| {
223 loop {
224 cx.background_executor().timer(interval).await;
225 if state
226 .update_in(cx, |state, window, cx| state.autoplay_tick(window, cx))
227 .is_err()
228 {
229 break;
230 }
231 }
232 })
233 });
234 cx.notify();
235 }
236 pub fn is_autoplaying(&self) -> bool {
237 self.autoplay.is_some()
238 }
239 fn autoplay_tick(&mut self, window: &mut Window, cx: &mut Context<Self>) {
240 if self.hovered
241 || !window.is_window_active()
242 || cx.reduce_motion()
243 || self.focus.contains_focused(window, cx)
244 || self.snap_count() < 2
245 {
246 return;
247 }
248 let Some(index) = self.selected else {
249 return;
250 };
251 let next = if index + 1 < self.snap_count() {
252 index + 1
253 } else {
254 0
255 };
256 self.select(next, window, cx);
257 }
258 fn stop_autoplay(&mut self, cx: &mut Context<Self>) {
259 if self.autoplay.take().is_some() {
260 cx.notify();
261 }
262 }
263 fn swipe_at_pointer(
264 &mut self,
265 position: Point<Pixels>,
266 window: &mut Window,
267 cx: &mut Context<Self>,
268 ) {
269 if self.drag_committed {
270 return;
271 }
272 let delta = match self.axis {
273 Axis::Horizontal => position.x - self.drag_origin.x,
274 Axis::Vertical => position.y - self.drag_origin.y,
275 };
276 if delta.abs() < px(40.) {
277 return;
278 }
279 self.drag_committed = true;
280 self.stop_autoplay(cx);
281 let forward = match self.axis {
282 Axis::Horizontal => self.direction.horizontal_forward(delta < px(0.)),
283 Axis::Vertical => delta < px(0.),
284 };
285 self.advance(forward, window, cx);
286 }
287
288 fn key_advance(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
289 if self.focus.is_focused(window) {
290 self.stop_autoplay(cx);
291 self.advance(forward, window, cx);
292 } else {
293 cx.propagate();
294 }
295 }
296 fn key_edge(&mut self, last: bool, window: &mut Window, cx: &mut Context<Self>) {
297 if !self.focus.is_focused(window) {
298 cx.propagate();
299 return;
300 }
301 self.stop_autoplay(cx);
302 if !self.labels.is_empty() {
303 self.select(if last { self.last_start() } else { 0 }, window, cx);
304 }
305 }
306}
307impl EventEmitter<CarouselEvent> for CarouselState {}
308
309#[derive(IntoElement)]
313pub struct Carousel {
314 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
315 state: Entity<CarouselState>,
316 label: SharedString,
317 axis: Axis,
318 direction: Option<Direction>,
319}
320impl Carousel {
321 pub fn new(
322 id: impl Into<ElementId>,
323 state: &Entity<CarouselState>,
324 label: impl Into<SharedString>,
325 ) -> Self {
326 Self {
327 base: div().id(id).test_support(),
328 state: state.clone(),
329 label: label.into(),
330 axis: Axis::Horizontal,
331 direction: None,
332 }
333 }
334 pub fn axis(mut self, axis: Axis) -> Self {
335 self.axis = axis;
336 self
337 }
338 pub fn direction(mut self, direction: Direction) -> Self {
339 self.direction = Some(direction);
340 self
341 }
342}
343impl Styled for Carousel {
344 fn style(&mut self) -> &mut StyleRefinement {
345 self.base.style()
346 }
347}
348impl ParentElement for Carousel {
349 fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
350 self.base.extend(children);
351 }
352}
353impl RenderOnce for Carousel {
354 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
355 let direction = self.direction.unwrap_or_else(|| Direction::current(cx));
356 self.state.update(cx, |state, _| {
357 state.axis = self.axis;
358 state.direction = direction;
359 });
360 let focus = self.state.read(cx).focus.clone();
361 let first = self.state.clone();
362 let last = self.state.clone();
363 let previous = self.state.clone();
364 let hover = self.state.clone();
365 let next = self.state;
366 let base = self
367 .base
368 .role(Role::Region)
369 .aria_label(self.label)
370 .track_focus(&focus)
371 .on_hover(move |hovered, _, cx| {
372 hover.update(cx, |state, _| state.hovered = *hovered);
373 })
374 .on_action(move |_: &SelectFirst, window, cx| {
375 first.update(cx, |state, cx| state.key_edge(false, window, cx));
376 })
377 .on_action(move |_: &SelectLast, window, cx| {
378 last.update(cx, |state, cx| state.key_edge(true, window, cx));
379 });
380 match self.axis {
381 Axis::Horizontal => base
382 .key_context("Carousel axis=horizontal")
383 .on_action(move |_: &SelectLeft, window, cx| {
384 previous.update(cx, |state, cx| {
385 state.key_advance(direction.horizontal_forward(false), window, cx)
386 });
387 })
388 .on_action(move |_: &SelectRight, window, cx| {
389 next.update(cx, |state, cx| {
390 state.key_advance(direction.horizontal_forward(true), window, cx)
391 });
392 }),
393 Axis::Vertical => base
394 .key_context("Carousel axis=vertical")
395 .on_action(move |_: &SelectUp, window, cx| {
396 previous.update(cx, |state, cx| state.key_advance(false, window, cx));
397 })
398 .on_action(move |_: &SelectDown, window, cx| {
399 next.update(cx, |state, cx| state.key_advance(true, window, cx));
400 }),
401 }
402 }
403}
404
405#[derive(Clone)]
406struct DragCarousel(EntityId);
407impl Render for DragCarousel {
408 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
409 Empty
410 }
411}
412
413#[derive(IntoElement)]
420pub struct CarouselSlide {
421 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
422 state: Entity<CarouselState>,
423 index: usize,
424}
425impl CarouselSlide {
426 pub fn new(state: &Entity<CarouselState>, index: usize) -> Self {
427 Self {
428 base: div()
429 .id((
430 ElementId::from(("carousel-slide", state.entity_id())),
431 index.to_string(),
432 ))
433 .test_support(),
434 state: state.clone(),
435 index,
436 }
437 }
438}
439impl Styled for CarouselSlide {
440 fn style(&mut self) -> &mut StyleRefinement {
441 self.base.style()
442 }
443}
444impl ParentElement for CarouselSlide {
445 fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
446 self.base.extend(children);
447 }
448}
449impl RenderOnce for CarouselSlide {
450 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
451 let model = self.state.read(cx);
452 assert!(
453 self.index < model.labels.len(),
454 "CarouselSlide index must identify a slide"
455 );
456 if !model.visible_range().contains(&self.index) {
457 return Empty.into_any_element();
458 }
459 let id = self.state.entity_id();
460 let drag = self.state.clone();
461 self.base
462 .role(Role::Group)
463 .aria_label(model.labels[self.index].clone())
464 .aria_position_in_set(self.index + 1)
465 .aria_size_of_set(model.labels.len())
466 .track_focus(&model.slide_focus[self.index].clone().tab_stop(false))
467 .overflow_hidden()
468 .on_mouse_down(
469 MouseButton::Left,
470 window.listener_for(&self.state, |state, event: &gpui::MouseDownEvent, _, _| {
471 state.drag_origin = event.position;
472 state.drag_committed = false;
473 }),
474 )
475 .on_drag(DragCarousel(id), move |value, _, window, cx| {
476 drag.update(cx, |state, cx| {
479 state.drag_committed = false;
480 state.swipe_at_pointer(window.mouse_position(), window, cx);
481 });
482 cx.stop_propagation();
483 cx.new(|_| value.clone())
484 })
485 .on_drag_move(window.listener_for(
486 &self.state,
487 move |state, event: &DragMoveEvent<DragCarousel>, window, cx| {
488 if event.drag(cx).0 == id {
489 state.swipe_at_pointer(event.event.position, window, cx);
490 }
491 },
492 ))
493 .into_any_element()
494 }
495}
496
497#[derive(IntoElement)]
499pub struct CarouselControl {
500 button: Button,
501 state: Entity<CarouselState>,
502 forward: bool,
503}
504impl CarouselControl {
505 pub fn previous(id: impl Into<ElementId>, state: &Entity<CarouselState>) -> Self {
506 Self {
507 button: Button::new(id).accessibility_label("Previous slide"),
508 state: state.clone(),
509 forward: false,
510 }
511 }
512 pub fn next(id: impl Into<ElementId>, state: &Entity<CarouselState>) -> Self {
513 Self {
514 button: Button::new(id).accessibility_label("Next slide"),
515 state: state.clone(),
516 forward: true,
517 }
518 }
519}
520impl Styled for CarouselControl {
521 fn style(&mut self) -> &mut StyleRefinement {
522 self.button.style()
523 }
524}
525impl ParentElement for CarouselControl {
526 fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
527 self.button.extend(children);
528 }
529}
530impl RenderOnce for CarouselControl {
531 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
532 let enabled = if self.forward {
533 self.state.read(cx).can_next()
534 } else {
535 self.state.read(cx).can_previous()
536 };
537 self.button
538 .disabled(!enabled)
539 .on_click(move |_, window, cx| {
540 self.state.update(cx, |state, cx| {
541 state.stop_autoplay(cx);
542 state.advance(self.forward, window, cx);
543 });
544 })
545 }
546}
547
548#[cfg(test)]
549mod tests {
550 use super::*;
551 use crate::Root;
552 use gpui::{Modifiers, Subscription, TestAppContext, point};
553
554 struct Harness {
555 state: Entity<CarouselState>,
556 button: FocusHandle,
557 axis: Axis,
558 direction: Direction,
559 _subscription: Subscription,
560 }
561 impl Render for Harness {
562 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
563 Carousel::new("carousel", &self.state, "Screenshots")
564 .axis(self.axis)
565 .direction(self.direction)
566 .w(px(300.))
567 .child(
568 CarouselSlide::new(&self.state, 0)
569 .w(px(300.))
570 .h(px(120.))
571 .child("First image"),
572 )
573 .child(
574 CarouselSlide::new(&self.state, 1)
575 .w(px(300.))
576 .h(px(120.))
577 .child(
578 Button::new("slide-action")
579 .track_focus(&self.button)
580 .child("Inspect image"),
581 ),
582 )
583 .child(CarouselControl::previous("previous", &self.state).child("Previous"))
584 .child(CarouselControl::next("next", &self.state).child("Next"))
585 }
586 }
587 #[gpui::test]
588 fn keys_swipe_and_outgoing_slide_keep_focus_reachable(cx: &mut TestAppContext) {
589 cx.update(crate::init);
590 let (root, cx) = cx.add_window_view(|window, cx| {
591 let view = cx.new(|cx| {
592 let state = cx.new(|cx| CarouselState::new(["First", "Second"], cx));
593 let subscription = cx.observe(&state, |_, _, cx| cx.notify());
594 Harness {
595 state,
596 button: cx.focus_handle(),
597 axis: Axis::Horizontal,
598 direction: Direction::Ltr,
599 _subscription: subscription,
600 }
601 });
602 Root::new(view, window, cx)
603 });
604 let view = root
605 .read_with(cx, |root, _| root.view().clone())
606 .downcast::<Harness>()
607 .unwrap();
608 cx.update(|window, cx| {
609 window.activate_window();
610 let focus = view.read(cx).state.read(cx).focus.clone();
611 focus.focus(window, cx);
612 window.draw(cx).clear(cx);
613 });
614 cx.simulate_keystrokes("right");
615 cx.run_until_parked();
616 cx.update(|window, cx| {
617 let state = view.read(cx).state.clone();
618 assert_eq!(state.read(cx).selected_index(), Some(1));
619 assert!(!state.read(cx).can_next());
620 let button = view.read(cx).button.clone();
621 button.focus(window, cx);
622 window.draw(cx).clear(cx);
623 state.update(cx, |state, cx| {
624 assert!(state.previous(window, cx));
625 assert!(state.focus.is_focused(window));
626 });
627 window.draw(cx).clear(cx);
628 });
629 cx.simulate_mouse_down(
631 point(px(180.), px(50.)),
632 MouseButton::Left,
633 Modifiers::default(),
634 );
635 cx.simulate_mouse_move(
636 point(px(130.), px(50.)),
637 Some(MouseButton::Left),
638 Modifiers::default(),
639 );
640 cx.simulate_mouse_up(
641 point(px(130.), px(50.)),
642 MouseButton::Left,
643 Modifiers::default(),
644 );
645 cx.run_until_parked();
646 cx.update(|_, cx| {
647 assert_eq!(view.read(cx).state.read(cx).selected_index(), Some(1));
648 });
649 for (axis, direction, key, end) in [
650 (
651 Axis::Horizontal,
652 Direction::Rtl,
653 "left",
654 point(px(240.), px(90.)),
655 ),
656 (
657 Axis::Vertical,
658 Direction::Rtl,
659 "down",
660 point(px(180.), px(40.)),
661 ),
662 ] {
663 view.update(cx, |view, cx| {
664 view.axis = axis;
665 view.direction = direction;
666 cx.notify();
667 });
668 cx.update(|window, cx| {
669 view.read(cx).state.clone().update(cx, |state, cx| {
670 state.select(0, window, cx);
671 state.focus.focus(window, cx);
672 });
673 window.draw(cx).clear(cx);
674 });
675 cx.simulate_keystrokes(key);
676 cx.update(|window, cx| {
677 view.read(cx).state.clone().update(cx, |state, cx| {
678 assert_eq!(state.selected_index(), Some(1));
679 state.select(0, window, cx);
680 });
681 window.draw(cx).clear(cx);
682 });
683 cx.simulate_mouse_down(
685 point(px(180.), px(90.)),
686 MouseButton::Left,
687 Modifiers::default(),
688 );
689 cx.simulate_mouse_move(end, Some(MouseButton::Left), Modifiers::default());
690 cx.update(|_, cx| {
692 view.read(cx)
693 .state
694 .clone()
695 .update(cx, |state, _| state.looping = true)
696 });
697 cx.simulate_mouse_move(end, Some(MouseButton::Left), Modifiers::default());
698 cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
699 cx.update(|_, cx| {
700 view.read(cx).state.clone().update(cx, |state, _| {
701 assert_eq!(state.selected_index(), Some(1));
702 state.looping = false;
703 })
704 });
705 }
706 cx.update(|window, cx| {
707 let state = view.read(cx).state.clone();
708 assert_eq!(state.read(cx).selected_index(), Some(1));
709 state.update(cx, |state, cx| {
710 assert!(!state.next(window, cx));
711 state.looping = true;
712 assert!(state.next(window, cx));
713 assert_eq!(state.selected, Some(0));
714 });
715 });
716 }
717
718 struct MultiHarness {
719 state: Entity<CarouselState>,
720 actions: Vec<FocusHandle>,
721 _subscription: Subscription,
722 }
723 impl Render for MultiHarness {
724 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
725 Carousel::new("carousel", &self.state, "Albums")
726 .flex()
727 .w(px(300.))
728 .children(self.actions.iter().enumerate().map(|(index, action)| {
729 CarouselSlide::new(&self.state, index)
730 .w(px(100.))
731 .h(px(80.))
732 .child(
733 Button::new(("open", index))
734 .track_focus(action)
735 .child("Open"),
736 )
737 }))
738 }
739 }
740
741 #[gpui::test]
742 fn several_slides_per_view_snap_by_one_and_release_hidden_focus(cx: &mut TestAppContext) {
743 cx.update(crate::init);
744 let (root, cx) = cx.add_window_view(|window, cx| {
745 let view = cx.new(|cx| {
746 let state = cx
747 .new(|cx| CarouselState::new(["A", "B", "C", "D", "E"], cx).slides_per_view(3));
748 let subscription = cx.observe(&state, |_, _, cx| cx.notify());
749 MultiHarness {
750 state,
751 actions: (0..5).map(|_| cx.focus_handle()).collect(),
752 _subscription: subscription,
753 }
754 });
755 Root::new(view, window, cx)
756 });
757 let view = root
758 .read_with(cx, |root, _| root.view().clone())
759 .downcast::<MultiHarness>()
760 .unwrap();
761 let state = view.read_with(cx, |view, _| view.state.clone());
762 let mounted = |cx: &mut gpui::VisualTestContext| {
763 cx.update(|window, _| {
764 let mut slides: Vec<_> = crate::test_support::snapshots(window)
765 .into_iter()
766 .filter(|node| node.role() == Some(Role::Group))
767 .map(|node| (node.bounds().left(), node.label().unwrap().to_owned()))
768 .collect();
769 slides.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
770 slides
771 .into_iter()
772 .map(|(_, label)| label)
773 .collect::<Vec<_>>()
774 })
775 };
776 cx.update(|window, cx| {
777 window.activate_window();
778 state.read(cx).focus.clone().focus(window, cx);
779 window.draw(cx).clear(cx);
780 });
781 assert_eq!(mounted(cx), ["A", "B", "C"]);
782 cx.update(|_, cx| {
783 let state = state.read(cx);
784 assert_eq!(state.snap_count(), 3);
785 assert!(!state.can_previous());
786 });
787 cx.simulate_keystrokes("end");
788 cx.run_until_parked();
789 assert_eq!(mounted(cx), ["C", "D", "E"], "the last view stays full");
790 cx.update(|window, cx| {
791 assert!(!state.read(cx).can_next());
792 let action = view.read(cx).actions[3].clone();
794 action.focus(window, cx);
795 state.update(cx, |state, cx| assert!(state.previous(window, cx)));
796 assert!(action.is_focused(window));
797 assert_eq!(state.read(cx).visible_range(), 1..4);
798 state.update(cx, |state, cx| assert!(state.previous(window, cx)));
800 assert!(state.read(cx).focus.is_focused(window));
801 state.update(cx, |state, cx| {
802 state.looping = true;
803 assert!(
804 state.previous(window, cx),
805 "looping wraps to the last full view"
806 );
807 assert_eq!(state.selected_index(), Some(2));
808 assert!(state.set_slides_per_view(4, window, cx));
809 assert_eq!(
810 state.visible_range(),
811 1..5,
812 "a larger view keeps the last one full"
813 );
814 });
815 window.draw(cx).clear(cx);
816 });
817 assert_eq!(mounted(cx), ["B", "C", "D", "E"]);
818 }
819
820 #[gpui::test]
821 fn autoplay_wraps_pauses_for_hover_focus_and_motion_and_stops_on_navigation(
822 cx: &mut TestAppContext,
823 ) {
824 cx.update(crate::init);
825 let (root, cx) = cx.add_window_view(|window, cx| {
826 let view = cx.new(|cx| {
827 let state = cx
828 .new(|cx| CarouselState::new(["A", "B", "C", "D", "E"], cx).slides_per_view(3));
829 let subscription = cx.observe(&state, |_, _, cx| cx.notify());
830 MultiHarness {
831 state,
832 actions: (0..5).map(|_| cx.focus_handle()).collect(),
833 _subscription: subscription,
834 }
835 });
836 Root::new(view, window, cx)
837 });
838 let state = root
839 .read_with(cx, |root, _| root.view().clone())
840 .downcast::<MultiHarness>()
841 .unwrap()
842 .read_with(cx, |view, _| view.state.clone());
843 cx.update(|window, cx| {
844 window.activate_window();
845 window.draw(cx).clear(cx);
846 state.update(cx, |state, cx| {
847 state.set_autoplay(Some(Duration::from_secs(1)), window, cx)
848 });
849 });
850 let tick = |cx: &mut gpui::VisualTestContext| {
851 cx.executor().advance_clock(Duration::from_secs(1));
852 cx.run_until_parked();
853 cx.update(|window, cx| {
854 window.draw(cx).clear(cx);
855 state.read(cx).selected_index()
856 })
857 };
858 cx.update(|_, cx| assert!(state.read(cx).hovered));
861 cx.update(|_, cx| state.update(cx, |state, _| state.hovered = false));
862 assert_eq!(tick(cx), Some(1));
863 assert_eq!(tick(cx), Some(2));
864 assert_eq!(tick(cx), Some(0), "the last full view wraps to the first");
865 cx.update(|_, cx| state.update(cx, |state, _| state.hovered = true));
866 assert_eq!(tick(cx), Some(0), "hovering pauses rotation");
867 cx.update(|_, cx| state.update(cx, |state, _| state.hovered = false));
868 assert_eq!(tick(cx), Some(1));
869 cx.update(|_, cx| cx.set_reduce_motion(true));
870 assert_eq!(tick(cx), Some(1), "reduced motion pauses rotation");
871 cx.update(|_, cx| cx.set_reduce_motion(false));
872 cx.update(|window, cx| state.read(cx).focus.clone().focus(window, cx));
873 assert_eq!(tick(cx), Some(1), "focus inside pauses rotation");
874 cx.simulate_keystrokes("right");
875 cx.update(|_, cx| {
876 let state = state.read(cx);
877 assert_eq!(state.selected_index(), Some(2));
878 assert!(
879 !state.is_autoplaying(),
880 "keyboard navigation stops rotation"
881 );
882 });
883 cx.update(|window, cx| window.blur(cx));
884 assert_eq!(tick(cx), Some(2));
885 }
886}