Files
kandev/apps/web/components/kanban/kanban-header.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

380 lines
12 KiB
TypeScript

"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Button } from "@kandev/ui/button";
import { ToggleGroup, ToggleGroupItem } from "@kandev/ui/toggle-group";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@kandev/ui/tooltip";
import {
IconPlus,
IconSettings,
IconList,
IconLayoutKanban,
IconMenu2,
IconChartBar,
IconTimeline,
IconBrandGithub,
} from "@tabler/icons-react";
import { KanbanDisplayDropdown } from "../kanban-display-dropdown";
import { RefreshReviewsButton } from "../github/refresh-reviews-button";
import { ReleaseNotesButton } from "../release-notes/release-notes-button";
import { ReleaseNotesDialog } from "../release-notes/release-notes-dialog";
import { HealthIndicatorButton, HealthIssuesDialog } from "../system-health/health-indicator";
import { TaskSearchInput } from "./task-search-input";
import { QuickChatButton } from "@/components/task/quick-chat-button";
import { KanbanHeaderMobile } from "./kanban-header-mobile";
import { MobileMenuSheet } from "./mobile-menu-sheet";
import { linkToTasks } from "@/lib/links";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import { useAppStore } from "@/components/state-provider";
import { useKanbanDisplaySettings } from "@/hooks/use-kanban-display-settings";
import { useReleaseNotes } from "@/hooks/use-release-notes";
import { useSystemHealthIndicator } from "@/hooks/use-system-health-indicator";
import { useGitHubStatus } from "@/hooks/domains/github/use-github-status";
type KanbanHeaderProps = {
onCreateTask: () => void;
workspaceId?: string;
currentPage?: "kanban" | "tasks";
searchQuery?: string;
onSearchChange?: (query: string) => void;
isSearchLoading?: boolean;
};
type ViewToggleItem = {
value: string;
icon: typeof IconLayoutKanban;
label: string;
};
const VIEW_TOGGLE_ITEMS: ViewToggleItem[] = [
{ value: "kanban", icon: IconLayoutKanban, label: "Kanban" },
{ value: "pipeline", icon: IconTimeline, label: "Pipeline" },
{ value: "list", icon: IconList, label: "List" },
];
function GitHubTopbarButton() {
const { status } = useGitHubStatus();
if (!status?.authenticated) return null;
return (
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="icon" asChild className="cursor-pointer">
<Link href="/github">
<IconBrandGithub className="h-4 w-4" />
</Link>
</Button>
</TooltipTrigger>
<TooltipContent>My GitHub — PRs & issues</TooltipContent>
</Tooltip>
);
}
function ViewToggleGroup({
toggleValue,
onValueChange,
className,
itemClassName,
}: {
toggleValue: string;
onValueChange: (value: string) => void;
className?: string;
itemClassName?: string;
}) {
return (
<ToggleGroup
type="single"
value={toggleValue}
onValueChange={onValueChange}
variant="outline"
className={className}
>
{VIEW_TOGGLE_ITEMS.map(({ value, icon: Icon, label }) => (
<ToggleGroupItem
key={value}
value={value}
className={`cursor-pointer data-[state=on]:bg-muted data-[state=on]:text-foreground ${itemClassName ?? ""}`}
>
<Tooltip>
<TooltipTrigger asChild>
<span className="flex items-center justify-center">
<Icon className="h-4 w-4" />
</span>
</TooltipTrigger>
<TooltipContent>{label}</TooltipContent>
</Tooltip>
</ToggleGroupItem>
))}
</ToggleGroup>
);
}
function getToggleValue(currentPage: string, kanbanViewMode: string | null): string {
if (currentPage === "tasks") return "list";
if (kanbanViewMode === "graph2") return "pipeline";
return "kanban";
}
function TabletHeader({
onCreateTask,
workspaceId,
searchQuery,
onSearchChange,
isSearchLoading,
toggleValue,
handleViewChange,
setMenuOpen,
showReleaseNotesButton,
onOpenReleaseNotes,
showHealthIndicator,
onOpenHealthDialog,
}: {
onCreateTask: () => void;
workspaceId?: string;
searchQuery: string;
onSearchChange?: (query: string) => void;
isSearchLoading: boolean;
toggleValue: string;
handleViewChange: (value: string) => void;
setMenuOpen: (open: boolean) => void;
showReleaseNotesButton: boolean;
onOpenReleaseNotes: () => void;
showHealthIndicator: boolean;
onOpenHealthDialog: () => void;
}) {
return (
<header className="flex items-center justify-between p-4 pb-3 gap-3">
<Link href="/" className="text-xl font-bold hover:opacity-80 flex-shrink-0">
KanDev
</Link>
{onSearchChange && (
<TaskSearchInput
value={searchQuery}
onChange={onSearchChange}
placeholder="Search..."
isLoading={isSearchLoading}
className="flex-1 max-w-[200px]"
/>
)}
<div className="flex items-center gap-2">
<Button
onClick={onCreateTask}
size="lg"
className="cursor-pointer"
data-testid="create-task-button"
>
<IconPlus className="h-4 w-4" />
<span className="hidden sm:inline ml-1">Add task</span>
</Button>
<QuickChatButton workspaceId={workspaceId} />
<TooltipProvider>
<ViewToggleGroup
toggleValue={toggleValue}
onValueChange={handleViewChange}
className="h-8"
itemClassName="h-8 w-8"
/>
<GitHubTopbarButton />
{showReleaseNotesButton && <ReleaseNotesButton hasUnseen onClick={onOpenReleaseNotes} />}
<HealthIndicatorButton hasIssues={showHealthIndicator} onClick={onOpenHealthDialog} />
</TooltipProvider>
<Button
variant="outline"
size="icon-lg"
onClick={() => setMenuOpen(true)}
className="cursor-pointer"
>
<IconMenu2 className="h-4 w-4" />
<span className="sr-only">Open menu</span>
</Button>
</div>
</header>
);
}
function DesktopHeader({
onCreateTask,
workspaceId,
searchQuery,
onSearchChange,
isSearchLoading,
toggleValue,
handleViewChange,
showReleaseNotesButton,
onOpenReleaseNotes,
showHealthIndicator,
onOpenHealthDialog,
}: {
onCreateTask: () => void;
workspaceId?: string;
searchQuery: string;
onSearchChange?: (query: string) => void;
isSearchLoading: boolean;
toggleValue: string;
handleViewChange: (value: string) => void;
showReleaseNotesButton: boolean;
onOpenReleaseNotes: () => void;
showHealthIndicator: boolean;
onOpenHealthDialog: () => void;
}) {
return (
<header className="relative flex items-center justify-between p-4 pb-3">
<div className="flex items-center gap-3">
<Link href="/" className="text-2xl font-bold hover:opacity-80">
KanDev
</Link>
</div>
{onSearchChange && (
<div className="absolute left-1/2 -translate-x-1/2">
<TaskSearchInput
value={searchQuery}
onChange={onSearchChange}
placeholder="Search tasks..."
isLoading={isSearchLoading}
className="w-64"
/>
</div>
)}
<div className="flex items-center gap-3">
<Button onClick={onCreateTask} className="cursor-pointer" data-testid="create-task-button">
<IconPlus className="h-4 w-4" />
Add task
</Button>
<QuickChatButton workspaceId={workspaceId} />
<TooltipProvider>
<ViewToggleGroup toggleValue={toggleValue} onValueChange={handleViewChange} />
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="icon" asChild className="cursor-pointer">
<Link href="/stats">
<IconChartBar className="h-4 w-4" />
</Link>
</Button>
</TooltipTrigger>
<TooltipContent>Stats</TooltipContent>
</Tooltip>
<GitHubTopbarButton />
</TooltipProvider>
<RefreshReviewsButton />
{showReleaseNotesButton && <ReleaseNotesButton hasUnseen onClick={onOpenReleaseNotes} />}
<HealthIndicatorButton hasIssues={showHealthIndicator} onClick={onOpenHealthDialog} />
<KanbanDisplayDropdown />
<Link href="/settings" className="cursor-pointer">
<Button variant="outline" className="cursor-pointer gap-2">
<IconSettings className="h-4 w-4" />
<span className="hidden 2xl:inline">Settings</span>
</Button>
</Link>
</div>
</header>
);
}
function useHeaderViewChange(
currentPage: string,
workspaceId: string | undefined,
onViewModeChange: (mode: string) => void,
) {
const router = useRouter();
return (value: string) => {
if (value === "list") {
if (currentPage !== "tasks") router.push(linkToTasks(workspaceId));
} else if (value === "kanban") {
if (currentPage !== "kanban") router.push("/");
onViewModeChange("");
} else if (value === "pipeline") {
if (currentPage !== "kanban") router.push("/");
onViewModeChange("graph2");
}
};
}
export function KanbanHeader({
onCreateTask,
workspaceId,
currentPage = "kanban",
searchQuery = "",
onSearchChange,
isSearchLoading = false,
}: KanbanHeaderProps) {
const { isMobile, isTablet } = useResponsiveBreakpoint();
const isMenuOpen = useAppStore((state) => state.mobileKanban.isMenuOpen);
const setMenuOpen = useAppStore((state) => state.setMobileKanbanMenuOpen);
const { kanbanViewMode, onViewModeChange } = useKanbanDisplaySettings();
const releaseNotes = useReleaseNotes();
const healthIndicator = useSystemHealthIndicator();
const toggleValue = getToggleValue(currentPage, kanbanViewMode);
const handleViewChange = useHeaderViewChange(currentPage, workspaceId, onViewModeChange);
const indicatorProps = {
showReleaseNotesButton: releaseNotes.showTopbarButton,
onOpenReleaseNotes: releaseNotes.openDialog,
showHealthIndicator: healthIndicator.hasIssues,
onOpenHealthDialog: healthIndicator.openDialog,
};
const sharedSearch = { searchQuery, onSearchChange, isSearchLoading };
const sharedActions = { onCreateTask, workspaceId };
const renderHeader = () => {
if (isMobile) {
return (
<KanbanHeaderMobile
workspaceId={workspaceId}
currentPage={currentPage}
{...sharedSearch}
{...indicatorProps}
/>
);
}
if (isTablet) {
return (
<>
<TabletHeader
{...sharedActions}
{...sharedSearch}
toggleValue={toggleValue}
handleViewChange={handleViewChange}
setMenuOpen={setMenuOpen}
{...indicatorProps}
/>
<MobileMenuSheet
open={isMenuOpen}
onOpenChange={setMenuOpen}
workspaceId={workspaceId}
currentPage={currentPage}
{...sharedSearch}
/>
</>
);
}
return (
<DesktopHeader
{...sharedActions}
{...sharedSearch}
toggleValue={toggleValue}
handleViewChange={handleViewChange}
{...indicatorProps}
/>
);
};
return (
<>
{renderHeader()}
{releaseNotes.hasNotes && (
<ReleaseNotesDialog
open={releaseNotes.dialogOpen}
onOpenChange={releaseNotes.closeDialog}
entries={releaseNotes.unseenEntries}
latestVersion={releaseNotes.latestVersion}
/>
)}
<HealthIssuesDialog
open={healthIndicator.dialogOpen}
onOpenChange={healthIndicator.closeDialog}
issues={healthIndicator.issues}
/>
</>
);
}