feat(web): collapsible icon sidebar (persisted, auto-collapse on narrow) (#44, #58)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-06 23:44:40 +02:00
parent 04c33cb1aa
commit 184e4ea2a5
6 changed files with 195 additions and 48 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"app": { "name": "Collection" }, "app": { "name": "Collection" },
"nav": { "objects": "Objects", "vocabularies": "Vocabularies", "authorities": "Authorities", "fields": "Fields", "search": "Search" }, "nav": { "objects": "Objects", "vocabularies": "Vocabularies", "authorities": "Authorities", "fields": "Fields", "search": "Search", "collapseSidebar": "Collapse sidebar", "expandSidebar": "Expand sidebar" },
"auth": { "email": "Email", "password": "Password", "signIn": "Sign in", "signOut": "Sign out", "invalid": "Invalid email or password", "networkError": "Could not reach the server" }, "auth": { "email": "Email", "password": "Password", "signIn": "Sign in", "signOut": "Sign out", "invalid": "Invalid email or password", "networkError": "Could not reach the server" },
"objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "selectPrompt": "Select an object to view its details", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object", "filter": "Filter objects…", "pageSize": "Per page", "columns": { "number": "Object №", "name": "Name", "visibility": "Visibility", "location": "Location", "count": "#", "updated": "Updated" } }, "objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "selectPrompt": "Select an object to view its details", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object", "filter": "Filter objects…", "pageSize": "Per page", "columns": { "number": "Object №", "name": "Name", "visibility": "Visibility", "location": "Location", "count": "#", "updated": "Updated" } },
"fieldsLabels": { "objectNumber": "Object number", "objectName": "Name", "count": "Number of objects", "briefDescription": "Brief description", "currentLocation": "Current location", "currentOwner": "Current owner", "recorder": "Recorder", "recordingDate": "Recording date", "visibility": "Visibility", "flexible": "Catalogue fields" }, "fieldsLabels": { "objectNumber": "Object number", "objectName": "Name", "count": "Number of objects", "briefDescription": "Brief description", "currentLocation": "Current location", "currentOwner": "Current owner", "recorder": "Recorder", "recordingDate": "Recording date", "visibility": "Visibility", "flexible": "Catalogue fields" },
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"app": { "name": "Samling" }, "app": { "name": "Samling" },
"nav": { "objects": "Föremål", "vocabularies": "Vokabulär", "authorities": "Auktoriteter", "fields": "Fält", "search": "Sök" }, "nav": { "objects": "Föremål", "vocabularies": "Vokabulär", "authorities": "Auktoriteter", "fields": "Fält", "search": "Sök", "collapseSidebar": "Fäll ihop sidofältet", "expandSidebar": "Fäll ut sidofältet" },
"auth": { "email": "E-post", "password": "Lösenord", "signIn": "Logga in", "signOut": "Logga ut", "invalid": "Fel e-post eller lösenord", "networkError": "Kunde inte nå servern" }, "auth": { "email": "E-post", "password": "Lösenord", "signIn": "Logga in", "signOut": "Logga ut", "invalid": "Fel e-post eller lösenord", "networkError": "Kunde inte nå servern" },
"objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "selectPrompt": "Välj ett föremål för att se detaljer", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål", "filter": "Filtrera föremål…", "pageSize": "Per sida", "columns": { "number": "Föremålsnr", "name": "Namn", "visibility": "Synlighet", "location": "Plats", "count": "Antal", "updated": "Uppdaterad" } }, "objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "selectPrompt": "Välj ett föremål för att se detaljer", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål", "filter": "Filtrera föremål…", "pageSize": "Per sida", "columns": { "number": "Föremålsnr", "name": "Namn", "visibility": "Synlighet", "location": "Plats", "count": "Antal", "updated": "Uppdaterad" } },
"fieldsLabels": { "objectNumber": "Föremålsnummer", "objectName": "Namn", "count": "Antal föremål", "briefDescription": "Kort beskrivning", "currentLocation": "Nuvarande plats", "currentOwner": "Nuvarande ägare", "recorder": "Registrerad av", "recordingDate": "Registreringsdatum", "visibility": "Synlighet", "flexible": "Katalogfält" }, "fieldsLabels": { "objectNumber": "Föremålsnummer", "objectName": "Namn", "count": "Antal föremål", "briefDescription": "Kort beskrivning", "currentLocation": "Nuvarande plats", "currentOwner": "Nuvarande ägare", "recorder": "Registrerad av", "recordingDate": "Registreringsdatum", "visibility": "Synlighet", "flexible": "Katalogfält" },
+3 -46
View File
@@ -1,9 +1,10 @@
import { NavLink, Outlet, useNavigate } from "react-router-dom"; import { Outlet, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useLogout } from "../api/queries"; import { useLogout } from "../api/queries";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { LangSwitch } from "./lang-switch"; import { LangSwitch } from "./lang-switch";
import { Sidebar } from "./sidebar";
export function AppShell() { export function AppShell() {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -17,51 +18,7 @@ export function AppShell() {
return ( return (
<div className="flex min-h-screen"> <div className="flex min-h-screen">
<aside className="w-44 shrink-0 border-r bg-neutral-50 p-3"> <Sidebar />
<div className="mb-4 font-semibold">{t("app.name")}</div>
<nav className="space-y-1 text-sm">
<NavLink
to="/objects"
className={({ isActive }) =>
`block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}`
}
>
{t("nav.objects")}
</NavLink>
<NavLink
to="/vocabularies"
className={({ isActive }) =>
`block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}`
}
>
{t("nav.vocabularies")}
</NavLink>
<NavLink
to="/authorities"
className={({ isActive }) =>
`block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}`
}
>
{t("nav.authorities")}
</NavLink>
<NavLink
to="/search"
className={({ isActive }) =>
`block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}`
}
>
{t("nav.search")}
</NavLink>
<NavLink
to="/fields"
className={({ isActive }) =>
`block rounded px-2 py-1 ${isActive ? "bg-neutral-200 font-medium" : ""}`
}
>
{t("nav.fields")}
</NavLink>
</nav>
</aside>
<div className="flex flex-1 flex-col"> <div className="flex flex-1 flex-col">
<header className="flex items-center gap-4 border-b px-4 py-2"> <header className="flex items-center gap-4 border-b px-4 py-2">
<div className="flex-1" /> <div className="flex-1" />
+45
View File
@@ -0,0 +1,45 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect } from 'storybook/test'
import { Sidebar } from './sidebar'
const meta = {
component: Sidebar,
tags: ['ai-generated'],
} satisfies Meta<typeof Sidebar>
export default meta
type Story = StoryObj<typeof meta>
// Expanded is the default wide-viewport state: the stored preference is "not
// collapsed", so the nav labels render inline next to their icons.
export const Expanded: Story = {
beforeEach: () => {
localStorage.setItem('sidebar-collapsed', 'false')
},
play: async ({ canvas }) => {
await expect(canvas.getByRole('link', { name: 'Objects' })).toBeVisible()
await expect(canvas.getByText('Vocabularies')).toBeVisible()
await expect(
canvas.getByRole('button', { name: 'Collapse sidebar' }),
).toBeVisible()
},
}
// Collapsed rail: labels are no longer inline text — each link exposes its
// label only via `aria-label` (and a tooltip rendered in a portal).
export const Collapsed: Story = {
beforeEach: () => {
localStorage.setItem('sidebar-collapsed', 'true')
},
play: async ({ canvas }) => {
const link = canvas.getByRole('link', { name: 'Objects' })
await expect(link).toBeVisible()
await expect(link).toHaveAttribute('aria-label', 'Objects')
// No inline label text in the collapsed rail.
await expect(canvas.queryByText('Vocabularies')).not.toBeInTheDocument()
await expect(
canvas.getByRole('button', { name: 'Expand sidebar' }),
).toBeVisible()
},
}
+126
View File
@@ -0,0 +1,126 @@
import { useEffect, useState } from "react";
import { NavLink } from "react-router-dom";
import { useTranslation } from "react-i18next";
import {
BookMarked,
Boxes,
PanelLeft,
PanelLeftClose,
Search,
Tags,
Users,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { Tooltip } from "@/components/ui/tooltip";
import { useMediaQuery } from "@/lib/use-media-query";
const STORAGE_KEY = "sidebar-collapsed";
type NavItem = {
to: string;
/** i18n key under `nav.*`. */
label: string;
Icon: LucideIcon;
};
const NAV_ITEMS: readonly NavItem[] = [
{ to: "/objects", label: "nav.objects", Icon: Boxes },
{ to: "/vocabularies", label: "nav.vocabularies", Icon: BookMarked },
{ to: "/authorities", label: "nav.authorities", Icon: Users },
{ to: "/search", label: "nav.search", Icon: Search },
{ to: "/fields", label: "nav.fields", Icon: Tags },
];
function readStored(): boolean {
if (typeof window === "undefined") return false;
return window.localStorage.getItem(STORAGE_KEY) === "true";
}
function navLinkClass(collapsed: boolean) {
return ({ isActive }: { isActive: boolean }) =>
cn(
"flex items-center gap-2 rounded px-2 py-1 outline-none",
"focus-visible:ring-3 focus-visible:ring-ring/50",
collapsed && "justify-center",
isActive && "bg-neutral-200 font-medium",
);
}
export function Sidebar() {
const { t } = useTranslation();
const narrow = useMediaQuery("(max-width: 768px)");
const [stored, setStored] = useState(readStored);
// On narrow viewports the rail is always collapsed regardless of the stored
// preference; the toggle only takes effect when wide.
const collapsed = narrow || stored;
useEffect(() => {
if (typeof window !== "undefined") {
window.localStorage.setItem(STORAGE_KEY, String(stored));
}
}, [stored]);
const toggle = () => setStored((prev) => !prev);
return (
<aside
className={cn(
"flex shrink-0 flex-col border-r bg-neutral-50 p-3 transition-[width]",
collapsed ? "w-14" : "w-44",
)}
>
<div className="mb-4 flex items-center justify-between">
{!collapsed && <span className="font-semibold">{t("app.name")}</span>}
<button
type="button"
onClick={toggle}
disabled={narrow}
aria-expanded={!collapsed}
aria-label={t(collapsed ? "nav.expandSidebar" : "nav.collapseSidebar")}
title={t(collapsed ? "nav.expandSidebar" : "nav.collapseSidebar")}
className={cn(
"flex items-center justify-center rounded p-1 outline-none",
"hover:bg-neutral-200 focus-visible:ring-3 focus-visible:ring-ring/50",
"disabled:pointer-events-none disabled:opacity-50",
)}
>
{collapsed ? (
<PanelLeft className="size-4" />
) : (
<PanelLeftClose className="size-4" />
)}
</button>
</div>
<nav className="space-y-1 text-sm">
{NAV_ITEMS.map(({ to, label, Icon }) => {
const text = t(label);
if (collapsed) {
return (
<Tooltip key={to} content={text} side="right">
<NavLink
to={to}
aria-label={text}
title={text}
className={navLinkClass(true)}
>
<Icon className="size-4" aria-hidden="true" />
</NavLink>
</Tooltip>
);
}
return (
<NavLink key={to} to={to} className={navLinkClass(false)}>
<Icon className="size-4" aria-hidden="true" />
<span>{text}</span>
</NavLink>
);
})}
</nav>
</aside>
);
}
+19
View File
@@ -21,6 +21,25 @@ if (typeof globalThis.localStorage === "undefined") {
}); });
} }
// jsdom does not implement matchMedia. useMediaQuery (used by the shell
// sidebar) calls it on mount, so provide a minimal non-matching stub.
if (typeof window !== "undefined" && typeof window.matchMedia !== "function") {
Object.defineProperty(window, "matchMedia", {
value: (query: string): MediaQueryList =>
({
matches: false,
media: query,
onchange: null,
addEventListener: () => {},
removeEventListener: () => {},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
}) as MediaQueryList,
writable: true,
});
}
// Start MSW at module level so its fetch patch is in place before any test // Start MSW at module level so its fetch patch is in place before any test
// module captures globalThis.fetch via openapi-fetch's createClient(). // module captures globalThis.fetch via openapi-fetch's createClient().
server.listen({ onUnhandledRequest: "error" }); server.listen({ onUnhandledRequest: "error" });