Skip to main content

subspace_dashboard/row_menu/
groups.rs

1//! The seven groups every context menu is built from, in the order every
2//! menu shows them. A board fills groups in; it never orders them, and a
3//! group with nothing in it is left out.
4
5use std::rc::Rc;
6
7use gpui_kit::component::menu::PopupMenu;
8use gpui_kit::{Action, App, Context, SharedString, Window};
9use subspace_lucide::IconName;
10
11use crate::Callback;
12
13/// Builds a submenu's entries in the submenu's own context.
14pub(super) type SubmenuBuilder =
15    Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>;
16
17/// Entries a board adds straight to the menu through the older
18/// `ListDashboard` hooks. They land at the end of [`MenuGroup::Act`].
19pub(crate) type Extension =
20    Box<dyn FnOnce(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>;
21
22/// A context menu's groups, in the order every menu shows them.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub enum MenuGroup {
25    /// The default action first ("Open", with Enter), then "Open in …".
26    Open,
27    /// The item's own verbs, with submenus for choices.
28    Act,
29    /// Copy (the selected text), Copy link, Copy title, Copy id.
30    Copy,
31    /// Add to chat, Add selection to chat.
32    Chat,
33    /// The container's commands, such as folding a group or closing a tab.
34    View,
35    /// Commands that remove or leave something, tinted as danger. An
36    /// ellipsis in the label means the command asks first.
37    Remove,
38    /// Settings for the place, such as "Space settings…".
39    Place,
40}
41
42impl MenuGroup {
43    /// Every group, in menu order.
44    pub const ORDER: [Self; 7] = [
45        Self::Open,
46        Self::Act,
47        Self::Copy,
48        Self::Chat,
49        Self::View,
50        Self::Remove,
51        Self::Place,
52    ];
53
54    /// Whether the group's commands remove or leave something, which the
55    /// menu tints in the theme's danger colour.
56    pub fn is_danger(self) -> bool {
57        self == Self::Remove
58    }
59}
60
61/// What choosing a command does.
62pub(super) enum Run {
63    Click(Callback),
64    /// Dispatches the action, as its key does.
65    Action(Box<dyn Action>),
66    Submenu(SubmenuBuilder),
67}
68
69/// One command in a context menu: its group, words and Lucide glyph, and
70/// what it does. A command that exists but cannot run now stays in the
71/// menu, disabled, with one line saying why.
72pub struct MenuCommand {
73    pub(super) group: MenuGroup,
74    pub(super) label: SharedString,
75    pub(super) icon: IconName,
76    pub(super) unavailable: Option<SharedString>,
77    pub(super) key: Option<Box<dyn Action>>,
78    pub(super) run: Run,
79}
80
81impl MenuCommand {
82    /// A command that calls `run`. Capture a weak handle to act on a board.
83    pub fn new(
84        group: MenuGroup,
85        label: impl Into<SharedString>,
86        icon: IconName,
87        run: impl Fn(&mut Window, &mut App) + 'static,
88    ) -> Self {
89        Self::with_run(group, label.into(), icon, Run::Click(Rc::new(run)))
90    }
91
92    /// A command that dispatches `action`, as its key does, and shows that
93    /// key.
94    pub fn action(
95        group: MenuGroup,
96        label: impl Into<SharedString>,
97        icon: IconName,
98        action: impl Action,
99    ) -> Self {
100        Self::with_run(group, label.into(), icon, Run::Action(Box::new(action)))
101    }
102
103    /// A submenu of choices, which `build` fills as it opens.
104    pub fn submenu(
105        group: MenuGroup,
106        label: impl Into<SharedString>,
107        icon: IconName,
108        build: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
109    ) -> Self {
110        Self::with_run(group, label.into(), icon, Run::Submenu(Rc::new(build)))
111    }
112
113    fn with_run(group: MenuGroup, label: SharedString, icon: IconName, run: Run) -> Self {
114        Self {
115            group,
116            label,
117            icon,
118            unavailable: None,
119            key: None,
120            run,
121        }
122    }
123
124    /// Shows the key bound to `action` beside the label, for a command
125    /// that does what that key does.
126    pub fn key(mut self, action: impl Action) -> Self {
127        self.key = Some(Box::new(action));
128        self
129    }
130
131    /// Disables the command when `disabled`, with `reason` on a line under
132    /// it, such as "The last open Space can't be closed."
133    pub fn disabled(mut self, disabled: bool, reason: impl Into<SharedString>) -> Self {
134        self.unavailable = disabled.then(|| reason.into());
135        self
136    }
137
138    pub fn group(&self) -> MenuGroup {
139        self.group
140    }
141
142    pub fn label(&self) -> &SharedString {
143        &self.label
144    }
145
146    /// Why the command cannot run now, when it is disabled.
147    pub fn reason(&self) -> Option<&SharedString> {
148        self.unavailable.as_ref()
149    }
150}
151
152/// The commands of one context menu, which [`super::build`] shows in
153/// [`MenuGroup::ORDER`] with a separator between groups that have any.
154#[derive(Default)]
155pub struct GroupedMenu {
156    pub(super) commands: Vec<MenuCommand>,
157    pub(super) extension: Option<Extension>,
158}
159
160impl GroupedMenu {
161    pub fn new() -> Self {
162        Self::default()
163    }
164
165    /// Adds `command` after the commands already in its group.
166    pub fn with(mut self, command: MenuCommand) -> Self {
167        self.commands.push(command);
168        self
169    }
170
171    pub fn push(&mut self, command: MenuCommand) {
172        self.commands.push(command);
173    }
174
175    pub fn is_empty(&self) -> bool {
176        self.commands.is_empty() && self.extension.is_none()
177    }
178
179    /// Entries added straight to the menu at the end of [`MenuGroup::Act`],
180    /// for the older `ListDashboard` hooks.
181    pub(crate) fn extend_act(mut self, extension: Extension) -> Self {
182        self.extension = Some(extension);
183        self
184    }
185
186    /// What the menu shows, line by line, without building it.
187    pub fn outline(&self) -> Vec<MenuLine> {
188        layout(&self.commands, self.extension.is_some())
189            .into_iter()
190            .map(|slot| outline_line(&self.commands, slot))
191            .collect()
192    }
193}
194
195impl Extend<MenuCommand> for GroupedMenu {
196    fn extend<I: IntoIterator<Item = MenuCommand>>(&mut self, commands: I) {
197        self.commands.extend(commands);
198    }
199}
200
201/// One line of a menu's [`GroupedMenu::outline`].
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub enum MenuLine {
204    Separator,
205    Command {
206        group: MenuGroup,
207        label: SharedString,
208        enabled: bool,
209        /// Tinted in the theme's danger colour.
210        danger: bool,
211    },
212    /// Why the command above cannot run now.
213    Reason(SharedString),
214    /// Entries a board adds straight to the menu.
215    Extension,
216}
217
218/// A line of the menu, by the index of its command.
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub(super) enum Slot {
221    Separator,
222    Command(usize),
223    Reason(SharedString),
224    Extension,
225}
226
227/// The menu's lines: the groups in order, each command followed by its
228/// reason when it is disabled, and a separator between groups that have
229/// lines. `extension` adds the board's own entries at the end of Act.
230pub(super) fn layout(commands: &[MenuCommand], extension: bool) -> Vec<Slot> {
231    let mut slots = Vec::new();
232    for group in MenuGroup::ORDER {
233        let extended = extension && group == MenuGroup::Act;
234        let members: Vec<usize> = (0..commands.len())
235            .filter(|index| commands[*index].group == group)
236            .collect();
237        if members.is_empty() && !extended {
238            continue;
239        }
240        if !slots.is_empty() {
241            slots.push(Slot::Separator);
242        }
243        for index in members {
244            slots.push(Slot::Command(index));
245            let reason = commands[index].unavailable.clone();
246            slots.extend(
247                reason
248                    .filter(|why| !why.trim().is_empty())
249                    .map(Slot::Reason),
250            );
251        }
252        if extended {
253            slots.push(Slot::Extension);
254        }
255    }
256    slots
257}
258
259fn outline_line(commands: &[MenuCommand], slot: Slot) -> MenuLine {
260    match slot {
261        Slot::Separator => MenuLine::Separator,
262        Slot::Reason(reason) => MenuLine::Reason(reason),
263        Slot::Extension => MenuLine::Extension,
264        Slot::Command(index) => {
265            let command = &commands[index];
266            let enabled = command.unavailable.is_none();
267            MenuLine::Command {
268                group: command.group,
269                label: command.label.clone(),
270                enabled,
271                danger: enabled && command.group.is_danger(),
272            }
273        }
274    }
275}