mirror of
https://github.com/alkimake/paperclip.git
synced 2026-06-14 01:50:39 +09:00
Add shared sidebar section controls (#5585)
## Thinking Path > - Paperclip is the control plane for AI-agent companies. > - The board UI sidebar is one of the main ways operators scan active agents and projects. > - Agents and projects had duplicated section header behavior, which made collapse controls, add actions, and future section menus harder to keep consistent. > - Operators also need lightweight ways to switch between their curated sidebar order and common scan orders like alphabetical or recent activity. > - This pull request introduces a shared sidebar section header and uses it for the Agents and Projects sidebar sections. > - The benefit is a more consistent sidebar surface with reusable header controls and persisted sort modes without losing the existing drag-ordered Top view. ## What Changed - Added a reusable `SidebarSection` component that supports collapsible content, header actions, and section dropdown menus. - Updated the Agents sidebar section to use the shared header and add persisted `Top`, `Alphabetical`, and `Recent` sort modes. - Updated the Projects sidebar section to use the shared header and add persisted `Top`, `Alphabetical`, and `Recent` sort modes. - Added local-storage helpers and cross-tab update events for agent/project sidebar sort preferences. - Added focused component coverage for the shared section behavior and the updated Agents/Projects sidebar ordering paths. ## Verification - `pnpm run preflight:workspace-links && pnpm exec vitest run ui/src/components/SidebarSection.test.tsx ui/src/components/SidebarProjects.test.tsx ui/src/components/SidebarAgents.test.tsx` - 3 test files passed - 18 tests passed ## Risks - Low-to-moderate UI risk: this changes sidebar section header interactions and adds persisted client-side sort preferences. - Drag ordering is intentionally limited to `Top` mode; non-top modes render sorted lists and do not persist drag order changes. - No database migrations or API contract changes. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - OpenAI Codex coding agent, GPT-5-based model, tool-use enabled; exact hosted model build/context-window identifier was not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] If this change affects the UI, I have included before/after screenshots - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
parent
433dfed33d
commit
e3af7aa489
8 changed files with 1345 additions and 189 deletions
|
|
@ -145,6 +145,34 @@ async function openAgentMenu(label = "Open actions for Alpha") {
|
||||||
await flushReact();
|
await flushReact();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function openAgentsSectionMenu() {
|
||||||
|
const trigger = document.body.querySelector('button[aria-label="Agents section actions"]');
|
||||||
|
expect(trigger).not.toBeNull();
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
trigger?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
|
||||||
|
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function chooseSortMode(label: string) {
|
||||||
|
const item = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))
|
||||||
|
.find((element) => element.textContent?.includes(label));
|
||||||
|
expect(item).toBeTruthy();
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
item?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
}
|
||||||
|
|
||||||
|
function agentLinkLabels(container: HTMLElement) {
|
||||||
|
return Array.from(container.querySelectorAll('a[href^="/agents/"]'))
|
||||||
|
.map((anchor) => anchor.textContent?.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
describe("SidebarAgents", () => {
|
describe("SidebarAgents", () => {
|
||||||
let container: HTMLDivElement;
|
let container: HTMLDivElement;
|
||||||
let root: ReturnType<typeof createRoot> | null;
|
let root: ReturnType<typeof createRoot> | null;
|
||||||
|
|
@ -165,6 +193,7 @@ describe("SidebarAgents", () => {
|
||||||
user: { id: "user-1" },
|
user: { id: "user-1" },
|
||||||
});
|
});
|
||||||
mockHeartbeatsApi.liveRunsForCompany.mockResolvedValue([]);
|
mockHeartbeatsApi.liveRunsForCompany.mockResolvedValue([]);
|
||||||
|
localStorage.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(async () => {
|
afterEach(async () => {
|
||||||
|
|
@ -177,10 +206,11 @@ describe("SidebarAgents", () => {
|
||||||
queryClient.clear();
|
queryClient.clear();
|
||||||
container.remove();
|
container.remove();
|
||||||
document.body.innerHTML = "";
|
document.body.innerHTML = "";
|
||||||
|
localStorage.clear();
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("shows edit and pause actions for an active sidebar agent", async () => {
|
async function renderSidebarAgents() {
|
||||||
const currentRoot = createRoot(container);
|
const currentRoot = createRoot(container);
|
||||||
root = currentRoot;
|
root = currentRoot;
|
||||||
|
|
||||||
|
|
@ -192,6 +222,97 @@ describe("SidebarAgents", () => {
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
await flushReact();
|
await flushReact();
|
||||||
|
}
|
||||||
|
|
||||||
|
it("keeps top mode in stored org-aware order", async () => {
|
||||||
|
localStorage.setItem("paperclip.agentOrder:company-1:user-1", JSON.stringify(["agent-b", "agent-a", "agent-c"]));
|
||||||
|
mockAgentsApi.list.mockResolvedValue([
|
||||||
|
makeAgent({ id: "agent-a", name: "Alpha", urlKey: "alpha" }),
|
||||||
|
makeAgent({ id: "agent-b", name: "Bravo", urlKey: "bravo" }),
|
||||||
|
makeAgent({ id: "agent-c", name: "Charlie", urlKey: "charlie" }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await renderSidebarAgents();
|
||||||
|
|
||||||
|
expect(agentLinkLabels(container)).toEqual(["Bravo", "Alpha", "Charlie"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses the heading for section menu and the plus button for agent creation", async () => {
|
||||||
|
await renderSidebarAgents();
|
||||||
|
|
||||||
|
const sectionMenuTrigger = container.querySelector('button[aria-label="Agents section actions"]');
|
||||||
|
expect(sectionMenuTrigger?.textContent).toContain("Agents");
|
||||||
|
expect(sectionMenuTrigger?.querySelector("svg")).toBeNull();
|
||||||
|
|
||||||
|
const newAgentButton = container.querySelector('button[aria-label="New agent"]');
|
||||||
|
expect(newAgentButton).toBeTruthy();
|
||||||
|
await act(async () => {
|
||||||
|
newAgentButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
});
|
||||||
|
expect(mockOpenNewAgent).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
await openAgentsSectionMenu();
|
||||||
|
|
||||||
|
const newAgentItem = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
|
||||||
|
.find((element) => element.textContent?.includes("New agent"));
|
||||||
|
expect(newAgentItem).toBeFalsy();
|
||||||
|
const browseLink = Array.from(document.body.querySelectorAll("a"))
|
||||||
|
.find((element) => element.textContent?.includes("Browse agents"));
|
||||||
|
expect(browseLink?.getAttribute("href")).toBe("/agents/all");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sorts alphabetically and persists the selected mode per company and user", async () => {
|
||||||
|
mockAgentsApi.list.mockResolvedValue([
|
||||||
|
makeAgent({ id: "agent-c", name: "Charlie", urlKey: "charlie" }),
|
||||||
|
makeAgent({ id: "agent-a", name: "Alpha", urlKey: "alpha" }),
|
||||||
|
makeAgent({ id: "agent-b", name: "Bravo", urlKey: "bravo" }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await renderSidebarAgents();
|
||||||
|
await openAgentsSectionMenu();
|
||||||
|
await chooseSortMode("Alphabetical");
|
||||||
|
|
||||||
|
expect(agentLinkLabels(container)).toEqual(["Alpha", "Bravo", "Charlie"]);
|
||||||
|
expect(localStorage.getItem("paperclip.agentSortMode:company-1:user-1")).toBe("alphabetical");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sorts recent agents by heartbeat, updated time, and created time descending", async () => {
|
||||||
|
mockAgentsApi.list.mockResolvedValue([
|
||||||
|
makeAgent({
|
||||||
|
id: "agent-a",
|
||||||
|
name: "Alpha",
|
||||||
|
urlKey: "alpha",
|
||||||
|
lastHeartbeatAt: null,
|
||||||
|
updatedAt: new Date("2026-01-20T00:00:00Z"),
|
||||||
|
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||||
|
}),
|
||||||
|
makeAgent({
|
||||||
|
id: "agent-b",
|
||||||
|
name: "Bravo",
|
||||||
|
urlKey: "bravo",
|
||||||
|
lastHeartbeatAt: new Date("2026-01-10T00:00:00Z"),
|
||||||
|
updatedAt: new Date("2026-01-02T00:00:00Z"),
|
||||||
|
createdAt: new Date("2026-01-02T00:00:00Z"),
|
||||||
|
}),
|
||||||
|
makeAgent({
|
||||||
|
id: "agent-c",
|
||||||
|
name: "Charlie",
|
||||||
|
urlKey: "charlie",
|
||||||
|
lastHeartbeatAt: null,
|
||||||
|
updatedAt: new Date("2026-01-20T00:00:00Z"),
|
||||||
|
createdAt: new Date("2026-01-03T00:00:00Z"),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
await renderSidebarAgents();
|
||||||
|
await openAgentsSectionMenu();
|
||||||
|
await chooseSortMode("Recent");
|
||||||
|
|
||||||
|
expect(agentLinkLabels(container)).toEqual(["Bravo", "Charlie", "Alpha"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows edit and pause actions for an active sidebar agent", async () => {
|
||||||
|
await renderSidebarAgents();
|
||||||
await openAgentMenu();
|
await openAgentMenu();
|
||||||
|
|
||||||
const editLink = Array.from(document.body.querySelectorAll("a"))
|
const editLink = Array.from(document.body.querySelectorAll("a"))
|
||||||
|
|
@ -216,17 +337,8 @@ describe("SidebarAgents", () => {
|
||||||
mockAgentsApi.list.mockResolvedValue([
|
mockAgentsApi.list.mockResolvedValue([
|
||||||
makeAgent({ status: "paused", pauseReason: "manual", pausedAt: new Date("2026-01-02T00:00:00Z") }),
|
makeAgent({ status: "paused", pauseReason: "manual", pausedAt: new Date("2026-01-02T00:00:00Z") }),
|
||||||
]);
|
]);
|
||||||
const currentRoot = createRoot(container);
|
|
||||||
root = currentRoot;
|
|
||||||
|
|
||||||
await act(async () => {
|
await renderSidebarAgents();
|
||||||
currentRoot.render(
|
|
||||||
<QueryClientProvider client={queryClient}>
|
|
||||||
<SidebarAgents />
|
|
||||||
</QueryClientProvider>,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
await flushReact();
|
|
||||||
await openAgentMenu();
|
await openAgentMenu();
|
||||||
|
|
||||||
const resumeItem = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
|
const resumeItem = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
|
||||||
|
|
@ -248,17 +360,8 @@ describe("SidebarAgents", () => {
|
||||||
makeAgent({ id: "agent-2", name: "Beta", urlKey: "beta" }),
|
makeAgent({ id: "agent-2", name: "Beta", urlKey: "beta" }),
|
||||||
]);
|
]);
|
||||||
mockAgentsApi.pause.mockImplementation(() => new Promise(() => {}));
|
mockAgentsApi.pause.mockImplementation(() => new Promise(() => {}));
|
||||||
const currentRoot = createRoot(container);
|
|
||||||
root = currentRoot;
|
|
||||||
|
|
||||||
await act(async () => {
|
await renderSidebarAgents();
|
||||||
currentRoot.render(
|
|
||||||
<QueryClientProvider client={queryClient}>
|
|
||||||
<SidebarAgents />
|
|
||||||
</QueryClientProvider>,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
await flushReact();
|
|
||||||
await openAgentMenu();
|
await openAgentMenu();
|
||||||
|
|
||||||
const pauseItem = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
|
const pauseItem = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
|
||||||
|
|
@ -287,17 +390,8 @@ describe("SidebarAgents", () => {
|
||||||
pausedAt: new Date("2026-01-02T00:00:00Z"),
|
pausedAt: new Date("2026-01-02T00:00:00Z"),
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
const currentRoot = createRoot(container);
|
|
||||||
root = currentRoot;
|
|
||||||
|
|
||||||
await act(async () => {
|
await renderSidebarAgents();
|
||||||
currentRoot.render(
|
|
||||||
<QueryClientProvider client={queryClient}>
|
|
||||||
<SidebarAgents />
|
|
||||||
</QueryClientProvider>,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
await flushReact();
|
|
||||||
await openAgentMenu();
|
await openAgentMenu();
|
||||||
|
|
||||||
const budgetPausedItem = Array.from(
|
const budgetPausedItem = Array.from(
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,13 @@
|
||||||
import { useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { Link, NavLink, useLocation } from "@/lib/router";
|
import { Link, NavLink, useLocation } from "@/lib/router";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
ChevronRight,
|
|
||||||
MoreHorizontal,
|
MoreHorizontal,
|
||||||
PauseCircle,
|
PauseCircle,
|
||||||
Pencil,
|
Pencil,
|
||||||
PlayCircle,
|
PlayCircle,
|
||||||
Plus,
|
Plus,
|
||||||
|
Users,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useCompany } from "../context/CompanyContext";
|
import { useCompany } from "../context/CompanyContext";
|
||||||
import { useDialogActions } from "../context/DialogContext";
|
import { useDialogActions } from "../context/DialogContext";
|
||||||
|
|
@ -20,14 +20,18 @@ import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
|
||||||
import { queryKeys } from "../lib/queryKeys";
|
import { queryKeys } from "../lib/queryKeys";
|
||||||
import { cn, agentRouteRef, agentUrl } from "../lib/utils";
|
import { cn, agentRouteRef, agentUrl } from "../lib/utils";
|
||||||
import { useAgentOrder } from "../hooks/useAgentOrder";
|
import { useAgentOrder } from "../hooks/useAgentOrder";
|
||||||
|
import {
|
||||||
|
AGENT_SORT_MODE_UPDATED_EVENT,
|
||||||
|
getAgentSortModeStorageKey,
|
||||||
|
readAgentSortMode,
|
||||||
|
type AgentSortModeUpdatedDetail,
|
||||||
|
type AgentSidebarSortMode,
|
||||||
|
writeAgentSortMode,
|
||||||
|
} from "../lib/agent-order";
|
||||||
import { AgentIcon } from "./AgentIconPicker";
|
import { AgentIcon } from "./AgentIconPicker";
|
||||||
import { BudgetSidebarMarker } from "./BudgetSidebarMarker";
|
import { BudgetSidebarMarker } from "./BudgetSidebarMarker";
|
||||||
|
import { SidebarSection, type SidebarSectionRadioChoice } from "./SidebarSection";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
|
||||||
Collapsible,
|
|
||||||
CollapsibleContent,
|
|
||||||
CollapsibleTrigger,
|
|
||||||
} from "@/components/ui/collapsible";
|
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
|
|
@ -37,6 +41,41 @@ import {
|
||||||
} from "@/components/ui/dropdown-menu";
|
} from "@/components/ui/dropdown-menu";
|
||||||
import type { Agent } from "@paperclipai/shared";
|
import type { Agent } from "@paperclipai/shared";
|
||||||
|
|
||||||
|
const AGENT_SORT_CHOICES: SidebarSectionRadioChoice[] = [
|
||||||
|
{ value: "top", label: "Top" },
|
||||||
|
{ value: "alphabetical", label: "Alphabetical" },
|
||||||
|
{ value: "recent", label: "Recent" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function agentTimestamp(agent: Agent, field: "lastHeartbeatAt" | "updatedAt" | "createdAt"): number {
|
||||||
|
const raw = agent[field];
|
||||||
|
if (!raw) return 0;
|
||||||
|
const time = new Date(raw).getTime();
|
||||||
|
return Number.isFinite(time) ? time : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortAgents(agents: Agent[], sortMode: AgentSidebarSortMode): Agent[] {
|
||||||
|
if (sortMode === "top") return agents;
|
||||||
|
const sorted = [...agents];
|
||||||
|
if (sortMode === "alphabetical") {
|
||||||
|
sorted.sort((left, right) => left.name.localeCompare(right.name, undefined, { sensitivity: "base" }));
|
||||||
|
return sorted;
|
||||||
|
}
|
||||||
|
sorted.sort((left, right) => {
|
||||||
|
const heartbeatDiff = agentTimestamp(right, "lastHeartbeatAt") - agentTimestamp(left, "lastHeartbeatAt");
|
||||||
|
if (heartbeatDiff !== 0) return heartbeatDiff;
|
||||||
|
|
||||||
|
const updatedDiff = agentTimestamp(right, "updatedAt") - agentTimestamp(left, "updatedAt");
|
||||||
|
if (updatedDiff !== 0) return updatedDiff;
|
||||||
|
|
||||||
|
const createdDiff = agentTimestamp(right, "createdAt") - agentTimestamp(left, "createdAt");
|
||||||
|
return createdDiff !== 0
|
||||||
|
? createdDiff
|
||||||
|
: left.name.localeCompare(right.name, undefined, { sensitivity: "base" });
|
||||||
|
});
|
||||||
|
return sorted;
|
||||||
|
}
|
||||||
|
|
||||||
function SidebarAgentItem({
|
function SidebarAgentItem({
|
||||||
activeAgentId,
|
activeAgentId,
|
||||||
activeTab,
|
activeTab,
|
||||||
|
|
@ -195,16 +234,69 @@ export function SidebarAgents() {
|
||||||
return filtered;
|
return filtered;
|
||||||
}, [agents]);
|
}, [agents]);
|
||||||
const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;
|
const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;
|
||||||
|
const sortModeStorageKey = useMemo(() => {
|
||||||
|
if (!selectedCompanyId) return null;
|
||||||
|
return getAgentSortModeStorageKey(selectedCompanyId, currentUserId);
|
||||||
|
}, [currentUserId, selectedCompanyId]);
|
||||||
|
const [sortMode, setSortMode] = useState<AgentSidebarSortMode>(() => {
|
||||||
|
if (!sortModeStorageKey) return "top";
|
||||||
|
return readAgentSortMode(sortModeStorageKey);
|
||||||
|
});
|
||||||
const { orderedAgents } = useAgentOrder({
|
const { orderedAgents } = useAgentOrder({
|
||||||
agents: visibleAgents,
|
agents: visibleAgents,
|
||||||
companyId: selectedCompanyId,
|
companyId: selectedCompanyId,
|
||||||
userId: currentUserId,
|
userId: currentUserId,
|
||||||
});
|
});
|
||||||
|
const sortedAgents = useMemo(
|
||||||
|
() => sortAgents(orderedAgents, sortMode),
|
||||||
|
[orderedAgents, sortMode],
|
||||||
|
);
|
||||||
|
|
||||||
const agentMatch = location.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/);
|
const agentMatch = location.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/);
|
||||||
const activeAgentId = agentMatch?.[1] ?? null;
|
const activeAgentId = agentMatch?.[1] ?? null;
|
||||||
const activeTab = agentMatch?.[2] ?? null;
|
const activeTab = agentMatch?.[2] ?? null;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!sortModeStorageKey) {
|
||||||
|
setSortMode("top");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSortMode(readAgentSortMode(sortModeStorageKey));
|
||||||
|
}, [sortModeStorageKey]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!sortModeStorageKey) return;
|
||||||
|
|
||||||
|
const onStorage = (event: StorageEvent) => {
|
||||||
|
if (event.key !== sortModeStorageKey) return;
|
||||||
|
setSortMode(readAgentSortMode(sortModeStorageKey));
|
||||||
|
};
|
||||||
|
const onCustomEvent = (event: Event) => {
|
||||||
|
const detail = (event as CustomEvent<AgentSortModeUpdatedDetail>).detail;
|
||||||
|
if (!detail || detail.storageKey !== sortModeStorageKey) return;
|
||||||
|
setSortMode(detail.sortMode);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener("storage", onStorage);
|
||||||
|
window.addEventListener(AGENT_SORT_MODE_UPDATED_EVENT, onCustomEvent);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("storage", onStorage);
|
||||||
|
window.removeEventListener(AGENT_SORT_MODE_UPDATED_EVENT, onCustomEvent);
|
||||||
|
};
|
||||||
|
}, [sortModeStorageKey]);
|
||||||
|
|
||||||
|
const persistSortMode = useCallback(
|
||||||
|
(value: string) => {
|
||||||
|
const nextSortMode: AgentSidebarSortMode =
|
||||||
|
value === "alphabetical" || value === "recent" ? value : "top";
|
||||||
|
setSortMode(nextSortMode);
|
||||||
|
if (sortModeStorageKey) {
|
||||||
|
writeAgentSortMode(sortModeStorageKey, nextSortMode);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[sortModeStorageKey],
|
||||||
|
);
|
||||||
|
|
||||||
const pauseResumeAgent = useMutation({
|
const pauseResumeAgent = useMutation({
|
||||||
mutationFn: ({ agent, action }: { agent: Agent; action: "pause" | "resume" }) =>
|
mutationFn: ({ agent, action }: { agent: Agent; action: "pause" | "resume" }) =>
|
||||||
action === "pause"
|
action === "pause"
|
||||||
|
|
@ -252,53 +344,42 @@ export function SidebarAgents() {
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Collapsible open={open} onOpenChange={setOpen}>
|
<SidebarSection
|
||||||
<div className="group">
|
label="Agents"
|
||||||
<div className="flex items-center px-3 py-1.5">
|
collapsible={{ open, onOpenChange: setOpen }}
|
||||||
<CollapsibleTrigger className="flex items-center gap-1 flex-1 min-w-0">
|
headerAction={{
|
||||||
<ChevronRight
|
ariaLabel: "New agent",
|
||||||
className={cn(
|
icon: Plus,
|
||||||
"h-3 w-3 text-muted-foreground/60 transition-transform opacity-0 group-hover:opacity-100",
|
onClick: openNewAgent,
|
||||||
open && "rotate-90"
|
}}
|
||||||
)}
|
menu={{
|
||||||
/>
|
ariaLabel: "Agents section actions",
|
||||||
<span className="text-[10px] font-medium uppercase tracking-widest font-mono text-muted-foreground/60">
|
actions: [
|
||||||
Agents
|
{ type: "item", label: "Browse agents", icon: Users, href: "/agents/all" },
|
||||||
</span>
|
{ type: "separator" },
|
||||||
</CollapsibleTrigger>
|
],
|
||||||
<button
|
radioLabel: "Agent sort",
|
||||||
onClick={(e) => {
|
radioChoices: AGENT_SORT_CHOICES,
|
||||||
e.stopPropagation();
|
radioValue: sortMode,
|
||||||
openNewAgent();
|
onRadioValueChange: persistSortMode,
|
||||||
}}
|
}}
|
||||||
className="flex items-center justify-center h-4 w-4 rounded text-muted-foreground/60 hover:text-foreground hover:bg-accent/50 transition-colors"
|
>
|
||||||
aria-label="New agent"
|
{sortedAgents.map((agent: Agent) => {
|
||||||
>
|
const runCount = liveCountByAgent.get(agent.id) ?? 0;
|
||||||
<Plus className="h-3 w-3" />
|
return (
|
||||||
</button>
|
<SidebarAgentItem
|
||||||
</div>
|
key={agent.id}
|
||||||
</div>
|
activeAgentId={activeAgentId}
|
||||||
|
activeTab={activeTab}
|
||||||
<CollapsibleContent>
|
agent={agent}
|
||||||
<div className="flex flex-col gap-0.5 mt-0.5">
|
disabled={pendingAgentIds.has(agent.id)}
|
||||||
{orderedAgents.map((agent: Agent) => {
|
isMobile={isMobile}
|
||||||
const runCount = liveCountByAgent.get(agent.id) ?? 0;
|
onPauseResume={(targetAgent, action) => pauseResumeAgent.mutate({ agent: targetAgent, action })}
|
||||||
return (
|
runCount={runCount}
|
||||||
<SidebarAgentItem
|
setSidebarOpen={setSidebarOpen}
|
||||||
key={agent.id}
|
/>
|
||||||
activeAgentId={activeAgentId}
|
);
|
||||||
activeTab={activeTab}
|
})}
|
||||||
agent={agent}
|
</SidebarSection>
|
||||||
disabled={pendingAgentIds.has(agent.id)}
|
|
||||||
isMobile={isMobile}
|
|
||||||
onPauseResume={(targetAgent, action) => pauseResumeAgent.mutate({ agent: targetAgent, action })}
|
|
||||||
runCount={runCount}
|
|
||||||
setSidebarOpen={setSidebarOpen}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</CollapsibleContent>
|
|
||||||
</Collapsible>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
299
ui/src/components/SidebarProjects.test.tsx
Normal file
299
ui/src/components/SidebarProjects.test.tsx
Normal file
|
|
@ -0,0 +1,299 @@
|
||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { act } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import type { Project } from "@paperclipai/shared";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { SidebarProjects } from "./SidebarProjects";
|
||||||
|
|
||||||
|
const mockProjectsApi = vi.hoisted(() => ({
|
||||||
|
list: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockAuthApi = vi.hoisted(() => ({
|
||||||
|
getSession: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const mockOpenNewProject = vi.hoisted(() => vi.fn());
|
||||||
|
const mockSetSidebarOpen = vi.hoisted(() => vi.fn());
|
||||||
|
const mockPersistOrder = vi.hoisted(() => vi.fn());
|
||||||
|
|
||||||
|
vi.mock("@/lib/router", () => ({
|
||||||
|
Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => (
|
||||||
|
<a href={to} {...props}>{children}</a>
|
||||||
|
),
|
||||||
|
NavLink: ({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
to,
|
||||||
|
...props
|
||||||
|
}: {
|
||||||
|
children: ReactNode;
|
||||||
|
className?: string | ((state: { isActive: boolean }) => string);
|
||||||
|
to: string;
|
||||||
|
}) => (
|
||||||
|
<a
|
||||||
|
href={to}
|
||||||
|
className={typeof className === "function" ? className({ isActive: false }) : className}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</a>
|
||||||
|
),
|
||||||
|
useLocation: () => ({ pathname: "/PAP/projects/bravo/issues", search: "", hash: "", state: null }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../context/CompanyContext", () => ({
|
||||||
|
useCompany: () => ({
|
||||||
|
selectedCompanyId: "company-1",
|
||||||
|
selectedCompany: { id: "company-1", issuePrefix: "PAP" },
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../context/DialogContext", () => ({
|
||||||
|
useDialog: () => ({
|
||||||
|
openNewProject: mockOpenNewProject,
|
||||||
|
}),
|
||||||
|
useDialogActions: () => ({
|
||||||
|
openNewProject: mockOpenNewProject,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../context/SidebarContext", () => ({
|
||||||
|
useSidebar: () => ({
|
||||||
|
isMobile: false,
|
||||||
|
setSidebarOpen: mockSetSidebarOpen,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../api/projects", () => ({
|
||||||
|
projectsApi: mockProjectsApi,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../api/auth", () => ({
|
||||||
|
authApi: mockAuthApi,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../hooks/useProjectOrder", () => ({
|
||||||
|
useProjectOrder: ({ projects }: { projects: Project[] }) => {
|
||||||
|
const curatedOrder = ["project-b", "project-a", "project-c"];
|
||||||
|
return {
|
||||||
|
orderedProjects: [...projects].sort(
|
||||||
|
(left, right) => curatedOrder.indexOf(left.id) - curatedOrder.indexOf(right.id),
|
||||||
|
),
|
||||||
|
persistOrder: mockPersistOrder,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/plugins/slots", () => ({
|
||||||
|
usePluginSlots: () => ({
|
||||||
|
slots: [{ id: "slot-1", pluginKey: "plugin-1" }],
|
||||||
|
}),
|
||||||
|
PluginSlotMount: ({ context }: { context: { projectId: string } }) => (
|
||||||
|
<div data-testid={`project-slot-${context.projectId}`}>Plugin slot</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||||
|
|
||||||
|
if (!globalThis.PointerEvent) {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
(globalThis as any).PointerEvent = MouseEvent;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeProject(overrides: Partial<Project>): Project {
|
||||||
|
return {
|
||||||
|
id: "project-a",
|
||||||
|
companyId: "company-1",
|
||||||
|
urlKey: "alpha",
|
||||||
|
goalId: null,
|
||||||
|
goalIds: [],
|
||||||
|
goals: [],
|
||||||
|
name: "Alpha",
|
||||||
|
description: null,
|
||||||
|
status: "in_progress",
|
||||||
|
leadAgentId: null,
|
||||||
|
targetDate: null,
|
||||||
|
color: "#ef4444",
|
||||||
|
env: null,
|
||||||
|
pauseReason: null,
|
||||||
|
pausedAt: null,
|
||||||
|
executionWorkspacePolicy: null,
|
||||||
|
codebase: {
|
||||||
|
workspaceId: null,
|
||||||
|
repoUrl: null,
|
||||||
|
repoRef: null,
|
||||||
|
defaultRef: null,
|
||||||
|
repoName: null,
|
||||||
|
localFolder: null,
|
||||||
|
managedFolder: "/tmp/project-a",
|
||||||
|
effectiveLocalFolder: "/tmp/project-a",
|
||||||
|
origin: "local_folder",
|
||||||
|
},
|
||||||
|
workspaces: [],
|
||||||
|
primaryWorkspace: null,
|
||||||
|
managedByPlugin: null,
|
||||||
|
archivedAt: null,
|
||||||
|
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||||
|
updatedAt: new Date("2026-01-01T00:00:00Z"),
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function flushReact() {
|
||||||
|
await act(async () => {
|
||||||
|
await Promise.resolve();
|
||||||
|
await new Promise((resolve) => window.setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function projectLinkLabels(container: HTMLElement) {
|
||||||
|
return Array.from(container.querySelectorAll('a[href$="/issues"]'))
|
||||||
|
.map((anchor) => anchor.textContent?.replace("Plugin slot", "").trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openProjectsMenu(container: HTMLElement) {
|
||||||
|
const trigger = container.querySelector('button[aria-label="Projects section actions"]');
|
||||||
|
expect(trigger).not.toBeNull();
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
trigger?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
|
||||||
|
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function chooseSortMode(label: string) {
|
||||||
|
const item = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))
|
||||||
|
.find((element) => element.textContent?.includes(label));
|
||||||
|
expect(item).toBeTruthy();
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
item?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("SidebarProjects", () => {
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: ReturnType<typeof createRoot> | null;
|
||||||
|
let queryClient: QueryClient;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
container = document.createElement("div");
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = null;
|
||||||
|
queryClient = new QueryClient({
|
||||||
|
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||||
|
});
|
||||||
|
localStorage.clear();
|
||||||
|
mockProjectsApi.list.mockResolvedValue([
|
||||||
|
makeProject({
|
||||||
|
id: "project-a",
|
||||||
|
urlKey: "alpha",
|
||||||
|
name: "Alpha",
|
||||||
|
createdAt: new Date("2026-01-01T00:00:00Z"),
|
||||||
|
updatedAt: new Date("2026-01-05T00:00:00Z"),
|
||||||
|
}),
|
||||||
|
makeProject({
|
||||||
|
id: "project-b",
|
||||||
|
urlKey: "bravo",
|
||||||
|
name: "Bravo",
|
||||||
|
createdAt: new Date("2026-01-02T00:00:00Z"),
|
||||||
|
updatedAt: new Date("2026-01-10T00:00:00Z"),
|
||||||
|
}),
|
||||||
|
makeProject({
|
||||||
|
id: "project-c",
|
||||||
|
urlKey: "charlie",
|
||||||
|
name: "Charlie",
|
||||||
|
createdAt: new Date("2026-01-03T00:00:00Z"),
|
||||||
|
updatedAt: new Date("2026-01-12T00:00:00Z"),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
mockAuthApi.getSession.mockResolvedValue({
|
||||||
|
session: { id: "session-1", userId: "user-1" },
|
||||||
|
user: { id: "user-1" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
const currentRoot = root;
|
||||||
|
if (currentRoot) {
|
||||||
|
await act(async () => {
|
||||||
|
currentRoot.unmount();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
queryClient.clear();
|
||||||
|
container.remove();
|
||||||
|
document.body.innerHTML = "";
|
||||||
|
localStorage.clear();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function renderSidebarProjects() {
|
||||||
|
const currentRoot = createRoot(container);
|
||||||
|
root = currentRoot;
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
currentRoot.render(
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<SidebarProjects />
|
||||||
|
</QueryClientProvider>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
}
|
||||||
|
|
||||||
|
it("keeps top mode in curated order and renders plugin project slots", async () => {
|
||||||
|
await renderSidebarProjects();
|
||||||
|
|
||||||
|
expect(projectLinkLabels(container)).toEqual(["Bravo", "Alpha", "Charlie"]);
|
||||||
|
expect(container.querySelector('[data-testid="project-slot-project-b"]')).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses the heading for section menu and the plus button for project creation", async () => {
|
||||||
|
await renderSidebarProjects();
|
||||||
|
|
||||||
|
const sectionMenuTrigger = container.querySelector('button[aria-label="Projects section actions"]');
|
||||||
|
expect(sectionMenuTrigger?.textContent).toContain("Projects");
|
||||||
|
expect(sectionMenuTrigger?.querySelector("svg")).toBeNull();
|
||||||
|
|
||||||
|
const newProjectButton = container.querySelector('button[aria-label="New project"]');
|
||||||
|
expect(newProjectButton).toBeTruthy();
|
||||||
|
await act(async () => {
|
||||||
|
newProjectButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
});
|
||||||
|
expect(mockOpenNewProject).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
await openProjectsMenu(container);
|
||||||
|
|
||||||
|
const newProjectItem = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
|
||||||
|
.find((element) => element.textContent?.includes("New project"));
|
||||||
|
expect(newProjectItem).toBeFalsy();
|
||||||
|
const browseLink = Array.from(document.body.querySelectorAll("a"))
|
||||||
|
.find((element) => element.textContent?.includes("Browse projects"));
|
||||||
|
expect(browseLink?.getAttribute("href")).toBe("/projects");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sorts alphabetically and persists the selected mode per company and user", async () => {
|
||||||
|
await renderSidebarProjects();
|
||||||
|
await openProjectsMenu(container);
|
||||||
|
await chooseSortMode("Alphabetical");
|
||||||
|
|
||||||
|
expect(projectLinkLabels(container)).toEqual(["Alpha", "Bravo", "Charlie"]);
|
||||||
|
expect(localStorage.getItem("paperclip.projectSortMode:company-1:user-1")).toBe("alphabetical");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sorts recent projects by updated time descending", async () => {
|
||||||
|
await renderSidebarProjects();
|
||||||
|
await openProjectsMenu(container);
|
||||||
|
await chooseSortMode("Recent");
|
||||||
|
|
||||||
|
expect(projectLinkLabels(container)).toEqual(["Charlie", "Bravo", "Alpha"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { useCallback, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { NavLink, useLocation } from "@/lib/router";
|
import { NavLink, useLocation } from "@/lib/router";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { ChevronRight, Plus } from "lucide-react";
|
import { FolderOpen, Plus } from "lucide-react";
|
||||||
import {
|
import {
|
||||||
DndContext,
|
DndContext,
|
||||||
MouseSensor,
|
MouseSensor,
|
||||||
|
|
@ -22,25 +22,27 @@ import { queryKeys } from "../lib/queryKeys";
|
||||||
import { cn, projectRouteRef } from "../lib/utils";
|
import { cn, projectRouteRef } from "../lib/utils";
|
||||||
import { useProjectOrder } from "../hooks/useProjectOrder";
|
import { useProjectOrder } from "../hooks/useProjectOrder";
|
||||||
import { BudgetSidebarMarker } from "./BudgetSidebarMarker";
|
import { BudgetSidebarMarker } from "./BudgetSidebarMarker";
|
||||||
import {
|
import { SidebarSection, type SidebarSectionRadioChoice } from "./SidebarSection";
|
||||||
Collapsible,
|
|
||||||
CollapsibleContent,
|
|
||||||
CollapsibleTrigger,
|
|
||||||
} from "@/components/ui/collapsible";
|
|
||||||
import { PluginSlotMount, usePluginSlots } from "@/plugins/slots";
|
import { PluginSlotMount, usePluginSlots } from "@/plugins/slots";
|
||||||
|
import {
|
||||||
|
getProjectSortModeStorageKey,
|
||||||
|
PROJECT_SORT_MODE_UPDATED_EVENT,
|
||||||
|
readProjectSortMode,
|
||||||
|
type ProjectSortModeUpdatedDetail,
|
||||||
|
type ProjectSidebarSortMode,
|
||||||
|
writeProjectSortMode,
|
||||||
|
} from "../lib/project-order";
|
||||||
import type { Project } from "@paperclipai/shared";
|
import type { Project } from "@paperclipai/shared";
|
||||||
|
|
||||||
type ProjectSidebarSlot = ReturnType<typeof usePluginSlots>["slots"][number];
|
type ProjectSidebarSlot = ReturnType<typeof usePluginSlots>["slots"][number];
|
||||||
|
|
||||||
function SortableProjectItem({
|
const PROJECT_SORT_CHOICES: SidebarSectionRadioChoice[] = [
|
||||||
activeProjectRef,
|
{ value: "top", label: "Top" },
|
||||||
companyId,
|
{ value: "alphabetical", label: "Alphabetical" },
|
||||||
companyPrefix,
|
{ value: "recent", label: "Recent" },
|
||||||
isMobile,
|
];
|
||||||
project,
|
|
||||||
projectSidebarSlots,
|
type ProjectItemProps = {
|
||||||
setSidebarOpen,
|
|
||||||
}: {
|
|
||||||
activeProjectRef: string | null;
|
activeProjectRef: string | null;
|
||||||
companyId: string | null;
|
companyId: string | null;
|
||||||
companyPrefix: string | null;
|
companyPrefix: string | null;
|
||||||
|
|
@ -48,7 +50,92 @@ function SortableProjectItem({
|
||||||
project: Project;
|
project: Project;
|
||||||
projectSidebarSlots: ProjectSidebarSlot[];
|
projectSidebarSlots: ProjectSidebarSlot[];
|
||||||
setSidebarOpen: (open: boolean) => void;
|
setSidebarOpen: (open: boolean) => void;
|
||||||
}) {
|
isDragging?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
function projectTimestamp(project: Project): number {
|
||||||
|
const updated = new Date(project.updatedAt).getTime();
|
||||||
|
if (Number.isFinite(updated)) return updated;
|
||||||
|
const created = new Date(project.createdAt).getTime();
|
||||||
|
return Number.isFinite(created) ? created : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortProjects(projects: Project[], sortMode: ProjectSidebarSortMode): Project[] {
|
||||||
|
if (sortMode === "top") return projects;
|
||||||
|
const sorted = [...projects];
|
||||||
|
if (sortMode === "alphabetical") {
|
||||||
|
sorted.sort((left, right) => left.name.localeCompare(right.name, undefined, { sensitivity: "base" }));
|
||||||
|
return sorted;
|
||||||
|
}
|
||||||
|
sorted.sort((left, right) => {
|
||||||
|
const timeDiff = projectTimestamp(right) - projectTimestamp(left);
|
||||||
|
return timeDiff !== 0 ? timeDiff : left.name.localeCompare(right.name, undefined, { sensitivity: "base" });
|
||||||
|
});
|
||||||
|
return sorted;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProjectItem({
|
||||||
|
activeProjectRef,
|
||||||
|
companyId,
|
||||||
|
companyPrefix,
|
||||||
|
isMobile,
|
||||||
|
project,
|
||||||
|
projectSidebarSlots,
|
||||||
|
setSidebarOpen,
|
||||||
|
isDragging = false,
|
||||||
|
}: ProjectItemProps) {
|
||||||
|
const routeRef = projectRouteRef(project);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-0.5">
|
||||||
|
<NavLink
|
||||||
|
to={`/projects/${routeRef}/issues`}
|
||||||
|
state={SIDEBAR_SCROLL_RESET_STATE}
|
||||||
|
onClick={(e) => {
|
||||||
|
if (isDragging) {
|
||||||
|
e.preventDefault();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (isMobile) setSidebarOpen(false);
|
||||||
|
}}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2.5 px-3 py-1.5 text-[13px] font-medium transition-colors",
|
||||||
|
activeProjectRef === routeRef || activeProjectRef === project.id
|
||||||
|
? "bg-accent text-foreground"
|
||||||
|
: "text-foreground/80 hover:bg-accent/50 hover:text-foreground",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="shrink-0 h-3.5 w-3.5 rounded-sm"
|
||||||
|
style={{ backgroundColor: project.color ?? "#6366f1" }}
|
||||||
|
/>
|
||||||
|
<span className="flex-1 truncate">{project.name}</span>
|
||||||
|
{project.pauseReason === "budget" ? <BudgetSidebarMarker title="Project paused by budget" /> : null}
|
||||||
|
</NavLink>
|
||||||
|
{projectSidebarSlots.length > 0 && (
|
||||||
|
<div className="ml-5 flex flex-col gap-0.5">
|
||||||
|
{projectSidebarSlots.map((slot) => (
|
||||||
|
<PluginSlotMount
|
||||||
|
key={`${project.id}:${slot.pluginKey}:${slot.id}`}
|
||||||
|
slot={slot}
|
||||||
|
context={{
|
||||||
|
companyId,
|
||||||
|
companyPrefix,
|
||||||
|
projectId: project.id,
|
||||||
|
projectRef: routeRef,
|
||||||
|
entityId: project.id,
|
||||||
|
entityType: "project",
|
||||||
|
}}
|
||||||
|
missingBehavior="placeholder"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SortableProjectItem(props: ProjectItemProps) {
|
||||||
const {
|
const {
|
||||||
attributes,
|
attributes,
|
||||||
listeners,
|
listeners,
|
||||||
|
|
@ -56,9 +143,7 @@ function SortableProjectItem({
|
||||||
transform,
|
transform,
|
||||||
transition,
|
transition,
|
||||||
isDragging,
|
isDragging,
|
||||||
} = useSortable({ id: project.id });
|
} = useSortable({ id: props.project.id });
|
||||||
|
|
||||||
const routeRef = projectRouteRef(project);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
|
@ -72,51 +157,7 @@ function SortableProjectItem({
|
||||||
{...attributes}
|
{...attributes}
|
||||||
{...listeners}
|
{...listeners}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col gap-0.5">
|
<ProjectItem {...props} isDragging={isDragging} />
|
||||||
<NavLink
|
|
||||||
to={`/projects/${routeRef}/issues`}
|
|
||||||
state={SIDEBAR_SCROLL_RESET_STATE}
|
|
||||||
onClick={(e) => {
|
|
||||||
if (isDragging) {
|
|
||||||
e.preventDefault();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (isMobile) setSidebarOpen(false);
|
|
||||||
}}
|
|
||||||
className={cn(
|
|
||||||
"flex items-center gap-2.5 px-3 py-1.5 text-[13px] font-medium transition-colors",
|
|
||||||
activeProjectRef === routeRef || activeProjectRef === project.id
|
|
||||||
? "bg-accent text-foreground"
|
|
||||||
: "text-foreground/80 hover:bg-accent/50 hover:text-foreground",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className="shrink-0 h-3.5 w-3.5 rounded-sm"
|
|
||||||
style={{ backgroundColor: project.color ?? "#6366f1" }}
|
|
||||||
/>
|
|
||||||
<span className="flex-1 truncate">{project.name}</span>
|
|
||||||
{project.pauseReason === "budget" ? <BudgetSidebarMarker title="Project paused by budget" /> : null}
|
|
||||||
</NavLink>
|
|
||||||
{projectSidebarSlots.length > 0 && (
|
|
||||||
<div className="ml-5 flex flex-col gap-0.5">
|
|
||||||
{projectSidebarSlots.map((slot) => (
|
|
||||||
<PluginSlotMount
|
|
||||||
key={`${project.id}:${slot.pluginKey}:${slot.id}`}
|
|
||||||
slot={slot}
|
|
||||||
context={{
|
|
||||||
companyId,
|
|
||||||
companyPrefix,
|
|
||||||
projectId: project.id,
|
|
||||||
projectRef: routeRef,
|
|
||||||
entityId: project.id,
|
|
||||||
entityType: "project",
|
|
||||||
}}
|
|
||||||
missingBehavior="placeholder"
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -145,6 +186,14 @@ export function SidebarProjects() {
|
||||||
});
|
});
|
||||||
|
|
||||||
const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;
|
const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;
|
||||||
|
const sortModeStorageKey = useMemo(() => {
|
||||||
|
if (!selectedCompanyId) return null;
|
||||||
|
return getProjectSortModeStorageKey(selectedCompanyId, currentUserId);
|
||||||
|
}, [currentUserId, selectedCompanyId]);
|
||||||
|
const [sortMode, setSortMode] = useState<ProjectSidebarSortMode>(() => {
|
||||||
|
if (!sortModeStorageKey) return "top";
|
||||||
|
return readProjectSortMode(sortModeStorageKey);
|
||||||
|
});
|
||||||
|
|
||||||
const visibleProjects = useMemo(
|
const visibleProjects = useMemo(
|
||||||
() => (projects ?? []).filter((project: Project) => !project.archivedAt),
|
() => (projects ?? []).filter((project: Project) => !project.archivedAt),
|
||||||
|
|
@ -155,6 +204,11 @@ export function SidebarProjects() {
|
||||||
companyId: selectedCompanyId,
|
companyId: selectedCompanyId,
|
||||||
userId: currentUserId,
|
userId: currentUserId,
|
||||||
});
|
});
|
||||||
|
const sortedProjects = useMemo(
|
||||||
|
() => sortProjects(orderedProjects, sortMode),
|
||||||
|
[orderedProjects, sortMode],
|
||||||
|
);
|
||||||
|
const isTopMode = sortMode === "top";
|
||||||
|
|
||||||
const projectMatch = location.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/);
|
const projectMatch = location.pathname.match(/^\/(?:[^/]+\/)?projects\/([^/]+)/);
|
||||||
const activeProjectRef = projectMatch?.[1] ?? null;
|
const activeProjectRef = projectMatch?.[1] ?? null;
|
||||||
|
|
@ -165,8 +219,50 @@ export function SidebarProjects() {
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!sortModeStorageKey) {
|
||||||
|
setSortMode("top");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setSortMode(readProjectSortMode(sortModeStorageKey));
|
||||||
|
}, [sortModeStorageKey]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!sortModeStorageKey) return;
|
||||||
|
|
||||||
|
const onStorage = (event: StorageEvent) => {
|
||||||
|
if (event.key !== sortModeStorageKey) return;
|
||||||
|
setSortMode(readProjectSortMode(sortModeStorageKey));
|
||||||
|
};
|
||||||
|
const onCustomEvent = (event: Event) => {
|
||||||
|
const detail = (event as CustomEvent<ProjectSortModeUpdatedDetail>).detail;
|
||||||
|
if (!detail || detail.storageKey !== sortModeStorageKey) return;
|
||||||
|
setSortMode(detail.sortMode);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener("storage", onStorage);
|
||||||
|
window.addEventListener(PROJECT_SORT_MODE_UPDATED_EVENT, onCustomEvent);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("storage", onStorage);
|
||||||
|
window.removeEventListener(PROJECT_SORT_MODE_UPDATED_EVENT, onCustomEvent);
|
||||||
|
};
|
||||||
|
}, [sortModeStorageKey]);
|
||||||
|
|
||||||
|
const persistSortMode = useCallback(
|
||||||
|
(value: string) => {
|
||||||
|
const nextSortMode: ProjectSidebarSortMode =
|
||||||
|
value === "alphabetical" || value === "recent" ? value : "top";
|
||||||
|
setSortMode(nextSortMode);
|
||||||
|
if (sortModeStorageKey) {
|
||||||
|
writeProjectSortMode(sortModeStorageKey, nextSortMode);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[sortModeStorageKey],
|
||||||
|
);
|
||||||
|
|
||||||
const handleDragEnd = useCallback(
|
const handleDragEnd = useCallback(
|
||||||
(event: DragEndEvent) => {
|
(event: DragEndEvent) => {
|
||||||
|
if (!isTopMode) return;
|
||||||
const { active, over } = event;
|
const { active, over } = event;
|
||||||
if (!over || active.id === over.id) return;
|
if (!over || active.id === over.id) return;
|
||||||
|
|
||||||
|
|
@ -177,38 +273,44 @@ export function SidebarProjects() {
|
||||||
|
|
||||||
persistOrder(arrayMove(ids, oldIndex, newIndex));
|
persistOrder(arrayMove(ids, oldIndex, newIndex));
|
||||||
},
|
},
|
||||||
[orderedProjects, persistOrder],
|
[isTopMode, orderedProjects, persistOrder],
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderProject = (project: Project) => (
|
||||||
|
<ProjectItem
|
||||||
|
key={project.id}
|
||||||
|
activeProjectRef={activeProjectRef}
|
||||||
|
companyId={selectedCompanyId}
|
||||||
|
companyPrefix={selectedCompany?.issuePrefix ?? null}
|
||||||
|
isMobile={isMobile}
|
||||||
|
project={project}
|
||||||
|
projectSidebarSlots={projectSidebarSlots}
|
||||||
|
setSidebarOpen={setSidebarOpen}
|
||||||
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Collapsible open={open} onOpenChange={setOpen}>
|
<SidebarSection
|
||||||
<div className="group">
|
label="Projects"
|
||||||
<div className="flex items-center px-3 py-1.5">
|
collapsible={{ open, onOpenChange: setOpen }}
|
||||||
<CollapsibleTrigger className="flex items-center gap-1 flex-1 min-w-0">
|
headerAction={{
|
||||||
<ChevronRight
|
ariaLabel: "New project",
|
||||||
className={cn(
|
icon: Plus,
|
||||||
"h-3 w-3 text-muted-foreground/60 transition-transform opacity-0 group-hover:opacity-100",
|
onClick: openNewProject,
|
||||||
open && "rotate-90"
|
}}
|
||||||
)}
|
menu={{
|
||||||
/>
|
ariaLabel: "Projects section actions",
|
||||||
<span className="text-[10px] font-medium uppercase tracking-widest font-mono text-muted-foreground/60">
|
actions: [
|
||||||
Projects
|
{ type: "item", label: "Browse projects", icon: FolderOpen, href: "/projects" },
|
||||||
</span>
|
{ type: "separator" },
|
||||||
</CollapsibleTrigger>
|
],
|
||||||
<button
|
radioLabel: "Project sort",
|
||||||
onClick={(e) => {
|
radioChoices: PROJECT_SORT_CHOICES,
|
||||||
e.stopPropagation();
|
radioValue: sortMode,
|
||||||
openNewProject();
|
onRadioValueChange: persistSortMode,
|
||||||
}}
|
}}
|
||||||
className="flex items-center justify-center h-4 w-4 rounded text-muted-foreground/60 hover:text-foreground hover:bg-accent/50 transition-colors"
|
>
|
||||||
aria-label="New project"
|
{isTopMode ? (
|
||||||
>
|
|
||||||
<Plus className="h-3 w-3" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<CollapsibleContent>
|
|
||||||
<DndContext
|
<DndContext
|
||||||
sensors={sensors}
|
sensors={sensors}
|
||||||
collisionDetection={closestCenter}
|
collisionDetection={closestCenter}
|
||||||
|
|
@ -218,7 +320,7 @@ export function SidebarProjects() {
|
||||||
items={orderedProjects.map((project) => project.id)}
|
items={orderedProjects.map((project) => project.id)}
|
||||||
strategy={verticalListSortingStrategy}
|
strategy={verticalListSortingStrategy}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col gap-0.5 mt-0.5">
|
<div className="flex flex-col gap-0.5">
|
||||||
{orderedProjects.map((project: Project) => (
|
{orderedProjects.map((project: Project) => (
|
||||||
<SortableProjectItem
|
<SortableProjectItem
|
||||||
key={project.id}
|
key={project.id}
|
||||||
|
|
@ -234,7 +336,11 @@ export function SidebarProjects() {
|
||||||
</div>
|
</div>
|
||||||
</SortableContext>
|
</SortableContext>
|
||||||
</DndContext>
|
</DndContext>
|
||||||
</CollapsibleContent>
|
) : (
|
||||||
</Collapsible>
|
<div className="flex flex-col gap-0.5">
|
||||||
|
{sortedProjects.map((project: Project) => renderProject(project))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</SidebarSection>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
299
ui/src/components/SidebarSection.test.tsx
Normal file
299
ui/src/components/SidebarSection.test.tsx
Normal file
|
|
@ -0,0 +1,299 @@
|
||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { act } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { SidebarSection } from "./SidebarSection";
|
||||||
|
import { Plus } from "lucide-react";
|
||||||
|
|
||||||
|
const sidebarState = vi.hoisted(() => ({
|
||||||
|
isMobile: false,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("@/lib/router", () => ({
|
||||||
|
Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => (
|
||||||
|
<a href={to} {...props}>{children}</a>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../context/SidebarContext", () => ({
|
||||||
|
useSidebar: () => sidebarState,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||||
|
|
||||||
|
if (!globalThis.PointerEvent) {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
(globalThis as any).PointerEvent = MouseEvent;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function flushReact() {
|
||||||
|
await act(async () => {
|
||||||
|
await Promise.resolve();
|
||||||
|
await new Promise((resolve) => window.setTimeout(resolve, 0));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openSectionMenu(container: HTMLElement) {
|
||||||
|
const trigger = container.querySelector('button[aria-label="Projects section actions"]');
|
||||||
|
expect(trigger).not.toBeNull();
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
trigger?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
|
||||||
|
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("SidebarSection", () => {
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: ReturnType<typeof createRoot> | null;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
sidebarState.isMobile = false;
|
||||||
|
container = document.createElement("div");
|
||||||
|
document.body.appendChild(container);
|
||||||
|
root = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
const currentRoot = root;
|
||||||
|
if (currentRoot) {
|
||||||
|
await act(async () => {
|
||||||
|
currentRoot.unmount();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
container.remove();
|
||||||
|
document.body.innerHTML = "";
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps static and collapsible section labels on the same text column", async () => {
|
||||||
|
const currentRoot = createRoot(container);
|
||||||
|
root = currentRoot;
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
currentRoot.render(
|
||||||
|
<div>
|
||||||
|
<SidebarSection label="Work">
|
||||||
|
<a href="/issues">Issues</a>
|
||||||
|
</SidebarSection>
|
||||||
|
<SidebarSection label="Projects" collapsible={{ open: true, onOpenChange: vi.fn() }}>
|
||||||
|
<a href="/projects">Projects</a>
|
||||||
|
</SidebarSection>
|
||||||
|
</div>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
|
||||||
|
const workLabel = Array.from(container.querySelectorAll("span"))
|
||||||
|
.find((element) => element.textContent === "Work");
|
||||||
|
const projectsLabel = Array.from(container.querySelectorAll("span"))
|
||||||
|
.find((element) => element.textContent === "Projects");
|
||||||
|
|
||||||
|
expect(workLabel?.parentElement?.textContent).toBe("Work");
|
||||||
|
expect(projectsLabel?.parentElement?.textContent).toBe("Projects");
|
||||||
|
expect(projectsLabel?.parentElement?.querySelector("svg")).toBeNull();
|
||||||
|
expect(container.querySelector('button[aria-label="Collapse Projects"] svg')).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps collapse on the caret and opens the menu from the heading", async () => {
|
||||||
|
const onOpenChange = vi.fn();
|
||||||
|
const currentRoot = createRoot(container);
|
||||||
|
root = currentRoot;
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
currentRoot.render(
|
||||||
|
<SidebarSection
|
||||||
|
label="Projects"
|
||||||
|
collapsible={{ open: true, onOpenChange }}
|
||||||
|
menu={{
|
||||||
|
ariaLabel: "Projects section actions",
|
||||||
|
actions: [{ type: "item", label: "Browse projects", href: "/projects" }],
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<a href="/projects">Projects</a>
|
||||||
|
</SidebarSection>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
|
||||||
|
await openSectionMenu(container);
|
||||||
|
|
||||||
|
expect(onOpenChange).not.toHaveBeenCalled();
|
||||||
|
expect(document.body.textContent).toContain("Browse projects");
|
||||||
|
|
||||||
|
const caret = container.querySelector('button[aria-label="Collapse Projects"]');
|
||||||
|
await act(async () => {
|
||||||
|
caret?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not apply hover background classes to static section labels", async () => {
|
||||||
|
const currentRoot = createRoot(container);
|
||||||
|
root = currentRoot;
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
currentRoot.render(
|
||||||
|
<SidebarSection label="Work">
|
||||||
|
<a href="/issues">Issues</a>
|
||||||
|
</SidebarSection>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
|
||||||
|
const workLabel = Array.from(container.querySelectorAll("span"))
|
||||||
|
.find((element) => element.textContent === "Work");
|
||||||
|
const staticLabelControl = workLabel?.parentElement;
|
||||||
|
|
||||||
|
expect(staticLabelControl?.tagName).toBe("DIV");
|
||||||
|
expect(staticLabelControl?.getAttribute("class")).not.toContain("hover:bg-accent/50");
|
||||||
|
expect(staticLabelControl?.getAttribute("class")).not.toContain("focus-visible:bg-accent/50");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the header action outside the label menu hit area", async () => {
|
||||||
|
const onAction = vi.fn();
|
||||||
|
const currentRoot = createRoot(container);
|
||||||
|
root = currentRoot;
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
currentRoot.render(
|
||||||
|
<SidebarSection
|
||||||
|
label="Projects"
|
||||||
|
menu={{
|
||||||
|
ariaLabel: "Projects section actions",
|
||||||
|
actions: [{ type: "item", label: "Browse projects", href: "/projects" }],
|
||||||
|
}}
|
||||||
|
headerAction={{
|
||||||
|
ariaLabel: "New project",
|
||||||
|
icon: Plus,
|
||||||
|
onClick: onAction,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<a href="/projects">Projects</a>
|
||||||
|
</SidebarSection>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
|
||||||
|
const sectionMenuTrigger = container.querySelector('button[aria-label="Projects section actions"]');
|
||||||
|
const newProjectButton = container.querySelector('button[aria-label="New project"]');
|
||||||
|
|
||||||
|
expect(sectionMenuTrigger?.textContent).toContain("Projects");
|
||||||
|
expect(sectionMenuTrigger?.querySelector("svg")).toBeNull();
|
||||||
|
expect(sectionMenuTrigger?.getAttribute("class")).toContain("hover:bg-accent/50");
|
||||||
|
expect(newProjectButton).toBeTruthy();
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
newProjectButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
|
||||||
|
expect(onAction).toHaveBeenCalledTimes(1);
|
||||||
|
expect(document.body.textContent).not.toContain("Browse projects");
|
||||||
|
|
||||||
|
await openSectionMenu(container);
|
||||||
|
expect(document.body.textContent).toContain("Browse projects");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders configured menu actions and radio choices", async () => {
|
||||||
|
const onAction = vi.fn();
|
||||||
|
const onRadioValueChange = vi.fn();
|
||||||
|
const currentRoot = createRoot(container);
|
||||||
|
root = currentRoot;
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
currentRoot.render(
|
||||||
|
<SidebarSection
|
||||||
|
label="Projects"
|
||||||
|
menu={{
|
||||||
|
ariaLabel: "Projects section actions",
|
||||||
|
actions: [
|
||||||
|
{ type: "item", label: "New project", onSelect: onAction },
|
||||||
|
{ type: "item", label: "Browse projects", href: "/projects" },
|
||||||
|
{ type: "separator" },
|
||||||
|
],
|
||||||
|
radioChoices: [
|
||||||
|
{ value: "top", label: "Top" },
|
||||||
|
{ value: "alphabetical", label: "Alphabetical" },
|
||||||
|
],
|
||||||
|
radioValue: "top",
|
||||||
|
onRadioValueChange,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<a href="/projects">Projects</a>
|
||||||
|
</SidebarSection>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
|
||||||
|
await openSectionMenu(container);
|
||||||
|
|
||||||
|
const newProjectItem = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
|
||||||
|
.find((element) => element.textContent?.includes("New project"));
|
||||||
|
expect(newProjectItem).toBeTruthy();
|
||||||
|
const browseLink = Array.from(document.body.querySelectorAll("a"))
|
||||||
|
.find((element) => element.textContent?.includes("Browse projects"));
|
||||||
|
expect(browseLink?.getAttribute("href")).toBe("/projects");
|
||||||
|
|
||||||
|
const alphabeticalItem = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))
|
||||||
|
.find((element) => element.textContent?.includes("Alphabetical"));
|
||||||
|
expect(alphabeticalItem).toBeTruthy();
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
alphabeticalItem?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
});
|
||||||
|
expect(onRadioValueChange).toHaveBeenCalledWith("alphabetical");
|
||||||
|
|
||||||
|
await openSectionMenu(container);
|
||||||
|
const reopenedNewProjectItem = Array.from(document.body.querySelectorAll('[data-slot="dropdown-menu-item"]'))
|
||||||
|
.find((element) => element.textContent?.includes("New project"));
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
reopenedNewProjectItem?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||||
|
});
|
||||||
|
expect(onAction).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps section header controls visible on mobile", async () => {
|
||||||
|
sidebarState.isMobile = true;
|
||||||
|
const currentRoot = createRoot(container);
|
||||||
|
root = currentRoot;
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
currentRoot.render(
|
||||||
|
<SidebarSection
|
||||||
|
label="Projects"
|
||||||
|
collapsible={{ open: false, onOpenChange: vi.fn() }}
|
||||||
|
menu={{
|
||||||
|
ariaLabel: "Projects section actions",
|
||||||
|
actions: [{ type: "item", label: "New project" }],
|
||||||
|
}}
|
||||||
|
headerAction={{
|
||||||
|
ariaLabel: "New project",
|
||||||
|
icon: Plus,
|
||||||
|
onClick: vi.fn(),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<a href="/projects">Projects</a>
|
||||||
|
</SidebarSection>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
await flushReact();
|
||||||
|
|
||||||
|
const projectsLabel = Array.from(container.querySelectorAll("span"))
|
||||||
|
.find((element) => element.textContent === "Projects");
|
||||||
|
const caret = container.querySelector('button[aria-label="Expand Projects"] svg');
|
||||||
|
const action = container.querySelector('button[aria-label="New project"]');
|
||||||
|
|
||||||
|
expect(caret?.getAttribute("class")).toContain("opacity-100");
|
||||||
|
expect(caret?.getAttribute("class")).not.toContain("opacity-0");
|
||||||
|
expect(projectsLabel?.parentElement?.textContent).toBe("Projects");
|
||||||
|
expect(action?.getAttribute("class")).toContain("opacity-100");
|
||||||
|
expect(action?.getAttribute("class")).not.toContain("opacity-0");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,17 +1,212 @@
|
||||||
import type { ReactNode } from "react";
|
import { useState, type ComponentType, type ReactNode } from "react";
|
||||||
|
import { Link } from "@/lib/router";
|
||||||
|
import { ChevronRight } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useSidebar } from "../context/SidebarContext";
|
||||||
|
import {
|
||||||
|
Collapsible,
|
||||||
|
CollapsibleContent,
|
||||||
|
CollapsibleTrigger,
|
||||||
|
} from "@/components/ui/collapsible";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuRadioGroup,
|
||||||
|
DropdownMenuRadioItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
type SidebarSectionIcon = ComponentType<{ className?: string }>;
|
||||||
|
|
||||||
|
export type SidebarSectionMenuAction =
|
||||||
|
| {
|
||||||
|
type: "item";
|
||||||
|
label: string;
|
||||||
|
icon?: SidebarSectionIcon;
|
||||||
|
href?: string;
|
||||||
|
onSelect?: () => void;
|
||||||
|
}
|
||||||
|
| { type: "separator" };
|
||||||
|
|
||||||
|
export type SidebarSectionRadioChoice = {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type SidebarSectionMenu = {
|
||||||
|
actions?: SidebarSectionMenuAction[];
|
||||||
|
ariaLabel?: string;
|
||||||
|
radioChoices?: SidebarSectionRadioChoice[];
|
||||||
|
radioLabel?: string;
|
||||||
|
radioValue?: string;
|
||||||
|
onRadioValueChange?: (value: string) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
type SidebarSectionHeaderAction = {
|
||||||
|
ariaLabel: string;
|
||||||
|
icon: SidebarSectionIcon;
|
||||||
|
onClick: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
interface SidebarSectionProps {
|
interface SidebarSectionProps {
|
||||||
label: string;
|
label: string;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
|
collapsible?: {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
};
|
||||||
|
menu?: SidebarSectionMenu;
|
||||||
|
headerAction?: SidebarSectionHeaderAction;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SidebarSection({ label, children }: SidebarSectionProps) {
|
function SidebarSectionHeader({
|
||||||
|
collapsible,
|
||||||
|
headerAction,
|
||||||
|
label,
|
||||||
|
menu,
|
||||||
|
}: Pick<SidebarSectionProps, "collapsible" | "headerAction" | "label" | "menu">) {
|
||||||
|
const { isMobile } = useSidebar();
|
||||||
|
const [menuOpen, setMenuOpen] = useState(false);
|
||||||
|
const hasMenu = Boolean(
|
||||||
|
menu && ((menu.actions?.length ?? 0) > 0 || (menu.radioChoices?.length ?? 0) > 0),
|
||||||
|
);
|
||||||
|
const labelClassName = "text-[10px] font-medium uppercase tracking-widest font-mono text-muted-foreground/60";
|
||||||
|
const headerControlVisibilityClassName = isMobile
|
||||||
|
? "opacity-100"
|
||||||
|
: "opacity-0 group-hover/sidebar-section:opacity-100 group-focus-within/sidebar-section:opacity-100";
|
||||||
|
const caretClassName = cn(
|
||||||
|
"h-3 w-3 shrink-0 text-muted-foreground/60 transition-all",
|
||||||
|
headerControlVisibilityClassName,
|
||||||
|
collapsible?.open && "rotate-90",
|
||||||
|
menuOpen && "opacity-100",
|
||||||
|
);
|
||||||
|
const actionClassName = cn(
|
||||||
|
"h-5 w-5 shrink-0 text-muted-foreground/60 transition-opacity hover:text-foreground data-[state=open]:opacity-100",
|
||||||
|
headerControlVisibilityClassName,
|
||||||
|
);
|
||||||
|
const headerContent = <span className={labelClassName}>{label}</span>;
|
||||||
|
const HeaderActionIcon = headerAction?.icon;
|
||||||
|
|
||||||
|
const headingControl = hasMenu ? (
|
||||||
|
<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
"inline-flex min-w-0 max-w-full items-center rounded-md px-1 py-0.5 text-left outline-none transition-colors",
|
||||||
|
"hover:bg-accent/50 focus-visible:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",
|
||||||
|
menuOpen && "bg-accent/50",
|
||||||
|
)}
|
||||||
|
aria-label={menu?.ariaLabel ?? `${label} actions`}
|
||||||
|
>
|
||||||
|
{headerContent}
|
||||||
|
</button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="start" className="w-48">
|
||||||
|
{menu?.actions?.map((action, index) => {
|
||||||
|
if (action.type === "separator") {
|
||||||
|
return <DropdownMenuSeparator key={`separator-${index}`} />;
|
||||||
|
}
|
||||||
|
const Icon = action.icon;
|
||||||
|
const content = (
|
||||||
|
<>
|
||||||
|
{Icon ? <Icon className="size-4" /> : null}
|
||||||
|
<span>{action.label}</span>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
if (action.href) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuItem key={`${action.label}-${index}`} asChild>
|
||||||
|
<Link to={action.href}>{content}</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<DropdownMenuItem key={`${action.label}-${index}`} onSelect={action.onSelect}>
|
||||||
|
{content}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{menu?.radioChoices && menu.radioChoices.length > 0 ? (
|
||||||
|
<DropdownMenuRadioGroup
|
||||||
|
value={menu.radioValue}
|
||||||
|
onValueChange={menu.onRadioValueChange}
|
||||||
|
aria-label={menu.radioLabel}
|
||||||
|
>
|
||||||
|
{menu.radioChoices.map((choice) => (
|
||||||
|
<DropdownMenuRadioItem key={choice.value} value={choice.value}>
|
||||||
|
{choice.label}
|
||||||
|
</DropdownMenuRadioItem>
|
||||||
|
))}
|
||||||
|
</DropdownMenuRadioGroup>
|
||||||
|
) : null}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
) : (
|
||||||
|
<div className="inline-flex min-w-0 max-w-full items-center px-1 py-0.5">{headerContent}</div>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div className="group/sidebar-section px-3 py-1.5">
|
||||||
<div className="px-3 py-1.5 text-[10px] font-medium uppercase tracking-widest font-mono text-muted-foreground/60">
|
<div className="relative flex min-h-6 min-w-0 items-center gap-1">
|
||||||
{label}
|
{collapsible ? (
|
||||||
|
<CollapsibleTrigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="absolute -left-4 flex h-5 w-5 items-center justify-center rounded-sm outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1"
|
||||||
|
aria-label={collapsible.open ? `Collapse ${label}` : `Expand ${label}`}
|
||||||
|
>
|
||||||
|
<ChevronRight className={caretClassName} aria-hidden="true" />
|
||||||
|
</button>
|
||||||
|
</CollapsibleTrigger>
|
||||||
|
) : null}
|
||||||
|
{headingControl}
|
||||||
|
{headerAction && HeaderActionIcon ? (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon-xs"
|
||||||
|
className={actionClassName}
|
||||||
|
aria-label={headerAction.ariaLabel}
|
||||||
|
onClick={headerAction.onClick}
|
||||||
|
>
|
||||||
|
<HeaderActionIcon className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-0.5 mt-0.5">{children}</div>
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SidebarSection({
|
||||||
|
label,
|
||||||
|
children,
|
||||||
|
collapsible,
|
||||||
|
menu,
|
||||||
|
headerAction,
|
||||||
|
}: SidebarSectionProps) {
|
||||||
|
const content = <div className="flex flex-col gap-0.5 mt-0.5">{children}</div>;
|
||||||
|
|
||||||
|
if (collapsible) {
|
||||||
|
return (
|
||||||
|
<Collapsible open={collapsible.open} onOpenChange={collapsible.onOpenChange}>
|
||||||
|
<SidebarSectionHeader
|
||||||
|
label={label}
|
||||||
|
collapsible={collapsible}
|
||||||
|
menu={menu}
|
||||||
|
headerAction={headerAction}
|
||||||
|
/>
|
||||||
|
<CollapsibleContent>{content}</CollapsibleContent>
|
||||||
|
</Collapsible>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<SidebarSectionHeader label={label} menu={menu} headerAction={headerAction} />
|
||||||
|
{content}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,32 @@
|
||||||
import type { Agent } from "@paperclipai/shared";
|
import type { Agent } from "@paperclipai/shared";
|
||||||
|
|
||||||
export const AGENT_ORDER_UPDATED_EVENT = "paperclip:agent-order-updated";
|
export const AGENT_ORDER_UPDATED_EVENT = "paperclip:agent-order-updated";
|
||||||
|
export const AGENT_SORT_MODE_UPDATED_EVENT = "paperclip:agent-sort-mode-updated";
|
||||||
const AGENT_ORDER_STORAGE_PREFIX = "paperclip.agentOrder";
|
const AGENT_ORDER_STORAGE_PREFIX = "paperclip.agentOrder";
|
||||||
|
const AGENT_SORT_MODE_STORAGE_PREFIX = "paperclip.agentSortMode";
|
||||||
const ANONYMOUS_USER_ID = "anonymous";
|
const ANONYMOUS_USER_ID = "anonymous";
|
||||||
|
|
||||||
|
export type AgentSidebarSortMode = "top" | "alphabetical" | "recent";
|
||||||
|
|
||||||
type AgentOrderUpdatedDetail = {
|
type AgentOrderUpdatedDetail = {
|
||||||
storageKey: string;
|
storageKey: string;
|
||||||
orderedIds: string[];
|
orderedIds: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type AgentSortModeUpdatedDetail = {
|
||||||
|
storageKey: string;
|
||||||
|
sortMode: AgentSidebarSortMode;
|
||||||
|
};
|
||||||
|
|
||||||
function normalizeIdList(value: unknown): string[] {
|
function normalizeIdList(value: unknown): string[] {
|
||||||
if (!Array.isArray(value)) return [];
|
if (!Array.isArray(value)) return [];
|
||||||
return value.filter((item): item is string => typeof item === "string" && item.length > 0);
|
return value.filter((item): item is string => typeof item === "string" && item.length > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normalizeSortMode(value: unknown): AgentSidebarSortMode {
|
||||||
|
return value === "alphabetical" || value === "recent" || value === "top" ? value : "top";
|
||||||
|
}
|
||||||
|
|
||||||
function resolveUserId(userId: string | null | undefined): string {
|
function resolveUserId(userId: string | null | undefined): string {
|
||||||
if (!userId) return ANONYMOUS_USER_ID;
|
if (!userId) return ANONYMOUS_USER_ID;
|
||||||
const trimmed = userId.trim();
|
const trimmed = userId.trim();
|
||||||
|
|
@ -24,6 +37,10 @@ export function getAgentOrderStorageKey(companyId: string, userId: string | null
|
||||||
return `${AGENT_ORDER_STORAGE_PREFIX}:${companyId}:${resolveUserId(userId)}`;
|
return `${AGENT_ORDER_STORAGE_PREFIX}:${companyId}:${resolveUserId(userId)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getAgentSortModeStorageKey(companyId: string, userId: string | null | undefined): string {
|
||||||
|
return `${AGENT_SORT_MODE_STORAGE_PREFIX}:${companyId}:${resolveUserId(userId)}`;
|
||||||
|
}
|
||||||
|
|
||||||
export function readAgentOrder(storageKey: string): string[] {
|
export function readAgentOrder(storageKey: string): string[] {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(storageKey);
|
const raw = localStorage.getItem(storageKey);
|
||||||
|
|
@ -34,6 +51,14 @@ export function readAgentOrder(storageKey: string): string[] {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function readAgentSortMode(storageKey: string): AgentSidebarSortMode {
|
||||||
|
try {
|
||||||
|
return normalizeSortMode(localStorage.getItem(storageKey));
|
||||||
|
} catch {
|
||||||
|
return "top";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function writeAgentOrder(storageKey: string, orderedIds: string[]) {
|
export function writeAgentOrder(storageKey: string, orderedIds: string[]) {
|
||||||
const normalized = normalizeIdList(orderedIds);
|
const normalized = normalizeIdList(orderedIds);
|
||||||
try {
|
try {
|
||||||
|
|
@ -50,6 +75,22 @@ export function writeAgentOrder(storageKey: string, orderedIds: string[]) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function writeAgentSortMode(storageKey: string, sortMode: AgentSidebarSortMode) {
|
||||||
|
const normalized = normalizeSortMode(sortMode);
|
||||||
|
try {
|
||||||
|
localStorage.setItem(storageKey, normalized);
|
||||||
|
} catch {
|
||||||
|
// Ignore storage write failures in restricted browser contexts.
|
||||||
|
}
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent<AgentSortModeUpdatedDetail>(AGENT_SORT_MODE_UPDATED_EVENT, {
|
||||||
|
detail: { storageKey, sortMode: normalized },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function sortAgentsByDefaultSidebarOrder(agents: Agent[]): Agent[] {
|
export function sortAgentsByDefaultSidebarOrder(agents: Agent[]): Agent[] {
|
||||||
if (agents.length === 0) return [];
|
if (agents.length === 0) return [];
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,32 @@
|
||||||
import type { Project } from "@paperclipai/shared";
|
import type { Project } from "@paperclipai/shared";
|
||||||
|
|
||||||
export const PROJECT_ORDER_UPDATED_EVENT = "paperclip:project-order-updated";
|
export const PROJECT_ORDER_UPDATED_EVENT = "paperclip:project-order-updated";
|
||||||
|
export const PROJECT_SORT_MODE_UPDATED_EVENT = "paperclip:project-sort-mode-updated";
|
||||||
const PROJECT_ORDER_STORAGE_PREFIX = "paperclip.projectOrder";
|
const PROJECT_ORDER_STORAGE_PREFIX = "paperclip.projectOrder";
|
||||||
|
const PROJECT_SORT_MODE_STORAGE_PREFIX = "paperclip.projectSortMode";
|
||||||
const ANONYMOUS_USER_ID = "anonymous";
|
const ANONYMOUS_USER_ID = "anonymous";
|
||||||
|
|
||||||
|
export type ProjectSidebarSortMode = "top" | "alphabetical" | "recent";
|
||||||
|
|
||||||
type ProjectOrderUpdatedDetail = {
|
type ProjectOrderUpdatedDetail = {
|
||||||
storageKey: string;
|
storageKey: string;
|
||||||
orderedIds: string[];
|
orderedIds: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type ProjectSortModeUpdatedDetail = {
|
||||||
|
storageKey: string;
|
||||||
|
sortMode: ProjectSidebarSortMode;
|
||||||
|
};
|
||||||
|
|
||||||
function normalizeIdList(value: unknown): string[] {
|
function normalizeIdList(value: unknown): string[] {
|
||||||
if (!Array.isArray(value)) return [];
|
if (!Array.isArray(value)) return [];
|
||||||
return value.filter((item): item is string => typeof item === "string" && item.length > 0);
|
return value.filter((item): item is string => typeof item === "string" && item.length > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normalizeSortMode(value: unknown): ProjectSidebarSortMode {
|
||||||
|
return value === "alphabetical" || value === "recent" || value === "top" ? value : "top";
|
||||||
|
}
|
||||||
|
|
||||||
function resolveUserId(userId: string | null | undefined): string {
|
function resolveUserId(userId: string | null | undefined): string {
|
||||||
if (!userId) return ANONYMOUS_USER_ID;
|
if (!userId) return ANONYMOUS_USER_ID;
|
||||||
const trimmed = userId.trim();
|
const trimmed = userId.trim();
|
||||||
|
|
@ -24,6 +37,10 @@ export function getProjectOrderStorageKey(companyId: string, userId: string | nu
|
||||||
return `${PROJECT_ORDER_STORAGE_PREFIX}:${companyId}:${resolveUserId(userId)}`;
|
return `${PROJECT_ORDER_STORAGE_PREFIX}:${companyId}:${resolveUserId(userId)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getProjectSortModeStorageKey(companyId: string, userId: string | null | undefined): string {
|
||||||
|
return `${PROJECT_SORT_MODE_STORAGE_PREFIX}:${companyId}:${resolveUserId(userId)}`;
|
||||||
|
}
|
||||||
|
|
||||||
export function readProjectOrder(storageKey: string): string[] {
|
export function readProjectOrder(storageKey: string): string[] {
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(storageKey);
|
const raw = localStorage.getItem(storageKey);
|
||||||
|
|
@ -34,6 +51,14 @@ export function readProjectOrder(storageKey: string): string[] {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function readProjectSortMode(storageKey: string): ProjectSidebarSortMode {
|
||||||
|
try {
|
||||||
|
return normalizeSortMode(localStorage.getItem(storageKey));
|
||||||
|
} catch {
|
||||||
|
return "top";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function writeProjectOrder(storageKey: string, orderedIds: string[]) {
|
export function writeProjectOrder(storageKey: string, orderedIds: string[]) {
|
||||||
const normalized = normalizeIdList(orderedIds);
|
const normalized = normalizeIdList(orderedIds);
|
||||||
try {
|
try {
|
||||||
|
|
@ -50,6 +75,22 @@ export function writeProjectOrder(storageKey: string, orderedIds: string[]) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function writeProjectSortMode(storageKey: string, sortMode: ProjectSidebarSortMode) {
|
||||||
|
const normalized = normalizeSortMode(sortMode);
|
||||||
|
try {
|
||||||
|
localStorage.setItem(storageKey, normalized);
|
||||||
|
} catch {
|
||||||
|
// Ignore storage write failures in restricted browser contexts.
|
||||||
|
}
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent<ProjectSortModeUpdatedDetail>(PROJECT_SORT_MODE_UPDATED_EVENT, {
|
||||||
|
detail: { storageKey, sortMode: normalized },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function sortProjectsByStoredOrder(projects: Project[], orderedIds: string[]): Project[] {
|
export function sortProjectsByStoredOrder(projects: Project[], orderedIds: string[]): Project[] {
|
||||||
if (projects.length === 0) return [];
|
if (projects.length === 0) return [];
|
||||||
if (orderedIds.length === 0) return projects;
|
if (orderedIds.length === 0) return projects;
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue