Skip to main content

rgpui/
sorter.rs

1//! 缩略图排序器 —— 可拖拽重排的缩略图网格(幻灯片 / 页面 / 图片)。
2//!
3//! 面向「一堆等尺寸缩略图 + 拖拽重排」的场景:自动换行网格、单选 / 范围选择 /
4//! 多选、缩放、键盘导航,以及**拖拽重排**(拖拽过程中在插入位置画一条指示线)。
5//! 框架只负责控件与交互,缩略图内容与项目顺序由应用通过 [`SorterDelegate`] 提供;
6//! 重排只抛出 [`SorterEvent::Reorder`](多选拖动时是 [`SorterEvent::ReorderMany`]),
7//! 真正移动数据由应用完成(见下方示例)。拖到视口上下边缘的自动滚动由
8//! [`SorterState::drag_autoscroll`] 提供逻辑,应用按帧驱动即可。
9//!
10//! 与 [`DataTable`](crate::DataTable) / [`VirtualList`](crate::VirtualList) 的区别:
11//! 后两者面向「有序行」且不提供重排,本控件面向「二维缩略图墙」并提供拖拽重排、
12//! 缩放与多选。
13//!
14//! ## 用法
15//!
16//! ```ignore
17//! use rgpui::sorter::{Sorter, SorterDelegate, SorterEvent, SorterState};
18//!
19//! struct Slides {
20//!     items: Vec<String>,
21//! }
22//!
23//! impl SorterDelegate for Slides {
24//!     fn count(&self, _: &App) -> usize {
25//!         self.items.len()
26//!     }
27//!
28//!     fn render_item(
29//!         &mut self,
30//!         index: usize,
31//!         _selected: bool,
32//!         _window: &mut Window,
33//!         _cx: &mut Context<SorterState<Self>>,
34//!     ) -> impl IntoElement {
35//!         div().size_full().child(self.items[index].clone())
36//!     }
37//! }
38//!
39//! let state = cx.new(|cx| SorterState::new(Slides { items }, cx));
40//! cx.subscribe_in(&state, window, |this, state, event: &SorterEvent, window, cx| {
41//!     if let SorterEvent::Reorder { from, to } = event {
42//!         state.update(cx, |state, cx| {
43//!             let item = state.delegate_mut().items.remove(*from);
44//!             state.delegate_mut().items.insert(*to, item);
45//!             cx.notify();
46//!         });
47//!     }
48//! })
49//! .detach();
50//!
51//! // 视图树中:
52//! Sorter::new(&state)
53//! ```
54
55use 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
65/// 缩略图基准宽度(缩放系数为 1.0 时的像素宽度)。
66pub const DEFAULT_CELL_WIDTH: Pixels = px(160.0);
67/// 缩略图之间以及网格四周的默认间距(像素)。
68pub const DEFAULT_GAP: Pixels = px(12.0);
69/// 最小缩放系数。
70pub const MIN_ZOOM: f32 = 0.4;
71/// 最大缩放系数。
72pub const MAX_ZOOM: f32 = 2.5;
73/// 默认单元格宽高比(16:9)。
74pub const DEFAULT_ASPECT_RATIO: f32 = 16.0 / 9.0;
75/// 拖拽自动滚动的触边距离(距视口上下边缘多少像素内开始滚动)。
76pub const AUTOSCROLL_EDGE: Pixels = px(48.0);
77/// 拖拽自动滚动的最快速度(每帧滚动多少像素,贴着边缘时取到)。
78pub const AUTOSCROLL_MAX_SPEED: Pixels = px(18.0);
79
80/// 把缩放系数夹取到 [`MIN_ZOOM`]..=[`MAX_ZOOM`],非有限值回落为 `1.0`。
81pub 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
89/// 归一化宽高比:非有限值或非正数回落为 [`DEFAULT_ASPECT_RATIO`]。
90pub 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
98/// 缩略图单元格尺寸:宽 = 基准宽 × 夹取后的缩放,高 = 宽 ÷ 宽高比。
99pub 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
104/// 一行能放下的缩略图数量(至少 1)。
105///
106/// 按 `floor((可用宽 + 间距) / (格宽 + 间距))` 计算,保证与 `flex-wrap` 的换行一致。
107pub 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
120/// 根据指针位置与各单元格边界求插入槽(取值 `0..=count`)。
121///
122/// 命中某个单元格时:指针在其水平中线右侧返回 `index + 1`,否则返回 `index`;
123/// 未命中任何单元格(如落在网格空白处)返回 `cells.len()`(排到末尾)。
124pub 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
138/// 把「拖拽源索引 + 插入槽」换算成移动后的目标索引;无需移动时返回 `None`。
139///
140/// 插入槽等于源位置本身或紧随其后时表示没有实际位移。
141pub 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
151/// 拖拽到视口上下边缘时的自动滚动速度(每帧像素,正数向下、负数向上)。
152///
153/// 指针进入距边缘 `edge` 的带状区域后开始滚动,越贴近边缘越快,贴边时取到
154/// `max_speed`;不在边缘区域时返回 0。自动滚动由应用按帧重复调用
155/// [`SorterState::drag_autoscroll`] 驱动,组件本身不持有定时器。
156pub 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
179/// 多选整组拖动:把插入槽换算成「整组落位后的起始索引」。
180///
181/// `selected` 必须升序且非空。槽位落在选中集合首项之后、末项及其后一位之前时返回
182/// `None`:整组拖回自己身上没有意义。返回值是**抽走选中项之后**的列表里,整组第一项
183/// 应处的索引。
184pub 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    // 目标槽前面的选中项会被抽走,落位索引要相应前移
192    let removed_before = selected.iter().filter(|&&index| index < slot).count();
193    Some(slot - removed_before)
194}
195
196/// 排序器抛出的事件(应用经 `subscribe` 接收)。
197#[derive(Clone, Debug, PartialEq, Eq)]
198pub enum SorterEvent {
199    /// 选中集合变化(升序索引列表)。
200    SelectionChanged(Vec<usize>),
201    /// 请求重排:把 `from` 处的项目移动到 `to`(移动后的索引)。
202    Reorder {
203        /// 拖拽源索引。
204        from: usize,
205        /// 移动后的目标索引。
206        to: usize,
207    },
208    /// 请求整组重排:把 `from` 里的项目(升序)整体移动到 `to` 起始的位置。
209    ///
210    /// 应用按「先按索引升序抽出这些项目,再插入到 `to`」的方式重排数据。
211    ReorderMany {
212        /// 整组项目的原索引,升序。
213        from: Vec<usize>,
214        /// 抽走后的列表中,整组第一项的目标索引。
215        to: usize,
216    },
217    /// 激活某一项(双击 / `Enter` / `Space`)。
218    Activate(usize),
219    /// 请求删除选中项(`Delete` / `Backspace`)。
220    Delete(Vec<usize>),
221}
222
223/// 为排序器提供项目数量、宽高比与缩略图渲染的代理 trait。
224pub trait SorterDelegate: Sized + 'static {
225    /// 项目数量。
226    fn count(&self, cx: &App) -> usize;
227
228    /// 单元格宽高比(宽 ÷ 高),默认 [`DEFAULT_ASPECT_RATIO`]。
229    fn aspect_ratio(&self, _cx: &App) -> f32 {
230        DEFAULT_ASPECT_RATIO
231    }
232
233    /// 渲染第 `index` 个缩略图内容(填充单元格,`selected` 为选中态)。
234    ///
235    /// 默认渲染项目序号。
236    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
247/// 排序器状态:持有委托、选中集合、缩放、拖拽与滚动。
248pub struct SorterState<D: SorterDelegate> {
249    /// 数据 / 渲染委托。
250    delegate: D,
251    /// 选中项索引(升序)。
252    selected: BTreeSet<usize>,
253    /// 范围选择的锚点。
254    anchor: Option<usize>,
255    /// 缩放系数(见 [`MIN_ZOOM`] / [`MAX_ZOOM`])。
256    zoom: f32,
257    /// 是否在缩略图左上角显示序号。
258    show_index: bool,
259    /// 正在拖拽的项目索引。
260    dragging: Option<usize>,
261    /// 拖拽期间的插入槽。
262    hover_slot: Option<usize>,
263    /// 拖拽期间的指针位置(窗口坐标;拖拽预览用)。
264    drag_position: Option<Point<Pixels>>,
265    /// 最近一次预绘制的各单元格边界(窗口坐标,随滚动更新)。
266    cell_bounds: Vec<Bounds<Pixels>>,
267    /// 最近一次预绘制的根元素边界(即视口)。
268    bounds: Bounds<Pixels>,
269    /// 每行列数(最近一次渲染缓存,键盘导航用)。
270    columns: usize,
271    /// 单元格基准宽。
272    base_width: Pixels,
273    /// 单元格间距(同时用作网格内边距)。
274    gap: Pixels,
275    /// 网格滚动句柄。
276    scroll: ScrollHandle,
277    /// 焦点句柄。
278    focus_handle: FocusHandle,
279}
280
281impl<D: SorterDelegate> SorterState<D> {
282    /// 创建排序器状态。
283    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    /// 数据委托。
304    pub fn delegate(&self) -> &D {
305        &self.delegate
306    }
307
308    /// 数据委托(可变)。
309    pub fn delegate_mut(&mut self) -> &mut D {
310        &mut self.delegate
311    }
312
313    /// 项目数量(实时向委托查询)。
314    pub fn count(&self, cx: &App) -> usize {
315        self.delegate.count(cx)
316    }
317
318    /// 选中项索引(升序)。
319    pub fn selected(&self) -> &BTreeSet<usize> {
320        &self.selected
321    }
322
323    /// 主选中项(最小索引)。
324    pub fn primary(&self) -> Option<usize> {
325        self.selected.iter().next().copied()
326    }
327
328    /// 某项是否被选中。
329    pub fn is_selected(&self, index: usize) -> bool {
330        self.selected.contains(&index)
331    }
332
333    /// 选中项数量。
334    pub fn selection_len(&self) -> usize {
335        self.selected.len()
336    }
337
338    /// 当前缩放系数。
339    pub fn zoom(&self) -> f32 {
340        self.zoom
341    }
342
343    /// 设置缩放系数(自动夹取到 [`MIN_ZOOM`]..=[`MAX_ZOOM`])。
344    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    /// 按 `delta` 增减缩放系数。
353    pub fn zoom_by(&mut self, delta: f32, cx: &mut Context<Self>) {
354        self.set_zoom(self.zoom + delta, cx);
355    }
356
357    /// 是否显示序号角标。
358    pub fn show_index(&self) -> bool {
359        self.show_index
360    }
361
362    /// 设置是否显示序号角标。
363    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    /// 单元格基准宽。
371    pub fn base_width(&self) -> Pixels {
372        self.base_width
373    }
374
375    /// 设置单元格基准宽。
376    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    /// 单元格间距。
384    pub fn gap(&self) -> Pixels {
385        self.gap
386    }
387
388    /// 设置单元格间距(同时用作网格内边距)。
389    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    /// 每行列数(最近一次渲染缓存)。
397    pub fn columns(&self) -> usize {
398        self.columns
399    }
400
401    /// 是否正在拖拽。
402    pub fn is_dragging(&self) -> bool {
403        self.dragging.is_some()
404    }
405
406    /// 聚焦排序器。
407    pub fn focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
408        self.focus_handle.focus(window, cx);
409    }
410
411    /// 单选某一项(越界忽略)。
412    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    /// 切换某项的选中态(多选)。
426    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    /// 以 `anchor`..=`cursor` 的范围选中(顺序无关)。
438    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    /// 全选。
454    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    /// 清空选择。
464    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    /// 开始拖拽某一项。
473    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    /// 设置拖拽插入槽(应用可直接按槽位驱动,也可用 [`Self::update_drag`] 由指针推算)。
480    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    /// 按指针位置更新插入槽(拖拽过程中由鼠标移动驱动)。
491    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    /// 拖拽边缘自动滚动:按指针位置滚动视口,返回本帧的滚动增量。
501    ///
502    /// 应用在拖拽期间用前台定时器每帧调用一次;返回 [`px(0.0)`] 表示指针不在边缘
503    /// 区域,可以停掉定时器。滚动后顺带重算插入槽。
504    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    /// 结束拖拽:位移有效时抛出 [`SorterEvent::Reorder`];拖的是多选中的一项时
528    /// 抛 [`SorterEvent::ReorderMany`],整组一起移动。
529    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    /// 取消拖拽(不抛出事件)。
548    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    /// 滚动到指定项使其可见。
556    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    /// 抛出选中变化事件并重绘。
577    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    /// 单元格鼠标按下:选择 + 双击激活 + 进入拖拽。
584    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    /// 鼠标移动:拖拽期间更新插入槽。
611    fn on_pointer_move(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
612        self.update_drag(position, cx);
613    }
614
615    /// 鼠标释放:结束拖拽(位移有效则抛出重排事件)。
616    fn on_pointer_up(&mut self, cx: &mut Context<Self>) {
617        self.finish_drag(cx);
618    }
619
620    /// 键盘导航 / 激活 / 删除。
621    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    /// 按步长移动选中项。
659    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    /// 移动选中项到 `index`(`extend` 为真时从锚点扩展范围)。
672    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    /// 渲染单元格的序号角标。
683    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        // 同步数量并夹取选择 / 拖拽 / 边界缓存。
709        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        // 先把主题色拷出来,避免与后续 `render_item` 的 `&mut cx` 借用冲突。
730        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        // 拖拽预览:跟随指针的半透明副本(原格保留半透明占位)。
790        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        // 插入指示线:按插入槽落在对应单元格的左缘(末尾落在最后一格右缘)。
816        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/// 排序器元素(薄包装:按键上下文、焦点与键盘 / 释放事件)。
881#[derive(IntoElement)]
882pub struct Sorter<D: SorterDelegate> {
883    state: Entity<SorterState<D>>,
884}
885
886impl<D: SorterDelegate> Sorter<D> {
887    /// 使用给定 [`SorterState`] 创建排序器元素。
888    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::*`——本模块的 glob 会把 `crate::test` 带进来遮蔽内置 `#[test]`。
924    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    /// 固定 5 项的测试委托。
937    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    /// 渲染排序器的测试宿主。
958    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    /// 构建宿主并收集排序器事件。
969    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    /// 缩放夹取与宽高比归一化。
996    #[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    /// 单元格尺寸随缩放线性变化,并按宽高比换算高度。
1009    #[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        // 越界缩放被夹取。
1020        assert_eq!(cell_size(px(100.0), 10.0, 1.0).width, px(100.0) * MAX_ZOOM);
1021    }
1022
1023    /// 每行列数按可用宽度换算,且至少为 1。
1024    #[test]
1025    fn columns_wrap_by_available_width() {
1026        // 间距 10、格宽 100:宽 310 恰好放 3 列(100*3 + 10*2 = 320 > 310)。
1027        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    /// 插入槽按指针落在单元格中线左右决定。
1033    #[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        // 第一格左半 → 槽 0;右半 → 槽 1。
1046        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        // 第二格右半 → 槽 2。
1049        assert_eq!(drop_slot(&cells, point(px(180.0), px(20.0))), 2);
1050        // 落在网格外 → 排到末尾。
1051        assert_eq!(drop_slot(&cells, point(px(400.0), px(400.0))), 2);
1052    }
1053
1054    /// 移动目标换算:源位置自身或紧随其后视为无位移。
1055    #[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    /// 拖到视口上下边缘才自动滚动,越贴边越快。
1065    #[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        // 视口中间:不滚
1073        assert_eq!(
1074            autoscroll_velocity(px(150.0), viewport, px(48.0), px(18.0)),
1075            px(0.0)
1076        );
1077        // 贴上边缘:向上滚,越贴越快,贴边取到上限
1078        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        // 贴下边缘:向下滚
1084        assert_eq!(
1085            autoscroll_velocity(px(320.0), viewport, px(48.0), px(18.0)),
1086            px(18.0)
1087        );
1088    }
1089
1090    /// 整组落位:抽走选中项后索引前移,拖回自己身上不产生位移。
1091    #[test]
1092    fn group_dest_compacts_before_slot() {
1093        // [1, 2] 拖到槽 4:抽走两项后落位索引变成 2
1094        assert_eq!(move_group_dest(&[1, 2], 4), Some(2));
1095        // 拖到最前
1096        assert_eq!(move_group_dest(&[3, 4], 0), Some(0));
1097        // 拖回自己区间:无位移
1098        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        // 空选择没有落位
1102        assert_eq!(move_group_dest(&[], 0), None);
1103    }
1104
1105    /// 单选 / 范围 / 多选 / 全选都抛出 `SelectionChanged`。
1106    #[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        // 越界索引被忽略,不抛出事件。
1141        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    /// 拖拽预览:拖拽期间记录指针位置,结束后清空(预览据此定位)。
1151    #[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    /// 拖拽到有效槽位抛出重排事件,落到相邻槽位则视为无位移。
1174    #[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        // 槽位等于源位置 / 紧随源位置:无位移,不抛出事件。
1192        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        // 取消拖拽不抛出事件。
1203        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    /// 拖的是多选中的一项时整组移动,抛 `ReorderMany`。
1215    #[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        // 抓取选中项之一拖到末尾:整组 [1, 2] 落到抽走两项后的索引 3
1228        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    /// 缩放 / 序号显示 / 间距的可配置性。
1245    #[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}