Skip to main content

gpui_kit_grid/state/editors/
checkbox.rs

1//! `CheckboxEditor`: a flag toggled at once, with no field.
2
3use gpui_kit::{App, Window};
4
5use crate::{
6    model::{CellValue, GridRow, OwnedValue},
7    state::edit::{CellEditor, EditInput, EditorOpen, EditorStart},
8};
9
10/// Toggles a `Bool` cell at once, with no field: F2, a double click on a
11/// `Text` column and a call commit the opposite value (`Bool(true)` for an
12/// empty cell) as `EditorOpen::Commit`, with no `EditStart`. Typing,
13/// Backspace and Delete take no edit. On a `Control` column the checkbox
14/// element toggles itself through
15/// [`CellElementContext::edit`](crate::CellElementContext::edit), Space
16/// included (`on_activate`).
17#[derive(Clone, Copy, Debug, Default)]
18pub struct CheckboxEditor;
19
20impl CheckboxEditor {
21    /// The value a start commits: the opposite of a flag, `true` for an
22    /// empty cell; `None` for another value or an input that takes no edit.
23    fn toggled(value: CellValue<'_>, input: &EditInput) -> Option<OwnedValue> {
24        if matches!(input, EditInput::Typing(_) | EditInput::Clear) {
25            return None;
26        }
27        match value {
28            CellValue::Bool(on) => Some(OwnedValue::Bool(!on)),
29            CellValue::Empty => Some(OwnedValue::Bool(true)),
30            _ => None,
31        }
32    }
33}
34
35impl<R: GridRow> CellEditor<R> for CheckboxEditor {
36    fn open(&self, start: &EditorStart<'_, R>, _: &mut Window, _: &mut App) -> EditorOpen {
37        Self::toggled(start.value(), start.input()).map_or(EditorOpen::Refuse, EditorOpen::Commit)
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn test_checkbox_toggles() {
47        let toggled = CheckboxEditor::toggled;
48        assert_eq!(
49            toggled(CellValue::Bool(false), &EditInput::Command),
50            Some(OwnedValue::Bool(true))
51        );
52        assert_eq!(
53            toggled(CellValue::Bool(true), &EditInput::Press { click_count: 2 }),
54            Some(OwnedValue::Bool(false))
55        );
56        assert_eq!(
57            toggled(CellValue::Empty, &EditInput::Programmatic),
58            Some(OwnedValue::Bool(true))
59        );
60        assert_eq!(toggled(CellValue::Bool(true), &EditInput::Clear), None);
61        assert_eq!(
62            toggled(CellValue::Bool(true), &EditInput::Typing("x".into())),
63            None
64        );
65        assert_eq!(toggled(CellValue::Int(1), &EditInput::Command), None);
66    }
67}