mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 09:50:48 +01:00
Fix project sidebar navigation and pinned task expansion (#22264)
Open recent and pinned projects on Tasks and share their expandable task list. Keep project pin and reorder controls at the header. Preserve unread markers and monitoring status through the existing full issue response. Verified 82 focused tests, UI typecheck, production build, token gates, and 58 successful CI checks. Greptile is 5/5 with all threads resolved. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
9b16044bf1
commit
3dffb2c9dd
6 files changed
+295
-27
No files matched your search
@@ -114,6 +114,9 @@ Coordinator Recents lets you pin tasks, agent chats, and projects above More.
|
||||
The pin button appears on the current row or when a row is hovered or focused
|
||||
with the keyboard. Shortcuts share the saved order with pinned pages and stay
|
||||
available as Recents changes.
|
||||
Project links in Recents and pinned navigation open the project's Tasks tab.
|
||||
Both locations have a chevron that shows up to 12 recently updated project tasks.
|
||||
The task list loads when expanded and keeps the task status and unread markers.
|
||||
|
||||
Agent-owned tasks show **In Progress** only while a task-linked run is queued
|
||||
or running. When execution ends, their visible status reflects recovery
|
||||
|
||||
@@ -19,7 +19,7 @@ vi.mock("@/hooks/useAgentChatNavigation", () => ({ useAgentChatNavigation: () =>
|
||||
vi.mock("@/hooks/useRecentTasks", () => ({ useRecentTasks: ({ pinnedTaskIds }: { pinnedTaskIds: string[] }) => ({
|
||||
entries: fixture.recentTasks, pinnedTasks: fixture.taskSummaries.filter(task => pinnedTaskIds.includes(String(task.id))),
|
||||
}) }));
|
||||
vi.mock("@/api/issues", () => ({ issuesApi: { listCompact: fixture.projectTasks } }));
|
||||
vi.mock("@/api/issues", () => ({ issuesApi: { list: fixture.projectTasks } }));
|
||||
vi.mock("@/context/DialogContext", () => ({ useDialogActions: () => ({ openNewIssue: fixture.openNewIssue }) }));
|
||||
vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false, setSidebarOpen: vi.fn() }) }));
|
||||
vi.mock("@/api/attention", () => ({ attentionApi: { list: fixture.attention, summary: fixture.summary } }));
|
||||
@@ -123,7 +123,7 @@ describe("Coordinator task creation", () => {
|
||||
const region = container.querySelector('[role="region"][aria-label="Recents"]')!;
|
||||
const links = Array.from(region.querySelectorAll("a"), link => link.getAttribute("href"));
|
||||
expect(links).toHaveLength(tasks.length + chats.length + 2);
|
||||
expect(links.slice(0, 4)).toEqual(["/projects/project-1", "/projects/project-0", "/issues/TASK-299", "/chats/agent-99"]);
|
||||
expect(links.slice(0, 4)).toEqual(["/projects/project-1/issues", "/projects/project-0/issues", "/issues/TASK-299", "/chats/agent-99"]);
|
||||
expect(links.at(-1)).toBe("/issues/TASK-0");
|
||||
expect(new Set(links).size).toBe(links.length);
|
||||
expect(fixture.projectTasks).not.toHaveBeenCalled();
|
||||
@@ -186,7 +186,7 @@ describe("Coordinator pinned pages", () => {
|
||||
await act(async () => button.click());
|
||||
expect(button.getAttribute("aria-pressed")).toBe("true");
|
||||
}
|
||||
expect(pinnedLinks()).toEqual(["/issues/TASK-1", "/chats/cto", "/projects/launch"]);
|
||||
expect(pinnedLinks()).toEqual(["/issues/TASK-1", "/chats/cto", "/projects/launch/issues"]);
|
||||
fixture.pathname = "/COO/issues";
|
||||
fixture.recentTasks = [];
|
||||
fixture.chats = [];
|
||||
@@ -195,10 +195,10 @@ describe("Coordinator pinned pages", () => {
|
||||
root = createRoot(container);
|
||||
await renderSidebar();
|
||||
expect(container.querySelector('[aria-label="Recents"]')).toBeNull();
|
||||
expect(pinnedLinks()).toEqual(["/issues/TASK-1", "/chats/cto", "/projects/launch"]);
|
||||
expect(pinnedLinks()).toEqual(["/issues/TASK-1", "/chats/cto", "/projects/launch/issues"]);
|
||||
expect(pinnedPage("/issues/TASK-1")?.textContent).toContain("Renamed release task");
|
||||
await click("Unpin Renamed release task");
|
||||
expect(pinnedLinks()).toEqual(["/chats/cto", "/projects/launch"]);
|
||||
expect(pinnedLinks()).toEqual(["/chats/cto", "/projects/launch/issues"]);
|
||||
});
|
||||
it("matches pinned and recent agent avatar dimensions to task status icons", async () => {
|
||||
fixture.agents = [{ id: "cto", companyId: "company", name: "CTO", urlKey: "cto", role: "cto", status: "idle" } as Agent];
|
||||
@@ -237,7 +237,7 @@ describe("Coordinator pinned pages", () => {
|
||||
const items = buildPinnedNavigationItems(bounded(pins), bounded(agents), [], bounded(tasks), bounded(projects));
|
||||
expect(items.map(item => item.key)).toEqual(pins);
|
||||
expect(reads).toBeLessThanOrEqual(4 * pins.length);
|
||||
expect(items.slice(0, 3).map(item => item.to)).toEqual(["/issues/TASK-199", "/projects/project-199", "/chats/agent-199"]);
|
||||
expect(items.slice(0, 3).map(item => item.to)).toEqual(["/issues/TASK-199", "/projects/project-199/issues", "/chats/agent-199"]);
|
||||
});
|
||||
it("keeps mixed pins above More in stored order and prevents native link dragging", async () => {
|
||||
fixture.agents = [{ id: "cto", companyId: "company", name: "CTO", urlKey: "cto", role: "cto", status: "idle" } as Agent];
|
||||
@@ -494,17 +494,141 @@ describe("Coordinator task status glyphs (BUG-07)", () => {
|
||||
expect(glyph("/issues/ONB-1")?.getAttribute("aria-label")).toBe("Blocked · waiting on active sub-task ONB-3");
|
||||
});
|
||||
|
||||
it("shows a recent project as a link without expanding its tasks", async () => {
|
||||
it("opens a recent project on Tasks and keeps its task query lazy", async () => {
|
||||
fixture.projects = [{ id: "project-1", companyId: "company", name: "Onboarding", urlKey: "onboarding" }];
|
||||
fixture.pathname = "/COO/projects/onboarding";
|
||||
await renderSidebar();
|
||||
const region = container.querySelector('[aria-label="Recents"]')!;
|
||||
expect(region.querySelector('a[href="/projects/onboarding"]')?.textContent).toBe("Onboarding");
|
||||
expect(region.querySelector('button[aria-expanded]')).toBeNull();
|
||||
expect(region.querySelector('a[href="/projects/onboarding/issues"]')?.textContent).toBe("Onboarding");
|
||||
expect(region.querySelector('button[aria-expanded="false"]')).not.toBeNull();
|
||||
expect(fixture.projectTasks).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Coordinator project tasks", () => {
|
||||
async function projectRow(pinned: boolean) {
|
||||
fixture.projects = [{ id: "project-1", companyId: "company", name: "Onboarding", urlKey: "onboarding" }];
|
||||
if (pinned) {
|
||||
localStorage.setItem("paperclip.coordinator.pinned-nav.v1:reviewer", JSON.stringify(["project:company:project-1"]));
|
||||
} else {
|
||||
fixture.pathname = "/COO/projects/onboarding/configuration";
|
||||
}
|
||||
await renderSidebar();
|
||||
return container.querySelector(pinned ? ".group\\/coordinator-pin" : '[aria-label="Recents"]')!;
|
||||
}
|
||||
|
||||
it.each([false, true])("opens Tasks and expands tasks beneath the project (pinned: %s)", async pinned => {
|
||||
const task = { id: "project-task", companyId: "company", projectId: "project-1", identifier: "TASK-42", title: "Prepare launch",
|
||||
status: "in_progress", displayStatus: "monitoring", isUnreadForMe: true };
|
||||
fixture.projectTasks.mockResolvedValue([task]);
|
||||
const row = await projectRow(pinned);
|
||||
expect(row.querySelector('a[href="/projects/onboarding/issues"]')?.textContent).toBe("Onboarding");
|
||||
expect(fixture.projectTasks).not.toHaveBeenCalled();
|
||||
const expand = row.querySelector<HTMLButtonElement>('button[aria-label="Expand Onboarding"]')!;
|
||||
expect(expand.closest("a")).toBeNull();
|
||||
await act(async () => expand.click());
|
||||
await flush();
|
||||
expect(expand.getAttribute("aria-expanded")).toBe("true");
|
||||
const tasks = document.getElementById(expand.getAttribute("aria-controls")!)!;
|
||||
expect(tasks.querySelector('a[href="/issues/TASK-42"]')?.textContent).toContain("Prepare launch");
|
||||
expect(tasks.querySelector('[aria-label="Unread"]')).not.toBeNull();
|
||||
expect(tasks.querySelector('svg[role="img"]')?.getAttribute("aria-label")).toBe("Monitoring");
|
||||
expect(fixture.projectTasks).toHaveBeenCalledWith("company", {
|
||||
projectId: "project-1", includeReadState: true, limit: 12, sortField: "updated", sortDir: "desc",
|
||||
}, { signal: expect.any(AbortSignal) });
|
||||
if (pinned) {
|
||||
expect(row.querySelector('[aria-label="Reorder pinned Onboarding"]')?.parentElement)
|
||||
.toBe(row.querySelector('[aria-label="Unpin Onboarding"]')?.parentElement);
|
||||
}
|
||||
await act(async () => expand.click());
|
||||
expect(expand.getAttribute("aria-expanded")).toBe("false");
|
||||
expect(row.querySelector('a[href="/issues/TASK-42"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps an expanded project's task links when it is pinned and unpinned", async () => {
|
||||
fixture.projectTasks.mockResolvedValue([{ id: "task", companyId: "company", projectId: "project-1", identifier: "TASK-42", title: "Prepare launch", status: "todo" }]);
|
||||
const recent = await projectRow(false);
|
||||
await act(async () => recent.querySelector<HTMLButtonElement>('[aria-label="Expand Onboarding"]')!.click());
|
||||
await flush();
|
||||
await act(async () => recent.querySelector<HTMLButtonElement>('[aria-label="Pin Onboarding"]')!.click());
|
||||
const pinned = container.querySelector(".group\\/coordinator-pin")!;
|
||||
await act(async () => pinned.querySelector<HTMLButtonElement>('[aria-label="Expand Onboarding"]')!.click());
|
||||
await flush();
|
||||
expect(pinned.querySelector('a[href="/issues/TASK-42"]')).not.toBeNull();
|
||||
await act(async () => pinned.querySelector<HTMLButtonElement>('[aria-label="Unpin Onboarding"]')!.click());
|
||||
expect(container.querySelector(".group\\/coordinator-pin")).toBeNull();
|
||||
expect(recent.querySelector('a[href="/issues/TASK-42"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("shows loading followed by the empty state", async () => {
|
||||
let resolve!: (tasks: never[]) => void;
|
||||
fixture.projectTasks.mockReturnValue(new Promise<never[]>(done => { resolve = done; }));
|
||||
const row = await projectRow(true);
|
||||
await act(async () => row.querySelector<HTMLButtonElement>('[aria-label="Expand Onboarding"]')!.click());
|
||||
expect(row.querySelector('[role="status"]')?.textContent).toBe("Loading tasks…");
|
||||
await act(async () => resolve([]));
|
||||
await flush();
|
||||
expect(row.textContent).toContain("No tasks yet.");
|
||||
});
|
||||
|
||||
it("reorders an expanded pinned project with the keyboard and keeps its tasks underneath", async () => {
|
||||
fixture.projects = [{ id: "project-1", companyId: "company", name: "Onboarding", urlKey: "onboarding" }];
|
||||
fixture.projectTasks.mockResolvedValue([{ id: "task", companyId: "company", projectId: "project-1", identifier: "TASK-42", title: "Prepare launch", status: "todo" }]);
|
||||
localStorage.setItem("paperclip.coordinator.pinned-nav.v1:reviewer", JSON.stringify(["project:company:project-1", "/artifacts"]));
|
||||
await renderSidebar();
|
||||
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Expand Onboarding"]')!.click());
|
||||
await flush();
|
||||
const nativeRect = HTMLElement.prototype.getBoundingClientRect;
|
||||
const rect = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
|
||||
const rows = [...container.querySelectorAll(".group\\/coordinator-pin")];
|
||||
const index = rows.indexOf(this);
|
||||
if (index < 0) return nativeRect.call(this);
|
||||
const top = index * 80;
|
||||
return { x: 0, y: top, top, bottom: top + 80, left: 0, right: 240, width: 240, height: 80, toJSON() {} };
|
||||
});
|
||||
try {
|
||||
const handle = container.querySelector<HTMLButtonElement>('[aria-label="Reorder pinned Onboarding"]')!;
|
||||
handle.focus();
|
||||
for (const code of ["Space", "ArrowDown", "Space"]) {
|
||||
await act(async () => {
|
||||
handle.dispatchEvent(new KeyboardEvent("keydown", { code, key: code === "Space" ? " " : code, bubbles: true, cancelable: true }));
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
});
|
||||
}
|
||||
const rows = [...container.querySelectorAll(".group\\/coordinator-pin")];
|
||||
expect(rows.map(row => row.querySelector("a")?.getAttribute("href"))).toEqual(["/artifacts", "/projects/onboarding/issues"]);
|
||||
expect(rows[1]!.querySelector('a[href="/issues/TASK-42"]')).not.toBeNull();
|
||||
expect(rows[1]!.querySelector('[aria-label="Collapse Onboarding"]')).not.toBeNull();
|
||||
} finally { rect.mockRestore(); }
|
||||
});
|
||||
|
||||
it("shows a failed task read without removing project navigation", async () => {
|
||||
fixture.projectTasks.mockRejectedValue(new Error("Forbidden"));
|
||||
const row = await projectRow(true);
|
||||
await act(async () => row.querySelector<HTMLButtonElement>('[aria-label="Expand Onboarding"]')!.click());
|
||||
await flush();
|
||||
expect(row.querySelector('[role="alert"]')?.textContent).toBe("Couldn’t load tasks.");
|
||||
expect(row.querySelector('a[href="/projects/onboarding/issues"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("does not reuse another person's expanded task cache", async () => {
|
||||
fixture.projectTasks.mockResolvedValue([{ id: "task", companyId: "company", projectId: "project-1", identifier: "TASK-42", title: "First person's task", status: "todo" }]);
|
||||
const row = await projectRow(false);
|
||||
await act(async () => row.querySelector<HTMLButtonElement>('[aria-label="Expand Onboarding"]')!.click());
|
||||
await flush();
|
||||
expect(row.querySelector('a[href="/issues/TASK-42"]')).not.toBeNull();
|
||||
fixture.userId = "another-person";
|
||||
fixture.projectTasks.mockResolvedValue([]);
|
||||
await renderSidebar();
|
||||
const recent = container.querySelector('[aria-label="Recents"]')!;
|
||||
expect(recent.querySelector('a[href="/issues/TASK-42"]')).toBeNull();
|
||||
await act(async () => recent.querySelector<HTMLButtonElement>('[aria-label="Expand Onboarding"]')!.click());
|
||||
await flush();
|
||||
expect(recent.querySelector('a[href="/issues/TASK-42"]')).toBeNull();
|
||||
expect(recent.textContent).toContain("No tasks yet.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Coordinator with Responsibilities", () => {
|
||||
const primaryLinks = () =>
|
||||
[...container.querySelectorAll('nav[aria-label="Workspace navigation"] .design-sidebar-primary.my-2 > a, nav[aria-label="Workspace navigation"] .design-sidebar-primary.my-2 > div > a')]
|
||||
|
||||
@@ -30,6 +30,7 @@ import { AgentAvatar } from "./AgentAvatar";
|
||||
import { agentChatPinKey } from "./AgentChatPin";
|
||||
import { PinnedNavigationList, type PinnedNavigationItem } from "./PinnedNavigationList";
|
||||
import { companyProjectsQuery } from "@/lib/company-projects-query";
|
||||
import { SidebarProjectTasks } from "./SidebarProjectTasks";
|
||||
|
||||
const NO_RECENT_TASKS: never[] = [];
|
||||
const TASK_PIN_ID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
||||
@@ -69,7 +70,7 @@ export function buildPinnedNavigationItems(
|
||||
}
|
||||
for (const project of projects) {
|
||||
const key = projectPinKey(project);
|
||||
if (keys.has(key)) items.set(key, { key, to: `/projects/${projectRouteRef(project)}`, label: project.name, icon: <FolderOpen className="size-4" /> });
|
||||
if (keys.has(key)) items.set(key, { key, to: `/projects/${projectRouteRef(project)}/issues`, label: project.name, icon: <FolderOpen className="size-4" />, project });
|
||||
}
|
||||
return pins.flatMap(key => {
|
||||
const item = items.get(key);
|
||||
@@ -212,7 +213,7 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity group-hover/coordinator-new:opacity-100 group-focus-within/coordinator-new:opacity-100 pointer-coarse:opacity-100 hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring"><Plus className="size-4" /></button>
|
||||
</div>
|
||||
<SidebarNavItem className="design-sidebar-item" to="/decisions" label="Inbox" icon={Inbox} badge={attentionCount} badgeLabel="decisions" />
|
||||
{orderedPins.length > 0 && <PinnedNavigationList key={`${companyId}:${userId}`} items={orderedPins} onReorder={pinnedNavigation.reorder} onUnpin={pinnedNavigation.toggle} />}
|
||||
{orderedPins.length > 0 && <PinnedNavigationList key={`${companyId}:${userId}`} items={orderedPins} userId={userId} onReorder={pinnedNavigation.reorder} onUnpin={pinnedNavigation.toggle} />}
|
||||
</div>
|
||||
<Flyout open={moreOpen} onOpenChange={setMoreOpen}>
|
||||
<FlyoutTrigger asChild><button type="button" aria-label="More workspace pages" className="design-sidebar-item flex w-auto items-center gap-2.5 rounded-lg py-1.5 text-left transition-colors focus-visible:ring-2 focus-visible:ring-ring"><MoreHorizontal className="size-4 shrink-0" /><span>More</span></button></FlyoutTrigger>
|
||||
@@ -238,9 +239,12 @@ export function CoordinatorSidebar({ children }: { children?: ReactNode }) {
|
||||
? <RecentPinRow key={item.id} pinKey={agentChatPinKey(item.agent.companyId, item.agent.id)} label={item.agent.name} pins={pins}>
|
||||
<SidebarNavItem className="design-sidebar-item" to={`/chats/${encodeURIComponent(agentRouteRef(item.agent))}`} label={item.agent.name} iconNode={<AgentAvatar agent={item.agent} size={16} />} />
|
||||
</RecentPinRow>
|
||||
: <RecentPinRow key={`${scope}:${item.id}`} pinKey={projectPinKey(item.project)} label={item.project.name} pins={pins}>
|
||||
<SidebarNavItem className="design-sidebar-item" to={`/projects/${projectRouteRef(item.project)}`} label={item.project.name} icon={FolderOpen} />
|
||||
</RecentPinRow>)}
|
||||
: <SidebarProjectTasks key={`${scope}:${item.id}`} project={item.project} userId={userId}
|
||||
renderTask={task => <RecentTaskPinRow task={task} pins={pins} />}>
|
||||
<RecentPinRow pinKey={projectPinKey(item.project)} label={item.project.name} pins={pins}>
|
||||
<SidebarNavItem className="design-sidebar-item" to={`/projects/${projectRouteRef(item.project)}/issues`} label={item.project.name} icon={FolderOpen} />
|
||||
</RecentPinRow>
|
||||
</SidebarProjectTasks>)}
|
||||
</RecentNavigationList>
|
||||
</SidebarSection></div>}
|
||||
{children}
|
||||
|
||||
@@ -6,6 +6,8 @@ import { GripVertical, PinOff } from "lucide-react";
|
||||
import { RecentTaskNavItem } from "./RecentTaskNavItem";
|
||||
import { SidebarNavItem } from "./SidebarNavItem";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { Project } from "@paperclipai/shared";
|
||||
import { SidebarProjectTasks } from "./SidebarProjectTasks";
|
||||
|
||||
export interface PinnedNavigationItem {
|
||||
key: string;
|
||||
@@ -13,33 +15,39 @@ export interface PinnedNavigationItem {
|
||||
label: string;
|
||||
icon: ReactNode;
|
||||
task?: { id: string; identifier: string | null; isUnreadForMe?: boolean };
|
||||
project?: Pick<Project, "id" | "companyId" | "name">;
|
||||
}
|
||||
|
||||
/** Keep this row mounted when a pin is toggled so its controls retain focus. */
|
||||
export function SortablePinnedRow({ id, label, disabled = false, className, handleClassName, handleIconClassName, children, ...props }: Omit<ComponentPropsWithoutRef<"div">, "id"> & {
|
||||
export function SortablePinnedRow({ id, label, disabled = false, className, handleClassName, handleIconClassName, children, ...props }: Omit<ComponentPropsWithoutRef<"div">, "id" | "children"> & {
|
||||
id: string; label: string; disabled?: boolean; handleClassName: string; handleIconClassName: string;
|
||||
children: ReactNode | ((handle: ReactNode) => ReactNode);
|
||||
}) {
|
||||
const sortable = useSortable({ id, disabled, transition: null });
|
||||
const handle = !disabled && <button ref={sortable.setActivatorNodeRef} type="button" {...sortable.attributes} {...sortable.listeners}
|
||||
aria-label={`Reorder pinned ${label}`} title={`Drag to reorder ${label}`}
|
||||
className={cn("absolute top-1/2 flex -translate-y-1/2 touch-none cursor-grab items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity active:cursor-grabbing hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:opacity-100", handleClassName)}>
|
||||
<GripVertical aria-hidden className={handleIconClassName} />
|
||||
</button>;
|
||||
return <div {...props} ref={sortable.setNodeRef} style={{ transform: CSS.Transform.toString(sortable.transform) }}
|
||||
className={cn(className, !disabled && "select-none", !sortable.isDragging && "motion-safe:transition-transform", sortable.isDragging && "z-10 opacity-80")}
|
||||
onDragStart={disabled ? undefined : event => event.preventDefault()}>
|
||||
{children}
|
||||
{!disabled && <button ref={sortable.setActivatorNodeRef} type="button" {...sortable.attributes} {...sortable.listeners}
|
||||
aria-label={`Reorder pinned ${label}`} title={`Drag to reorder ${label}`}
|
||||
className={cn("absolute top-1/2 flex -translate-y-1/2 touch-none cursor-grab items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity active:cursor-grabbing hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring pointer-coarse:opacity-100", handleClassName)}>
|
||||
<GripVertical aria-hidden className={handleIconClassName} />
|
||||
</button>}
|
||||
{typeof children === "function" ? children(handle) : <>{children}{handle}</>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function PinnedItem({ item, onUnpin }: { item: PinnedNavigationItem; onUnpin: (key: string) => void }) {
|
||||
function PinnedItem({ item, userId, onUnpin }: { item: PinnedNavigationItem; userId?: string | null; onUnpin: (key: string) => void }) {
|
||||
const link = { to: item.to, label: item.label, iconNode: item.icon, className: "design-sidebar-item design-sidebar-pinned-item group-hover/coordinator-pin:bg-sidebar-accent" };
|
||||
return <SortablePinnedRow id={item.key} label={item.label} className="group/coordinator-pin relative"
|
||||
handleClassName="right-3 size-7 group-hover/coordinator-pin:opacity-100 group-focus-within/coordinator-pin:opacity-100" handleIconClassName="size-3.5">
|
||||
const row = (handle: ReactNode) => <>
|
||||
{item.task ? <RecentTaskNavItem {...link} task={item.task} /> : <SidebarNavItem {...link} />}
|
||||
<button type="button" aria-label={`Unpin ${item.label}`} title={`Unpin ${item.label}`}
|
||||
onMouseDown={event => event.stopPropagation()} onClick={() => onUnpin(item.key)}
|
||||
className="absolute right-10 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-sidebar-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring group-hover/coordinator-pin:opacity-100 group-focus-within/coordinator-pin:opacity-100 pointer-coarse:opacity-100"><PinOff className="size-3.5" /></button>
|
||||
{handle}
|
||||
</>;
|
||||
return <SortablePinnedRow id={item.key} label={item.label} className="group/coordinator-pin relative"
|
||||
handleClassName="right-3 size-7 group-hover/coordinator-pin:opacity-100 group-focus-within/coordinator-pin:opacity-100" handleIconClassName="size-3.5">
|
||||
{handle => item.project ? <SidebarProjectTasks project={item.project} userId={userId}>{row(handle)}</SidebarProjectTasks> : row(handle)}
|
||||
</SortablePinnedRow>;
|
||||
}
|
||||
|
||||
@@ -62,10 +70,10 @@ export function SortablePinnedList({ keys, onReorder, children }: {
|
||||
</DndContext>;
|
||||
}
|
||||
|
||||
export function PinnedNavigationList({ items, onReorder, onUnpin }: {
|
||||
items: PinnedNavigationItem[]; onReorder: (keys: string[]) => void; onUnpin: (key: string) => void;
|
||||
export function PinnedNavigationList({ items, userId, onReorder, onUnpin }: {
|
||||
items: PinnedNavigationItem[]; userId?: string | null; onReorder: (keys: string[]) => void; onUnpin: (key: string) => void;
|
||||
}) {
|
||||
return <SortablePinnedList keys={items.map(item => item.key)} onReorder={onReorder}>
|
||||
{items.map(item => <PinnedItem key={item.key} item={item} onUnpin={onUnpin} />)}
|
||||
{items.map(item => <PinnedItem key={item.key} item={item} userId={userId} onUnpin={onUnpin} />)}
|
||||
</SortablePinnedList>;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, type ReactNode } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { SidebarProjectTasks } from "./SidebarProjectTasks";
|
||||
import { TooltipProvider } from "./ui/tooltip";
|
||||
|
||||
vi.mock("@/context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false, setSidebarOpen: vi.fn() }) }));
|
||||
vi.mock("@/lib/router", () => ({
|
||||
NavLink: ({ to, children, className, state: _state, end: _end, ...props }: {
|
||||
to: string; children: ReactNode; className?: string | ((state: { isActive: boolean }) => string); state?: unknown; end?: boolean;
|
||||
}) => <a href={to} className={typeof className === "function" ? className({ isActive: false }) : className} {...props}>{children}</a>,
|
||||
}));
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
let root: Root, container: HTMLDivElement, client: QueryClient;
|
||||
const fetchMock = vi.fn<typeof fetch>();
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
});
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
client.clear();
|
||||
container.remove();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
async function expandProject() {
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><TooltipProvider>
|
||||
<SidebarProjectTasks project={{ id: "project", companyId: "company", name: "Launch" }} userId="viewer">
|
||||
<a href="/projects/launch/issues">Launch</a>
|
||||
</SidebarProjectTasks>
|
||||
</TooltipProvider></QueryClientProvider>));
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Expand Launch"]')!.click());
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
|
||||
}
|
||||
|
||||
describe("SidebarProjectTasks API contract", () => {
|
||||
it("requests full task rows with read state and renders their monitoring and unread fields", async () => {
|
||||
fetchMock.mockImplementation(async input => {
|
||||
const params = new URL(String(input), "https://paperclip.test").searchParams;
|
||||
const full = params.get("view") === null;
|
||||
const readState = params.get("includeReadState") === "true";
|
||||
return new Response(JSON.stringify([
|
||||
{ id: "monitor", companyId: "company", projectId: "project", identifier: "TASK-1", title: "Watching launch", status: "in_progress",
|
||||
...(full ? { displayStatus: "monitoring" } : {}), ...(readState ? { isUnreadForMe: true } : {}) },
|
||||
{ id: "read", companyId: "company", projectId: "project", identifier: "TASK-2", title: "Reviewed task", status: "todo",
|
||||
...(readState ? { isUnreadForMe: false } : {}) },
|
||||
]), { headers: { "Content-Type": "application/json" } });
|
||||
});
|
||||
await expandProject();
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
const [input, options] = fetchMock.mock.calls[0]!;
|
||||
const url = new URL(String(input), "https://paperclip.test");
|
||||
expect(url.pathname).toBe("/api/companies/company/issues");
|
||||
expect(Object.fromEntries(url.searchParams)).toEqual({
|
||||
projectId: "project", includeReadState: "true", limit: "12", sortField: "updated", sortDir: "desc",
|
||||
});
|
||||
expect(options?.credentials).toBe("include");
|
||||
const monitoring = container.querySelector('a[href="/issues/TASK-1"]')!;
|
||||
expect(monitoring.querySelector('[aria-label="Unread"]')).not.toBeNull();
|
||||
expect(monitoring.querySelector('svg[role="img"]')?.getAttribute("aria-label")).toBe("Monitoring");
|
||||
const read = container.querySelector('a[href="/issues/TASK-2"]')!;
|
||||
expect(read.querySelector('[aria-label="Unread"]')).toBeNull();
|
||||
expect(read.querySelector('svg[role="img"]')?.getAttribute("aria-label")).toBe("Todo");
|
||||
});
|
||||
|
||||
it("shows a denied read without rendering task data", async () => {
|
||||
fetchMock.mockResolvedValue(new Response(JSON.stringify({ error: "Forbidden" }), {
|
||||
status: 403, headers: { "Content-Type": "application/json" },
|
||||
}));
|
||||
await expandProject();
|
||||
expect(container.querySelector('[role="alert"]')?.textContent).toBe("Couldn’t load tasks.");
|
||||
expect(container.querySelector('a[href^="/issues/"]')).toBeNull();
|
||||
expect(container.querySelector('a[href="/projects/launch/issues"]')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useId, useState, type ReactNode } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { ChevronRight } from "lucide-react";
|
||||
import type { Issue, Project } from "@paperclipai/shared";
|
||||
import { issuesApi } from "@/api/issues";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { taskStatusIconProps } from "@/lib/task-status-presentation";
|
||||
import { RecentTaskNavItem } from "./RecentTaskNavItem";
|
||||
import { StatusIcon } from "./StatusIcon";
|
||||
|
||||
export function SidebarProjectTasks({ project, userId, children, renderTask }: {
|
||||
project: Pick<Project, "id" | "companyId" | "name">;
|
||||
userId?: string | null;
|
||||
children: ReactNode;
|
||||
renderTask?: (task: Issue) => ReactNode;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const contentId = useId();
|
||||
const { data: tasks, isPending, error } = useQuery({
|
||||
queryKey: [...queryKeys.issues.listByProject(project.companyId, project.id), "sidebar-tasks", userId ?? "__local_board__"],
|
||||
queryFn: ({ signal }) => issuesApi.list(project.companyId, {
|
||||
projectId: project.id, includeReadState: true, limit: 12, sortField: "updated", sortDir: "desc",
|
||||
}, { signal }),
|
||||
enabled: expanded,
|
||||
});
|
||||
return <div>
|
||||
<div className="flex min-w-0 items-center">
|
||||
<div className="relative min-w-0 flex-1">{children}</div>
|
||||
<button type="button" aria-label={`${expanded ? "Collapse" : "Expand"} ${project.name}`} aria-expanded={expanded} aria-controls={contentId}
|
||||
className="mr-2 flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => setExpanded(previous => !previous)}>
|
||||
<ChevronRight aria-hidden className={cn("size-3.5 transition-transform", expanded && "rotate-90")} />
|
||||
</button>
|
||||
</div>
|
||||
{expanded && <div id={contentId} className="ml-5 border-l border-border pl-1">
|
||||
{isPending ? <p className="px-3 py-2 text-xs text-muted-foreground" role="status">Loading tasks…</p>
|
||||
: error ? <p className="px-3 py-2 text-xs text-muted-foreground" role="alert">Couldn’t load tasks.</p>
|
||||
: tasks?.length ? tasks.map(task => <div key={task.id}>{renderTask ? renderTask(task)
|
||||
: <RecentTaskNavItem className="design-sidebar-item" task={task} label={task.title} iconNode={<StatusIcon {...taskStatusIconProps(task)} />} />}</div>)
|
||||
: <p className="px-3 py-2 text-xs text-muted-foreground">No tasks yet.</p>}
|
||||
</div>}
|
||||
</div>;
|
||||
}
|
||||
Reference in new issue
Block a user