diff --git a/e2e/githubIssuesLayout.spec.ts b/e2e/githubIssuesLayout.spec.ts
new file mode 100644
index 0000000000..257e78f271
--- /dev/null
+++ b/e2e/githubIssuesLayout.spec.ts
@@ -0,0 +1,194 @@
+import type { GhProjectAccountStatus } from "../src/bindings";
+import { expect, stubDesktop, test } from "./fixtures";
+
+test("GitHub Issues matches Pull Requests header, search chips, rows, and context menu", async ({
+ workbench: page,
+}) => {
+ await page.setViewportSize({ width: 1280, height: 840 });
+ await stubDesktop(page);
+ await page.evaluate(() => {
+ const now = new Date().toISOString();
+ const yesterday = new Date(Date.now() - 86_400_000).toISOString();
+ const status: GhProjectAccountStatus = {
+ ghInstalled: true,
+ accounts: [
+ { login: "l0ng-ai", active: true },
+ { login: "l0ng-work", active: false },
+ ],
+ configuredAccount: "",
+ effectiveAccount: "l0ng-ai",
+ suggestedAccount: null,
+ };
+ const issues = [
+ {
+ id: "I8139",
+ url: "https://github.com/l0ng-ai/openidea/issues/8139",
+ number: 8139,
+ title: "编辑器:跳到下一个匹配项后,Ctrl+V 无法覆盖当前匹配项",
+ state: "OPEN",
+ createdAt: yesterday,
+ updatedAt: now,
+ author: { __typename: "User", id: "U2", login: "alextrevisan", url: "", avatarUrl: "", name: null },
+ labels: { nodes: [{ id: "L1", url: "", name: "bug", color: "d73a4a" }] },
+ assignees: { nodes: [] },
+ comments: { totalCount: 2 },
+ },
+ {
+ id: "I8133",
+ url: "https://github.com/l0ng-ai/openidea/issues/8133",
+ number: 8133,
+ title: "Flatpak support",
+ state: "OPEN",
+ createdAt: yesterday,
+ updatedAt: yesterday,
+ author: { __typename: "User", id: "U3", login: "charli117", url: "", avatarUrl: "", name: null },
+ labels: { nodes: [{ id: "L2", url: "", name: "enhancement", color: "a2eeef" }] },
+ assignees: { nodes: [] },
+ comments: { totalCount: 0 },
+ },
+ {
+ id: "I8050",
+ url: "https://github.com/l0ng-ai/openidea/issues/8050",
+ number: 8050,
+ title: "Select Opened File in External Libraries",
+ state: "CLOSED",
+ createdAt: yesterday,
+ updatedAt: yesterday,
+ author: { __typename: "User", id: "U4", login: "wildcatDownstairs", url: "", avatarUrl: "", name: null },
+ labels: { nodes: [] },
+ assignees: { nodes: [] },
+ comments: { totalCount: 5 },
+ },
+ ];
+ const prs = [
+ {
+ id: "PR7822",
+ url: "https://github.com/l0ng-ai/openidea/pull/7822",
+ number: 7822,
+ title: "feat(run): choose the run device from plugin device providers",
+ state: "OPEN",
+ isDraft: true,
+ createdAt: yesterday,
+ updatedAt: yesterday,
+ isReadByViewer: true,
+ author: { __typename: "User", id: "U2", login: "alextrevisan", url: "", avatarUrl: "", name: null },
+ assignees: { nodes: [] },
+ labels: { nodes: [{ id: "L2", url: "", name: "enhancement", color: "a2eeef" }] },
+ reviewRequests: { nodes: [] },
+ reviewThreads: { nodes: [] },
+ reviews: { nodes: [] },
+ reactions: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } },
+ mergeable: "MERGEABLE",
+ viewerCanUpdate: false,
+ viewerCanReact: false,
+ viewerDidAuthor: false,
+ },
+ ];
+ Object.assign(window.__ipc.handlers, {
+ settings_get_global: () => ({}),
+ vcs_roots: () => [{ root: "/dev/openidea", name: "openidea", branch: "main" }],
+ vcs_remotes: () => [{ name: "origin", url: "https://github.com/l0ng-ai/openidea.git", resolvedUrl: null }],
+ gh_project_account_status: () => status,
+ gh_availability: () => ({
+ kind: "ready",
+ login: "l0ng-ai",
+ repo: { nameWithOwner: "l0ng-ai/openidea", url: "https://github.com/l0ng-ai/openidea" },
+ }),
+ gh_api: ({ request }: { request: { endpoint: string; body?: string | null } }) => {
+ if (request.endpoint === "user") return JSON.stringify({ login: "l0ng-ai", id: 1 });
+ const parsed = request.body
+ ? (JSON.parse(request.body) as { query?: string; variables?: { query?: string } })
+ : {};
+ const q = parsed.variables?.query ?? "";
+ if (q.startsWith("type:issue")) {
+ const filtered = q.includes("is:closed")
+ ? issues.filter((i) => i.state === "CLOSED")
+ : q.includes("is:open")
+ ? issues.filter((i) => i.state === "OPEN")
+ : issues;
+ return JSON.stringify({
+ data: {
+ search: {
+ pageInfo: { startCursor: null, endCursor: null, hasNextPage: false, hasPreviousPage: false },
+ nodes: filtered,
+ },
+ },
+ });
+ }
+ if (q.startsWith("type:pr")) {
+ return JSON.stringify({
+ data: {
+ search: {
+ pageInfo: { startCursor: null, endCursor: null, hasNextPage: false, hasPreviousPage: false },
+ nodes: prs,
+ },
+ },
+ });
+ }
+ return JSON.stringify({
+ data: {
+ repository: {
+ id: "R1",
+ owner: { __typename: "User", id: "O1", login: "l0ng-ai" },
+ nameWithOwner: "l0ng-ai/openidea",
+ viewerPermission: "WRITE",
+ mergeCommitAllowed: true,
+ squashMergeAllowed: true,
+ rebaseMergeAllowed: true,
+ defaultBranchRef: { name: "main" },
+ isFork: false,
+ url: "https://github.com/l0ng-ai/openidea",
+ sshUrl: "git@github.com:l0ng-ai/openidea.git",
+ },
+ viewer: {
+ __typename: "User",
+ id: "U1",
+ login: "l0ng-ai",
+ url: "https://github.com/l0ng-ai",
+ avatarUrl: "",
+ name: null,
+ },
+ },
+ });
+ },
+ });
+ });
+
+ // Open Pull Requests first (baseline comparison)
+ await page.evaluate(async () => {
+ const contributions = "/src/workbench/contributions.ts";
+ const { toolWindowService } = await import(/* @vite-ignore */ contributions);
+ toolWindowService().show("pullRequests", true);
+ });
+ await expect(page.getByRole("textbox", { name: "Search pull requests" })).toBeVisible();
+ await expect(page.getByText("feat(run): choose the run device from plugin device providers")).toBeVisible();
+
+ // Switch to GitHub Issues
+ await page.evaluate(async () => {
+ const contributions = "/src/workbench/contributions.ts";
+ const { toolWindowService } = await import(/* @vite-ignore */ contributions);
+ toolWindowService().show("githubIssues", true);
+ });
+ await expect(page.getByRole("textbox", { name: "Search issues" })).toBeVisible();
+ await expect(page.getByRole("tab", { name: "openidea" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "@l0ng-ai" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Author" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Label" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Assignee" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Sort" })).toBeVisible();
+ await expect(page.getByText("Flatpak support")).toBeVisible();
+ await expect(page.getByText(/^#8133 · created .+, by charli117$/)).toBeVisible();
+
+ // Clear State chip → closed issue appears with CLOSED pill
+ await page.getByRole("button", { name: "Reset State" }).click();
+ await expect(page.getByText("Select Opened File in External Libraries")).toBeVisible();
+ await expect(page.getByText("CLOSED", { exact: true })).toBeVisible();
+
+ // Right-click menu
+ await page.getByRole("option", { name: /Flatpak support/ }).click({ button: "right" });
+ await expect(page.getByRole("menuitem", { name: "View Issue", exact: true })).toBeVisible();
+ await expect(page.getByRole("menuitem", { name: "Create Branch from Issue…", exact: true })).toBeVisible();
+ await expect(page.getByRole("menuitem", { name: "View Issue in Browser", exact: true })).toBeVisible();
+ await expect(page.getByRole("menuitem", { name: "Copy Issue URL", exact: true })).toBeVisible();
+ await expect(page.getByRole("menuitem", { name: "Refresh List", exact: true })).toBeVisible();
+});
diff --git a/src/features/github/index.ts b/src/features/github/index.ts
index c282ca48c6..4f428206fa 100644
--- a/src/features/github/index.ts
+++ b/src/features/github/index.ts
@@ -29,11 +29,13 @@ import { GithubDialogHost } from "./ui/dialogs";
import { activateSettingsPages } from "./settingsPages";
const WINDOW = "pullRequests";
+const ISSUES_WINDOW = "githubIssues";
const ACTIONS_WINDOW = "githubActions";
const TIMELINE_KIND = "github.timeline";
const WHEN = "projectOpen";
const CONNECTED = "projectOpen && githubConnected";
const IN_WINDOW = `activeToolWindow == '${WINDOW}'`;
+const IN_ISSUES_WINDOW = `activeToolWindow == '${ISSUES_WINDOW}'`;
/** The pull requests UI and data load after start-up (or on first use); registrations stay here. */
type Runtime = typeof import("./runtime");
@@ -68,6 +70,14 @@ function actions(): ActionSpec[] {
when: CONNECTED,
run: async () => (await import("./issues/actions")).newIssue(),
},
+ {
+ id: "github.issue.show",
+ title: "View Issue",
+ description: "View issue description and comments",
+ category: "GitHub",
+ when: CONNECTED,
+ run: async ({ arg }) => (await import("./issues/actions")).openIssue(arg),
+ },
{
id: "github.issue.createBranch",
title: "Create Branch from Issue…",
@@ -77,6 +87,32 @@ function actions(): ActionSpec[] {
enabled: ({ arg }) => Boolean(arg) || maybeEditorService()?.activeInput?.()?.kind === ISSUE_KIND,
run: async ({ arg }) => (await import("./issues/actions")).createIssueBranch(arg),
},
+ {
+ id: "github.issue.openInBrowser",
+ title: "View Issue in Browser",
+ category: "GitHub",
+ icon: "external-link",
+ when: CONNECTED,
+ run: async ({ arg }) => (await import("./issues/actions")).openIssueInBrowser(arg),
+ },
+ {
+ id: "github.issue.copyUrl",
+ title: "Copy Issue URL",
+ category: "GitHub",
+ icon: "copy",
+ when: CONNECTED,
+ run: async ({ arg }) => (await import("./issues/actions")).copyIssueUrl(arg),
+ },
+ {
+ id: "github.issue.refresh",
+ title: "Refresh Issues List",
+ category: "GitHub",
+ icon: "refresh",
+ keywords: ["refresh list", "reload"],
+ when: WHEN,
+ keyWhen: IN_ISSUES_WINDOW,
+ run: async () => (await import("./issues/actions")).refreshIssues(),
+ },
// Git › GitHub
{
// Github.View.Pull.Request
@@ -338,6 +374,9 @@ function actions(): ActionSpec[] {
const lazyView = (name: "PullRequestsToolWindow" | "PullRequestsTabs" | "PullRequestsHeaderActions") =>
lazyComponent<{ id: string }>(() => import("./toolwindow/PullRequestsToolWindow").then((m) => m[name]));
+const lazyIssueView = (name: "IssuesToolWindow" | "IssuesHeaderTabs" | "IssuesHeaderActions") =>
+ lazyComponent<{ id: string }>(() => import("./issues/IssuesToolWindow").then((m) => m[name]));
+
const useHeaderMenu = () => useGithubShell((s) => s.headerMenu);
export function activate(): () => void {
@@ -380,13 +419,15 @@ export function activate(): () => void {
icon: (input) => (issueData(input)?.state === "CLOSED" ? "issue-closed" : "issue-open"),
}),
registerToolWindow({
- id: "githubIssues",
+ id: ISSUES_WINDOW,
title: "GitHub Issues",
icon: "toolwindow-github-issues",
anchor: "left",
order: 3,
stripe: "onUse",
- component: lazyComponent(() => import("./issues/IssuesToolWindow").then((m) => m.IssuesToolWindow)),
+ component: lazyIssueView("IssuesToolWindow"),
+ headerContent: lazyIssueView("IssuesHeaderTabs"),
+ headerActions: lazyIssueView("IssuesHeaderActions"),
headerMenu: useHeaderMenu,
}),
registerToolWindow({
diff --git a/src/features/github/issues/IssueRow.tsx b/src/features/github/issues/IssueRow.tsx
new file mode 100644
index 0000000000..350f58cbd7
--- /dev/null
+++ b/src/features/github/issues/IssueRow.tsx
@@ -0,0 +1,80 @@
+/**
+ * An issue list row, matching `PullRequestRow`:
+ * First line: title (with truncation tooltip) + labels icon on the left; CLOSED pill,
+ * up to 2 assignee avatars and comment counter on the right. Second line:
+ * `#N · created {date}, by {login}`.
+ */
+import { memo } from "react";
+import { Icon } from "@/ui";
+import { Avatar, AvatarStack, AVATAR_SIZE } from "../ui/Avatar";
+import { labelColor, StateTag } from "../ui/chips";
+import { prettyDate } from "../ui/prettyDate";
+import { HoverBalloon, type BalloonItem } from "../list/HoverBalloon";
+import { assigneesTitle, infoLine, labelsTitle } from "../list/model";
+import { titleTooltip } from "../list/PullRequestRow";
+import styles from "../list/List.module.css";
+import type { IssueRow } from "./api";
+import { issueCommentsTooltip } from "./model";
+
+const MAX_AVATARS = 2;
+
+export const IssueRowView = memo(function IssueRowView({ issue }: { issue: IssueRow }) {
+ const labels = issue.labels?.nodes ?? [];
+ const assignees = issue.assignees?.nodes ?? [];
+ const comments = issue.comments?.totalCount ?? 0;
+
+ const labelItems: BalloonItem[] = labels.map((l) => ({
+ key: l.id || l.name,
+ icon: (
+
+
+
+ ),
+ text: l.name,
+ }));
+
+ const assigneeItems: BalloonItem[] = assignees.map((u) => ({
+ key: u.id || u.login,
+ icon: ,
+ text: u.login,
+ }));
+
+ return (
+
+
+
+
+ {issue.title}
+
+ {labels.length > 0 && (
+
+
+
+ )}
+
+
+
+ {assignees.length > 0 && (
+
+ ({ key: u.id || u.login, url: u.avatarUrl, name: u.login }))}
+ title={null}
+ />
+
+ )}
+
+
+ {comments}
+
+
+
+
+ {issue.createdAt
+ ? infoLine(issue.number, prettyDate(issue.createdAt), issue.author?.login)
+ : `#${issue.number}`}
+
+
+ );
+});
diff --git a/src/features/github/issues/Issues.module.css b/src/features/github/issues/Issues.module.css
index fa5e0e868f..b5e660714b 100644
--- a/src/features/github/issues/Issues.module.css
+++ b/src/features/github/issues/Issues.module.css
@@ -1,63 +1,10 @@
-.panel {
- display: flex;
- flex-direction: column;
- height: 100%;
- min-height: 0;
- gap: var(--space-1);
- padding: var(--space-1) var(--space-2);
-}
-.toolbar,
-.filters,
-.row,
.metadata {
display: flex;
- align-items: center;
- gap: var(--space-1);
- min-width: 0;
-}
-.repo {
- flex: 1;
- min-width: 0;
- overflow: hidden;
- color: var(--fg-secondary);
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.filters,
-.metadata {
flex-wrap: wrap;
-}
-.list {
- flex: 1;
- min-height: 0;
-}
-.row {
- width: 100%;
- gap: var(--space-1-5);
-}
-.subject {
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
- overflow: hidden;
- white-space: normal;
- overflow-wrap: anywhere;
-}
-.row > svg {
- flex: none;
-}
-.number {
- color: var(--fg-secondary);
- font-size: var(--fs-small);
-}
-.metadata {
+ align-items: center;
+ min-width: 0;
margin: 0 var(--space-4) var(--space-2);
gap: var(--space-2);
color: var(--fg-secondary);
overflow-wrap: anywhere;
}
-.error {
- color: var(--danger);
- font-size: var(--fs-small);
- overflow-wrap: anywhere;
-}
diff --git a/src/features/github/issues/IssuesToolWindow.tsx b/src/features/github/issues/IssuesToolWindow.tsx
index 8d7f8fb8f7..8bbfc4af71 100644
--- a/src/features/github/issues/IssuesToolWindow.tsx
+++ b/src/features/github/issues/IssuesToolWindow.tsx
@@ -1,123 +1,335 @@
-import { useCallback, useState, type MouseEvent } from "react";
-import { useRowHeight } from "@/ui/density";
-import { editorService } from "@/workbench/contributions";
-import { tx } from "@/platform/i18n";
-import { isImeKey } from "@/platform/ime";
-import { Button, EmptyState, Icon, IconButton, List, SearchField, Select, T } from "@/ui";
-import { nameWithOwner, repositoryKey, useGhRepository, type GHConnection } from "../data/repository";
+/**
+ * The GitHub Issues tool window, matching `PullRequestsToolWindow` and `ListPanel`:
+ * repository tab and account/create/refresh actions in the tool window header, shared
+ * search field with history, Quick Filters + horizontally scrolling FilterChips,
+ * 2-line issue rows, 70% scroll paging, top progress stripe, and right-click menu.
+ */
+import { useCallback, useEffect, useRef, type MouseEvent } from "react";
+import { useTx } from "@/platform/i18n";
+import { EmptyState, IconButton, List, ProgressBar, T, Tabs, showContextMenu, type MenuItem } from "@/ui";
+import { repositoryDisplayName } from "../data/model";
+import { nameWithOwner, repositoryKey, useGhRepository } from "../data/repository";
+import {
+ createSearchHistoryRecorder,
+ pastThreshold,
+ SORT_OPTIONS,
+ sortText,
+ type SearchHistoryRecorder,
+} from "../list/model";
+import {
+ AssigneeChooser,
+ AuthorChooser,
+ ChipsRow,
+ FilterChip,
+ LabelChooser,
+ OptionChip,
+ QuickFilterButton,
+ SearchTextField,
+} from "../list/SearchPanel";
+import listStyles from "../list/List.module.css";
import { GithubConnectionGate } from "../toolwindow/GithubConnectionGate";
-import { issueList, type IssueRow, type IssueStateFilter } from "./api";
-import { issueInput } from "./input";
-import { usePages } from "./usePages";
-import styles from "./Issues.module.css";
+import { GithubAccountBadge, useOnShown } from "../toolwindow/PullRequestsToolWindow";
+import toolWindowStyles from "../toolwindow/ToolWindow.module.css";
+import { openIssue } from "./actions";
+import type { IssueRow } from "./api";
+import { IssueRowView } from "./IssueRow";
+import { loadMoreIssues, reloadIssues, setIssueSearch, setSelectedIssue, useGhIssueList } from "./list";
+import {
+ defaultIssueFilter,
+ ISSUE_STATE_OPTIONS,
+ isExactIssueNumberQuery,
+ isIssueQuickFilterSelected,
+ issueFilterCount,
+ issueQuickFilters,
+ issueSearchHistoryText,
+ issueStateText,
+ sameIssueSearch,
+ withIssueQuery,
+ type IssueSearchValue,
+} from "./model";
+import { initialIssueSearch, loadIssueSearchHistory, rememberIssueSearch, saveLastIssueSearch } from "./searchHistory";
-const issueKey = (item: IssueRow) => item.number;
+/** Row height: 4px + the 24px first line + the 16px info line + 5px (same as `PullRequestRow`). */
+const ROW_HEIGHT = 49;
+
+function contextMenu(issue: IssueRow, repoKey: string): MenuItem[] {
+ return [
+ { kind: "action", action: "github.issue.show", arg: issue },
+ {
+ kind: "action",
+ action: "github.issue.createBranch",
+ arg: { repository: repoKey, number: issue.number, title: issue.title, state: issue.state },
+ },
+ { kind: "action", action: "github.issue.openInBrowser", arg: issue },
+ { kind: "action", action: "github.issue.copyUrl", arg: issue },
+ { kind: "separator" },
+ { kind: "action", action: "github.issue.refresh", label: "Refresh List" },
+ ];
+}
+
+function useApplyIssueSearch(repoKey: string | undefined, login: string | undefined): (v: IssueSearchValue) => void {
+ const recorder = useRef | null>(null);
+ useEffect(() => {
+ if (!repoKey || !login) return;
+ const defaultSearch = defaultIssueFilter();
+ const r = createSearchHistoryRecorder({
+ defaultSearch,
+ saveLast: (v) => saveLastIssueSearch(v),
+ remember: (v) => rememberIssueSearch(v, undefined, defaultSearch),
+ countFilters: issueFilterCount,
+ isSame: sameIssueSearch,
+ });
+ recorder.current = r;
+ const initial = initialIssueSearch();
+ r.onChange(initial);
+ void setIssueSearch(initial);
+ return () => {
+ r.dispose();
+ if (recorder.current === r) recorder.current = null;
+ };
+ }, [repoKey, login]);
+ return useCallback((v: IssueSearchValue) => {
+ recorder.current?.onChange(v);
+ void setIssueSearch(v);
+ }, []);
+}
+
+function IssueSearchPanel({
+ search,
+ apply,
+ login,
+}: {
+ search: IssueSearchValue;
+ apply: (v: IssueSearchValue) => void;
+ login: string;
+}) {
+ const exactNumber = isExactIssueNumberQuery(search.searchQuery);
+ const disabledTooltip = "Filters are ignored for #number lookup";
+ const patch = (p: Partial) => {
+ const next: IssueSearchValue = { ...search, ...p };
+ for (const k of Object.keys(p) as (keyof IssueSearchValue)[]) if (next[k] === undefined) delete next[k];
+ apply(next);
+ };
+ return (
+
+
apply(withIssueQuery(search, text))}
+ loadHistory={loadIssueSearchHistory}
+ formatHistory={issueSearchHistoryText}
+ onSelectHistory={apply}
+ ariaLabel="Search issues"
+ placeholder="Title or #number"
+ />
+
+
({
+ id: q.id,
+ title: q.title,
+ selected: isIssueQuickFilterSelected(search, q),
+ run: () => apply(q.filter),
+ }))}
+ count={issueFilterCount(search)}
+ onClear={() => apply({})}
+ />
+
+ patch({ state })}
+ disabled={exactNumber}
+ disabledTooltip={disabledTooltip}
+ />
+ patch({ author })}
+ popup={(anchor, done) => }
+ disabled={exactNumber}
+ disabledTooltip={disabledTooltip}
+ />
+ patch({ label })}
+ popup={(anchor, done) => }
+ disabled={exactNumber}
+ disabledTooltip={disabledTooltip}
+ />
+ patch({ assignee })}
+ popup={(anchor, done) => }
+ disabled={exactNumber}
+ disabledTooltip={disabledTooltip}
+ />
+ patch({ sort })}
+ disabled={exactNumber}
+ disabledTooltip={disabledTooltip}
+ />
+
+
+
+ );
+}
+
+function ErrorState({ error }: { error: string }) {
+ return (
+
+
void reloadIssues()}>
+ Retry
+
+ }
+ >
+ {error}
+
+
+ );
+}
+
+function IssuesListPanel() {
+ const t = useTx();
+ const connection = useGhRepository((s) => s.connection);
+ const login = connection?.currentUser.login;
+ const repoKey = connection ? repositoryKey(connection.coordinates) : undefined;
+ const { search, items, loading, error, loaded, hasMore, selectedNumber } = useGhIssueList();
+ const apply = useApplyIssueSearch(repoKey, login);
+ const body = useRef(null);
+
+ const checkScroll = useCallback(() => {
+ const list = body.current?.querySelector("[role=listbox]");
+ if (!list || list.offsetParent === null) return;
+ if (pastThreshold(list.scrollTop, list.clientHeight, list.scrollHeight)) void loadMoreIssues();
+ }, []);
+
+ useEffect(() => {
+ if (loaded && !loading && hasMore && !error) {
+ const id = requestAnimationFrame(checkScroll);
+ return () => cancelAnimationFrame(id);
+ }
+ }, [items.length, loaded, loading, hasMore, error, checkScroll]);
+
+ if (!connection || !login || !repoKey) return null;
+ const activeIndex = items.length
+ ? Math.max(
+ 0,
+ items.findIndex((i) => i.number === selectedNumber),
+ )
+ : -1;
+
+ const onContextMenu = (issue: IssueRow, _i: number, e: MouseEvent) => {
+ e.preventDefault();
+ setSelectedIssue(issue.number);
+ showContextMenu(e, contextMenu(issue, repoKey));
+ };
+
+ const empty = loading ? (
+
+ ) : issueFilterCount(search) === 0 ? (
+
+ ) : (
+ apply({})}>
+ Clear filters
+
+ }
+ />
+ );
+
+ return (
+
+
+
+ {loading &&
}
+ {error ? (
+
+ ) : (
+
+ items={items}
+ getKey={(i) => String(i.number)}
+ rowHeight={ROW_HEIGHT}
+ activeIndex={activeIndex}
+ onActiveChange={(i) => setSelectedIssue(items[i]?.number ?? null)}
+ onActivate={(row, _i, e) => {
+ if (e.type === "click" && (e as MouseEvent).detail !== 2) return;
+ void openIssue(row);
+ }}
+ onContextMenu={onContextMenu}
+ aria-label="GitHub Issues"
+ className={listStyles.list}
+ empty={empty}
+ renderItem={(issue) => }
+ />
+ )}
+
+
+ );
+}
+
+function Connected() {
+ const listRef = useRef(null);
+ useOnShown(listRef, () => {
+ if (useGhIssueList.getState().loaded) void reloadIssues();
+ });
+ return (
+
+ );
+}
export function IssuesToolWindow() {
- const connection = useGhRepository((s) => s.connection);
return (
- {connection && (
-
- )}
+
);
}
-function IssuesList({ connection }: { connection: GHConnection }) {
- const [text, setText] = useState("");
- const [term, setTerm] = useState("");
- const [state, setState] = useState("OPEN");
- const [mine, setMine] = useState(false);
- const [selectedNumber, setSelectedNumber] = useState(null);
- const fetchPage = useCallback(
- (cursor: string | null) =>
- issueList(connection.coordinates, term, state, mine ? connection.currentUser.login : null, cursor),
- [connection, term, state, mine],
- );
- const page = usePages(fetchPage, issueKey);
- const rowHeight = useRowHeight(44);
- const exact = /^#\d+$/.test(term);
- const activeIndex = page.items.length
- ? Math.max(
- 0,
- page.items.findIndex((i) => i.number === selectedNumber),
- )
- : -1;
+/** Header content: the repository tab, matching `PullRequestsTabs`. */
+export function IssuesHeaderTabs() {
+ const connection = useGhRepository((s) => s.connection);
+ const remotes = useGhRepository((s) => s.remotes);
+ if (!connection) return null;
+ const repo = repositoryDisplayName(remotes, connection.coordinates);
return (
-
-
-
- {nameWithOwner(connection.coordinates)}
-
-
- void page.refresh()} />
-
-
{
- setText(v);
- if (!v.trim()) setTerm("");
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter" && !isImeKey(e.nativeEvent)) setTerm(text.trim());
- }}
- />
-
-
- String(i.number)}
- activeIndex={activeIndex}
- onActiveChange={(i) => setSelectedNumber(page.items[i]?.number ?? null)}
- className={styles.list}
- aria-label="GitHub Issues"
- onActivate={(row, _i, event) => {
- if (event.type === "click" && (event as MouseEvent).detail !== 2) return;
- void editorService().openInput(issueInput(repositoryKey(connection.coordinates), row), { focus: true });
- }}
- renderItem={(row) => (
-
-
-
- #{row.number} {row.title}
-
-
- )}
- empty={page.error ? null : }
- />
- {page.error && (
-
- {page.error}
-
- )}
- {(page.next || page.error) && (
-
- )}
-
+ {}}
+ items={[
+ { id: "list", label: repo, verbatim: true, tooltip: nameWithOwner(connection.coordinates), closable: false },
+ ]}
+ />
+ );
+}
+
+/** Header actions: account switcher (when multi-account), New Issue (+) and Refresh List. */
+export function IssuesHeaderActions() {
+ const connection = useGhRepository((s) => s.connection);
+ if (!connection) return null;
+ return (
+ <>
+
+
+
+ >
);
}
diff --git a/src/features/github/issues/actions.ts b/src/features/github/issues/actions.ts
index dbc54cc399..f487af86d4 100644
--- a/src/features/github/issues/actions.ts
+++ b/src/features/github/issues/actions.ts
@@ -1,10 +1,12 @@
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
-import { maybeEditorService } from "@/workbench/contributions";
+import { editorService, maybeEditorService } from "@/workbench/contributions";
import { pickItems } from "@/workbench/inputDialogs";
-import { useGhRepository, repositoryKey } from "../data/repository";
-import { openInBrowser } from "../data/local";
-import { issueBranchName, issueData, rememberIssueBranch, type IssueInput } from "./input";
+import { refreshConnection, repositoryKey, useGhRepository } from "../data/repository";
+import { copyUrl, openInBrowser } from "../data/local";
+import type { IssueRow } from "./api";
+import { issueBranchName, issueData, issueInput, rememberIssueBranch, type IssueInput } from "./input";
+import { reloadIssues, useGhIssueList } from "./list";
export function newIssue() {
const connection = useGhRepository.getState().connection;
@@ -19,11 +21,67 @@ function asIssueInput(arg: unknown): IssueInput | null {
: null;
}
+function resolveIssueRow(arg?: unknown): IssueRow | null {
+ if (typeof arg === "number") {
+ return useGhIssueList.getState().items.find((i) => i.number === arg) ?? null;
+ }
+ if (arg && typeof arg === "object") {
+ const d = arg as Partial;
+ if (typeof d.number === "number" && typeof d.title === "string" && (d.state === "OPEN" || d.state === "CLOSED"))
+ return d as IssueRow;
+ }
+ const s = useGhIssueList.getState();
+ if (s.selectedNumber !== null) {
+ return s.items.find((i) => i.number === s.selectedNumber) ?? null;
+ }
+ const active = maybeEditorService()?.activeInput?.();
+ const data = active ? issueData(active) : null;
+ return data ? { number: data.number, title: data.title, state: data.state } : null;
+}
+
+function resolveIssueUrl(arg?: unknown): string | null {
+ const connection = useGhRepository.getState().connection;
+ if (!connection) return null;
+ const row = resolveIssueRow(arg);
+ if (row) return row.url ?? `${connection.repository.url}/issues/${row.number}`;
+ if (typeof arg === "number") return `${connection.repository.url}/issues/${arg}`;
+ return null;
+}
+
+export async function openIssue(arg?: unknown) {
+ const connection = useGhRepository.getState().connection;
+ const row = resolveIssueRow(arg);
+ if (!connection || !row) return;
+ await editorService().openInput(issueInput(repositoryKey(connection.coordinates), row), { focus: true });
+}
+
+export async function openIssueInBrowser(arg?: unknown) {
+ const url = resolveIssueUrl(arg);
+ if (url) await openInBrowser(url);
+}
+
+export async function copyIssueUrl(arg?: unknown) {
+ const url = resolveIssueUrl(arg);
+ if (url) await copyUrl(url);
+}
+
+export async function refreshIssues() {
+ if (!useGhRepository.getState().connection) await refreshConnection();
+ if (useGhRepository.getState().connection) await reloadIssues();
+}
+
export async function createIssueBranch(arg?: unknown) {
const input = maybeEditorService()?.activeInput?.();
- const issue = asIssueInput(arg) ?? (input && issueData(input));
const connection = useGhRepository.getState().connection;
- if (!connection || !issue || repositoryKey(connection.coordinates) !== issue.repository) return;
+ if (!connection) return;
+ const repoKey = repositoryKey(connection.coordinates);
+ const direct = asIssueInput(arg);
+ const row = !direct && arg !== undefined ? resolveIssueRow(arg) : null;
+ const issue =
+ direct ??
+ (row ? { repository: repoKey, number: row.number, title: row.title, state: row.state } : null) ??
+ (input && issueData(input));
+ if (!issue || repoKey !== issue.repository) return;
const branches = await call(commands.vcsBranches(connection.root));
if (connection !== useGhRepository.getState().connection) return;
const choices = branches
diff --git a/src/features/github/issues/api.ts b/src/features/github/issues/api.ts
index 6e40b86f4b..1645d0d30a 100644
--- a/src/features/github/issues/api.ts
+++ b/src/features/github/issues/api.ts
@@ -1,11 +1,19 @@
import { graphql, repoVariables } from "../api/client";
-import type { GHActor, GHConnection, GHRepositoryCoordinates } from "../api/types";
-import { nameWithOwner } from "../data/repository";
+import type { GHActor, GHConnection, GHLabel, GHRepositoryCoordinates, GHUser } from "../api/types";
+import { isExactIssueNumberQuery, issueSearchQuery, type IssueSearchValue } from "./model";
export interface IssueRow {
+ id?: string;
+ url?: string;
number: number;
title: string;
state: "OPEN" | "CLOSED";
+ createdAt?: string;
+ updatedAt?: string;
+ author?: GHActor | null;
+ labels?: { nodes: GHLabel[] };
+ assignees?: { nodes: GHUser[] };
+ comments?: { totalCount: number };
}
export interface IssueComment {
@@ -15,7 +23,7 @@ export interface IssueComment {
createdAt: string;
}
-interface Issue extends IssueRow, IssueComment {
+interface Issue extends Pick, IssueComment {
url: string;
locked: boolean;
labels: { nodes: { name: string; color: string }[] };
@@ -23,21 +31,37 @@ interface Issue extends IssueRow, IssueComment {
comments: GHConnection;
}
-const rowFields = "number title state";
+const rowFields = `
+ id
+ url
+ number
+ title
+ state
+ createdAt
+ updatedAt
+ author {
+ ...actor
+ }
+ assignees(first: 100) {
+ nodes {
+ ...user
+ }
+ }
+ labels(first: 100) {
+ nodes {
+ ...labelInfo
+ }
+ }
+ comments(first: 0) {
+ totalCount
+ }
+`;
const pageInfo = "pageInfo { hasNextPage endCursor }";
const numbered = `query($repoOwner:String!, $repoName:String!, $number:Int!) {
repository(owner:$repoOwner,name:$repoName) {
issueOrPullRequest(number:$number) { __typename ... on Issue { ${rowFields} } }
}
}`;
-const browse = `query($repoOwner:String!, $repoName:String!, $states:[IssueState!], $filter:IssueFilters, $cursor:String) {
- repository(owner:$repoOwner,name:$repoName) {
- issues(first:50, after:$cursor, states:$states, filterBy:$filter, orderBy:{field:UPDATED_AT,direction:DESC}) {
- nodes { ${rowFields} }
- ${pageInfo}
- }
- }
-}`;
const search = `query($query:String!, $cursor:String) {
search(first:50, after:$cursor, type:ISSUE, query:$query) {
nodes { ... on Issue { ${rowFields} } }
@@ -45,51 +69,19 @@ const search = `query($query:String!, $cursor:String) {
}
}`;
-export type IssueStateFilter = "OPEN" | "CLOSED" | "ALL";
-
-export async function issueList(
- repo: GHRepositoryCoordinates,
- text: string,
- state: IssueStateFilter,
- assigned: string | null,
- cursor: string | null,
-) {
- const term = text.trim();
- const vars = repoVariables(repo);
- if (/^#\d+$/.test(term)) {
+export async function issueList(repo: GHRepositoryCoordinates, filter: IssueSearchValue, cursor: string | null) {
+ const term = filter.searchQuery?.trim() ?? "";
+ if (isExactIssueNumberQuery(term)) {
const number = Number(term.slice(1));
if (!number || number > 2147483647) return { items: [], next: null };
const data = await graphql<{
repository: { issueOrPullRequest: (IssueRow & { __typename: string }) | null } | null;
- }>(numbered, { ...vars, number });
+ }>(numbered, { ...repoVariables(repo), number });
const row = data.repository?.issueOrPullRequest;
return { items: row?.__typename === "Issue" ? [row] : [], next: null };
}
- let page: GHConnection | null;
- if (term) {
- const query = [
- `repo:${nameWithOwner(repo)}`,
- "is:issue",
- "in:title",
- "sort:updated-desc",
- state !== "ALL" && `is:${state.toLowerCase()}`,
- assigned && `assignee:${assigned}`,
- JSON.stringify(term),
- ]
- .filter(Boolean)
- .join(" ");
- page = (await graphql<{ search: GHConnection }>(search, { query, cursor })).search;
- } else {
- page =
- (
- await graphql<{ repository: { issues: GHConnection } | null }>(browse, {
- ...vars,
- states: state === "ALL" ? null : [state],
- filter: assigned ? { assignee: assigned } : null,
- cursor,
- })
- ).repository?.issues ?? null;
- }
+ const query = issueSearchQuery(repo, filter);
+ const page = (await graphql<{ search: GHConnection }>(search, { query, cursor })).search;
return {
items: (page?.nodes ?? []).filter((row): row is IssueRow => Boolean(row?.number)),
next: page?.pageInfo.hasNextPage && page.pageInfo.endCursor ? page.pageInfo.endCursor : null,
@@ -99,7 +91,7 @@ export async function issueList(
const details = `query($repoOwner:String!, $repoName:String!, $number:Int!, $cursor:String) {
repository(owner:$repoOwner,name:$repoName) {
issue(number:$number) {
- ${rowFields} id url body createdAt locked
+ number title state id url body createdAt locked
author {
...actorInfo
}
diff --git a/src/features/github/issues/issues.test.tsx b/src/features/github/issues/issues.test.tsx
index 257a645dfd..3262870f56 100644
--- a/src/features/github/issues/issues.test.tsx
+++ b/src/features/github/issues/issues.test.tsx
@@ -1,20 +1,53 @@
-import { afterEach, expect, it, vi } from "vitest";
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import * as actions from "@/platform/actions";
+import { useProject } from "@/platform/project";
+import { useContextMenuStore, type MenuItem } from "@/ui";
import { maybeEditorService, provideEditorService, type EditorService } from "@/workbench/contributions";
import * as client from "../api/client";
import type { GHRepository, GHUser } from "../api/types";
+import { useGhProjectAccount } from "../data/account";
import { resetConnection, useGhRepository } from "../data/repository";
import * as api from "./api";
import { IssueEditor } from "./IssueEditor";
-import { IssuesToolWindow } from "./IssuesToolWindow";
+import { IssuesHeaderActions, IssuesHeaderTabs, IssuesToolWindow } from "./IssuesToolWindow";
import { hasClosingReference, issueBranchName, issueForBranch, issueInput, rememberIssueBranch } from "./input";
+import { clearIssues, loadMoreIssues, useGhIssueList } from "./list";
+import {
+ isIssueQuickFilterSelected,
+ issueCommentsTooltip,
+ issueQuickFilters,
+ issueSearchHistoryText,
+ issueSearchQuery,
+} from "./model";
+import { loadIssueSearchHistory, loadLastIssueSearch } from "./searchHistory";
const repo = { owner: "acme", name: "app", host: "code.example" };
-const row = { title: "Fix editor focus", number: 7, state: "OPEN" as const };
+const user = (login: string, name: string | null = null): GHUser => ({
+ __typename: "User",
+ id: `id-${login}`,
+ login,
+ url: `https://code.example/${login}`,
+ avatarUrl: "",
+ name,
+});
+const row: api.IssueRow = {
+ id: "I7",
+ url: "https://code.example/acme/app/issues/7",
+ title: "Fix editor focus",
+ number: 7,
+ state: "OPEN",
+ createdAt: "2026-08-01T00:00:00Z",
+ updatedAt: "2026-08-01T00:00:00Z",
+ author: user("ann"),
+ labels: { nodes: [] },
+ assignees: { nodes: [] },
+ comments: { totalCount: 0 },
+};
const input = issueInput("code.example/acme/app", row);
function connectRepo() {
+ useProject.setState({ project: { root: "/one", name: "app" } as never });
useGhRepository.setState({
availability: {
kind: "ready",
@@ -29,18 +62,27 @@ function connectRepo() {
viewerPermission: "READ",
},
},
+ remotes: [{ owner: "acme", name: "app", host: "code.example", remote: "origin", url: "" }],
connection: {
coordinates: repo,
root: "/one",
repository: { viewerPermission: "READ", url: "https://code.example/acme/app" } as GHRepository,
- currentUser: { login: "me" } as GHUser,
+ currentUser: user("me"),
remotes: [],
},
});
}
+beforeEach(() => {
+ localStorage.clear();
+});
+
afterEach(() => {
vi.restoreAllMocks();
+ clearIssues();
+ useGhIssueList.setState({ search: {} });
+ useGhProjectAccount.setState({ status: null, loading: false, saving: false, revision: 0 });
+ useContextMenuStore.setState({ menu: null });
resetConnection();
localStorage.clear();
});
@@ -79,48 +121,65 @@ it("detects closing references regardless of line endings, casing, or keyword",
expect(hasClosingReference("Encloses #7", 7)).toBe(false);
});
-it("omits assignee filter when browsing all issues and passes IssueFilters when filtering by assignee", async () => {
- const gql = vi.spyOn(client, "graphql").mockResolvedValue({
- repository: {
- issues: {
- nodes: [row, null],
- pageInfo: { hasNextPage: true, endCursor: "c1" },
- },
- },
- });
- const all = await api.issueList(repo, "", "OPEN", null, null);
- expect(all).toEqual({ items: [row], next: "c1" });
- expect(gql).toHaveBeenCalledWith(
- expect.stringContaining("$filter:IssueFilters"),
- expect.objectContaining({ filter: null, states: ["OPEN"], cursor: null }),
+it("builds issue quick filters, search queries, history text, and comment tooltips", () => {
+ const q = issueQuickFilters("me");
+ expect(q.map((f) => f.title)).toEqual(["Open", "Your issues", "Assigned to you"]);
+ expect(isIssueQuickFilterSelected({ state: "OPEN", author: "me" }, q[1]!)).toBe(true);
+ expect(isIssueQuickFilterSelected({ state: "OPEN", author: "me", sort: "NEWEST" }, q[1]!)).toBe(false);
+
+ expect(
+ issueSearchQuery(repo, {
+ searchQuery: "crash",
+ state: "CLOSED",
+ author: "ann",
+ label: "good first issue",
+ assignee: "me",
+ sort: "RECENTLY_UPDATED",
+ }),
+ ).toBe(
+ 'type:issue repo:acme/app (crash) is:closed assignee:me author:ann label:"good first issue" sort:updated-desc',
);
- await api.issueList(repo, "", "ALL", "me", "c1");
- expect(gql).toHaveBeenLastCalledWith(
- expect.stringContaining("filterBy:$filter"),
- expect.objectContaining({ filter: { assignee: "me" }, states: null, cursor: "c1" }),
- );
+ expect(
+ issueSearchHistoryText({
+ searchQuery: "crash",
+ state: "OPEN",
+ label: "bug",
+ assignee: "me",
+ author: "ann",
+ sort: "NEWEST",
+ }),
+ ).toBe('"crash" state:"Open" label:bug assignee:me author:ann sort:"Newest"');
+
+ expect(issueCommentsTooltip(0)).toBe("No comments");
+ expect(issueCommentsTooltip(1)).toBe("1 comment");
+ expect(issueCommentsTooltip(4)).toBe("4 comments");
});
-it("filters out pull requests on exact #number lookup and safely quotes search queries", async () => {
+it("filters out pull requests on exact #number lookup and searches issues via GitHub search", async () => {
const gql = vi
.spyOn(client, "graphql")
.mockResolvedValueOnce({ repository: { issueOrPullRequest: { __typename: "PullRequest" } } })
.mockResolvedValueOnce({
search: {
nodes: [null, {}, row],
- pageInfo: { hasNextPage: false, endCursor: null },
+ pageInfo: { hasNextPage: true, endCursor: "c1" },
},
});
- expect(await api.issueList(repo, "#0", "OPEN", null, null)).toEqual({ items: [], next: null });
- expect(await api.issueList(repo, "#9999999999", "OPEN", null, null)).toEqual({ items: [], next: null });
+ expect(await api.issueList(repo, { searchQuery: "#0", state: "OPEN" }, null)).toEqual({ items: [], next: null });
+ expect(await api.issueList(repo, { searchQuery: "#9999999999", state: "OPEN" }, null)).toEqual({
+ items: [],
+ next: null,
+ });
expect(gql).not.toHaveBeenCalled();
- expect(await api.issueList(repo, "#12", "OPEN", null, null)).toEqual({ items: [], next: null });
- expect(await api.issueList(repo, 'foo "is:pr"', "CLOSED", "me", null)).toEqual({ items: [row], next: null });
+ expect(await api.issueList(repo, { searchQuery: "#12", state: "OPEN" }, null)).toEqual({ items: [], next: null });
+ expect(
+ await api.issueList(repo, { searchQuery: "focus", state: "CLOSED", assignee: "me", label: "bug" }, "c0"),
+ ).toEqual({ items: [row], next: "c1" });
expect(gql).toHaveBeenLastCalledWith(expect.any(String), {
- query: 'repo:acme/app is:issue in:title sort:updated-desc is:closed assignee:me "foo \\"is:pr\\""',
- cursor: null,
+ query: 'type:issue repo:acme/app (focus) is:closed assignee:me label:"bug"',
+ cursor: "c0",
});
});
@@ -193,31 +252,105 @@ it("passes issue metadata when clicking Create Branch in an IssueEditor", async
});
});
+it("renders repository header tab, account badge, two-line issue rows, and context menu matching Pull Requests", async () => {
+ connectRepo();
+ useGhProjectAccount.setState({
+ status: {
+ ghInstalled: true,
+ accounts: [
+ { login: "me", active: true },
+ { login: "me-work", active: false },
+ ],
+ configuredAccount: "",
+ effectiveAccount: "me",
+ suggestedAccount: null,
+ },
+ });
+ const items: api.IssueRow[] = [
+ {
+ ...row,
+ number: 7,
+ title: "Fix editor focus",
+ state: "OPEN",
+ labels: { nodes: [{ id: "L1", url: "", name: "bug", color: "ff0000" }] },
+ assignees: { nodes: [user("a"), user("b"), user("c")] },
+ comments: { totalCount: 3 },
+ },
+ {
+ ...row,
+ id: "I8",
+ number: 8,
+ title: "Already fixed",
+ state: "CLOSED",
+ author: null,
+ comments: { totalCount: 0 },
+ },
+ ];
+ vi.spyOn(api, "issueList").mockResolvedValue({ items, next: null });
+
+ await act(async () => {
+ render(
+ <>
+
+
+
+ >,
+ );
+ });
+
+ expect(screen.getByRole("tab", { name: "app" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "@me" })).toBeTruthy();
+ const rows = screen.getAllByRole("option");
+ expect(rows).toHaveLength(2);
+ const first = within(rows[0]!);
+ expect(first.getByText("Fix editor focus")).toBeTruthy();
+ expect(first.getByText(/^#7 · created .+, by ann$/)).toBeTruthy();
+ expect(rows[0]!.querySelector("[data-tooltip='3 comments']")?.textContent).toBe("3");
+ expect(rows[0]!.querySelectorAll("[data-avatar]")).toHaveLength(2);
+ expect(within(rows[1]!).getByText("CLOSED")).toBeTruthy();
+ expect(within(rows[1]!).getByText(/^#8 · created /).textContent).not.toContain(", by");
+ expect(loadLastIssueSearch()).toEqual({ state: "OPEN" });
+
+ fireEvent.contextMenu(rows[1]!);
+ expect(useGhIssueList.getState().selectedNumber).toBe(8);
+ const menuItems = useContextMenuStore.getState().menu!.items;
+ expect(menuItems.map((i: MenuItem) => ("action" in i ? i.action : i.kind))).toEqual([
+ "github.issue.show",
+ "github.issue.createBranch",
+ "github.issue.openInBrowser",
+ "github.issue.copyUrl",
+ "separator",
+ "github.issue.refresh",
+ ]);
+});
+
it("deduplicates paginated issues and keeps keyboard activation working after filtering", async () => {
connectRepo();
const openInput = vi.fn().mockResolvedValue(undefined);
const previousEditor = maybeEditorService();
provideEditorService({ openInput } as unknown as EditorService);
try {
- const page1 = [
- { number: 10, title: "First issue", state: "OPEN" as const },
- { number: 9, title: "Second issue", state: "OPEN" as const },
- { number: 8, title: "Third issue", state: "OPEN" as const },
+ const page1: api.IssueRow[] = [
+ { number: 10, title: "First issue", state: "OPEN" },
+ { number: 9, title: "Second issue", state: "OPEN" },
+ { number: 8, title: "Third issue", state: "OPEN" },
];
- const page2 = [
- { number: 8, title: "Third issue", state: "OPEN" as const },
- { number: 7, title: "Fourth issue", state: "OPEN" as const },
+ const page2: api.IssueRow[] = [
+ { number: 8, title: "Third issue", state: "OPEN" },
+ { number: 7, title: "Fourth issue", state: "OPEN" },
];
- vi.spyOn(api, "issueList").mockImplementation(async (_r, term, _state, _assigned, cursor) => {
- if (term === "#7") return { items: [row], next: null };
+ vi.spyOn(api, "issueList").mockImplementation(async (_r, filter, cursor) => {
+ if (filter.searchQuery === "#7") return { items: [row], next: null };
if (cursor === "c1") return { items: page2, next: null };
return { items: page1, next: "c1" };
});
- render();
- const loadMore = await screen.findByRole("button", { name: "Load more" });
- fireEvent.click(loadMore);
- await waitFor(() => expect(screen.queryByRole("button", { name: "Load more" })).toBeNull());
+ await act(async () => {
+ render();
+ });
+ await act(async () => {
+ await loadMoreIssues();
+ });
// Move selection down to the last item (index 3, #7) — requires 3 ArrowDowns if index 0 is active
// and #8 was deduplicated rather than appended twice.
@@ -234,8 +367,11 @@ it("deduplicates paginated issues and keeps keyboard activation working after fi
// Filter down to a single item (#7): active index must clamp back to 0 so Enter still works.
const search = screen.getByRole("textbox", { name: "Search issues" });
fireEvent.change(search, { target: { value: "#7" } });
- fireEvent.keyDown(search, { key: "Enter" });
- await waitFor(() => expect(api.issueList).toHaveBeenCalledWith(repo, "#7", "OPEN", null, null));
+ await act(async () => {
+ fireEvent.keyDown(search, { key: "Enter" });
+ });
+ await waitFor(() => expect(api.issueList).toHaveBeenCalledWith(repo, { state: "OPEN", searchQuery: "#7" }, null));
+ expect(loadIssueSearchHistory()).toEqual([{ state: "OPEN", searchQuery: "#7" }]);
fireEvent.keyDown(listbox, { key: "Enter" });
expect(openInput).toHaveBeenLastCalledWith(issueInput("code.example/acme/app", row), { focus: true });
@@ -244,26 +380,29 @@ it("deduplicates paginated issues and keeps keyboard activation working after fi
}
});
-it("ignores stale responses when changing filters mid-fetch", async () => {
+it("ignores stale responses when changing filters mid-fetch and supports chip reset, empty states, and retry", async () => {
connectRepo();
let resolveFirst!: (v: { items: api.IssueRow[]; next: string | null }) => void;
const first = new Promise<{ items: api.IssueRow[]; next: string | null }>((r) => {
resolveFirst = r;
});
- vi.spyOn(api, "issueList").mockImplementation((_r, _term, _state, assigned) => {
- if (assigned === "me")
- return Promise.resolve({ items: [{ number: 42, title: "Mine", state: "OPEN" }], next: null });
+ const spy = vi.spyOn(api, "issueList").mockImplementation((_r, filter) => {
+ if (filter.state === undefined)
+ return Promise.resolve({ items: [{ number: 42, title: "All states", state: "OPEN" }], next: null });
return first;
});
render();
- const mineBtn = await screen.findByRole("button", { name: "Assigned to me" });
- fireEvent.click(mineBtn);
- await waitFor(() => expect(api.issueList).toHaveBeenCalledWith(repo, "", "OPEN", "me", null));
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Reset State" }));
+ });
+ await waitFor(() => expect(spy).toHaveBeenCalledWith(repo, {}, null));
- // Resolve the stale unfiltered request after the filtered request already completed.
- resolveFirst({ items: [{ number: 1, title: "Stale issue", state: "OPEN" }], next: null });
- await Promise.resolve();
+ // Resolve the stale filtered request after the unfiltered request already completed.
+ await act(async () => {
+ resolveFirst({ items: [{ number: 1, title: "Stale issue", state: "OPEN" }], next: null });
+ await Promise.resolve();
+ });
const openInput = vi.fn().mockResolvedValue(undefined);
const previousEditor = maybeEditorService();
@@ -272,10 +411,85 @@ it("ignores stale responses when changing filters mid-fetch", async () => {
const listbox = screen.getByRole("listbox", { name: "GitHub Issues" });
fireEvent.keyDown(listbox, { key: "Enter" });
expect(openInput).toHaveBeenCalledWith(
- issueInput("code.example/acme/app", { number: 42, title: "Mine", state: "OPEN" }),
+ issueInput("code.example/acme/app", { number: 42, title: "All states", state: "OPEN" }),
{ focus: true },
);
} finally {
provideEditorService(previousEditor);
}
+
+ // Empty state & retry on error.
+ spy.mockResolvedValueOnce({ items: [], next: null });
+ await act(async () => {
+ fireEvent.click(screen.getByText("Sort"));
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByText("Newest"));
+ });
+ expect(screen.getByText("No issues matching filters")).toBeTruthy();
+
+ spy.mockRejectedValueOnce(new Error("HTTP 502"));
+ await act(async () => {
+ fireEvent.click(screen.getByText("Clear filters"));
+ });
+ expect(screen.getByText("Can't load issues")).toBeTruthy();
+
+ spy.mockResolvedValueOnce({ items: [row], next: null });
+ await act(async () => {
+ fireEvent.click(screen.getByText("Retry"));
+ });
+ expect(screen.getAllByRole("option")).toHaveLength(1);
+});
+
+it("fetches issues only once when switching the active GitHub account", async () => {
+ connectRepo();
+ const spy = vi.spyOn(api, "issueList").mockResolvedValue({ items: [row], next: null });
+
+ await act(async () => {
+ render();
+ });
+ expect(spy).toHaveBeenCalledTimes(1);
+
+ spy.mockClear();
+ await act(async () => {
+ const cur = useGhRepository.getState().connection!;
+ useGhRepository.setState({
+ connection: { ...cur, currentUser: user("me-work") },
+ });
+ });
+ expect(spy).toHaveBeenCalledTimes(1);
+});
+
+it("hints #number lookup via placeholder and disables ignored filter chips while #number is active", async () => {
+ connectRepo();
+ vi.spyOn(api, "issueList").mockResolvedValue({ items: [row], next: null });
+
+ await act(async () => {
+ render();
+ });
+
+ const search = screen.getByRole("textbox", { name: "Search issues" });
+ expect(search).toHaveAttribute("placeholder", "Title or #number");
+ expect(screen.getByRole("button", { name: "Author" })).toBeEnabled();
+ expect(screen.getByRole("button", { name: "Reset State" })).toBeEnabled();
+
+ fireEvent.change(search, { target: { value: "#7" } });
+ await act(async () => {
+ fireEvent.keyDown(search, { key: "Enter" });
+ });
+
+ for (const label of ["Open", "Reset State", "Author", "Label", "Assignee", "Sort"]) {
+ expect(screen.getByRole("button", { name: label })).toBeDisabled();
+ }
+ expect(screen.getByRole("button", { name: "Author" }).closest("[data-tooltip]")).toHaveAttribute(
+ "data-tooltip",
+ "Filters are ignored for #number lookup",
+ );
+
+ fireEvent.change(search, { target: { value: "" } });
+ await act(async () => {
+ fireEvent.keyDown(search, { key: "Enter" });
+ });
+ expect(screen.getByRole("button", { name: "Author" })).toBeEnabled();
+ expect(screen.getByRole("button", { name: "Reset State" })).toBeEnabled();
});
diff --git a/src/features/github/issues/list.ts b/src/features/github/issues/list.ts
new file mode 100644
index 0000000000..e71cc1c6bf
--- /dev/null
+++ b/src/features/github/issues/list.ts
@@ -0,0 +1,114 @@
+/**
+ * The GitHub Issues list store, paralleling `data/list.ts`: pages of 50, cursor-paged,
+ * scrolling past 70% loads the next page, and `reloadIssues()` keeps rows visible until
+ * the first page arrives.
+ */
+import { create } from "zustand";
+import { errorMessage } from "../api/client";
+import { sameRepository, useGhRepository } from "../data/repository";
+import * as api from "./api";
+import type { IssueRow } from "./api";
+import { sameIssueSearch, type IssueSearchValue } from "./model";
+
+interface IssueListState {
+ search: IssueSearchValue;
+ items: IssueRow[];
+ cursor: string | null;
+ hasMore: boolean;
+ loading: boolean;
+ error: string | null;
+ loaded: boolean;
+ selectedNumber: number | null;
+}
+
+export const useGhIssueList = create(() => ({
+ search: {},
+ items: [],
+ cursor: null,
+ hasMore: true,
+ loading: false,
+ error: null,
+ loaded: false,
+ selectedNumber: null,
+}));
+
+let seq = 0;
+
+function mergeByNumber(previous: readonly IssueRow[], incoming: readonly IssueRow[]): IssueRow[] {
+ const seen = new Set(previous.map((i) => i.number));
+ const out = [...previous];
+ for (const item of incoming) {
+ if (seen.has(item.number)) continue;
+ seen.add(item.number);
+ out.push(item);
+ }
+ return out;
+}
+
+async function fetchPage(reset: boolean): Promise {
+ const repo = useGhRepository.getState().connection?.coordinates;
+ if (!repo) return;
+ const my = ++seq;
+ const s = useGhIssueList.getState();
+ useGhIssueList.setState({ loading: true, error: null });
+ try {
+ const page = await api.issueList(repo, s.search, reset ? null : s.cursor);
+ if (my !== seq) return;
+ useGhIssueList.setState((cur) => ({
+ items: reset ? mergeByNumber([], page.items) : mergeByNumber(cur.items, page.items),
+ cursor: page.next,
+ hasMore: page.next !== null,
+ loading: false,
+ loaded: true,
+ }));
+ } catch (e) {
+ if (my !== seq) return;
+ useGhIssueList.setState({
+ loading: false,
+ error: errorMessage(e),
+ hasMore: false,
+ loaded: true,
+ ...(reset ? { items: [] } : {}),
+ });
+ }
+}
+
+export function setIssueSearch(search: IssueSearchValue): Promise {
+ const same = sameIssueSearch(useGhIssueList.getState().search, search);
+ useGhIssueList.setState({ search, ...(same ? {} : { items: [], loaded: false }), cursor: null, hasMore: true });
+ return fetchPage(true);
+}
+
+export function loadMoreIssues(): Promise {
+ const s = useGhIssueList.getState();
+ if (s.loading || !s.hasMore || !s.loaded) return Promise.resolve();
+ return fetchPage(false);
+}
+
+export function reloadIssues(): Promise {
+ useGhIssueList.setState({ cursor: null, hasMore: true });
+ return fetchPage(true);
+}
+
+export function setSelectedIssue(number: number | null) {
+ useGhIssueList.setState({ selectedNumber: number });
+}
+
+export function clearIssues() {
+ seq++;
+ useGhIssueList.setState({
+ items: [],
+ cursor: null,
+ hasMore: true,
+ loading: false,
+ error: null,
+ loaded: false,
+ selectedNumber: null,
+ });
+}
+
+useGhRepository.subscribe((s, prev) => {
+ const a = s.connection?.coordinates;
+ const b = prev.connection?.coordinates;
+ if (!sameRepository(a, b ?? null) && (a || b)) clearIssues();
+});
diff --git a/src/features/github/issues/model.ts b/src/features/github/issues/model.ts
new file mode 100644
index 0000000000..e13aa0504a
--- /dev/null
+++ b/src/features/github/issues/model.ts
@@ -0,0 +1,136 @@
+/**
+ * Pure rules of the GitHub Issues list, paralleling `list/model.ts` and `data/model.ts`:
+ * Quick Filters, State/Sort chip options, search query serialization, history text and
+ * row presentation helpers.
+ */
+import { tx } from "@/platform/i18n";
+import type { GHRepositoryCoordinates } from "../api/types";
+import type { PrSearchSort } from "../data/model";
+import { sortText, type ChipOption } from "../list/model";
+
+export type IssueSearchState = "OPEN" | "CLOSED";
+export type IssueSearchSort = PrSearchSort;
+
+/** The issue list filter: free text (or `#number`) plus chips. Unset = absent. */
+export interface IssueSearchValue {
+ searchQuery?: string;
+ state?: IssueSearchState;
+ author?: string;
+ label?: string;
+ assignee?: string;
+ sort?: IssueSearchSort;
+}
+
+export const DEFAULT_ISSUE_SEARCH: IssueSearchValue = { state: "OPEN" };
+
+const ISSUE_SEARCH_KEYS = ["searchQuery", "state", "author", "label", "assignee", "sort"] as const;
+
+const ISSUE_STATE_TERMS: Record = {
+ OPEN: "is:open",
+ CLOSED: "is:closed",
+};
+
+const ISSUE_SORT_TERMS: Record = {
+ NEWEST: "sort:created-desc",
+ OLDEST: "sort:created-asc",
+ MOST_COMMENTED: "sort:comments-desc",
+ LEAST_COMMENTED: "sort:comments-asc",
+ RECENTLY_UPDATED: "sort:updated-desc",
+ LEAST_RECENTLY_UPDATED: "sort:updated-asc",
+};
+
+export type IssueQuickFilterId = "OPEN" | "YOURS" | "ASSIGNED";
+
+export interface IssueQuickFilter {
+ id: IssueQuickFilterId;
+ title: string;
+ filter: IssueSearchValue;
+}
+
+export function issueQuickFilters(login: string): IssueQuickFilter[] {
+ return [
+ { id: "OPEN", title: "Open", filter: { state: "OPEN" } },
+ { id: "YOURS", title: "Your issues", filter: { state: "OPEN", author: login } },
+ { id: "ASSIGNED", title: "Assigned to you", filter: { state: "OPEN", assignee: login } },
+ ];
+}
+
+export const defaultIssueFilter = (): IssueSearchValue => ({ state: "OPEN" });
+
+export function issueFilterCount(v: IssueSearchValue): number {
+ return ISSUE_SEARCH_KEYS.filter((k) => v[k] !== undefined).length;
+}
+
+export function sameIssueSearch(a: IssueSearchValue, b: IssueSearchValue): boolean {
+ return ISSUE_SEARCH_KEYS.every((k) => a[k] === b[k]);
+}
+
+export const isIssueQuickFilterSelected = (search: IssueSearchValue, q: IssueQuickFilter) =>
+ sameIssueSearch(search, q.filter);
+
+export function normalizeIssueSearch(v: unknown): IssueSearchValue | null {
+ if (!v || typeof v !== "object") return null;
+ const r = v as Record;
+ const str = (x: unknown) => (typeof x === "string" && x !== "" ? x : undefined);
+ const oneOf = (x: unknown, all: Record) =>
+ typeof x === "string" && x in all ? (x as T) : undefined;
+ const out: IssueSearchValue = {
+ searchQuery: str(r.searchQuery),
+ state: oneOf(r.state, ISSUE_STATE_TERMS),
+ author: str(r.author),
+ label: str(r.label),
+ assignee: str(r.assignee),
+ sort: oneOf(r.sort, ISSUE_SORT_TERMS),
+ };
+ for (const k of ISSUE_SEARCH_KEYS) if (out[k] === undefined) delete out[k];
+ return out;
+}
+
+export const ISSUE_STATE_OPTIONS: ChipOption[] = [
+ { value: "OPEN", text: "Open" },
+ { value: "CLOSED", text: "Closed" },
+];
+
+export const issueStateText = (v: IssueSearchState) => tx(ISSUE_STATE_OPTIONS.find((o) => o.value === v)?.text ?? v);
+
+export function withIssueQuery(v: IssueSearchValue, text: string): IssueSearchValue {
+ const { searchQuery: _, ...rest } = v;
+ const trimmed = text.trim();
+ return trimmed ? { ...rest, searchQuery: trimmed } : rest;
+}
+
+/** Whether `text` is an exact `#number` issue lookup (e.g. `#42`). */
+export const isExactIssueNumberQuery = (text: string | undefined): boolean => /^#\d+$/.test((text ?? "").trim());
+
+export function issueSearchTerms(v: IssueSearchValue): string | null {
+ const terms: string[] = [];
+ const text = v.searchQuery?.trim();
+ if (text) terms.push(`(${text})`);
+ if (v.state) terms.push(ISSUE_STATE_TERMS[v.state]);
+ if (v.assignee !== undefined) terms.push(`assignee:${v.assignee}`);
+ if (v.author !== undefined) terms.push(`author:${v.author}`);
+ if (v.label !== undefined) terms.push(`label:"${v.label.replace(/"/g, '\\"')}"`);
+ if (v.sort) terms.push(ISSUE_SORT_TERMS[v.sort]);
+ return terms.length ? terms.join(" ") : null;
+}
+
+export function issueSearchQuery(repo: GHRepositoryCoordinates, v: IssueSearchValue): string {
+ const terms = issueSearchTerms(v);
+ return [`type:issue repo:${repo.owner}/${repo.name}`, terms].filter(Boolean).join(" ");
+}
+
+export function issueSearchHistoryText(v: IssueSearchValue): string {
+ const parts: string[] = [];
+ if (v.searchQuery !== undefined) parts.push(`"${v.searchQuery}"`);
+ if (v.state) parts.push(`state:"${issueStateText(v.state)}"`);
+ if (v.label !== undefined) parts.push(`label:${v.label}`);
+ if (v.assignee !== undefined) parts.push(`assignee:${v.assignee}`);
+ if (v.author !== undefined) parts.push(`author:${v.author}`);
+ if (v.sort) parts.push(`sort:"${sortText(v.sort)}"`);
+ return parts.join(" ");
+}
+
+export function issueCommentsTooltip(count: number): string {
+ if (count === 0) return tx("No comments");
+ return count === 1 ? tx`${count} comment` : tx`${count} comments`;
+}
diff --git a/src/features/github/issues/searchHistory.ts b/src/features/github/issues/searchHistory.ts
new file mode 100644
index 0000000000..5822c959a2
--- /dev/null
+++ b/src/features/github/issues/searchHistory.ts
@@ -0,0 +1,69 @@
+/**
+ * Per-project search history for the GitHub Issues list, paralleling `data/searchHistory.ts`:
+ * keeps the last 10 searches (newest first) and restores the last search used.
+ */
+import { useProject } from "@/platform/project";
+import {
+ DEFAULT_ISSUE_SEARCH,
+ issueFilterCount,
+ normalizeIssueSearch,
+ sameIssueSearch,
+ type IssueSearchValue,
+} from "./model";
+
+const MAX_HISTORY = 10;
+const historyKey = (root: string) => `openidea.github.issueSearchHistory.v1:${root}`;
+const lastKey = (root: string) => `openidea.github.issueLastSearch.v1:${root}`;
+const projectRoot = () => useProject.getState().project?.root ?? null;
+
+function load(key: string): unknown {
+ try {
+ const raw = globalThis.localStorage?.getItem(key);
+ return raw ? JSON.parse(raw) : null;
+ } catch {
+ return null;
+ }
+}
+
+function save(key: string, value: unknown) {
+ try {
+ globalThis.localStorage?.setItem(key, JSON.stringify(value));
+ } catch {
+ /* storage unavailable */
+ }
+}
+
+export function withIssueSearch(
+ history: readonly IssueSearchValue[],
+ v: IssueSearchValue,
+ defaultSearch: IssueSearchValue = DEFAULT_ISSUE_SEARCH,
+): IssueSearchValue[] {
+ if (issueFilterCount(v) === 0 || sameIssueSearch(v, defaultSearch)) return [...history];
+ return [v, ...history.filter((h) => !sameIssueSearch(h, v))].slice(0, MAX_HISTORY);
+}
+
+export function loadIssueSearchHistory(root = projectRoot()): IssueSearchValue[] {
+ if (!root) return [];
+ const v = load(historyKey(root));
+ return Array.isArray(v) ? v.flatMap((x) => normalizeIssueSearch(x) ?? []) : [];
+}
+
+export function rememberIssueSearch(
+ v: IssueSearchValue,
+ root = projectRoot(),
+ defaultSearch: IssueSearchValue = DEFAULT_ISSUE_SEARCH,
+) {
+ if (root) save(historyKey(root), withIssueSearch(loadIssueSearchHistory(root), v, defaultSearch));
+}
+
+export function loadLastIssueSearch(root = projectRoot()): IssueSearchValue | null {
+ return root ? normalizeIssueSearch(load(lastKey(root))) : null;
+}
+
+export function saveLastIssueSearch(v: IssueSearchValue, root = projectRoot()) {
+ if (root) save(lastKey(root), v);
+}
+
+export function initialIssueSearch(root = projectRoot()): IssueSearchValue {
+ return loadLastIssueSearch(root) ?? { state: "OPEN" };
+}
diff --git a/src/features/github/list/List.module.css b/src/features/github/list/List.module.css
index 1305681429..9a71ffccd4 100644
--- a/src/features/github/list/List.module.css
+++ b/src/features/github/list/List.module.css
@@ -83,12 +83,15 @@
color: var(--fg);
white-space: nowrap;
}
-.chip:hover {
+.chip:hover:not([data-disabled]) {
background: var(--bg-toolbar-hover);
}
.chip[data-set] {
color: var(--fg-strong);
}
+.chip[data-disabled] {
+ opacity: 0.45;
+}
.chipMain {
display: inline-flex;
align-items: center;
diff --git a/src/features/github/list/PullRequestRow.tsx b/src/features/github/list/PullRequestRow.tsx
index 2f4456801c..d1e040712f 100644
--- a/src/features/github/list/PullRequestRow.tsx
+++ b/src/features/github/list/PullRequestRow.tsx
@@ -28,7 +28,7 @@ import styles from "./List.module.css";
const MAX_AVATARS = 2;
/** Sets the full title as the tooltip only while it is cut off. */
-function titleTooltip(e: PointerEvent) {
+export function titleTooltip(e: PointerEvent) {
const el = e.currentTarget;
if (el.scrollWidth > el.clientWidth) el.dataset.tooltip = el.textContent ?? "";
else delete el.dataset.tooltip;
diff --git a/src/features/github/list/SearchPanel.tsx b/src/features/github/list/SearchPanel.tsx
index 40f1ea3bf9..80e98b8eb8 100644
--- a/src/features/github/list/SearchPanel.tsx
+++ b/src/features/github/list/SearchPanel.tsx
@@ -10,6 +10,7 @@
*/
import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { tx, txPart, useTx } from "@/platform/i18n";
+import { isImeKey } from "@/platform/ime";
import { Icon, IconButton, Menu, SearchField, showContextMenu, type MenuItem } from "@/ui";
import type { GHLabel, GHUser } from "../api/types";
import { filterCount, type PrSearchValue } from "../data/model";
@@ -38,25 +39,40 @@ type Apply = (v: PrSearchValue) => void;
// ---------------------------------------------------------------------------
// Search field
-function SearchTextField({ search, apply }: { search: PrSearchValue; apply: Apply }) {
- const applied = search.searchQuery ?? "";
- const [text, setText] = useState(applied);
+export function SearchTextField({
+ value,
+ onApply,
+ loadHistory,
+ formatHistory,
+ onSelectHistory,
+ ariaLabel,
+ placeholder,
+}: {
+ value: string;
+ onApply: (text: string) => void;
+ loadHistory: () => H[];
+ formatHistory: (item: H) => string;
+ onSelectHistory: (item: H) => void;
+ ariaLabel: string;
+ placeholder?: string;
+}) {
+ const [text, setText] = useState(value);
// The text follows the search when it changes elsewhere (history, Quick Filters, Clear).
- const [shown, setShown] = useState(applied);
- if (shown !== applied) {
- setShown(applied);
- setText(applied);
+ const [shown, setShown] = useState(value);
+ if (shown !== value) {
+ setShown(value);
+ setText(value);
}
const field = useRef(null);
const showHistory = () => {
const r = field.current?.getBoundingClientRect();
- const history = loadSearchHistory();
+ const history = loadHistory();
const items: MenuItem[] = history.length
? history.map((v, i) => ({
id: `h${i}`,
- label: searchHistoryText(v),
+ label: formatHistory(v),
verbatim: true,
- run: () => apply(v),
+ run: () => onSelectHistory(v),
}))
: [{ label: "Nothing to show", disabled: true }];
showContextMenu({ x: (r?.left ?? 0) + 2, y: r?.bottom ?? 0 }, items);
@@ -68,12 +84,13 @@ function SearchTextField({ search, apply }: { search: PrSearchValue; apply: Appl
onChange={setText}
onHistory={showHistory}
clearable={false}
+ placeholder={placeholder}
onKeyDown={(e) => {
- if (e.key !== "Enter") return;
+ if (e.key !== "Enter" || isImeKey(e.nativeEvent)) return;
e.preventDefault();
- apply(withQuery(search, text));
+ onApply(text);
}}
- aria-label="Search pull requests"
+ aria-label={ariaLabel}
/>
);
@@ -82,20 +99,34 @@ function SearchTextField({ search, apply }: { search: PrSearchValue; apply: Appl
// ---------------------------------------------------------------------------
// Quick Filters
-function QuickFilterButton({ search, apply, login }: { search: PrSearchValue; apply: Apply; login: string }) {
+export interface QuickFilterMenuItem {
+ id: string;
+ title: string;
+ selected: boolean;
+ run: () => void;
+}
+
+export function QuickFilterButton({
+ quickItems,
+ count,
+ onClear,
+}: {
+ quickItems: readonly QuickFilterMenuItem[];
+ count: number;
+ onClear: () => void;
+}) {
const [open, setOpen] = useState(false);
const anchor = useRef(null);
- const count = filterCount(search);
const items: MenuItem[] = [
{ kind: "header", label: "Quick Filters" },
- ...quickFilters(login).map((q): MenuItem => ({
+ ...quickItems.map((q): MenuItem => ({
id: q.id,
label: q.title,
- checked: isQuickFilterSelected(search, q),
- run: () => apply(q.filter),
+ checked: q.selected,
+ run: q.run,
})),
{ kind: "separator" },
- ...(count > 0 ? [{ id: "clear", label: tx`Clear ${count} Filters`, verbatim: true, run: () => apply({}) }] : []),
+ ...(count > 0 ? [{ id: "clear", label: tx`Clear ${count} Filters`, verbatim: true, run: onClear }] : []),
];
return (
@@ -111,17 +142,21 @@ function QuickFilterButton({ search, apply, login }: { search: PrSearchValue; ap
type PopupRender = (anchor: HTMLElement, done: (value: string | undefined) => void) => ReactNode;
-function FilterChip({
+export function FilterChip({
title,
value,
onChange,
popup,
+ disabled,
+ disabledTooltip,
}: {
title: string;
/** The chip's text for the current value; undefined when unset. */
value: string | undefined;
onChange: (value: string | undefined) => void;
popup: PopupRender;
+ disabled?: boolean;
+ disabledTooltip?: string;
}) {
const t = useTx();
const chip = useRef(null);
@@ -129,19 +164,27 @@ function FilterChip({
const set = value !== undefined;
const name = t(title);
const onKeyDown = (e: KeyboardEvent) => {
+ if (disabled) return;
if (e.key === "Delete" || e.key === "Backspace") {
e.preventDefault();
onChange(undefined);
}
};
return (
-
+