From 8c03f7a8ef3d42c95e007bb958b9863774add063 Mon Sep 17 00:00:00 2001 From: Jake Leventhal Date: Thu, 15 Oct 2026 12:29:18 -0400 Subject: [PATCH] feat(prs): save named filter views across clients --- .../pull-requests/PullRequestListFilters.tsx | 4 +- .../PullRequestSavedViewsMenu.tsx | 122 +++++++++ .../pull-requests/PullRequestsScreen.tsx | 23 ++ .../pullRequestSavedViews.test.ts | 51 ++++ .../pull-requests/pullRequestSavedViews.ts | 44 ++++ .../usePullRequestListControls.ts | 33 ++- apps/mobile/src/lib/storage.test.ts | 67 +++++ .../src/persistence/mobile-preferences.ts | 15 ++ .../PullRequestSavedViewsMenu.test.tsx | 158 +++++++++++ .../pullRequest/PullRequestSavedViewsMenu.tsx | 249 ++++++++++++++++++ .../pullRequest/pullRequestListPreferences.ts | 2 +- .../pullRequest/pullRequestSavedViews.test.ts | 107 ++++++++ .../pullRequest/pullRequestSavedViews.ts | 54 ++++ apps/web/src/routes/_chat.pull-requests.tsx | 11 + docs/user/source-control.md | 6 + packages/client-runtime/package.json | 4 + .../src/pullRequestSavedViews.ts | 28 ++ 17 files changed, 975 insertions(+), 3 deletions(-) create mode 100644 apps/mobile/src/features/pull-requests/PullRequestSavedViewsMenu.tsx create mode 100644 apps/mobile/src/features/pull-requests/pullRequestSavedViews.test.ts create mode 100644 apps/mobile/src/features/pull-requests/pullRequestSavedViews.ts create mode 100644 apps/web/src/components/pullRequest/PullRequestSavedViewsMenu.test.tsx create mode 100644 apps/web/src/components/pullRequest/PullRequestSavedViewsMenu.tsx create mode 100644 apps/web/src/components/pullRequest/pullRequestSavedViews.test.ts create mode 100644 apps/web/src/components/pullRequest/pullRequestSavedViews.ts create mode 100644 packages/client-runtime/src/pullRequestSavedViews.ts diff --git a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx index 24296142593dc..ec1dee477d762 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx @@ -1,5 +1,5 @@ import { sortProjectsByGroupOrder } from "@t3tools/client-runtime/state/project-grouping"; -import { useMemo } from "react"; +import { useMemo, type ReactNode } from "react"; import { ScrollView } from "react-native"; import type { ControlPillMenuProps } from "../../components/ControlPillMenu.types"; import { ListFilterMenu } from "../workspace/ListFilterMenu"; @@ -66,6 +66,7 @@ export function PullRequestListFilters(props: { readonly authors: readonly string[]; readonly labels: readonly string[]; readonly projects: readonly { id: string; title: string; environmentId: string }[]; + readonly savedViewsMenu: ReactNode; }) { const { value } = props; const projects = useProjectsInSidebarOrder(props.projects); @@ -228,6 +229,7 @@ export function PullRequestListFilters(props: { showsHorizontalScrollIndicator={false} contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 2, paddingBottom: 10, gap: 8 }} > + {props.savedViewsMenu} void; +}) { + const { views, ready, update } = usePullRequestSavedViews(); + const [selectedId, setSelectedId] = useState(null); + const [busy, setBusy] = useState(false); + const explicitlySelected = views.find((view) => view.id === selectedId); + const matchingView = + explicitlySelected && pullRequestViewMatches(explicitlySelected, scope) + ? explicitlySelected + : views.find((view) => pullRequestViewMatches(view, scope)); + const selectedView = matchingView ?? explicitlySelected; + const modified = selectedView !== undefined && !pullRequestViewMatches(selectedView, scope); + + async function persist( + transform: ( + current: ReadonlyArray, + ) => ReadonlyArray, + ) { + setBusy(true); + try { + await update(transform); + return true; + } catch { + Alert.alert("Could not save PR views", "The device could not save your views. Try again."); + return false; + } finally { + setBusy(false); + } + } + + function editName(view?: PullRequestSavedView) { + showTextInputDialog({ + title: view ? "Rename PR view" : "Save PR view", + initialValue: + view?.name ?? + (scope.controls.involvement === "reviewing" ? "PRs Requesting My Review" : ""), + confirmText: "Save", + onConfirm: (value) => { + const error = pullRequestViewNameError(value, views, view?.id); + if (error) { + Alert.alert("Could not save view", error); + return; + } + const id = view?.id ?? uuidv4(); + const name = value.trim(); + void persist((current) => + view + ? current.map((item) => (item.id === view.id ? { ...item, name } : item)) + : [...current, { ...scope, id, name }], + ).then((saved) => { + if (saved) setSelectedId(id); + }); + }, + }); + } + + const actions: ControlPillMenuProps["actions"] = [ + ...views.map((view) => ({ + id: `apply:${view.id}`, + title: view.name, + state: matchingView?.id === view.id ? ("on" as const) : ("off" as const), + })), + { id: "save", title: "Save current view…" }, + ...(selectedView + ? [ + ...(modified ? [{ id: "update", title: "Update saved view" }] : []), + { id: "rename", title: "Rename view…" }, + { id: "delete", title: "Delete view", attributes: { destructive: true } }, + ] + : []), + ]; + + return ( + ({ + ...action, + attributes: { ...action.attributes, disabled: !ready || busy }, + }))} + onSelect={(id) => { + if (!ready || busy) return; + const view = views.find((item) => `apply:${item.id}` === id); + if (view) { + setSelectedId(view.id); + onApply(view); + return; + } + if (id === "save") editName(); + else if (id === "rename" && selectedView) editName(selectedView); + else if (id === "update" && selectedView) + void persist((current) => + current.map((item) => (item.id === selectedView.id ? { ...item, ...scope } : item)), + ); + else if (id === "delete" && selectedView) + void persist((current) => current.filter((item) => item.id !== selectedView.id)).then( + (saved) => { + if (saved) setSelectedId(null); + }, + ); + }} + /> + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index e3e8d3d0eb120..76f33d96faf91 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -24,6 +24,7 @@ import { useProjects } from "../../state/entities"; import { environmentServerConfigsAtom } from "../../state/server"; import { PullRequestListRow } from "./PullRequestListRow"; import { PullRequestListFilters } from "./PullRequestListFilters"; +import { PullRequestSavedViewsMenu } from "./PullRequestSavedViewsMenu"; import { usePullRequestList } from "./usePullRequestList"; import { usePullRequestListControls } from "./usePullRequestListControls"; import { usePullRequestListActions } from "./usePullRequestListActions"; @@ -280,6 +281,28 @@ export function PullRequestsScreen( ListHeaderComponent={ <> { + listControls.applyView(view); + workspace.dispatch( + view.query + ? { type: "search", tab: "pullRequests" } + : { type: "cancel", tab: "pullRequests" }, + ); + workspace.dispatch({ type: "query", tab: "pullRequests", query: view.query }); + void listRef.current?.scrollToOffset({ + offset: Platform.OS === "ios" ? -insets.top : 0, + animated: false, + }); + }} + /> + } environments={environments.map((item) => ({ id: String(item.environmentId), label: item.environmentLabel, diff --git a/apps/mobile/src/features/pull-requests/pullRequestSavedViews.test.ts b/apps/mobile/src/features/pull-requests/pullRequestSavedViews.test.ts new file mode 100644 index 0000000000000..83fe5079214c3 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/pullRequestSavedViews.test.ts @@ -0,0 +1,51 @@ +import { expect, it } from "vite-plus/test"; +import type { PullRequestSavedView } from "../../persistence/mobile-preferences"; +import { pullRequestViewMatches } from "./pullRequestSavedViews"; + +const view = { + id: "review", + name: "Review queue", + environmentId: "remote", + query: "bug", + controls: { + state: "open", + involvement: "reviewing", + filters: { + author: "me", + draft: "hide", + labels: [["bug", "fix"], ["urgent"]], + excludedLabels: ["hold", "later"], + }, + sort: "created", + projectId: "project", + projectEnvironmentId: "remote", + }, +} as const satisfies PullRequestSavedView; + +it("recognizes a saved view regardless of filter property or label ordering", () => { + const controls = { + ...view.controls, + filters: { + excludedLabels: ["later", "hold"], + labels: [["urgent"], ["fix", "bug"]], + draft: "hide", + author: "me", + }, + } as const; + expect(pullRequestViewMatches(view, { ...view, query: " bug ", controls })).toBe(true); + expect(view.controls.filters.labels).toEqual([["bug", "fix"], ["urgent"]]); +}); + +it("marks the view modified when search, sort, environment, or project environment changes", () => { + expect(pullRequestViewMatches(view, { ...view, query: "different" })).toBe(false); + expect(pullRequestViewMatches(view, { ...view, environmentId: null })).toBe(false); + expect( + pullRequestViewMatches(view, { ...view, controls: { ...view.controls, sort: "oldest" } }), + ).toBe(false); + expect( + pullRequestViewMatches(view, { + ...view, + controls: { ...view.controls, projectEnvironmentId: "other" }, + }), + ).toBe(false); +}); diff --git a/apps/mobile/src/features/pull-requests/pullRequestSavedViews.ts b/apps/mobile/src/features/pull-requests/pullRequestSavedViews.ts new file mode 100644 index 0000000000000..b80ff65d8f7d0 --- /dev/null +++ b/apps/mobile/src/features/pull-requests/pullRequestSavedViews.ts @@ -0,0 +1,44 @@ +import type { Preferences, PullRequestSavedView } from "../../persistence/mobile-preferences"; + +export type PullRequestSavedViewScope = Pick< + PullRequestSavedView, + "environmentId" | "controls" | "query" +>; + +export function pullRequestViewMatches( + view: PullRequestSavedView, + scope: PullRequestSavedViewScope, +) { + const key = ({ environmentId, controls, query }: PullRequestSavedViewScope) => + JSON.stringify([ + environmentId, + query.trim(), + controls.state, + controls.involvement, + controls.sort, + controls.projectId, + controls.projectEnvironmentId, + controls.filters.draft, + controls.filters.review, + controls.filters.checks, + controls.filters.author, + controls.filters.labels + ?.map((group) => [...group].sort()) + .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), + controls.filters.excludedLabels ? [...controls.filters.excludedLabels].sort() : undefined, + ]); + return key(view) === key(scope); +} + +/** Apply environment and controls in one preference write, retaining other environments' controls. */ +export function pullRequestSavedViewPreferences(current: Preferences, view: PullRequestSavedView) { + return { + pullRequestListFilters: { + environmentId: view.environmentId, + controls: { + ...current.pullRequestListFilters?.controls, + [view.environmentId ?? ""]: view.controls, + }, + }, + }; +} diff --git a/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts b/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts index b64eed69fa109..dc79576be6518 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestListControls.ts @@ -4,6 +4,8 @@ import { useCallback } from "react"; import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { DEFAULT_PR_LIST_CONTROLS, type PullRequestListControls } from "./pullRequestList"; +import type { PullRequestSavedView } from "../../persistence/mobile-preferences"; +import { pullRequestSavedViewPreferences } from "./pullRequestSavedViews"; /** The pull request list's environment and its filters, restored on the next launch. */ export function usePullRequestListControls() { @@ -44,5 +46,34 @@ export function usePullRequestListControls() { }), [savePreferences], ); - return { environmentId, controlsFor, setEnvironmentId, setControls } as const; + const applyView = useCallback( + (view: PullRequestSavedView) => + savePreferences({ + transform: (current) => pullRequestSavedViewPreferences(current, view), + }), + [savePreferences], + ); + return { environmentId, controlsFor, setEnvironmentId, setControls, applyView } as const; +} + +const EMPTY_SAVED_VIEWS: ReadonlyArray = []; + +export function usePullRequestSavedViews() { + const preferences = useAtomValue(mobilePreferencesAtom); + const savePreferences = useAtomSet(updateMobilePreferencesAtom, { mode: "promise" }); + const ready = AsyncResult.isSuccess(preferences) && !preferences.waiting; + const views = AsyncResult.isSuccess(preferences) + ? (preferences.value.pullRequestSavedViews ?? EMPTY_SAVED_VIEWS) + : EMPTY_SAVED_VIEWS; + const update = ( + transform: ( + current: ReadonlyArray, + ) => ReadonlyArray, + ) => + savePreferences({ + transform: (current) => ({ + pullRequestSavedViews: transform(current.pullRequestSavedViews ?? EMPTY_SAVED_VIEWS), + }), + }); + return { views, ready, update } as const; } diff --git a/apps/mobile/src/lib/storage.test.ts b/apps/mobile/src/lib/storage.test.ts index b9f7a17b4d5ff..7f76682fa5b41 100644 --- a/apps/mobile/src/lib/storage.test.ts +++ b/apps/mobile/src/lib/storage.test.ts @@ -101,6 +101,7 @@ import { savePreferencesPatch, } from "../persistence/imperative"; import { toStableSavedRemoteConnection } from "./connection"; +import { pullRequestSavedViewPreferences } from "../features/pull-requests/pullRequestSavedViews"; const managedConnection = { environmentId: EnvironmentId.make("environment-1"), @@ -302,6 +303,72 @@ describe("mobile connection storage", () => { await expect(loadPreferences()).resolves.toEqual({}); }); + it("restores named PR views and applies their complete scope after restarting storage", async () => { + const views = [ + { + id: "reviewing", + name: "PRs Requesting My Review", + environmentId: "remote", + query: "label:bug authentication", + controls: { + state: "open", + involvement: "reviewing", + filters: { + draft: "hide", + review: "review-required", + checks: "passing", + author: "me", + labels: [["bug"]], + }, + sort: "created", + projectId: "project", + projectEnvironmentId: "remote", + }, + }, + { + id: "all", + name: "All PRs", + environmentId: null, + query: "", + controls: { state: "all", involvement: "all", filters: {}, sort: "updated" }, + }, + ] as const; + const localControls = { + state: "merged", + involvement: "authored", + filters: { checks: "failing" }, + sort: "oldest", + } as const; + await savePreferencesPatch({ + pullRequestSavedViews: views, + pullRequestListFilters: { environmentId: "local", controls: { local: localControls } }, + }); + + const restored = await loadPreferences(); + expect(restored.pullRequestSavedViews).toEqual(views); + await savePreferencesPatch(pullRequestSavedViewPreferences(restored, views[0])); + expect((await loadPreferences()).pullRequestListFilters).toEqual({ + environmentId: "remote", + controls: { local: localControls, remote: views[0].controls }, + }); + await savePreferencesPatch(pullRequestSavedViewPreferences(await loadPreferences(), views[1])); + expect((await loadPreferences()).pullRequestListFilters).toEqual({ + environmentId: null, + controls: { local: localControls, remote: views[0].controls, "": views[1].controls }, + }); + }); + + it("discards malformed saved PR views without discarding other preferences", async () => { + mocks.setPreferencesJson( + JSON.stringify({ + baseFontSize: 17, + pullRequestSavedViews: [{ id: "invalid", name: "Broken", controls: { sort: "unknown" } }], + }), + 10, + ); + expect(await loadPreferences()).toEqual({ baseFontSize: 17 }); + }); + it("reconciles fallback preferences after SQLite recovers", async () => { mocks.setPreferencesJson(JSON.stringify({ baseFontSize: 15 }), 10); await mocks.setItemAsync( diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts index 808383183e4c1..e349839d1157f 100644 --- a/apps/mobile/src/persistence/mobile-preferences.ts +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -5,6 +5,7 @@ import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; +import { PullRequestSavedViewIdentity } from "@t3tools/client-runtime/pull-request-saved-views"; import { EnvironmentId, PullRequestInvolvement, @@ -36,6 +37,15 @@ export const PullRequestListControls = Schema.Struct({ }); export type PullRequestListControls = typeof PullRequestListControls.Type; +export const PullRequestSavedView = Schema.Struct({ + ...PullRequestSavedViewIdentity.fields, + environmentId: Schema.NullOr(Schema.String), + controls: PullRequestListControls, + query: Schema.String, +}); +export type PullRequestSavedView = typeof PullRequestSavedView.Type; +const isPullRequestSavedViews = Schema.is(Schema.Array(PullRequestSavedView)); + const ThreadListFilters = Schema.Struct({ environmentId: Schema.NullOr(EnvironmentId), projectKey: Schema.NullOr(Schema.String), @@ -95,6 +105,7 @@ export interface Preferences { /** Home list filters, restored on the next launch. */ readonly threadListFilters?: ThreadListFilters; readonly pullRequestListFilters?: PullRequestListPreferences; + readonly pullRequestSavedViews?: ReadonlyArray; } export class MobilePreferencesLoadError extends Schema.TaggedError()( @@ -163,6 +174,7 @@ function sanitizePreferences(parsed: Preferences): Preferences { threadListWorkingShelfExpanded?: boolean; threadListFilters?: ThreadListFilters; pullRequestListFilters?: PullRequestListPreferences; + pullRequestSavedViews?: ReadonlyArray; } = {}; if (typeof parsed.pullRequestHideTestFiles === "boolean") { @@ -283,6 +295,9 @@ function sanitizePreferences(parsed: Preferences): Preferences { if (isPullRequestListPreferences(parsed.pullRequestListFilters)) { preferences.pullRequestListFilters = parsed.pullRequestListFilters; } + if (isPullRequestSavedViews(parsed.pullRequestSavedViews)) { + preferences.pullRequestSavedViews = parsed.pullRequestSavedViews; + } return preferences; } diff --git a/apps/web/src/components/pullRequest/PullRequestSavedViewsMenu.test.tsx b/apps/web/src/components/pullRequest/PullRequestSavedViewsMenu.test.tsx new file mode 100644 index 0000000000000..158a0e8a7c852 --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestSavedViewsMenu.test.tsx @@ -0,0 +1,158 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; + +import { PullRequestSavedViewsMenu } from "./PullRequestSavedViewsMenu"; +import type { PullRequestListPreferences } from "./pullRequestListPreferences"; +import { PULL_REQUEST_SAVED_VIEWS_KEY, type PullRequestSavedView } from "./pullRequestSavedViews"; + +const { toastAdd } = vi.hoisted(() => ({ toastAdd: vi.fn() })); +vi.mock("../ui/toast", () => ({ toastManager: { add: toastAdd } })); + +let root: Root; +let container: HTMLDivElement; +const onApply = vi.fn(); +const reviewing = { + involvement: "reviewing", + state: "open", + q: "bug", + draft: "hide", + sort: "updated", +} as const satisfies PullRequestListPreferences; + +beforeEach(() => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + localStorage.clear(); + onApply.mockClear(); + toastAdd.mockClear(); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); + +afterEach(async () => { + await act(() => root.unmount()); + container.remove(); + localStorage.clear(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +async function render(preferences: PullRequestListPreferences = reviewing) { + await act(() => + root.render(), + ); +} + +async function openMenu() { + await act(() => + container.querySelector('[aria-label="Saved pull request views"]')!.click(), + ); +} + +async function choose(label: string) { + const item = [...document.querySelectorAll('[role="menuitem"]')].find( + (element) => element.textContent === label, + ); + expect(item, label).toBeDefined(); + await act(() => item!.click()); +} + +async function nameView(name: string) { + const input = document.querySelector("input")!; + await act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, name); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); +} + +async function submit() { + await act(() => + document + .querySelector("form")! + .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })), + ); +} + +function storedViews(): ReadonlyArray { + return JSON.parse(localStorage.getItem(PULL_REQUEST_SAVED_VIEWS_KEY) ?? "[]"); +} + +it("saves a named filter setup and restores it after remounting", async () => { + await render(); + await openMenu(); + await choose("Save current view…"); + expect(document.querySelector("input")?.value).toBe("PRs Requesting My Review"); + await submit(); + expect(storedViews()).toEqual([ + { id: expect.any(String), name: "PRs Requesting My Review", preferences: reviewing }, + ]); + + await act(() => root.unmount()); + root = createRoot(container); + await render({ involvement: "all", state: "merged", checks: "failing" }); + await openMenu(); + await choose("PRs Requesting My Review"); + expect(onApply).toHaveBeenCalledExactlyOnceWith(reviewing); +}); + +it("updates, renames, and deletes a view without affecting another saved view", async () => { + localStorage.setItem( + PULL_REQUEST_SAVED_VIEWS_KEY, + JSON.stringify([ + { id: "reviewing", name: "Review queue", preferences: reviewing }, + { id: "authored", name: "My PRs", preferences: { involvement: "authored", state: "open" } }, + ]), + ); + await render(); + await openMenu(); + await choose("Review queue"); + await render({ ...reviewing, checks: "passing" }); + await openMenu(); + await choose("Update saved view"); + expect(storedViews()[0]?.preferences.checks).toBe("passing"); + await openMenu(); + await choose("Rename view…"); + await nameView("My PRs"); + expect(document.body.textContent).toContain("A view with this name already exists."); + await nameView(" Ready to review "); + await submit(); + expect(storedViews()[0]?.name).toBe("Ready to review"); + await openMenu(); + await choose("Delete view"); + expect(storedViews().map((view) => view.id)).toEqual(["authored"]); +}); + +it("keeps the dialog open and reports a failed storage write", async () => { + await render(); + await openMenu(); + await choose("Save current view…"); + vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { + throw new Error("quota exceeded"); + }); + vi.spyOn(console, "error").mockImplementation(() => {}); + await submit(); + expect(document.querySelector('[role="dialog"]')).not.toBeNull(); + expect(storedViews()).toEqual([]); + expect(toastAdd).toHaveBeenCalledWith( + expect.objectContaining({ type: "error", title: "Could not save PR views" }), + ); +}); + +it("keeps the explicitly chosen view selected when two views have identical filters", async () => { + localStorage.setItem( + PULL_REQUEST_SAVED_VIEWS_KEY, + JSON.stringify([ + { id: "first", name: "First queue", preferences: reviewing }, + { id: "second", name: "Second queue", preferences: reviewing }, + ]), + ); + await render(); + await openMenu(); + await choose("Second queue"); + expect(container.textContent).toContain("Second queue"); + await openMenu(); + await choose("Delete view"); + expect(storedViews().map((view) => view.id)).toEqual(["first"]); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestSavedViewsMenu.tsx b/apps/web/src/components/pullRequest/PullRequestSavedViewsMenu.tsx new file mode 100644 index 0000000000000..9aeb096aae162 --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestSavedViewsMenu.tsx @@ -0,0 +1,249 @@ +import { BookmarkIcon, CheckIcon, ChevronDownIcon, PlusIcon } from "lucide-react"; +import { useId, useState } from "react"; +import { + PULL_REQUEST_VIEW_NAME_MAX_LENGTH, + pullRequestViewNameError, +} from "@t3tools/client-runtime/pull-request-saved-views"; + +import { getLocalStorageItem, useLocalStorage } from "../../hooks/useLocalStorage"; +import { randomUUID } from "../../lib/utils"; +import { Button } from "../ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { Input } from "../ui/input"; +import { Label } from "../ui/label"; +import { Menu, MenuItem, MenuItemLabel, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/menu"; +import { toastManager } from "../ui/toast"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { + pullRequestListPreferences, + type PullRequestListPreferences, +} from "./pullRequestListPreferences"; +import { + EMPTY_PULL_REQUEST_SAVED_VIEWS, + PULL_REQUEST_SAVED_VIEWS_KEY, + PullRequestSavedViews, + pullRequestViewMatches, + type PullRequestSavedView, +} from "./pullRequestSavedViews"; + +export function PullRequestSavedViewsMenu({ + preferences, + onApply, +}: { + preferences: PullRequestListPreferences; + onApply: (preferences: PullRequestListPreferences) => void; +}) { + const [views, setViews] = useLocalStorage( + PULL_REQUEST_SAVED_VIEWS_KEY, + EMPTY_PULL_REQUEST_SAVED_VIEWS, + PullRequestSavedViews, + ); + const [selectedId, setSelectedId] = useState(null); + const [editor, setEditor] = useState<{ id?: string; name: string } | null>(null); + const inputId = useId(); + const errorId = useId(); + const explicitlySelectedView = views.find((view) => view.id === selectedId); + const matchingView = + explicitlySelectedView && pullRequestViewMatches(explicitlySelectedView, preferences) + ? explicitlySelectedView + : views.find((view) => pullRequestViewMatches(view, preferences)); + const selectedView = matchingView ?? explicitlySelectedView; + const modified = selectedView !== undefined && !pullRequestViewMatches(selectedView, preferences); + const nameError = editor ? pullRequestViewNameError(editor.name, views, editor.id) : null; + + function persist( + update: (current: ReadonlyArray) => ReadonlyArray, + ) { + let written: ReadonlyArray | undefined; + setViews((current) => { + written = update(current); + return written; + }); + // The shared hook logs storage failures. Keep the editor open and explain when saving failed. + try { + if ( + written && + JSON.stringify(getLocalStorageItem(PULL_REQUEST_SAVED_VIEWS_KEY, PullRequestSavedViews)) === + JSON.stringify(written) + ) { + return true; + } + } catch { + // A browser policy can deny reads as well as writes. + } + toastManager.add({ + type: "error", + title: "Could not save PR views", + description: + "Local storage is unavailable or full. Try again after freeing space or allowing storage.", + }); + return false; + } + + function saveName() { + if (!editor || nameError) return; + const id = editor.id ?? randomUUID(); + const name = editor.name.trim(); + const editingId = editor.id; + const saved = persist((current) => + editingId + ? current.map((view) => (view.id === editingId ? { ...view, name } : view)) + : [...current, { id, name, preferences: pullRequestListPreferences(preferences) }], + ); + if (!saved) return; + setSelectedId(id); + setEditor(null); + } + + return ( + <> + + + } + aria-label="Saved pull request views" + /> + } + > + + {selectedView?.name ?? "Views"} + {modified ? * : null} + + + {selectedView?.name ?? "Saved pull request views"} + + + {views.map((view) => ( + + { + setSelectedId(view.id); + onApply(pullRequestListPreferences(view.preferences)); + }} + /> + } + > + {matchingView?.id === view.id ? ( + + ) : ( + + )} + {view.name} + + {view.name} + + ))} + {views.length > 0 ? : null} + + setEditor({ + name: preferences.involvement === "reviewing" ? "PRs Requesting My Review" : "", + }) + } + > + + Save current view… + + {selectedView ? ( + <> + {modified ? ( + + persist((current) => + current.map((view) => + view.id === selectedView.id + ? { ...view, preferences: pullRequestListPreferences(preferences) } + : view, + ), + ) + } + > + Update saved view + + ) : null} + setEditor({ id: selectedView.id, name: selectedView.name })}> + Rename view… + + { + if (persist((current) => current.filter((view) => view.id !== selectedView.id))) + setSelectedId(null); + }} + > + Delete view + + + ) : null} + + + { + if (!open) setEditor(null); + }} + > + +
{ + event.preventDefault(); + saveName(); + }} + > + + {editor?.id ? "Rename PR view" : "Save PR view"} + + Save your search, filters, and sort order on this device. + + + +
+ + + setEditor((current) => + current ? { ...current, name: event.target.value } : null, + ) + } + /> + {nameError && editor?.name ? ( +

+ {nameError} +

+ ) : null} +
+
+ + + + +
+
+
+ + ); +} diff --git a/apps/web/src/components/pullRequest/pullRequestListPreferences.ts b/apps/web/src/components/pullRequest/pullRequestListPreferences.ts index e58e36bb9e775..c0cbd745f3cb8 100644 --- a/apps/web/src/components/pullRequest/pullRequestListPreferences.ts +++ b/apps/web/src/components/pullRequest/pullRequestListPreferences.ts @@ -44,7 +44,7 @@ const DEFAULT_PULL_REQUEST_LIST_PREFERENCES = { } as const satisfies PullRequestListPreferences; const BoundedPreference = Schema.String.check(Schema.isMaxLength(200)); -const PullRequestListPreferencesSchema = Schema.Struct({ +export const PullRequestListPreferencesSchema = Schema.Struct({ involvement: PullRequestInvolvement, state: PullRequestListState, environmentId: Schema.optional(EnvironmentId), diff --git a/apps/web/src/components/pullRequest/pullRequestSavedViews.test.ts b/apps/web/src/components/pullRequest/pullRequestSavedViews.test.ts new file mode 100644 index 0000000000000..13d007796030f --- /dev/null +++ b/apps/web/src/components/pullRequest/pullRequestSavedViews.test.ts @@ -0,0 +1,107 @@ +import { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { pullRequestViewNameError } from "@t3tools/client-runtime/pull-request-saved-views"; +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { + pullRequestListPreferences, + type PullRequestListPreferences, +} from "./pullRequestListPreferences"; +import { + PullRequestSavedViews, + pullRequestSavedViewPatch, + pullRequestViewMatches, +} from "./pullRequestSavedViews"; + +const preferences = { + involvement: "reviewing", + state: "open", + environmentId: EnvironmentId.make("remote"), + projectId: ProjectId.make("project"), + host: "github.example.com", + q: "label:bug authentication", + draft: "hide", + review: "review-required", + checks: "passing", + author: "me", + labels: ["bug", "priority"], + sort: "updated", +} as const satisfies PullRequestListPreferences; +const view = { id: "review", name: "PRs Requesting My Review", preferences }; +const decodeViews = Schema.decodeUnknownSync(PullRequestSavedViews); + +describe("saved PR views", () => { + it("round trips multiple named views with every list setting", () => { + const views = [ + view, + { id: "authored", name: "My PRs", preferences: { involvement: "authored", state: "closed" } }, + ]; + expect(decodeViews(JSON.parse(JSON.stringify(views)))).toEqual(views); + }); + + it("replaces all filters while preserving the selected PR", () => { + const current = { + ...preferences, + repository: "org/repo", + number: 42, + selectedHost: "github.com", + selectedEnvironmentId: EnvironmentId.make("other"), + selectedProjectId: ProjectId.make("other"), + }; + const restored = { + ...current, + ...pullRequestSavedViewPatch({ involvement: "all", state: "merged" }), + }; + expect(pullRequestListPreferences(restored)).toEqual({ involvement: "all", state: "merged" }); + expect(restored).toMatchObject({ + repository: "org/repo", + number: 42, + selectedHost: "github.com", + selectedEnvironmentId: "other", + selectedProjectId: "other", + }); + }); + + it("restores scoped filters without conflating a project on two environments", () => { + const previous = { involvement: "all", state: "closed" } as const; + expect( + pullRequestListPreferences({ + ...previous, + ...pullRequestSavedViewPatch(preferences), + }), + ).toEqual(preferences); + expect( + pullRequestViewMatches(view, { + ...preferences, + environmentId: EnvironmentId.make("another"), + }), + ).toBe(false); + }); + + it("matches default sorting and label sets regardless of selection or label order", () => { + const defaultView = { ...view, preferences: { ...preferences, sort: undefined } }; + expect( + pullRequestViewMatches(defaultView, { + ...preferences, + labels: ["priority", "bug"], + sort: "ready", + }), + ).toBe(true); + expect(pullRequestViewMatches(view, { ...preferences, q: "different" })).toBe(false); + expect(pullRequestViewMatches(view, { ...preferences, labels: ["bug"] })).toBe(false); + }); + + it("rejects blank and duplicate names while allowing a view to keep its own name", () => { + expect(pullRequestViewNameError(" ", [view])).toBeTruthy(); + expect(pullRequestViewNameError("x".repeat(81), [view])).toBeTruthy(); + expect(pullRequestViewNameError(" PRS REQUESTING MY REVIEW ", [view])).toBeTruthy(); + expect(pullRequestViewNameError(view.name, [view], view.id)).toBeNull(); + expect(pullRequestViewNameError(" My PRs ", [view])).toBeNull(); + }); + + it("rejects malformed stored filters", () => { + expect(() => + decodeViews([{ ...view, preferences: { ...preferences, involvement: "unknown" } }]), + ).toThrow(); + }); +}); diff --git a/apps/web/src/components/pullRequest/pullRequestSavedViews.ts b/apps/web/src/components/pullRequest/pullRequestSavedViews.ts new file mode 100644 index 0000000000000..181d2b50e72a1 --- /dev/null +++ b/apps/web/src/components/pullRequest/pullRequestSavedViews.ts @@ -0,0 +1,54 @@ +import * as Schema from "effect/Schema"; +import { PullRequestSavedViewIdentity } from "@t3tools/client-runtime/pull-request-saved-views"; + +import { + pullRequestListPreferences, + PullRequestListPreferencesSchema, + type PullRequestListPreferencePatch, + type PullRequestListPreferences, +} from "./pullRequestListPreferences"; + +export const PULL_REQUEST_SAVED_VIEWS_KEY = "t3.pullRequests.savedViews"; + +export const PullRequestSavedViews = Schema.Array( + Schema.Struct({ + ...PullRequestSavedViewIdentity.fields, + preferences: PullRequestListPreferencesSchema, + }), +); +export type PullRequestSavedView = (typeof PullRequestSavedViews.Type)[number]; +export const EMPTY_PULL_REQUEST_SAVED_VIEWS: typeof PullRequestSavedViews.Type = []; + +export function pullRequestViewMatches( + view: PullRequestSavedView, + preferences: PullRequestListPreferences, +): boolean { + const key = (value: PullRequestListPreferences) => { + const normalized = pullRequestListPreferences(value); + return JSON.stringify({ + ...normalized, + labels: normalized.labels?.toSorted(), + }); + }; + return key(pullRequestListPreferences(view.preferences)) === key(preferences); +} + +/** Explicit clears replace the old list scope without touching the independently selected PR. */ +export function pullRequestSavedViewPatch( + preferences: PullRequestListPreferences, +): PullRequestListPreferencePatch & Pick { + return { + involvement: preferences.involvement, + state: preferences.state, + environmentId: preferences.environmentId, + projectId: preferences.projectId, + host: preferences.host, + q: preferences.q, + draft: preferences.draft, + review: preferences.review, + checks: preferences.checks, + author: preferences.author, + labels: preferences.labels, + sort: preferences.sort, + }; +} diff --git a/apps/web/src/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsx index f7154177f57b1..15b6e13317d4f 100644 --- a/apps/web/src/routes/_chat.pull-requests.tsx +++ b/apps/web/src/routes/_chat.pull-requests.tsx @@ -100,6 +100,8 @@ import { writePullRequestListPreferences, } from "../components/pullRequest/pullRequestListPreferences"; import { assignProjectsToEnvironments } from "../components/pullRequest/pullRequestProjectAssignment.logic"; +import { PullRequestSavedViewsMenu } from "../components/pullRequest/PullRequestSavedViewsMenu"; +import { pullRequestSavedViewPatch } from "../components/pullRequest/pullRequestSavedViews"; import { pullRequestFilterProjects } from "../components/pullRequest/pullRequestProjectFilter.logic"; import { environmentMachineIcon } from "../components/EnvironmentMachineIcon"; import { PullRequestDetailPanel } from "../components/pullRequest/PullRequestDetailPanel"; @@ -2118,6 +2120,12 @@ function PullRequestsRouteView() { searchInput, sortMenu, filtersMenu, + savedViewsMenu: ( + updateListScope(pullRequestSavedViewPatch(preferences))} + /> + ), rightPanelControl: // Footprint reserve while the panel is closed: the toggle itself stays // mounted at the fixed titlebar inset in both states so it cannot move @@ -2574,6 +2582,7 @@ function PullRequestsColumn({ searchInput, sortMenu, filtersMenu, + savedViewsMenu, rightPanelControl, titlebarControls, rightPanelOpen, @@ -2594,6 +2603,7 @@ function PullRequestsColumn({ searchInput: ReactNode; sortMenu: ReactNode; filtersMenu: ReactNode; + savedViewsMenu: ReactNode; rightPanelControl: ReactNode; titlebarControls: ReactNode; rightPanelOpen: boolean; @@ -2752,6 +2762,7 @@ function PullRequestsColumn({ {sortMenu} {filtersMenu} + {savedViewsMenu} , + editingId?: string, +): string | null { + const trimmed = name.trim(); + if (!trimmed) return "Enter a name for this view."; + if (trimmed.length > PULL_REQUEST_VIEW_NAME_MAX_LENGTH) { + return `Use ${PULL_REQUEST_VIEW_NAME_MAX_LENGTH} characters or fewer.`; + } + return views.some( + (view) => view.id !== editingId && view.name.toLowerCase() === trimmed.toLowerCase(), + ) + ? "A view with this name already exists." + : null; +}