Visual Studio Code, rebuilt in Rust
Rust
feat(testing): filter the test explorer with a filter box
rokarturf08caaead4f2
diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rsindex a26c103546e..f35093adc13 100644--- a/native/crates/app/src/workbench.rs+++ b/native/crates/app/src/workbench.rs@@ -36,6 +36,7 @@ pub(crate) mod debug_service;pub(crate) mod debug_task_runner;mod debug_view;mod testing_continuous;+mod testing_filter;mod testing_item_menu;pub(crate) mod testing_service;mod testing_view;@@ -902,7 +903,7 @@ impl Workbench {refactor_preview: Default::default(),breakpoint_widget: None,testing: Default::default(),- testing_view: Default::default(),+ testing_view: testing_view::TestingView::new(cx),multi_diff_layout_logs: Vec::new(),multi_diff_sash: Default::default(),};diff --git a/native/crates/app/src/workbench/find_widget.rs b/native/crates/app/src/workbench/find_widget.rsindex 3969076241b..5c2ea55dcdd 100644--- a/native/crates/app/src/workbench/find_widget.rs+++ b/native/crates/app/src/workbench/find_widget.rs@@ -451,6 +451,10 @@ impl Workbench {self.show_comments_filter_history_value(previous, window, cx);return Outcome::done();}+ if id == InputId::TestingFilter {+ self.show_testing_filter_history_value(previous, window, cx);+ return Outcome::done();+ }if id == InputId::DebugConsoleFilter {self.show_debug_console_filter_history_value(previous, window, cx);return Outcome::done();diff --git a/native/crates/app/src/workbench/input_box_view.rs b/native/crates/app/src/workbench/input_box_view.rsindex c7aefd51ab8..7f2bfb9e6ba 100644--- a/native/crates/app/src/workbench/input_box_view.rs+++ b/native/crates/app/src/workbench/input_box_view.rs@@ -51,12 +51,13 @@ pub enum InputId {IconSelectSearch,CommentsFilter,DebugConsoleFilter,+ TestingFilter,TrustedPath,/// One of the custom dialog's inputs (dialog.ts `inputs`).Dialog(usize),}-const INPUTS: [InputId; 28] = [+const INPUTS: [InputId; 29] = [InputId::QuickInput,InputId::Explorer,InputId::ExplorerFind,@@ -84,6 +85,7 @@ const INPUTS: [InputId; 28] = [InputId::IconSelectSearch,InputId::CommentsFilter,InputId::DebugConsoleFilter,+ InputId::TestingFilter,InputId::TrustedPath,];@@ -190,6 +192,7 @@ impl Workbench {InputId::DebugView => &self.debug_view.input_view,InputId::BreakpointWidget => &self.debug_view.widget_view,InputId::CommentsFilter => &self.comments.view.filter_view,+ InputId::TestingFilter => &self.testing_view.filter.view,InputId::DebugConsoleFilter => &self.debug_console.filter_view,InputId::DebugConsole => &self.debug_console.input_view,InputId::TerminalFind => &self.terminal_view.find.view,@@ -229,6 +232,7 @@ impl Workbench {InputId::DebugView => &mut self.debug_view.input_view,InputId::BreakpointWidget => &mut self.debug_view.widget_view,InputId::CommentsFilter => &mut self.comments.view.filter_view,+ InputId::TestingFilter => &mut self.testing_view.filter.view,InputId::DebugConsoleFilter => &mut self.debug_console.filter_view,InputId::DebugConsole => &mut self.debug_console.input_view,InputId::TerminalFind => &mut self.terminal_view.find.view,@@ -268,6 +272,7 @@ impl Workbench {InputId::DebugView => &self.debug_view.input_focus,InputId::BreakpointWidget => &self.debug_view.widget_focus,InputId::CommentsFilter => &self.comments.view.filter_focus,+ InputId::TestingFilter => &self.testing_view.filter.focus,InputId::DebugConsoleFilter => &self.debug_console.filter_focus,InputId::DebugConsole => &self.debug_console.input_focus,InputId::TerminalFind => &self.terminal_view.find.focus,@@ -304,6 +309,7 @@ impl Workbench {InputId::DebugView => self.debug_view.editing.as_ref().map(|_| &self.debug_view.input),InputId::BreakpointWidget => self.breakpoint_widget.as_ref().map(|widget| &widget.input),InputId::CommentsFilter => Some(&self.comments.view.filter),+ InputId::TestingFilter => Some(&self.testing_view.filter.input),InputId::DebugConsoleFilter => Some(&self.debug_console.filter),InputId::DebugConsole => Some(&self.debug_console.input),InputId::TerminalFind => Some(&self.terminal_view.find.input),@@ -415,6 +421,10 @@ impl Workbench {self.edit_comments_filter(edit, window, cx);Outcome::done()}+ InputId::TestingFilter => {+ self.edit_testing_filter(edit, window, cx);+ Outcome::done()+ }InputId::DebugConsoleFilter => {self.edit_debug_console_filter(edit, window, cx);Outcome::done()@@ -696,6 +706,7 @@ impl Workbench {InputId::DebugView => "debug-view-input-text".into(),InputId::BreakpointWidget => "breakpoint-widget-input-text".into(),InputId::CommentsFilter => "comments-filter-text".into(),+ InputId::TestingFilter => "testing-filter-text".into(),InputId::DebugConsoleFilter => "debug-console-filter-text".into(),InputId::DebugConsole => "debug-console-input-text".into(),InputId::TerminalFind => "terminal-find-text".into(),diff --git a/native/crates/app/src/workbench/keyboard.rs b/native/crates/app/src/workbench/keyboard.rsindex 3abc8e2d053..b4d4373977e 100644--- a/native/crates/app/src/workbench/keyboard.rs+++ b/native/crates/app/src/workbench/keyboard.rs@@ -459,6 +459,7 @@ impl Workbench {self.action_widget_context(&mut context);self.problems_context(window, &mut context);self.comments_filter_context(window, &mut context);+ self.testing_filter_context(window, &mut context);self.view_containers_context(&mut context);self.refactor_preview_context(&mut context);self.modal_group_context(window, &mut context);diff --git a/native/crates/app/src/workbench/quick_open.rs b/native/crates/app/src/workbench/quick_open.rsindex 356c7a9a887..78d08e25b88 100644--- a/native/crates/app/src/workbench/quick_open.rs+++ b/native/crates/app/src/workbench/quick_open.rs@@ -65,6 +65,7 @@ impl Workbench {self.restore_problems_state();self.restore_debug_console_state();self.restore_outline_state();+ self.restore_testing_filter();}/// `handleActiveEditorChangeInHistory`. Upstream saves on shutdown only; the port saves on each change, as itsdiff --git a/native/crates/app/src/workbench/testing_filter.rs b/native/crates/app/src/workbench/testing_filter.rsnew file mode 100644index 00000000000..c11bcbd8010--- /dev/null+++ b/native/crates/app/src/workbench/testing_filter.rs@@ -0,0 +1,472 @@+//! The Testing explorer's filter box (testingExplorerFilter.ts) and the filter it applies (testExplorerFilterState.ts+//! and testingExplorerView.ts `TestsFilter`).++use std::cell::Cell;+use std::collections::{HashMap, HashSet};+use std::rc::Rc;+use std::sync::LazyLock;++use gpui::{App, Bounds, Context, Div, FocusHandle, MouseButton, MouseDownEvent, Pixels, Task, Window, div, prelude::*, px};+use regex::Regex;+use serde_json::{Value, json};++use super::Workbench;+use super::input_box_view::{InputId, InputLook, InputView};+use super::output_view::bounds_tracker;+use crate::commands::Outcome;+use crate::history::HistoryNavigator;+use crate::input_box::InputBox;+use crate::menus::MenuAction;+use crate::testing::{ResultState, parent_id};++/// testingExplorerFilter.ts's `history`, a workspace StoredValue.+const HISTORY_KEY: &str = "testing.filterHistory2";+/// testExplorerFilterState.ts's `fuzzy`, a profile StoredValue.+const FUZZY_KEY: &str = "testHistoryFuzzy";++/// `TestFilterTerm` with testingExplorerFilter.ts's `testFilterDescriptions`.+const FAILED: &str = "@failed";+const EXECUTED: &str = "@executed";+const CURRENT_DOC: &str = "@doc";+const OPENED_FILES: &str = "@openedFiles";+const HIDDEN: &str = "@hidden";+const TERMS: [(&str, &str); 5] = [+ (FAILED, "Show Only Failed Tests"),+ (EXECUTED, "Show Only Executed Tests"),+ (CURRENT_DOC, "Show in Active File Only"),+ (OPENED_FILES, "Show in Opened Files Only"),+ (HIDDEN, "Show Hidden Tests"),+];++static TAG_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"!?@([^ ,:]+)").unwrap());+static EXTRA_WHITESPACE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s\s+").unwrap());++/// The filter box with its history and the parsed `TestExplorerFilterState`.+pub struct TestingFilter {+ pub input: InputBox,+ pub view: InputView,+ pub focus: FocusHandle,+ pub state: FilterState,+ history: HistoryNavigator,+ applying: Option<Task<()>>,+ menu_bounds: Rc<Cell<Bounds<Pixels>>>,+}++impl TestingFilter {+ pub fn new(cx: &mut App) -> Self {+ TestingFilter {+ input: InputBox::default(),+ view: InputView::default(),+ focus: cx.focus_handle(),+ state: FilterState::default(),+ history: HistoryNavigator::new(Vec::new(), 100),+ applying: None,+ menu_bounds: Rc::default(),+ }+ }+}++/// testExplorerFilterState.ts `TestExplorerFilterState`: the text, and what `setText` parsed from it.+#[derive(Default)]+pub struct FilterState {+ pub text: String,+ terms: HashSet<String>,+ /// `globList`: lowercase, `false` for a `!` exclusion.+ globs: Vec<(bool, String)>,+ include_tags: HashSet<String>,+ exclude_tags: HashSet<String>,+ pub fuzzy: bool,+}++impl FilterState {+ pub fn set_text(&mut self, text: &str) {+ if text == self.text {+ return;+ }+ self.terms.clear();+ self.globs.clear();+ self.include_tags.clear();+ self.exclude_tags.clear();+ let mut glob_text = String::new();+ let mut last = 0;+ for found in TAG_RE.captures_iter(text) {+ let tag = found.get(0).expect("the whole match");+ let mut next = tag.end();+ let is_term = TERMS.iter().any(|(term, _)| *term == tag.as_str());+ if is_term {+ self.terms.insert(tag.as_str().to_owned());+ }+ // `@ctrlId:tagId`, or quoted as `@ctrlId:"tag \"id"`.+ let is_tag = text[next..].starts_with(':');+ if is_tag {+ next += 1;+ let delimiter = match text[next..].chars().next() {+ Some(quote @ ('"' | '\'')) => {+ next += 1;+ quote+ }+ _ => ' ',+ };+ let mut tag_id = String::new();+ let mut chars = text[next..].chars();+ while let Some(char) = chars.next() {+ if char == delimiter {+ break;+ }+ next += char.len_utf8();+ if char == '\\' {+ let Some(escaped) = chars.next() else { break };+ next += escaped.len_utf8();+ tag_id.push(escaped);+ } else {+ tag_id.push(char);+ }+ }+ let namespaced = format!("{}\0{tag_id}", &found[1]);+ match tag.as_str().starts_with('!') {+ true => self.exclude_tags.insert(namespaced),+ false => self.include_tags.insert(namespaced),+ };+ next += 1;+ }+ // Other `@` text, such as a test named "@smoke", is filter text.+ if !is_term && !is_tag {+ continue;+ }+ glob_text += text.get(last..tag.start()).unwrap_or_default();+ last = next;+ }+ glob_text += text.get(last..).unwrap_or_default().trim();+ for filter in files::glob::split_glob_aware(&glob_text, ',') {+ let filter = filter.trim();+ match filter.strip_prefix('!') {+ _ if filter.is_empty() => {}+ Some(excluded) => self.globs.push((false, excluded.to_lowercase())),+ None => self.globs.push((true, filter.to_lowercase())),+ }+ }+ self.text = text.to_owned();+ }++ pub fn is_filtering_for(&self, term: &str) -> bool {+ self.terms.contains(term)+ }++ /// `toggleFilteringFor`: the text with the term appended, or with its first occurrence taken out.+ fn toggled_text(&self, term: &str) -> String {+ let text = self.text.trim();+ match self.is_filtering_for(term) {+ false if text.is_empty() => term.to_owned(),+ false => format!("{text} {term}"),+ true => EXTRA_WHITESPACE_RE.replace_all(&text.replacen(term, "", 1), " ").trim().to_owned(),+ }+ }+}++/// testingExplorerView.ts `FilterResult`, ordered so the lowest of the filters wins.+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+enum FilterResult {+ Exclude,+ Inherit,+ Include,+}++/// A tree node's `TreeVisibility` from `TestsFilter.filter`.+#[derive(PartialEq)]+enum Visibility {+ Hidden,+ Visible,+ Recurse,+}++impl Workbench {+ /// The tests the explorer's filter leaves visible, by indexTreeModel.ts: a `Recurse` node shows when a descendant+ /// does, a hidden one hides its subtree. `None` while nothing filters. Also answers the tests `Include`d, whose+ /// parents a text filter expands.+ pub(super) fn testing_filtered_tests(&self) -> Option<(HashSet<String>, Vec<String>)> {+ let state = &self.testing_view.filter.state;+ let by_location = state.is_filtering_for(CURRENT_DOC) || state.is_filtering_for(OPENED_FILES);+ if state.terms.is_empty() && state.globs.is_empty() && state.include_tags.is_empty() && state.exclude_tags.is_empty() {+ return None;+ }+ let documents = if by_location { self.testing_filter_documents() } else { Vec::new() };+ let mut visible = HashSet::new();+ let mut included = Vec::new();+ for id in self.testing_top_level() {+ self.filter_test(&id, &documents, &mut visible, &mut included);+ }+ Some((visible, included))+ }++ /// The explorer's top level: index.ts shows a single root's children there.+ pub(super) fn testing_top_level(&self) -> Vec<String> {+ let collection = &self.testing.collection;+ match collection.roots.as_slice() {+ [only] => collection.children_of(only).to_vec(),+ roots => roots.to_vec(),+ }+ }++ fn filter_test(&self, id: &str, documents: &[String], visible: &mut HashSet<String>, included: &mut Vec<String>) -> bool {+ let Some(item) = self.testing.collection.items.get(id) else { return false };+ let state = &self.testing_view.filter.state;+ let tags: Vec<&str> = item.item["tags"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();+ let tags = match state.include_tags.is_empty() && state.exclude_tags.is_empty() {+ true => FilterResult::Include,+ false => match (state.include_tags.is_empty() || tags.iter().any(|tag| state.include_tags.contains(*tag))) && tags.iter().all(|tag| !state.exclude_tags.contains(*tag)) {+ true => FilterResult::Include,+ false => FilterResult::Inherit,+ },+ };+ let result_state = self.testing.state_of(id).unwrap_or_default();+ let test_state = if state.is_filtering_for(FAILED) {+ if matches!(result_state, ResultState::Failed | ResultState::Errored) { FilterResult::Include } else { FilterResult::Inherit }+ } else if state.is_filtering_for(EXECUTED) {+ if result_state != ResultState::Unset { FilterResult::Include } else { FilterResult::Inherit }+ } else {+ FilterResult::Include+ };+ let location = match documents.is_empty() || documents.iter().any(|document| self.has_test_in_or_parent_of(document, id)) {+ true => FilterResult::Include,+ false => FilterResult::Inherit,+ };+ let visibility = match self.test_filter_text(id).min(location).min(test_state).min(tags) {+ FilterResult::Exclude => Visibility::Hidden,+ FilterResult::Include => {+ included.push(id.to_owned());+ Visibility::Visible+ }+ FilterResult::Inherit => Visibility::Recurse,+ };+ if visibility == Visibility::Hidden {+ return false;+ }+ let mut descendant_visible = false;+ for child in self.testing.collection.children_of(id) {+ descendant_visible |= self.filter_test(child, documents, visible, included);+ }+ let shown = visibility == Visibility::Visible || descendant_visible;+ if shown {+ visible.insert(id.to_owned());+ }+ shown+ }++ /// `TestsFilter.testFilterText`: the first of the test and its parents a glob decides.+ fn test_filter_text(&self, id: &str) -> FilterResult {+ let state = &self.testing_view.filter.state;+ let Some((first_include, _)) = state.globs.first() else { return FilterResult::Include };+ let top_level_root = match self.testing.collection.roots.as_slice() {+ [only] => Some(only.as_str()),+ _ => None,+ };+ let mut test = Some(id);+ while let Some(id) = test.filter(|id| Some(*id) != top_level_root) {+ let mut included = if *first_include { FilterResult::Inherit } else { FilterResult::Include };+ let label = self.testing.collection.items.get(id).map(|item| item.label().to_lowercase()).unwrap_or_default();+ for (include, text) in &state.globs {+ let matches = if state.fuzzy { crate::filters::fuzzy_contains(&label, text) } else { label.contains(text.as_str()) };+ if matches {+ included = if *include { FilterResult::Include } else { FilterResult::Exclude };+ }+ }+ if included != FilterResult::Inherit {+ return included;+ }+ test = parent_id(id);+ }+ FilterResult::Inherit+ }++ /// `hasNodeInOrParentOfUri`: the test, or a test under it, is in the document and has a range or can expand.+ fn has_test_in_or_parent_of(&self, document: &str, id: &str) -> bool {+ let collection = &self.testing.collection;+ let mut queue = vec![id.to_owned()];+ while let Some(id) = queue.pop() {+ let Some(item) = collection.items.get(&id) else { continue };+ if !item.path().is_some_and(|path| std::path::Path::new(document).starts_with(path)) {+ continue;+ }+ if !item.item["range"].is_null() || item.expand == crate::testing::ExpandState::Expandable {+ return true;+ }+ queue.extend(collection.children_of(&id).iter().cloned());+ }+ false+ }++ /// The `file` paths `filterToDocumentUri` gets: every open editor's for `@openedFiles`, else the active one's.+ fn testing_filter_documents(&self) -> Vec<String> {+ let file_path = |editor: &crate::editor::OpenEditor| (editor.document().scheme == "file").then(|| editor.document().path.to_string_lossy().into_owned());+ if !self.testing_view.filter.state.is_filtering_for(OPENED_FILES) {+ return self.editors.active().and_then(file_path).into_iter().collect();+ }+ let mut paths = Vec::new();+ for group in self.groups_in_grid_order() {+ paths.extend(self.editors.group_tabs(group).0.iter().filter_map(file_path));+ }+ paths+ }++ /// Restores the filter text (`lastValue`), its history and Fuzzy Match.+ pub(super) fn restore_testing_filter(&mut self) {+ let stored: Value = self.workspace_storage.lock().unwrap().get(HISTORY_KEY).and_then(|raw| serde_json::from_str(raw).ok()).unwrap_or_default();+ // An older version stored only the values.+ let (last, values) = match stored.as_array() {+ Some(values) => (String::new(), values.as_slice()),+ None => (stored["lastValue"].as_str().unwrap_or_default().to_owned(), stored["values"].as_array().map(Vec::as_slice).unwrap_or_default()),+ };+ let history = values.iter().filter_map(Value::as_str).map(str::to_owned).collect();+ let fuzzy = self.profile_storage.lock().unwrap().get(FUZZY_KEY) == Some("true");+ let filter = &mut self.testing_view.filter;+ filter.history = HistoryNavigator::new(history, 100);+ filter.state.fuzzy = fuzzy;+ filter.input.set_value(last.clone());+ filter.state.set_text(&last);+ }++ pub(super) fn register_testing_filter_commands(&mut self) {+ for (term, _) in TERMS {+ self.commands.register(format!("testing.filters.toggle{term}"), move |workbench, _, window, cx| {+ let text = workbench.testing_view.filter.state.toggled_text(term);+ workbench.edit_testing_filter(|input| input.set_value(text), window, cx);+ workbench.apply_testing_filter(cx);+ Outcome::done()+ });+ }+ self.commands.register("testing.filters.toggleFuzzy", |workbench, _, _, cx| {+ let filter = &mut workbench.testing_view.filter;+ filter.state.fuzzy = !filter.state.fuzzy;+ workbench.profile_storage.lock().unwrap().set(FUZZY_KEY, filter.state.fuzzy.to_string());+ workbench.testing_filter_changed(cx);+ Outcome::done()+ });+ }++ /// `onInputDidChange` after the 400 ms `Delayer`: the input's value goes into the history and applies.+ pub(super) fn edit_testing_filter(&mut self, edit: impl FnOnce(&mut InputBox), window: &mut Window, cx: &mut Context<Self>) {+ let before = self.testing_view.filter.input.value.clone();+ edit(&mut self.testing_view.filter.input);+ cx.notify();+ if self.testing_view.filter.input.value == before {+ return;+ }+ self.testing_view.filter.applying = Some(cx.spawn_in(window, async move |workbench, cx| {+ cx.background_executor().timer(std::time::Duration::from_millis(400)).await;+ let _ = workbench.update(cx, |workbench, cx| {+ let filter = &mut workbench.testing_view.filter;+ filter.history.add_to_history(&filter.input.value, false);+ workbench.apply_testing_filter(cx);+ });+ }));+ }++ fn apply_testing_filter(&mut self, cx: &mut Context<Self>) {+ let filter = &mut self.testing_view.filter;+ let text = filter.input.value.clone();+ let stored = json!({ "lastValue": text, "values": filter.history.elements() });+ self.workspace_storage.lock().unwrap().set(HISTORY_KEY, stored.to_string());+ if text != filter.state.text {+ filter.state.set_text(&text);+ self.testing_filter_changed(cx);+ }+ }++ /// testingExplorerView.ts on a filter change: with text, the tree expands to each test the filter includes.+ fn testing_filter_changed(&mut self, cx: &mut Context<Self>) {+ cx.notify();+ if self.testing_view.filter.state.text.is_empty() {+ return;+ }+ let Some((_, included)) = self.testing_filtered_tests() else { return };+ for test in included {+ let mut parent = parent_id(&test);+ while let Some(id) = parent {+ self.testing_view.collapsed.remove(id);+ self.testing_view.expanded.insert(id.to_owned());+ parent = parent_id(id);+ }+ }+ }++ /// `history.showPrevious` and `history.showNext` in the filter box.+ pub(super) fn show_testing_filter_history_value(&mut self, previous: bool, window: &mut Window, cx: &mut Context<Self>) {+ let filter = &mut self.testing_view.filter;+ let value = match previous {+ true => filter.history.show_previous_value(&filter.input.value),+ false => Some(filter.history.show_next_value(&filter.input.value)),+ };+ if let Some(value) = value {+ self.edit_testing_filter(|input| input.set_value(value), window, cx);+ }+ }++ /// The history input's keys while the filter box has the focus.+ pub(super) fn testing_filter_context(&self, window: &Window, context: &mut HashMap<String, Value>) {+ if !self.testing_view.filter.focus.is_focused(window) {+ return;+ }+ for key in ["inputFocus", "historyNavigationWidgetFocus", "historyNavigationForwardsEnabled", "historyNavigationBackwardsEnabled"] {+ context.insert(key.into(), json!(true));+ }+ }++ /// testing.css `.testing-filter-action-bar`: the SuggestEnabledInput (suggestEnabledInput.ts, 20px lines of 13px+ /// text, padded 2px 6px) with More Filters... at its right.+ pub(super) fn testing_filter_box(&self, window: &Window, cx: &mut Context<Self>) -> Div {+ let filter = &self.testing_view.filter;+ let focused = filter.focus.is_focused(window);+ let border = if focused { self.color("focusBorder") } else { self.theme.color("input.border").unwrap_or(gpui::transparent_black().into()) };+ // `updateFilterActiveState`: checked while a test is hidden, which needs testExclusions.ts.+ let foreground = self.foreground_or("icon.foreground");+ let bounds = filter.menu_bounds.clone();+ let more_filters = self+ .icon("filter", 22., 16., foreground)+ .id("testing-filter-menu")+ .rounded(px(4.))+ .cursor_pointer()+ .hover(|button| button.bg(self.color("toolbar.hoverBackground")))+ .child(bounds_tracker(bounds.clone()))+ .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, _: &MouseDownEvent, window, cx| {+ cx.stop_propagation();+ workbench.show_testing_filter_menu(bounds.get(), window, cx);+ }));+ let look = InputLook { password: false, placeholder: Some("Filter (e.g. text, !exclude, @tag)".into()), focused };+ let input = div()+ .relative()+ .flex_1()+ .min_w_0()+ .flex()+ .items_center()+ .py(px(2.))+ .pl(px(6.))+ .pr(px(30.))+ .rounded(px(4.))+ .border_1()+ .border_color(border)+ .bg(self.color("input.background"))+ .text_color(self.foreground_or("input.foreground"))+ .cursor_text()+ .child(div().flex_1().min_w_0().h(px(20.)).flex().text_size(px(13.)).child(self.input_text(InputId::TestingFilter, look, cx)))+ .child(div().absolute().top_0().bottom_0().right(px(3.)).flex().items_center().child(more_filters));+ div().flex_none().mx(px(12.)).my(px(4.)).flex().child(input)+ }++ /// `FiltersDropdownMenuActionViewItem.getActions`.+ fn show_testing_filter_menu(&mut self, anchor: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {+ let state = &self.testing_view.filter.state;+ let item = |id: String, title: &str, checked: bool, enabled: bool| MenuAction::Command { id, title: title.into(), enabled, checked, alt: None };+ let mut actions: Vec<MenuAction> = TERMS[..4].iter().map(|(term, title)| item(format!("testing.filters.toggle{term}"), title, state.is_filtering_for(term), true)).collect();+ actions.push(MenuAction::Separator);+ actions.push(item("testing.filters.toggleFuzzy".into(), "Fuzzy Match", state.fuzzy, true));+ actions.push(MenuAction::Separator);+ // `excluded.hasAny` enables these; nothing is hidden until testExclusions.ts is ported.+ actions.push(item(format!("testing.filters.toggle{HIDDEN}"), TERMS[4].1, state.is_filtering_for(HIDDEN), false));+ actions.push(item("testing.filters.unhideAll".into(), "Unhide All Tests", false, false));+ let context = self.key_context(window);+ self.show_dropdown_menu_actions(actions, &context, anchor, Vec::new(), window, cx);+ }+}++#[cfg(test)]+mod tests;diff --git a/native/crates/app/src/workbench/testing_filter/tests.rs b/native/crates/app/src/workbench/testing_filter/tests.rsnew file mode 100644index 00000000000..5d0f89ecf84--- /dev/null+++ b/native/crates/app/src/workbench/testing_filter/tests.rs@@ -0,0 +1,85 @@+use std::collections::HashSet;+use std::path::Path;+use std::time::Duration;++use gpui::{TestAppContext, VisualTestContext};+use serde_json::{Value, json};++use super::{CURRENT_DOC, FAILED, FilterState};+use crate::workbench::Workbench;++fn add(id: &str, label: &str, uri: Value) -> Value {+ json!({ "op": 0, "item": { "expand": 0, "item": { "extId": id, "label": label, "tags": [], "uri": uri } } })+}++fn workbench(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut VisualTestContext) {+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();+ let theme = crate::theme::load_theme(&[exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();+ let (sender, _host) = std::sync::mpsc::channel();+ cx.add_window_view(|_, cx| {+ let mut workbench = Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(sender), cx);+ let file = json!({ "scheme": "file", "path": "/math.test.js" });+ workbench.testing.collection.apply(&[+ add("c", "c", Value::Null),+ add("c\0math", "Math", file.clone()),+ add("c\0math\0basic", "Basic", file.clone()),+ add("c\0math\0basic\0add", "adds numbers", file.clone()),+ add("c\0math\0basic\0sub", "subtracts", file),+ add("c\0other", "Other", Value::Null),+ ]);+ workbench+ })+}++fn type_filter(workbench: &gpui::Entity<Workbench>, text: &str, cx: &mut VisualTestContext) {+ let text = text.to_owned();+ workbench.update_in(cx, |workbench, window, cx| workbench.edit_testing_filter(|input| input.set_value(text), window, cx));+ cx.executor().advance_clock(Duration::from_millis(400));+ cx.run_until_parked();+}++fn visible(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Option<HashSet<String>> {+ workbench.read_with(cx, |workbench, _| workbench.testing_filtered_tests().map(|(visible, _)| visible))+}++fn ids(ids: &[&str]) -> Option<HashSet<String>> {+ Some(ids.iter().map(|id| id.to_string()).collect())+}++/// testExplorerFilterState.ts `setText`: terms and `@ctrlId:tagId` tags leave the text, other `@` text is a glob,+/// and the rest splits on commas outside braces, `!` excluding.+#[test]+fn filter_text_parses_into_terms_tags_and_globs() {+ let mut state = FilterState::default();+ state.set_text(r#"@failed Add, !sub{a,b}, @smoke @ctrl:"slow \"one\"" !@ctrl:fast"#);+ assert!(state.is_filtering_for(FAILED));+ assert_eq!(state.include_tags, HashSet::from(["ctrl\0slow \"one\"".to_owned()]));+ assert_eq!(state.exclude_tags, HashSet::from(["ctrl\0fast".to_owned()]));+ assert_eq!(state.globs, [(true, "add".to_owned()), (false, "sub{a,b}".to_owned()), (true, "@smoke".to_owned())]);+ assert_eq!(state.toggled_text(FAILED), r#"Add, !sub{a,b}, @smoke @ctrl:"slow \"one\"" !@ctrl:fast"#);+ assert_eq!(state.toggled_text(CURRENT_DOC), format!("{} @doc", state.text));+}++/// testingExplorerView.ts `TestsFilter`: 400 ms after typing, a test shows when its label or a parent's matches+/// (its parents for its sake), others hide, and the tree expands to each match. The text and history are stored.+#[gpui::test]+fn the_filter_box_shows_the_matching_tests_and_expands_to_them(cx: &mut TestAppContext) {+ let (workbench, cx) = workbench(cx);+ assert_eq!(visible(&workbench, cx), None);++ type_filter(&workbench, "add", cx);+ assert_eq!(visible(&workbench, cx), ids(&["c\0math", "c\0math\0basic", "c\0math\0basic\0add"]));+ let (expanded, stored) = workbench.read_with(cx, |workbench, _| (workbench.testing_view.expanded.clone(), workbench.workspace_storage.lock().unwrap().get(super::HISTORY_KEY).map(str::to_owned)));+ assert!(expanded.contains("c\0math\0basic"), "the tree expands to the match: {expanded:?}");+ assert_eq!(stored.as_deref(), Some(r#"{"lastValue":"add","values":["add"]}"#));++ type_filter(&workbench, "basic, !sub", cx);+ assert_eq!(visible(&workbench, cx), ids(&["c\0math", "c\0math\0basic", "c\0math\0basic\0add"]), "a child inherits its parent's match unless excluded");++ type_filter(&workbench, "", cx);+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("testing.filters.toggle@failed", Vec::new(), window, cx)));+ cx.run_until_parked();+ let (text, input) = workbench.read_with(cx, |workbench, _| (workbench.testing_view.filter.state.text.clone(), workbench.testing_view.filter.input.value.clone()));+ assert_eq!((text.as_str(), input.as_str()), ("@failed", "@failed"));+ assert_eq!(visible(&workbench, cx), ids(&[]), "no test has failed");+}diff --git a/native/crates/app/src/workbench/testing_view.rs b/native/crates/app/src/workbench/testing_view.rsindex 2e639b8beb7..3cb8deae159 100644--- a/native/crates/app/src/workbench/testing_view.rs+++ b/native/crates/app/src/workbench/testing_view.rs@@ -10,6 +10,7 @@ use serde_json::{Value, json};use super::Workbench;use crate::commands::Outcome;use super::panel::PanelView;+use super::testing_filter::TestingFilter;use crate::editor::OpenEditor;use crate::menus::{MenuAction, MenuId, menu_group_actions};use crate::testing::{ExpandState, GROUP_DEBUG, GROUP_RUN, ResultState};@@ -19,7 +20,6 @@ pub const TEST_RESULTS_VIEW_ID: &str = "workbench.panel.testResults";const ROW_HEIGHT: f32 = 22.;/// The view state of the explorer and the results editor.-#[derive(Default)]pub struct TestingView {/// Rows the user collapsed; others below the roots start collapsed until expanded (`expanded`).pub collapsed: HashSet<String>,@@ -29,6 +29,20 @@ pub struct TestingView {pub selected_test: Option<String>,/// Where the continuous run dropdown's chevron last painted, to anchor its menu.pub continuous_dropdown_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,+ pub filter: TestingFilter,+}++impl TestingView {+ pub fn new(cx: &mut gpui::App) -> Self {+ TestingView {+ collapsed: HashSet::new(),+ expanded: HashSet::new(),+ selected_result: None,+ selected_test: None,+ continuous_dropdown_bounds: Default::default(),+ filter: TestingFilter::new(cx),+ }+ }}/// testingStates icons (icons.ts `testingStatesToIcons`) and their colors (theme.ts `testStatesToIconColors`).@@ -72,6 +86,7 @@ impl Workbench {});self.register_testing_continuous_commands();self.register_test_item_commands();+ self.register_testing_filter_commands();self.commands.register("workbench.view.extension.test", |workbench, args, window, cx| workbench.execute_command("workbench.view.testing", args, window, cx));for (id, group) in [("testing.runAll", GROUP_RUN), ("testing.debugAll", GROUP_DEBUG)] {self.commands.register(id, move |workbench, _, window, cx| {@@ -237,23 +252,14 @@ impl Workbench {body = body.child(div().px(px(20.)).child(self.testing_button("Install Additional Test Extensions...", "testing.searchForTestExtension", cx)));} else {let mut rows = Vec::new();- let roots = self.testing.collection.roots.clone();- // index.ts: a single root shows its children at the top level.- match roots.as_slice() {- [only] => {- for child in self.testing.collection.children_of(only) {- self.test_rows(child, 0, &mut rows, window, cx);- }- }- _ => {- for root in &roots {- self.test_rows(root, 0, &mut rows, window, cx);- }- }+ let visible = self.testing_filtered_tests().map(|(visible, _)| visible);+ for id in self.testing_top_level() {+ self.test_rows(&id, 0, visible.as_ref(), &mut rows, window, cx);}body = body.children(rows);}- self.side_bar_frame().text_color(foreground).child(title).child(body)+ let filter = has_tests.then(|| self.testing_filter_box(window, cx));+ self.side_bar_frame().text_color(foreground).child(title).children(filter).child(body)}fn testing_button(&self, label: &str, command: &'static str, cx: &mut Context<Self>) -> gpui::Stateful<Div> {@@ -274,7 +280,11 @@ impl Workbench {}))}- fn test_rows(&self, id: &str, depth: usize, rows: &mut Vec<gpui::AnyElement>, window: &Window, cx: &mut Context<Self>) {+ /// The rows of the test and its expanded descendants that the filter leaves `visible` (all of them without one).+ fn test_rows(&self, id: &str, depth: usize, visible: Option<&HashSet<String>>, rows: &mut Vec<gpui::AnyElement>, window: &Window, cx: &mut Context<Self>) {+ if visible.is_some_and(|visible| !visible.contains(id)) {+ return;+ }let Some(item) = self.testing.collection.items.get(id) else { return };let children = self.testing.collection.children_of(id);let expandable = item.expand != ExpandState::NotExpandable || !children.is_empty();@@ -348,7 +358,7 @@ impl Workbench {rows.push(row.into_any_element());if expanded {for child in children {- self.test_rows(child, depth + 1, rows, window, cx);+ self.test_rows(child, depth + 1, visible, rows, window, cx);}}}diff --git a/port/ledger.md b/port/ledger.mdindex f1c129b1cfd..7cbad978dee 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -546,7 +546,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| workbench/contrib/telemetry | workbench contribution | M19 | verified | | the contribution logs to the NullTelemetryService and registers Show Telemetry only when supportsTelemetry, false in the built product: nothing to port; port/tools/telemetry-source-check no endpoint in 18370 shipped files (SELF_TEST finds 9 in the inert packages) || workbench/contrib/terminal | workbench contribution | M15 | verified | | workbench/terminal_view.rs: the Terminal panel view, terminals, split, kill, rename, profiles (`newWithProfile` with `profileName`: cargo test -p app new_with_profile), tabs list, the `TerminalInstanceContext` menu; no exit alert after a Ctrl+D exit (cargo test -p app a_ctrl_d_exit_shows_no_exit_alert); gutter command decorations with their menu (workbench/terminal_decorations.rs), scroll to previous/next command (terminal/marks.rs; cargo test -p app terminal::marks); ui-pair against the reference. Copy as HTML and Copy Output as HTML (terminal/serialize_html.rs; cargo test -p app serialize_html); the decoration hover with duration and exit code (cargo test -p app terminal_decorations, hover); Record Terminal Session (cargo test -p app a_recording_keeps_each_kind_of_event); overview ruler marks, Toggle Visibility (cargo test -p app toggle_visibility_writes_the_decorations_setting), the Rerun Command trust prompt, `terminal.integrated.cwd` variables (cargo test -p app the_cwd_setting_resolves_its_variables); ui-pair of OSC 99, decorations, overview ruler, Copy as HTML and Record Terminal Session (port/results/terminal.md); tab description `terminal.integrated.tabs.description` with `${cwdFolder}` (terminal/label.rs, TerminalLabelComputer and labels.ts `template`), the single tab "fish - docs": cargo test -p app terminal::label; ui-pair m12/folder-terminal.json matches but the reference's panel overflow "..." (its Ports view, remote is out of scope). The grid below `padding-block` 8px with columns from the rendered cell, the title toolbar at the reference's x and its "..." menu (cargo test -p app terminal_view::tests), Run Selected Text and Run Active File with paths quoted as `preparePathForShell` (cargo test -p app paths_are_quoted, call_operator); ui-pair m11/task-presentation.json for `reveal: silent` and `close` (port/results/manage-menu.md). Tab list rows: 4px inset, 8px padding (modernUI tabs.css), `┌ ` prefix, icon, name and description at the reference's device pixels (cargo test -p app a_tab_row_is_inset_and_its_label_is_one_line_of_text; ui-pair terminal tabs). Persistent sessions: panel groups with their splits and active panes, and terminal editors, revive with their history after a restart (cargo test -p app panel_terminals_revive_in_their_groups_after_a_restart a_terminal_editor_revives_with_its_history_after_a_restart) || workbench/contrib/terminalContrib | workbench contribution | M15 | verified | | links (terminal/link_parsing.rs, link_computer.rs, workbench/terminal_links.rs: Cmd+click URLs and paths with line:column), sendSequence, sendSignal, zoom (font size commands, Cmd+wheel), autoReplies (terminal/auto_replies.rs), find (terminal/search.rs and workbench/terminal_find.rs: case, whole word, regex, count, previous/next, match highlights), prompt input model (terminal/prompt_input.rs), suggest (workbench/terminal_suggest.rs), history (terminal/history.rs, workbench/terminal_history.rs: Run Recent Command, Go to Recent Directory, pinned items, shell history files), quick access (`term `, workbench/terminal_quick_access.rs), sticky scroll (terminal/sticky_scroll.rs, workbench/terminal_sticky_scroll.rs); cargo test -p app link_, terminal::search, prompt_input, auto_replies, terminal_contrib, terminal_links, terminal::history, sticky_scroll, quick_access; ui-pair of Run Recent Command, `term ` and sticky scroll; resize overlay (workbench/terminal_resize_overlay.rs), environment changes (Show Environment Contributions, workbench/terminal_environment.rs; cargo test -p app environment_collection), developer Write Data to Terminal (Show Terminal Texture Atlas and Restart Pty Host have no counterpart: GPUI draws without an atlas page and there is no pty host), command guide (cargo test -p app terminal::marks), notification (OSC 99, terminal/osc99.rs, workbench/terminal_notifications.rs; cargo test -p app osc99), quick fix (terminal/quick_fix.rs, workbench/terminal_quick_fix.rs: builtin fixes, extension providers, light bulb, Cmd+. widget, decoration menu; cargo test -p app quick_fix), accessibility (terminal/accessible_buffer.rs, the terminal provider of workbench/accessible_view.rs; cargo test -p app accessible), links in wrapped lines with the hover and underline (cargo test -p app terminal_links). inlineHint without AI: the initial hint "Show suggestions ⌃Space" with its dismiss links (workbench/terminal_initial_hint.rs; ui-pair against the reference); its Copilot CLI part, chat and voice are AI (removed), wslRecommendation is Windows (port/notes.md milestone 15) |-| workbench/contrib/testing | workbench contribution | M16 | ported | [3 S] testing_item_menu.rs:test_item_context: testExclusions.ts not ported: no Hide Test or Unhide Test, `testing.testItemIsHidden` is always false; a hidden test comes back only through the filter's Show Hidden Tests and Unhide All Tests, so it waits for the filter box <br> [3 L] testing_view.rs:207: the explorer has no filter box (testingExplorerFilter.ts: text with history, the `@failed`, `@executed`, `@doc`, `@openedFiles` and `@hidden` terms and the filter menu) | A test row's actions are `MenuId.TestItem`'s `inline` group with the testing icons (testingExplorerView.ts `fillActionBar`: cargo test -p app a_test_row_shows_the_test_item_menu_s_inline_group); A test row's context menu (testingExplorerView.ts `onContextMenu`: `MenuId.TestItem` but `inline`, the `getActionableElementActions` keys, the row as `TestItemContext`; cargo test -p app a_test_rows_context_menu_shows_and_runs_the_test_item_actions); `TreeSorter` by location with `compareFileNames` (cargo test -p app children_sort_by_line_then_by_file_name_order). The view title's continuous run dropdown when several profiles of controllers with tests support it (testingExplorerView.ts `getContinuousRunDropdown`: group labels, checked profiles, `stopProfile` cancels only that profile; cargo test -p app the_view_title_dropdown_starts_and_stops_one_profile_of_several); `testing.continuousRunUsingForTest` picks from the test's controller's profiles (cargo test -p app continuous_run_using_picks_from_the_tests_controller_only); testingContinuousRunService.ts: Turn on Continuous Run of a test and Start Continuous Run each hold one cancellable `$startContinuousRun` per profile until stopped, the eye activity badge, `testing.isContinuousModeOn`, the last run's profiles in workspace storage (cargo test -p app a_continuous_run_holds_one_cancellable_request_per_profile_until_it_stops). The Testing item's activity badge: the spinner during a run, else the newest result's `testing.countBadge` count (cargo test -p app the_testing_item_spins). ui-pair port/fixtures/debug-node with tests-provider: Testing view tree, Run All, pass/fail icons, Test Results tree and output, run glyphs in the gutter; cargo test -p app testing::; testServiceImpl.ts `runResolvedTests` asks for workspace trust after the live result is created, a refusal completes it (cargo test -p app a_test_run_waits_for_workspace_trust_and_completes_when_it_is_refused) |+| workbench/contrib/testing | workbench contribution | M16 | ported | [3 S] testing_item_menu.rs:test_item_context: testExclusions.ts not ported: no Hide Test or Unhide Test, `testing.testItemIsHidden` is always false, and the filter menu's Show Hidden Tests and Unhide All Tests are disabled | The explorer's filter box (testingExplorerFilter.ts and testExplorerFilterState.ts: text with history, terms, tags, globs, fuzzy; cargo test -p app testing_filter); A test row's actions are `MenuId.TestItem`'s `inline` group with the testing icons (testingExplorerView.ts `fillActionBar`: cargo test -p app a_test_row_shows_the_test_item_menu_s_inline_group); A test row's context menu (testingExplorerView.ts `onContextMenu`: `MenuId.TestItem` but `inline`, the `getActionableElementActions` keys, the row as `TestItemContext`; cargo test -p app a_test_rows_context_menu_shows_and_runs_the_test_item_actions); `TreeSorter` by location with `compareFileNames` (cargo test -p app children_sort_by_line_then_by_file_name_order). The view title's continuous run dropdown when several profiles of controllers with tests support it (testingExplorerView.ts `getContinuousRunDropdown`: group labels, checked profiles, `stopProfile` cancels only that profile; cargo test -p app the_view_title_dropdown_starts_and_stops_one_profile_of_several); `testing.continuousRunUsingForTest` picks from the test's controller's profiles (cargo test -p app continuous_run_using_picks_from_the_tests_controller_only); testingContinuousRunService.ts: Turn on Continuous Run of a test and Start Continuous Run each hold one cancellable `$startContinuousRun` per profile until stopped, the eye activity badge, `testing.isContinuousModeOn`, the last run's profiles in workspace storage (cargo test -p app a_continuous_run_holds_one_cancellable_request_per_profile_until_it_stops). The Testing item's activity badge: the spinner during a run, else the newest result's `testing.countBadge` count (cargo test -p app the_testing_item_spins). ui-pair port/fixtures/debug-node with tests-provider: Testing view tree, Run All, pass/fail icons, Test Results tree and output, run glyphs in the gutter; cargo test -p app testing::; testServiceImpl.ts `runResolvedTests` asks for workspace trust after the live result is created, a refusal completes it (cargo test -p app a_test_run_waits_for_workspace_trust_and_completes_when_it_is_refused) || workbench/contrib/themes | workbench contribution | M9 | verified | | Color Theme picker (`workbench.action.selectTheme`, Cmd+K Cmd+T): rows, order and descriptions as the reference, 200ms preview, Escape restores, accept writes `workbench.colorTheme`; File Icon Theme picker (`workbench.action.selectIconTheme`, Themes submenu): None and the installed themes, preview, Escape restores, accept writes `workbench.iconTheme` (null for None) (cargo test -p app themes); Product Icon Theme picker (`workbench.action.selectProductIconTheme`, Themes submenu): Default and the installed themes, writes `workbench.productIconTheme` (cargo test -p app product_icon; product-icons-pair `picker`: the same rows, except the reference's "Test Product Icon Theme" of vscode-colorize-tests, a test extension the port does not ship); no Marketplace browsing, no `window.autoDetectColorScheme` || workbench/contrib/timeline | workbench contribution | M14 | verified | | Timeline view (workbench/timeline_view.rs, timeline.rs): active editor and workspace timelines, paging, follow active editor, excluded sources in profile storage, compare selected, keyboard, `timeline/item/context` and title menus: cargo test -p app timeline; the title toolbar is a tab stop between the pane header and the tree (Shift+Tab focuses its first action with its hover, Left/Right, Enter): cargo test -p app shift_tab_reaches_the_title_toolbar; ui-pair m12/timeline.json header step matches; item labels draw their `$(icon)`s (cargo test -p app an_item_label_draws_its_icons); a `null` `timeline.pageSize` follows the view height (cargo test -p app a_null_page_size_follows_the_view_height) || workbench/contrib/typeHierarchy | workbench contribution | M13 | verified | | Peek Type Hierarchy in workbench/hierarchy_peek.rs: supertypes/subtypes toggle, layout `typeHierarchyPeekLayout`, the focused message of an empty answer, `_executePrepareTypeHierarchy`, `_executeProvideSupertypes`, `_executeProvideSubtypes`; cargo test -p app hierarchy; ui-pair port/results/language-features.md (Type hierarchy) |