Commit 4b0e72d7 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add Soundmarks: location-tied anthems with role-gated admin panels

Frontend for the new backend feature - a Soundmark is a curated
"anthem" tied to a real place, either a super-admin-curated landmark
or a business's location. Three new surfaces:

- Nearby (Soundmarks nav item): uses the browser Geolocation API
  (getCurrentPosition + watchPosition, so it keeps tracking as you
  move) to find and play the anthem at your current spot, through the
  same shared player used everywhere else in the app.
- Business panel (/business, business_admin+): soundmarks you own,
  each with a "Change anthem" picker spanning your personal library
  and a new cross-user "public library" search.
- Admin panel (/admin, super_admin only): full CRUD for every
  soundmark regardless of owner, plus user role management
  (promote/demote business_admin).

AuthContext now fetches the caller's role via /auth/me and exposes
isBusinessAdmin/isSuperAdmin; a super admin passes both. RequireRole
gates the two new routes and Layout conditionally shows Business/
Admin links in the header. PlayerContext gained an optional
`streamUrl` override on PlayableSong so a soundmark's anthem can
stream via its own cross-user-safe endpoint instead of the
personal-library one, without touching the player's core logic.

Caught and fixed a real accessibility bug via testing: the header's
Business/Admin/Log out controls had their icon aria-hidden and their
label CSS-hidden on mobile, leaving them with no accessible name at
all - fixed with explicit aria-labels.

Verified with a real end-to-end Playwright run (not just unit tests):
logged in as super admin, created a soundmark through the actual UI,
assigned an anthem, then used Chromium's real geolocation mocking to
walk into it from the Nearby page and play it through the shared
player - zero console errors throughout. 82 total tests passing
(11 new: RequireRole, Nearby, BusinessPanel, AdminPanel, plus
AuthContext role coverage).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent b3a07d39
Pipeline #1052 failed with stage
...@@ -5,7 +5,11 @@ import { Discovery } from './pages/Discovery' ...@@ -5,7 +5,11 @@ import { Discovery } from './pages/Discovery'
import { Rooms } from './pages/Rooms' import { Rooms } from './pages/Rooms'
import { Channels } from './pages/Channels' import { Channels } from './pages/Channels'
import { Remix } from './pages/Remix' import { Remix } from './pages/Remix'
import { Nearby } from './pages/Nearby'
import { BusinessPanel } from './pages/BusinessPanel'
import { AdminPanel } from './pages/AdminPanel'
import { ProtectedRoute } from './components/ProtectedRoute' import { ProtectedRoute } from './components/ProtectedRoute'
import { RequireRole } from './components/RequireRole'
function protect(element: React.ReactElement) { function protect(element: React.ReactElement) {
return <ProtectedRoute>{element}</ProtectedRoute> return <ProtectedRoute>{element}</ProtectedRoute>
...@@ -20,6 +24,23 @@ export function App() { ...@@ -20,6 +24,23 @@ export function App() {
<Route path="/rooms" element={protect(<Rooms />)} /> <Route path="/rooms" element={protect(<Rooms />)} />
<Route path="/channels" element={protect(<Channels />)} /> <Route path="/channels" element={protect(<Channels />)} />
<Route path="/remix" element={protect(<Remix />)} /> <Route path="/remix" element={protect(<Remix />)} />
<Route path="/nearby" element={protect(<Nearby />)} />
<Route
path="/business"
element={
<RequireRole role="business_admin">
<BusinessPanel />
</RequireRole>
}
/>
<Route
path="/admin"
element={
<RequireRole role="super_admin">
<AdminPanel />
</RequireRole>
}
/>
<Route path="*" element={<Navigate to="/library" replace />} /> <Route path="*" element={<Navigate to="/library" replace />} />
</Routes> </Routes>
) )
......
...@@ -16,3 +16,15 @@ export interface Chat { ...@@ -16,3 +16,15 @@ export interface Chat {
export function getChats() { export function getChats() {
return apiFetch<{ status: string; chats: Chat[] }>('/auth/chats') return apiFetch<{ status: string; chats: Chat[] }>('/auth/chats')
} }
export type UserRole = 'user' | 'business_admin' | 'super_admin'
export interface CurrentUser {
id: number
username: string | null
role: UserRole
}
export function getMe() {
return apiFetch<{ status: string; user: CurrentUser }>('/auth/me')
}
import { API_BASE_URL, apiFetch, getAccessToken } from './client'
export interface SoundmarkSong {
id: number
title: string
artist: string
album: string | null
coverart: string | null
}
export interface Soundmark {
id: number
name: string
description: string | null
latitude: number
longitude: number
radius_meters: number
business_owner_id: number | null
business_owner_username: string | null
song: SoundmarkSong | null
created_at: string
updated_at: string
}
export interface NearbySoundmark extends Soundmark {
distance_meters: number
}
/** Soundmarks whose own trigger radius currently contains (lat, lon), closest first. */
export function getNearbySoundmarks(lat: number, lon: number) {
const params = new URLSearchParams({ lat: String(lat), lon: String(lon) })
return apiFetch<{ status: string; soundmarks: NearbySoundmark[] }>(`/soundmarks/nearby?${params}`)
}
/** Business admin: soundmarks the caller owns. */
export function getMySoundmarks() {
return apiFetch<{ status: string; soundmarks: Soundmark[] }>('/soundmarks/mine')
}
/** Super admin: every soundmark, regardless of owner. */
export function getAllSoundmarks() {
return apiFetch<{ status: string; soundmarks: Soundmark[] }>('/soundmarks')
}
export interface SoundmarkCreateInput {
name: string
description?: string | null
latitude: number
longitude: number
radius_meters?: number
business_owner_id?: number | null
song_id?: number | null
}
export function createSoundmark(input: SoundmarkCreateInput) {
return apiFetch<{ status: string; soundmark: Soundmark }>('/soundmarks', { method: 'POST', json: input })
}
export type SoundmarkUpdateInput = Partial<SoundmarkCreateInput>
export function updateSoundmark(id: number, input: SoundmarkUpdateInput) {
return apiFetch<{ status: string; soundmark: Soundmark }>(`/soundmarks/${id}`, { method: 'PATCH', json: input })
}
export function deleteSoundmark(id: number) {
return apiFetch<{ status: string }>(`/soundmarks/${id}`, { method: 'DELETE' })
}
/** Sets or clears (songId = null) a soundmark's anthem - business admins can only do this for
* soundmarks they own; super admins can do it for any. */
export function setSoundmarkSong(id: number, songId: number | null) {
return apiFetch<{ status: string; soundmark: Soundmark }>(`/soundmarks/${id}/song`, {
method: 'PATCH',
json: { song_id: songId },
})
}
export interface PublicLibrarySong {
id: number
title: string
artist: string
album: string | null
genre: string | null
coverart: string | null
}
/** The "public library" business admins pick anthems from - every user's tagged songs, not
* just their own (unlike api/library.ts's searchLibrary, which is scoped to the caller). */
export function searchSongLibrary(q: string) {
const params = new URLSearchParams({ q })
return apiFetch<{ status: string; results: PublicLibrarySong[] }>(`/soundmarks/song-library?${params}`)
}
export interface AdminUser {
id: number
username: string | null
phone_number: string | null
role: 'user' | 'business_admin' | 'super_admin'
}
export function listUsers(role?: string) {
const suffix = role ? `?${new URLSearchParams({ role })}` : ''
return apiFetch<{ status: string; users: AdminUser[] }>(`/soundmarks/admin/users${suffix}`)
}
export function updateUserRole(userId: number, role: string) {
return apiFetch<{ status: string; user: { id: number; username: string | null; role: string } }>(
`/soundmarks/admin/users/${userId}/role`,
{ method: 'PATCH', json: { role } },
)
}
/** For PlayerContext's `streamUrl` override - fetches a soundmark's anthem as an authenticated
* blob and returns an object URL, mirroring api/stream.ts's fetchStreamUrl but against the
* soundmark-specific endpoint (streamable regardless of who uploaded the underlying song).
* Caller is responsible for calling URL.revokeObjectURL() when done, same as fetchStreamUrl. */
export async function fetchSoundmarkStreamUrl(soundmarkId: number): Promise<string> {
const token = getAccessToken()
const res = await fetch(`${API_BASE_URL}/soundmarks/${soundmarkId}/stream`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
})
if (!res.ok) {
throw new Error(`Failed to load audio (${res.status})`)
}
const blob = await res.blob()
return URL.createObjectURL(blob)
}
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { Link, useLocation } from 'react-router-dom' import { Link, useLocation } from 'react-router-dom'
import { Compass, Headphones, Library, LogOut, Radio, Rss, Upload, Wand2, type LucideIcon } from 'lucide-react' import {
Compass,
Headphones,
Library,
LogOut,
MapPin,
Radio,
Rss,
ShieldCheck,
Store,
Upload,
Wand2,
type LucideIcon,
} from 'lucide-react'
import { useAuth } from '../context/AuthContext' import { useAuth } from '../context/AuthContext'
import { usePlayer } from '../context/PlayerContext' import { usePlayer } from '../context/PlayerContext'
import { Button } from './ui/Button' import { Button } from './ui/Button'
...@@ -15,10 +28,11 @@ const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [ ...@@ -15,10 +28,11 @@ const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [
{ to: '/rooms', label: 'Rooms', icon: Radio }, { to: '/rooms', label: 'Rooms', icon: Radio },
{ to: '/channels', label: 'Channels', icon: Rss }, { to: '/channels', label: 'Channels', icon: Rss },
{ to: '/remix', label: 'Remix', icon: Wand2 }, { to: '/remix', label: 'Remix', icon: Wand2 },
{ to: '/nearby', label: 'Soundmarks', icon: MapPin },
] ]
export function Layout({ title, children }: { title: string; children: ReactNode }) { export function Layout({ title, children }: { title: string; children: ReactNode }) {
const { logout } = useAuth() const { logout, isBusinessAdmin, isSuperAdmin } = useAuth()
const { currentSong } = usePlayer() const { currentSong } = usePlayer()
const location = useLocation() const location = useLocation()
...@@ -42,11 +56,37 @@ export function Layout({ title, children }: { title: string; children: ReactNode ...@@ -42,11 +56,37 @@ export function Layout({ title, children }: { title: string; children: ReactNode
<Headphones size={20} strokeWidth={2} className="text-emerald-400" /> <Headphones size={20} strokeWidth={2} className="text-emerald-400" />
Stax Stax
</Link> </Link>
<Button variant="ghost" size="sm" onClick={handleLogout} className="gap-1.5 !px-3"> <div className="flex items-center gap-1">
<LogOut size={15} strokeWidth={2} /> {isBusinessAdmin && (
Log out <Link
to="/business"
aria-label="Business panel"
className={`flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors duration-150 ${
location.pathname === '/business' ? 'bg-neutral-900 text-white' : 'text-neutral-400 hover:text-white'
}`}
>
<Store size={15} strokeWidth={2} aria-hidden="true" />
<span className="hidden sm:inline" aria-hidden="true">Business</span>
</Link>
)}
{isSuperAdmin && (
<Link
to="/admin"
aria-label="Admin panel"
className={`flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors duration-150 ${
location.pathname === '/admin' ? 'bg-neutral-900 text-white' : 'text-neutral-400 hover:text-white'
}`}
>
<ShieldCheck size={15} strokeWidth={2} aria-hidden="true" />
<span className="hidden sm:inline" aria-hidden="true">Admin</span>
</Link>
)}
<Button variant="ghost" size="sm" onClick={handleLogout} aria-label="Log out" className="gap-1.5 !px-3">
<LogOut size={15} strokeWidth={2} aria-hidden="true" />
<span className="hidden sm:inline" aria-hidden="true">Log out</span>
</Button> </Button>
</div> </div>
</div>
<nav className="hidden gap-1 pb-2 text-sm sm:flex"> <nav className="hidden gap-1 pb-2 text-sm sm:flex">
{NAV_ITEMS.map((item) => { {NAV_ITEMS.map((item) => {
const active = location.pathname === item.to const active = location.pathname === item.to
......
import { render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { RequireRole } from './RequireRole'
import * as AuthContextModule from '../context/AuthContext'
function mockAuth(overrides: Partial<ReturnType<typeof AuthContextModule.useAuth>>) {
vi.spyOn(AuthContextModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
role: null,
isBusinessAdmin: false,
isSuperAdmin: false,
logout: vi.fn(),
...overrides,
})
}
describe('RequireRole', () => {
it('shows a not-authenticated message when the user is not logged in', () => {
mockAuth({ isAuthenticated: false, role: null })
render(
<RequireRole role="business_admin">
<p>Secret content</p>
</RequireRole>,
)
expect(screen.getByText(/Not authenticated/)).toBeInTheDocument()
expect(screen.queryByText('Secret content')).not.toBeInTheDocument()
})
it('renders nothing while role is still resolving (avoids flashing "access denied")', () => {
mockAuth({ isAuthenticated: true, role: null })
const { container } = render(
<RequireRole role="business_admin">
<p>Secret content</p>
</RequireRole>,
)
expect(container).toBeEmptyDOMElement()
})
it('denies a plain user access to a business_admin-gated page', () => {
mockAuth({ isAuthenticated: true, role: 'user', isBusinessAdmin: false, isSuperAdmin: false })
render(
<RequireRole role="business_admin">
<p>Secret content</p>
</RequireRole>,
)
expect(screen.getByText(/don't have access/)).toBeInTheDocument()
expect(screen.queryByText('Secret content')).not.toBeInTheDocument()
})
it('allows a business_admin into a business_admin-gated page', () => {
mockAuth({ isAuthenticated: true, role: 'business_admin', isBusinessAdmin: true, isSuperAdmin: false })
render(
<RequireRole role="business_admin">
<p>Secret content</p>
</RequireRole>,
)
expect(screen.getByText('Secret content')).toBeInTheDocument()
})
it('denies a business_admin access to a super_admin-gated page', () => {
mockAuth({ isAuthenticated: true, role: 'business_admin', isBusinessAdmin: true, isSuperAdmin: false })
render(
<RequireRole role="super_admin">
<p>Secret content</p>
</RequireRole>,
)
expect(screen.getByText(/don't have access/)).toBeInTheDocument()
})
it('allows a super_admin into both business_admin- and super_admin-gated pages (elevated privileges)', () => {
mockAuth({ isAuthenticated: true, role: 'super_admin', isBusinessAdmin: true, isSuperAdmin: true })
const { rerender } = render(
<RequireRole role="business_admin">
<p>Business content</p>
</RequireRole>,
)
expect(screen.getByText('Business content')).toBeInTheDocument()
rerender(
<RequireRole role="super_admin">
<p>Admin content</p>
</RequireRole>,
)
expect(screen.getByText('Admin content')).toBeInTheDocument()
})
})
import type { ReactNode } from 'react'
import { useAuth } from '../context/AuthContext'
export function RequireRole({ role, children }: { role: 'business_admin' | 'super_admin'; children: ReactNode }) {
const { isAuthenticated, role: currentRole, isBusinessAdmin, isSuperAdmin } = useAuth()
if (!isAuthenticated) {
return (
<div className="flex min-h-screen items-center justify-center bg-neutral-950 px-4 text-center text-neutral-400">
<p>Not authenticated - no login flow is wired up in this build.</p>
</div>
)
}
// Still resolving /auth/me - render nothing rather than flashing "access denied" for
// someone who actually does have access (or the real content for someone who doesn't).
if (currentRole === null) return null
const allowed = role === 'super_admin' ? isSuperAdmin : isBusinessAdmin
if (!allowed) {
return (
<div className="flex min-h-screen items-center justify-center bg-neutral-950 px-4 text-center text-neutral-400">
<p>You don't have access to this page.</p>
</div>
)
}
return <>{children}</>
}
import { useEffect, useState } from 'react'
import { Music2, X } from 'lucide-react'
import { getLibrary, type LibrarySong } from '../api/library'
import { searchSongLibrary, type PublicLibrarySong } from '../api/soundmarks'
import { Input } from './ui/Input'
type Tab = 'mine' | 'public'
type PickableSong = LibrarySong | PublicLibrarySong
interface SongPickerProps {
onSelect: (song: PickableSong) => void
onClose: () => void
}
/** Modal song picker shared by the business and super admin panels - "music from their
* personal library and the public music library" as two explicit tabs, rather than folding
* them into one always-cross-user search (the public tab already technically includes the
* caller's own songs too, but presenting them separately matches how the two sources were
* actually described and is clearer for picking your own recent upload quickly). */
export function SongPicker({ onSelect, onClose }: SongPickerProps) {
const [tab, setTab] = useState<Tab>('mine')
const [myLibrary, setMyLibrary] = useState<LibrarySong[]>([])
const [query, setQuery] = useState('')
const [publicResults, setPublicResults] = useState<PublicLibrarySong[]>([])
const [loading, setLoading] = useState(false)
useEffect(() => {
getLibrary()
.then((res) => setMyLibrary(res.library))
.catch(() => {
// Picker just shows an empty list if this fails - not worth a dedicated error state.
})
}, [])
useEffect(() => {
if (tab !== 'public') return
setLoading(true)
const handle = setTimeout(() => {
searchSongLibrary(query)
.then((res) => setPublicResults(res.results))
.catch(() => setPublicResults([]))
.finally(() => setLoading(false))
}, 300)
return () => clearTimeout(handle)
}, [tab, query])
useEffect(() => {
function onKeyDown(e: KeyboardEvent) {
if (e.key === 'Escape') onClose()
}
document.addEventListener('keydown', onKeyDown)
return () => document.removeEventListener('keydown', onKeyDown)
}, [onClose])
const list = tab === 'mine' ? myLibrary : publicResults
return (
<div
role="dialog"
aria-modal="true"
aria-label="Choose an anthem"
className="fixed inset-0 z-40 flex items-end justify-center bg-black/60 sm:items-center"
onClick={onClose}
>
<div
className="flex max-h-[80vh] w-full max-w-md flex-col overflow-hidden rounded-t-2xl bg-neutral-900 sm:rounded-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between border-b border-neutral-800 px-4 py-3">
<p className="text-sm font-semibold text-white">Choose an anthem</p>
<button
onClick={onClose}
aria-label="Close"
className="rounded-full p-1.5 text-neutral-400 transition-colors hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<X size={18} strokeWidth={2} />
</button>
</div>
<div className="flex gap-1 px-4 pt-3">
{(['mine', 'public'] as const).map((t) => (
<button
key={t}
onClick={() => setTab(t)}
className={`rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors ${
tab === t ? 'bg-neutral-100 text-neutral-950' : 'text-neutral-400 hover:text-white'
}`}
>
{t === 'mine' ? 'My Library' : 'Public Library'}
</button>
))}
</div>
{tab === 'public' && (
<div className="px-4 pt-3">
<Input
placeholder="Search title or artist"
value={query}
onChange={(e) => setQuery(e.target.value)}
autoFocus
/>
</div>
)}
<ul className="mt-2 flex-1 overflow-y-auto px-2 pb-3">
{list.length === 0 && (
<p className="px-2 py-8 text-center text-sm text-neutral-500">
{loading ? 'Searching…' : tab === 'mine' ? 'Your library is empty.' : 'No songs found.'}
</p>
)}
{list.map((song) => (
<li key={song.id}>
<button
onClick={() => onSelect(song)}
className="flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-white/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600">
<Music2 size={14} strokeWidth={1.75} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-white">{song.title}</p>
<p className="truncate text-xs text-neutral-500">{song.artist}</p>
</div>
</button>
</li>
))}
</ul>
</div>
</div>
)
}
...@@ -14,12 +14,25 @@ import { clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/ ...@@ -14,12 +14,25 @@ import { clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/
async function loadFreshAuthContext() { async function loadFreshAuthContext() {
vi.resetModules() vi.resetModules()
return import('./AuthContext') // AuthContext.tsx's own `import * as authApi from '../api/auth'` gets re-evaluated as part
// of this fresh import too (resetModules cleared that module instance as well) - so a spy
// has to target *this* freshly-imported reference, not one imported statically at the top
// of this file before resetModules() ran, which would bind to a stale, disconnected copy.
const authModule = await import('./AuthContext')
const authApi = await import('../api/auth')
return { ...authModule, authApi }
} }
function Probe({ useAuth }: { useAuth: typeof import('./AuthContext').useAuth }) { function Probe({ useAuth }: { useAuth: typeof import('./AuthContext').useAuth }) {
const { isAuthenticated } = useAuth() const { isAuthenticated, role, isBusinessAdmin, isSuperAdmin } = useAuth()
return <span data-testid="auth-state">{isAuthenticated ? 'authenticated' : 'not-authenticated'}</span> return (
<div>
<span data-testid="auth-state">{isAuthenticated ? 'authenticated' : 'not-authenticated'}</span>
<span data-testid="role">{role ?? 'none'}</span>
<span data-testid="is-business-admin">{String(isBusinessAdmin)}</span>
<span data-testid="is-super-admin">{String(isSuperAdmin)}</span>
</div>
)
} }
describe('AuthProvider dev auto-login', () => { describe('AuthProvider dev auto-login', () => {
...@@ -30,6 +43,7 @@ describe('AuthProvider dev auto-login', () => { ...@@ -30,6 +43,7 @@ describe('AuthProvider dev auto-login', () => {
afterEach(() => { afterEach(() => {
vi.unstubAllEnvs() vi.unstubAllEnvs()
clearTokens() clearTokens()
vi.restoreAllMocks()
}) })
it('does not auto-authenticate when no dev tokens are configured', async () => { it('does not auto-authenticate when no dev tokens are configured', async () => {
...@@ -50,7 +64,8 @@ describe('AuthProvider dev auto-login', () => { ...@@ -50,7 +64,8 @@ describe('AuthProvider dev auto-login', () => {
it('auto-authenticates using the configured dev tokens', async () => { it('auto-authenticates using the configured dev tokens', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token') vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token') vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token')
const { AuthProvider, useAuth } = await loadFreshAuthContext() const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'x', role: 'user' } })
render( render(
<AuthProvider> <AuthProvider>
...@@ -69,7 +84,8 @@ describe('AuthProvider dev auto-login', () => { ...@@ -69,7 +84,8 @@ describe('AuthProvider dev auto-login', () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token') vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token') vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token')
setTokens('already-logged-in-token', 'already-logged-in-refresh') setTokens('already-logged-in-token', 'already-logged-in-refresh')
const { AuthProvider, useAuth } = await loadFreshAuthContext() const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'x', role: 'user' } })
render( render(
<AuthProvider> <AuthProvider>
...@@ -80,6 +96,48 @@ describe('AuthProvider dev auto-login', () => { ...@@ -80,6 +96,48 @@ describe('AuthProvider dev auto-login', () => {
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated') expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
expect(getAccessToken()).toBe('already-logged-in-token') expect(getAccessToken()).toBe('already-logged-in-token')
}) })
it('fetches and exposes the current user role once authenticated', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token')
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: { id: 1, username: 'dev-test-user', role: 'super_admin' },
})
render(
<AuthProvider>
<Probe useAuth={useAuth} />
</AuthProvider>,
)
await waitFor(() => {
expect(screen.getByTestId('role')).toHaveTextContent('super_admin')
})
// Super admin has business admin privileges too, not a separate track.
expect(screen.getByTestId('is-business-admin')).toHaveTextContent('true')
expect(screen.getByTestId('is-super-admin')).toHaveTextContent('true')
})
it('leaves role null (not "user") until the fetch resolves, and plain "user" role gates out admin UI', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token')
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'x', role: 'user' } })
render(
<AuthProvider>
<Probe useAuth={useAuth} />
</AuthProvider>,
)
await waitFor(() => {
expect(screen.getByTestId('role')).toHaveTextContent('user')
})
expect(screen.getByTestId('is-business-admin')).toHaveTextContent('false')
expect(screen.getByTestId('is-super-admin')).toHaveTextContent('false')
})
}) })
describe('logout', () => { describe('logout', () => {
...@@ -89,37 +147,44 @@ describe('logout', () => { ...@@ -89,37 +147,44 @@ describe('logout', () => {
vi.restoreAllMocks() vi.restoreAllMocks()
}) })
it('clears tokens and flips isAuthenticated to false', async () => { it('clears tokens, flips isAuthenticated to false, and resets role to null', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '') vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '') vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
setTokens('some-access-token', 'some-refresh-token') setTokens('some-access-token', 'some-refresh-token')
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', { status: 200 })))
const { AuthProvider, useAuth } = await loadFreshAuthContext() const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
user: { id: 1, username: 'x', role: 'super_admin' },
})
vi.spyOn(authApi, 'logout').mockResolvedValue({ status: 'success' })
function LogoutProbe() { function LogoutButton() {
const { isAuthenticated, logout } = useAuth() const { logout } = useAuth()
return ( return <button onClick={() => logout()}>Log out</button>
<div>
<span data-testid="auth-state">{isAuthenticated ? 'authenticated' : 'not-authenticated'}</span>
<button onClick={() => logout()}>Log out</button>
</div>
)
} }
render( render(
<AuthProvider> <AuthProvider>
<LogoutProbe /> <LogoutButton />
<Probe useAuth={useAuth} />
</AuthProvider>, </AuthProvider>,
) )
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated') expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
await waitFor(() => expect(screen.getByTestId('role')).toHaveTextContent('super_admin'))
screen.getByText('Log out').click() screen.getByText('Log out').click()
await waitFor(() => { await waitFor(() => {
expect(screen.getByTestId('auth-state')).toHaveTextContent('not-authenticated') expect(screen.getByTestId('auth-state')).toHaveTextContent('not-authenticated')
}) })
expect(getAccessToken()).toBeNull() expect(getAccessToken()).toBeNull()
vi.unstubAllGlobals() // The role-reset effect is a separate passive effect keyed off isAuthenticated - it can
// land a tick after the DOM already shows "not-authenticated", so this needs its own wait
// rather than a synchronous assertion right after the one above.
await waitFor(() => {
expect(screen.getByTestId('role')).toHaveTextContent('none')
})
}) })
}) })
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react' import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
import * as authApi from '../api/auth' import * as authApi from '../api/auth'
import type { UserRole } from '../api/auth'
import { clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/client' import { clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/client'
interface AuthContextValue { interface AuthContextValue {
isAuthenticated: boolean isAuthenticated: boolean
/** null until the post-auth /auth/me fetch resolves - don't gate admin UI on `role` alone,
* check `isAuthenticated` too so a momentarily-null role during that fetch doesn't flash a
* "not allowed" state for someone who actually is an admin. */
role: UserRole | null
isBusinessAdmin: boolean
isSuperAdmin: boolean
logout: () => Promise<void> logout: () => Promise<void>
} }
...@@ -20,6 +27,7 @@ const DEV_REFRESH_TOKEN = import.meta.env.VITE_DEV_REFRESH_TOKEN as string | und ...@@ -20,6 +27,7 @@ const DEV_REFRESH_TOKEN = import.meta.env.VITE_DEV_REFRESH_TOKEN as string | und
export function AuthProvider({ children }: { children: ReactNode }) { export function AuthProvider({ children }: { children: ReactNode }) {
const [isAuthenticated, setIsAuthenticated] = useState(() => Boolean(getAccessToken())) const [isAuthenticated, setIsAuthenticated] = useState(() => Boolean(getAccessToken()))
const [role, setRole] = useState<UserRole | null>(null)
useEffect(() => { useEffect(() => {
if (import.meta.env.DEV && !getAccessToken() && DEV_ACCESS_TOKEN && DEV_REFRESH_TOKEN) { if (import.meta.env.DEV && !getAccessToken() && DEV_ACCESS_TOKEN && DEV_REFRESH_TOKEN) {
...@@ -28,6 +36,25 @@ export function AuthProvider({ children }: { children: ReactNode }) { ...@@ -28,6 +36,25 @@ export function AuthProvider({ children }: { children: ReactNode }) {
} }
}, []) }, [])
useEffect(() => {
if (!isAuthenticated) {
setRole(null)
return
}
let cancelled = false
authApi
.getMe()
.then((res) => {
if (!cancelled) setRole(res.user.role)
})
.catch(() => {
// Role-gated UI just stays hidden if this fails - not worth surfacing an error for.
})
return () => {
cancelled = true
}
}, [isAuthenticated])
async function logout() { async function logout() {
const refreshToken = getRefreshToken() const refreshToken = getRefreshToken()
try { try {
...@@ -38,7 +65,14 @@ export function AuthProvider({ children }: { children: ReactNode }) { ...@@ -38,7 +65,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
} }
} }
return <AuthContext.Provider value={{ isAuthenticated, logout }}>{children}</AuthContext.Provider> const isBusinessAdmin = role === 'business_admin' || role === 'super_admin'
const isSuperAdmin = role === 'super_admin'
return (
<AuthContext.Provider value={{ isAuthenticated, role, isBusinessAdmin, isSuperAdmin, logout }}>
{children}
</AuthContext.Provider>
)
} }
export function useAuth(): AuthContextValue { export function useAuth(): AuthContextValue {
......
...@@ -12,6 +12,13 @@ export interface PlayableSong { ...@@ -12,6 +12,13 @@ export interface PlayableSong {
album?: string | null album?: string | null
coverart?: string | null coverart?: string | null
lyrics?: string | null lyrics?: string | null
/** Overrides how the audio URL is fetched - used for sources that aren't a plain
* LibrarySong id, e.g. a Soundmark's anthem (streamed via /soundmarks/{id}/stream and
* playable regardless of who originally uploaded the underlying song, unlike the default
* /library/stream/{id} path). When set, `id` only needs to be unique for play/pause
* identity purposes - callers should give it a value that can't collide with a real
* LibrarySong id (e.g. negate a soundmark's own id) since it's never used to fetch audio. */
streamUrl?: () => Promise<string>
} }
export type RepeatMode = 'off' | 'all' | 'one' export type RepeatMode = 'off' | 'all' | 'one'
...@@ -89,7 +96,8 @@ export function PlayerProvider({ children }: { children: ReactNode }) { ...@@ -89,7 +96,8 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
setDuration(0) setDuration(0)
setPlaybackError(null) setPlaybackError(null)
fetchStreamUrl(song.id) const streamUrlPromise = song.streamUrl ? song.streamUrl() : fetchStreamUrl(song.id)
streamUrlPromise
.then((url) => { .then((url) => {
if (requestId !== requestIdRef.current) { if (requestId !== requestIdRef.current) {
URL.revokeObjectURL(url) // a newer play request already superseded this one URL.revokeObjectURL(url) // a newer play request already superseded this one
......
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { AdminPanel } from './AdminPanel'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as soundmarksApi from '../api/soundmarks'
import * as libraryApi from '../api/library'
const LANDMARK: soundmarksApi.Soundmark = {
id: 1,
name: 'Old Clock Tower',
description: 'A neighborhood fixture',
latitude: 10,
longitude: 20,
radius_meters: 100,
business_owner_id: null,
business_owner_username: null,
song: null,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
}
const PLAIN_USER: soundmarksApi.AdminUser = { id: 7, username: 'alex', phone_number: '+15551234', role: 'user' }
function renderPanel() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<AdminPanel />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('AdminPanel', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('lists every soundmark regardless of owner, distinguishing landmarks from businesses', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
renderPanel()
expect(await screen.findByText('Old Clock Tower')).toBeInTheDocument()
expect(screen.getByText(/Landmark/)).toBeInTheDocument()
})
it('creates a new soundmark via the form', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
const create = vi.spyOn(soundmarksApi, 'createSoundmark').mockResolvedValue({
status: 'success',
soundmark: { ...LANDMARK, id: 2, name: 'New Plaza' },
})
renderPanel()
await screen.findByText(/No soundmarks yet/)
await userEvent.click(screen.getByRole('button', { name: 'New soundmark' }))
await userEvent.type(screen.getByPlaceholderText('Name'), 'New Plaza')
await userEvent.type(screen.getByPlaceholderText('Latitude'), '12.5')
await userEvent.type(screen.getByPlaceholderText('Longitude'), '45.5')
await userEvent.click(screen.getByRole('button', { name: 'Create soundmark' }))
await waitFor(() => {
expect(create).toHaveBeenCalledWith(
expect.objectContaining({ name: 'New Plaza', latitude: 12.5, longitude: 45.5, business_owner_id: null }),
)
})
expect(await screen.findByText('New Plaza')).toBeInTheDocument()
})
it('deletes a soundmark after confirming', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
const del = vi.spyOn(soundmarksApi, 'deleteSoundmark').mockResolvedValue({ status: 'success' })
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderPanel()
await screen.findByText('Old Clock Tower')
await userEvent.click(screen.getByRole('button', { name: 'Delete Old Clock Tower' }))
await waitFor(() => expect(del).toHaveBeenCalledWith(LANDMARK.id))
await waitFor(() => expect(screen.queryByText('Old Clock Tower')).not.toBeInTheDocument())
})
it('does not delete when the confirmation is declined', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
const del = vi.spyOn(soundmarksApi, 'deleteSoundmark').mockResolvedValue({ status: 'success' })
vi.spyOn(window, 'confirm').mockReturnValue(false)
renderPanel()
await screen.findByText('Old Clock Tower')
await userEvent.click(screen.getByRole('button', { name: 'Delete Old Clock Tower' }))
expect(del).not.toHaveBeenCalled()
expect(screen.getByText('Old Clock Tower')).toBeInTheDocument()
})
it('promotes a user to business_admin from the Users tab', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [PLAIN_USER] })
const updateRole = vi.spyOn(soundmarksApi, 'updateUserRole').mockResolvedValue({
status: 'success',
user: { id: PLAIN_USER.id, username: PLAIN_USER.username, role: 'business_admin' },
})
renderPanel()
// The tab label is rendered lowercase in markup and capitalized purely via CSS
// (text-transform), so the accessible name to match against is the lowercase text.
await userEvent.click(screen.getByRole('button', { name: 'users' }))
await screen.findByText('alex')
await userEvent.selectOptions(screen.getByRole('combobox', { name: /Role for alex/ }), 'business_admin')
await waitFor(() => {
expect(updateRole).toHaveBeenCalledWith(PLAIN_USER.id, 'business_admin')
})
})
it('sets an anthem on a soundmark by picking from the public library', async () => {
vi.spyOn(soundmarksApi, 'getAllSoundmarks').mockResolvedValue({ status: 'success', soundmarks: [LANDMARK] })
vi.spyOn(soundmarksApi, 'listUsers').mockResolvedValue({ status: 'success', users: [] })
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
vi.spyOn(soundmarksApi, 'searchSongLibrary').mockResolvedValue({
status: 'success',
results: [{ id: 99, title: 'Anyone\'s Track', artist: 'Anyone', album: null, genre: null, coverart: null }],
})
const setSong = vi.spyOn(soundmarksApi, 'setSoundmarkSong').mockResolvedValue({
status: 'success',
soundmark: { ...LANDMARK, song: { id: 99, title: "Anyone's Track", artist: 'Anyone', album: null, coverart: null } },
})
renderPanel()
await screen.findByText('Old Clock Tower')
await userEvent.click(screen.getByRole('button', { name: 'Set anthem' }))
await userEvent.click(screen.getByRole('button', { name: 'Public Library' }))
await screen.findByText("Anyone's Track")
await userEvent.click(screen.getByText("Anyone's Track"))
await waitFor(() => {
expect(setSong).toHaveBeenCalledWith(LANDMARK.id, 99)
})
})
})
This diff is collapsed.
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { BusinessPanel } from './BusinessPanel'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import { ApiError } from '../api/client'
import * as soundmarksApi from '../api/soundmarks'
import * as libraryApi from '../api/library'
const OWNED_MARK: soundmarksApi.Soundmark = {
id: 1,
name: "Joe's Cafe",
description: 'Downtown spot',
latitude: 1,
longitude: 2,
radius_meters: 150,
business_owner_id: 5,
business_owner_username: 'joe',
song: null,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
}
const MY_SONG = {
id: 10,
user_id: 5,
title: 'My Own Track',
artist: 'Me',
album: null,
genre: null,
coverart: null,
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
}
function renderPanel() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<BusinessPanel />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('BusinessPanel', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows an empty state when the caller owns no soundmarks', async () => {
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
renderPanel()
expect(await screen.findByText(/No soundmarks assigned/)).toBeInTheDocument()
})
it('lists owned soundmarks and shows "No anthem set" when none is assigned', async () => {
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [OWNED_MARK] })
renderPanel()
expect(await screen.findByText("Joe's Cafe")).toBeInTheDocument()
expect(screen.getByText('No anthem set')).toBeInTheDocument()
})
it('sets an anthem by picking a song from "My Library"', async () => {
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [OWNED_MARK] })
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [MY_SONG] })
const setSong = vi.spyOn(soundmarksApi, 'setSoundmarkSong').mockResolvedValue({
status: 'success',
soundmark: { ...OWNED_MARK, song: { id: MY_SONG.id, title: MY_SONG.title, artist: MY_SONG.artist, album: null, coverart: null } },
})
renderPanel()
await screen.findByText("Joe's Cafe")
await userEvent.click(screen.getByRole('button', { name: 'Set anthem' }))
await screen.findByText('My Own Track')
await userEvent.click(screen.getByText('My Own Track'))
await waitFor(() => {
expect(setSong).toHaveBeenCalledWith(OWNED_MARK.id, MY_SONG.id)
})
expect(await screen.findByText('My Own Track', { selector: 'p' })).toBeInTheDocument()
})
it('clears an assigned anthem', async () => {
const withSong = { ...OWNED_MARK, song: { id: 10, title: 'Current', artist: 'Someone', album: null, coverart: null } }
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [withSong] })
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
const setSong = vi
.spyOn(soundmarksApi, 'setSoundmarkSong')
.mockResolvedValue({ status: 'success', soundmark: { ...withSong, song: null } })
renderPanel()
await screen.findByText('Current')
await userEvent.click(screen.getByRole('button', { name: 'Clear' }))
await waitFor(() => {
expect(setSong).toHaveBeenCalledWith(withSong.id, null)
})
expect(await screen.findByText('No anthem set')).toBeInTheDocument()
})
it('shows an error message if loading soundmarks fails', async () => {
vi.spyOn(soundmarksApi, 'getMySoundmarks').mockRejectedValue(new ApiError(500, 'Server exploded', null))
renderPanel()
expect(await screen.findByText('Server exploded')).toBeInTheDocument()
})
})
import { useEffect, useState } from 'react'
import { MapPin, Music2 } from 'lucide-react'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
import { SongPicker } from '../components/SongPicker'
import { ApiError } from '../api/client'
import { getMySoundmarks, setSoundmarkSong, type Soundmark } from '../api/soundmarks'
export function BusinessPanel() {
const [soundmarks, setSoundmarks] = useState<Soundmark[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [pickerFor, setPickerFor] = useState<number | null>(null)
const [savingId, setSavingId] = useState<number | null>(null)
function load() {
setLoading(true)
getMySoundmarks()
.then((res) => setSoundmarks(res.soundmarks))
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to load your soundmarks'))
.finally(() => setLoading(false))
}
useEffect(load, [])
async function handleSelect(soundmarkId: number, songId: number) {
setPickerFor(null)
setSavingId(soundmarkId)
try {
const res = await setSoundmarkSong(soundmarkId, songId)
setSoundmarks((prev) => prev.map((sm) => (sm.id === soundmarkId ? res.soundmark : sm)))
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to update the anthem')
} finally {
setSavingId(null)
}
}
async function handleClear(soundmarkId: number) {
setSavingId(soundmarkId)
try {
const res = await setSoundmarkSong(soundmarkId, null)
setSoundmarks((prev) => prev.map((sm) => (sm.id === soundmarkId ? res.soundmark : sm)))
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to update the anthem')
} finally {
setSavingId(null)
}
}
return (
<Layout title="Business Panel">
<p className="mb-6 text-sm leading-relaxed text-neutral-400">
Set the anthem that plays at each of your soundmarks - pick from your own library or search every
tagged song on Stax.
</p>
{loading && (
<div className="divide-y divide-neutral-800/80">
<SkeletonRow />
<SkeletonRow />
</div>
)}
{error && <p className="mb-4 text-sm text-red-400">{error}</p>}
{!loading && soundmarks.length === 0 && !error && (
<EmptyState icon={MapPin} message="No soundmarks assigned to your business yet - ask a Stax admin to set one up." />
)}
<ul className="space-y-3">
{soundmarks.map((sm) => (
<li key={sm.id} className="rounded-xl border border-neutral-800 bg-neutral-900 p-3">
<div className="mb-2 flex items-center gap-1.5 px-1 text-xs font-medium uppercase tracking-wide text-neutral-500">
<MapPin size={12} strokeWidth={2.5} />
{sm.name}
<span className="text-neutral-600">· {sm.radius_meters}m radius</span>
</div>
<div className="flex items-center gap-4 p-1">
{sm.song?.coverart ? (
<img src={sm.song.coverart} alt="" className="h-14 w-14 shrink-0 rounded-lg object-cover" />
) : (
<div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-lg bg-neutral-800 text-neutral-600">
<Music2 size={18} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
{sm.song ? (
<>
<p className="truncate font-medium text-white">{sm.song.title}</p>
<p className="truncate text-sm text-neutral-400">{sm.song.artist}</p>
</>
) : (
<p className="text-sm text-neutral-500">No anthem set</p>
)}
</div>
</div>
<div className="mt-3 flex items-center gap-2 px-1">
<Button
variant="secondary"
size="sm"
onClick={() => setPickerFor(sm.id)}
disabled={savingId === sm.id}
>
{savingId === sm.id ? 'Saving…' : sm.song ? 'Change anthem' : 'Set anthem'}
</Button>
{sm.song && (
<Button variant="ghost" size="sm" onClick={() => handleClear(sm.id)} disabled={savingId === sm.id}>
Clear
</Button>
)}
</div>
{sm.description && <p className="mt-3 px-1 text-sm text-neutral-400">{sm.description}</p>}
</li>
))}
</ul>
{pickerFor !== null && (
<SongPicker onClose={() => setPickerFor(null)} onSelect={(song) => handleSelect(pickerFor, song.id)} />
)}
</Layout>
)
}
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Nearby } from './Nearby'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as soundmarksApi from '../api/soundmarks'
const FOUND_MARK: soundmarksApi.NearbySoundmark = {
id: 1,
name: 'Joe\'s Cafe',
description: 'The house anthem.',
latitude: 37.7749,
longitude: -122.4194,
radius_meters: 150,
business_owner_id: 5,
business_owner_username: 'joe',
song: { id: 42, title: 'Cafe Anthem', artist: 'Local Band', album: null, coverart: null },
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
distance_meters: 12,
}
function mockGeolocation({ succeed = true, code = 1 }: { succeed?: boolean; code?: number } = {}) {
const position = { coords: { latitude: 37.7749, longitude: -122.4194 } } as GeolocationPosition
const geolocation = {
getCurrentPosition: vi.fn((success: PositionCallback, error?: PositionErrorCallback) => {
if (succeed) success(position)
else error?.({ code, PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3 } as GeolocationPositionError)
}),
watchPosition: vi.fn(() => 1),
clearWatch: vi.fn(),
}
vi.stubGlobal('navigator', { ...navigator, geolocation })
return geolocation
}
function renderNearby() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<Nearby />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('Nearby', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
it('shows a prompt before location has been requested', () => {
renderNearby()
expect(screen.getByRole('button', { name: 'Find soundmarks near me' })).toBeInTheDocument()
})
it('finds and displays a nearby soundmark with its anthem', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] })
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
await waitFor(() => expect(screen.getByText('Cafe Anthem')).toBeInTheDocument())
expect(screen.getByText('Local Band')).toBeInTheDocument()
expect(screen.getByText(/Joe's Cafe/)).toBeInTheDocument()
expect(soundmarksApi.getNearbySoundmarks).toHaveBeenCalledWith(37.7749, -122.4194)
})
it('plays the found anthem through the shared player when tapped', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] })
vi.spyOn(soundmarksApi, 'fetchSoundmarkStreamUrl').mockResolvedValue('blob:fake-url')
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
await waitFor(() => expect(screen.getByText('Cafe Anthem')).toBeInTheDocument())
// Only one "Play" button exists at this point (NowPlayingBar hasn't mounted yet - no song
// is loaded until this very click starts one), so no scoping is needed here.
await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await waitFor(() => {
expect(soundmarksApi.fetchSoundmarkStreamUrl).toHaveBeenCalledWith(FOUND_MARK.id)
})
// NowPlayingBar mounts its own "Pause" button once playback starts, alongside the one on
// this page - scope to the anthem card (found via the soundmark name, a direct sibling of
// the play button, both children of the card div) to disambiguate.
const card = screen.getByText(/Joe's Cafe/).closest('div')!
expect(await within(card).findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
it('shows an empty state when no soundmark is nearby', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [] })
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
expect(await screen.findByText(/No soundmark nearby right now/)).toBeInTheDocument()
})
it('shows a clear message when location permission is denied', async () => {
mockGeolocation({ succeed: false, code: 1 })
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
expect(await screen.findByText(/Location access was denied/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()
})
})
import { useEffect, useRef, useState } from 'react'
import { MapPin, Music2, Pause, Play } from 'lucide-react'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { EmptyState } from '../components/ui/EmptyState'
import { ApiError } from '../api/client'
import { fetchSoundmarkStreamUrl, getNearbySoundmarks, type NearbySoundmark } from '../api/soundmarks'
import { usePlayer } from '../context/PlayerContext'
type Status = 'idle' | 'locating' | 'ready' | 'error'
function toPlayable(sm: NearbySoundmark & { song: NonNullable<NearbySoundmark['song']> }) {
return {
// Negative to guarantee this can never collide with a real LibrarySong id - see the
// `streamUrl` doc on PlayableSong for why that matters (play/pause identity, not a real
// library lookup key, since `streamUrl` below overrides how the audio itself is fetched).
id: -sm.id,
title: sm.song.title,
artist: sm.song.artist,
album: sm.song.album,
coverart: sm.song.coverart,
streamUrl: () => fetchSoundmarkStreamUrl(sm.id),
}
}
export function Nearby() {
const [status, setStatus] = useState<Status>('idle')
const [error, setError] = useState<string | null>(null)
const [soundmarks, setSoundmarks] = useState<NearbySoundmark[]>([])
const watchIdRef = useRef<number | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
function handlePosition(position: GeolocationPosition) {
setStatus('ready')
setError(null)
getNearbySoundmarks(position.coords.latitude, position.coords.longitude)
.then((res) => setSoundmarks(res.soundmarks))
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to check nearby soundmarks'))
}
function handlePositionError(err: GeolocationPositionError) {
setStatus('error')
setError(
err.code === err.PERMISSION_DENIED
? 'Location access was denied - allow it in your browser settings to find soundmarks near you.'
: "Couldn't determine your location. Please try again.",
)
}
function start() {
if (!navigator.geolocation) {
setStatus('error')
setError("Your browser doesn't support location services.")
return
}
setStatus('locating')
setError(null)
// getCurrentPosition for a fast first result, watchPosition to keep updating as you move -
// together they mean the shown soundmark tracks your actual position, not just where you
// were standing when you tapped the button.
navigator.geolocation.getCurrentPosition(handlePosition, handlePositionError, {
enableHighAccuracy: true,
timeout: 15000,
})
if (watchIdRef.current !== null) navigator.geolocation?.clearWatch(watchIdRef.current)
watchIdRef.current = navigator.geolocation.watchPosition(handlePosition, handlePositionError, {
enableHighAccuracy: true,
})
}
useEffect(() => {
return () => {
if (watchIdRef.current !== null) navigator.geolocation?.clearWatch(watchIdRef.current)
}
}, [])
const closest = soundmarks[0]
const active = closest?.song ? toPlayable(closest as NearbySoundmark & { song: NonNullable<NearbySoundmark['song']> }) : null
const isCurrent = !!active && currentSong?.id === active.id
return (
<Layout title="Soundmarks">
<p className="mb-6 text-sm leading-relaxed text-neutral-400">
Find the anthem playing at this spot - some places have a song tied to them, either because it's
significant here or a local business chose it.
</p>
{status === 'idle' && (
<div className="flex flex-col items-center gap-4 rounded-xl border border-dashed border-neutral-700 p-10 text-center">
<MapPin size={28} strokeWidth={1.5} className="text-neutral-500" />
<p className="text-sm text-neutral-400">Use your location to find soundmarks near you.</p>
<Button onClick={start}>Find soundmarks near me</Button>
</div>
)}
{status === 'locating' && (
<div className="flex flex-col items-center gap-3 py-16 text-neutral-500">
<span
className="h-6 w-6 animate-spin rounded-full border-2 border-neutral-700 border-t-emerald-400"
aria-hidden="true"
/>
<p className="text-sm">Getting your location…</p>
</div>
)}
{status === 'error' && (
<div className="rounded-xl border border-red-900/50 bg-neutral-900 p-4">
<p className="text-sm text-red-400">{error}</p>
<Button variant="secondary" size="sm" onClick={start} className="mt-3">
Try again
</Button>
</div>
)}
{status === 'ready' && !active && (
<EmptyState icon={MapPin} message="No soundmark nearby right now - keep moving, we'll keep checking." />
)}
{status === 'ready' && active && closest && (
<div className="rounded-xl border border-neutral-800 bg-neutral-900 p-3">
<p className="mb-2 flex items-center gap-1.5 px-1 text-xs font-medium uppercase tracking-wide text-emerald-400">
<MapPin size={12} strokeWidth={2.5} />
{closest.name}
</p>
<button
onClick={() => toggle(active)}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'}
className="flex w-full items-center gap-4 rounded-lg p-1 text-left transition-colors hover:bg-white/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:cursor-not-allowed"
>
{active.coverart ? (
<img src={active.coverart} alt="" className="h-16 w-16 shrink-0 rounded-lg object-cover" />
) : (
<div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-lg bg-neutral-800 text-neutral-600">
<Music2 size={20} strokeWidth={1.75} />
</div>
)}
<div className="min-w-0 flex-1">
<p className="truncate font-semibold text-white">{active.title}</p>
<p className="truncate text-sm text-neutral-400">{active.artist}</p>
</div>
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-neutral-800 text-white">
{isCurrent && streamLoading ? (
<span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-neutral-600 border-t-white" />
) : isCurrent && isPlaying ? (
<Pause size={16} strokeWidth={2} fill="currentColor" />
) : (
<Play size={16} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</span>
</button>
{closest.description && <p className="mt-3 px-1 text-sm text-neutral-400">{closest.description}</p>}
</div>
)}
</Layout>
)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment