sqlly-datatable 1.4.0

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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! Public context-menu extensibility types.
//!
//! Consumers implement [`ContextMenuProvider`] and register it on
//! [`crate::grid::SqllyDataTableBuilder`] to fully control the right-click
//! menu. When a provider is registered the built-in column-header menu is
//! suppressed; consumers can compose built-in items via
//! [`ContextMenuItem::standard_column_header_items`].
//!
//! The provider receives an owned [`ContextMenuRequest`] snapshot captured
//! at menu-open time. The snapshot survives until the user clicks a menu
//! item, so the provider's [`ContextMenuProvider::on_action`] sees exactly
//! what was selected/right-clicked when the menu opened — even if grid state
//! (sort, filter, selection) changed in the interim.

use std::fmt;
use std::sync::Arc;

use crate::data::{CellValue, ColumnKind};
use crate::grid::menu::MenuAction;
use crate::grid::state::GridState;

/// What was right-clicked. Maps directly from the grid's hit-test result.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ContextMenuTarget {
    /// A data cell.
    Cell {
        display_row_index: usize,
        source_row_index: usize,
        column_index: usize,
    },
    /// The row-number gutter on the left edge.
    RowHeader {
        display_row_index: usize,
        source_row_index: usize,
    },
    /// A column header cell (excluding the sort button area).
    ColumnHeader { column_index: usize },
    /// The sort/indicator button inside a column header.
    SortButton { column_index: usize },
}

impl ContextMenuTarget {
    /// Returns the column index for targets that carry one, or `None` for
    /// row-header targets.
    #[must_use]
    pub fn column_index(&self) -> Option<usize> {
        match self {
            Self::Cell { column_index, .. } => Some(*column_index),
            Self::ColumnHeader { column_index } => Some(*column_index),
            Self::SortButton { column_index } => Some(*column_index),
            Self::RowHeader { .. } => None,
        }
    }

    /// Returns the display row index for targets that carry one, or `None`
    /// for column-header/sort-button targets.
    #[must_use]
    pub fn display_row_index(&self) -> Option<usize> {
        match self {
            Self::Cell {
                display_row_index, ..
            } => Some(*display_row_index),
            Self::RowHeader {
                display_row_index, ..
            } => Some(*display_row_index),
            Self::ColumnHeader { .. } | Self::SortButton { .. } => None,
        }
    }
}

/// Normalized inclusive selection range captured at menu-open time.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContextMenuSelection {
    pub row_start: usize,
    pub row_end: usize,
    pub column_start: usize,
    pub column_end: usize,
}

/// Metadata and value for a single selected cell.
#[derive(Clone, Debug)]
pub struct SelectedCellContext {
    pub display_row_index: usize,
    pub source_row_index: usize,
    pub column_index: usize,
    pub column_name: String,
    pub value: CellValue,
}

/// Metadata for a column, included in [`SelectedRowContext`].
#[derive(Clone, Debug)]
pub struct ColumnContext {
    pub index: usize,
    pub name: String,
    pub kind: ColumnKind,
}

/// Full selected row: all cell values plus column metadata for name-based
/// lookup helpers.
#[derive(Clone, Debug)]
pub struct SelectedRowContext {
    pub display_row_index: usize,
    pub source_row_index: usize,
    pub values: Vec<CellValue>,
    pub columns: Vec<ColumnContext>,
}

impl SelectedRowContext {
    /// Value at the given ordinal column index.
    #[must_use]
    pub fn value_at(&self, column_index: usize) -> Option<&CellValue> {
        self.values.get(column_index)
    }

    /// Value for the first column whose name matches `column_name` exactly
    /// (case-sensitive). If duplicate names exist, the first match wins.
    #[must_use]
    pub fn value_by_name(&self, column_name: &str) -> Option<&CellValue> {
        self.column_index(column_name)
            .and_then(|i| self.values.get(i))
    }

    /// Iterator over `(column_name, value)` pairs for every column in this
    /// row.
    pub fn named_values(&self) -> impl Iterator<Item = (&str, &CellValue)> {
        self.columns
            .iter()
            .filter_map(move |col| self.values.get(col.index).map(|v| (col.name.as_str(), v)))
    }

    /// Ordinal column index for the first column whose name matches
    /// `column_name` exactly (case-sensitive). First duplicate wins.
    #[must_use]
    pub fn column_index(&self, column_name: &str) -> Option<usize> {
        self.columns
            .iter()
            .find(|c| c.name == column_name)
            .map(|c| c.index)
    }
}

/// Lazy snapshot of the right-click context, captured at menu-open time.
///
/// Construction is O(1): the request holds shared ([`Arc`]) handles to the
/// grid's row data, display order, and column metadata plus the normalized
/// selection bounds. **No per-cell or per-row data is cloned when the menu
/// opens**, so right-clicking a huge selection is instant.
///
/// The owned per-cell / per-row snapshots are materialized on demand:
/// - [`clicked_cell`](Self::clicked_cell) / [`clicked_row`](Self::clicked_row)
///   are cheap (a single cell / row).
/// - [`for_each_selected_cell`](Self::for_each_selected_cell) /
///   [`for_each_selected_row`](Self::for_each_selected_row) stream the
///   selection without allocating a big intermediate `Vec` — prefer these in
///   background work (e.g. building an export).
/// - [`selected_cells`](Self::selected_cells) /
///   [`selected_rows`](Self::selected_rows) collect into a `Vec` for
///   convenience; these clone O(cells)/O(rows x cols) owned data and should
///   be called off the UI thread for large selections (see
///   [`GridState::spawn_background`](crate::grid::GridState::spawn_background)).
///
/// All indices are display indices (post sort/filter) unless prefixed with
/// `source_`.
///
/// For column-oriented targets (`ColumnHeader`, `SortButton`, or a
/// `Selection::Column`), the row accessors are empty — a column right-click is
/// column-oriented (`clicked_row()` is `None`), so the column's values are
/// exposed through the cell accessors and full per-row snapshots are skipped.
///
/// The type is `Send + Sync + 'static` (it holds only `Arc`s and `Copy`
/// bounds), so a clone can be moved into a background task.
#[derive(Clone)]
pub struct ContextMenuRequest {
    pub target: ContextMenuTarget,
    pub selection: Option<ContextMenuSelection>,
    rows: Arc<Vec<Vec<CellValue>>>,
    display_indices: Arc<Vec<usize>>,
    columns: Arc<[ColumnContext]>,
    column_oriented: bool,
}

impl fmt::Debug for ContextMenuRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ContextMenuRequest")
            .field("target", &self.target)
            .field("selection", &self.selection)
            .field("column_oriented", &self.column_oriented)
            .field("selected_cell_count", &self.selected_cell_count())
            .field("selected_row_count", &self.selected_row_count())
            .finish_non_exhaustive()
    }
}

impl ContextMenuRequest {
    /// Construct a lazy request. Internal: the widget builds this at
    /// menu-open time from the grid's shared state.
    pub(crate) fn new(
        target: ContextMenuTarget,
        selection: Option<ContextMenuSelection>,
        rows: Arc<Vec<Vec<CellValue>>>,
        display_indices: Arc<Vec<usize>>,
        columns: Arc<[ColumnContext]>,
        column_oriented: bool,
    ) -> Self {
        Self {
            target,
            selection,
            rows,
            display_indices,
            columns,
            column_oriented,
        }
    }

    /// The inclusive selection bounds as `(row_start, col_start, row_end,
    /// col_end)` in display/column space, or `None` when there is no
    /// selection.
    fn bounds(&self) -> Option<(usize, usize, usize, usize)> {
        self.selection.as_ref().map(|s| {
            (
                s.row_start,
                s.column_start,
                s.row_end.min(self.display_indices.len().saturating_sub(1)),
                s.column_end.min(self.columns.len().saturating_sub(1)),
            )
        })
    }

    /// Build the [`SelectedCellContext`] at a given display row / column,
    /// resolving the source row through the display order. `None` if out of
    /// bounds.
    fn cell_at(&self, display_row: usize, column: usize) -> Option<SelectedCellContext> {
        let &source_row_index = self.display_indices.get(display_row)?;
        let value = self.rows.get(source_row_index)?.get(column)?.clone();
        let col = self.columns.get(column)?;
        Some(SelectedCellContext {
            display_row_index: display_row,
            source_row_index,
            column_index: column,
            column_name: col.name.clone(),
            value,
        })
    }

    /// Build the [`SelectedRowContext`] for a given display row. `None` if out
    /// of bounds.
    fn row_at(&self, display_row: usize) -> Option<SelectedRowContext> {
        let &source_row_index = self.display_indices.get(display_row)?;
        let values = self.rows.get(source_row_index)?.clone();
        Some(SelectedRowContext {
            display_row_index: display_row,
            source_row_index,
            values,
            columns: self.columns.to_vec(),
        })
    }

    /// The specific cell under the cursor when the menu opened, if the
    /// right-click landed on a data cell. Cheap (clones one cell).
    #[must_use]
    pub fn clicked_cell(&self) -> Option<SelectedCellContext> {
        match self.target {
            ContextMenuTarget::Cell {
                display_row_index,
                column_index,
                ..
            } => self.cell_at(display_row_index, column_index),
            _ => None,
        }
    }

    /// The row under the cursor when the menu opened, if the right-click
    /// landed on a cell or row header. Cheap (clones one row).
    #[must_use]
    pub fn clicked_row(&self) -> Option<SelectedRowContext> {
        let row = self.target.display_row_index()?;
        self.row_at(row)
    }

    /// Number of cells in the effective selection. O(1) — computed from the
    /// selection bounds without materializing anything.
    #[must_use]
    pub fn selected_cell_count(&self) -> usize {
        self.bounds()
            .map_or(0, |(r1, c1, r2, c2)| (r2 - r1 + 1) * (c2 - c1 + 1))
    }

    /// Number of rows in the effective selection. `0` for column-oriented
    /// targets. O(1).
    #[must_use]
    pub fn selected_row_count(&self) -> usize {
        if self.column_oriented {
            return 0;
        }
        self.bounds().map_or(0, |(r1, _, r2, _)| r2 - r1 + 1)
    }

    /// Whether this request is column-oriented (a column-header/sort-button
    /// right-click or a `Selection::Column`), in which case the row accessors
    /// are empty.
    #[must_use]
    pub fn is_column_oriented(&self) -> bool {
        self.column_oriented
    }

    /// Stream every selected cell without allocating an intermediate `Vec`.
    /// Prefer this in background work.
    pub fn for_each_selected_cell(&self, mut f: impl FnMut(SelectedCellContext)) {
        let Some((r1, c1, r2, c2)) = self.bounds() else {
            return;
        };
        for dr in r1..=r2 {
            for c in c1..=c2 {
                if let Some(cell) = self.cell_at(dr, c) {
                    f(cell);
                }
            }
        }
    }

    /// Stream every selected row without allocating an intermediate `Vec`.
    /// Yields nothing for column-oriented targets. Prefer this in background
    /// work.
    pub fn for_each_selected_row(&self, mut f: impl FnMut(SelectedRowContext)) {
        if self.column_oriented {
            return;
        }
        let Some((r1, _, r2, _)) = self.bounds() else {
            return;
        };
        for dr in r1..=r2 {
            if let Some(r) = self.row_at(dr) {
                f(r);
            }
        }
    }

    /// All selected cells in the effective selection, materialized into a
    /// `Vec`. Clones O(cells) owned data — call off the UI thread for large
    /// selections.
    #[must_use]
    pub fn selected_cells(&self) -> Vec<SelectedCellContext> {
        let mut out = Vec::with_capacity(self.selected_cell_count());
        self.for_each_selected_cell(|c| out.push(c));
        out
    }

    /// All selected rows in the effective selection, materialized into a
    /// `Vec` (empty for column-oriented targets). Clones O(rows x cols) owned
    /// data — call off the UI thread for large selections.
    #[must_use]
    pub fn selected_rows(&self) -> Vec<SelectedRowContext> {
        let mut out = Vec::with_capacity(self.selected_row_count());
        self.for_each_selected_row(|r| out.push(r));
        out
    }
}

/// Public menu item returned by a [`ContextMenuProvider`]. Distinct from the
/// internal `MenuItem` used by the rendering pipeline.
#[derive(Clone, Debug)]
pub enum ContextMenuItem {
    /// A built-in action (sort, copy, filter, etc.). Allows providers to
    /// compose standard column-header actions alongside custom ones.
    BuiltIn(MenuAction),
    /// A custom action with a consumer-defined `id` and display label.
    Action { id: String, label: String },
    /// A visual separator.
    Separator,
}

impl ContextMenuItem {
    /// Convenience constructor for a custom action.
    #[must_use]
    pub fn action(id: impl Into<String>, label: impl Into<String>) -> Self {
        Self::Action {
            id: id.into(),
            label: label.into(),
        }
    }

    /// Convenience constructor for a separator.
    #[must_use]
    pub fn separator() -> Self {
        Self::Separator
    }

    /// The standard built-in column-header menu items, in the same order
    /// the grid uses when no provider is registered. Providers can prepend
    /// or append custom items around this list.
    #[must_use]
    pub fn standard_column_header_items() -> Vec<Self> {
        vec![
            Self::BuiltIn(MenuAction::SelectColumn),
            Self::BuiltIn(MenuAction::CopyColumn),
            Self::BuiltIn(MenuAction::CopyColumnWithHeaders),
            Self::Separator,
            Self::BuiltIn(MenuAction::SortAscending),
            Self::BuiltIn(MenuAction::SortDescending),
            Self::BuiltIn(MenuAction::ClearSort),
            Self::Separator,
            Self::BuiltIn(MenuAction::FilterPrompt),
            Self::BuiltIn(MenuAction::ClearFilter),
        ]
    }
}

/// Trait implemented by consumers to supply custom right-click menu items
/// and handle clicks on those items.
///
/// The provider is registered on
/// [`crate::grid::SqllyDataTableBuilder::context_menu_provider`]. When
/// registered, the provider fully controls the right-click menu for all
/// targets (cells, row headers, column headers). When no provider is
/// registered, the built-in column-header menu is used unchanged.
///
/// `menu_items` is called only on right-click, so normal render/scroll
/// performance is unaffected. `on_action` is called when the user clicks a
/// custom menu item, with `&mut GridState` and `&mut gpui::App` available
/// for clipboard, selection, or application-level side effects.
pub trait ContextMenuProvider: 'static {
    /// Build the menu items for the given right-click context.
    fn menu_items(&self, request: &ContextMenuRequest) -> Vec<ContextMenuItem>;

    /// Handle a click on a custom action item. `action_id` matches the `id`
    /// supplied in [`ContextMenuItem::Action`]. Built-in items
    /// ([`ContextMenuItem::BuiltIn`]) are handled by the grid and do not
    /// reach this method.
    #[allow(unused_variables)]
    fn on_action(
        &self,
        action_id: &str,
        request: &ContextMenuRequest,
        state: &mut GridState,
        cx: &mut gpui::App,
    ) {
    }
}

/// Type-erased handle wrapping an `Arc<dyn ContextMenuProvider>`. Stored on
/// `GridState` and cloned into event closures.
#[derive(Clone)]
pub(crate) struct ContextMenuProviderHandle(Arc<dyn ContextMenuProvider>);

impl ContextMenuProviderHandle {
    pub(crate) fn new(provider: impl ContextMenuProvider + 'static) -> Self {
        Self(Arc::new(provider))
    }
}

impl fmt::Debug for ContextMenuProviderHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ContextMenuProviderHandle")
            .finish_non_exhaustive()
    }
}

impl std::ops::Deref for ContextMenuProviderHandle {
    type Target = dyn ContextMenuProvider;

    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

/// Deferred custom context-menu action, flushed at the top of `render`.
#[derive(Clone, Debug)]
pub(crate) struct PendingCustomContextMenuAction {
    pub id: String,
    pub request: ContextMenuRequest,
}

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

    fn row(name: &str, values: &[CellValue]) -> SelectedRowContext {
        let columns = vec![
            ColumnContext {
                index: 0,
                name: "id".into(),
                kind: ColumnKind::Integer,
            },
            ColumnContext {
                index: 1,
                name: name.into(),
                kind: ColumnKind::Text,
            },
        ];
        SelectedRowContext {
            display_row_index: 0,
            source_row_index: 0,
            values: values.to_vec(),
            columns,
        }
    }

    #[test]
    fn value_at_returns_by_ordinal() {
        let r = row(
            "name",
            &[CellValue::Integer(7), CellValue::Text("hi".into())],
        );
        assert_eq!(r.value_at(0), Some(&CellValue::Integer(7)));
        assert_eq!(r.value_at(1), Some(&CellValue::Text("hi".into())));
        assert_eq!(r.value_at(2), None);
    }

    #[test]
    fn value_by_name_exact_case_sensitive() {
        let r = row(
            "Name",
            &[CellValue::Integer(7), CellValue::Text("hi".into())],
        );
        assert_eq!(r.value_by_name("Name"), Some(&CellValue::Text("hi".into())));
        assert_eq!(r.value_by_name("name"), None);
        assert_eq!(r.value_by_name("NAME"), None);
    }

    #[test]
    fn value_by_name_first_duplicate_wins() {
        let columns = vec![
            ColumnContext {
                index: 0,
                name: "dup".into(),
                kind: ColumnKind::Integer,
            },
            ColumnContext {
                index: 1,
                name: "dup".into(),
                kind: ColumnKind::Integer,
            },
        ];
        let r = SelectedRowContext {
            display_row_index: 0,
            source_row_index: 0,
            values: vec![CellValue::Integer(1), CellValue::Integer(2)],
            columns,
        };
        assert_eq!(r.value_by_name("dup"), Some(&CellValue::Integer(1)));
        assert_eq!(r.column_index("dup"), Some(0));
    }

    #[test]
    fn named_values_iterates_all_columns() {
        let r = row(
            "name",
            &[CellValue::Integer(7), CellValue::Text("hi".into())],
        );
        let pairs: Vec<_> = r.named_values().collect();
        assert_eq!(pairs.len(), 2);
        assert_eq!(pairs[0].0, "id");
        assert_eq!(pairs[0].1, &CellValue::Integer(7));
        assert_eq!(pairs[1].0, "name");
        assert_eq!(pairs[1].1, &CellValue::Text("hi".into()));
    }

    #[test]
    fn context_menu_target_column_index() {
        assert_eq!(
            ContextMenuTarget::Cell {
                display_row_index: 0,
                source_row_index: 0,
                column_index: 3
            }
            .column_index(),
            Some(3)
        );
        assert_eq!(
            ContextMenuTarget::RowHeader {
                display_row_index: 0,
                source_row_index: 0
            }
            .column_index(),
            None
        );
    }

    #[test]
    fn context_menu_target_display_row_index() {
        assert_eq!(
            ContextMenuTarget::Cell {
                display_row_index: 5,
                source_row_index: 2,
                column_index: 0
            }
            .display_row_index(),
            Some(5)
        );
        assert_eq!(
            ContextMenuTarget::ColumnHeader { column_index: 1 }.display_row_index(),
            None
        );
    }

    #[test]
    fn standard_column_header_items_match_builtin_order() {
        let items = ContextMenuItem::standard_column_header_items();
        assert_eq!(items.len(), 10);
        assert!(matches!(
            items[0],
            ContextMenuItem::BuiltIn(MenuAction::SelectColumn)
        ));
        assert!(matches!(items[3], ContextMenuItem::Separator));
        assert!(matches!(
            items[9],
            ContextMenuItem::BuiltIn(MenuAction::ClearFilter)
        ));
    }

    fn cols() -> Arc<[ColumnContext]> {
        Arc::from(vec![
            ColumnContext {
                index: 0,
                name: "a".into(),
                kind: ColumnKind::Integer,
            },
            ColumnContext {
                index: 1,
                name: "b".into(),
                kind: ColumnKind::Text,
            },
        ])
    }

    fn sel(r1: usize, c1: usize, r2: usize, c2: usize) -> ContextMenuSelection {
        ContextMenuSelection {
            row_start: r1,
            row_end: r2,
            column_start: c1,
            column_end: c2,
        }
    }

    #[test]
    fn clicked_cell_finds_target_cell() {
        let rows = Arc::new(vec![
            vec![CellValue::Integer(1), CellValue::Text("x".into())],
            vec![CellValue::Integer(2), CellValue::Text("y".into())],
            vec![CellValue::Integer(3), CellValue::Text("z".into())],
        ]);
        // display order maps display row 1 -> source row 2
        let display = Arc::new(vec![0usize, 2usize]);
        let request = ContextMenuRequest::new(
            ContextMenuTarget::Cell {
                display_row_index: 1,
                source_row_index: 2,
                column_index: 0,
            },
            Some(sel(0, 0, 1, 1)),
            rows,
            display,
            cols(),
            false,
        );
        let clicked = request.clicked_cell().unwrap();
        assert_eq!(clicked.source_row_index, 2);
        assert_eq!(clicked.value, CellValue::Integer(3));
    }

    #[test]
    fn clicked_cell_none_for_column_header_target() {
        let request = ContextMenuRequest::new(
            ContextMenuTarget::ColumnHeader { column_index: 0 },
            None,
            Arc::new(vec![]),
            Arc::new(vec![]),
            cols(),
            true,
        );
        assert!(request.clicked_cell().is_none());
    }

    #[test]
    fn clicked_row_finds_target_for_row_header() {
        let rows = Arc::new(vec![
            vec![CellValue::Integer(1), CellValue::Text("x".into())],
            vec![CellValue::Integer(2), CellValue::Text("y".into())],
            vec![CellValue::Integer(3), CellValue::Text("z".into())],
        ]);
        let display = Arc::new(vec![0usize, 2usize]);
        let request = ContextMenuRequest::new(
            ContextMenuTarget::RowHeader {
                display_row_index: 1,
                source_row_index: 2,
            },
            Some(sel(0, 0, 1, 1)),
            rows,
            display,
            cols(),
            false,
        );
        let clicked = request.clicked_row().unwrap();
        assert_eq!(clicked.source_row_index, 2);
        assert_eq!(
            clicked.values,
            vec![CellValue::Integer(3), CellValue::Text("z".into())]
        );
    }

    #[test]
    fn clicked_row_none_for_column_header() {
        let request = ContextMenuRequest::new(
            ContextMenuTarget::ColumnHeader { column_index: 0 },
            None,
            Arc::new(vec![]),
            Arc::new(vec![]),
            cols(),
            true,
        );
        assert!(request.clicked_row().is_none());
    }

    #[test]
    fn counts_are_computed_from_bounds() {
        let rows = Arc::new(vec![
            vec![CellValue::Integer(1), CellValue::Text("x".into())],
            vec![CellValue::Integer(2), CellValue::Text("y".into())],
        ]);
        let display = Arc::new(vec![0usize, 1usize]);
        let request = ContextMenuRequest::new(
            ContextMenuTarget::Cell {
                display_row_index: 0,
                source_row_index: 0,
                column_index: 0,
            },
            Some(sel(0, 0, 1, 1)),
            rows,
            display,
            cols(),
            false,
        );
        assert_eq!(request.selected_cell_count(), 4);
        assert_eq!(request.selected_row_count(), 2);
        assert_eq!(request.selected_cells().len(), 4);
        assert_eq!(request.selected_rows().len(), 2);
    }

    #[test]
    fn column_oriented_has_no_rows() {
        let rows = Arc::new(vec![
            vec![CellValue::Integer(1), CellValue::Text("x".into())],
            vec![CellValue::Integer(2), CellValue::Text("y".into())],
        ]);
        let display = Arc::new(vec![0usize, 1usize]);
        let request = ContextMenuRequest::new(
            ContextMenuTarget::ColumnHeader { column_index: 0 },
            Some(sel(0, 0, 1, 0)),
            rows,
            display,
            cols(),
            true,
        );
        assert_eq!(request.selected_row_count(), 0);
        assert!(request.selected_rows().is_empty());
        // cells for the column are still available
        assert_eq!(request.selected_cell_count(), 2);
        assert_eq!(request.selected_cells().len(), 2);
    }
}