feat(gitlab): filter issues by milestone (#3278)

Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
Henry
2026-09-02 16:55:31 +00:00
committed by GitHub
parent c1161e0fbe
commit ffec4aade9
47 changed files with 3945 additions and 272 deletions
+9 -160
View File
@@ -11,20 +11,12 @@ import { fetchGitLabStatus } from "@/lib/api/domains/gitlab-api";
import type { GitLabStatus, Issue, MR } from "@/lib/types/gitlab";
import { MRList } from "@/components/gitlab/my-gitlab/mr-list";
import { IssueList } from "@/components/gitlab/my-gitlab/issue-list";
import {
PresetsSidebar,
type SidebarSelection,
} from "@/components/gitlab/my-gitlab/presets-sidebar";
import type { SidebarSelection } from "@/components/gitlab/my-gitlab/presets-sidebar";
import { PresetsSidebar } from "@/components/gitlab/my-gitlab/presets-sidebar";
import { PresetsScopeBar } from "@/components/gitlab/my-gitlab/presets-scope-bar";
import { MR_PRESETS, ISSUE_PRESETS, presetLabel } from "@/components/gitlab/my-gitlab/presets";
import { useGitLabSearch } from "@/components/gitlab/my-gitlab/use-gitlab-search";
import { useSavedPresets, type SavedPreset } from "@/components/gitlab/my-gitlab/use-saved-presets";
import {
useKnownProjects,
resetKnownProjectsStore,
} from "@/components/gitlab/my-gitlab/use-known-projects";
import { useCommittedQuery } from "@/components/gitlab/my-gitlab/use-committed-query";
import { resetKnownProjectsStore } from "@/components/gitlab/my-gitlab/use-known-projects";
import { ListToolbar } from "@/components/gitlab/my-gitlab/list-toolbar";
import { useGitLabPageState, type GitLabPageState } from "./use-gitlab-page-state";
import { ResultsPagination } from "@/components/gitlab/my-gitlab/results-pagination";
import { SavePresetDialog } from "@/components/gitlab/my-gitlab/save-preset-dialog";
import { useMRKeyToTasks } from "@/hooks/domains/gitlab/use-mr-key-to-tasks";
@@ -67,23 +59,6 @@ function NotConnectedNotice({ reconnect }: { reconnect?: boolean }) {
);
}
function resolveTitle(
selection: SidebarSelection,
saved: SavedPreset[],
t: (key: string, values?: Record<string, unknown>) => string,
): string {
if (selection.source === "saved") {
return saved.find((p) => p.id === selection.id)?.label ?? t("gitlab:savedQueryFallback");
}
const presets = selection.kind === "mr" ? MR_PRESETS : ISSUE_PRESETS;
return (
presetLabel(
t,
presets.find((p) => p.value === selection.id),
) ?? (selection.kind === "mr" ? t("gitlab:titleMergeRequests") : t("gitlab:titleIssues"))
);
}
function ResultsList({
selection,
items,
@@ -132,137 +107,6 @@ function ResultsList({
);
}
type GitLabPageState = ReturnType<typeof useGitLabPageState>;
function useProjectOptions(
selection: SidebarSelection,
committedQuery: string,
items: Array<MR | Issue>,
projectFilter: string,
): string[] {
const pageProjects = useMemo(
() => items.filter((it) => !!it.project_path).map((it) => it.project_path),
[items],
);
const resetKey = `${selection.kind}:${selection.source}:${selection.id}:${committedQuery.trim()}`;
const knownProjects = useKnownProjects(resetKey, pageProjects);
return useMemo(() => {
const set = new Set(knownProjects);
if (projectFilter) set.add(projectFilter);
return Array.from(set).sort();
}, [knownProjects, projectFilter]);
}
/** Lifted out of `useGitLabPageState`, which is at the 100-line function cap. */
function initialSelection(): SidebarSelection {
return { kind: "mr", source: "preset", id: MR_PRESETS[0]?.value ?? "" };
}
function useGitLabPageState(searchEnabled: boolean, workspaceId?: string) {
const { t } = useTranslation();
const [selection, setSelection] = useState<SidebarSelection>(initialSelection);
const {
draft: customQuery,
committed: committedQuery,
setDraft: setCustomQuery,
setImmediate: setQueryImmediate,
commit: commitCustomQuery,
} = useCommittedQuery("");
const [projectFilter, setProjectFilter] = useState("");
const [saveDialogOpen, setSaveDialogOpen] = useState(false);
const {
presets: savedPresets,
save: saveSavedPreset,
remove: removeSavedPreset,
} = useSavedPresets();
const presets = selection.kind === "mr" ? MR_PRESETS : ISSUE_PRESETS;
const search = useGitLabSearch({
workspaceId: workspaceId ?? "",
kind: selection.kind,
presets,
preset: selection.source === "preset" ? selection.id : "",
customQuery: committedQuery,
projectFilter,
enabled: searchEnabled && Boolean(workspaceId),
});
const projectOptions = useProjectOptions(
selection,
committedQuery,
search.rawItems,
projectFilter,
);
const title = useMemo(
() => resolveTitle(selection, savedPresets, t),
[selection, savedPresets, t],
);
const onSelect = useCallback(
(s: SidebarSelection) => {
setSelection(s);
if (s.source === "saved") {
const found = savedPresets.find((p) => p.id === s.id);
setQueryImmediate(found?.customQuery ?? "");
setProjectFilter(found?.projectFilter ?? "");
return;
}
setQueryImmediate("");
setProjectFilter("");
},
[savedPresets, setQueryImmediate],
);
// Use committedQuery (not the unflushed draft) so the saved preset always
// matches what is currently displayed in the list.
const canSaveCurrent = committedQuery.trim().length > 0 || projectFilter.length > 0;
// i18n-exempt: persisted as the saved query's name, so it must not depend on the creating locale.
const suggestedLabel =
committedQuery.trim() || (projectFilter ? `In ${projectFilter}` : "Saved query");
const onOpenSaveDialog = () => {
if (canSaveCurrent) setSaveDialogOpen(true);
};
const onConfirmSave = (label: string) => {
const created = saveSavedPreset({
kind: selection.kind,
label,
customQuery: committedQuery,
projectFilter,
});
setSelection({ kind: selection.kind, source: "saved", id: created.id });
};
const onDeleteSaved = (id: string) => {
removeSavedPreset(id);
if (selection.source === "saved" && selection.id === id) {
const fallbackPresets = selection.kind === "mr" ? MR_PRESETS : ISSUE_PRESETS;
setSelection({ kind: selection.kind, source: "preset", id: fallbackPresets[0]?.value ?? "" });
setQueryImmediate("");
setProjectFilter("");
}
};
return {
selection,
customQuery,
committedQuery,
setCustomQuery,
commitCustomQuery,
projectFilter,
setProjectFilter,
savedPresets,
search,
projectOptions,
title,
onSelect,
canSaveCurrent,
suggestedLabel,
saveDialogOpen,
setSaveDialogOpen,
onOpenSaveDialog,
onConfirmSave,
onDeleteSaved,
};
}
function AuthenticatedLayout({
workspaceId,
state,
@@ -311,6 +155,11 @@ function AuthenticatedLayout({
onProjectFilterChange={state.setProjectFilter}
projectOptions={projectOptions}
onRefresh={search.refresh}
showMilestoneFilter={state.showMilestoneFilter}
milestone={state.milestone}
committedMilestone={state.committedMilestone}
onMilestoneChange={state.setMilestone}
onCommitMilestone={state.onCommitMilestone}
/>
<div className="flex-1 overflow-auto px-6 py-4">
<ResultsList
@@ -0,0 +1,424 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
import type { Issue, IssueSearchPage } from "@/lib/types/gitlab";
import { ISSUE_PRESETS, MR_PRESETS } from "@/components/gitlab/my-gitlab/presets";
import {
__resetSnapshotForTests,
type SavedPreset,
} from "@/components/gitlab/my-gitlab/use-saved-presets";
import { resetKnownProjectsStore } from "@/components/gitlab/my-gitlab/use-known-projects";
import type { SidebarSelection } from "@/components/gitlab/my-gitlab/presets-sidebar";
const searchUserMRsMock = vi.fn<(input: unknown) => Promise<unknown>>();
const searchUserIssuesMock = vi.fn<(input: unknown) => Promise<IssueSearchPage | null>>();
vi.mock("@/lib/api/domains/gitlab-api", () => ({
searchUserMRs: (args: unknown) => searchUserMRsMock(args),
searchUserIssues: (args: unknown) => searchUserIssuesMock(args),
}));
const fetchUserSettingsMock = vi.fn();
const updateUserSettingsMock = vi.fn();
vi.mock("@/lib/api/domains/settings-api", () => ({
fetchUserSettings: (...args: unknown[]) => fetchUserSettingsMock(...args),
updateUserSettings: (...args: unknown[]) => updateUserSettingsMock(...args),
}));
import {
buildProjectOptionsResetKey,
trimGitLabMilestone,
useGitLabPageState,
useProjectOptions,
} from "./use-gitlab-page-state";
afterEach(() => cleanup());
const WORKSPACE_ID = "ws-1";
const CREATED_AT = "2026-01-01T00:00:00Z";
function fakeIssue(overrides: Partial<Issue> = {}): Issue {
return {
id: 1,
iid: 1,
project_id: 1,
title: "",
body: "",
url: "",
web_url: "",
state: "opened",
author_username: "alice",
project_namespace: "acme",
project_path: "acme/api",
labels: [],
assignees: [],
milestone: "",
created_at: "",
updated_at: "",
...overrides,
};
}
function issuePage(items: Issue[]): IssueSearchPage {
return { issues: items, total_count: items.length, page: 1, per_page: 25 };
}
beforeEach(() => {
vi.clearAllMocks();
resetKnownProjectsStore();
__resetSnapshotForTests();
fetchUserSettingsMock.mockResolvedValue({ settings: { gitlab_saved_presets: [] } });
updateUserSettingsMock.mockResolvedValue({ settings: {} });
searchUserMRsMock.mockResolvedValue({ mrs: [], total_count: 0, page: 1, per_page: 25 });
searchUserIssuesMock.mockResolvedValue(issuePage([]));
});
describe("trimGitLabMilestone", () => {
it("trims ordinary leading/trailing whitespace", () => {
expect(trimGitLabMilestone(" v1.0 ")).toBe("v1.0");
});
it("trims a leading BOM (\uFEFF) and a trailing NBSP (\u00A0)", () => {
expect(trimGitLabMilestone("\uFEFFv1.0\u00A0")).toBe("v1.0");
});
it("trims a trailing NEL (\u0085), which the bare \\s regex class omits", () => {
expect(trimGitLabMilestone("v1.0\u0085")).toBe("v1.0");
});
it("preserves internal whitespace", () => {
expect(trimGitLabMilestone(" Sprint 42 ")).toBe("Sprint 42");
});
it("returns empty for a whitespace-only value including a NEL", () => {
expect(trimGitLabMilestone(" \u0085 ")).toBe("");
});
// Mirrors the Go side's TestTrimGitLabWhitespace_MatchesNormativeSet
// (client_helpers_milestone_test.go) code point for code point: the
// normative set is Unicode White_Space together with U+FEFF, on BOTH
// sides, and the two languages' own defaults disagree with it and with
// each other in both directions (Scenario 27). Asserting only a handful
// of ad-hoc cases on one side does not establish the cross-language
// agreement the spec requires.
it("matches the normative set for every code point in the Go-side conformance table", () => {
const trimmed = [
0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x0020, 0x0085, 0x00a0, 0x1680, 0x2000, 0x2028,
0x2029, 0x202f, 0x205f, 0x3000, 0xfeff,
];
for (const cp of trimmed) {
expect(trimGitLabMilestone(String.fromCodePoint(cp))).toBe("");
}
// Preserved: not part of Unicode White_Space or U+FEFF.
const preserved = [0x200b, 0x180e, 0x2060, 0x00b7];
for (const cp of preserved) {
const ch = String.fromCodePoint(cp);
expect(trimGitLabMilestone(ch)).toBe(ch);
}
});
});
describe("buildProjectOptionsResetKey", () => {
it("keeps delimiter-containing query and milestone values distinct", () => {
const selection: SidebarSelection = { kind: "issue", source: "preset", id: "assigned" };
const queryWithDelimiter = buildProjectOptionsResetKey(selection, "labels=backend:v1", "Q2");
const milestoneWithDelimiter = buildProjectOptionsResetKey(
selection,
"labels=backend",
"v1:Q2",
);
expect(queryWithDelimiter).not.toBe(milestoneWithDelimiter);
});
});
describe("useProjectOptions — ordinary pagination (key unchanged)", () => {
beforeEach(() => resetKnownProjectsStore());
const SELECTION: SidebarSelection = { kind: "issue", source: "preset", id: "assigned" };
it("keeps projects seen on an earlier page while a same-key page turn is loading", () => {
const items = [fakeIssue({ project_path: "acme/api" })];
const { result, rerender } = renderHook(
(props: { loading: boolean; items: Issue[] }) =>
useProjectOptions({
selection: SELECTION,
committedQuery: "",
milestone: "",
items: props.items,
loading: props.loading,
projectFilter: "",
}),
{ initialProps: { loading: false, items } },
);
expect(result.current).toEqual(["acme/api"]);
// Page 2 is loading: same key, so the accumulator must not clear.
rerender({ loading: true, items: [] });
expect(result.current).toEqual(["acme/api"]);
// Page 2 resolves with a different project; it accumulates on top.
rerender({ loading: false, items: [fakeIssue({ project_path: "acme/web" })] });
expect(result.current).toEqual(["acme/api", "acme/web"]);
});
});
describe("useGitLabPageState", () => {
it("does not leak the previous milestone's projects into the dropdown while the new milestone's fetch is in flight (Scenario 29)", async () => {
searchUserIssuesMock.mockResolvedValueOnce(
issuePage([fakeIssue({ project_path: "acme/api" })]),
);
let resolveNext: (v: IssueSearchPage) => void = () => {};
searchUserIssuesMock.mockReturnValueOnce(
new Promise<IssueSearchPage>((res) => {
resolveNext = res;
}),
);
const { result } = renderHook(() => useGitLabPageState(true, WORKSPACE_ID));
act(() => result.current.onSelect({ kind: "issue", source: "preset", id: "assigned" }));
await waitFor(() => expect(result.current.projectOptions).toEqual(["acme/api"]));
act(() => result.current.setMilestone("Next"));
act(() => result.current.onCommitMilestone());
// The new milestone's fetch is in flight; the previous milestone's
// project must not still be offered.
expect(result.current.projectOptions).toEqual([]);
await act(async () => {
resolveNext(issuePage([fakeIssue({ project_path: "acme/web" })]));
await Promise.resolve();
});
await waitFor(() => expect(result.current.projectOptions).toEqual(["acme/web"]));
expect(result.current.projectOptions).not.toContain("acme/api");
});
it("clears the milestone draft and committed value when the selection changes, including switching to the MR view", async () => {
const { result } = renderHook(() => useGitLabPageState(true, WORKSPACE_ID));
act(() => result.current.onSelect({ kind: "issue", source: "preset", id: "assigned" }));
act(() => result.current.setMilestone("Next"));
act(() => result.current.onCommitMilestone());
await waitFor(() => expect(result.current.committedMilestone).toBe("Next"));
act(() => result.current.onSelect({ kind: "mr", source: "preset", id: MR_PRESETS[0].value }));
expect(result.current.milestone).toBe("");
expect(result.current.committedMilestone).toBe("");
expect(result.current.showMilestoneFilter).toBe(false);
});
it("onCommitMilestone normalizes the visible input via the trim helper, resets to page 1, and issues exactly one request (Scenario 7)", async () => {
searchUserIssuesMock.mockResolvedValue(issuePage([]));
const { result } = renderHook(() => useGitLabPageState(true, WORKSPACE_ID));
act(() => result.current.onSelect({ kind: "issue", source: "preset", id: "assigned" }));
await waitFor(() => expect(result.current.search.loading).toBe(false));
act(() => result.current.search.setPage(3));
await waitFor(() => expect(result.current.search.page).toBe(3));
const callsBeforeCommit = searchUserIssuesMock.mock.calls.length;
act(() => result.current.setMilestone(" Next "));
act(() => result.current.onCommitMilestone());
expect(result.current.milestone).toBe("Next");
expect(result.current.committedMilestone).toBe("Next");
await waitFor(() => expect(result.current.search.page).toBe(1));
// Committing and resetting the page together must fire exactly one
// request for the new value — adding milestone to the existing
// [preset, customQuery, kind] reset effect would instead fire twice
// (once for the stale page, once for page 1); see spec "Client
// function, and where trimming happens".
await waitFor(() => expect(searchUserIssuesMock).toHaveBeenCalledTimes(callsBeforeCommit + 1));
const lastCall = searchUserIssuesMock.mock.calls.at(-1)?.[0] as {
page: number;
milestone?: string;
};
expect(lastCall.page).toBe(1);
expect(lastCall.milestone).toBe("Next");
});
it("resets to page 1 when selecting a sidebar preset clears a committed milestone (Scenario 6, clause 3)", async () => {
searchUserIssuesMock.mockResolvedValue(issuePage([]));
const { result } = renderHook(() => useGitLabPageState(true, WORKSPACE_ID));
act(() => result.current.onSelect({ kind: "issue", source: "preset", id: "assigned" }));
act(() => result.current.setMilestone("Next"));
act(() => result.current.onCommitMilestone());
await waitFor(() => expect(result.current.committedMilestone).toBe("Next"));
act(() => result.current.search.setPage(3));
await waitFor(() => expect(result.current.search.page).toBe(3));
// Re-select the SAME preset: effectivePreset/customQuery/kind are all
// unchanged, so useGitLabSearch's `[preset, customQuery, kind]` reset
// effect will not fire on its own — only the milestone clears.
act(() => result.current.onSelect({ kind: "issue", source: "preset", id: "assigned" }));
expect(result.current.committedMilestone).toBe("");
await waitFor(() => expect(result.current.search.page).toBe(1));
});
});
describe("useGitLabPageState — saved query save", () => {
it("canSaveCurrent and suggestedLabel consider the milestone alongside the query and project filter", async () => {
const { result } = renderHook(() => useGitLabPageState(true, WORKSPACE_ID));
act(() => result.current.onSelect({ kind: "issue", source: "preset", id: "assigned" }));
expect(result.current.canSaveCurrent).toBe(false);
act(() => result.current.setMilestone("Next"));
act(() => result.current.onCommitMilestone());
expect(result.current.canSaveCurrent).toBe(true);
expect(result.current.suggestedLabel).toBe("Next");
});
it("suggestedLabel precedence ladder: custom query beats project filter beats milestone beats the default (Scenario 25)", async () => {
const { result } = renderHook(() => useGitLabPageState(true, WORKSPACE_ID));
act(() => result.current.onSelect({ kind: "issue", source: "preset", id: "assigned" }));
expect(result.current.suggestedLabel).toBe("Saved query");
act(() => result.current.setMilestone("Next"));
act(() => result.current.onCommitMilestone());
expect(result.current.suggestedLabel).toBe("Next");
act(() => result.current.setProjectFilter("group/app"));
expect(result.current.suggestedLabel).toBe("In group/app");
act(() => result.current.setCustomQuery("state=closed"));
act(() => result.current.commitCustomQuery());
await waitFor(() => expect(result.current.committedQuery).toBe("state=closed"));
expect(result.current.suggestedLabel).toBe("state=closed");
});
it("onConfirmSave writes the committed (trimmed) milestone and the effective preset, never the raw draft", async () => {
const { result } = renderHook(() => useGitLabPageState(true, WORKSPACE_ID));
act(() => result.current.onSelect({ kind: "issue", source: "preset", id: "assigned" }));
act(() => result.current.setMilestone(" Next "));
act(() => result.current.onCommitMilestone());
await waitFor(() => expect(result.current.committedMilestone).toBe("Next"));
await act(async () => {
result.current.onConfirmSave("My saved query");
await Promise.resolve();
});
await waitFor(() => expect(updateUserSettingsMock).toHaveBeenCalled());
const payload = updateUserSettingsMock.mock.calls.at(-1)?.[0] as {
gitlab_saved_presets: SavedPreset[];
};
const saved = payload.gitlab_saved_presets.at(-1);
expect(saved?.label).toBe("My saved query");
expect(saved?.milestone).toBe("Next");
expect(saved?.preset).toBe("assigned");
expect(saved?.customQuery).toBe("");
});
});
describe("useGitLabPageState — saved query restore", () => {
it("restores both the milestone and the effective preset (including a preset-only query with no custom text) when the saved query is selected", async () => {
const created: SavedPreset = {
id: "g_1",
kind: "issue",
label: "Next sprint",
customQuery: "",
projectFilter: "",
milestone: "Next",
preset: "assigned",
createdAt: CREATED_AT,
};
fetchUserSettingsMock.mockResolvedValue({ settings: { gitlab_saved_presets: [created] } });
searchUserIssuesMock.mockResolvedValue(issuePage([fakeIssue({ project_path: "acme/api" })]));
const { result } = renderHook(() => useGitLabPageState(true, WORKSPACE_ID));
await waitFor(() => expect(result.current.savedPresets).toHaveLength(1));
act(() => result.current.onSelect({ kind: "issue", source: "saved", id: "g_1" }));
expect(result.current.committedMilestone).toBe("Next");
expect(result.current.committedQuery).toBe("");
// Preset-only saved query with no custom query text: the original
// preset filter (persisted as `preset`) must still drive the fetch.
await waitFor(() => expect(searchUserIssuesMock).toHaveBeenCalled());
const lastCall = searchUserIssuesMock.mock.calls.at(-1)?.[0] as Record<string, unknown>;
expect(lastCall.filter).toBe("assigned_to_me");
});
it("resets to page 1 when selecting a saved query that differs from the current state only in its milestone (Scenario 6, clause 2)", async () => {
const created: SavedPreset = {
id: "g_1",
kind: "issue",
label: "Next sprint",
customQuery: "",
projectFilter: "",
milestone: "Next",
preset: "assigned",
createdAt: CREATED_AT,
};
fetchUserSettingsMock.mockResolvedValue({ settings: { gitlab_saved_presets: [created] } });
const { result } = renderHook(() => useGitLabPageState(true, WORKSPACE_ID));
await waitFor(() => expect(result.current.savedPresets).toHaveLength(1));
// Same effective preset ("assigned"), same empty custom query, same kind
// as the saved query below — only the milestone will differ, so the
// `[preset, customQuery, kind]` reset effect in useGitLabSearch will not
// fire on its own.
act(() => result.current.onSelect({ kind: "issue", source: "preset", id: "assigned" }));
await waitFor(() => expect(result.current.search.loading).toBe(false));
act(() => result.current.search.setPage(3));
await waitFor(() => expect(result.current.search.page).toBe(3));
act(() => result.current.onSelect({ kind: "issue", source: "saved", id: "g_1" }));
expect(result.current.committedMilestone).toBe("Next");
await waitFor(() => expect(result.current.search.page).toBe(1));
});
});
describe("useGitLabPageState — saved query delete", () => {
it("clears milestone and resets to page 1 only when the deleted saved query was the active selection", async () => {
const other: SavedPreset = {
id: "g_other",
kind: "issue",
label: "Other",
customQuery: "labels=bug",
projectFilter: "",
milestone: "",
preset: "",
createdAt: CREATED_AT,
};
const selected: SavedPreset = {
id: "g_selected",
kind: "issue",
label: "Selected",
customQuery: "",
projectFilter: "",
milestone: "Next",
preset: "assigned",
createdAt: CREATED_AT,
};
fetchUserSettingsMock.mockResolvedValue({
settings: { gitlab_saved_presets: [other, selected] },
});
const { result } = renderHook(() => useGitLabPageState(true, WORKSPACE_ID));
await waitFor(() => expect(result.current.savedPresets).toHaveLength(2));
act(() => result.current.onSelect({ kind: "issue", source: "saved", id: "g_selected" }));
await waitFor(() => expect(result.current.committedMilestone).toBe("Next"));
act(() => result.current.search.setPage(2));
await waitFor(() => expect(result.current.search.page).toBe(2));
// Deleting an unrelated saved query leaves the active scope untouched.
act(() => result.current.onDeleteSaved("g_other"));
expect(result.current.committedMilestone).toBe("Next");
expect(result.current.search.page).toBe(2);
// Deleting the currently-selected saved query clears the scope and
// resets the page in the same batch.
act(() => result.current.onDeleteSaved("g_selected"));
expect(result.current.committedMilestone).toBe("");
await waitFor(() => expect(result.current.search.page).toBe(1));
expect(result.current.selection).toEqual({
kind: "issue",
source: "preset",
id: ISSUE_PRESETS[0]?.value ?? "",
});
});
});
@@ -0,0 +1,421 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import type { Issue, MR } from "@/lib/types/gitlab";
import type { SidebarSelection } from "@/components/gitlab/my-gitlab/presets-sidebar";
import { MR_PRESETS, ISSUE_PRESETS, presetLabel } from "@/components/gitlab/my-gitlab/presets";
import { useGitLabSearch } from "@/components/gitlab/my-gitlab/use-gitlab-search";
import { useSavedPresets, type SavedPreset } from "@/components/gitlab/my-gitlab/use-saved-presets";
import { useKnownProjects } from "@/components/gitlab/my-gitlab/use-known-projects";
import { useCommittedQuery } from "@/components/gitlab/my-gitlab/use-committed-query";
// Normative trim set for the milestone filter: Unicode White_Space plus
// U+0085 (NEL), which JS's built-in String.prototype.trim() and the bare \s
// regex class both omit. Mirrors the backend's trimGitLabWhitespace. Every
// commit site for the milestone draft must go through this helper, never
// String.prototype.trim() directly.
export function trimGitLabMilestone(value: string): string {
return value.replace(/^[\s\u0085]+|[\s\u0085]+$/gu, "");
}
function resolveTitle(
selection: SidebarSelection,
saved: SavedPreset[],
t: (key: string, values?: Record<string, unknown>) => string,
): string {
if (selection.source === "saved") {
return saved.find((p) => p.id === selection.id)?.label ?? t("gitlab:savedQueryFallback");
}
const presets = selection.kind === "mr" ? MR_PRESETS : ISSUE_PRESETS;
return (
presetLabel(
t,
presets.find((p) => p.value === selection.id),
) ?? (selection.kind === "mr" ? t("gitlab:titleMergeRequests") : t("gitlab:titleIssues"))
);
}
const EMPTY_PROJECTS: string[] = [];
export type UseProjectOptionsArgs = {
selection: SidebarSelection;
committedQuery: string;
milestone: string;
items: Array<MR | Issue>;
loading: boolean;
projectFilter: string;
};
/** Encode every reset-key component as a JSON tuple so user values cannot collide. */
export function buildProjectOptionsResetKey(
selection: SidebarSelection,
committedQuery: string,
milestone: string,
): string {
return JSON.stringify([
selection.kind,
selection.source,
selection.id,
committedQuery.trim(),
milestone,
]);
}
export function useProjectOptions({
selection,
committedQuery,
milestone,
items,
loading,
projectFilter,
}: UseProjectOptionsArgs): string[] {
const resetKey = buildProjectOptionsResetKey(selection, committedQuery, milestone);
// `useKnownProjects`'s accumulator clears the instant `resetKey` changes and
// immediately refills with whatever project list it is handed in that same
// effect call. On the render where a key change first lands, `items` (from
// useGitLabSearch) still holds the *previous* key's results, and `loading`
// still reads false, because the fetch for the new key is dispatched from
// an effect that has not run yet (state.loading only flips inside
// fetchData, which runs from an effect). `committedKey` mirrors `resetKey`
// one render late via an ordinary effect, so on that first render
// `committedKey !== resetKey` forces the page list empty regardless of
// what `loading` happens to read at that instant; by the time
// `committedKey` catches up, the fetch has been dispatched and `loading`
// governs the empty state correctly for the rest of the request.
const [committedKey, setCommittedKey] = useState(resetKey);
useEffect(() => {
setCommittedKey(resetKey);
}, [resetKey]);
const pageProjects = useMemo(() => {
if (loading || committedKey !== resetKey) return EMPTY_PROJECTS;
return items.filter((it) => !!it.project_path).map((it) => it.project_path);
}, [loading, committedKey, resetKey, items]);
const knownProjects = useKnownProjects(resetKey, pageProjects);
return useMemo(() => {
const set = new Set(knownProjects);
if (projectFilter) set.add(projectFilter);
return Array.from(set).sort();
}, [knownProjects, projectFilter]);
}
/** Lifted out of `useGitLabPageState`, which is at the 100-line function cap. */
export function initialSelection(): SidebarSelection {
return { kind: "mr", source: "preset", id: MR_PRESETS[0]?.value ?? "" };
}
type SaveQueryDialogArgs = {
selection: SidebarSelection;
setSelection: (s: SidebarSelection) => void;
committedQuery: string;
projectFilter: string;
committedMilestone: string;
effectivePreset: string;
saveSavedPreset: ReturnType<typeof useSavedPresets>["save"];
removeSavedPreset: ReturnType<typeof useSavedPresets>["remove"];
clearScope: () => void;
resetPage: () => void;
};
/** Lifted out of `useGitLabPageState`, which is at the 100-line function cap. */
function useSaveQueryDialog({
selection,
setSelection,
committedQuery,
projectFilter,
committedMilestone,
effectivePreset,
saveSavedPreset,
removeSavedPreset,
clearScope,
resetPage,
}: SaveQueryDialogArgs) {
const [saveDialogOpen, setSaveDialogOpen] = useState(false);
// Use committed values (not unflushed drafts) so the saved preset always
// matches what is currently displayed in the list.
const canSaveCurrent =
committedQuery.trim().length > 0 || projectFilter.length > 0 || committedMilestone.length > 0;
// i18n-exempt: persisted as the saved query's name, so it must not depend on the creating locale.
const suggestedLabel =
committedQuery.trim() ||
(projectFilter ? `In ${projectFilter}` : "") ||
committedMilestone ||
"Saved query";
const onOpenSaveDialog = useCallback(() => {
if (canSaveCurrent) setSaveDialogOpen(true);
}, [canSaveCurrent]);
const onConfirmSave = useCallback(
(label: string) => {
const created = saveSavedPreset({
kind: selection.kind,
label,
customQuery: committedQuery,
projectFilter,
milestone: committedMilestone,
preset: effectivePreset,
});
setSelection({ kind: selection.kind, source: "saved", id: created.id });
},
[
selection.kind,
committedQuery,
projectFilter,
committedMilestone,
effectivePreset,
saveSavedPreset,
setSelection,
],
);
const onDeleteSaved = useCallback(
(id: string) => {
removeSavedPreset(id);
if (selection.source === "saved" && selection.id === id) {
const fallbackPresets = selection.kind === "mr" ? MR_PRESETS : ISSUE_PRESETS;
setSelection({
kind: selection.kind,
source: "preset",
id: fallbackPresets[0]?.value ?? "",
});
clearScope();
resetPage();
}
},
[removeSavedPreset, selection, setSelection, clearScope, resetPage],
);
return {
saveDialogOpen,
setSaveDialogOpen,
canSaveCurrent,
suggestedLabel,
onOpenSaveDialog,
onConfirmSave,
onDeleteSaved,
};
}
type ScopeActionsArgs = {
savedPresets: SavedPreset[];
setSelection: (s: SidebarSelection) => void;
setQueryImmediate: (v: string) => void;
setProjectFilter: (v: string) => void;
setMilestoneImmediate: (v: string) => void;
milestone: string;
setPage: (p: number) => void;
};
/** Lifted out of `useGitLabPageState`, which is at the 100-line function cap. */
function useScopeActions({
savedPresets,
setSelection,
setQueryImmediate,
setProjectFilter,
setMilestoneImmediate,
milestone,
setPage,
}: ScopeActionsArgs) {
const onSelect = useCallback(
(s: SidebarSelection) => {
setSelection(s);
if (s.source === "saved") {
const found = savedPresets.find((p) => p.id === s.id);
setQueryImmediate(found?.customQuery ?? "");
setProjectFilter(found?.projectFilter ?? "");
setMilestoneImmediate(found?.milestone ?? "");
setPage(1);
return;
}
setQueryImmediate("");
setProjectFilter("");
setMilestoneImmediate("");
setPage(1);
},
[
savedPresets,
setSelection,
setQueryImmediate,
setProjectFilter,
setMilestoneImmediate,
setPage,
],
);
// Every path that changes the committed milestone calls setPage(1) from
// inside the same event handler (commit, select, delete), so a stale later
// page is never left showing results for a filter that no longer applies —
// a saved query or sidebar preset can differ from the current state only
// in its milestone, in which case useGitLabSearch's own
// `[preset, customQuery, kind]` reset effect would not otherwise fire.
const onCommitMilestone = useCallback(() => {
setMilestoneImmediate(trimGitLabMilestone(milestone));
setPage(1);
}, [milestone, setMilestoneImmediate, setPage]);
const clearScope = useCallback(() => {
setQueryImmediate("");
setProjectFilter("");
setMilestoneImmediate("");
}, [setQueryImmediate, setProjectFilter, setMilestoneImmediate]);
const resetPage = useCallback(() => setPage(1), [setPage]);
return { onSelect, onCommitMilestone, clearScope, resetPage };
}
type SearchAndProjectsArgs = {
searchEnabled: boolean;
workspaceId?: string;
selection: SidebarSelection;
committedQuery: string;
committedMilestone: string;
projectFilter: string;
savedPresets: SavedPreset[];
t: (key: string, values?: Record<string, unknown>) => string;
};
/** Lifted out of `useGitLabPageState`, which is at the 100-line function cap. */
function useSearchAndProjects({
searchEnabled,
workspaceId,
selection,
committedQuery,
committedMilestone,
projectFilter,
savedPresets,
t,
}: SearchAndProjectsArgs) {
const presets = selection.kind === "mr" ? MR_PRESETS : ISSUE_PRESETS;
// A saved query with no custom query text still needs the preset filter it
// was saved under, or restoring it would silently widen to "no filter".
const effectivePreset = useMemo(() => {
if (selection.source === "preset") return selection.id;
return savedPresets.find((p) => p.id === selection.id)?.preset ?? "";
}, [selection, savedPresets]);
const search = useGitLabSearch({
workspaceId: workspaceId ?? "",
kind: selection.kind,
presets,
preset: effectivePreset,
customQuery: committedQuery,
milestone: committedMilestone,
projectFilter,
enabled: searchEnabled && Boolean(workspaceId),
});
const projectOptions = useProjectOptions({
selection,
committedQuery,
milestone: committedMilestone,
items: search.rawItems,
loading: search.loading,
projectFilter,
});
const title = useMemo(
() => resolveTitle(selection, savedPresets, t),
[selection, savedPresets, t],
);
return { search, projectOptions, title, effectivePreset };
}
export function useGitLabPageState(searchEnabled: boolean, workspaceId?: string) {
const { t } = useTranslation();
const [selection, setSelection] = useState<SidebarSelection>(initialSelection);
const {
draft: customQuery,
committed: committedQuery,
setDraft: setCustomQuery,
setImmediate: setQueryImmediate,
commit: commitCustomQuery,
} = useCommittedQuery("");
const {
draft: milestone,
committed: committedMilestone,
setDraft: setMilestone,
setImmediate: setMilestoneImmediate,
} = useCommittedQuery("");
const [projectFilter, setProjectFilter] = useState("");
const {
presets: savedPresets,
save: saveSavedPreset,
remove: removeSavedPreset,
} = useSavedPresets();
const { search, projectOptions, title, effectivePreset } = useSearchAndProjects({
searchEnabled,
workspaceId,
selection,
committedQuery,
committedMilestone,
projectFilter,
savedPresets,
t,
});
const { onSelect, onCommitMilestone, clearScope, resetPage } = useScopeActions({
savedPresets,
setSelection,
setQueryImmediate,
setProjectFilter,
setMilestoneImmediate,
milestone,
setPage: search.setPage,
});
const {
saveDialogOpen,
setSaveDialogOpen,
canSaveCurrent,
suggestedLabel,
onOpenSaveDialog,
onConfirmSave,
onDeleteSaved,
} = useSaveQueryDialog({
selection,
setSelection,
committedQuery,
projectFilter,
committedMilestone,
effectivePreset,
saveSavedPreset,
removeSavedPreset,
clearScope,
resetPage,
});
return {
selection,
customQuery,
committedQuery,
setCustomQuery,
commitCustomQuery,
milestone,
committedMilestone,
setMilestone,
onCommitMilestone,
showMilestoneFilter: selection.kind === "issue",
projectFilter,
setProjectFilter,
savedPresets,
search,
projectOptions,
title,
onSelect,
canSaveCurrent,
suggestedLabel,
saveDialogOpen,
setSaveDialogOpen,
onOpenSaveDialog,
onConfirmSave,
onDeleteSaved,
};
}
export type GitLabPageState = ReturnType<typeof useGitLabPageState>;