feat(welcome): group recent projects by Local and remote host (#6763)

When the recent list holds remote projects, Welcome › Projects, the Recent Projects popup, the title-bar Project Widget's Recent Projects and File › Open Recent group them under Local and each remote target (SSH · host, WSL · distro, Dev Container · folder), most recently used first, with collapsible groups and the per-row host pill dropped inside a host group; search flattens the groups again. Local-only lists are unchanged. Recent list rows now take their natural height, so two- and three-line remote rows no longer overlap in the popup's virtualized list.

Co-authored-by: dengliu <[email protected]>
Цей коміт міститься в:
Deng Liuтаdengliu authored and GitHub committed 2026-11-29 12:28:47 +08:00
1 джерело b53915e4b6
коміт 90734775b9
25 files changed
+1061 -104

No files matched your search

+118 -18
Переглянути файл
@@ -9,12 +9,21 @@ use std::path::Path;
/// Prefix of Open Recent item ids; the rest of the id is the project path.
pub const RECENT_PREFIX: &str = "recent:";
/// Item id of the local-projects section header in Open Recent.
pub const RECENT_LOCAL_ID: &str = "recent.local";
/// Prefix of remote host section header ids in Open Recent.
pub const RECENT_SECTION_PREFIX: &str = "recent.section:";
/// Prefix of items the frontend lists ([`MenuConfig::dynamic`]): `dyn:<action>` or `dyn:<action>|<arg>`.
pub const DYNAMIC_PREFIX: &str = "dyn:";
/// Action run for an Open Recent entry (argument: the project path).
pub const OPEN_RECENT_ACTION: &str = "file.openRecentProject";
pub const MAX_RECENT: usize = 15;
/// Whether `id` names a non-interactive Open Recent placeholder or section header.
pub fn is_recent_placeholder(id: &str) -> bool {
id == "recent.none" || id == RECENT_LOCAL_ID || id.starts_with(RECENT_SECTION_PREFIX)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Os {
Mac,
@@ -1087,33 +1096,107 @@ pub struct RemoteRecent {
pub opened_at_ms: f64,
}
pub struct RecentItem {
pub path: String,
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecentSection {
pub id: String,
pub label: String,
}
/// The local and remote recent projects, most recently opened first.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecentItem {
pub path: String,
pub label: String,
pub section: Option<RecentSection>,
}
fn parse_remote_recent(r: &RemoteRecent) -> (RecentSection, String) {
const SCHEMES: [(&str, &str, &str); 3] =
[("ssh://", "ssh", "SSH"), ("wsl://", "wsl", "WSL"), ("devcontainer://", "devContainer", "Dev Container")];
for (prefix, kind, kind_label) in SCHEMES {
if let Some(rest) = r.location.strip_prefix(prefix)
&& let Some(slash) = rest.find('/')
&& slash > 0
{
let remote_path = &rest[slash..];
let (host, shown_path) = match r.detail.strip_suffix(remote_path).and_then(|h| h.strip_suffix(':')) {
Some(host) if !host.is_empty() => (host, remote_path),
_ => r.detail.split_once(':').unwrap_or((&rest[..slash], remote_path)),
};
return (
RecentSection {
id: format!("{RECENT_SECTION_PREFIX}{kind}:{host}"),
label: format!("{kind_label} · {host}"),
},
format!("{} — {shown_path}", r.name),
);
}
}
let (host, shown_path) = r.detail.split_once(':').unwrap_or((r.detail.as_str(), r.detail.as_str()));
(
RecentSection { id: format!("{RECENT_SECTION_PREFIX}remote:{host}"), label: host.to_owned() },
format!("{} — {shown_path}", r.name),
)
}
/// The local and remote recent projects, grouped by host in MRU order when remote projects exist.
pub fn recent_items(
recent: &[ide_workspace::RecentProject],
remote: &[RemoteRecent],
home: Option<&Path>,
) -> Vec<RecentItem> {
enum Candidate<'a> {
Local { path: String, label: String },
Remote(&'a RemoteRecent),
}
let local = recent.iter().map(|p| {
let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) {
Some(rest) => format!("~/{}", rest.display()),
None => p.path.display().to_string(),
};
let item =
RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) };
(p.opened_at_ms, item)
(
p.opened_at_ms,
Candidate::Local {
path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name)
},
)
});
let remote = remote.iter().map(|r| {
(r.opened_at_ms, RecentItem { path: r.location.clone(), label: format!("{} — {}", r.name, r.detail) })
});
let mut items: Vec<(f64, RecentItem)> = local.chain(remote).collect();
let remote_candidates = remote.iter().map(|r| (r.opened_at_ms, Candidate::Remote(r)));
let mut items: Vec<(f64, Candidate<'_>)> = local.chain(remote_candidates).collect();
// Stable: the local list's own order holds among equal times.
items.sort_by(|a, b| b.0.total_cmp(&a.0));
items.into_iter().take(MAX_RECENT).map(|(_, item)| item).collect()
items.truncate(MAX_RECENT);
let has_remote = items.iter().any(|(_, c)| matches!(c, Candidate::Remote(_)));
if !has_remote {
return items
.into_iter()
.filter_map(|(_, c)| match c {
Candidate::Local { path, label } => Some(RecentItem { path, label, section: None }),
Candidate::Remote(_) => None,
})
.collect();
}
let mut groups: Vec<(String, Vec<RecentItem>)> = Vec::new();
for (_, candidate) in items {
let (section, path, label) = match candidate {
Candidate::Local { path, label } => {
(RecentSection { id: RECENT_LOCAL_ID.into(), label: "Local".into() }, path, label)
}
Candidate::Remote(r) => {
let (section, label) = parse_remote_recent(r);
(section, r.location.clone(), label)
}
};
let item = RecentItem { path, label, section: Some(section.clone()) };
if let Some((_, members)) = groups.iter_mut().find(|(id, _)| *id == section.id) {
members.push(item);
} else {
groups.push((section.id, vec![item]));
}
}
groups.into_iter().flat_map(|(_, members)| members).collect()
}
/// A menu entry for a menu bar drawn by the frontend (Windows title bar).
@@ -1202,13 +1285,30 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
Entry::RecentProjects if recent.is_empty() => {
out.push(MenuNode::Placeholder { id: "recent.none".into(), label: "No Recent Projects".into() })
}
Entry::RecentProjects => out.extend(recent.iter().map(|r| MenuNode::Action {
id: OPEN_RECENT_ACTION.into(),
label: r.label.clone(),
hint: None,
arg: Some(r.path.clone()),
checked: None,
})),
Entry::RecentProjects => {
let mut current_section: Option<&str> = None;
for r in recent {
if let Some(sec) = &r.section
&& current_section != Some(sec.id.as_str())
{
if current_section.is_some() {
out.push(MenuNode::Separator);
}
out.push(MenuNode::Placeholder {
id: sec.id.clone(),
label: config.label(&sec.id, &sec.label),
});
current_section = Some(sec.id.as_str());
}
out.push(MenuNode::Action {
id: OPEN_RECENT_ACTION.into(),
label: r.label.clone(),
hint: None,
arg: Some(r.path.clone()),
checked: None,
});
}
}
}
}
out
+119
Переглянути файл
@@ -0,0 +1,119 @@
import { expect, stubDesktop, test } from "./fixtures";
test("groups recent projects by Local and remote host across Welcome, Recent Projects, and Project Popup without row overlap", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 980, height: 740 });
await stubDesktop(page);
await page.evaluate(async () => {
const localProjects = [
{ path: "/Users/dev/git/gocommon", name: "gocommon", openedAtMs: 70_000, branch: "main" },
{ path: "/Users/dev/git/openidea_all", name: "openidea_all", openedAtMs: 40_000, branch: null },
{ path: "/Users/dev/git/superpowers", name: "superpowers", openedAtMs: 20_000, branch: "main" },
];
const remoteProjects = [
{
target: { kind: "ssh", config: "devbox" },
path: "/home/coder/git/openidea_all",
name: "openidea_all",
host: "[email protected]:22",
openedAtMs: 100_000,
},
{
target: { kind: "ssh", config: "mbp1" },
path: "/Users/dev/git/gocommon",
name: "gocommon",
host: "dev-mbp1.local",
openedAtMs: 90_000,
},
{
target: { kind: "ssh", config: "devbox" },
path: "/home/coder/git/gocommon",
name: "gocommon",
host: "[email protected]:22",
openedAtMs: 60_000,
},
{
target: { kind: "wsl", distro: "Ubuntu-24.04" },
path: "/home/dev/git/openidea_all",
name: "openidea_all",
host: "Ubuntu-24.04",
openedAtMs: 30_000,
},
];
localStorage.setItem("openidea.remote.recent", JSON.stringify(remoteProjects));
window.__ipc.handlers.recent_projects = () => localProjects;
window.__ipc.handlers.recent_project_groups = () => [];
window.__ipc.handlers.app_info = () => ({ version: "0.1.55" });
window.__ipc.handlers.window_open_projects = () => [
{ name: "openidea_all", root: "/Users/dev/git/openidea_all", current: true, remote: null },
{
name: "openidea_all",
root: "/home/coder/git/openidea_all",
current: false,
remote: { kind: "ssh", config: "devbox" },
},
];
const projectMod = "/src/platform/project.ts";
const recentMod = "/src/features/welcome/recent.ts";
const { useProject } = await import(/* @vite-ignore */ projectMod);
const { loadRecent, useRecent } = await import(/* @vite-ignore */ recentMod);
await loadRecent();
useRecent.setState({ home: "/Users/dev" });
const prev = useProject.getState().project;
if (prev) {
useProject.setState({
project: { ...prev, name: "openidea_all", displayName: "openidea_all", root: "/Users/dev/git/openidea_all" },
});
}
});
// 1. Project Widget dropdown keeps Open Projects flat and groups Recent Projects by host.
await page.getByRole("button", { name: "openidea_all" }).click();
const projectPopup = page.getByRole("dialog", { name: "Projects" });
await expect(projectPopup).toBeVisible();
await expect(projectPopup).toContainText("Open Projects");
await expect(projectPopup).toContainText("Recent Projects");
await expect(projectPopup).toContainText("dev-mbp1.local");
await expect(projectPopup).toContainText("Local");
await expect(projectPopup).toContainText("Ubuntu-24.04");
await page.keyboard.press("Escape");
await expect(projectPopup).toBeHidden();
// 2. Recent Projects popup groups by host and never overlaps rows (grouped or 3-line search results).
await page.evaluate(async () => {
const popupMod = "/src/features/welcome/RecentProjectsPopup.tsx";
const { showRecentProjectsPopup } = await import(/* @vite-ignore */ popupMod);
showRecentProjectsPopup();
});
const recentDialog = page.getByRole("dialog", { name: "Recent Projects" });
await expect(recentDialog).toBeVisible();
const assertNoVerticalOverlap = async () => {
const options = recentDialog.getByRole("option");
const count = await options.count();
expect(count).toBeGreaterThan(1);
const boxes = await Promise.all(Array.from({ length: count }, (_, i) => options.nth(i).boundingBox()));
for (let i = 1; i < boxes.length; i++) {
expect(boxes[i]!.y).toBeGreaterThanOrEqual(boxes[i - 1]!.y + boxes[i - 1]!.height - 0.5);
}
};
await assertNoVerticalOverlap();
await recentDialog.getByRole("textbox", { name: "Search recent projects" }).fill("openidea_all");
await assertNoVerticalOverlap();
await page.keyboard.press("Escape");
await expect(recentDialog).toBeHidden();
// 3. Welcome › Projects folds and unfolds host groups.
await page.evaluate(async () => {
const projectMod = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectMod);
useProject.setState({ project: null, lightEdit: false });
});
const welcomeList = page.getByRole("listbox", { name: "Recent projects" });
await expect(welcomeList.getByRole("option")).toHaveCount(11);
await welcomeList.getByRole("option").first().click();
await expect(welcomeList.getByRole("option")).toHaveCount(9);
});
+113 -14
Переглянути файл
@@ -94,7 +94,7 @@ pub fn fires_natively(spec: &[Entry], id: &str) -> bool {
/// The action an item id stands for, if it is an IDE action item.
fn item_action(id: &str) -> Option<&str> {
if id.starts_with(RECENT_PREFIX) || id == "recent.none" || id.starts_with("submenu:") {
if id.starts_with(RECENT_PREFIX) || is_recent_placeholder(id) || id.starts_with("submenu:") {
return None;
}
Some(id.strip_prefix(DYNAMIC_PREFIX).map_or(id, |rest| rest.split_once('|').map_or(rest, |(a, _)| a)))
@@ -102,7 +102,7 @@ fn item_action(id: &str) -> Option<&str> {
/// Whether the item `id` is enabled given the disabled action ids.
pub fn item_enabled(id: &str, disabled: &HashSet<String>) -> bool {
id != "recent.none" && item_action(id).is_none_or(|a| !disabled.contains(a))
!is_recent_placeholder(id) && item_action(id).is_none_or(|a| !disabled.contains(a))
}
/// Updates the enabled state of the installed menu's items in place (no rebuild).
@@ -254,7 +254,20 @@ fn render_items(entries: &[Entry], config: &MenuConfig, recent: &[RecentItem]) -
text: config.label("recent.none", "No Recent Projects"),
}),
Entry::RecentProjects => {
let mut current_section: Option<&str> = None;
for item in recent {
if let Some(sec) = &item.section
&& current_section != Some(sec.id.as_str())
{
if current_section.is_some() {
out.push(RenderedItem::Separator);
}
out.push(RenderedItem::Placeholder {
id: sec.id.clone(),
text: config.label(&sec.id, &sec.label),
});
current_section = Some(sec.id.as_str());
}
out.push(RenderedItem::Action {
id: format!("{RECENT_PREFIX}{}", item.path),
text: item.label.clone(),
@@ -769,7 +782,7 @@ mod tests {
fn recent_projects_change_only_the_file_menu() {
let entries = spec(Os::Mac);
let config = MenuConfig::default();
let recent = [RecentItem { path: "/p/a".into(), label: "a — ~/a".into() }];
let recent = [RecentItem { path: "/p/a".into(), label: "a — ~/a".into(), section: None }];
assert_eq!(
changed_menus(&render_bar(&entries, &config, &[]), &render_bar(&entries, &config, &recent)),
["file"]
@@ -808,7 +821,13 @@ mod tests {
let spec = spec(Os::Mac);
assert_eq!(route(&spec, "submenu:file"), None);
assert_eq!(route(&spec, "recent.none"), None);
assert_eq!(route(&spec, "recent.local"), None);
assert_eq!(route(&spec, "recent.section:ssh:dev@host:22"), None);
assert_eq!(route(&spec, "nonexistent.action"), None);
let disabled = HashSet::new();
assert!(!item_enabled("recent.none", &disabled));
assert!(!item_enabled("recent.local", &disabled));
assert!(!item_enabled("recent.section:ssh:dev@host:22", &disabled));
}
#[test]
@@ -1076,7 +1095,7 @@ mod tests {
}
#[test]
fn remote_projects_join_the_recent_list_by_when_they_were_opened() {
fn remote_projects_group_open_recent_by_host_in_mru_order() {
let local = |path: &str, at: f64| ide_workspace::RecentProject {
path: path.into(),
name: path.rsplit('/').next().unwrap().into(),
@@ -1085,19 +1104,99 @@ mod tests {
missing: false,
};
let recent = vec![local("/home/me/new", 30.0), local("/home/me/old", 10.0)];
let remote = [RemoteRecent {
location: "wsl://Ubuntu/home/me/api".into(),
name: "api".into(),
detail: "Ubuntu:/home/me/api".into(),
opened_at_ms: 20.0,
}];
let remote = [
RemoteRecent {
location: "ssh://devbox/home/coder/app".into(),
name: "app".into(),
detail: "[email protected]:22:/home/coder/app".into(),
opened_at_ms: 25.0,
},
RemoteRecent {
location: "wsl://Ubuntu/home/me/api".into(),
name: "api".into(),
detail: "Ubuntu:/home/me/api".into(),
opened_at_ms: 20.0,
},
RemoteRecent {
location: "ssh://devbox/home/coder/lib".into(),
name: "lib".into(),
detail: "[email protected]:22:/home/coder/lib".into(),
opened_at_ms: 5.0,
},
];
let items = recent_items(&recent, &remote, Some(Path::new("/home/me")));
let paths: Vec<&str> = items.iter().map(|i| i.path.as_str()).collect();
assert_eq!(paths, ["/home/me/new", "wsl://Ubuntu/home/me/api", "/home/me/old"]);
assert_eq!(items[1].label, "api — Ubuntu:/home/me/api");
assert_eq!(
paths,
[
"/home/me/new",
"/home/me/old",
"ssh://devbox/home/coder/app",
"ssh://devbox/home/coder/lib",
"wsl://Ubuntu/home/me/api",
]
);
assert_eq!(items[0].section.as_ref().map(|s| s.label.as_str()), Some("Local"));
assert_eq!(items[2].section.as_ref().map(|s| s.label.as_str()), Some("SSH · [email protected]:22"));
assert_eq!(items[2].label, "app — /home/coder/app");
assert_eq!(items[4].section.as_ref().map(|s| s.label.as_str()), Some("WSL · Ubuntu"));
assert_eq!(items[4].label, "api — /home/me/api");
let spec = vec![sub("openRecent", "Open Recent", vec![Entry::RecentProjects])];
let mut config = MenuConfig::default();
config.labels.insert("menu.recent.local".into(), "本地".into());
let MenuNode::Submenu { children, .. } = &model(&spec, &items, &config)[0] else { panic!("not a submenu") };
assert_eq!(
children,
&[
MenuNode::Placeholder { id: "recent.local".into(), label: "本地".into() },
MenuNode::Action {
id: OPEN_RECENT_ACTION.into(),
label: "new — ~/new".into(),
hint: None,
arg: Some("/home/me/new".into()),
checked: None,
},
MenuNode::Action {
id: OPEN_RECENT_ACTION.into(),
label: "old — ~/old".into(),
hint: None,
arg: Some("/home/me/old".into()),
checked: None,
},
MenuNode::Separator,
MenuNode::Placeholder {
id: "recent.section:ssh:[email protected]:22".into(),
label: "SSH · [email protected]:22".into(),
},
MenuNode::Action {
id: OPEN_RECENT_ACTION.into(),
label: "app — /home/coder/app".into(),
hint: None,
arg: Some("ssh://devbox/home/coder/app".into()),
checked: None,
},
MenuNode::Action {
id: OPEN_RECENT_ACTION.into(),
label: "lib — /home/coder/lib".into(),
hint: None,
arg: Some("ssh://devbox/home/coder/lib".into()),
checked: None,
},
MenuNode::Separator,
MenuNode::Placeholder { id: "recent.section:wsl:Ubuntu".into(), label: "WSL · Ubuntu".into() },
MenuNode::Action {
id: OPEN_RECENT_ACTION.into(),
label: "api — /home/me/api".into(),
hint: None,
arg: Some("wsl://Ubuntu/home/me/api".into()),
checked: None,
},
]
);
let many: Vec<_> = (0..20).map(|i| local(&format!("/p/{i}"), f64::from(i))).collect();
let items = recent_items(&many, &remote, None);
let items = recent_items(&many, &remote[1..2], None);
assert_eq!(items.len(), MAX_RECENT);
assert_eq!([items[0].path.as_str(), items[1].path.as_str()], ["wsl://Ubuntu/home/me/api", "/p/19"]);
assert_eq!(items[MAX_RECENT - 1].path, format!("/p/{}", 20 - MAX_RECENT + 1), "the remote one takes a slot");
@@ -1110,7 +1209,7 @@ mod tests {
"File",
vec![Entry::Native(Native::Undo), act("file.save", "Save All"), SEP, Entry::RecentProjects],
)];
let recent = [RecentItem { path: "/p/a".into(), label: "a — ~/a".into() }];
let recent = [RecentItem { path: "/p/a".into(), label: "a — ~/a".into(), section: None }];
let MenuNode::Submenu { children, .. } = &model(&spec, &recent, &MenuConfig::default())[0] else {
panic!("not a submenu")
};
+44
Переглянути файл
@@ -172,4 +172,48 @@ describe("ProjectPopup", () => {
fireEvent.keyDown(list, { key: "Enter" });
expect(openRecent).toHaveBeenLastCalledWith(exampleWeb, null);
});
it("groups Recent Projects by host in MRU order while keeping Open Projects flat", async () => {
const sshA = { kind: "ssh", config: "devbox" } as const;
const sshB = { kind: "ssh", config: "mbp" } as const;
open = [{ name: "openidea_all", root: "/Users/me/git/openidea_all", current: true, remote: null }];
groups = [];
recent = [
{ path: remoteLocation(sshA, "/srv/openidea_all"), name: "openidea_all", openedAtMs: 90, branch: null },
{ path: "/Users/me/git/gocommon", name: "gocommon", openedAtMs: 80, branch: "main" },
{ path: remoteLocation(sshB, "/Users/dev/gocommon"), name: "gocommon", openedAtMs: 70, branch: null },
{ path: remoteLocation(sshA, "/srv/gocommon"), name: "gocommon", openedAtMs: 60, branch: null },
{ path: "/Users/me/git/superpowers", name: "superpowers", openedAtMs: 50, branch: null },
];
const anchor = createRef<HTMLButtonElement>();
render(
<>
<button ref={anchor} />
<ProjectPopup anchor={anchor} onClose={() => {}} />
</>,
);
await screen.findByText("Recent Projects");
const list = screen.getByRole("listbox");
const text = list.textContent ?? "";
const order = [
"Open Projects",
"Recent Projects",
"SSH·devbox",
"/srv/openidea_all",
"/srv/gocommon",
"Local",
"~/git/gocommon",
"~/git/superpowers",
"SSH·mbp",
"/Users/dev/gocommon",
];
expect(order.every((t) => text.includes(t))).toBe(true);
expect(order.map((t) => text.indexOf(t))).toEqual([...order.map((t) => text.indexOf(t))].sort((a, b) => a - b));
// Rows inside a host group omit the duplicate per-row host pill; typing to filter flattens and restores it.
const groupedRemote = within(list).getByText("/srv/openidea_all").closest('[role="option"]')!;
expect(groupedRemote.querySelector('[data-remote-kind="ssh"]')).toBeNull();
fireEvent.keyDown(list, { key: "g" });
const searchedRemote = within(list).getByText("/srv/gocommon").closest('[role="option"]')!;
expect(searchedRemote.querySelector('[data-remote-kind="ssh"]')?.textContent).toContain("devbox");
});
});
+46 -15
Переглянути файл
@@ -6,6 +6,7 @@ import { HighlightedText, Icon, Popup, showContextMenu, type IconName, T } from
import type { ProjectPopupProps } from "@/workbench/contributions";
import {
askRemoveRecent,
HostGroupTitle,
ProjectBadge,
projectAppearanceMenu,
recentMenu,
@@ -13,7 +14,15 @@ import {
splitRemoteMatch,
unavailableTitle,
} from "./RecentList";
import { filterRecent, loadRecent, openRecent, recentRows, useRecent, type RecentMatch } from "./recent";
import {
filterRecent,
loadRecent,
openRecent,
recentRows,
useRecent,
type HostGroup,
type RecentMatch,
} from "./recent";
import styles from "./ProjectPopup.module.css";
import { tx } from "@/platform/i18n";
import { parseRemoteLocation, remoteLocation } from "@/platform/remote";
@@ -21,7 +30,7 @@ import { projectWindowOverride, type ProjectWindowOverride } from "@/workbench/p
type Entry =
| { kind: "action"; id: string; label: string; icon: IconName }
| { kind: "project"; open: boolean; m: RecentMatch; group?: string | null };
| { kind: "project"; open: boolean; m: RecentMatch; group?: string | null; hostGroup?: HostGroup | null };
const ACTIONS: { id: string; label: string; icon: IconName }[] = [
{ id: "file.newProject", label: "New Project…", icon: "plus" },
@@ -80,7 +89,12 @@ export function ProjectPopup({ anchor, onClose }: ProjectPopupProps) {
expanded,
query,
home,
).flatMap((r) => (r.kind === "project" ? [{ kind: "project" as const, open: false, m: r.m, group: r.group }] : []));
[],
).flatMap((r) =>
r.kind === "project"
? [{ kind: "project" as const, open: false, m: r.m, group: r.group, hostGroup: r.hostGroup ?? null }]
: [],
);
const acts = query ? [] : ACTIONS.filter((a) => actions.has(a.id)).map((a) => ({ kind: "action" as const, ...a }));
return [...acts, ...open, ...rest];
}, [actions, recent, groups, home, openProjects, query]);
@@ -194,7 +208,7 @@ export function ProjectPopup({ anchor, onClose }: ProjectPopupProps) {
<span className={styles.label}>{tx(e.label)}</span>
</>
) : (
<ProjectRow m={e.m} active={i === current} />
<ProjectRow m={e.m} active={i === current} hideHost={!e.open && e.hostGroup != null} />
)}
</div>
</div>
@@ -218,7 +232,14 @@ function Header({ first, children }: { first: boolean; children: ReactNode }) {
);
}
/** A project group's name above its first project; a separator where the ungrouped projects start. */
function sectionKey(entry: Entry | undefined): string | null {
if (entry?.kind !== "project" || entry.open) return null;
if (entry.group) return `group:${entry.group}`;
if (entry.hostGroup) return `host:${entry.hostGroup.id}`;
return null;
}
/** A project or host group's name above its first project; a separator where sections change. */
function GroupBoundary({
entry,
previous,
@@ -226,19 +247,29 @@ function GroupBoundary({
entry: Extract<Entry, { kind: "project" }>;
previous: Entry | undefined;
}) {
const before = previous?.kind === "project" && !previous.open ? (previous.group ?? null) : null;
const group = entry.group ?? null;
if (group === before) return null;
if (group === null) return <div className={styles.separator} role="separator" />;
const prevRecent = previous?.kind === "project" && !previous.open;
const before = sectionKey(previous);
const current = sectionKey(entry);
if (current === before) return null;
if (current === null) return <div className={styles.separator} role="separator" />;
return (
<div className={styles.groupHeader}>
<Icon name="folder" size={14} />
<span className={styles.label}>{group}</span>
</div>
<>
{prevRecent && <div className={styles.separator} role="separator" />}
<div className={styles.groupHeader}>
{entry.group ? (
<>
<Icon name="folder" size={14} />
<span className={styles.label}>{entry.group}</span>
</>
) : (
entry.hostGroup && <HostGroupTitle host={entry.hostGroup} iconSize={14} />
)}
</div>
</>
);
}
function ProjectRow({ m, active }: { m: RecentMatch; active: boolean }) {
function ProjectRow({ m, active, hideHost }: { m: RecentMatch; active: boolean; hideHost?: boolean }) {
const { hostMatch, locationMatch, locationText } = splitRemoteMatch(m);
return (
@@ -256,7 +287,7 @@ function ProjectRow({ m, active }: { m: RecentMatch; active: boolean }) {
indices={m.nameMatch}
tone={active ? "accent" : "strong"}
/>
{m.remote && <RemoteHostPill remote={m.remote} hostMatch={hostMatch} />}
{!hideHost && m.remote && <RemoteHostPill remote={m.remote} hostMatch={hostMatch} />}
<HighlightedText className={styles.path} text={locationText} indices={locationMatch} />
{m.project.branch && (
<span className={styles.metadata}>
+85 -8
Переглянути файл
@@ -24,13 +24,23 @@ import {
import {
askRemoveRecent,
groupMenu,
HostGroupTitle,
ProjectBadge,
recentMenu,
RemoteHostPill,
splitRemoteMatch,
unavailableTitle,
} from "./RecentList";
import { openRecent, recentRows, setGroupExpanded, useRecent, type RecentMatch, type RecentRow } from "./recent";
import {
openRecent,
recentRows,
setGroupExpanded,
setHostGroupExpanded,
useRecent,
type HostGroup,
type RecentMatch,
type RecentRow,
} from "./recent";
import { projectWindowOverride } from "@/workbench/projectWindow";
import type { RecentProjectGroup } from "@/platform/ipc";
import styles from "./Welcome.module.css";
@@ -248,11 +258,51 @@ function GroupRow({
);
}
/** A host group (`Local` or a remote target): click or Enter folds its projects. */
function HostGroupRow({
host,
count,
id,
selected,
onSelect,
}: {
host: HostGroup;
count: number;
id: string;
selected: boolean;
onSelect: () => void;
}) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (selected) ref.current?.scrollIntoView?.({ block: "nearest" });
}, [selected]);
return (
<div
ref={ref}
id={id}
role="option"
aria-selected={selected}
aria-expanded={host.expanded}
className={clsx(styles.project, styles.group, selected && styles.projectSelected)}
onMouseDown={(e) => e.preventDefault()}
onClick={() => {
onSelect();
setHostGroupExpanded(host.id, !host.expanded);
}}
>
<Icon name={host.expanded ? "chevron-down" : "chevron-right"} size={16} />
<HostGroupTitle host={host} iconSize={16} />
<span className={styles.groupCount}>{count}</span>
</div>
);
}
function ProjectRow({
m,
id,
selected,
nested,
hideHost,
onSelect,
onOpen,
}: {
@@ -261,6 +311,8 @@ function ProjectRow({
selected: boolean;
/** Listed under a group. */
nested?: boolean;
/** Listed under a host group header that already names the remote host. */
hideHost?: boolean;
onSelect: () => void;
/** Its modifier keys pick the window ({@link projectWindowOverride}). */
onOpen: (e: MouseEvent<HTMLDivElement>) => void;
@@ -314,7 +366,7 @@ function ProjectRow({
</span>
) : (
<>
{m.remote && <RemoteHostPill remote={m.remote} hostMatch={hostMatch} />}
{!hideHost && m.remote && <RemoteHostPill remote={m.remote} hostMatch={hostMatch} />}
<HighlightedText className={styles.projectPath} text={locationText} indices={locationMatch} />
</>
)}
@@ -364,13 +416,17 @@ export function handleListKey<T>(
export function ProjectsPage() {
const projects = useRecent((s) => s.projects);
const groups = useRecent((s) => s.groups);
const collapsedHosts = useRecent((s) => s.collapsedHosts);
const loaded = useRecent((s) => s.loaded);
const home = useRecent((s) => s.home);
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const search = useRef<HTMLInputElement>(null);
const baseId = useId();
const items = useMemo(() => recentRows(projects, groups, query, home), [projects, groups, query, home]);
const items = useMemo(
() => recentRows(projects, groups, query, home, collapsedHosts),
[projects, groups, query, home, collapsedHosts],
);
const current = Math.max(0, Math.min(active, items.length - 1));
if (!loaded) return null;
@@ -384,10 +440,17 @@ export function ProjectsPage() {
!input || (input.selectionStart === input.value.length && input.selectionEnd === input.value.length);
const row = items[current];
// A group folds with ← / → (and Enter, below), like a tree node.
if (row?.kind === "group" && !input && (e.key === "ArrowLeft" || e.key === "ArrowRight")) {
e.preventDefault();
void setGroupExpanded(row.group.name, e.key === "ArrowRight");
return;
if ((!input || !input.value) && (e.key === "ArrowLeft" || e.key === "ArrowRight")) {
if (row?.kind === "group") {
e.preventDefault();
void setGroupExpanded(row.group.name, e.key === "ArrowRight");
return;
}
if (row?.kind === "host") {
e.preventDefault();
setHostGroupExpanded(row.host.id, e.key === "ArrowRight");
return;
}
}
const r = handleListKey(e, { items, current, caretAtEnd });
if (!r) {
@@ -414,6 +477,10 @@ export function ProjectsPage() {
}
return;
}
if (match.kind === "host") {
if (r.kind === "open") setHostGroupExpanded(match.host.id, !match.host.expanded);
return;
}
if (r.kind === "open") void openRecent(match.m.project, projectWindowOverride(e));
else if (r.kind === "remove") void askRemoveRecent(match.m.project);
else {
@@ -462,13 +529,23 @@ export function ProjectsPage() {
selected={i === current}
onSelect={() => setActive(i)}
/>
) : row.kind === "host" ? (
<HostGroupRow
key={`host:${row.host.id}`}
host={row.host}
count={row.count}
id={optionId(i)}
selected={i === current}
onSelect={() => setActive(i)}
/>
) : (
<ProjectRow
key={row.m.project.path}
m={row.m}
id={optionId(i)}
selected={i === current}
nested={row.group !== null}
nested={row.group !== null || row.hostGroup != null}
hideHost={row.hostGroup != null}
onSelect={() => setActive(i)}
onOpen={(e) => void openRecent(row.m.project, projectWindowOverride(e))}
/>
+205 -34
Переглянути файл
@@ -1,5 +1,15 @@
import { writeClipboardText } from "@/platform/clipboard";
import { useMemo, useState, useSyncExternalStore, type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
import {
useEffect,
useId,
useMemo,
useRef,
useState,
useSyncExternalStore,
type KeyboardEvent,
type MouseEvent,
type ReactNode,
} from "react";
import clsx from "clsx";
import { call, commands, type RecentProject, type RecentProjectGroup } from "@/platform/ipc";
import { revealInFileManager, showInFileManagerLabel } from "@/platform/fileManager";
@@ -8,9 +18,9 @@ import {
HighlightedText,
Icon,
IconButton,
List,
SearchField,
Spinner,
T,
listNavigate,
showContextMenu,
type MenuItem,
@@ -26,15 +36,18 @@ import { open as openDialog } from "@/platform/dialog";
import { subscribeTabColors, tabColorOverride, tabColorVars, tabColorsVersion } from "@/workbench/tabColors";
import {
createGroup,
filterRecent,
groupNameError,
groupOf,
moveToGroup,
openRecent,
recentRows,
removeGroup,
removeRecent,
renameGroup,
setGroupExpanded,
setHostGroupExpanded,
useRecent,
type HostGroup,
type RecentMatch,
} from "./recent";
import styles from "./Welcome.module.css";
@@ -118,6 +131,32 @@ export function RemoteHostPill({
);
}
/** Icon and label of a `Local` or remote host group header. */
export function HostGroupTitle({ host, iconSize }: { host: HostGroup; iconSize: number }) {
if (host.kind === "local") {
return (
<>
<Icon name="folder" size={iconSize} />
<span className={styles.hostTitle}>
<T>Local</T>
</span>
</>
);
}
return (
<>
<Icon name="remote" size={iconSize} />
<span className={styles.hostTitle} data-remote-kind={host.kind}>
<span className={styles.hostKind}>{host.kindLabel}</span>
<span className={styles.remoteDot} aria-hidden="true">
·
</span>
<span className={styles.hostName}>{host.host}</span>
</span>
</>
);
}
/** Change Project Icon…: an SVG or PNG for the project, kept in its `.openidea` folder. */
async function chooseProjectIcon(root: string) {
const file = await openDialog({ filters: [{ name: tx("Image files"), extensions: ["svg", "png"] }] });
@@ -275,11 +314,13 @@ function RecentRow({
m,
active,
compact,
hideHost,
onOpened,
}: {
m: RecentMatch;
active: boolean;
compact?: boolean;
hideHost?: boolean;
onOpened?: () => void;
}) {
const opening = useRecent((s) => s.opening === m.project.path);
@@ -303,7 +344,7 @@ function RecentRow({
</span>
)}
</span>
{m.remote && <RemoteHostPill remote={m.remote} hostMatch={hostMatch} />}
{!hideHost && m.remote && <RemoteHostPill remote={m.remote} hostMatch={hostMatch} />}
<HighlightedText className={styles.recentPath} text={locationText} indices={locationMatch} />
</span>
{opening ? (
@@ -322,7 +363,7 @@ function RecentRow({
onClick={(e) => {
e.stopPropagation();
const r = e.currentTarget.getBoundingClientRect();
showContextMenu({ x: r.left, y: r.bottom + 2 }, recentMenu(m.project, onOpened));
showContextMenu({ x: r.left, y: r.bottom + 2 }, recentMenu(m.project, onOpened, onOpened));
}}
/>
</>
@@ -345,14 +386,26 @@ export interface RecentListProps {
/** Searchable, keyboard-navigable recent projects list (search field keeps focus). */
export function RecentList({ exclude, compact, autoFocus, onOpened, className, toolbar }: RecentListProps) {
const projects = useRecent((s) => s.projects);
const groups = useRecent((s) => s.groups);
const collapsedHosts = useRecent((s) => s.collapsedHosts);
const home = useRecent((s) => s.home);
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const items = useMemo(
() => filterRecent(exclude ? projects.filter((p) => p.path !== exclude) : projects, query, home),
[projects, query, home, exclude],
const listRef = useRef<HTMLDivElement>(null);
const baseId = useId();
const visibleProjects = useMemo(
() => (exclude ? projects.filter((p) => p.path !== exclude) : projects),
[projects, exclude],
);
const current = Math.min(active, items.length - 1);
const items = useMemo(
() => recentRows(visibleProjects, groups, query, home, collapsedHosts),
[visibleProjects, groups, query, home, collapsedHosts],
);
const current = Math.max(0, Math.min(active, items.length - 1));
useEffect(() => {
listRef.current?.querySelector(`[data-recent-index="${current}"]`)?.scrollIntoView?.({ block: "nearest" });
}, [current]);
/** `e`'s modifier keys pick the window ({@link projectWindowOverride}); a plain click or Enter follows "Open project in". */
const open = (m: RecentMatch | undefined, e: ModifierKeys) => {
@@ -360,24 +413,45 @@ export function RecentList({ exclude, compact, autoFocus, onOpened, className, t
};
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
const row = items[current];
const field = e.currentTarget;
if (!field.value && (e.key === "ArrowLeft" || e.key === "ArrowRight")) {
if (row?.kind === "group") {
e.preventDefault();
void setGroupExpanded(row.group.name, e.key === "ArrowRight");
return;
}
if (row?.kind === "host") {
e.preventDefault();
setHostGroupExpanded(row.host.id, e.key === "ArrowRight");
return;
}
}
if (e.key === "Enter") {
e.preventDefault();
open(items[current], e);
if (row?.kind === "group") void setGroupExpanded(row.group.name, !row.group.expanded);
else if (row?.kind === "host") setHostGroupExpanded(row.host.id, !row.host.expanded);
else if (row?.kind === "project") open(row.m, e);
return;
}
// Delete removes the selected project only when it has no text to delete: the caret is at the end
// of the query (⌘⌫: the query is empty). Otherwise it edits the query.
const field = e.currentTarget;
const atEnd = field.selectionStart === field.value.length && field.selectionEnd === field.value.length;
if (((e.key === "Delete" && atEnd) || (e.key === "Backspace" && e.metaKey && !field.value)) && items[current]) {
if (
((e.key === "Delete" && atEnd) || (e.key === "Backspace" && e.metaKey && !field.value)) &&
row?.kind === "project"
) {
e.preventDefault();
void askRemoveRecent(items[current]!.project);
void askRemoveRecent(row.m.project, onOpened);
return;
}
if (e.key === "ContextMenu" || (e.key === "F10" && e.shiftKey)) {
const m = items[current];
const el = e.currentTarget.getBoundingClientRect();
if (m) showContextMenu({ x: el.left + 20, y: el.bottom + 4 }, recentMenu(m.project, onOpened));
if (row?.kind === "project") {
showContextMenu({ x: el.left + 20, y: el.bottom + 4 }, recentMenu(row.m.project, onOpened, onOpened));
} else if (row?.kind === "group") {
showContextMenu({ x: el.left + 20, y: el.bottom + 4 }, groupMenu(row.group));
}
e.preventDefault();
return;
}
@@ -387,6 +461,8 @@ export function RecentList({ exclude, compact, autoFocus, onOpened, className, t
setActive(next);
};
const optionId = (i: number) => `${baseId}-r${i}`;
return (
<div className={clsx(styles.recentList, className)}>
<div className={styles.searchRow}>
@@ -398,6 +474,8 @@ export function RecentList({ exclude, compact, autoFocus, onOpened, className, t
}}
placeholder="Search projects"
aria-label="Search recent projects"
aria-controls={`${baseId}-list`}
aria-activedescendant={items.length ? optionId(current) : undefined}
autoFocus={autoFocus}
data-autofocus={autoFocus || undefined}
onKeyDown={onKeyDown}
@@ -405,26 +483,119 @@ export function RecentList({ exclude, compact, autoFocus, onOpened, className, t
/>
{toolbar}
</div>
<List<RecentMatch>
aria-label="Recent projects"
items={items}
getKey={(m) => m.project.path}
activeIndex={current}
onActiveChange={setActive}
focusable={false}
rowHeight={compact ? 40 : 48}
className={styles.list}
onActivate={(m, _i, e) => open(m, e)}
onContextMenu={(m, i, e: MouseEvent) => {
e.preventDefault();
setActive(i);
showContextMenu(e, recentMenu(m.project, onOpened));
}}
renderItem={(m, s) => <RecentRow m={m} active={s.active} compact={compact} onOpened={onOpened} />}
empty={
<div
ref={listRef}
id={`${baseId}-list`}
role="listbox"
aria-label={tx("Recent projects")}
tabIndex={-1}
className={styles.recentScroll}
>
{items.length === 0 ? (
<span className={styles.noMatches}>{query ? tx("No matching projects") : tx("No recent projects")}</span>
}
/>
) : (
items.map((row, i) => {
const selected = i === current;
if (row.kind === "group") {
return (
<div
key={`group:${row.group.name}`}
id={optionId(i)}
data-recent-index={i}
role="option"
aria-selected={selected}
aria-expanded={row.group.expanded}
className={clsx(styles.recentItem, styles.recentGroup, selected && styles.recentSelected)}
onMouseDown={(e) => {
if (e.button !== 0) return;
e.preventDefault();
setActive(i);
}}
onClick={() => void setGroupExpanded(row.group.name, !row.group.expanded)}
onContextMenu={(e: MouseEvent) => {
e.preventDefault();
setActive(i);
showContextMenu(e, groupMenu(row.group));
}}
>
<Icon name={row.group.expanded ? "chevron-down" : "chevron-right"} size={14} />
<Icon name="folder" size={14} />
<span className={styles.groupName}>{row.group.name}</span>
<span className={styles.groupCount}>{row.count}</span>
<IconButton
icon="more"
title="Group actions"
size="small"
iconSize={14}
className={styles.rowMore}
tabIndex={-1}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => {
e.stopPropagation();
setActive(i);
const r = e.currentTarget.getBoundingClientRect();
showContextMenu({ x: r.left, y: r.bottom + 2 }, groupMenu(row.group));
}}
/>
</div>
);
}
if (row.kind === "host") {
return (
<div
key={`host:${row.host.id}`}
id={optionId(i)}
data-recent-index={i}
role="option"
aria-selected={selected}
aria-expanded={row.host.expanded}
className={clsx(styles.recentItem, styles.recentGroup, selected && styles.recentSelected)}
onMouseDown={(e) => {
if (e.button !== 0) return;
e.preventDefault();
setActive(i);
}}
onClick={() => setHostGroupExpanded(row.host.id, !row.host.expanded)}
>
<Icon name={row.host.expanded ? "chevron-down" : "chevron-right"} size={14} />
<HostGroupTitle host={row.host} iconSize={14} />
<span className={styles.groupCount}>{row.count}</span>
</div>
);
}
const nested = row.group !== null || row.hostGroup != null;
return (
<div
key={row.m.project.path}
id={optionId(i)}
data-recent-index={i}
role="option"
aria-selected={selected}
className={clsx(styles.recentItem, nested && styles.recentNested, selected && styles.recentSelected)}
onMouseDown={(e) => {
if (e.button !== 0) return;
e.preventDefault();
setActive(i);
}}
onClick={(e) => open(row.m, e)}
onContextMenu={(e: MouseEvent) => {
e.preventDefault();
setActive(i);
showContextMenu(e, recentMenu(row.m.project, onOpened, onOpened));
}}
>
<RecentRow
m={row.m}
active={selected}
compact={compact}
hideHost={row.hostGroup != null}
onOpened={onOpened}
/>
</div>
);
})
)}
</div>
</div>
);
}
+4 -1
Переглянути файл
@@ -1,6 +1,7 @@
import { useEffect } from "react";
import { create } from "zustand";
import { useProject } from "@/platform/project";
import { remoteLocation, useRemote } from "@/platform/remote";
import { Dialog, T } from "@/ui";
import { RecentList } from "./RecentList";
import { loadRecent } from "./recent";
@@ -17,7 +18,9 @@ const close = () => useRecentPopup.setState({ open: false });
/** File › Open Recent: chooser over recent projects (overlay contribution). */
export function RecentProjectsPopup() {
const open = useRecentPopup((s) => s.open);
const current = useProject((s) => s.project?.root ?? null);
const root = useProject((s) => s.project?.root ?? null);
const session = useRemote((s) => s.session);
const current = root && session?.root === root ? remoteLocation(session.target, root) : root;
useEffect(() => {
if (open) void loadRecent();
}, [open]);
+50 -2
Переглянути файл
@@ -283,6 +283,27 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.hostTitle {
flex: 1;
min-width: 0;
display: inline-flex;
align-items: center;
gap: var(--space-1);
color: var(--fg-strong);
font-weight: 600;
overflow: hidden;
white-space: nowrap;
}
.hostKind {
flex: none;
color: var(--fg-muted);
font-weight: 500;
}
.hostName {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.groupCount {
color: var(--fg-faint);
}
@@ -581,9 +602,34 @@
align-items: center;
gap: 10px;
}
.list {
.recentScroll {
flex: 1;
min-height: 0;
overflow-y: auto;
display: flex;
flex-direction: column;
outline: none;
}
.recentItem {
display: flex;
align-items: center;
padding: var(--space-1-5) var(--space-2);
border-radius: var(--radius-selection, 5px);
cursor: default;
}
.recentItem:hover {
background: var(--bg-tree-hover);
}
.recentSelected,
.recentSelected:hover {
background: var(--bg-tree-selected);
}
.recentGroup {
gap: var(--space-1-5);
--icon-color: var(--fg-muted);
}
.recentNested {
padding-left: 28px;
}
.recent {
flex: 1;
@@ -597,6 +643,7 @@
min-width: 0;
display: flex;
flex-direction: column;
gap: var(--space-0-5);
}
.recentTop {
display: flex;
@@ -643,7 +690,8 @@
flex: none;
opacity: 0;
}
.recent:hover .rowMore,
.recentItem:hover .rowMore,
.recentSelected .rowMore,
.rowMore:focus-visible {
opacity: 1;
}
+45 -3
Переглянути файл
@@ -89,11 +89,20 @@ describe("session restore", () => {
});
describe("project groups", () => {
const formatRow = (r: ReturnType<typeof recentRows>[number]) => {
if (r.kind === "group") return `[${r.group.name} ${r.count}]`;
if (r.kind === "host")
return `{${r.host.kind === "local" ? "Local" : `${r.host.kindLabel} · ${r.host.host}`} ${r.count}}`;
return `${r.group || r.hostGroup ? " " : ""}${r.m.project.name}`;
};
const rows = (query = "") =>
recentRows(projects, useRecent.getState().groups, query, "/Users/me").map((r) =>
r.kind === "group" ? `[${r.group.name} ${r.count}]` : `${r.group ? " " : ""}${r.m.project.name}`,
recentRows(projects, useRecent.getState().groups, query, "/Users/me", useRecent.getState().collapsedHosts).map(
formatRow,
);
afterEach(() => useRecent.setState({ groups: [] }));
afterEach(() => {
useRecent.setState({ groups: [], collapsedHosts: [] });
localStorage.clear();
});
it("lists groups first with their projects, then the rest; a search lists matches only", async () => {
expect(rows()).toEqual(["acme-api", "openidea-ide", "tokio", "notes"]);
@@ -128,4 +137,37 @@ describe("project groups", () => {
await removeGroup("Open source");
expect(rows()).toEqual(["acme-api", "openidea-ide", "tokio", "notes"]);
});
it("groups ungrouped projects by Local and remote host when remote entries exist", async () => {
const mixed = [
{ path: "ssh://devbox/srv/acme", name: "acme-remote", openedAtMs: 50, branch: null },
...projects,
{ path: "wsl://Ubuntu/home/me/tokio", name: "tokio-wsl", openedAtMs: 10, branch: null },
{ path: "ssh://devbox/srv/lib", name: "lib-remote", openedAtMs: 5, branch: null },
];
await createGroup("Pinned", "/Users/me/dev/acme");
expect(recentRows(mixed, useRecent.getState().groups, "", "/Users/me").map(formatRow)).toEqual([
"[Pinned 1]",
" acme-api",
"{SSH · devbox 2}",
" acme-remote",
" lib-remote",
"{Local 3}",
" openidea-ide",
" tokio",
" notes",
"{WSL · Ubuntu 1}",
" tokio-wsl",
]);
expect(recentRows(mixed, useRecent.getState().groups, "", "/Users/me", ["local"]).map(formatRow)).toEqual([
"[Pinned 1]",
" acme-api",
"{SSH · devbox 2}",
" acme-remote",
" lib-remote",
"{Local 3}",
"{WSL · Ubuntu 1}",
" tokio-wsl",
]);
});
});
+90 -7
Переглянути файл
@@ -32,6 +32,8 @@ interface RecentState {
projects: RecentProject[];
/** Project groups (New Project Group…), shown above the ungrouped projects. */
groups: RecentProjectGroup[];
/** Host group ids (`local`, `ssh:…`, `wsl:…`) folded by the user. */
collapsedHosts: string[];
loaded: boolean;
home: string | null;
version: string | null;
@@ -39,9 +41,30 @@ interface RecentState {
opening: string | null;
}
const COLLAPSED_HOSTS_KEY = "openidea.recent.collapsedHosts";
function readCollapsedHosts(): string[] {
try {
const raw = JSON.parse(localStorage.getItem(COLLAPSED_HOSTS_KEY) ?? "[]") as unknown;
return Array.isArray(raw) ? raw.filter((v): v is string => typeof v === "string") : [];
} catch {
return [];
}
}
function writeCollapsedHosts(ids: string[]) {
try {
if (ids.length) localStorage.setItem(COLLAPSED_HOSTS_KEY, JSON.stringify(ids));
else localStorage.removeItem(COLLAPSED_HOSTS_KEY);
} catch {
/* storage unavailable */
}
}
export const useRecent = create<RecentState>(() => ({
projects: [],
groups: [],
collapsedHosts: readCollapsedHosts(),
loaded: false,
home: null,
version: null,
@@ -62,7 +85,13 @@ const SAMPLE: RecentProject[] = [
export async function loadRecent() {
if (!isTauri()) {
useRecent.setState({ projects: SAMPLE, loaded: true, home: "/Users/dev", version: "0.1.0-dev" });
useRecent.setState({
projects: SAMPLE,
collapsedHosts: readCollapsedHosts(),
loaded: true,
home: "/Users/dev",
version: "0.1.0-dev",
});
return;
}
const [projects, groups, info, home] = await Promise.all([
@@ -74,6 +103,7 @@ export async function loadRecent() {
useRecent.setState({
projects: withRemotes(projects),
groups,
collapsedHosts: readCollapsedHosts(),
loaded: true,
version: info?.version ?? useRecent.getState().version,
home: home ? home.replace(/\/+$/, "") : useRecent.getState().home,
@@ -348,30 +378,83 @@ export function setGroupExpanded(name: string, expanded: boolean) {
return saveGroups(groups().map((g) => (g.name === name ? { ...g, expanded } : g)));
}
export function setHostGroupExpanded(id: string, expanded: boolean) {
const current = useRecent.getState().collapsedHosts;
const next = expanded ? current.filter((h) => h !== id) : current.includes(id) ? current : [...current, id];
useRecent.setState({ collapsedHosts: next });
writeCollapsedHosts(next);
}
export type HostGroup =
| { id: "local"; kind: "local"; expanded: boolean }
| {
id: string;
kind: RemoteTarget["kind"];
kindLabel: string;
host: string;
expanded: boolean;
};
export type RecentRow =
| { kind: "group"; group: RecentProjectGroup; count: number }
| { kind: "project"; m: RecentMatch; group: string | null };
| { kind: "host"; host: HostGroup; count: number }
| { kind: "project"; m: RecentMatch; group: string | null; hostGroup?: HostGroup | null };
/**
* The rows of the list: without a query, groups first (their projects under the expanded
* ones, most recent first), then the ungrouped projects; while searching, the matches only.
* The rows of the list: without a query, custom groups first (their projects under the expanded
* ones, most recent first), then the remaining projects grouped by host (`Local` and each remote
* host in MRU order) when any remote project exists, or flat when all projects are local; while
* searching, the matches only.
*/
export function recentRows(
projects: readonly RecentProject[],
groupList: readonly RecentProjectGroup[],
query: string,
home?: string | null,
collapsedHosts: readonly string[] = [],
): RecentRow[] {
const matches = filterRecent(projects, query, home);
if (query.trim() || groupList.length === 0) return matches.map((m) => ({ kind: "project", m, group: null }));
if (query.trim()) return matches.map((m) => ({ kind: "project", m, group: null, hostGroup: null }));
const rows: RecentRow[] = [];
const grouped = new Set<string>();
for (const group of groupList) {
const members = matches.filter((m) => group.paths.includes(m.project.path));
members.forEach((m) => grouped.add(m.project.path));
rows.push({ kind: "group", group, count: members.length });
if (group.expanded) rows.push(...members.map((m): RecentRow => ({ kind: "project", m, group: group.name })));
if (group.expanded) {
rows.push(...members.map((m): RecentRow => ({ kind: "project", m, group: group.name, hostGroup: null })));
}
}
const rest = matches.filter((m) => !grouped.has(m.project.path));
if (!rest.some((m) => m.remote !== null)) {
for (const m of rest) rows.push({ kind: "project", m, group: null, hostGroup: null });
return rows;
}
const collapsed = new Set(collapsedHosts);
const buckets = new Map<string, { host: HostGroup; members: RecentMatch[] }>();
for (const m of rest) {
const id = m.remote ? `${m.remote.kind}:${m.remote.host}` : "local";
let bucket = buckets.get(id);
if (!bucket) {
const host: HostGroup = m.remote
? {
id,
kind: m.remote.kind,
kindLabel: m.remote.kindLabel,
host: m.remote.host,
expanded: !collapsed.has(id),
}
: { id: "local", kind: "local", expanded: !collapsed.has("local") };
bucket = { host, members: [] };
buckets.set(id, bucket);
}
bucket.members.push(m);
}
for (const { host, members } of buckets.values()) {
rows.push({ kind: "host", host, count: members.length });
if (host.expanded) {
rows.push(...members.map((m): RecentRow => ({ kind: "project", m, group: null, hostGroup: host })));
}
}
for (const m of matches) if (!grouped.has(m.project.path)) rows.push({ kind: "project", m, group: null });
return rows;
}
+108
Переглянути файл
@@ -276,6 +276,114 @@ describe("Welcome › Projects", () => {
expect(screen.getByText("Welcome to OpenIDEA")).toBeTruthy();
expect(screen.queryByLabelText("Search projects")).toBeNull();
});
it("groups projects by Local and remote host in MRU order, folds hosts, and flattens on search", async () => {
recent = [
{ name: "gocommon", path: "/Users/me/git/gocommon", branch: "main", openedAtMs: 70 },
{ name: "openidea_all", path: "/Users/me/git/openidea_all", branch: null, openedAtMs: 40 },
];
localStorage.setItem(
"openidea.remote.recent",
JSON.stringify([
{
target: { kind: "ssh", config: "devbox" },
path: "/home/coder/git/openidea_all",
name: "openidea_all",
host: "dev@devbox:22",
openedAtMs: 100,
},
{
target: { kind: "ssh", config: "devbox" },
path: "/home/coder/git/gocommon",
name: "gocommon",
host: "dev@devbox:22",
openedAtMs: 50,
},
{
target: { kind: "wsl", distro: "Ubuntu" },
path: "/home/me/git/openidea_all",
name: "openidea_all",
host: "Ubuntu",
openedAtMs: 30,
},
]),
);
await renderWelcome();
const options = () => screen.getAllByRole("option");
expect(options().map((o) => o.textContent)).toEqual([
"SSH·dev@devbox:222",
expect.stringContaining("openidea_all/home/coder/git/openidea_all"),
expect.stringContaining("gocommon/home/coder/git/gocommon"),
"Local2",
expect.stringContaining("gocommon~/git/gocommonmain"),
expect.stringContaining("openidea_all~/git/openidea_all"),
"WSL·Ubuntu1",
expect.stringContaining("openidea_all/home/me/git/openidea_all"),
]);
// Grouped rows omit the redundant per-row RemoteHostPill while keeping the badge corner.
expect(options()[1]!.querySelector("[data-remote-badge]")).not.toBeNull();
expect(options()[1]!.querySelector('[data-remote-kind="ssh"]')).toBeNull();
// Folding SSH · dev@devbox:22 hides its 2 projects and persists across reloads.
fireEvent.click(options()[0]!);
expect(options()).toHaveLength(6);
expect(JSON.parse(localStorage.getItem("openidea.recent.collapsedHosts") ?? "[]")).toEqual(["ssh:dev@devbox:22"]);
// Searching flattens the list and restores per-row remote host pills even for folded hosts.
const search = screen.getByLabelText("Search projects");
fireEvent.change(search, { target: { value: "openidea_all" } });
expect(options()).toHaveLength(3);
expect(options()[0]!.querySelector('[data-remote-kind="ssh"]')?.textContent).toContain("dev@devbox:22");
});
it("excludes only the active remote location in RecentProjectsPopup, not a local folder at the same path", async () => {
const { RecentProjectsPopup, showRecentProjectsPopup, useRecentPopup } = await import("./RecentProjectsPopup");
recent = [{ name: "openidea_all", path: "/Users/me/git/openidea_all", branch: null, openedAtMs: 50 }];
const target: RemoteTarget = { kind: "ssh", config: "mbp" };
localStorage.setItem(
"openidea.remote.recent",
JSON.stringify([
{
target,
path: "/Users/me/git/openidea_all",
name: "openidea_all",
host: "mbp.local",
openedAtMs: 100,
},
{
target,
path: "/Users/me/git/gocommon",
name: "gocommon",
host: "mbp.local",
openedAtMs: 80,
},
]),
);
useProject.setState({
project: { root: "/Users/me/git/openidea_all", name: "openidea_all", trusted: true, isGit: false, settings: {} },
});
useRemote.setState({
session: { target, root: "/Users/me/git/openidea_all", host: "mbp.local", os: "macos", commands: [] },
});
try {
render(<RecentProjectsPopup />);
act(() => showRecentProjectsPopup());
await act(async () => {});
const list = screen.getByRole("listbox", { name: "Recent projects" });
const texts = within(list)
.getAllByRole("option")
.map((o) => o.textContent);
expect(texts).toEqual([
"SSH·mbp.local1",
expect.stringContaining("gocommon/Users/me/git/gocommon"),
"Local1",
expect.stringContaining("openidea_all~/git/openidea_all"),
]);
} finally {
useRecentPopup.setState({ open: false });
useRemote.setState({ session: null });
}
});
});
describe("Welcome › navigation", () => {
+1
Переглянути файл
@@ -302,6 +302,7 @@
"menu.navigate.nextMethod": "Next Method",
"menu.navigate.previousMethod": "Previous Method",
"menu.openRecent": "Open Recent",
"menu.recent.local": "Local",
"menu.recent.none": "No Recent Projects",
"menu.refactor": "Refactor",
"menu.refactor.changeSignature": "Change Signature…",
+1
Переглянути файл
@@ -235,6 +235,7 @@
"menu.navigate.nextMethod": "Siguiente método",
"menu.navigate.previousMethod": "Método anterior",
"menu.openRecent": "Abrir reciente",
"menu.recent.local": "Local",
"menu.recent.none": "No hay proyectos recientes",
"menu.refactor": "Refactorizar",
"menu.refactor.changeSignature": "Cambiar firma…",
+1
Переглянути файл
@@ -234,6 +234,7 @@
"menu.navigate.nextMethod": "Méthode suivante",
"menu.navigate.previousMethod": "Méthode précédente",
"menu.openRecent": "Ouvrir un élément récent",
"menu.recent.local": "Local",
"menu.recent.none": "Aucun projet récent",
"menu.refactor": "Refactoriser",
"menu.refactor.changeSignature": "Modifier la signature…",
+1
Переглянути файл
@@ -241,6 +241,7 @@
"menu.navigate.nextMethod": "다음 메서드",
"menu.navigate.previousMethod": "이전 메서드",
"menu.openRecent": "최근 항목 열기",
"menu.recent.local": "로컬",
"menu.recent.none": "최근 프로젝트 없음",
"menu.refactor": "리팩터링",
"menu.refactor.changeSignature": "시그니처 변경…",
+1
Переглянути файл
@@ -235,6 +235,7 @@
"menu.navigate.nextMethod": "Następna metoda",
"menu.navigate.previousMethod": "Poprzednia metoda",
"menu.openRecent": "Otwórz ostatnie",
"menu.recent.local": "Lokalne",
"menu.recent.none": "Brak ostatnich projektów",
"menu.refactor": "Refaktoryzacja",
"menu.refactor.changeSignature": "Zmień sygnaturę…",
+1
Переглянути файл
@@ -235,6 +235,7 @@
"menu.navigate.nextMethod": "Próximo método",
"menu.navigate.previousMethod": "Método anterior",
"menu.openRecent": "Abrir recente",
"menu.recent.local": "Local",
"menu.recent.none": "Nenhum projeto recente",
"menu.refactor": "Refatorar",
"menu.refactor.changeSignature": "Alterar assinatura…",
+1
Переглянути файл
@@ -300,6 +300,7 @@
"menu.navigate.nextMethod": "Следующий метод",
"menu.navigate.previousMethod": "Предыдущий метод",
"menu.openRecent": "Открыть недавние",
"menu.recent.local": "Локальный",
"menu.recent.none": "Нет недавних проектов",
"menu.refactor": "Рефакторинг",
"menu.refactor.changeSignature": "Изменить сигнатуру…",
+1
Переглянути файл
@@ -297,6 +297,7 @@
"menu.navigate.nextMethod": "Sonraki Metot",
"menu.navigate.previousMethod": "Önceki Metot",
"menu.openRecent": "Son Kullanılanları Aç",
"menu.recent.local": "Yerel",
"menu.recent.none": "Son Kullanılan Proje Yok",
"menu.refactor": "Yeniden Düzenle",
"menu.refactor.changeSignature": "İmzayı Değiştir…",
+1
Переглянути файл
@@ -298,6 +298,7 @@
"menu.navigate.nextMethod": "下一個方法",
"menu.navigate.previousMethod": "上一個方法",
"menu.openRecent": "最近開啟",
"menu.recent.local": "本機",
"menu.recent.none": "沒有最近的專案",
"menu.refactor": "重構",
"menu.refactor.changeSignature": "更改簽名…",
+1
Переглянути файл
@@ -302,6 +302,7 @@
"menu.navigate.nextMethod": "下一个方法",
"menu.navigate.previousMethod": "上一个方法",
"menu.openRecent": "最近打开",
"menu.recent.local": "本地",
"menu.recent.none": "没有最近的项目",
"menu.refactor": "重构",
"menu.refactor.changeSignature": "更改签名…",
+6 -2
Переглянути файл
@@ -25,7 +25,7 @@ import { isSubmenuAim, type MenuPointer } from "./menuAim";
export type MenuItem =
| { kind: "separator" }
| { kind: "header"; label: string; asTitle?: boolean }
| { kind: "header"; label: string; asTitle?: boolean; verbatim?: boolean }
| {
kind: "action";
action: string;
@@ -95,7 +95,11 @@ export function resolveMenuItems(items: MenuItem[]): Resolved[] {
return;
}
if (item.kind === "header") {
out.push({ kind: item.asTitle ? "title" : "header", key: `h${i}`, label: tx(item.label) });
out.push({
kind: item.asTitle ? "title" : "header",
key: `h${i}`,
label: item.verbatim ? item.label : tx(item.label),
});
return;
}
if (item.kind === "action") {
+15
Переглянути файл
@@ -88,6 +88,21 @@ describe("main menu model", () => {
});
expect(sub[1]).toMatchObject({ label: "No Recent Projects", disabled: true });
});
it("renders Open Recent host placeholders as non-selectable headers", () => {
const items = menuItems([
{ kind: "placeholder", id: "recent.local", label: "Local" },
{ kind: "placeholder", id: "recent.section:ssh:dev@box:22", label: "SSH · dev@box:22" },
]);
expect(items).toEqual([
{ kind: "header", label: "Local", verbatim: false },
{ kind: "header", label: "SSH · dev@box:22", verbatim: true },
]);
expect(resolveMenuItems(items).map((r) => [r.kind, r.label])).toEqual([
["header", "Local"],
["header", "SSH · dev@box:22"],
]);
});
});
describe("check marks in the main menu", () => {
+3
Переглянути файл
@@ -27,6 +27,9 @@ export function menuItems(nodes: MenuNode[]): MenuItem[] {
case "separator":
return { kind: "separator" };
case "placeholder":
if (n.id === "recent.local" || n.id.startsWith("recent.section:")) {
return { kind: "header", label: label(n.id, n.label), verbatim: n.id.startsWith("recent.section:") };
}
return { id: n.id, label: label(n.id, n.label), disabled: true };
case "submenu":
return {