Skip to main content

subspace_dashboard/
palette.rs

1//! The commands and item search a dashboard offers the ⌘K palette.
2
3use std::rc::Rc;
4
5use gpui_kit::{Action, App, SharedString, Window};
6
7use crate::{Row, SearchDoc, SearchIndex};
8
9pub type Callback = Rc<dyn Fn(&mut Window, &mut App)>;
10pub type PickCallback = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
11
12/// One choice in a command's sub-list.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct PaletteOption {
15    pub value: SharedString,
16    pub label: SharedString,
17    pub hint: Option<SharedString>,
18    pub checked: bool,
19}
20
21impl PaletteOption {
22    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
23        Self {
24            value: value.into(),
25            label: label.into(),
26            hint: None,
27            checked: false,
28        }
29    }
30
31    pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
32        self.hint = Some(hint.into());
33        self
34    }
35
36    pub fn checked(mut self, checked: bool) -> Self {
37        self.checked = checked;
38        self
39    }
40}
41
42/// A second step, such as the sprint or team list, shown in place of the
43/// palette's root list. Picking an option closes the palette and calls
44/// `on_pick` with the option's value.
45pub struct SubList {
46    pub placeholder: SharedString,
47    pub options: Vec<PaletteOption>,
48    pub on_pick: PickCallback,
49}
50
51impl SubList {
52    pub fn new(
53        placeholder: impl Into<SharedString>,
54        options: Vec<PaletteOption>,
55        on_pick: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
56    ) -> Self {
57        Self {
58            placeholder: placeholder.into(),
59            options,
60            on_pick: Rc::new(on_pick),
61        }
62    }
63}
64
65/// What a palette command does.
66pub enum CommandRun {
67    /// Dispatch the action to the focused dashboard's view, like a key.
68    Action(Box<dyn Action>),
69    Callback(Callback),
70    Sub(Rc<SubList>),
71}
72
73impl Clone for CommandRun {
74    fn clone(&self) -> Self {
75        match self {
76            Self::Action(action) => Self::Action(action.boxed_clone()),
77            Self::Callback(callback) => Self::Callback(callback.clone()),
78            Self::Sub(sub) => Self::Sub(sub.clone()),
79        }
80    }
81}
82
83/// A palette command a dashboard offers.
84#[derive(Clone)]
85pub struct PaletteCommand {
86    pub label: SharedString,
87    /// Extra words the palette matches, separated by spaces.
88    pub keywords: SharedString,
89    /// The key that does the same, shown at the right.
90    pub shortcut: Option<SharedString>,
91    pub run: CommandRun,
92    /// What the palette's recent commands store for this command, when its
93    /// label changes with state, such as *Back to #discovery*. `None`
94    /// stores the label.
95    pub recent_key: Option<SharedString>,
96}
97
98impl PaletteCommand {
99    /// A command that dispatches `action` to the dashboard's view, so the
100    /// dashboard handles it with `on_action` like a key.
101    pub fn new(label: impl Into<SharedString>, action: impl Action) -> Self {
102        Self::with_run(label, CommandRun::Action(Box::new(action)))
103    }
104
105    /// A command that calls `run`. Capture `cx.entity().downgrade()` to
106    /// reach the dashboard.
107    pub fn callback(
108        label: impl Into<SharedString>,
109        run: impl Fn(&mut Window, &mut App) + 'static,
110    ) -> Self {
111        Self::with_run(label, CommandRun::Callback(Rc::new(run)))
112    }
113
114    /// A command that shows `sub` in place of the palette's list.
115    pub fn sub(label: impl Into<SharedString>, sub: SubList) -> Self {
116        Self::with_run(label, CommandRun::Sub(Rc::new(sub)))
117    }
118
119    fn with_run(label: impl Into<SharedString>, run: CommandRun) -> Self {
120        Self {
121            label: label.into(),
122            keywords: SharedString::default(),
123            shortcut: None,
124            run,
125            recent_key: None,
126        }
127    }
128
129    pub fn keywords(mut self, keywords: impl Into<SharedString>) -> Self {
130        self.keywords = keywords.into();
131        self
132    }
133
134    pub fn shortcut(mut self, shortcut: impl Into<SharedString>) -> Self {
135        self.shortcut = Some(shortcut.into());
136        self
137    }
138}
139
140impl std::fmt::Debug for PaletteCommand {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        let run = match &self.run {
143            CommandRun::Action(action) => action.name(),
144            CommandRun::Callback(_) => "callback",
145            CommandRun::Sub(_) => "sub-list",
146        };
147        f.debug_struct("PaletteCommand")
148            .field("label", &self.label)
149            .field("run", &run)
150            .finish()
151    }
152}
153
154// ---- Item search ------------------------------------------------------------------
155
156/// A dashboard's loaded items, indexed for the palette (REQ-05). Build it
157/// again when the items change; searching makes no request.
158pub struct ItemSearch {
159    index: SearchIndex,
160    rows: Vec<Row>,
161}
162
163impl ItemSearch {
164    /// Each item's search document and the row the palette shows for it.
165    pub fn new(items: impl IntoIterator<Item = (SearchDoc, Row)>) -> Self {
166        let (docs, rows) = items.into_iter().unzip();
167        Self {
168            index: SearchIndex::new(docs),
169            rows,
170        }
171    }
172
173    /// The best `limit` items for `query`, best first.
174    pub fn search(&self, query: &str, limit: usize) -> Vec<(&SearchDoc, &Row)> {
175        self.index
176            .search(query, limit)
177            .into_iter()
178            .map(|hit| (&self.index.docs()[hit.index], &self.rows[hit.index]))
179            .collect()
180    }
181
182    /// The item with document id `id`.
183    pub fn find(&self, id: &str) -> Option<(&SearchDoc, &Row)> {
184        let at = self.index.docs().iter().position(|doc| doc.id == id)?;
185        Some((&self.index.docs()[at], &self.rows[at]))
186    }
187
188    pub fn is_empty(&self) -> bool {
189        self.index.is_empty()
190    }
191}
192
193/// What `/` searches in a dashboard.
194#[derive(Clone)]
195pub struct Search {
196    /// Such as "Search this board"; also the help text for `/`.
197    pub placeholder: SharedString,
198    pub items: Rc<ItemSearch>,
199}