Files
kandev/apps/web/components/github/my-github/presets-sidebar.tsx
T
João Salavisa 85aa3ac0aa feat(github): add /github page for PRs and issues (#687)
* feat(github): add /github page for PRs and issues

Dedicated page under /github lists pull requests and issues across the
authenticated user's repos with preset filters, custom GitHub search
queries, per-repo narrowing, saved queries, and one-click task launching
for any PR or issue.

Performance:
- Cache user PR/issue search responses for 30s with singleflight to
  coalesce concurrent misses, so preset switching and pagination avoid
  upstream round trips.
- Replace the per-row PR status fetch (N+1) with a batch endpoint
  POST /api/v1/github/prs/statuses that fans out concurrently on the
  backend with a semaphore and caches per-PR.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* style: apply Prettier formatting

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address review feedback on PR cache + status batching

- Harden searchCacheKey against separator collisions from
  user-controllable customQuery (length-prefix encoding).
- Drop repositories.loaded hydration when inner workspace fetch fails
  so the client refetches instead of trusting a partial snapshot.
- Guard useGitHubSearch with a monotonic request counter to drop
  stale responses when filter+page changes overlap.
- Fix usePRStatuses teardown: depend only on composed key so a new
  array identity per render doesn't cancel the in-flight batch.
- Correct godocs (duplicate, outdated state:open claim).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address additional review feedback

- Restore state:open for issue watcher: buildIssueSearchQuery no
  longer injects it as a default, so existing watches were starting
  to surface closed issues. Inject state:open in buildIssueFilter so
  only the watcher path is affected; the /github page presets already
  set their own state qualifiers.
- countCheckResults now excludes in-progress checks from the denominator
  so a `1/3` badge reflects pass rate on completed checks, not a mix of
  running and failed. The pending state is still carried via ChecksState.
- usePRStatuses retries after a transient fetch error (only mark the
  key as completed once the fetch resolves). This also fixes missing
  badges under React Strict Mode's intentional double-mount, since the
  first effect's cleanup fires before the response lands and the guard
  stays unset for the second mount to retry.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test(github): add tests for my-github hooks

Covers use-committed-query, buildParams from use-github-search,
use-saved-presets readStorage validation, use-known-repos recordForKey
accumulator semantics, and use-pr-statuses batch fetch lifecycle.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address review feedback on search cache and repo accumulator

- Clamp perPage before composing the search cache key so identical
  pages (e.g. perPage=150 and =100) share a cache entry instead of
  creating duplicates keyed on the raw value.
- Add resetKnownReposStore and call it on /github unmount so the
  module-level repo accumulator doesn't carry across navigations.
- Rename use-pr-statuses test to match its assertion (it verifies
  stale statuses are cleared when the key changes and fetch fails).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* style: apply Prettier formatting

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(web): distinguish blocked from dirty in PR mergeable badge

GitHub's blocked state (required reviews/checks/branch protection)
is not a merge conflict, so don't label it "Conflicts". Surface it
as "Blocked" with the pending tone; keep "Conflicts" for dirty.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: address remaining /github code review comments

- Route PR status + batch through handleSearchError so ErrNoClient
  surfaces as 503 instead of 500 (matches the search endpoints).
- Sort workflow steps by position in the quick-task-launcher default
  pick, matching the convention in issue-watch-dialog.
- Make PresetItem keyboard-accessible: role=button, tabIndex, and
  Enter/Space handling on the wrapping div (it contains a nested
  delete button, so it can't itself be a button).
- Extract useRepoOptions out of useGitHubPageState to bring the hook
  back under the 100-line complexity limit.
- Honor ctx.Done() when acquiring the PR-status batch semaphore so a
  cancelled HTTP request releases queued goroutines instead of
  running each upstream fetch to completion.
- Clarify parsePaginationQuery doc: the upper bound (100) is enforced
  by clampSearchPage in the client layer, not here.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(web): address /github review follow-ups

- Merge duplicate @/lib/utils imports in pr-list.
- Use rel="noopener noreferrer" on external PR/issue links (codebase
  convention) and add cursor-pointer per the UI guidelines.
- Rewrite onOpenSaveDialog as an explicit if-block so the callback
  returns void rather than boolean | void.
- Use PaginationEllipsis in its own PaginationItem so the ellipsis
  and the adjacent page link are separate list items instead of
  visually fused into a single cell.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(web): derive QuickTaskLauncher dialog state from props

Replaces the useEffect+setState anti-pattern with useMemo-derived state
driven directly by the payload prop. Drops the eslint suppression that
was needed for react-hooks/set-state-in-effect.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 10:38:49 +01:00

239 lines
6.3 KiB
TypeScript

"use client";
import { IconX, IconDeviceFloppy, IconBookmark } from "@tabler/icons-react";
import type { Icon } from "@tabler/icons-react";
import { cn } from "@/lib/utils";
import { PR_PRESETS, ISSUE_PRESETS, type PresetOption, type PresetGroup } from "./search-bar";
import type { SavedPreset } from "./use-saved-presets";
export type SidebarSelection = {
kind: "pr" | "issue";
source: "preset" | "saved";
id: string;
};
type PresetsSidebarProps = {
selected: SidebarSelection;
onSelect: (s: SidebarSelection) => void;
savedPresets: SavedPreset[];
onDeleteSaved: (id: string) => void;
canSaveCurrent: boolean;
onSaveCurrent: () => void;
};
function KindToggle({
kind,
onChange,
}: {
kind: "pr" | "issue";
onChange: (k: "pr" | "issue") => void;
}) {
return (
<div className="mx-2 mb-3 grid grid-cols-2 rounded-md border p-0.5 text-xs">
{(["pr", "issue"] as const).map((value) => (
<button
key={value}
type="button"
onClick={() => onChange(value)}
className={cn(
"px-2 py-1 rounded cursor-pointer transition-colors",
kind === value
? "bg-muted font-medium text-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
{value === "pr" ? "Pull requests" : "Issues"}
</button>
))}
</div>
);
}
function SectionHeader({ title }: { title: string }) {
return (
<div className="px-2 mt-3 mb-1 text-[11px] uppercase tracking-wider text-muted-foreground font-medium">
{title}
</div>
);
}
function PresetItem({
label,
Icon,
active,
onClick,
trailing,
}: {
label: string;
Icon: Icon;
active: boolean;
onClick: () => void;
trailing?: React.ReactNode;
}) {
const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onClick();
}
};
return (
<div
role="button"
tabIndex={0}
aria-pressed={active}
className={cn(
"group/item mx-1 flex items-center gap-2 rounded-md px-2 py-1.5 text-sm cursor-pointer transition-colors",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
active ? "bg-muted font-medium text-foreground" : "text-muted-foreground hover:bg-muted/50",
)}
onClick={onClick}
onKeyDown={onKeyDown}
>
<Icon className="h-4 w-4 shrink-0" />
<span className="truncate flex-1">{label}</span>
{trailing}
</div>
);
}
function PresetGroupList({
presets,
group,
selected,
onSelect,
kind,
}: {
presets: PresetOption[];
group: PresetGroup;
selected: SidebarSelection;
onSelect: (s: SidebarSelection) => void;
kind: "pr" | "issue";
}) {
const items = presets.filter((p) => p.group === group);
if (items.length === 0) return null;
return (
<>
<SectionHeader title={group === "inbox" ? "Inbox" : "Created"} />
{items.map((p) => (
<PresetItem
key={`${kind}-${p.value}`}
label={p.label}
Icon={p.icon}
active={selected.source === "preset" && selected.id === p.value}
onClick={() => onSelect({ kind, source: "preset", id: p.value })}
/>
))}
</>
);
}
function SavedSection({
saved,
selected,
onSelect,
onDelete,
kind,
canSaveCurrent,
onSaveCurrent,
}: {
saved: SavedPreset[];
selected: SidebarSelection;
onSelect: (s: SidebarSelection) => void;
onDelete: (id: string) => void;
kind: "pr" | "issue";
canSaveCurrent: boolean;
onSaveCurrent: () => void;
}) {
return (
<>
<SectionHeader title="Saved" />
{saved.length === 0 && (
<div className="mx-2 px-2 py-1 text-xs text-muted-foreground/80 italic">
No saved queries yet.
</div>
)}
{saved.map((s) => (
<PresetItem
key={s.id}
label={s.label}
Icon={IconBookmark}
active={selected.source === "saved" && selected.id === s.id}
onClick={() => onSelect({ kind, source: "saved", id: s.id })}
trailing={
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onDelete(s.id);
}}
className="opacity-0 group-hover/item:opacity-100 transition-opacity text-muted-foreground hover:text-foreground cursor-pointer"
title="Delete saved query"
>
<IconX className="h-3.5 w-3.5" />
</button>
}
/>
))}
<button
type="button"
onClick={onSaveCurrent}
disabled={!canSaveCurrent}
className={cn(
"mx-1 mt-1 flex items-center gap-2 rounded-md px-2 py-1.5 text-xs transition-colors",
canSaveCurrent
? "text-muted-foreground hover:bg-muted/50 hover:text-foreground cursor-pointer"
: "text-muted-foreground/50 cursor-not-allowed",
)}
title={canSaveCurrent ? "Save current query" : "Type a custom query first"}
>
<IconDeviceFloppy className="h-4 w-4 shrink-0" />
<span>Save current query</span>
</button>
</>
);
}
export function PresetsSidebar({
selected,
onSelect,
savedPresets,
onDeleteSaved,
canSaveCurrent,
onSaveCurrent,
}: PresetsSidebarProps) {
const presets = selected.kind === "pr" ? PR_PRESETS : ISSUE_PRESETS;
const saved = savedPresets.filter((p) => p.kind === selected.kind);
const onKindChange = (kind: "pr" | "issue") => {
const fallback = (kind === "pr" ? PR_PRESETS : ISSUE_PRESETS)[0]?.value ?? "";
onSelect({ kind, source: "preset", id: fallback });
};
return (
<nav className="flex flex-col py-3">
<KindToggle kind={selected.kind} onChange={onKindChange} />
<PresetGroupList
presets={presets}
group="inbox"
selected={selected}
onSelect={onSelect}
kind={selected.kind}
/>
<PresetGroupList
presets={presets}
group="created"
selected={selected}
onSelect={onSelect}
kind={selected.kind}
/>
<SavedSection
saved={saved}
selected={selected}
onSelect={onSelect}
onDelete={onDeleteSaved}
kind={selected.kind}
canSaveCurrent={canSaveCurrent}
onSaveCurrent={onSaveCurrent}
/>
</nav>
);
}