Visual Studio Code, rebuilt in Rust
Rust
feat(scm): offer history item ref actions per ref in the graph menu
rokartur620e0bac3335
diff --git a/native/crates/app/src/menus.rs b/native/crates/app/src/menus.rsindex f0ba66c986f..56be6b1f766 100644--- a/native/crates/app/src/menus.rs+++ b/native/crates/app/src/menus.rs@@ -95,6 +95,10 @@ pub enum MenuId {ScmHistoryTitle,ScmHistoryItemContext,ScmHistoryItemChangeContext,+ /// `MenuId.SCMHistoryItemRefContext`: read per ref by a history item's context menu, never shown itself.+ ScmHistoryItemRefContext,+ /// `MenuId.for(actionId)`: the refs submenu of the `index`th `ScmHistoryItemRefContext` item.+ ScmHistoryItemRefAction(usize),ScmChangeContext,DiffEditorHunkToolbar,/// `MenuId.MultiDiffEditorFileToolbar`: a multi diff editor file header's toolbar.@@ -876,7 +880,7 @@ pub fn workbench_menus() -> Vec<MenuItem> {/// menusExtensionPoint.ts `apiMenus`: the `contributes.menus` keys of the menus the port shows. `commandPalette`/// is read by `command_palette::menu`.-const API_MENUS: [(&str, MenuId); 45] = [+const API_MENUS: [(&str, MenuId); 46] = [("file/newFile", MenuId::NewFile),("editor/context", MenuId::EditorContext),("explorer/context", MenuId::ExplorerContext),@@ -902,6 +906,7 @@ const API_MENUS: [(&str, MenuId); 45] = [("scm/artifact/context", MenuId::ScmArtifactContext),("scm/history/title", MenuId::ScmHistoryTitle),("scm/historyItem/context", MenuId::ScmHistoryItemContext),+ ("scm/historyItemRef/context", MenuId::ScmHistoryItemRefContext),("timeline/title", MenuId::TimelineTitle),("timeline/item/context", MenuId::TimelineItemContext),("testing/item/context", MenuId::TestItem),@@ -1022,6 +1027,7 @@ pub fn extension_menus(extensions: &[ScannedExtension]) -> Vec<MenuItem> {let proposal = match key.as_str() {"editor/content" => Some("contribEditorContentMenu"),"commentsView/commentThread/context" => Some("contribCommentsViewThreadMenus"),+ "scm/historyItemRef/context" => Some("contribSourceControlHistoryItemMenu"),_ => None,};if let Some(proposal) = proposal.filter(|proposal| !extension.description["enabledApiProposals"].as_array().is_some_and(|proposals| proposals.iter().any(|enabled| enabled == proposal))) {diff --git a/native/crates/app/src/menus/tests.rs b/native/crates/app/src/menus/tests.rsindex b27f615fc18..a9227fe123e 100644--- a/native/crates/app/src/menus/tests.rs+++ b/native/crates/app/src/menus/tests.rs@@ -185,9 +185,12 @@ fn api_menu_keys_reach_their_menus() {("terminal/context", MenuId::TerminalInstanceContext),("terminal/title/context", MenuId::TerminalTabContext),("scm/resourceFolder/context", MenuId::ScmResourceFolderContext),+ ("scm/historyItemRef/context", MenuId::ScmHistoryItemRefContext),];for (key, menu) in keys {- let items = extension_menus(&[extension("k", json!({ "commands": [{ "command": "k.run", "title": "Run" }], "menus": { key: [{ "command": "k.run" }] } }))]);+ let mut contributor = extension("k", json!({ "commands": [{ "command": "k.run", "title": "Run" }], "menus": { key: [{ "command": "k.run" }] } }));+ contributor.description["enabledApiProposals"] = json!(["contribSourceControlHistoryItemMenu"]);+ let items = extension_menus(&[contributor]);let reached: Vec<_> = items.iter().map(|item| item.menu).collect();assert_eq!(reached, [menu], "{key}");}diff --git a/native/crates/app/src/workbench/scm_actions.rs b/native/crates/app/src/workbench/scm_actions.rsindex 22fa7c87d68..7c479fc1dec 100644--- a/native/crates/app/src/workbench/scm_actions.rs+++ b/native/crates/app/src/workbench/scm_actions.rs@@ -20,7 +20,7 @@ use crate::commands::Outcome;use crate::contextkey::Expr;use crate::menus::{CommandIcon, Entry, MenuAction, MenuId, MenuItem, Toggled, menu_actions};use crate::scm::Provider;-use crate::scm_history::{HistoryItem, HistoryItemKind, SCM_INCOMING_HISTORY_ITEM_ID, SCM_OUTGOING_HISTORY_ITEM_ID};+use crate::scm_history::{HistoryItem, HistoryItemKind, HistoryItemRef, SCM_INCOMING_HISTORY_ITEM_ID, SCM_OUTGOING_HISTORY_ITEM_ID};const VIEW_PANE_ID: &str = "workbench.scm";const HISTORY_VIEW_PANE_ID: &str = "workbench.scm.history";@@ -572,12 +572,53 @@ impl Workbench {let current = self.scm_graph.refs[0].as_ref().map(|reference| reference.id.as_str());context.insert("scmHistoryItemHasCurrentHistoryItemRef".into(), json!(history_item.references.iter().any(|reference| Some(reference.id.as_str()) == current)));let args = vec![Self::provider_arg(provider), history_item_arg(history_item)];- let id = history_item.id.clone();- self.scm_graph.selected = Some(id);- let actions = self.menu_actions_outside(MenuId::ScmHistoryItemContext, "inline", &context);+ let references = history_item.references.clone();+ self.scm_graph.selected = Some(history_item.id.clone());+ let mut registry: Vec<MenuItem> = self.menus.iter().filter(|item| item.menu != MenuId::ScmHistoryItemContext || item.group != "inline").cloned().collect();+ registry.extend(self.register_scm_history_item_ref_actions(&references, &context));+ let actions = menu_actions(®istry, MenuId::ScmHistoryItemContext, &context);self.show_context_menu_actions(actions, &context, Bounds::new(position, Default::default()), args, window, cx);}+ /// `_onContextMenu`'s history item refs: each `MenuId.SCMHistoryItemRefContext` command that some of the item's refs+ /// show becomes a submenu of those refs, each running the command with the ref id after the menu's arguments.+ /// Returns the submenus' menu items; the commands of the previous menu are disposed.+ fn register_scm_history_item_ref_actions(&mut self, references: &[HistoryItemRef], context: &HashMap<String, Value>) -> Vec<MenuItem> {+ for (id, registration) in std::mem::take(&mut self.scm_graph.ref_commands) {+ self.commands.dispose(&id, registration);+ }+ let mut refs_by_action: HashMap<String, Vec<&HistoryItemRef>> = HashMap::new();+ for reference in references {+ let mut overlay = context.clone();+ overlay.insert("scmHistoryItemRef".into(), json!(reference.id));+ for action in menu_actions(&self.menus, MenuId::ScmHistoryItemRefContext, &overlay) {+ if let MenuAction::Command { id, .. } = action {+ refs_by_action.entry(id).or_default().push(reference);+ }+ }+ }+ let ref_menu_items: Vec<MenuItem> = self.menus.iter().filter(|item| item.menu == MenuId::ScmHistoryItemRefContext).cloned().collect();+ let mut items = Vec::new();+ for (index, item) in ref_menu_items.into_iter().enumerate() {+ let Entry::Command { id: action, .. } = &item.entry else { continue };+ let Some(refs) = refs_by_action.get(action) else { continue };+ let submenu = MenuId::ScmHistoryItemRefAction(index);+ items.push(MenuItem { menu: MenuId::ScmHistoryItemContext, entry: Entry::Submenu { submenu, toggled: None }, title: item.title.clone(), group: item.group.clone(), order: item.order, when: None });+ for reference in refs {+ let id = format!("{action}.{}", reference.id);+ let (action, ref_id) = (action.clone(), reference.id.clone());+ let registration = self.commands.register(id.clone(), move |workbench, mut args, window, cx| {+ args.push(json!(ref_id));+ workbench.execute_command(&action, args, window, cx)+ });+ self.scm_graph.ref_commands.push((id.clone(), registration));+ let group = reference.category.clone().unwrap_or_default();+ items.push(MenuItem { menu: submenu, entry: Entry::Command { id, precondition: None, toggled: None, alt: None }, title: reference.name.clone(), group, order: 0., when: None });+ }+ }+ items+ }+/// `_onContextMenu` of a history item change: `MenuId.SCMHistoryItemChangeContext` run with the item and the change.pub(super) fn show_scm_history_change_menu(&mut self, history_item: &HistoryItem, change: &Value, position: gpui::Point<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {let Some(provider) = self.active_scm_provider() else { return };diff --git a/native/crates/app/src/workbench/scm_actions/tests.rs b/native/crates/app/src/workbench/scm_actions/tests.rsindex 7f4d98d8211..122e6e2d9a5 100644--- a/native/crates/app/src/workbench/scm_actions/tests.rs+++ b/native/crates/app/src/workbench/scm_actions/tests.rs@@ -298,3 +298,47 @@ fn a_folder_row_shows_the_resource_folder_menu_with_its_resources(cx: &mut TestAassert_eq!(menu.args, [resource(1), resource(3)]);});}++/// scmHistoryViewPane.ts `_onContextMenu`: each `scm/historyItemRef/context` command the item's refs show is a+/// submenu of those refs, grouped by category, and an entry runs the command with the ref id last.+#[gpui::test]+fn a_history_item_menu_offers_each_ref_action_per_ref(cx: &mut TestAppContext) {+ use crate::menus::{Entry, MenuItem};+ use crate::scm_history::{HistoryItem, HistoryItemRef, to_history_item_view_models};+ let (workbench, _receiver, cx) = workbench_in("scm-history-item-refs", cx);+ request(&workbench, cx, "$registerSourceControl", register(0, "/w/repo"));+ let reference = |id: &str, name: &str, category: &str| HistoryItemRef { id: id.into(), name: name.into(), category: Some(category.into()), ..Default::default() };+ let item = HistoryItem { id: "a1".into(), subject: "init".into(), references: vec![reference("refs/heads/main", "main", "branches"), reference("refs/tags/v1", "v1", "tags")], ..Default::default() };+ let ran = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));+ workbench.update_in(cx, |workbench, window, cx| {+ let command = |id: &str| Entry::Command { id: id.into(), precondition: None, toggled: None, alt: None };+ workbench.menus.push(MenuItem { menu: MenuId::ScmHistoryItemRefContext, entry: command("git.graph.checkout"), title: "Checkout".into(), group: "1_checkout".into(), order: 1., when: None });+ let when = crate::contextkey::Expr::deserialize("scmHistoryItemRef == 'refs/heads/main'");+ workbench.menus.push(MenuItem { menu: MenuId::ScmHistoryItemRefContext, entry: command("git.graph.deleteBranch"), title: "Delete Branch".into(), group: "2_branch".into(), order: 2., when });+ let ran = ran.clone();+ workbench.commands.register("git.graph.checkout", move |_, args, _, _| {+ ran.borrow_mut().push(args);+ crate::commands::Outcome::done()+ });+ workbench.scm_graph.view_models = to_history_item_view_models(&[item], &Default::default(), None, None, None, false, false, None);+ workbench.show_scm_history_item_menu(0, 0, gpui::point(gpui::px(10.), gpui::px(10.)), window, cx);+ });+ let args = workbench.read_with(cx, |workbench, _| {+ let menu = workbench.context_menu.as_ref().expect("the history item's context menu opens");+ let submenus: Vec<(String, Vec<String>)> = menu.levels[0]+ .actions+ .iter()+ .filter_map(|action| match action {+ MenuAction::Submenu { title, actions, .. } => Some((title.clone(), actions.iter().map(|action| format!("{action:?}")).collect())),+ _ => None,+ })+ .collect();+ let [(checkout, refs), (delete, branch)] = &submenus[..] else { panic!("{submenus:?}") };+ assert_eq!((checkout.as_str(), delete.as_str()), ("Checkout", "Delete Branch"));+ assert!(matches!(&refs[..], [main, separator, tag] if main.contains("\"git.graph.checkout.refs/heads/main\"") && separator == "Separator" && tag.contains("title: \"v1\"")), "{refs:?}");+ assert!(matches!(&branch[..], [main] if main.contains("\"git.graph.deleteBranch.refs/heads/main\"")), "{branch:?}");+ menu.args.clone()+ });+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("git.graph.checkout.refs/tags/v1", args.clone(), window, cx)));+ assert_eq!(ran.borrow().as_slice(), [[args, vec![json!("refs/tags/v1")]].concat()]);+}diff --git a/native/crates/app/src/workbench/scm_graph_view.rs b/native/crates/app/src/workbench/scm_graph_view.rsindex 96ca436a9e5..90e8296b0de 100644--- a/native/crates/app/src/workbench/scm_graph_view.rs+++ b/native/crates/app/src/workbench/scm_graph_view.rs@@ -49,6 +49,8 @@ pub struct ScmGraph {pub(super) scroll: gpui::ScrollHandle,/// `_repositoryOutdated`: refs changed in the background while the list was scrolled down.pub(super) outdated: bool,+ /// The per-ref commands of the last history item menu (`_contextMenuDisposables`), disposed by the next one.+ pub(super) ref_commands: Vec<(String, crate::commands::Registration)>,}/// scmHistoryViewPane.ts `HistoryItemRefsFilter`: all refs, the current refs, or the refs by id.diff --git a/port/fixtures/ui-pair/m11/scm-history-item-refs.json b/port/fixtures/ui-pair/m11/scm-history-item-refs.jsonnew file mode 100644index 00000000000..73599e5a4e1--- /dev/null+++ b/port/fixtures/ui-pair/m11/scm-history-item-refs.json@@ -0,0 +1,12 @@+[+ {"hotkey": ["ctrl", "shift", "g"]},+ {"wait": 3000},+ {"rightClick": [90, 435], "foreground": true},+ {"wait": 1000},+ {"shot": "menu"},+ {"hover": [200, 182]},+ {"wait": 1000},+ {"shot": "delete-branch"},+ {"key": "escape"},+ {"wait": 500}+]diff --git a/port/ledger.md b/port/ledger.mdindex 663f33f0b07..44c1fb6699d 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -365,7 +365,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| workbench/parts/views | workbench part | M11 | verified | | Explorer views as panes (view_panes.rs): collapse by mouse and keys, sashes, header drag to reorder with drop overlay, state in workbench.explorer.views.state; no view actions, view menus or hidden views; cargo test -p app view_panes, ui-pair port/results/layout.md; pane headers drawn statically (workbench.rs section_header): no collapse, resize or view actions; verified: ui-pair port/results/references-view.md and every pair of port/results/windows.md (milestone 11 verification): the Explorer panes and contributed views as the reference; Explorer and Source Control views as panes of a ViewPaneContainer (view_panes.rs `PaneContainer`): collapse by mouse and keys, sashes, header drag to reorder with drop overlay, single view merged into the container, header actions, state in the container's storageId; cargo test -p app view_panes scm_container, ui-pair port/results/layout.md and port/fixtures/ui-pair/m11/scm-panes.json (port/notes.md View panes); verified: ui-pair port/results/references-view.md and every pair of port/results/windows.md (milestone 11 verification): the Explorer panes and contributed views as the reference; Run and Debug, Extensions and webview containers still draw section_header rows: no collapse, resize or view actions; welcome buttons draw their `$(icon)`s (cargo test -p app a_welcome_button_draws_its_label_icons; ui-pair port/fixtures/ui-pair/icons/scm-welcome.json: github's Publish to GitHub button with the github codicon as the reference); wrapped text stacks unsnapped 18.2px lines as Chromium (vendor gpui elements/text.rs; cargo test -p app wrapped_lines_keep_their_fractional_line_height): scm-welcome's Publish button 0.5pt from the reference, was 2.5pt; left: the port wraps "Git" of "To learn more about how to use Git" to the next line; a merged view's "..." puts the Views submenu, a separator and the view's own actions (panecomposite.ts `getSecondaryActions`; cargo test -p app a_merged_changes_view_shows_the_views_submenu_in_its_more_actions a_merged_view_without_actions_lists_the_view_toggles_flat) || workbench/services/accessibility | workbench service | M19 | verified | | electron-browser accessibilityService.ts over GPUI: screen reader attach follows Electron's `isAccessibilitySupportEnabled` on macOS (VoiceOver, or an assistive app setting AXManualAccessibility or AXEnhancedUserInterface, as cua-driver does; ui-pair screen-reader-detection.json with accessibility support auto shows the prompt in both), the Screen reader usage detected prompt and status entry; port/tools/a11y-check; cargo test -p app accessib; electron-browser accessibilityService.ts over GPUI: screen reader attach follows is_a11y_active, the Screen reader usage detected prompt and status entry; port/tools/a11y-check; cargo test -p app accessib || workbench/services/accounts | workbench service | | removed | | no sign-in/AI by decision (port/notes.md); not ported |-| workbench/services/actions | workbench service | M9 | ported | [3 L] contributes.menus: unmapped ids of menusExtensionPoint.ts, each needing its view's menu first (e.g. the debug variables and watch context menus with their built-in items): debug/*, scm/historyItemRef/context, testing/item/gutter, testing/profiles/context, testing/item/result, testing/message/context, testing/message/content, viewContainer/title, webview/context, extension/context, editor/title/run, modalEditor/editorTitle, editor/inlineCompletions/actions, diffEditor/gutter/selection, multiDiffEditor/content, notebook/cell/execute, notebook/kernelSource, notebook/variables/context, mergeEditor/result/title, comments/comment/editorActions, comments/commentThread/additionalActions, comments/commentThread/title/context, comments/commentThread/comment/context, issue/reporter, searchPanel/aiResults/commands, titleBar; chat/*, chatSessions/*, agents/*, editor/context/chat, ports/*, statusBar/remoteIndicator, menuBar/home class 4; touchBar class 2 | contributes.menus and contributes.submenus for editor/context, explorer/context, editor/title/context (menus::extension_menus): cargo test -p app menus explorer_actions; terminal/context and terminal/title/context (cargo test -p app api_menu_keys_reach_their_menus); ui-pair README.md Explorer menu (port/results/contextmenu.md); other menu ids wait for their views |+| workbench/services/actions | workbench service | M9 | ported | [3 L] contributes.menus: unmapped ids of menusExtensionPoint.ts, each needing its view's menu first (e.g. the debug variables and watch context menus with their built-in items): debug/*, testing/item/gutter, testing/profiles/context, testing/item/result, testing/message/context, testing/message/content, viewContainer/title, webview/context, extension/context, editor/title/run, modalEditor/editorTitle, editor/inlineCompletions/actions, diffEditor/gutter/selection, multiDiffEditor/content, notebook/cell/execute, notebook/kernelSource, notebook/variables/context, mergeEditor/result/title, comments/comment/editorActions, comments/commentThread/additionalActions, comments/commentThread/title/context, comments/commentThread/comment/context, issue/reporter, titleBar; ports/*, statusBar/remoteIndicator, menuBar/home class 4; touchBar class 2 | contributes.menus and contributes.submenus for editor/context, explorer/context, editor/title/context (menus::extension_menus): cargo test -p app menus explorer_actions; terminal/context, terminal/title/context, scm/resourceFolder/context and scm/historyItemRef/context (cargo test -p app api_menu_keys_reach_their_menus a_folder_row a_history_item_menu); the AI menu ids (chat/*, chatSessions/*, agents/*, agents/titleBar, editor/context/chat, searchPanel/aiResults/commands) removed by decision (port/notes.md:35); ui-pair README.md Explorer menu (port/results/contextmenu.md); other menu ids wait for their views || workbench/services/activity | workbench service | M11 | verified | | activity badges of view containers: view `$setBadge` values, the SCM and Extensions counts and `withProgress` progress badges (300 ms delay, kept 300 ms), numbers summed and shortened as compositeBarActions.ts (workbench/activity.rs; cargo test -p app -- activity progress_at_a_view_container_badges_its_activity_bar_item); `withCompositeProgress` progress bars of a container (side bar or panel title bottom) and of a view (pane header, merged title): `options.delay`, discrete worked of total, infinite, gone on done (progress_at_a_view_container_shows_its_progress_bar_under_the_title); ui-pair `activity-badge.json` on a git folder with two changes: the Source Control badge matches the reference (AE 1808 over the window, port/results/layout.md) || workbench/services/agentEditorComments | workbench service | | removed | | no sign-in/AI by decision (port/notes.md); not ported || workbench/services/agentHost | workbench service | | removed | | no sign-in/AI by decision (port/notes.md); not ported |