fix(github): fix issue browse assignee filter, list keyboard navigation, and edge cases

Цей коміт міститься в:
l0ng-ai committed 2026-12-05 00:49:35 +08:00
1 джерело 177babf298
коміт 55464314bb
10 files changed
+365 -60

No files matched your search

+7 -3
Переглянути файл
@@ -24,7 +24,8 @@ import {
T,
type MenuItem,
} from "@/ui";
import { issueForBranch } from "../issues/input";
import { connectedRoot } from "../data/repository";
import { hasClosingReference, issueForBranch } from "../issues/input";
import { openPullRequest } from "../toolwindow/open";
import { ChangesPanel } from "./ChangesPanel";
import { DirectionSelector } from "./DirectionSelector";
@@ -109,7 +110,10 @@ function TextPanel() {
const templateLoading = useCreatePr((s) => s.templateLoading);
const direction = useCreatePr((s) => s.direction);
const head = direction?.headBranch;
const number = direction && head?.kind === "local" ? issueForBranch(direction.baseRepo, head.name) : null;
const number =
direction && head?.kind === "local"
? issueForBranch({ ...direction.baseRepo, root: direction.baseRepo.root ?? connectedRoot() }, head.name)
: null;
const closing = number ? `Closes #${number}` : null;
return (
<div className={styles.text}>
@@ -120,7 +124,7 @@ function TextPanel() {
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
{closing && !templateLoading && !description.split("\n").includes(closing) && (
{closing && number && !templateLoading && !hasClosingReference(description, number) && (
<Button
size="small"
variant="ghost"
+2 -2
Переглянути файл
@@ -74,8 +74,8 @@ function actions(): ActionSpec[] {
category: "GitHub",
icon: "branch",
when: CONNECTED,
enabled: () => maybeEditorService()?.activeInput?.()?.kind === ISSUE_KIND,
run: async () => (await import("./issues/actions")).createIssueBranch(),
enabled: ({ arg }) => Boolean(arg) || maybeEditorService()?.activeInput?.()?.kind === ISSUE_KIND,
run: async ({ arg }) => (await import("./issues/actions")).createIssueBranch(arg),
},
// Git › GitHub
{
+21 -3
Переглянути файл
@@ -46,8 +46,15 @@ function Discussion({ connection, number }: { connection: GHConnection; number:
)}
</div>
);
const comments = page.items.flatMap((item) => item.comments.nodes);
const seen = new Set(comments.map((c) => c.id));
const seen = new Set<string>();
const comments: IssueComment[] = [];
for (const item of page.items) {
for (const c of item.comments.nodes) {
if (seen.has(c.id)) continue;
seen.add(c.id);
comments.push(c);
}
}
return (
<div className={timeline.scroll}>
<div className={timeline.column}>
@@ -72,7 +79,18 @@ function Discussion({ connection, number }: { connection: GHConnection; number:
{issue.assignees.nodes.map((u) => (
<span key={u.login}>@{u.login}</span>
))}
<Button size="small" icon="branch" onClick={() => void executeAction("github.issue.createBranch")}>
<Button
size="small"
icon="branch"
onClick={() =>
void executeAction("github.issue.createBranch", {
repository: repositoryKey(connection.coordinates),
number: issue.number,
title: issue.title,
state: issue.state,
})
}
>
<T>Create Branch…</T>
</Button>
<IconButton size="small" title="Refresh" icon="refresh" onClick={() => void page.refresh()} />
+7 -4
Переглянути файл
@@ -16,15 +16,13 @@
min-width: 0;
}
.repo {
flex: 1;
min-width: 0;
overflow: hidden;
color: var(--fg-secondary);
text-overflow: ellipsis;
white-space: nowrap;
}
.repo {
flex: 1;
color: var(--fg-secondary);
}
.filters,
.metadata {
flex-wrap: wrap;
@@ -58,3 +56,8 @@
color: var(--fg-secondary);
overflow-wrap: anywhere;
}
.error {
color: var(--danger);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
+20 -4
Переглянути файл
@@ -2,14 +2,17 @@ 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";
import { GithubConnectionGate } from "../toolwindow/GithubConnectionGate";
import { issueList, type IssueStateFilter } from "./api";
import { issueList, type IssueRow, type IssueStateFilter } from "./api";
import { issueInput } from "./input";
import { usePages } from "./usePages";
import styles from "./Issues.module.css";
const issueKey = (item: IssueRow) => item.number;
export function IssuesToolWindow() {
const connection = useGhRepository((s) => s.connection);
return (
@@ -29,14 +32,21 @@ function IssuesList({ connection }: { connection: GHConnection }) {
const [term, setTerm] = useState("");
const [state, setState] = useState<IssueStateFilter>("OPEN");
const [mine, setMine] = useState(false);
const [selectedNumber, setSelectedNumber] = useState<number | null>(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);
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;
return (
<div className={styles.panel}>
<div className={styles.toolbar}>
@@ -55,7 +65,7 @@ function IssuesList({ connection }: { connection: GHConnection }) {
if (!v.trim()) setTerm("");
}}
onKeyDown={(e) => {
if (e.key === "Enter") setTerm(text.trim());
if (e.key === "Enter" && !isImeKey(e.nativeEvent)) setTerm(text.trim());
}}
/>
<div className={styles.filters}>
@@ -80,6 +90,8 @@ function IssuesList({ connection }: { connection: GHConnection }) {
rowHeight={rowHeight}
items={page.items}
getKey={(i) => String(i.number)}
activeIndex={activeIndex}
onActiveChange={(i) => setSelectedNumber(page.items[i]?.number ?? null)}
className={styles.list}
aria-label="GitHub Issues"
onActivate={(row, _i, event) => {
@@ -96,7 +108,11 @@ function IssuesList({ connection }: { connection: GHConnection }) {
)}
empty={page.error ? null : <EmptyState title={page.loading ? "Loading…" : "No matching issues"} />}
/>
{page.error && <div role="alert">{page.error}</div>}
{page.error && (
<div className={styles.error} role="alert">
{page.error}
</div>
)}
{(page.next || page.error) && (
<Button size="small" disabled={page.loading} onClick={() => void page.more()}>
{tx(page.error ? "Retry" : "Load more")}
+12 -3
Переглянути файл
@@ -4,16 +4,24 @@ import { maybeEditorService } from "@/workbench/contributions";
import { pickItems } from "@/workbench/inputDialogs";
import { useGhRepository, repositoryKey } from "../data/repository";
import { openInBrowser } from "../data/local";
import { issueBranchName, issueData, rememberIssueBranch } from "./input";
import { issueBranchName, issueData, rememberIssueBranch, type IssueInput } from "./input";
export function newIssue() {
const connection = useGhRepository.getState().connection;
if (connection) return openInBrowser(`${connection.repository.url}/issues/new/choose`);
}
export async function createIssueBranch() {
function asIssueInput(arg: unknown): IssueInput | null {
if (!arg || typeof arg !== "object") return null;
const d = arg as Partial<IssueInput>;
return typeof d.number === "number" && typeof d.repository === "string" && typeof d.title === "string"
? (d as IssueInput)
: null;
}
export async function createIssueBranch(arg?: unknown) {
const input = maybeEditorService()?.activeInput?.();
const issue = input && issueData(input);
const issue = asIssueInput(arg) ?? (input && issueData(input));
const connection = useGhRepository.getState().connection;
if (!connection || !issue || repositoryKey(connection.coordinates) !== issue.repository) return;
const branches = await call(commands.vcsBranches(connection.root));
@@ -21,6 +29,7 @@ export async function createIssueBranch() {
const choices = branches
.filter((b) => !b.remote || !b.name.endsWith("/HEAD"))
.sort((a, b) => Number(b.current) - Number(a.current));
if (!choices.length) return;
const picked = await pickItems({
title: "Choose Base Branch",
multiple: false,
+34 -22
Переглянути файл
@@ -30,9 +30,9 @@ const numbered = `query($repoOwner:String!, $repoName:String!, $number:Int!) {
issueOrPullRequest(number:$number) { __typename ... on Issue { ${rowFields} } }
}
}`;
const browse = `query($repoOwner:String!, $repoName:String!, $states:[IssueState!], $assigned:String, $cursor:String) {
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:{assignee:$assigned}, orderBy:{field:UPDATED_AT,direction:DESC}) {
issues(first:50, after:$cursor, states:$states, filterBy:$filter, orderBy:{field:UPDATED_AT,direction:DESC}) {
nodes { ${rowFields} }
${pageInfo}
}
@@ -59,14 +59,13 @@ export async function issueList(
if (/^#\d+$/.test(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 } }>(
numbered,
{ ...vars, number },
);
const row = data.repository.issueOrPullRequest;
const data = await graphql<{
repository: { issueOrPullRequest: (IssueRow & { __typename: string }) | null } | null;
}>(numbered, { ...vars, number });
const row = data.repository?.issueOrPullRequest;
return { items: row?.__typename === "Issue" ? [row] : [], next: null };
}
let page: GHConnection<IssueRow>;
let page: GHConnection<IssueRow | null> | null;
if (term) {
const query = [
`repo:${nameWithOwner(repo)}`,
@@ -79,20 +78,21 @@ export async function issueList(
]
.filter(Boolean)
.join(" ");
page = (await graphql<{ search: GHConnection<IssueRow> }>(search, { query, cursor })).search;
page = (await graphql<{ search: GHConnection<IssueRow | null> }>(search, { query, cursor })).search;
} else {
page = (
await graphql<{ repository: { issues: GHConnection<IssueRow> } }>(browse, {
...vars,
states: state === "ALL" ? null : [state],
assigned,
cursor,
})
).repository.issues;
page =
(
await graphql<{ repository: { issues: GHConnection<IssueRow | null> } | null }>(browse, {
...vars,
states: state === "ALL" ? null : [state],
filter: assigned ? { assignee: assigned } : null,
cursor,
})
).repository?.issues ?? null;
}
return {
items: page.nodes.filter((row) => row.number),
next: page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null,
items: (page?.nodes ?? []).filter((row): row is IssueRow => Boolean(row?.number)),
next: page?.pageInfo.hasNextPage && page.pageInfo.endCursor ? page.pageInfo.endCursor : null,
};
}
@@ -119,15 +119,27 @@ const details = `query($repoOwner:String!, $repoName:String!, $number:Int!, $cur
}`;
export async function issueDetails(repo: GHRepositoryCoordinates, number: number, cursor: string | null) {
const data = await graphql<{ repository: { issue: Issue | null } }>(details, {
const data = await graphql<{ repository: { issue: Issue | null } | null }>(details, {
...repoVariables(repo),
number,
cursor,
});
const issue = data.repository.issue;
const raw = data.repository?.issue;
const issue = raw
? {
...raw,
comments: {
...raw.comments,
nodes: raw.comments.nodes.filter((comment): comment is IssueComment => Boolean(comment?.id)),
},
}
: null;
return {
items: issue ? [issue] : [],
next: issue?.comments.pageInfo.hasNextPage ? issue.comments.pageInfo.endCursor : null,
next:
issue?.comments.pageInfo.hasNextPage && issue.comments.pageInfo.endCursor
? issue.comments.pageInfo.endCursor
: null,
};
}
+24 -6
Переглянути файл
@@ -25,25 +25,43 @@ export function issueData(input: EditorInput): IssueInput | null {
}
export function issueBranchName(issue: IssueRow) {
const slug = issue.title
const normalized = issue.title
.normalize("NFC")
.toLowerCase()
.replace(/[^\p{L}\p{N}]+/gu, "-")
.slice(0, 48)
.replace(/^-+|-+$/g, "");
.replace(/^-+/, "");
const slug = [...normalized].slice(0, 48).join("").replace(/-+$/, "");
return [`issue-${issue.number}`, slug].filter(Boolean).join("-");
}
export function hasClosingReference(description: string, number: number): boolean {
return new RegExp(`(?:^|[\\s(])(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?):?\\s+#${number}(?:$|[^\\d])`, "i").test(
description,
);
}
type Checkout = GHRepositoryCoordinates & { root?: string | null };
function branchKey(repo: Checkout, branch: string) {
const root = repo.root ?? useProject.getState().project?.root ?? "";
return `openidea.github.issueBranch.v1:${root}:${repo.host ?? "github.com"}/${repo.owner}/${repo.name}:${branch}`;
const host = (repo.host ?? "github.com").toLowerCase();
const owner = repo.owner.toLowerCase();
const name = repo.name.toLowerCase();
return `openidea.github.issueBranch.v1:${root}:${host}/${owner}/${name}:${branch}`;
}
export function rememberIssueBranch(repo: Checkout, branch: string, number: number) {
localStorage.setItem(branchKey(repo, branch), String(number));
try {
localStorage.setItem(branchKey(repo, branch), String(number));
} catch {
/* storage unavailable */
}
}
export function issueForBranch(repo: Checkout, branch: string): number | null {
return Number(localStorage.getItem(branchKey(repo, branch))) || null;
try {
return Number(localStorage.getItem(branchKey(repo, branch))) || null;
} catch {
return null;
}
}
+218 -9
Переглянути файл
@@ -1,40 +1,131 @@
import { afterEach, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import * as actions from "@/platform/actions";
import { maybeEditorService, provideEditorService, type EditorService } from "@/workbench/contributions";
import * as client from "../api/client";
import type { GHRepository, GHUser } from "../api/types";
import { resetConnection, useGhRepository } from "../data/repository";
import * as api from "./api";
import { IssueEditor } from "./IssueEditor";
import { issueForBranch, issueInput, rememberIssueBranch } from "./input";
import { IssuesToolWindow } from "./IssuesToolWindow";
import { hasClosingReference, issueBranchName, issueForBranch, issueInput, rememberIssueBranch } from "./input";
const repo = { owner: "acme", name: "app", host: "code.example" };
const row = { title: "Fix editor focus", number: 7, state: "OPEN" as const };
const input = issueInput("code.example/acme/app", row);
function connectRepo() {
useGhRepository.setState({
availability: {
kind: "ready",
login: "me",
repo: {
nameWithOwner: "acme/app",
url: "https://code.example/acme/app",
defaultBranch: "main",
mergeCommitAllowed: true,
squashMergeAllowed: true,
rebaseMergeAllowed: true,
viewerPermission: "READ",
},
},
connection: {
coordinates: repo,
root: "/one",
repository: { viewerPermission: "READ", url: "https://code.example/acme/app" } as GHRepository,
currentUser: { login: "me" } as GHUser,
remotes: [],
},
});
}
afterEach(() => {
vi.restoreAllMocks();
resetConnection();
localStorage.clear();
});
it("keeps issue editors and branch associations scoped to the repository and checkout", () => {
const checkout = { ...repo, root: "/one" };
rememberIssueBranch(checkout, "custom-name", 7);
expect(issueForBranch(checkout, "custom-name")).toBe(7);
expect(issueForBranch({ owner: "ACME", name: "App", host: "CODE.EXAMPLE", root: "/one" }, "custom-name")).toBe(7);
expect(issueForBranch({ ...checkout, root: "/two" }, "custom-name")).toBeNull();
expect(issueForBranch({ ...checkout, host: "github.com" }, "custom-name")).toBeNull();
expect(input.key).not.toBe(issueInput("github.com/acme/app", row).key);
expect(input.key).toBe(issueInput("code.example/acme/app", { ...row, title: "Renamed" }).key);
});
it("keeps a failed comment draft and shows the confirmed comment after retry", async () => {
useGhRepository.setState({
connection: {
coordinates: repo,
root: "/one",
repository: { viewerPermission: "READ" } as GHRepository,
currentUser: { login: "me" } as GHUser,
remotes: [],
it("sanitizes issue titles into valid git branch names", () => {
expect(issueBranchName({ number: 7, title: "Fix .. @{ ~ ^ : ? * [ \\ / foo.lock", state: "OPEN" })).toBe(
"issue-7-fix-foo-lock",
);
expect(issueBranchName({ number: 8, title: " !!! 🚀🔥 ", state: "OPEN" })).toBe("issue-8");
expect(issueBranchName({ number: 9, title: "Re\u0301sume\u0301 cafe\u0301", state: "OPEN" })).toBe(
"issue-9-résumé-café",
);
const astral = "\u{1D400}".repeat(60);
const name = issueBranchName({ number: 10, title: astral, state: "OPEN" });
expect(name).toBe(`issue-10-${"\u{1D400}".repeat(48)}`);
});
it("detects closing references regardless of line endings, casing, or keyword", () => {
expect(hasClosingReference("Closes #7", 7)).toBe(true);
expect(hasClosingReference("Summary\r\nCloses #7\r\nMore", 7)).toBe(true);
expect(hasClosingReference("fixes #7.", 7)).toBe(true);
expect(hasClosingReference("(Resolves: #7)", 7)).toBe(true);
expect(hasClosingReference("Closes #70", 7)).toBe(false);
expect(hasClosingReference("See #7", 7)).toBe(false);
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 }),
);
await api.issueList(repo, "", "ALL", "me", "c1");
expect(gql).toHaveBeenLastCalledWith(
expect.stringContaining("filterBy:$filter"),
expect.objectContaining({ filter: { assignee: "me" }, states: null, cursor: "c1" }),
);
});
it("filters out pull requests on exact #number lookup and safely quotes search queries", async () => {
const gql = vi
.spyOn(client, "graphql")
.mockResolvedValueOnce({ repository: { issueOrPullRequest: { __typename: "PullRequest" } } })
.mockResolvedValueOnce({
search: {
nodes: [null, {}, row],
pageInfo: { hasNextPage: false, endCursor: null },
},
});
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(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(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,
});
});
it("keeps a failed comment draft and shows the confirmed comment after retry", async () => {
connectRepo();
const issue = {
...row,
id: "issue-id",
@@ -70,3 +161,121 @@ it("keeps a failed comment draft and shows the confirmed comment after retry", a
["issue-id", "Confirmed locally"],
]);
});
it("passes issue metadata when clicking Create Branch in an IssueEditor", async () => {
connectRepo();
const issue = {
...row,
title: "Updated issue title",
id: "issue-id",
body: "",
locked: false,
createdAt: "2026-08-01T00:00:00Z",
author: null,
url: "https://code.example/acme/app/issues/7",
labels: { nodes: [] },
assignees: { nodes: [] },
comments: {
nodes: [],
pageInfo: { hasNextPage: false, hasPreviousPage: false, startCursor: null, endCursor: null },
},
};
vi.spyOn(api, "issueDetails").mockResolvedValue({ items: [issue], next: null });
const exec = vi.spyOn(actions, "executeAction").mockResolvedValue(true);
render(<IssueEditor input={input} />);
const button = await screen.findByRole("button", { name: "Create Branch…" });
fireEvent.click(button);
expect(exec).toHaveBeenCalledWith("github.issue.createBranch", {
repository: "code.example/acme/app",
number: 7,
title: "Updated issue title",
state: "OPEN",
});
});
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 page2 = [
{ number: 8, title: "Third issue", state: "OPEN" as const },
{ number: 7, title: "Fourth issue", state: "OPEN" as const },
];
vi.spyOn(api, "issueList").mockImplementation(async (_r, term, _state, _assigned, cursor) => {
if (term === "#7") return { items: [row], next: null };
if (cursor === "c1") return { items: page2, next: null };
return { items: page1, next: "c1" };
});
render(<IssuesToolWindow />);
const loadMore = await screen.findByRole("button", { name: "Load more" });
fireEvent.click(loadMore);
await waitFor(() => expect(screen.queryByRole("button", { name: "Load more" })).toBeNull());
// 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.
const listbox = screen.getByRole("listbox", { name: "GitHub Issues" });
fireEvent.keyDown(listbox, { key: "ArrowDown" });
fireEvent.keyDown(listbox, { key: "ArrowDown" });
fireEvent.keyDown(listbox, { key: "ArrowDown" });
fireEvent.keyDown(listbox, { key: "Enter" });
expect(openInput).toHaveBeenLastCalledWith(
issueInput("code.example/acme/app", { number: 7, title: "Fourth issue", state: "OPEN" }),
{ focus: true },
);
// 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));
fireEvent.keyDown(listbox, { key: "Enter" });
expect(openInput).toHaveBeenLastCalledWith(issueInput("code.example/acme/app", row), { focus: true });
} finally {
provideEditorService(previousEditor);
}
});
it("ignores stale responses when changing filters mid-fetch", 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 });
return first;
});
render(<IssuesToolWindow />);
const mineBtn = await screen.findByRole("button", { name: "Assigned to me" });
fireEvent.click(mineBtn);
await waitFor(() => expect(api.issueList).toHaveBeenCalledWith(repo, "", "OPEN", "me", 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();
const openInput = vi.fn().mockResolvedValue(undefined);
const previousEditor = maybeEditorService();
provideEditorService({ openInput } as unknown as EditorService);
try {
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" }),
{ focus: true },
);
} finally {
provideEditorService(previousEditor);
}
});
+20 -4
Переглянути файл
@@ -7,7 +7,20 @@ interface Page<T> {
next: string | null;
}
function pagesFor<T>(fetchPage: (cursor: string | null) => Promise<Page<T>>) {
function mergeItems<T>(previous: T[], incoming: T[], keyOf?: (item: T) => string | number) {
if (!keyOf) return [...previous, ...incoming];
const seen = new Set(previous.map(keyOf));
const out = [...previous];
for (const item of incoming) {
const key = keyOf(item);
if (seen.has(key)) continue;
seen.add(key);
out.push(item);
}
return out;
}
function pagesFor<T>(fetchPage: (cursor: string | null) => Promise<Page<T>>, keyOf?: (item: T) => string | number) {
const store = createStore(() => ({
items: [] as T[],
next: null as string | null,
@@ -23,7 +36,7 @@ function pagesFor<T>(fetchPage: (cursor: string | null) => Promise<Page<T>>) {
const result = await fetchPage(cursor);
if (request === sequence)
store.setState((previous) => ({
items: cursor ? [...previous.items, ...result.items] : result.items,
items: cursor ? mergeItems(previous.items, result.items, keyOf) : mergeItems([], result.items, keyOf),
next: result.next,
loading: false,
}));
@@ -40,8 +53,11 @@ function pagesFor<T>(fetchPage: (cursor: string | null) => Promise<Page<T>>) {
};
}
export function usePages<T>(fetchPage: (cursor: string | null) => Promise<Page<T>>) {
const pages = useMemo(() => pagesFor(fetchPage), [fetchPage]);
export function usePages<T>(
fetchPage: (cursor: string | null) => Promise<Page<T>>,
keyOf?: (item: T) => string | number,
) {
const pages = useMemo(() => pagesFor(fetchPage, keyOf), [fetchPage, keyOf]);
const state = useStore(pages.store);
useEffect(() => {
void pages.load(null);