1
0

feat: router, tab shell, setup and login pages

This commit is contained in:
2026-08-29 19:50:10 +02:00
parent fdf200a960
commit bda43ce237
10 changed files with 413 additions and 7 deletions

View File

@@ -1,7 +1,46 @@
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
import type { ReactNode } from 'react'
import { AuthProvider, useAuth } from './auth'
import Shell from './shell'
import SetupPage from './pages/SetupPage'
import LoginPage from './pages/LoginPage'
import LibraryPage from './pages/LibraryPage'
import ScanPage from './pages/ScanPage'
import AddPage from './pages/AddPage'
import SettingsPage from './pages/SettingsPage'
function Gate({ children }: { children: ReactNode }) {
const { status } = useAuth()
if (status === 'loading') {
return <div className="min-h-dvh bg-neutral-950" aria-busy="true" />
}
if (status === 'setup') return <Navigate to="/setup" replace />
if (status === 'unauthenticated') return <Navigate to="/login" replace />
return <>{children}</>
}
export default function App() { export default function App() {
return ( return (
<div className="min-h-dvh bg-neutral-950 text-neutral-100 flex items-center justify-center"> <AuthProvider>
<h1 className="text-2xl font-semibold">record-shop</h1> <BrowserRouter>
</div> <Routes>
<Route path="/setup" element={<SetupPage />} />
<Route path="/login" element={<LoginPage />} />
<Route
element={
<Gate>
<Shell />
</Gate>
}
>
<Route path="/library" element={<LibraryPage />} />
<Route path="/scan" element={<ScanPage />} />
<Route path="/add" element={<AddPage />} />
<Route path="/settings" element={<SettingsPage />} />
</Route>
<Route path="*" element={<Navigate to="/library" replace />} />
</Routes>
</BrowserRouter>
</AuthProvider>
) )
} }

View File

@@ -0,0 +1,3 @@
export default function AddPage() {
return <p className="text-neutral-400">Search goes here.</p>
}

View File

@@ -0,0 +1,3 @@
export default function LibraryPage() {
return <p className="text-neutral-400">Library goes here.</p>
}

View File

@@ -0,0 +1,71 @@
import { useState, type FormEvent } from 'react'
import { useNavigate } from 'react-router-dom'
import { api, ApiError } from '../api'
import { useAuth } from '../auth'
export default function LoginPage() {
const { onLogin } = useAuth()
const navigate = useNavigate()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
async function submit(e: FormEvent) {
e.preventDefault()
setBusy(true)
setError(null)
try {
const { user } = await api.login(username, password)
onLogin(user)
navigate('/library', { replace: true })
} catch (err) {
setError(err instanceof ApiError && err.status === 401 ? 'Wrong username or password' : 'Something went wrong')
} finally {
setBusy(false)
}
}
return (
<div className="min-h-dvh bg-neutral-950 text-neutral-100 flex items-center justify-center p-4">
<form onSubmit={submit} className="w-full max-w-sm space-y-4">
<h1 className="text-2xl font-semibold">Sign in</h1>
<div>
<label htmlFor="username" className="mb-1 block text-sm">
Username
</label>
<input
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full rounded-lg border border-neutral-700 bg-neutral-900 px-3 py-2"
autoComplete="username"
required
/>
</div>
<div>
<label htmlFor="password" className="mb-1 block text-sm">
Password
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full rounded-lg border border-neutral-700 bg-neutral-900 px-3 py-2"
autoComplete="current-password"
required
/>
</div>
{error && <p className="text-sm text-red-400">{error}</p>}
<button
type="submit"
disabled={busy}
className="w-full rounded-lg bg-emerald-500 py-2 font-medium text-neutral-950 disabled:opacity-50"
>
Sign in
</button>
</form>
</div>
)
}

View File

@@ -0,0 +1,3 @@
export default function ScanPage() {
return <p className="text-neutral-400">Scanner goes here.</p>
}

View File

@@ -0,0 +1,14 @@
import { useAuth } from '../auth'
export default function SettingsPage() {
const { user, onLogout } = useAuth()
return (
<section>
<h2 className="mb-2 text-sm font-semibold uppercase tracking-wide text-neutral-400">Settings</h2>
<p>Account</p>
<p className="text-neutral-400">
{user?.username} {user?.isAdmin ? '(admin)' : ''}
</p>
</section>
)
}

View File

@@ -0,0 +1,74 @@
import { useState, type FormEvent } from 'react'
import { useNavigate } from 'react-router-dom'
import { api, ApiError } from '../api'
import { useAuth } from '../auth'
export default function SetupPage() {
const { onSetupComplete } = useAuth()
const navigate = useNavigate()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
async function submit(e: FormEvent) {
e.preventDefault()
setBusy(true)
setError(null)
try {
const { user } = await api.setup(username, password)
onSetupComplete(user)
navigate('/library', { replace: true })
} catch (err) {
setError(err instanceof ApiError ? err.detail ?? err.code : 'Something went wrong')
} finally {
setBusy(false)
}
}
return (
<div className="min-h-dvh bg-neutral-950 text-neutral-100 flex items-center justify-center p-4">
<form onSubmit={submit} className="w-full max-w-sm space-y-4">
<h1 className="text-2xl font-semibold">Welcome to record-shop</h1>
<p className="text-sm text-neutral-400">Create the admin account to get started.</p>
<div>
<label htmlFor="username" className="mb-1 block text-sm">
Username
</label>
<input
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full rounded-lg border border-neutral-700 bg-neutral-900 px-3 py-2"
autoComplete="username"
required
minLength={3}
/>
</div>
<div>
<label htmlFor="password" className="mb-1 block text-sm">
Password
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full rounded-lg border border-neutral-700 bg-neutral-900 px-3 py-2"
autoComplete="new-password"
required
minLength={8}
/>
</div>
{error && <p className="text-sm text-red-400">{error}</p>}
<button
type="submit"
disabled={busy}
className="w-full rounded-lg bg-emerald-500 py-2 font-medium text-neutral-950 disabled:opacity-50"
>
Create admin account
</button>
</form>
</div>
)
}

79
web/src/shell.tsx Normal file
View File

@@ -0,0 +1,79 @@
import { NavLink, Outlet } from 'react-router-dom'
import type { ReactNode } from 'react'
const TABS: { to: string; label: string; icon: ReactNode }[] = [
{
to: '/library',
label: 'Library',
icon: (
<svg viewBox="0 0 24 24" className="size-6" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
<rect x="3" y="3" width="18" height="18" rx="2" />
<path d="M3 9h18M9 21V9" />
</svg>
),
},
{
to: '/scan',
label: 'Scan',
icon: (
<svg viewBox="0 0 24 24" className="size-6" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
<path d="M3 7V5a2 2 0 0 1 2-2h2M17 3h2a2 2 0 0 1 2 2v2M21 17v2a2 2 0 0 1-2 2h-2M7 21H5a2 2 0 0 1-2-2v-2M7 12h10" />
</svg>
),
},
{
to: '/add',
label: 'Add',
icon: (
<svg viewBox="0 0 24 24" className="size-6" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v8M8 12h8" />
</svg>
),
},
{
to: '/settings',
label: 'Settings',
icon: (
<svg viewBox="0 0 24 24" className="size-6" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33h.01a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51h.01a1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v.01a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z" />
</svg>
),
},
]
export default function Shell({ title }: { title?: string }) {
return (
<div className="min-h-dvh bg-neutral-950 text-neutral-100">
<header className="sticky top-0 z-10 border-b border-neutral-800 bg-neutral-950/90 backdrop-blur">
<h1 className="mx-auto max-w-3xl px-4 py-3 text-lg font-semibold">{title ?? 'record-shop'}</h1>
</header>
<main className="mx-auto max-w-3xl px-4 pb-24 pt-4">
<Outlet />
</main>
<nav
aria-label="Main"
className="fixed inset-x-0 bottom-0 z-10 border-t border-neutral-800 bg-neutral-950/95 backdrop-blur"
>
<div className="mx-auto flex max-w-3xl">
{TABS.map((tab) => (
<NavLink
key={tab.to}
to={tab.to}
role="tab"
className={({ isActive }) =>
`flex flex-1 flex-col items-center gap-1 py-2 text-xs ${
isActive ? 'text-emerald-400' : 'text-neutral-400'
}`
}
>
{tab.icon}
{tab.label}
</NavLink>
))}
</div>
</nav>
</div>
)
}

99
web/test/router.test.tsx Normal file
View File

@@ -0,0 +1,99 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import App from '../src/App'
const fetchMock = vi.fn()
beforeEach(() => {
fetchMock.mockReset()
vi.stubGlobal('fetch', fetchMock)
window.history.replaceState(null, '', '/')
})
function json(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'content-type': 'application/json' },
})
}
function loggedInServer() {
fetchMock.mockImplementation((url: string) => {
if (url === '/api/setup') return Promise.resolve(json(200, { needed: false }))
if (url === '/api/me') return Promise.resolve(json(200, { user: { id: 1, username: 'sam', isAdmin: true } }))
return Promise.resolve(json(404, { error: 'not_found' }))
})
}
describe('routing', () => {
it('shows the setup form when the server needs setup', async () => {
fetchMock.mockImplementation((url: string) =>
url === '/api/setup' ? Promise.resolve(json(200, { needed: true })) : Promise.resolve(json(404, {}))
)
render(<App />)
await waitFor(() => expect(screen.getByRole('heading', { name: /welcome/i })).toBeTruthy())
})
it('shows the login form when unauthenticated', async () => {
fetchMock.mockImplementation((url: string) => {
if (url === '/api/setup') return Promise.resolve(json(200, { needed: false }))
return Promise.resolve(json(401, { error: 'unauthorized' }))
})
render(<App />)
await waitFor(() => expect(screen.getByRole('heading', { name: /sign in/i })).toBeTruthy())
})
it('lands on Library with the tab bar when authenticated', async () => {
loggedInServer()
render(<App />)
await waitFor(() => expect(screen.getByRole('tab', { name: /library/i })).toBeTruthy())
for (const tab of ['Library', 'Scan', 'Add', 'Settings']) {
expect(screen.getByRole('tab', { name: new RegExp(tab, 'i') })).toBeTruthy()
}
})
it('login form authenticates and enters the app', async () => {
fetchMock.mockImplementation((url: string) => {
if (url === '/api/setup') return Promise.resolve(json(200, { needed: false }))
if (url === '/api/me') return Promise.resolve(json(401, { error: 'unauthorized' }))
if (url === '/api/login') {
return Promise.resolve(json(200, { user: { id: 1, username: 'sam', isAdmin: true } }))
}
return Promise.resolve(json(404, {}))
})
render(<App />)
await waitFor(() => expect(screen.getByLabelText(/username/i)).toBeTruthy())
await userEvent.type(screen.getByLabelText(/username/i), 'sam')
await userEvent.type(screen.getByLabelText(/password/i), 'password123')
await userEvent.click(screen.getByRole('button', { name: /sign in/i }))
await waitFor(() => expect(screen.getByRole('tab', { name: /library/i })).toBeTruthy())
})
it('setup form creates the admin account and enters the app', async () => {
fetchMock.mockImplementation((url: string, init?: RequestInit) => {
if (url === '/api/setup' && (!init || !init.method || init.method === 'GET')) {
return Promise.resolve(json(200, { needed: true }))
}
if (url === '/api/setup' && init?.method === 'POST') {
return Promise.resolve(json(200, { user: { id: 1, username: 'boss', isAdmin: true } }))
}
return Promise.resolve(json(404, {}))
})
render(<App />)
await waitFor(() => expect(screen.getByLabelText(/username/i)).toBeTruthy())
await userEvent.type(screen.getByLabelText(/username/i), 'boss')
await userEvent.type(screen.getByLabelText(/password/i), 'password123')
await userEvent.click(screen.getByRole('button', { name: /create/i }))
await waitFor(() => expect(screen.getByRole('tab', { name: /library/i })).toBeTruthy())
})
it('tab navigation switches pages', async () => {
loggedInServer()
render(<App />)
await waitFor(() => expect(screen.getByRole('tab', { name: /settings/i })).toBeTruthy())
await userEvent.click(screen.getByRole('tab', { name: /settings/i }))
await waitFor(() => expect(screen.getByRole('heading', { name: /settings/i })).toBeTruthy())
expect(screen.getByText(/account/i)).toBeTruthy()
})
})

View File

@@ -1,10 +1,31 @@
import { describe, it, expect } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react' import { render, screen, waitFor } from '@testing-library/react'
import App from '../src/App' import App from '../src/App'
const fetchMock = vi.fn()
beforeEach(() => {
fetchMock.mockReset()
vi.stubGlobal('fetch', fetchMock)
window.history.replaceState(null, '', '/')
})
function json(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'content-type': 'application/json' },
})
}
describe('App', () => { describe('App', () => {
it('renders the app title', () => { it('renders the app title', async () => {
fetchMock.mockImplementation((url: string) => {
if (url === '/api/setup') return Promise.resolve(json(200, { needed: false }))
if (url === '/api/me')
return Promise.resolve(json(200, { user: { id: 1, username: 'sam', isAdmin: true } }))
return Promise.resolve(json(404, {}))
})
render(<App />) render(<App />)
expect(screen.getByRole('heading', { name: 'record-shop' })).toBeTruthy() await waitFor(() => expect(screen.getByRole('heading', { name: 'record-shop' })).toBeTruthy())
}) })
}) })