Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

feat(sidebar): add collapsible dashboard sidebar with persisted state

Khuram Niaz2f0efc2590eb
diff --git a/__tests__/Sidebar.spec.tsx b/__tests__/Sidebar.spec.tsx
new file mode 100644
index 0000000..c4cc0e2
--- /dev/null
+++ b/__tests__/Sidebar.spec.tsx
@@ -0,0 +1,208 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { usePathname } from "next/navigation";
+import { Briefcase } from "lucide-react";
+import Sidebar from "@/components/Sidebar";
+import SidebarToggle from "@/components/SidebarToggle";
+import NavLink from "@/components/NavLink";
+import { SidebarProvider } from "@/context/SidebarContext";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { APP_CONSTANTS } from "@/lib/constants";
+
+vi.mock("next/navigation", () => ({
+ usePathname: vi.fn().mockReturnValue("/dashboard"),
+}));
+
+const renderSidebar = () =>
+ render(
+ <SidebarProvider initialExpanded>
+ <Sidebar />
+ <SidebarToggle />
+ </SidebarProvider>
+ );
+
+describe("NavLink - active state", () => {
+ const renderNavLink = (route: string, pathname: string) =>
+ render(
+ <TooltipProvider>
+ <NavLink
+ label="Jobs"
+ Icon={Briefcase}
+ route={route}
+ pathname={pathname}
+ expanded
+ />
+ </TooltipProvider>
+ );
+
+ it("marks the link active on an exact route match", () => {
+ renderNavLink("/dashboard/myjobs", "/dashboard/myjobs");
+
+ expect(screen.getByRole("link")).toHaveAttribute("aria-current", "page");
+ });
+
+ it("marks the link active on a nested route", () => {
+ renderNavLink("/dashboard/myjobs", "/dashboard/myjobs/job-123");
+
+ expect(screen.getByRole("link")).toHaveAttribute("aria-current", "page");
+ });
+
+ // "/dashboard" is a prefix of every other route, so it must not match them.
+ it("does not mark the dashboard link active on other pages", () => {
+ renderNavLink("/dashboard", "/dashboard/myjobs");
+
+ expect(screen.getByRole("link")).not.toHaveAttribute("aria-current");
+ });
+
+ it("does not match a route that is only a string prefix", () => {
+ renderNavLink("/dashboard/job", "/dashboard/jobs");
+
+ expect(screen.getByRole("link")).not.toHaveAttribute("aria-current");
+ });
+});
+
+describe("NavLink - label rendering", () => {
+ const renderNavLink = (expanded: boolean) =>
+ render(
+ <TooltipProvider>
+ <NavLink
+ label="Jobs"
+ Icon={Briefcase}
+ route="/dashboard/myjobs"
+ pathname="/dashboard"
+ expanded={expanded}
+ />
+ </TooltipProvider>
+ );
+
+ it("shows a visible label when expanded", () => {
+ renderNavLink(true);
+
+ expect(screen.getByText("Jobs")).not.toHaveClass("sr-only");
+ });
+
+ // A hidden-but-in-flow label takes flex space and pushes the icon
+ // off-center in the collapsed rail, so it must be sr-only there.
+ it("keeps the label screen-reader-only when collapsed", () => {
+ renderNavLink(false);
+
+ expect(screen.getByText("Jobs")).toHaveClass("sr-only");
+ });
+
+ it("keeps an accessible name in both states", () => {
+ const { unmount } = renderNavLink(false);
+ expect(screen.getByRole("link", { name: "Jobs" })).toBeInTheDocument();
+ unmount();
+
+ renderNavLink(true);
+ expect(screen.getByRole("link", { name: "Jobs" })).toBeInTheDocument();
+ });
+});
+
+describe("Sidebar", () => {
+ beforeEach(() => {
+ document.cookie = `${APP_CONSTANTS.SIDEBAR_STORAGE_KEY}=; path=/; max-age=0`;
+ (usePathname as any).mockReturnValue("/dashboard");
+ });
+
+ it("renders a link for each nav item plus settings", () => {
+ renderSidebar();
+
+ expect(screen.getByRole("link", { name: "Dashboard" })).toHaveAttribute(
+ "href",
+ "/dashboard"
+ );
+ expect(screen.getByRole("link", { name: "Jobs" })).toHaveAttribute(
+ "href",
+ "/dashboard/myjobs"
+ );
+ expect(screen.getByRole("link", { name: "Settings" })).toHaveAttribute(
+ "href",
+ "/dashboard/settings"
+ );
+ });
+
+ it("marks the current page with aria-current", () => {
+ (usePathname as any).mockReturnValue("/dashboard/tasks");
+
+ renderSidebar();
+
+ expect(screen.getByRole("link", { name: "Tasks" })).toHaveAttribute(
+ "aria-current",
+ "page"
+ );
+ expect(
+ screen.getByRole("link", { name: "Dashboard" })
+ ).not.toHaveAttribute("aria-current");
+ });
+
+ it("does not render a collapse control inside the sidebar", () => {
+ renderSidebar();
+
+ // The only toggle lives in the header; the rail is nav links only.
+ expect(
+ screen.getByRole("complementary").querySelector("button")
+ ).toBeNull();
+ });
+});
+
+describe("SidebarToggle", () => {
+ beforeEach(() => {
+ document.cookie = `${APP_CONSTANTS.SIDEBAR_STORAGE_KEY}=; path=/; max-age=0`;
+ (usePathname as any).mockReturnValue("/dashboard");
+ });
+
+ it("collapses and expands the sidebar", async () => {
+ const user = userEvent.setup();
+ renderSidebar();
+
+ const toggle = screen.getByRole("button", { name: "Collapse sidebar" });
+ expect(toggle).toHaveAttribute("aria-expanded", "true");
+
+ await user.click(toggle);
+
+ const expandToggle = screen.getByRole("button", {
+ name: "Expand sidebar",
+ });
+ expect(expandToggle).toHaveAttribute("aria-expanded", "false");
+
+ await user.click(expandToggle);
+
+ expect(
+ screen.getByRole("button", { name: "Collapse sidebar" })
+ ).toHaveAttribute("aria-expanded", "true");
+ });
+
+ it("hides nav labels visually when collapsed", async () => {
+ const user = userEvent.setup();
+ renderSidebar();
+
+ expect(screen.getByText("Jobs")).not.toHaveClass("sr-only");
+
+ await user.click(screen.getByRole("button", { name: "Collapse sidebar" }));
+
+ expect(screen.getByText("Jobs")).toHaveClass("sr-only");
+ });
+
+ it("persists the collapsed state as a cookie", async () => {
+ const user = userEvent.setup();
+ renderSidebar();
+
+ await user.click(screen.getByRole("button", { name: "Collapse sidebar" }));
+
+ expect(document.cookie).toContain(
+ `${APP_CONSTANTS.SIDEBAR_STORAGE_KEY}=false`
+ );
+ });
+
+ it("points aria-controls at the sidebar element", () => {
+ renderSidebar();
+
+ const toggle = screen.getByRole("button", { name: "Collapse sidebar" });
+ const target = toggle.getAttribute("aria-controls");
+
+ expect(document.getElementById(target!)).toBe(
+ screen.getByRole("complementary")
+ );
+ });
+});
diff --git a/__tests__/SidebarContext.spec.tsx b/__tests__/SidebarContext.spec.tsx
new file mode 100644
index 0000000..08143c7
--- /dev/null
+++ b/__tests__/SidebarContext.spec.tsx
@@ -0,0 +1,151 @@
+import { act, render, renderHook, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { SidebarProvider, useSidebar } from "@/context/SidebarContext";
+import { APP_CONSTANTS } from "@/lib/constants";
+
+function makeWrapper(initialExpanded: boolean) {
+ return function Wrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <SidebarProvider initialExpanded={initialExpanded}>
+ {children}
+ </SidebarProvider>
+ );
+ };
+}
+
+describe("SidebarContext", () => {
+ beforeEach(() => {
+ // Clear any cookie left over from a previous test's toggle().
+ document.cookie = `${APP_CONSTANTS.SIDEBAR_STORAGE_KEY}=; path=/; max-age=0`;
+ });
+
+ it("uses the initialExpanded value passed in", () => {
+ const { result } = renderHook(() => useSidebar(), {
+ wrapper: makeWrapper(true),
+ });
+
+ expect(result.current.expanded).toBe(true);
+ });
+
+ it("respects a false initialExpanded value", () => {
+ const { result } = renderHook(() => useSidebar(), {
+ wrapper: makeWrapper(false),
+ });
+
+ expect(result.current.expanded).toBe(false);
+ });
+
+ it("persists the state as a cookie when toggled", () => {
+ const { result } = renderHook(() => useSidebar(), {
+ wrapper: makeWrapper(true),
+ });
+
+ act(() => result.current.toggle());
+
+ expect(result.current.expanded).toBe(false);
+ expect(document.cookie).toContain(
+ `${APP_CONSTANTS.SIDEBAR_STORAGE_KEY}=false`
+ );
+
+ act(() => result.current.toggle());
+
+ expect(result.current.expanded).toBe(true);
+ expect(document.cookie).toContain(
+ `${APP_CONSTANTS.SIDEBAR_STORAGE_KEY}=true`
+ );
+ });
+
+ it("toggles on Cmd/Ctrl+B", async () => {
+ const user = userEvent.setup();
+ const { result } = renderHook(() => useSidebar(), {
+ wrapper: makeWrapper(true),
+ });
+
+ await user.keyboard("{Meta>}b{/Meta}");
+ expect(result.current.expanded).toBe(false);
+
+ await user.keyboard("{Control>}b{/Control}");
+ expect(result.current.expanded).toBe(true);
+ });
+
+ it("ignores a bare 'b' keypress", async () => {
+ const user = userEvent.setup();
+ const { result } = renderHook(() => useSidebar(), {
+ wrapper: makeWrapper(true),
+ });
+
+ await user.keyboard("b");
+
+ expect(result.current.expanded).toBe(true);
+ });
+
+ // Tiptap binds Mod-b to bold; the sidebar shortcut must not steal it.
+ it("ignores Cmd/Ctrl+B while focus is in an editable element", async () => {
+ const user = userEvent.setup();
+
+ function Consumer() {
+ const { expanded } = useSidebar();
+ return (
+ <>
+ <span>{expanded ? "expanded" : "collapsed"}</span>
+ <input aria-label="note" />
+ </>
+ );
+ }
+
+ render(
+ <SidebarProvider initialExpanded={true}>
+ <Consumer />
+ </SidebarProvider>
+ );
+
+ await user.click(screen.getByLabelText("note"));
+ await user.keyboard("{Meta>}b{/Meta}");
+
+ expect(screen.getByText("expanded")).toBeInTheDocument();
+ });
+
+ it("throws when used outside the provider", () => {
+ const consoleError = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ function Orphan() {
+ useSidebar();
+ return null;
+ }
+
+ expect(() => render(<Orphan />)).toThrow(
+ "useSidebar must be used within a SidebarProvider"
+ );
+
+ consoleError.mockRestore();
+ });
+
+ it("shares one state across consumers", async () => {
+ const user = userEvent.setup();
+
+ function Consumer() {
+ const { expanded, toggle } = useSidebar();
+ return (
+ <>
+ <span>{expanded ? "expanded" : "collapsed"}</span>
+ <button onClick={toggle}>toggle</button>
+ </>
+ );
+ }
+
+ render(
+ <SidebarProvider initialExpanded={true}>
+ <Consumer />
+ <Consumer />
+ </SidebarProvider>
+ );
+
+ expect(screen.getAllByText("expanded")).toHaveLength(2);
+
+ await user.click(screen.getAllByRole("button", { name: "toggle" })[0]);
+
+ expect(screen.getAllByText("collapsed")).toHaveLength(2);
+ });
+});
diff --git a/src/app/dashboard/layout.tsx b/src/app/dashboard/layout.tsx
index 300c4fe..6f36c9b 100644
--- a/src/app/dashboard/layout.tsx
+++ b/src/app/dashboard/layout.tsx
@@ -1,27 +1,37 @@
+import { cookies } from "next/headers";
import Header from "@/components/Header";
import Sidebar from "@/components/Sidebar";
import { Toaster } from "@/components/ui/toaster";
import { ActivityProvider } from "@/context/ActivityContext";
import { GlobalActivityBanner } from "@/components/activities/GlobalActivityBanner";
+import { SidebarProvider } from "@/context/SidebarContext";
+import SidebarInset from "@/components/SidebarInset";
+import { APP_CONSTANTS } from "@/lib/constants";
-export default function RootLayout({
+export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
+ const cookieStore = await cookies();
+ const sidebarCookie = cookieStore.get(APP_CONSTANTS.SIDEBAR_STORAGE_KEY);
+ const initialExpanded = sidebarCookie ? sidebarCookie.value === "true" : true;
+
return (
<ActivityProvider>
- <div className="flex min-h-screen w-full flex-col bg-muted/40">
- <Sidebar />
- <div className="flex flex-1 flex-col sm:gap-4 sm:py-4 sm:pl-14">
- <Header />
- <GlobalActivityBanner />
- <main className="flex-1 md:block lg:grid items-start gap-4 p-4 sm:px-6 sm:py-0 md:gap-4 lg:grid-cols-3 xl:grid-cols-3">
- {children}
- </main>
- <Toaster />
+ <SidebarProvider initialExpanded={initialExpanded}>
+ <div className="flex min-h-screen w-full flex-col bg-muted/40">
+ <Sidebar />
+ <SidebarInset>
+ <Header />
+ <GlobalActivityBanner />
+ <main className="flex-1 md:block lg:grid items-start gap-4 p-4 sm:px-6 sm:py-0 md:gap-4 lg:grid-cols-3 xl:grid-cols-3">
+ {children}
+ </main>
+ <Toaster />
+ </SidebarInset>
</div>
- </div>
+ </SidebarProvider>
</ActivityProvider>
);
}
diff --git a/src/app/globals.css b/src/app/globals.css
index 9035f87..91b26d2 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -145,7 +145,7 @@
/* Navlink */
.navlink {
- @apply flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:text-foreground md:h-8 md:w-8;
+ @apply relative flex items-center overflow-hidden transition-colors;
}
}
diff --git a/src/components/Header.tsx b/src/components/Header.tsx
index 991634d..ae4d1d1 100644
--- a/src/components/Header.tsx
+++ b/src/components/Header.tsx
@@ -13,6 +13,7 @@ import { SIDEBAR_LINKS } from "@/lib/constants";
import { signOut } from "@/auth";
import { getCurrentUser } from "@/utils/user.utils";
import { ProfileDropdown } from "./ProfileDropdown";
+import SidebarToggle from "./SidebarToggle";
async function Header() {
// const session = await auth();
@@ -58,6 +59,7 @@ async function Header() {
</nav>
</SheetContent>
</Sheet>
+ <SidebarToggle />
<h1 className="font-semibold">JobSync - Job Search Assistant</h1>
<div className="relative ml-auto flex-1 md:grow-0">
{/* <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
diff --git a/src/components/NavLink.tsx b/src/components/NavLink.tsx
index 76ad3ee..6420d84 100644
--- a/src/components/NavLink.tsx
+++ b/src/components/NavLink.tsx
@@ -16,28 +16,50 @@ interface NavLinkProps {
>;
route: string;
pathname: string;
+ expanded: boolean;
}
-function NavLink({ label, Icon, route, pathname }: NavLinkProps) {
+function NavLink({ label, Icon, route, pathname, expanded }: NavLinkProps) {
+ // "/dashboard" is a prefix of every other route, so it only matches exactly.
const isActive =
- route === pathname || pathname.startsWith(`${route}/dashboard`);
+ pathname === route ||
+ (route !== "/dashboard" && pathname.startsWith(`${route}/`));
+
+ const link = (
+ <Link
+ href={route}
+ aria-current={isActive ? "page" : undefined}
+ className={cn(
+ "navlink w-full hover:text-foreground",
+ expanded ? "h-10 justify-start gap-3 px-4" : "h-12 justify-center",
+ isActive ? "text-foreground" : "text-muted-foreground",
+ isActive && expanded && "rounded-md bg-accent"
+ )}
+ >
+ {isActive && (
+ <span
+ aria-hidden
+ className="absolute left-0 top-0 h-full w-0.5 bg-foreground"
+ />
+ )}
+ <Icon className="h-6 w-6 shrink-0" strokeWidth={1.5} />
+ {/* Collapsed uses sr-only, not opacity: an in-flow hidden span still
+ takes flex space and pushes the icon off-center in the rail. */}
+ {expanded ? (
+ <span className="truncate text-sm">{label}</span>
+ ) : (
+ <span className="sr-only">{label}</span>
+ )}
+ </Link>
+ );
+
+ if (expanded) {
+ return link;
+ }
+
return (
<Tooltip>
- <TooltipTrigger asChild>
- <Link
- href={route}
- className={cn("navlink", {
- "border-b-2 border-black dark:border-white": isActive,
- })}
- >
- <Icon
- className={cn("h-5 w-5", {
- "text-black dark:text-white": isActive,
- })}
- />
- <span className="sr-only">{label}</span>
- </Link>
- </TooltipTrigger>
+ <TooltipTrigger asChild>{link}</TooltipTrigger>
<TooltipContent side="right">{label}</TooltipContent>
</Tooltip>
);
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index 212197e..08f9e44 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -3,52 +3,83 @@ import Link from "next/link";
import { TooltipProvider } from "@/components/ui/tooltip";
import { Briefcase, Settings } from "lucide-react";
-import { SIDEBAR_LINKS } from "@/lib/constants";
+import { APP_CONSTANTS, SIDEBAR_LINKS } from "@/lib/constants";
import NavLink from "./NavLink";
import { usePathname } from "next/navigation";
+import { useSidebar } from "@/context/SidebarContext";
+import { cn } from "@/lib/utils";
function Sidebar() {
const path = usePathname();
+ const { expanded } = useSidebar();
+
return (
- <aside className="fixed inset-y-0 left-0 z-10 hidden w-14 flex-col border-r bg-background sm:flex">
- <nav className="flex flex-col items-center gap-4 px-2 sm:py-5">
- <Link
- href="/"
- className="group flex h-9 w-9 shrink-0 items-center justify-center gap-2 rounded-full bg-primary text-lg font-semibold text-primary-foreground md:h-8 md:w-8 md:text-base"
+ <TooltipProvider delayDuration={300}>
+ <aside
+ id={APP_CONSTANTS.SIDEBAR_DOM_ID}
+ className={cn(
+ "fixed inset-y-0 left-0 z-10 hidden flex-col border-r bg-background transition-[width] duration-200 ease-in-out sm:flex",
+ expanded
+ ? APP_CONSTANTS.SIDEBAR_WIDTH.expanded.rail
+ : APP_CONSTANTS.SIDEBAR_WIDTH.collapsed.rail
+ )}
+ >
+ <div
+ className={cn(
+ "flex h-14 shrink-0 items-center gap-2",
+ expanded ? "px-4" : "justify-center"
+ )}
+ >
+ <Link
+ href="/"
+ className="group flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground md:h-8 md:w-8"
+ >
+ <Briefcase className="h-4 w-4 transition-transform group-hover:scale-110" />
+ <span className="sr-only">JobSync</span>
+ </Link>
+ {expanded && <span className="truncate font-semibold">JobSync</span>}
+ </div>
+
+ <nav
+ className={cn(
+ "flex flex-1 flex-col overflow-y-auto py-2",
+ expanded ? "gap-0.5" : "gap-2"
+ )}
>
- <Briefcase className="h-4 w-4 transition-all group-hover:scale-110" />
- <span className="sr-only">JobSync</span>
- </Link>
- <TooltipProvider delayDuration={800}>
{SIDEBAR_LINKS.map((item) => {
// Only show dev-only items in development mode
if (item.devOnly && process.env.NODE_ENV !== "development") {
return null;
}
return (
- <div key={item.label} className="text-white fill-color">
- <NavLink
- label={item.label}
- Icon={item.icon}
- route={item.route}
- pathname={path}
- />
- </div>
+ <NavLink
+ key={item.label}
+ label={item.label}
+ Icon={item.icon}
+ route={item.route}
+ pathname={path}
+ expanded={expanded}
+ />
);
})}
- </TooltipProvider>
- </nav>
- <nav className="mt-auto flex flex-col items-center gap-4 px-2 sm:py-5">
- <TooltipProvider>
+ </nav>
+
+ <div
+ className={cn(
+ "flex flex-col py-2",
+ expanded ? "gap-0.5 border-t" : "gap-2"
+ )}
+ >
<NavLink
label="Settings"
Icon={Settings}
route="/dashboard/settings"
pathname={path}
+ expanded={expanded}
/>
- </TooltipProvider>
- </nav>
- </aside>
+ </div>
+ </aside>
+ </TooltipProvider>
);
}
diff --git a/src/components/SidebarInset.tsx b/src/components/SidebarInset.tsx
new file mode 100644
index 0000000..fda0b1d
--- /dev/null
+++ b/src/components/SidebarInset.tsx
@@ -0,0 +1,24 @@
+"use client";
+
+import { useSidebar } from "@/context/SidebarContext";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { cn } from "@/lib/utils";
+
+// Offsets page content by the sidebar's current width.
+function SidebarInset({ children }: { children: React.ReactNode }) {
+ const { expanded } = useSidebar();
+ return (
+ <div
+ className={cn(
+ "flex flex-1 flex-col transition-[padding] duration-200 ease-in-out sm:gap-4 sm:py-4",
+ expanded
+ ? APP_CONSTANTS.SIDEBAR_WIDTH.expanded.contentOffset
+ : APP_CONSTANTS.SIDEBAR_WIDTH.collapsed.contentOffset
+ )}
+ >
+ {children}
+ </div>
+ );
+}
+
+export default SidebarInset;
diff --git a/src/components/SidebarToggle.tsx b/src/components/SidebarToggle.tsx
new file mode 100644
index 0000000..1459d5a
--- /dev/null
+++ b/src/components/SidebarToggle.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import { PanelLeft } from "lucide-react";
+import { Button } from "./ui/button";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
+import { useSidebar } from "@/context/SidebarContext";
+import { APP_CONSTANTS } from "@/lib/constants";
+
+// Desktop counterpart to the mobile Sheet trigger in Header.
+function SidebarToggle() {
+ const { expanded, toggle } = useSidebar();
+
+ return (
+ <TooltipProvider delayDuration={300}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={toggle}
+ aria-expanded={expanded}
+ aria-controls={APP_CONSTANTS.SIDEBAR_DOM_ID}
+ aria-label={expanded ? "Collapse sidebar" : "Expand sidebar"}
+ className="hidden sm:inline-flex"
+ >
+ <PanelLeft className="h-5 w-5" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ {expanded ? "Collapse sidebar" : "Expand sidebar"}
+ <kbd className="ml-2 rounded border px-1 text-[10px]">⌘B</kbd>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
+}
+
+export default SidebarToggle;
diff --git a/src/context/SidebarContext.tsx b/src/context/SidebarContext.tsx
new file mode 100644
index 0000000..14208d4
--- /dev/null
+++ b/src/context/SidebarContext.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import { createContext, useCallback, useContext, useEffect, useState } from "react";
+import { APP_CONSTANTS } from "@/lib/constants";
+
+type SidebarContextValue = {
+ expanded: boolean;
+ toggle: () => void;
+};
+
+const SidebarContext = createContext<SidebarContextValue | null>(null);
+
+// One year, so the preference persists like a typical "remember my setting" cookie.
+const COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365;
+
+export function SidebarProvider({
+ children,
+ initialExpanded,
+}: {
+ children: React.ReactNode;
+ initialExpanded: boolean;
+}) {
+ const [expanded, setExpanded] = useState(initialExpanded);
+
+ const toggle = useCallback(() => {
+ setExpanded((prev) => !prev);
+ }, []);
+
+ useEffect(() => {
+ document.cookie = `${APP_CONSTANTS.SIDEBAR_STORAGE_KEY}=${expanded}; path=/; max-age=${COOKIE_MAX_AGE_SECONDS}; samesite=lax`;
+ }, [expanded]);
+
+ useEffect(() => {
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key.toLowerCase() !== "b" || (!e.metaKey && !e.ctrlKey)) return;
+
+ // Let editable elements (inputs, Tiptap/ProseMirror) keep Cmd/Ctrl+B
+ // for their own shortcuts (e.g. bold) instead of toggling the sidebar.
+ const target = e.target as HTMLElement | null;
+ if (target?.closest('input, textarea, [contenteditable="true"]')) return;
+
+ e.preventDefault();
+ toggle();
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [toggle]);
+
+ return (
+ <SidebarContext.Provider value={{ expanded, toggle }}>
+ {children}
+ </SidebarContext.Provider>
+ );
+}
+
+export function useSidebar() {
+ const ctx = useContext(SidebarContext);
+ if (!ctx) {
+ throw new Error("useSidebar must be used within a SidebarProvider");
+ }
+ return ctx;
+}
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 9890d47..35efef9 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -28,6 +28,13 @@ export const APP_CONSTANTS = {
AI_SLOW_RESPONSE_THRESHOLD_MS: 15_000, // 15 seconds
INTERSECTION_OBSERVER_THRESHOLD: 0.1,
TOAST_LIMIT: 1,
+ SIDEBAR_STORAGE_KEY: "sidebar-expanded",
+ SIDEBAR_DOM_ID: "app-sidebar",
+ // Paired so the rail width and its matching content offset can't drift.
+ SIDEBAR_WIDTH: {
+ expanded: { rail: "w-56", contentOffset: "sm:pl-56" },
+ collapsed: { rail: "w-14", contentOffset: "sm:pl-14" },
+ },
// Ollama API timeouts
AI_OLLAMA_LIST_TIMEOUT_MS: 5_000,