Файли
openidea/src/features/welcome/RecentList.tsx
T

498 рядки
17 KiB
TypeScript

import { writeClipboardText } from "@/platform/clipboard";
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";
import { parseRemoteLocation } from "@/platform/remote";
import {
HighlightedText,
Icon,
IconButton,
SearchField,
Spinner,
listNavigate,
showContextMenu,
type MenuItem,
} from "@/ui";
import { promptInput } from "@/workbench/inputDialogs";
import { confirm, showError } from "@/workbench/messages";
import { describeError } from "@/platform/errorLog";
import { projectWindowOverride, type ModifierKeys } from "@/workbench/projectWindow";
import { ProjectAvatar } from "@/workbench/ProjectBadge";
import { hasCustomProjectIcon, setProjectIcon } from "@/workbench/projectIcon";
import { openProjectColorPicker } from "@/workbench/TabColorPicker";
import { open as openDialog } from "@/platform/dialog";
import { subscribeTabColors, tabColorOverride, tabColorVars, tabColorsVersion } from "@/workbench/tabColors";
import {
createGroup,
groupNameError,
groupOf,
moveToGroup,
openRecent,
recentRows,
removeGroup,
removeRecent,
renameGroup,
setGroupExpanded,
useRecent,
type RecentMatch,
} from "./recent";
import styles from "./Welcome.module.css";
import { tx } from "@/platform/i18n";
/**
* IDEA's "Remove Recent Project" confirmation, then removes it from the list.
* `before` runs just before the confirmation opens: hosts above the dialog's
* layer (a popup) pass their closer so the confirmation is not covered (#1883).
*/
export async function askRemoveRecent(project: RecentProject, before?: () => void) {
before?.();
const ok = await confirm({
title: "Remove Recent Project",
message: tx`Remove '${project.name}' from the list of recent projects?`,
ok: "Remove",
});
if (ok) await removeRecent(project.path);
}
/** Rounded-square project avatar; same colour and initials as the title bar's project widget. */
export function ProjectBadge({
name,
path,
className,
missing,
}: {
name: string;
path: string;
className?: string;
missing?: boolean;
}) {
useSyncExternalStore(subscribeTabColors, tabColorsVersion);
const remote = Boolean(parseRemoteLocation(path));
return (
<span
className={clsx(styles.tile, remote && styles.tileRemote, missing && styles.tileMissing, className)}
style={tabColorVars(name, tabColorOverride(path))}
data-remote-badge={remote ? "" : undefined}
aria-hidden
>
<ProjectAvatar name={name} root={path} />
{remote && (
<i className={styles.remoteCorner} aria-hidden="true">
<Icon name="remote" size={8} />
</i>
)}
</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"] }] });
if (typeof file !== "string") return;
await setProjectIcon(root, file).catch((e: unknown) =>
showError(tx("Cannot change the project icon"), describeError(e)),
);
}
async function resetProjectIcon(root: string) {
await setProjectIcon(root, null).catch((e: unknown) =>
showError(tx("Cannot reset the project icon"), describeError(e)),
);
}
/**
* IDEA's project widget and Welcome screen: Change Project Color…, and for a local project
* Change Project Icon… (with Reset Project Icon once it has one). Also an open project's menu.
*/
export function projectAppearanceMenu(project: Pick<RecentProject, "path" | "name">): MenuItem[] {
const items: MenuItem[] = [
{ id: "color", label: "Change Project Color…", run: () => openProjectColorPicker(project.path, project.name) },
];
if (parseRemoteLocation(project.path)) return items;
items.push({ id: "icon", label: "Change Project Icon…", run: () => void chooseProjectIcon(project.path) });
if (hasCustomProjectIcon(project.path))
items.push({ id: "resetIcon", label: "Reset Project Icon", run: () => void resetProjectIcon(project.path) });
return items;
}
/** The tooltip of a recent project whose folder is gone. */
export function unavailableTitle(project: Pick<RecentProject, "path" | "missing">): string | undefined {
return project.missing ? tx`${project.path} (unavailable)` : undefined;
}
/** New Project Group…: asks for a name; with `path`, that project moves into the new group. */
export async function askNewGroup(path?: string) {
const name = await promptInput({
title: "New Project Group",
label: "Group name:",
okLabel: "Create",
validate: (v) => groupNameError(v),
});
if (name !== null) await createGroup(name, path);
}
/** Move to Group: the other groups, a new one, or out of its group. */
function moveToGroupMenu(project: RecentProject): MenuItem {
const groups = useRecent.getState().groups;
const current = groupOf(project.path, groups)?.name ?? null;
const others = groups.filter((g) => g.name !== current);
const submenu: MenuItem[] = [
...others.map((g): MenuItem => ({
label: g.name,
verbatim: true,
run: () => void moveToGroup(project.path, g.name),
})),
...(others.length ? [{ kind: "separator" } as const] : []),
{ label: "New Group…", run: () => void askNewGroup(project.path) },
...(current
? [{ label: tx`Remove from '${current}'`, verbatim: true, run: () => void moveToGroup(project.path, null) }]
: []),
];
return { label: "Move to Group", icon: "folder", submenu };
}
/** A project group's actions. */
export function groupMenu(group: RecentProjectGroup): MenuItem[] {
return [
{
label: "Rename Group…",
icon: "edit",
run: () =>
void promptInput({
title: "Rename Project Group",
label: "Group name:",
initial: group.name,
okLabel: "Rename",
validate: (v) => groupNameError(v, group.name),
}).then((name) => (name === null ? undefined : renameGroup(group.name, name))),
},
{ label: "New Project Group…", icon: "plus", run: () => void askNewGroup() },
{ kind: "separator" },
{
label: "Remove Group",
icon: "close",
danger: true,
run: () => void removeGroup(group.name),
},
];
}
export function recentMenu(project: RecentProject, onOpened?: () => void, onRemove?: () => void): MenuItem[] {
// A remote project has no local folder.
const remote = parseRemoteLocation(project.path);
const items: MenuItem[] = [
{
id: "open",
label: "Open",
icon: "folder-open",
run: () => void openRecent(project).then((ok) => ok && onOpened?.()),
},
remote
? {
id: "openInNewWindow",
label: "Open in New Window",
icon: "folder-open",
run: () =>
void call(commands.windowOpenRemote(remote.target, remote.path, true))
.then(() => onOpened?.())
.catch(() => undefined),
}
: { kind: "action", action: "file.openInNewWindow", arg: project.path, label: "Open in New Window" },
{
id: "reveal",
label: showInFileManagerLabel(),
icon: "external-link",
run: () => void revealInFileManager(project.path, null).catch(() => undefined),
},
{
id: "copy",
label: "Copy Path",
icon: "copy",
run: () => void writeClipboardText(project.path).catch(() => undefined),
},
{ kind: "separator" },
...projectAppearanceMenu(project),
{ kind: "separator" },
// Groups hold local projects (remote ones live in this window's own list).
...(remote ? [] : [moveToGroupMenu(project), { kind: "separator" } as const]),
{
id: "remove",
label: "Remove from Recent Projects…",
icon: "close",
danger: true,
run: () => void askRemoveRecent(project, onRemove),
},
];
return remote ? items.filter((i) => !("id" in i && i.id === "reveal")) : items;
}
function relativeTime(ms: number | null): string | null {
if (!ms) return null;
const diff = Date.now() - ms;
const min = 60_000,
hour = 60 * min,
day = 24 * hour;
if (diff < hour) return "just now";
if (diff < day) return `${Math.round(diff / hour)}h ago`;
if (diff < 30 * day) return `${Math.round(diff / day)}d ago`;
return new Date(ms).toLocaleDateString();
}
function RecentRow({
m,
active,
compact,
onOpened,
}: {
m: RecentMatch;
active: boolean;
compact?: boolean;
onOpened?: () => void;
}) {
const opening = useRecent((s) => s.opening === m.project.path);
const when = relativeTime(m.project.openedAtMs);
return (
<div className={styles.recent} title={unavailableTitle(m.project)}>
<ProjectBadge name={m.project.name} path={m.project.path} missing={!!m.project.missing} />
<span className={styles.recentText}>
<span className={styles.recentTop}>
<HighlightedText
className={clsx(styles.recentName, m.project.missing && styles.unavailable)}
text={m.project.name}
indices={m.nameMatch}
tone={active ? "accent" : "strong"}
/>
{m.project.branch && (
<span className={styles.branch}>
<Icon name="branch" size={11} />
{m.project.branch}
</span>
)}
</span>
<HighlightedText className={styles.recentPath} text={m.displayPath} indices={m.pathMatch} />
</span>
{opening ? (
<Spinner size={14} />
) : (
<>
{!compact && when && <span className={styles.when}>{when}</span>}
<IconButton
icon="more"
title="Project actions"
size="small"
iconSize={14}
className={styles.rowMore}
tabIndex={-1}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => {
e.stopPropagation();
const r = e.currentTarget.getBoundingClientRect();
showContextMenu({ x: r.left, y: r.bottom + 2 }, recentMenu(m.project, onOpened, onOpened));
}}
/>
</>
)}
</div>
);
}
export interface RecentListProps {
/** Hide the current project (the popup while a project is open). */
exclude?: string | null;
compact?: boolean;
autoFocus?: boolean;
onOpened?: () => void;
className?: string;
/** Extra controls right of the search field. */
toolbar?: ReactNode;
}
/** 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 home = useRecent((s) => s.home);
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const listRef = useRef<HTMLDivElement>(null);
const baseId = useId();
const visibleProjects = useMemo(
() => (exclude ? projects.filter((p) => p.path !== exclude) : projects),
[projects, exclude],
);
const items = useMemo(() => recentRows(visibleProjects, groups, query, home), [visibleProjects, groups, query, home]);
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) => {
if (m) void openRecent(m.project, projectWindowOverride(e)).then((ok) => ok && onOpened?.());
};
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 (e.key === "Enter") {
e.preventDefault();
if (row?.kind === "group") void setGroupExpanded(row.group.name, !row.group.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 atEnd = field.selectionStart === field.value.length && field.selectionEnd === field.value.length;
if (
((e.key === "Delete" && atEnd) || (e.key === "Backspace" && e.metaKey && !field.value)) &&
row?.kind === "project"
) {
e.preventDefault();
void askRemoveRecent(row.m.project, onOpened);
return;
}
if (e.key === "ContextMenu" || (e.key === "F10" && e.shiftKey)) {
const el = e.currentTarget.getBoundingClientRect();
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;
}
const next = listNavigate(e.key, { items, active: current, pageSize: compact ? 8 : 6 });
if (next === null) return;
e.preventDefault();
setActive(next);
};
const optionId = (i: number) => `${baseId}-r${i}`;
return (
<div className={clsx(styles.recentList, className)}>
<div className={styles.searchRow}>
<SearchField
value={query}
onChange={(q) => {
setQuery(q);
setActive(0);
}}
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}
className={styles.search}
/>
{toolbar}
</div>
<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>
);
}
const nested = row.group !== 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} onOpened={onOpened} />
</div>
);
})
)}
</div>
</div>
);
}