sqlly-datatable 1.1.2

Configurable virtualized data grid component for the GPUI toolkit.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Context menu — column-header right-click interaction. Layout, hover
//! resolution, and action labels live here so paint code only consumes the
//! menu snapshot.

use gpui::{Hsla, Pixels, Point};

use crate::grid::context_menu::ContextMenuRequest;

/// Height, padding, and minimum width used to lay the menu out. Public so the
/// state module's hit-testing math can stay in sync with paint.
pub const MENU_FONT_SIZE: f32 = 14.0;
pub const MENU_ITEM_HEIGHT: f32 = MENU_FONT_SIZE + 8.0;
pub const MENU_PADDING_X: f32 = 12.0;
pub const MENU_MIN_WIDTH: f32 = 180.0;
pub const MENU_BORDER: f32 = 1.0;
pub const MENU_INNER_PAD: f32 = 4.0;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MenuAction {
    SelectColumn,
    CopyColumn,
    CopyColumnWithHeaders,
    SortAscending,
    SortDescending,
    ClearSort,
    FilterPrompt,
    ClearFilter,
}

#[derive(Clone, Debug)]
pub enum MenuItem {
    Action(MenuAction),
    Custom { id: String, label: String },
    Separator,
}

impl MenuItem {
    /// Display label for the item, or `None` for separators.
    #[must_use]
    pub fn label(&self) -> Option<&str> {
        match self {
            Self::Action(a) => Some(label(*a)),
            Self::Custom { label, .. } => Some(label.as_str()),
            Self::Separator => None,
        }
    }

    /// `true` for action/custom items that participate in hover/click.
    #[must_use]
    pub fn is_selectable(&self) -> bool {
        !matches!(self, Self::Separator)
    }
}

#[derive(Clone, Debug)]
pub struct ContextMenu {
    pub col: usize,
    pub anchor: Point<Pixels>,
    pub items: Vec<MenuItem>,
    pub hovered: Option<usize>,
    pub request: Option<ContextMenuRequest>,
}

impl ContextMenu {
    /// Standard column-header menu. Constructed by state when the user
    /// right-clicks a column header or sort button.
    #[must_use]
    pub fn standard(col: usize, anchor: Point<Pixels>) -> Self {
        Self {
            col,
            anchor,
            items: vec![
                MenuItem::Action(MenuAction::SelectColumn),
                MenuItem::Action(MenuAction::CopyColumn),
                MenuItem::Action(MenuAction::CopyColumnWithHeaders),
                MenuItem::Separator,
                MenuItem::Action(MenuAction::SortAscending),
                MenuItem::Action(MenuAction::SortDescending),
                MenuItem::Action(MenuAction::ClearSort),
                MenuItem::Separator,
                MenuItem::Action(MenuAction::FilterPrompt),
                MenuItem::Action(MenuAction::ClearFilter),
            ],
            hovered: None,
            request: None,
        }
    }

    /// Construct a custom menu from provider-supplied items plus the
    /// captured request snapshot. `col` is used for built-in action
    /// dispatch when the provider composes `BuiltIn` items.
    #[must_use]
    pub fn custom(
        col: usize,
        anchor: Point<Pixels>,
        items: Vec<MenuItem>,
        request: ContextMenuRequest,
    ) -> Self {
        Self {
            col,
            anchor,
            items,
            hovered: None,
            request: Some(request),
        }
    }

    /// Width needed to fit the longest label, with padding, bounded below by
    /// [`MENU_MIN_WIDTH`].
    #[must_use]
    pub fn width_for(&self, char_width: f32) -> f32 {
        let mut max_label_w = 0.0_f32;
        for item in &self.items {
            if let Some(text) = item.label() {
                max_label_w = max_label_w.max(text.chars().count() as f32 * char_width);
            }
        }
        MENU_MIN_WIDTH.max(max_label_w + MENU_PADDING_X * 2.0)
    }

    /// Total height including inner padding.
    #[must_use]
    pub fn total_height(&self) -> f32 {
        self.items.len() as f32 * MENU_ITEM_HEIGHT + MENU_INNER_PAD * 2.0
    }
}

/// Maps an action to its user-facing label. Used by hit-testing, paint, and
/// any overlay that needs to show the same string the menu shows.
#[must_use]
pub fn label(action: MenuAction) -> &'static str {
    match action {
        MenuAction::SelectColumn => "Select column",
        MenuAction::CopyColumn => "Copy column",
        MenuAction::CopyColumnWithHeaders => "Copy column with headers",
        MenuAction::SortAscending => "Sort Ascending",
        MenuAction::SortDescending => "Sort Descending",
        MenuAction::ClearSort => "Clear sort",
        MenuAction::FilterPrompt => "Filter...",
        MenuAction::ClearFilter => "Clear filter",
    }
}

/// Index of the hovered action under `x` (content-space) given the
/// caller's full `y`. The caller supplies `y` because the menu overlay is
/// drawn outside the bounds; we don't double-correct it here.
#[must_use]
pub fn hover_at(menu: &ContextMenu, x: f32, y: f32, char_width: f32) -> Option<usize> {
    let w = menu.width_for(char_width);
    let ax: f32 = menu.anchor.x.into();
    let ay: f32 = menu.anchor.y.into();
    if x < ax || x > ax + w || y < ay {
        return None;
    }
    let rel_y = y - ay - MENU_INNER_PAD;
    if rel_y < 0.0 {
        return None;
    }
    let idx = (rel_y / MENU_ITEM_HEIGHT) as usize;
    if idx >= menu.items.len() {
        return None;
    }
    for (cur_row, item) in menu.items.iter().enumerate() {
        if cur_row == idx {
            return match item {
                MenuItem::Action(_) | MenuItem::Custom { .. } => action_index(&menu.items, idx),
                MenuItem::Separator => None,
            };
        }
    }
    None
}

fn action_index(items: &[MenuItem], row: usize) -> Option<usize> {
    let mut action_idx = 0;
    for (i, item) in items.iter().enumerate() {
        if item.is_selectable() {
            if i == row {
                return Some(action_idx);
            }
            action_idx += 1;
        }
    }
    None
}

/// Stable palette for menu chrome.
#[must_use]
pub fn background() -> Hsla {
    Hsla {
        h: 0.0,
        s: 0.0,
        l: 1.0,
        a: 1.0,
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::field_reassign_with_default
)]
mod tests {
    use super::*;
    use gpui::px;

    fn menu_at(x: f32, y: f32) -> ContextMenu {
        ContextMenu::standard(7, point_from(x, y))
    }

    fn point_from(x: f32, y: f32) -> Point<Pixels> {
        Point { x: px(x), y: px(y) }
    }

    fn anchor_y(m: &ContextMenu) -> f32 {
        f32::from(m.anchor.y)
    }

    #[test]
    fn standard_menu_item_sequence_is_stable() {
        let m = ContextMenu::standard(0, point_from(0.0, 0.0));
        let kinds: Vec<&'static str> = m
            .items
            .iter()
            .map(|i| match i {
                MenuItem::Action(MenuAction::SelectColumn) => "SelectColumn",
                MenuItem::Action(MenuAction::CopyColumn) => "CopyColumn",
                MenuItem::Action(MenuAction::CopyColumnWithHeaders) => "CopyColumnWithHeaders",
                MenuItem::Separator => "Separator",
                MenuItem::Action(MenuAction::SortAscending) => "SortAscending",
                MenuItem::Action(MenuAction::SortDescending) => "SortDescending",
                MenuItem::Action(MenuAction::ClearSort) => "ClearSort",
                MenuItem::Action(MenuAction::FilterPrompt) => "FilterPrompt",
                MenuItem::Action(MenuAction::ClearFilter) => "ClearFilter",
                MenuItem::Custom { .. } => "Custom",
            })
            .collect();
        assert_eq!(
            kinds,
            [
                "SelectColumn",
                "CopyColumn",
                "CopyColumnWithHeaders",
                "Separator",
                "SortAscending",
                "SortDescending",
                "ClearSort",
                "Separator",
                "FilterPrompt",
                "ClearFilter",
            ],
        );
    }

    #[test]
    fn at_least_two_separators_break_three_groups() {
        let m = ContextMenu::standard(0, point_from(0.0, 0.0));
        let separators = m
            .items
            .iter()
            .filter(|i| matches!(i, MenuItem::Separator))
            .count();
        assert_eq!(separators, 2);
    }

    #[test]
    fn every_menu_action_has_non_empty_label() {
        for a in [
            MenuAction::SelectColumn,
            MenuAction::CopyColumn,
            MenuAction::CopyColumnWithHeaders,
            MenuAction::SortAscending,
            MenuAction::SortDescending,
            MenuAction::ClearSort,
            MenuAction::FilterPrompt,
            MenuAction::ClearFilter,
        ] {
            assert!(!label(a).is_empty(), "{a:?} has empty label");
        }
    }

    #[test]
    fn width_respects_min_width() {
        let m = menu_at(0.0, 0.0);
        assert!(m.width_for(1.0) >= MENU_MIN_WIDTH);
    }

    #[test]
    fn width_grows_with_longest_label() {
        let m = menu_at(0.0, 0.0);
        let narrow = m.width_for(1.0);
        let wide = m.width_for(20.0);
        assert!(wide > narrow);
    }

    #[test]
    fn total_height_matches_items_and_padding() {
        let m = menu_at(0.0, 0.0);
        let expected = m.items.len() as f32 * MENU_ITEM_HEIGHT + MENU_INNER_PAD * 2.0;
        assert_eq!(m.total_height(), expected);
    }

    #[test]
    fn hover_returns_none_outside_x_bounds() {
        let m = menu_at(100.0, 100.0);
        let right = m.width_for(8.0);
        assert_eq!(hover_at(&m, 99.0, 110.0, 8.0), None);
        assert_eq!(hover_at(&m, 100.0 + right + 1.0, 110.0, 8.0), None);
    }

    #[test]
    fn hover_returns_none_above_anchor() {
        let m = menu_at(100.0, 100.0);
        assert_eq!(hover_at(&m, 110.0, 99.0, 8.0), None);
    }

    #[test]
    fn hover_on_first_action_returns_action_index_zero() {
        let m = menu_at(100.0, 100.0);
        let y: f32 = anchor_y(&m) + MENU_INNER_PAD;
        assert_eq!(hover_at(&m, 110.0, y, 8.0), Some(0));
    }

    #[test]
    fn hover_on_separator_returns_none() {
        let m = menu_at(100.0, 100.0);
        let y: f32 = anchor_y(&m) + MENU_INNER_PAD + 3.0 * MENU_ITEM_HEIGHT;
        assert_eq!(hover_at(&m, 110.0, y, 8.0), None);
    }

    #[test]
    fn hover_below_last_item_is_none() {
        let m = menu_at(100.0, 100.0);
        let y: f32 = anchor_y(&m) + 1000.0;
        assert_eq!(hover_at(&m, 110.0, y, 8.0), None);
    }

    fn custom_menu_with_items(x: f32, y: f32, items: Vec<MenuItem>) -> ContextMenu {
        ContextMenu {
            col: 0,
            anchor: point_from(x, y),
            items,
            hovered: None,
            request: None,
        }
    }

    #[test]
    fn custom_item_contributes_to_width() {
        let long_label = "A very long custom menu item label";
        let items = vec![
            MenuItem::Custom {
                id: "a".into(),
                label: long_label.into(),
            },
            MenuItem::Separator,
        ];
        let m = custom_menu_with_items(0.0, 0.0, items);
        let w = m.width_for(8.0);
        let expected = long_label.chars().count() as f32 * 8.0 + MENU_PADDING_X * 2.0;
        assert_eq!(w, expected);
    }

    #[test]
    fn custom_item_is_selectable_and_hoverable() {
        let items = vec![
            MenuItem::Custom {
                id: "first".into(),
                label: "First".into(),
            },
            MenuItem::Separator,
            MenuItem::Custom {
                id: "third".into(),
                label: "Third".into(),
            },
        ];
        let m = custom_menu_with_items(100.0, 100.0, items);
        // First custom item at index 0.
        let y: f32 = anchor_y(&m) + MENU_INNER_PAD;
        assert_eq!(hover_at(&m, 110.0, y, 8.0), Some(0));
        // Separator at row 1 returns None.
        let y: f32 = anchor_y(&m) + MENU_INNER_PAD + 1.0 * MENU_ITEM_HEIGHT;
        assert_eq!(hover_at(&m, 110.0, y, 8.0), None);
        // Third item (second custom) at row 2 -> action index 1.
        let y: f32 = anchor_y(&m) + MENU_INNER_PAD + 2.0 * MENU_ITEM_HEIGHT;
        assert_eq!(hover_at(&m, 110.0, y, 8.0), Some(1));
    }

    #[test]
    fn menu_item_label_helper() {
        assert_eq!(
            MenuItem::Action(MenuAction::SortAscending).label(),
            Some("Sort Ascending")
        );
        assert_eq!(
            MenuItem::Custom {
                id: "x".into(),
                label: "Hello".into()
            }
            .label(),
            Some("Hello")
        );
        assert_eq!(MenuItem::Separator.label(), None);
    }

    #[test]
    fn menu_item_is_selectable() {
        assert!(MenuItem::Action(MenuAction::ClearFilter).is_selectable());
        assert!(MenuItem::Custom {
            id: "x".into(),
            label: "y".into()
        }
        .is_selectable());
        assert!(!MenuItem::Separator.is_selectable());
    }
}