1use std::collections::BTreeSet;
56
57use crate::{
58 ActiveTheme as _, AnyElement, App, Bounds, Context, ElementExt as _, Entity, EventEmitter,
59 FocusHandle, Focusable, Hsla, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton,
60 MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point, Render,
61 RenderOnce, ScrollHandle, Scrollbar, Size, StatefulInteractiveElement as _, Styled as _,
62 Window, div, px, size,
63};
64
65pub const DEFAULT_CELL_WIDTH: Pixels = px(160.0);
67pub const DEFAULT_GAP: Pixels = px(12.0);
69pub const MIN_ZOOM: f32 = 0.4;
71pub const MAX_ZOOM: f32 = 2.5;
73pub const DEFAULT_ASPECT_RATIO: f32 = 16.0 / 9.0;
75pub const AUTOSCROLL_EDGE: Pixels = px(48.0);
77pub const AUTOSCROLL_MAX_SPEED: Pixels = px(18.0);
79
80pub fn clamp_zoom(zoom: f32) -> f32 {
82 if zoom.is_finite() {
83 zoom.clamp(MIN_ZOOM, MAX_ZOOM)
84 } else {
85 1.0
86 }
87}
88
89pub fn normalize_aspect_ratio(aspect_ratio: f32) -> f32 {
91 if aspect_ratio.is_finite() && aspect_ratio > 0.0 {
92 aspect_ratio
93 } else {
94 DEFAULT_ASPECT_RATIO
95 }
96}
97
98pub fn cell_size(base_width: Pixels, zoom: f32, aspect_ratio: f32) -> Size<Pixels> {
100 let width = base_width * clamp_zoom(zoom);
101 size(width, width * (1.0 / normalize_aspect_ratio(aspect_ratio)))
102}
103
104pub fn grid_columns(available_width: Pixels, cell_width: Pixels, gap: Pixels) -> usize {
108 let step = (cell_width + gap).as_f32();
109 if step <= 0.0 {
110 return 1;
111 }
112 let columns = ((available_width.as_f32() + gap.as_f32()) / step).floor();
113 if columns.is_finite() && columns >= 1.0 {
114 columns as usize
115 } else {
116 1
117 }
118}
119
120pub fn drop_slot(cells: &[Bounds<Pixels>], pointer: Point<Pixels>) -> usize {
125 for (index, bounds) in cells.iter().enumerate() {
126 if bounds.contains(&pointer) {
127 let center_x = bounds.origin.x + bounds.size.width * 0.5;
128 return if pointer.x > center_x {
129 index + 1
130 } else {
131 index
132 };
133 }
134 }
135 cells.len()
136}
137
138pub fn move_dest(from: usize, slot: usize) -> Option<usize> {
142 if slot == from || slot == from + 1 {
143 None
144 } else if slot > from {
145 Some(slot - 1)
146 } else {
147 Some(slot)
148 }
149}
150
151pub fn autoscroll_velocity(
157 pointer_y: Pixels,
158 viewport: Bounds<Pixels>,
159 edge: Pixels,
160 max_speed: Pixels,
161) -> Pixels {
162 let top = viewport.origin.y.as_f32();
163 let bottom = top + viewport.size.height.as_f32();
164 let edge = edge.as_f32().max(1.0);
165 let max_speed = max_speed.as_f32();
166 let y = pointer_y.as_f32();
167
168 if y < top + edge {
169 let intensity = ((top + edge - y) / edge).clamp(0.0, 1.0);
170 px(-max_speed * intensity)
171 } else if y > bottom - edge {
172 let intensity = ((y - (bottom - edge)) / edge).clamp(0.0, 1.0);
173 px(max_speed * intensity)
174 } else {
175 px(0.0)
176 }
177}
178
179pub fn move_group_dest(selected: &[usize], slot: usize) -> Option<usize> {
185 let first = *selected.first()?;
186 let last = *selected.last()?;
187 if slot == first || (slot > first && slot <= last + 1) {
188 return None;
189 }
190
191 let removed_before = selected.iter().filter(|&&index| index < slot).count();
193 Some(slot - removed_before)
194}
195
196#[derive(Clone, Debug, PartialEq, Eq)]
198pub enum SorterEvent {
199 SelectionChanged(Vec<usize>),
201 Reorder {
203 from: usize,
205 to: usize,
207 },
208 ReorderMany {
212 from: Vec<usize>,
214 to: usize,
216 },
217 Activate(usize),
219 Delete(Vec<usize>),
221}
222
223pub trait SorterDelegate: Sized + 'static {
225 fn count(&self, cx: &App) -> usize;
227
228 fn aspect_ratio(&self, _cx: &App) -> f32 {
230 DEFAULT_ASPECT_RATIO
231 }
232
233 fn render_item(
237 &mut self,
238 index: usize,
239 _selected: bool,
240 _window: &mut Window,
241 _cx: &mut Context<SorterState<Self>>,
242 ) -> impl IntoElement {
243 div().size_full().child((index + 1).to_string())
244 }
245}
246
247pub struct SorterState<D: SorterDelegate> {
249 delegate: D,
251 selected: BTreeSet<usize>,
253 anchor: Option<usize>,
255 zoom: f32,
257 show_index: bool,
259 dragging: Option<usize>,
261 hover_slot: Option<usize>,
263 drag_position: Option<Point<Pixels>>,
265 cell_bounds: Vec<Bounds<Pixels>>,
267 bounds: Bounds<Pixels>,
269 columns: usize,
271 base_width: Pixels,
273 gap: Pixels,
275 scroll: ScrollHandle,
277 focus_handle: FocusHandle,
279}
280
281impl<D: SorterDelegate> SorterState<D> {
282 pub fn new(delegate: D, cx: &mut Context<Self>) -> Self {
284 Self {
285 delegate,
286 selected: BTreeSet::new(),
287 anchor: None,
288 zoom: 1.0,
289 show_index: true,
290 dragging: None,
291 hover_slot: None,
292 drag_position: None,
293 cell_bounds: Vec::new(),
294 bounds: Bounds::default(),
295 columns: 1,
296 base_width: DEFAULT_CELL_WIDTH,
297 gap: DEFAULT_GAP,
298 scroll: ScrollHandle::new(),
299 focus_handle: cx.focus_handle(),
300 }
301 }
302
303 pub fn delegate(&self) -> &D {
305 &self.delegate
306 }
307
308 pub fn delegate_mut(&mut self) -> &mut D {
310 &mut self.delegate
311 }
312
313 pub fn count(&self, cx: &App) -> usize {
315 self.delegate.count(cx)
316 }
317
318 pub fn selected(&self) -> &BTreeSet<usize> {
320 &self.selected
321 }
322
323 pub fn primary(&self) -> Option<usize> {
325 self.selected.iter().next().copied()
326 }
327
328 pub fn is_selected(&self, index: usize) -> bool {
330 self.selected.contains(&index)
331 }
332
333 pub fn selection_len(&self) -> usize {
335 self.selected.len()
336 }
337
338 pub fn zoom(&self) -> f32 {
340 self.zoom
341 }
342
343 pub fn set_zoom(&mut self, zoom: f32, cx: &mut Context<Self>) {
345 let zoom = clamp_zoom(zoom);
346 if (self.zoom - zoom).abs() > f32::EPSILON {
347 self.zoom = zoom;
348 cx.notify();
349 }
350 }
351
352 pub fn zoom_by(&mut self, delta: f32, cx: &mut Context<Self>) {
354 self.set_zoom(self.zoom + delta, cx);
355 }
356
357 pub fn show_index(&self) -> bool {
359 self.show_index
360 }
361
362 pub fn set_show_index(&mut self, show: bool, cx: &mut Context<Self>) {
364 if self.show_index != show {
365 self.show_index = show;
366 cx.notify();
367 }
368 }
369
370 pub fn base_width(&self) -> Pixels {
372 self.base_width
373 }
374
375 pub fn set_base_width(&mut self, width: Pixels, cx: &mut Context<Self>) {
377 if self.base_width != width {
378 self.base_width = width;
379 cx.notify();
380 }
381 }
382
383 pub fn gap(&self) -> Pixels {
385 self.gap
386 }
387
388 pub fn set_gap(&mut self, gap: Pixels, cx: &mut Context<Self>) {
390 if self.gap != gap {
391 self.gap = gap;
392 cx.notify();
393 }
394 }
395
396 pub fn columns(&self) -> usize {
398 self.columns
399 }
400
401 pub fn is_dragging(&self) -> bool {
403 self.dragging.is_some()
404 }
405
406 pub fn focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
408 self.focus_handle.focus(window, cx);
409 }
410
411 pub fn select(&mut self, index: usize, cx: &mut Context<Self>) {
413 if index >= self.delegate.count(cx) {
414 return;
415 }
416 self.anchor = Some(index);
417 if self.selected.len() == 1 && self.selected.contains(&index) {
418 return;
419 }
420 self.selected.clear();
421 self.selected.insert(index);
422 self.emit_selection(cx);
423 }
424
425 pub fn toggle(&mut self, index: usize, cx: &mut Context<Self>) {
427 if index >= self.delegate.count(cx) {
428 return;
429 }
430 if !self.selected.remove(&index) {
431 self.selected.insert(index);
432 }
433 self.anchor = Some(index);
434 self.emit_selection(cx);
435 }
436
437 pub fn select_range(&mut self, anchor: usize, cursor: usize, cx: &mut Context<Self>) {
439 let count = self.delegate.count(cx);
440 if count == 0 {
441 return;
442 }
443 let last = count - 1;
444 let (start, end) = (anchor.min(cursor).min(last), anchor.max(cursor).min(last));
445 let next: BTreeSet<usize> = (start..=end).collect();
446 self.anchor = Some(anchor.min(last));
447 if next != self.selected {
448 self.selected = next;
449 self.emit_selection(cx);
450 }
451 }
452
453 pub fn select_all(&mut self, cx: &mut Context<Self>) {
455 let count = self.delegate.count(cx);
456 let next: BTreeSet<usize> = (0..count).collect();
457 if next != self.selected {
458 self.selected = next;
459 self.emit_selection(cx);
460 }
461 }
462
463 pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
465 if self.selected.is_empty() {
466 return;
467 }
468 self.selected.clear();
469 self.emit_selection(cx);
470 }
471
472 pub fn begin_drag(&mut self, index: usize, cx: &mut Context<Self>) {
474 self.dragging = Some(index);
475 self.hover_slot = Some(index);
476 cx.notify();
477 }
478
479 pub fn set_drop_slot(&mut self, slot: usize, cx: &mut Context<Self>) {
481 if self.dragging.is_none() {
482 return;
483 }
484 if self.hover_slot != Some(slot) {
485 self.hover_slot = Some(slot);
486 cx.notify();
487 }
488 }
489
490 pub fn update_drag(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
492 if self.dragging.is_none() {
493 return;
494 }
495 self.drag_position = Some(position);
496 let slot = drop_slot(&self.cell_bounds, position);
497 self.set_drop_slot(slot, cx);
498 }
499
500 pub fn drag_autoscroll(&mut self, pointer: Point<Pixels>, cx: &mut Context<Self>) -> Pixels {
505 if self.dragging.is_none() {
506 return px(0.0);
507 }
508
509 let delta = autoscroll_velocity(
510 pointer.y,
511 self.bounds,
512 AUTOSCROLL_EDGE,
513 AUTOSCROLL_MAX_SPEED,
514 );
515 if delta == px(0.0) {
516 return delta;
517 }
518
519 let mut offset = self.scroll.offset();
520 offset.y = offset.y + delta;
521 self.scroll.set_offset(offset);
522 self.update_drag(pointer, cx);
523 cx.notify();
524 delta
525 }
526
527 pub fn finish_drag(&mut self, cx: &mut Context<Self>) {
530 let Some(from) = self.dragging.take() else {
531 return;
532 };
533 self.drag_position = None;
534 let slot = self.hover_slot.take().unwrap_or(from);
535
536 if self.selected.len() > 1 && self.selected.contains(&from) {
537 let indices: Vec<usize> = self.selected.iter().copied().collect();
538 if let Some(to) = move_group_dest(&indices, slot) {
539 cx.emit(SorterEvent::ReorderMany { from: indices, to });
540 }
541 } else if let Some(to) = move_dest(from, slot) {
542 cx.emit(SorterEvent::Reorder { from, to });
543 }
544 cx.notify();
545 }
546
547 pub fn cancel_drag(&mut self, cx: &mut Context<Self>) {
549 self.drag_position = None;
550 if self.dragging.take().is_some() || self.hover_slot.take().is_some() {
551 cx.notify();
552 }
553 }
554
555 pub fn scroll_to_item(&mut self, index: usize, cx: &mut Context<Self>) {
557 let Some(item) = self.cell_bounds.get(index).copied() else {
558 return;
559 };
560 let viewport_height = self.bounds.size.height.as_f32();
561 if viewport_height <= 0.0 {
562 return;
563 }
564 let rel_top = item.origin.y.as_f32() - self.bounds.origin.y.as_f32();
565 let rel_bottom = rel_top + item.size.height.as_f32();
566 let mut offset = self.scroll.offset();
567 if rel_top < 0.0 {
568 offset.y = offset.y + px(rel_top);
569 } else if rel_bottom > viewport_height {
570 offset.y = offset.y - px(rel_bottom - viewport_height);
571 }
572 self.scroll.set_offset(offset);
573 cx.notify();
574 }
575
576 fn emit_selection(&mut self, cx: &mut Context<Self>) {
578 let indices: Vec<usize> = self.selected.iter().copied().collect();
579 cx.emit(SorterEvent::SelectionChanged(indices));
580 cx.notify();
581 }
582
583 fn on_item_mouse_down(
585 &mut self,
586 event: &MouseDownEvent,
587 index: usize,
588 window: &mut Window,
589 cx: &mut Context<Self>,
590 ) {
591 self.focus(window, cx);
592 let command = event.modifiers.control || event.modifiers.platform;
593
594 if event.click_count >= 2 {
595 self.select(index, cx);
596 cx.emit(SorterEvent::Activate(index));
597 return;
598 }
599 if event.modifiers.shift {
600 let anchor = self.anchor.unwrap_or(index);
601 self.select_range(anchor, index, cx);
602 } else if command {
603 self.toggle(index, cx);
604 } else {
605 self.select(index, cx);
606 }
607 self.begin_drag(index, cx);
608 }
609
610 fn on_pointer_move(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
612 self.update_drag(position, cx);
613 }
614
615 fn on_pointer_up(&mut self, cx: &mut Context<Self>) {
617 self.finish_drag(cx);
618 }
619
620 fn on_key_down(&mut self, event: &KeyDownEvent, cx: &mut Context<Self>) {
622 let count = self.delegate.count(cx);
623 if count == 0 {
624 return;
625 }
626 let key = event.keystroke.key.to_ascii_lowercase();
627 let modifiers = event.keystroke.modifiers;
628 let extend = modifiers.shift;
629 let command = modifiers.control || modifiers.platform;
630 let columns = self.columns.max(1) as i64;
631 let current = self.primary().unwrap_or(0);
632
633 match key.as_str() {
634 "left" => self.move_selection(current, -1, extend, count, cx),
635 "right" => self.move_selection(current, 1, extend, count, cx),
636 "up" => self.move_selection(current, -columns, extend, count, cx),
637 "down" => self.move_selection(current, columns, extend, count, cx),
638 "home" => self.move_to(0, extend, cx),
639 "end" => self.move_to(count - 1, extend, cx),
640 "a" if command => self.select_all(cx),
641 "enter" | "space" => {
642 if self.selected.is_empty() {
643 self.select(current, cx);
644 }
645 cx.emit(SorterEvent::Activate(current));
646 }
647 "delete" | "backspace" => {
648 if !self.selected.is_empty() {
649 let indices: Vec<usize> = self.selected.iter().copied().collect();
650 cx.emit(SorterEvent::Delete(indices));
651 }
652 }
653 _ => return,
654 }
655 cx.stop_propagation();
656 }
657
658 fn move_selection(
660 &mut self,
661 current: usize,
662 delta: i64,
663 extend: bool,
664 count: usize,
665 cx: &mut Context<Self>,
666 ) {
667 let next = (current as i64 + delta).clamp(0, count as i64 - 1) as usize;
668 self.move_to(next, extend, cx);
669 }
670
671 fn move_to(&mut self, index: usize, extend: bool, cx: &mut Context<Self>) {
673 if extend {
674 let anchor = self.anchor.unwrap_or(index);
675 self.select_range(anchor, index, cx);
676 } else {
677 self.select(index, cx);
678 }
679 self.scroll_to_item(index, cx);
680 }
681
682 fn render_index_badge(&self, index: usize, bg: Hsla, fg: Hsla) -> AnyElement {
684 div()
685 .absolute()
686 .top_1()
687 .left_1()
688 .px_1()
689 .rounded_sm()
690 .bg(bg)
691 .text_color(fg)
692 .text_xs()
693 .child((index + 1).to_string())
694 .into_any_element()
695 }
696}
697
698impl<D: SorterDelegate> EventEmitter<SorterEvent> for SorterState<D> {}
699
700impl<D: SorterDelegate> Focusable for SorterState<D> {
701 fn focus_handle(&self, _cx: &App) -> FocusHandle {
702 self.focus_handle.clone()
703 }
704}
705
706impl<D: SorterDelegate> Render for SorterState<D> {
707 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
708 let count = self.delegate.count(cx);
710 self.selected.retain(|index| *index < count);
711 if self.anchor.is_some_and(|anchor| anchor >= count) {
712 self.anchor = None;
713 }
714 if self.dragging.is_some_and(|index| index >= count) {
715 self.dragging = None;
716 self.hover_slot = None;
717 }
718 self.cell_bounds.truncate(count);
719
720 let cell = cell_size(self.base_width, self.zoom, self.delegate.aspect_ratio(cx));
721 let gap = self.gap;
722 let padding = gap * 2.0;
723 self.columns = grid_columns(
724 (self.bounds.size.width - padding).max(px(0.0)),
725 cell.width,
726 gap,
727 );
728
729 let theme = cx.theme();
731 let border = theme.border;
732 let selected_border = theme.primary;
733 let index_bg = theme.muted;
734 let index_fg = theme.muted_foreground;
735
736 let selected = self.selected.clone();
737 let dragging = self.dragging;
738 let show_index = self.show_index;
739
740 let mut cells: Vec<AnyElement> = Vec::with_capacity(count);
741 for index in 0..count {
742 let is_selected = selected.contains(&index);
743 let content = self
744 .delegate
745 .render_item(index, is_selected, window, cx)
746 .into_any_element();
747
748 let mut item = div()
749 .relative()
750 .overflow_hidden()
751 .rounded_md()
752 .border_2()
753 .border_color(if is_selected { selected_border } else { border })
754 .w(cell.width)
755 .h(cell.height)
756 .on_prepaint({
757 let state = cx.entity();
758 move |bounds, _window, cx| {
759 state.update(cx, |state, _| {
760 if state.cell_bounds.len() <= index {
761 state.cell_bounds.resize(index + 1, Bounds::default());
762 }
763 state.cell_bounds[index] = bounds;
764 });
765 }
766 })
767 .id(("sorter-item", index))
768 .on_mouse_down(
769 MouseButton::Left,
770 cx.listener(move |state, event, window, cx| {
771 state.on_item_mouse_down(event, index, window, cx);
772 }),
773 )
774 .on_mouse_move(
775 cx.listener(move |state, event: &MouseMoveEvent, _window, cx| {
776 state.on_pointer_move(event.position, cx);
777 }),
778 );
779
780 if dragging == Some(index) {
781 item = item.opacity(0.4);
782 }
783 if show_index {
784 item = item.child(self.render_index_badge(index, index_bg, index_fg));
785 }
786 cells.push(item.child(content).into_any_element());
787 }
788
789 let ghost = match (dragging, self.drag_position) {
791 (Some(index), Some(position)) => {
792 let content = self
793 .delegate
794 .render_item(index, false, window, cx)
795 .into_any_element();
796 Some(
797 div()
798 .absolute()
799 .left(position.x - self.bounds.origin.x - cell.width / 2.0)
800 .top(position.y - self.bounds.origin.y - cell.height / 2.0)
801 .w(cell.width)
802 .h(cell.height)
803 .rounded_md()
804 .border_2()
805 .border_color(selected_border)
806 .opacity(0.85)
807 .overflow_hidden()
808 .child(content)
809 .into_any_element(),
810 )
811 }
812 _ => None,
813 };
814
815 let insertion = self.hover_slot.and_then(|slot| {
817 let (x, y, height) = if slot < self.cell_bounds.len() {
818 let bounds = self.cell_bounds[slot];
819 (bounds.origin.x, bounds.origin.y, bounds.size.height)
820 } else {
821 let bounds = *self.cell_bounds.last()?;
822 (
823 bounds.origin.x + bounds.size.width,
824 bounds.origin.y,
825 bounds.size.height,
826 )
827 };
828 Some((x - self.bounds.origin.x, y - self.bounds.origin.y, height))
829 });
830
831 let scroll = self.scroll.clone();
832 div()
833 .id(("sorter-body", cx.entity().entity_id()))
834 .size_full()
835 .relative()
836 .p(padding)
837 .overflow_y_scroll()
838 .track_scroll(&self.scroll)
839 .on_prepaint({
840 let state = cx.entity();
841 move |bounds, _window, cx| {
842 state.update(cx, |state, _| state.bounds = bounds);
843 }
844 })
845 .on_mouse_move(cx.listener(|state, event: &MouseMoveEvent, _window, cx| {
846 state.on_pointer_move(event.position, cx);
847 }))
848 .child(
849 div()
850 .flex()
851 .flex_wrap()
852 .gap(gap)
853 .content_start()
854 .children(cells),
855 )
856 .children(ghost)
857 .children(insertion.map(|(x, y, height)| {
858 div()
859 .absolute()
860 .left(x)
861 .top(y)
862 .w(px(3.0))
863 .h(height)
864 .rounded_full()
865 .bg(selected_border)
866 .into_any_element()
867 }))
868 .child(
869 div()
870 .absolute()
871 .top_0()
872 .right_0()
873 .bottom_0()
874 .w(Scrollbar::width())
875 .child(Scrollbar::vertical(&scroll)),
876 )
877 }
878}
879
880#[derive(IntoElement)]
882pub struct Sorter<D: SorterDelegate> {
883 state: Entity<SorterState<D>>,
884}
885
886impl<D: SorterDelegate> Sorter<D> {
887 pub fn new(state: &Entity<SorterState<D>>) -> Self {
889 Self {
890 state: state.clone(),
891 }
892 }
893}
894
895impl<D: SorterDelegate> RenderOnce for Sorter<D> {
896 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
897 let focus_handle = self.state.read(cx).focus_handle(cx);
898 let entity_id = self.state.entity_id();
899
900 div()
901 .id(("sorter", entity_id))
902 .key_context("Sorter")
903 .track_focus(&focus_handle)
904 .size_full()
905 .on_key_down(window.listener_for(
906 &self.state,
907 |state, event: &KeyDownEvent, _window, cx| {
908 state.on_key_down(event, cx);
909 },
910 ))
911 .capture_any_mouse_up(window.listener_for(
912 &self.state,
913 |state, _event: &MouseUpEvent, _window, cx| {
914 state.on_pointer_up(cx);
915 },
916 ))
917 .child(self.state)
918 }
919}
920
921#[cfg(test)]
922mod tests {
923 use super::{
925 DEFAULT_ASPECT_RATIO, MAX_ZOOM, MIN_ZOOM, Sorter, SorterDelegate, SorterEvent, SorterState,
926 autoscroll_velocity, cell_size, clamp_zoom, drop_slot, grid_columns, move_dest,
927 move_group_dest, normalize_aspect_ratio,
928 };
929 use crate::{
930 App, AppContext as _, Bounds, Context, Entity, IntoElement, ParentElement as _, Render,
931 SharedString, Styled as _, Window, div, point, px, size,
932 };
933 use std::cell::RefCell;
934 use std::rc::Rc;
935
936 struct TestSorter;
938
939 impl SorterDelegate for TestSorter {
940 fn count(&self, _cx: &App) -> usize {
941 5
942 }
943
944 fn render_item(
945 &mut self,
946 index: usize,
947 _selected: bool,
948 _window: &mut Window,
949 _cx: &mut Context<SorterState<Self>>,
950 ) -> impl IntoElement {
951 div()
952 .size_full()
953 .child(SharedString::from(index.to_string()))
954 }
955 }
956
957 struct Probe {
959 state: Entity<SorterState<TestSorter>>,
960 }
961
962 impl Render for Probe {
963 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
964 div().size_full().child(Sorter::new(&self.state))
965 }
966 }
967
968 fn setup(
970 cx: &mut crate::TestAppContext,
971 ) -> (
972 Entity<SorterState<TestSorter>>,
973 Rc<RefCell<Vec<SorterEvent>>>,
974 &mut crate::VisualTestContext,
975 ) {
976 let events: Rc<RefCell<Vec<SorterEvent>>> = Rc::new(RefCell::new(Vec::new()));
977 let sink = events.clone();
978 cx.update(crate::theme::init);
979 let (probe, cx) = cx.add_window_view(move |window, cx| {
980 let state = cx.new(|cx| SorterState::new(TestSorter, cx));
981 cx.subscribe_in(
982 &state,
983 window,
984 move |_this, _state, event: &SorterEvent, _window, _cx| {
985 sink.borrow_mut().push(event.clone());
986 },
987 )
988 .detach();
989 Probe { state }
990 });
991 let state = probe.read_with(&*cx, |probe, _| probe.state.clone());
992 (state, events, cx)
993 }
994
995 #[test]
997 fn zoom_and_aspect_are_clamped() {
998 assert_eq!(clamp_zoom(1.0), 1.0);
999 assert_eq!(clamp_zoom(0.1), MIN_ZOOM);
1000 assert_eq!(clamp_zoom(99.0), MAX_ZOOM);
1001 assert_eq!(clamp_zoom(f32::NAN), 1.0);
1002
1003 assert_eq!(normalize_aspect_ratio(2.0), 2.0);
1004 assert_eq!(normalize_aspect_ratio(0.0), DEFAULT_ASPECT_RATIO);
1005 assert_eq!(normalize_aspect_ratio(f32::INFINITY), DEFAULT_ASPECT_RATIO);
1006 }
1007
1008 #[test]
1010 fn cell_size_scales_and_follows_ratio() {
1011 let base = cell_size(px(160.0), 1.0, 2.0);
1012 assert_eq!(base.width, px(160.0));
1013 assert_eq!(base.height, px(80.0));
1014
1015 let doubled = cell_size(px(160.0), 2.0, 2.0);
1016 assert_eq!(doubled.width, px(320.0));
1017 assert_eq!(doubled.height, px(160.0));
1018
1019 assert_eq!(cell_size(px(100.0), 10.0, 1.0).width, px(100.0) * MAX_ZOOM);
1021 }
1022
1023 #[test]
1025 fn columns_wrap_by_available_width() {
1026 assert_eq!(grid_columns(px(310.0), px(100.0), px(10.0)), 2);
1028 assert_eq!(grid_columns(px(320.0), px(100.0), px(10.0)), 3);
1029 assert_eq!(grid_columns(px(0.0), px(100.0), px(10.0)), 1);
1030 }
1031
1032 #[test]
1034 fn drop_slot_uses_cell_midpoint() {
1035 let cells = [
1036 Bounds {
1037 origin: point(px(0.0), px(0.0)),
1038 size: size(px(100.0), px(50.0)),
1039 },
1040 Bounds {
1041 origin: point(px(100.0), px(0.0)),
1042 size: size(px(100.0), px(50.0)),
1043 },
1044 ];
1045 assert_eq!(drop_slot(&cells, point(px(10.0), px(20.0))), 0);
1047 assert_eq!(drop_slot(&cells, point(px(80.0), px(20.0))), 1);
1048 assert_eq!(drop_slot(&cells, point(px(180.0), px(20.0))), 2);
1050 assert_eq!(drop_slot(&cells, point(px(400.0), px(400.0))), 2);
1052 }
1053
1054 #[test]
1056 fn move_dest_skips_noop_slots() {
1057 assert_eq!(move_dest(2, 2), None);
1058 assert_eq!(move_dest(2, 3), None);
1059 assert_eq!(move_dest(2, 5), Some(4));
1060 assert_eq!(move_dest(4, 1), Some(1));
1061 assert_eq!(move_dest(0, 4), Some(3));
1062 }
1063
1064 #[test]
1066 fn autoscroll_only_near_edges() {
1067 let viewport = Bounds {
1068 origin: point(px(0.0), px(0.0)),
1069 size: size(px(400.0), px(300.0)),
1070 };
1071
1072 assert_eq!(
1074 autoscroll_velocity(px(150.0), viewport, px(48.0), px(18.0)),
1075 px(0.0)
1076 );
1077 let near_top = autoscroll_velocity(px(10.0), viewport, px(48.0), px(18.0));
1079 let above_top = autoscroll_velocity(px(-20.0), viewport, px(48.0), px(18.0));
1080 assert!(near_top < px(0.0));
1081 assert!(near_top > above_top);
1082 assert_eq!(above_top, px(-18.0));
1083 assert_eq!(
1085 autoscroll_velocity(px(320.0), viewport, px(48.0), px(18.0)),
1086 px(18.0)
1087 );
1088 }
1089
1090 #[test]
1092 fn group_dest_compacts_before_slot() {
1093 assert_eq!(move_group_dest(&[1, 2], 4), Some(2));
1095 assert_eq!(move_group_dest(&[3, 4], 0), Some(0));
1097 assert_eq!(move_group_dest(&[1, 2], 1), None);
1099 assert_eq!(move_group_dest(&[1, 2], 2), None);
1100 assert_eq!(move_group_dest(&[1, 2], 3), None);
1101 assert_eq!(move_group_dest(&[], 0), None);
1103 }
1104
1105 #[rgpui::test]
1107 fn selection_variants_emit_changes(cx: &mut crate::TestAppContext) {
1108 let (state, events, mut cx) = setup(cx);
1109
1110 cx.update(|_, cx| state.update(cx, |state, cx| state.select(2, cx)));
1111 assert_eq!(state.read_with(cx, |state, _| state.primary()), Some(2));
1112 assert_eq!(
1113 events.borrow().as_slice(),
1114 [SorterEvent::SelectionChanged(vec![2])]
1115 );
1116
1117 events.borrow_mut().clear();
1118 cx.update(|_, cx| state.update(cx, |state, cx| state.select_range(2, 4, cx)));
1119 assert_eq!(
1120 state.read_with(cx, |state, _| state
1121 .selected()
1122 .iter()
1123 .copied()
1124 .collect::<Vec<_>>()),
1125 vec![2, 3, 4]
1126 );
1127 assert_eq!(
1128 events.borrow().as_slice(),
1129 [SorterEvent::SelectionChanged(vec![2, 3, 4])]
1130 );
1131
1132 events.borrow_mut().clear();
1133 cx.update(|_, cx| state.update(cx, |state, cx| state.toggle(0, cx)));
1134 assert_eq!(state.read_with(cx, |state, _| state.selection_len()), 4);
1135 assert_eq!(
1136 events.borrow().as_slice(),
1137 [SorterEvent::SelectionChanged(vec![0, 2, 3, 4])]
1138 );
1139
1140 events.borrow_mut().clear();
1142 cx.update(|_, cx| state.update(cx, |state, cx| state.select(99, cx)));
1143 assert!(events.borrow().is_empty());
1144
1145 events.borrow_mut().clear();
1146 cx.update(|_, cx| state.update(cx, |state, cx| state.select_all(cx)));
1147 assert_eq!(state.read_with(cx, |state, _| state.selection_len()), 5);
1148 }
1149
1150 #[rgpui::test]
1152 fn drag_records_pointer_position(cx: &mut crate::TestAppContext) {
1153 let (state, _events, mut cx) = setup(cx);
1154 cx.update(|_, cx| {
1155 state.update(cx, |state, cx| {
1156 state.begin_drag(0, cx);
1157 state.update_drag(crate::point(crate::px(120.0), crate::px(64.0)), cx);
1158 })
1159 });
1160 let position = state.read_with(cx, |state, _| state.drag_position);
1161 assert!(position.is_some(), "拖拽期间应记录指针位置");
1162 cx.update(|_, cx| {
1163 state.update(cx, |state, cx| {
1164 state.cancel_drag(cx);
1165 })
1166 });
1167 assert!(
1168 state
1169 .read_with(cx, |state, _| state.drag_position)
1170 .is_none()
1171 );
1172 }
1173 #[rgpui::test]
1175 fn drag_reorder_emits_event(cx: &mut crate::TestAppContext) {
1176 let (state, events, mut cx) = setup(cx);
1177
1178 cx.update(|_, cx| {
1179 state.update(cx, |state, cx| {
1180 state.begin_drag(0, cx);
1181 state.set_drop_slot(3, cx);
1182 state.finish_drag(cx);
1183 })
1184 });
1185 assert_eq!(
1186 events.borrow().as_slice(),
1187 [SorterEvent::Reorder { from: 0, to: 2 }]
1188 );
1189 assert!(!state.read_with(cx, |state, _| state.is_dragging()));
1190
1191 events.borrow_mut().clear();
1193 cx.update(|_, cx| {
1194 state.update(cx, |state, cx| {
1195 state.begin_drag(2, cx);
1196 state.set_drop_slot(2, cx);
1197 state.finish_drag(cx);
1198 })
1199 });
1200 assert!(events.borrow().is_empty());
1201
1202 events.borrow_mut().clear();
1204 cx.update(|_, cx| {
1205 state.update(cx, |state, cx| {
1206 state.begin_drag(1, cx);
1207 state.set_drop_slot(4, cx);
1208 state.cancel_drag(cx);
1209 })
1210 });
1211 assert!(events.borrow().is_empty());
1212 }
1213
1214 #[rgpui::test]
1216 fn drag_multi_selection_emits_reorder_many(cx: &mut crate::TestAppContext) {
1217 let (state, events, mut cx) = setup(cx);
1218
1219 cx.update(|_, cx| {
1220 state.update(cx, |state, cx| {
1221 state.toggle(1, cx);
1222 state.toggle(2, cx);
1223 })
1224 });
1225 events.borrow_mut().clear();
1226
1227 cx.update(|_, cx| {
1229 state.update(cx, |state, cx| {
1230 state.begin_drag(2, cx);
1231 state.set_drop_slot(5, cx);
1232 state.finish_drag(cx);
1233 })
1234 });
1235 assert_eq!(
1236 events.borrow().as_slice(),
1237 [SorterEvent::ReorderMany {
1238 from: vec![1, 2],
1239 to: 3
1240 }]
1241 );
1242 }
1243
1244 #[rgpui::test]
1246 fn options_are_configurable(cx: &mut crate::TestAppContext) {
1247 let (state, _events, mut cx) = setup(cx);
1248
1249 cx.update(|_, cx| {
1250 state.update(cx, |state, cx| {
1251 state.set_zoom(99.0, cx);
1252 state.set_show_index(false, cx);
1253 state.set_gap(px(4.0), cx);
1254 state.set_base_width(px(200.0), cx);
1255 })
1256 });
1257 assert_eq!(state.read_with(cx, |state, _| state.zoom()), MAX_ZOOM);
1258 assert!(!state.read_with(cx, |state, _| state.show_index()));
1259 assert_eq!(state.read_with(cx, |state, _| state.gap()), px(4.0));
1260 assert_eq!(
1261 state.read_with(cx, |state, _| state.base_width()),
1262 px(200.0)
1263 );
1264 }
1265}