Skip to main content

subspace_dashboard/
row_menu.rs

1//! The right-click menu: every context menu is built from the same seven
2//! groups in the same order ([`MenuGroup`]), with a separator between groups
3//! that have commands. A board fills groups in with [`MenuCommand`]s; it
4//! never orders them, and a group with nothing in it is left out.
5//! [`build`] turns a [`GroupedMenu`] into GPUI Kit's `PopupMenu`.
6//!
7//! A list row, a group header or the detail panel says what it is
8//! ([`RowMenu`]); which standard commands that earns is a pure decision
9//! ([`row_menu_items`], [`panel_menu_items`]) the app and the boards share,
10//! and [`grouped`] turns it into commands.
11
12mod groups;
13mod render;
14
15pub use groups::{GroupedMenu, MenuCommand, MenuGroup, MenuLine};
16pub use render::build;
17
18use std::rc::Rc;
19
20use gpui_kit::SharedString;
21use subspace_lucide::IconName;
22
23use crate::links::{self, safe_url};
24use crate::{Activate, AddSelectionToChat, AddToChat, Callback, Row, set_selection};
25
26/// Whether a menu offers to send what it shows to the chat. Menus offer it
27/// unless their board keeps its content out of chat.
28#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
29pub enum MenuChat {
30    #[default]
31    Offered,
32    /// Leaves out Add to chat and Add selection to chat.
33    Off,
34}
35
36/// What a dashboard knows about the row the menu was opened over. Only the
37/// facts a dashboard already has: nothing here makes a service call.
38#[derive(Debug, Clone, Default, PartialEq, Eq)]
39pub struct RowMenu {
40    /// The row's title, for Copy title.
41    pub title: SharedString,
42    /// The short identifier the row shows, such as `1258950`.
43    pub id: Option<SharedString>,
44    /// The item's page in its service. Only `http` and `https` links are
45    /// kept, so a menu never offers to open anything else.
46    pub url: Option<SharedString>,
47    /// The service the link belongs to, for "Open in GitHub".
48    pub service: Option<SharedString>,
49    /// Whether the row has details to open, which is Enter's action.
50    pub opens_details: bool,
51    /// Whether the menu offers the chat entries.
52    pub chat: MenuChat,
53}
54
55impl RowMenu {
56    pub fn new(title: impl Into<SharedString>) -> Self {
57        Self {
58            title: title.into(),
59            ..Self::default()
60        }
61    }
62
63    /// The default for a list row: its title and id, with details to open.
64    pub fn from_row(row: &Row) -> Self {
65        Self {
66            title: row.title.clone(),
67            id: row.id.clone(),
68            url: None,
69            service: None,
70            opens_details: true,
71            chat: MenuChat::Offered,
72        }
73    }
74
75    pub fn id(mut self, id: impl Into<SharedString>) -> Self {
76        self.id = Some(id.into());
77        self
78    }
79
80    /// The item's page in `service`. A link that is not `http` or `https` is
81    /// dropped, so Open and Copy link never offer it.
82    pub fn link(mut self, service: impl Into<SharedString>, url: &str) -> Self {
83        self.url = browser_url(url).map(SharedString::from);
84        self.service = Some(service.into());
85        self
86    }
87
88    pub fn opens_details(mut self, opens: bool) -> Self {
89        self.opens_details = opens;
90        self
91    }
92}
93
94/// A link a browser may open: `http` or `https` only.
95fn browser_url(url: &str) -> Option<String> {
96    safe_url(url).filter(|url| url.starts_with("http://") || url.starts_with("https://"))
97}
98
99/// One of the standard commands a row, a group header or the detail panel
100/// offers.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub enum RowMenuItem {
103    /// The row's Enter action, "Open".
104    OpenDetails,
105    OpenInBrowser {
106        label: SharedString,
107        url: SharedString,
108    },
109    /// The text selected in the detail panel.
110    CopySelection,
111    CopyLink(SharedString),
112    CopyTitle(SharedString),
113    CopyId(SharedString),
114    /// The whole row and its open details, through the shell's `AddToChat`.
115    AddToChat,
116    AddSelectionToChat,
117}
118
119impl RowMenuItem {
120    /// The group the command belongs to.
121    pub fn group(&self) -> MenuGroup {
122        match self {
123            Self::OpenDetails | Self::OpenInBrowser { .. } => MenuGroup::Open,
124            Self::CopySelection | Self::CopyLink(_) | Self::CopyTitle(_) | Self::CopyId(_) => {
125                MenuGroup::Copy
126            }
127            Self::AddToChat | Self::AddSelectionToChat => MenuGroup::Chat,
128        }
129    }
130
131    /// Whether the command acts on the list's selected line rather than on
132    /// facts it carries: Open runs the selected line's Enter action, and the
133    /// shell's Add to chat sends the selected line.
134    pub(crate) fn acts_on_selection(&self) -> bool {
135        matches!(
136            self,
137            Self::OpenDetails | Self::AddToChat | Self::AddSelectionToChat
138        )
139    }
140}
141
142/// What a row's menu offers, in menu order: opening it, the copies, then
143/// the chat. A row offers the chat unless its board turned it off and, when
144/// it has one, its title.
145pub fn row_menu_items(facts: &RowMenu) -> Vec<RowMenuItem> {
146    let mut items = opening_items(facts, facts.opens_details);
147    items.extend(copy_items(facts));
148    items.extend(chat_items(facts.chat));
149    items
150}
151
152/// What the detail panel's menu offers, in menu order: the service's page,
153/// Copy for the selection with the item's copies, then the chat. The panel
154/// is already open, so it never offers to open its own details.
155pub fn panel_menu_items(facts: &RowMenu, selection: &str) -> Vec<RowMenuItem> {
156    let selected = !selection.trim().is_empty();
157    let mut items = opening_items(facts, false);
158    if selected {
159        items.push(RowMenuItem::CopySelection);
160    }
161    items.extend(copy_items(facts));
162    items.extend(chat_items(facts.chat));
163    if selected && facts.chat == MenuChat::Offered {
164        items.push(RowMenuItem::AddSelectionToChat);
165    }
166    items
167}
168
169/// Add to chat, when the menu offers the chat.
170fn chat_items(chat: MenuChat) -> Vec<RowMenuItem> {
171    match chat {
172        MenuChat::Offered => vec![RowMenuItem::AddToChat],
173        MenuChat::Off => Vec::new(),
174    }
175}
176
177/// Open and Open in the service's site, when either applies.
178fn opening_items(facts: &RowMenu, details: bool) -> Vec<RowMenuItem> {
179    let mut items = Vec::new();
180    if details {
181        items.push(RowMenuItem::OpenDetails);
182    }
183    if let Some(url) = &facts.url {
184        let service = facts.service.clone().unwrap_or_else(|| "browser".into());
185        items.push(RowMenuItem::OpenInBrowser {
186            label: format!("Open in {service}").into(),
187            url: url.clone(),
188        });
189    }
190    items
191}
192
193/// Copy link, title and id, for whichever the row has.
194fn copy_items(facts: &RowMenu) -> Vec<RowMenuItem> {
195    let mut items = Vec::new();
196    if let Some(url) = &facts.url {
197        items.push(RowMenuItem::CopyLink(url.clone()));
198    }
199    if !facts.title.trim().is_empty() {
200        items.push(RowMenuItem::CopyTitle(facts.title.clone()));
201    }
202    if let Some(id) = facts.id.clone().filter(|id| !id.trim().is_empty()) {
203        items.push(RowMenuItem::CopyId(id));
204    }
205    items
206}
207
208/// The commands `items` stand for, in their groups. `open` is the row's
209/// Enter action, which only a caller that has a row can give; without it
210/// the menu has no Open.
211pub fn grouped(items: Vec<RowMenuItem>, open: Option<Callback>) -> GroupedMenu {
212    let mut menu = GroupedMenu::new();
213    menu.extend(
214        items
215            .into_iter()
216            .filter_map(|item| command(item, open.clone())),
217    );
218    menu
219}
220
221/// The commands `items` stand for, for a line the list could not select:
222/// those that act on the selected line stay in their places, disabled, with
223/// `reason` under them, so they never act on another line.
224pub(crate) fn grouped_unselected(items: Vec<RowMenuItem>, reason: &SharedString) -> GroupedMenu {
225    let inert: Callback = Rc::new(|_, _| {});
226    let mut menu = GroupedMenu::new();
227    menu.extend(items.into_iter().filter_map(|item| {
228        let blocked = item.acts_on_selection();
229        command(item, Some(inert.clone())).map(|command| command.disabled(blocked, reason.clone()))
230    }));
231    menu
232}
233
234/// One standard command, with its glyph.
235fn command(item: RowMenuItem, open: Option<Callback>) -> Option<MenuCommand> {
236    let group = item.group();
237    Some(match item {
238        RowMenuItem::OpenDetails => {
239            let open = open?;
240            MenuCommand::new(group, "Open", IconName::ArrowRight, move |window, cx| {
241                open(window, cx)
242            })
243            .key(Activate)
244        }
245        RowMenuItem::OpenInBrowser { label, url } => {
246            MenuCommand::new(group, label, IconName::ArrowUpRight, move |_, cx| {
247                links::open(&url, cx);
248            })
249        }
250        // An empty text copies the window's selection.
251        RowMenuItem::CopySelection => copy_command("Copy", IconName::Copy, String::new()),
252        RowMenuItem::CopyLink(url) => copy_command("Copy link", IconName::Link, url.to_string()),
253        RowMenuItem::CopyTitle(title) => {
254            copy_command("Copy title", IconName::Copy, title.to_string())
255        }
256        RowMenuItem::CopyId(id) => copy_command("Copy id", IconName::Copy, id.to_string()),
257        // The action carries its own key hint, and the shell handles it.
258        RowMenuItem::AddToChat => {
259            MenuCommand::action(group, "Add to chat", IconName::MessageSquarePlus, AddToChat)
260        }
261        RowMenuItem::AddSelectionToChat => MenuCommand::action(
262            group,
263            "Add selection to chat",
264            IconName::MessageSquareQuote,
265            AddSelectionToChat,
266        ),
267    })
268}
269
270/// Copies `text`, or the window's selection when `text` is empty, which is
271/// what the panel's Copy does.
272fn copy_command(label: &'static str, icon: IconName, text: String) -> MenuCommand {
273    MenuCommand::new(MenuGroup::Copy, label, icon, move |window, cx| {
274        let text = match text.is_empty() {
275            true => gpui_kit::base::TextSelection::selected_text(window, cx),
276            false => text.clone(),
277        };
278        links::copy(text, cx);
279    })
280}
281
282/// Holds the window's selection for the shell's `AddSelectionToChat`, which
283/// runs after the menu dismisses and cannot read it then.
284pub fn hold_selection(window: &mut gpui_kit::Window, cx: &mut gpui_kit::App) -> String {
285    let text = gpui_kit::base::TextSelection::selected_text(window, cx);
286    set_selection(cx, text.clone());
287    text
288}
289
290#[cfg(test)]
291mod tests;