Commit 543f0d38 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add location picker, live map, and song proposals/voting to Soundmarks

Location picker (admin panel create/edit form): address-search
autocomplete backed by the new backend geocode proxy, plus an
embedded Leaflet/OpenStreetMap map - search, click, or drag the pin
to set a soundmark's coordinates. Replaces raw lat/lon number inputs.

Map screen + live location (Nearby page): a real map showing a
live-updating "you are here" dot (tracks the existing watchPosition
feed) and pins for whatever soundmarks are currently in range,
alongside the existing text/card view - not a replacement for it.

Song proposals + voting (Nearby page): shows every proposal for the
detected soundmark with vote counts, a "Propose a song" button
(reuses the existing SongPicker), and a vote toggle per proposal.
Soundmarks with no anthem yet now show a "propose one" prompt instead
of a play button, so there's an actual path to making the first
proposal for a brand new soundmark.

OpenStreetMap over Google Maps per explicit choice - no API key/
billing setup required. leaflet + react-leaflet added; the default
marker icon bundler quirk (broken image paths once bundled - a
known issue with every bundler) is patched once via src/lib/leafletIcons.ts.

10 new tests (LocationPicker search/selection, SoundmarkMap smoke
tests, Nearby proposal/vote/propose flows and the "no anthem yet"
state) - 83 webapp tests passing overall. Verified live end-to-end
with a real Nominatim geocode search ("Eiffel Tower, Paris") and
real Chromium geolocation mocking rather than stubbed data - the
whole loop (create -> geocode -> place pin -> assign anthem -> detect
via live location -> see it on the map -> view proposals) worked with
zero console errors.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 4b0e72d7
Pipeline #1054 failed with stage
...@@ -8,9 +8,11 @@ ...@@ -8,9 +8,11 @@
"name": "stax_webapp", "name": "stax_webapp",
"version": "0.0.0", "version": "0.0.0",
"dependencies": { "dependencies": {
"leaflet": "^1.9.4",
"lucide-react": "^1.31.0", "lucide-react": "^1.31.0",
"react": "^19.2.8", "react": "^19.2.8",
"react-dom": "^19.2.8", "react-dom": "^19.2.8",
"react-leaflet": "^5.0.0",
"react-router-dom": "^7.18.2" "react-router-dom": "^7.18.2"
}, },
"devDependencies": { "devDependencies": {
...@@ -18,6 +20,7 @@ ...@@ -18,6 +20,7 @@
"@testing-library/jest-dom": "^6.9.1", "@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2", "@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.3", "@testing-library/user-event": "^14.6.3",
"@types/leaflet": "^1.9.22",
"@types/node": "^24.13.3", "@types/node": "^24.13.3",
"@types/react": "^19.2.17", "@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
...@@ -679,6 +682,17 @@ ...@@ -679,6 +682,17 @@
"node": "^20.19.0 || >=22.12.0" "node": "^20.19.0 || >=22.12.0"
} }
}, },
"node_modules/@react-leaflet/core": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@react-leaflet/core/-/core-3.0.0.tgz",
"integrity": "sha512-3EWmekh4Nz+pGcr+xjf0KNyYfC3U2JjnkWsh0zcqaexYqmmB5ZhH37kz41JXGmKzpaMZCnPofBBm64i+YrEvGQ==",
"license": "Hippocratic-2.1",
"peerDependencies": {
"leaflet": "^1.9.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
}
},
"node_modules/@rolldown/binding-android-arm64": { "node_modules/@rolldown/binding-android-arm64": {
"version": "1.2.3", "version": "1.2.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.3.tgz",
...@@ -1587,6 +1601,23 @@ ...@@ -1587,6 +1601,23 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/leaflet": {
"version": "1.9.22",
"resolved": "https://registry.npmjs.org/@types/leaflet/-/leaflet-1.9.22.tgz",
"integrity": "sha512-h3lhECYEKDasG7LFHu+GiHqAvsgLuQvlJvVZzJDGONo3sEL+wUOqSFLnwkZlK0qVxnxbuGFW8iBlJNYs5wgndA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/geojson": "*"
}
},
"node_modules/@types/node": { "node_modules/@types/node": {
"version": "24.13.3", "version": "24.13.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",
...@@ -2101,6 +2132,12 @@ ...@@ -2101,6 +2132,12 @@
} }
} }
}, },
"node_modules/leaflet": {
"version": "1.9.4",
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
"license": "BSD-2-Clause"
},
"node_modules/lightningcss": { "node_modules/lightningcss": {
"version": "1.33.0", "version": "1.33.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
...@@ -2625,6 +2662,20 @@ ...@@ -2625,6 +2662,20 @@
"license": "MIT", "license": "MIT",
"peer": true "peer": true
}, },
"node_modules/react-leaflet": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/react-leaflet/-/react-leaflet-5.0.0.tgz",
"integrity": "sha512-CWbTpr5vcHw5bt9i4zSlPEVQdTVcML390TjeDG0cK59z1ylexpqC6M1PJFjV8jD7CF+ACBFsLIDs6DRMoLEofw==",
"license": "Hippocratic-2.1",
"dependencies": {
"@react-leaflet/core": "^3.0.0"
},
"peerDependencies": {
"leaflet": "^1.9.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
}
},
"node_modules/react-router": { "node_modules/react-router": {
"version": "7.18.2", "version": "7.18.2",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.2.tgz", "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.2.tgz",
......
...@@ -12,9 +12,11 @@ ...@@ -12,9 +12,11 @@
"test:watch": "vitest" "test:watch": "vitest"
}, },
"dependencies": { "dependencies": {
"leaflet": "^1.9.4",
"lucide-react": "^1.31.0", "lucide-react": "^1.31.0",
"react": "^19.2.8", "react": "^19.2.8",
"react-dom": "^19.2.8", "react-dom": "^19.2.8",
"react-leaflet": "^5.0.0",
"react-router-dom": "^7.18.2" "react-router-dom": "^7.18.2"
}, },
"devDependencies": { "devDependencies": {
...@@ -22,6 +24,7 @@ ...@@ -22,6 +24,7 @@
"@testing-library/jest-dom": "^6.9.1", "@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2", "@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.3", "@testing-library/user-event": "^14.6.3",
"@types/leaflet": "^1.9.22",
"@types/node": "^24.13.3", "@types/node": "^24.13.3",
"@types/react": "^19.2.17", "@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
......
...@@ -17,7 +17,10 @@ export interface Soundmark { ...@@ -17,7 +17,10 @@ export interface Soundmark {
radius_meters: number radius_meters: number
business_owner_id: number | null business_owner_id: number | null
business_owner_username: string | null business_owner_username: string | null
/** The currently-winning song - either the top-voted proposal, or the admin-set fallback if
* there are no proposals yet. See proposal_count to tell those two cases apart. */
song: SoundmarkSong | null song: SoundmarkSong | null
proposal_count: number
created_at: string created_at: string
updated_at: string updated_at: string
} }
...@@ -125,3 +128,51 @@ export async function fetchSoundmarkStreamUrl(soundmarkId: number): Promise<stri ...@@ -125,3 +128,51 @@ export async function fetchSoundmarkStreamUrl(soundmarkId: number): Promise<stri
const blob = await res.blob() const blob = await res.blob()
return URL.createObjectURL(blob) return URL.createObjectURL(blob)
} }
export interface GeocodeResult {
display_name: string
latitude: number
longitude: number
}
/** Address-search autocomplete for the location picker, proxied through the backend (see
* GET /soundmarks/geocode's docstring for why it can't be called directly from the browser). */
export function geocodeAddress(q: string) {
const params = new URLSearchParams({ q })
return apiFetch<{ status: string; results: GeocodeResult[] }>(`/soundmarks/geocode?${params}`)
}
export interface SoundmarkProposal {
id: number
song: SoundmarkSong | null
vote_count: number
has_voted: boolean
proposed_by_username: string | null
created_at: string
}
/** Sorted by vote_count descending - the first entry is the one currently winning. */
export function getProposals(soundmarkId: number) {
return apiFetch<{ status: string; proposals: SoundmarkProposal[] }>(`/soundmarks/${soundmarkId}/proposals`)
}
/** Proposes a song for a soundmark, casting the caller's own vote for it too. Proposing a song
* that's already been proposed just adds your vote to the existing proposal. */
export function proposeSong(soundmarkId: number, songId: number) {
return apiFetch<{ status: string; proposal: SoundmarkProposal }>(`/soundmarks/${soundmarkId}/proposals`, {
method: 'POST',
json: { song_id: songId },
})
}
/** One vote per (soundmark, caller) - voting for a different proposal moves it. */
export function voteForProposal(soundmarkId: number, proposalId: number) {
return apiFetch<{ status: string; proposal: SoundmarkProposal }>(
`/soundmarks/${soundmarkId}/proposals/${proposalId}/vote`,
{ method: 'POST' },
)
}
export function removeVote(soundmarkId: number) {
return apiFetch<{ status: string }>(`/soundmarks/${soundmarkId}/proposals/vote`, { method: 'DELETE' })
}
import { useState } from 'react'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { LocationPicker } from './LocationPicker'
import * as soundmarksApi from '../api/soundmarks'
function Controlled({ initialLat = null, initialLon = null }: { initialLat?: number | null; initialLon?: number | null }) {
// Mirrors how AdminPanel actually uses LocationPicker - a controlled lat/lon pair updated
// via onChange, not the picker holding its own coordinate state.
const [lat, setLat] = useState(initialLat)
const [lon, setLon] = useState(initialLon)
return (
<div>
<LocationPicker
latitude={lat}
longitude={lon}
onChange={(newLat, newLon) => {
setLat(newLat)
setLon(newLon)
}}
/>
<p data-testid="coords">{lat !== null && lon !== null ? `${lat},${lon}` : 'none'}</p>
</div>
)
}
describe('LocationPicker', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('shows no coordinates hint text until a location is picked', () => {
render(<Controlled />)
expect(screen.queryByText(/°/)).not.toBeInTheDocument()
})
it('searches for an address and selecting a result sets the coordinates', async () => {
vi.spyOn(soundmarksApi, 'geocodeAddress').mockResolvedValue({
status: 'success',
results: [{ display_name: 'Eiffel Tower, Paris, France', latitude: 48.8584, longitude: 2.2945 }],
})
render(<Controlled />)
await userEvent.type(screen.getByPlaceholderText('Search for an address or place'), 'Eiffel')
const result = await screen.findByText('Eiffel Tower, Paris, France')
await userEvent.click(result)
await waitFor(() => {
expect(screen.getByTestId('coords')).toHaveTextContent('48.8584,2.2945')
})
})
it('does not search for a blank query', async () => {
const geocode = vi.spyOn(soundmarksApi, 'geocodeAddress').mockResolvedValue({ status: 'success', results: [] })
render(<Controlled />)
await userEvent.type(screen.getByPlaceholderText('Search for an address or place'), ' ')
await new Promise((resolve) => setTimeout(resolve, 500))
expect(geocode).not.toHaveBeenCalled()
})
it('shows the picked coordinates once set', async () => {
render(<Controlled initialLat={48.8584} initialLon={2.2945} />)
expect(screen.getByText(/48.85840, 2.29450/)).toBeInTheDocument()
})
})
import { useEffect, useState } from 'react'
import { MapContainer, Marker, TileLayer, useMap, useMapEvents } from 'react-leaflet'
import type { LeafletMouseEvent } from 'leaflet'
import { MapPin, Search } from 'lucide-react'
import { Input } from './ui/Input'
import { geocodeAddress, type GeocodeResult } from '../api/soundmarks'
const DEFAULT_CENTER: [number, number] = [20, 0] // low zoom, whole-world view when nothing is set yet
const ZOOM_NO_PIN = 2
const ZOOM_ON_JUMP = 15
interface LocationPickerProps {
latitude: number | null
longitude: number | null
onChange: (lat: number, lon: number) => void
}
/** Only moves the map view when `jumpTo` itself changes (i.e. an address was picked from the
* autocomplete dropdown) - deliberately NOT tied to latitude/longitude directly, since a map
* click or marker drag also changes those and should just move the pin, not yank the view the
* user already framed back to dead center. */
function FlyToOnJump({ jumpTo }: { jumpTo: { lat: number; lon: number } | null }) {
const map = useMap()
useEffect(() => {
if (jumpTo) map.setView([jumpTo.lat, jumpTo.lon], ZOOM_ON_JUMP)
}, [jumpTo, map])
return null
}
function ClickToPlacePin({ onClick }: { onClick: (lat: number, lon: number) => void }) {
useMapEvents({
click(e: LeafletMouseEvent) {
onClick(e.latlng.lat, e.latlng.lng)
},
})
return null
}
/** Address-search autocomplete (backed by the free OpenStreetMap Nominatim geocoder, proxied
* through the backend) plus an interactive map - search, click, or drag the pin to set a
* soundmark's coordinates. Used in the admin panel's create/edit form instead of raw lat/lon
* number inputs. */
export function LocationPicker({ latitude, longitude, onChange }: LocationPickerProps) {
const [query, setQuery] = useState('')
const [results, setResults] = useState<GeocodeResult[]>([])
const [showResults, setShowResults] = useState(false)
const [jumpTo, setJumpTo] = useState<{ lat: number; lon: number } | null>(null)
useEffect(() => {
if (!query.trim()) {
setResults([])
return
}
const handle = setTimeout(() => {
geocodeAddress(query)
.then((res) => {
setResults(res.results)
setShowResults(true)
})
.catch(() => setResults([]))
}, 400)
return () => clearTimeout(handle)
}, [query])
function selectResult(result: GeocodeResult) {
onChange(result.latitude, result.longitude)
setJumpTo({ lat: result.latitude, lon: result.longitude })
setQuery(result.display_name)
setShowResults(false)
}
const hasPin = latitude !== null && longitude !== null
const initialCenter: [number, number] = hasPin ? [latitude, longitude] : DEFAULT_CENTER
const initialZoom = hasPin ? ZOOM_ON_JUMP : ZOOM_NO_PIN
return (
<div>
<div className="relative">
<Search
size={16}
strokeWidth={2}
className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-neutral-500"
/>
<Input
placeholder="Search for an address or place"
value={query}
onChange={(e) => setQuery(e.target.value)}
onFocus={() => results.length > 0 && setShowResults(true)}
className="pl-9"
/>
{showResults && results.length > 0 && (
<ul className="absolute z-[1000] mt-1 max-h-56 w-full overflow-y-auto rounded-lg border border-neutral-700 bg-neutral-800 shadow-xl">
{results.map((r, i) => (
<li key={i}>
<button
type="button"
onClick={() => selectResult(r)}
className="flex w-full items-start gap-2 px-3 py-2 text-left text-sm text-neutral-200 hover:bg-neutral-700"
>
<MapPin size={14} strokeWidth={2} className="mt-0.5 shrink-0 text-neutral-500" />
<span className="line-clamp-2">{r.display_name}</span>
</button>
</li>
))}
</ul>
)}
</div>
<div className="relative z-0 mt-3 h-56 overflow-hidden rounded-lg border border-neutral-700">
<MapContainer center={initialCenter} zoom={initialZoom} className="h-full w-full" scrollWheelZoom>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<FlyToOnJump jumpTo={jumpTo} />
<ClickToPlacePin onClick={onChange} />
{hasPin && (
<Marker
position={[latitude, longitude]}
draggable
eventHandlers={{
dragend: (e) => {
const pos = e.target.getLatLng()
onChange(pos.lat, pos.lng)
},
}}
/>
)}
</MapContainer>
</div>
<p className="mt-1 text-xs text-neutral-500">
Search an address, click the map, or drag the pin to fine-tune.
{hasPin && ` ${latitude.toFixed(5)}, ${longitude.toFixed(5)}`}
</p>
</div>
)
}
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it } from 'vitest'
import { SoundmarkMap } from './SoundmarkMap'
import type { NearbySoundmark } from '../api/soundmarks'
const NEARBY: NearbySoundmark = {
id: 1,
name: "Joe's Cafe",
description: null,
latitude: 37.7749,
longitude: -122.4194,
radius_meters: 150,
business_owner_id: null,
business_owner_username: null,
song: { id: 1, title: 'Anthem', artist: 'Artist', album: null, coverart: null },
created_at: '2026-01-01T00:00:00Z',
proposal_count: 0,
updated_at: '2026-01-01T00:00:00Z',
distance_meters: 10,
}
describe('SoundmarkMap', () => {
it('renders without crashing given a live location and nearby soundmarks', () => {
render(<SoundmarkMap userLocation={{ lat: 37.7749, lon: -122.4194 }} soundmarks={[NEARBY]} />)
expect(screen.getByRole('button', { name: 'Center on me' })).toBeInTheDocument()
})
it('renders with an empty soundmarks list (just the live location dot)', () => {
render(<SoundmarkMap userLocation={{ lat: 0, lon: 0 }} soundmarks={[]} />)
expect(screen.getByRole('button', { name: 'Center on me' })).toBeInTheDocument()
})
it('the "Center on me" button is clickable without throwing', async () => {
render(<SoundmarkMap userLocation={{ lat: 37.7749, lon: -122.4194 }} soundmarks={[NEARBY]} />)
await userEvent.click(screen.getByRole('button', { name: 'Center on me' }))
})
})
import { useEffect, useState } from 'react'
import { CircleMarker, MapContainer, Marker, Popup, TileLayer, useMap } from 'react-leaflet'
import type { Map as LeafletMap } from 'leaflet'
import { LocateFixed } from 'lucide-react'
import type { NearbySoundmark } from '../api/soundmarks'
const INITIAL_ZOOM = 16
interface SoundmarkMapProps {
userLocation: { lat: number; lon: number }
soundmarks: NearbySoundmark[]
}
/** Pans to the user's position exactly once, when the map first mounts (the very first GPS
* fix) - not on every subsequent update, which would fight anyone panning around to look at
* their surroundings. Live tracking after that is opt-in via the "Center on me" button. */
function CenterOnMount({ lat, lon }: { lat: number; lon: number }) {
const map = useMap()
useEffect(() => {
map.setView([lat, lon], INITIAL_ZOOM)
// Intentionally empty deps - this should only run once, for the initial fix.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return null
}
/** Live-updating "you are here" dot, plus pins for whatever soundmarks are currently in range
* (from the same /soundmarks/nearby result the card view below uses) - a real map screen
* alongside the text-based summary, not a replacement for it. */
export function SoundmarkMap({ userLocation, soundmarks }: SoundmarkMapProps) {
const [map, setMap] = useState<LeafletMap | null>(null)
function centerOnMe() {
map?.setView([userLocation.lat, userLocation.lon], INITIAL_ZOOM)
}
return (
<div className="relative h-64 overflow-hidden rounded-xl border border-neutral-800">
<MapContainer
ref={setMap}
center={[userLocation.lat, userLocation.lon]}
zoom={INITIAL_ZOOM}
className="h-full w-full"
scrollWheelZoom={false}
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<CenterOnMount lat={userLocation.lat} lon={userLocation.lon} />
<CircleMarker
center={[userLocation.lat, userLocation.lon]}
radius={8}
pathOptions={{ color: '#10b981', fillColor: '#34d399', fillOpacity: 1, weight: 2 }}
>
<Popup>You are here</Popup>
</CircleMarker>
{soundmarks.map((sm) => (
<Marker key={sm.id} position={[sm.latitude, sm.longitude]}>
<Popup>
<span className="font-medium">{sm.name}</span>
{sm.song && (
<>
<br />
{sm.song.title} · {sm.song.artist}
</>
)}
</Popup>
</Marker>
))}
</MapContainer>
<button
onClick={centerOnMe}
aria-label="Center on me"
className="absolute bottom-3 right-3 z-[1000] flex h-9 w-9 items-center justify-center rounded-full bg-neutral-900/90 text-white shadow-lg backdrop-blur transition-colors hover:bg-neutral-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400"
>
<LocateFixed size={16} strokeWidth={2} />
</button>
</div>
)
}
@import "tailwindcss"; @import "tailwindcss";
@import "leaflet/dist/leaflet.css";
@keyframes message-enter { @keyframes message-enter {
from { from {
......
import L from 'leaflet'
import marker2x from 'leaflet/dist/images/marker-icon-2x.png'
import marker from 'leaflet/dist/images/marker-icon.png'
import markerShadow from 'leaflet/dist/images/marker-shadow.png'
// Leaflet's default marker icon references image paths that don't resolve correctly once
// bundled (a well-known issue with every bundler, not specific to Vite) - re-point them at
// the actual bundled asset URLs. Importing this file (for its side effect) once is enough;
// it patches the shared L.Icon.Default prototype that every <Marker> without an explicit
// icon prop uses.
delete (L.Icon.Default.prototype as unknown as { _getIconUrl?: unknown })._getIconUrl
L.Icon.Default.mergeOptions({
iconRetinaUrl: marker2x,
iconUrl: marker,
shadowUrl: markerShadow,
})
...@@ -2,6 +2,7 @@ import { StrictMode } from 'react' ...@@ -2,6 +2,7 @@ import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom' import { BrowserRouter } from 'react-router-dom'
import './index.css' import './index.css'
import './lib/leafletIcons'
import { App } from './App.tsx' import { App } from './App.tsx'
import { AuthProvider } from './context/AuthContext.tsx' import { AuthProvider } from './context/AuthContext.tsx'
import { PlayerProvider } from './context/PlayerContext.tsx' import { PlayerProvider } from './context/PlayerContext.tsx'
......
...@@ -8,6 +8,17 @@ import { PlayerProvider } from '../context/PlayerContext' ...@@ -8,6 +8,17 @@ import { PlayerProvider } from '../context/PlayerContext'
import * as soundmarksApi from '../api/soundmarks' import * as soundmarksApi from '../api/soundmarks'
import * as libraryApi from '../api/library' import * as libraryApi from '../api/library'
// LocationPicker renders a real Leaflet map, which doesn't render meaningfully in jsdom (no
// real layout engine) - LocationPicker.test.tsx covers its own behavior directly, so here it's
// stubbed down to just its essential contract: call onChange(lat, lon) when a location is set.
vi.mock('../components/LocationPicker', () => ({
LocationPicker: ({ onChange }: { onChange: (lat: number, lon: number) => void }) => (
<button type="button" onClick={() => onChange(12.5, 45.5)}>
Set location (mock)
</button>
),
}))
const LANDMARK: soundmarksApi.Soundmark = { const LANDMARK: soundmarksApi.Soundmark = {
id: 1, id: 1,
name: 'Old Clock Tower', name: 'Old Clock Tower',
...@@ -19,6 +30,7 @@ const LANDMARK: soundmarksApi.Soundmark = { ...@@ -19,6 +30,7 @@ const LANDMARK: soundmarksApi.Soundmark = {
business_owner_username: null, business_owner_username: null,
song: null, song: null,
created_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z',
proposal_count: 0,
updated_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z',
} }
...@@ -70,8 +82,7 @@ describe('AdminPanel', () => { ...@@ -70,8 +82,7 @@ describe('AdminPanel', () => {
await userEvent.click(screen.getByRole('button', { name: 'New soundmark' })) await userEvent.click(screen.getByRole('button', { name: 'New soundmark' }))
await userEvent.type(screen.getByPlaceholderText('Name'), 'New Plaza') await userEvent.type(screen.getByPlaceholderText('Name'), 'New Plaza')
await userEvent.type(screen.getByPlaceholderText('Latitude'), '12.5') await userEvent.click(screen.getByRole('button', { name: 'Set location (mock)' }))
await userEvent.type(screen.getByPlaceholderText('Longitude'), '45.5')
await userEvent.click(screen.getByRole('button', { name: 'Create soundmark' })) await userEvent.click(screen.getByRole('button', { name: 'Create soundmark' }))
await waitFor(() => { await waitFor(() => {
......
...@@ -6,6 +6,7 @@ import { Input, Textarea } from '../components/ui/Input' ...@@ -6,6 +6,7 @@ import { Input, Textarea } from '../components/ui/Input'
import { SkeletonRow } from '../components/ui/Skeleton' import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState' import { EmptyState } from '../components/ui/EmptyState'
import { SongPicker } from '../components/SongPicker' import { SongPicker } from '../components/SongPicker'
import { LocationPicker } from '../components/LocationPicker'
import { ApiError } from '../api/client' import { ApiError } from '../api/client'
import { import {
createSoundmark, createSoundmark,
...@@ -24,22 +25,22 @@ type Section = 'soundmarks' | 'users' ...@@ -24,22 +25,22 @@ type Section = 'soundmarks' | 'users'
interface SoundmarkFormValues { interface SoundmarkFormValues {
name: string name: string
description: string description: string
latitude: string latitude: number | null
longitude: string longitude: number | null
radius_meters: string radius_meters: string
business_owner_id: string // '' = none (curated landmark) business_owner_id: string // '' = none (curated landmark)
} }
function emptyForm(): SoundmarkFormValues { function emptyForm(): SoundmarkFormValues {
return { name: '', description: '', latitude: '', longitude: '', radius_meters: '200', business_owner_id: '' } return { name: '', description: '', latitude: null, longitude: null, radius_meters: '200', business_owner_id: '' }
} }
function formFromSoundmark(sm: Soundmark): SoundmarkFormValues { function formFromSoundmark(sm: Soundmark): SoundmarkFormValues {
return { return {
name: sm.name, name: sm.name,
description: sm.description ?? '', description: sm.description ?? '',
latitude: String(sm.latitude), latitude: sm.latitude,
longitude: String(sm.longitude), longitude: sm.longitude,
radius_meters: String(sm.radius_meters), radius_meters: String(sm.radius_meters),
business_owner_id: sm.business_owner_id ? String(sm.business_owner_id) : '', business_owner_id: sm.business_owner_id ? String(sm.business_owner_id) : '',
} }
...@@ -63,7 +64,7 @@ function SoundmarkFormModal({ ...@@ -63,7 +64,7 @@ function SoundmarkFormModal({
}) { }) {
const [values, setValues] = useState<SoundmarkFormValues>(initial ? formFromSoundmark(initial) : emptyForm()) const [values, setValues] = useState<SoundmarkFormValues>(initial ? formFromSoundmark(initial) : emptyForm())
function update<K extends keyof SoundmarkFormValues>(key: K, value: string) { function update<K extends keyof SoundmarkFormValues>(key: K, value: SoundmarkFormValues[K]) {
setValues((v) => ({ ...v, [key]: value })) setValues((v) => ({ ...v, [key]: value }))
} }
...@@ -94,22 +95,11 @@ function SoundmarkFormModal({ ...@@ -94,22 +95,11 @@ function SoundmarkFormModal({
onChange={(e) => update('description', e.target.value)} onChange={(e) => update('description', e.target.value)}
rows={2} rows={2}
/> />
<div className="grid grid-cols-2 gap-3"> <LocationPicker
<Input latitude={values.latitude}
placeholder="Latitude" longitude={values.longitude}
inputMode="decimal" onChange={(lat, lon) => setValues((v) => ({ ...v, latitude: lat, longitude: lon }))}
value={values.latitude}
onChange={(e) => update('latitude', e.target.value)}
required
/> />
<Input
placeholder="Longitude"
inputMode="decimal"
value={values.longitude}
onChange={(e) => update('longitude', e.target.value)}
required
/>
</div>
<Input <Input
placeholder="Trigger radius in meters" placeholder="Trigger radius in meters"
inputMode="numeric" inputMode="numeric"
...@@ -173,14 +163,18 @@ export function AdminPanel() { ...@@ -173,14 +163,18 @@ export function AdminPanel() {
useEffect(loadAll, []) useEffect(loadAll, [])
async function handleFormSubmit(values: SoundmarkFormValues) { async function handleFormSubmit(values: SoundmarkFormValues) {
if (values.latitude === null || values.longitude === null) {
setError('Pick a location on the map before saving.')
return
}
setSubmittingForm(true) setSubmittingForm(true)
setError(null) setError(null)
try { try {
const payload = { const payload = {
name: values.name, name: values.name,
description: values.description || null, description: values.description || null,
latitude: Number(values.latitude), latitude: values.latitude,
longitude: Number(values.longitude), longitude: values.longitude,
radius_meters: Number(values.radius_meters) || 200, radius_meters: Number(values.radius_meters) || 200,
business_owner_id: values.business_owner_id ? Number(values.business_owner_id) : null, business_owner_id: values.business_owner_id ? Number(values.business_owner_id) : null,
} }
......
...@@ -20,6 +20,7 @@ const OWNED_MARK: soundmarksApi.Soundmark = { ...@@ -20,6 +20,7 @@ const OWNED_MARK: soundmarksApi.Soundmark = {
business_owner_username: 'joe', business_owner_username: 'joe',
song: null, song: null,
created_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z',
proposal_count: 0,
updated_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z',
} }
......
...@@ -6,6 +6,7 @@ import { Nearby } from './Nearby' ...@@ -6,6 +6,7 @@ import { Nearby } from './Nearby'
import { AuthProvider } from '../context/AuthContext' import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext' import { PlayerProvider } from '../context/PlayerContext'
import * as soundmarksApi from '../api/soundmarks' import * as soundmarksApi from '../api/soundmarks'
import * as libraryApi from '../api/library'
const FOUND_MARK: soundmarksApi.NearbySoundmark = { const FOUND_MARK: soundmarksApi.NearbySoundmark = {
id: 1, id: 1,
...@@ -18,10 +19,27 @@ const FOUND_MARK: soundmarksApi.NearbySoundmark = { ...@@ -18,10 +19,27 @@ const FOUND_MARK: soundmarksApi.NearbySoundmark = {
business_owner_username: 'joe', business_owner_username: 'joe',
song: { id: 42, title: 'Cafe Anthem', artist: 'Local Band', album: null, coverart: null }, song: { id: 42, title: 'Cafe Anthem', artist: 'Local Band', album: null, coverart: null },
created_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z',
proposal_count: 0,
updated_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z',
distance_meters: 12, distance_meters: 12,
} }
const NO_ANTHEM_MARK: soundmarksApi.NearbySoundmark = {
...FOUND_MARK,
id: 2,
name: 'New Landmark',
song: null,
}
const EXISTING_PROPOSAL: soundmarksApi.SoundmarkProposal = {
id: 100,
song: { id: 42, title: 'Cafe Anthem', artist: 'Local Band', album: null, coverart: null },
vote_count: 3,
has_voted: false,
proposed_by_username: 'someone',
created_at: '2026-01-01T00:00:00Z',
}
function mockGeolocation({ succeed = true, code = 1 }: { succeed?: boolean; code?: number } = {}) { function mockGeolocation({ succeed = true, code = 1 }: { succeed?: boolean; code?: number } = {}) {
const position = { coords: { latitude: 37.7749, longitude: -122.4194 } } as GeolocationPosition const position = { coords: { latitude: 37.7749, longitude: -122.4194 } } as GeolocationPosition
const geolocation = { const geolocation = {
...@@ -52,6 +70,9 @@ describe('Nearby', () => { ...@@ -52,6 +70,9 @@ describe('Nearby', () => {
beforeEach(() => { beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '') vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '') vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
// Safety net so tests that don't care about proposals don't issue a real, unmocked fetch -
// proposal-specific behavior gets its own dedicated tests.
vi.spyOn(soundmarksApi, 'getProposals').mockResolvedValue({ status: 'success', proposals: [] })
}) })
afterEach(() => { afterEach(() => {
...@@ -120,4 +141,112 @@ describe('Nearby', () => { ...@@ -120,4 +141,112 @@ describe('Nearby', () => {
expect(await screen.findByText(/Location access was denied/)).toBeInTheDocument() expect(await screen.findByText(/Location access was denied/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()
}) })
it('shows a "propose one" prompt (no play button) for a soundmark with no anthem yet', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({
status: 'success',
soundmarks: [NO_ANTHEM_MARK],
})
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
expect(await screen.findByText('No anthem here yet - propose one below.')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Play' })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Propose a song' })).toBeInTheDocument()
})
it('lists existing proposals with their vote counts', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] })
vi.spyOn(soundmarksApi, 'getProposals').mockResolvedValue({ status: 'success', proposals: [EXISTING_PROPOSAL] })
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
expect(await screen.findByText('3 votes')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Vote for Cafe Anthem' })).toBeInTheDocument()
})
it('votes for a proposal and reflects the updated count', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] })
const getProposals = vi.spyOn(soundmarksApi, 'getProposals')
getProposals.mockResolvedValueOnce({ status: 'success', proposals: [EXISTING_PROPOSAL] })
const vote = vi.spyOn(soundmarksApi, 'voteForProposal').mockResolvedValue({
status: 'success',
proposal: { ...EXISTING_PROPOSAL, vote_count: 4, has_voted: true },
})
getProposals.mockResolvedValueOnce({
status: 'success',
proposals: [{ ...EXISTING_PROPOSAL, vote_count: 4, has_voted: true }],
})
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
await screen.findByText('3 votes')
await userEvent.click(screen.getByRole('button', { name: 'Vote for Cafe Anthem' }))
await waitFor(() => expect(vote).toHaveBeenCalledWith(FOUND_MARK.id, EXISTING_PROPOSAL.id))
expect(await screen.findByText('4 votes')).toBeInTheDocument()
})
it('removes a vote when toggling an already-voted proposal', async () => {
const votedProposal = { ...EXISTING_PROPOSAL, has_voted: true }
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] })
const getProposals = vi.spyOn(soundmarksApi, 'getProposals')
getProposals.mockResolvedValueOnce({ status: 'success', proposals: [votedProposal] })
const remove = vi.spyOn(soundmarksApi, 'removeVote').mockResolvedValue({ status: 'success' })
getProposals.mockResolvedValueOnce({
status: 'success',
proposals: [{ ...votedProposal, vote_count: 2, has_voted: false }],
})
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
await screen.findByText('3 votes')
await userEvent.click(screen.getByRole('button', { name: 'Remove your vote for Cafe Anthem' }))
await waitFor(() => expect(remove).toHaveBeenCalledWith(FOUND_MARK.id))
expect(await screen.findByText('2 votes')).toBeInTheDocument()
})
it('proposes a song via the song picker', async () => {
mockGeolocation({ succeed: true })
vi.spyOn(soundmarksApi, 'getNearbySoundmarks').mockResolvedValue({ status: 'success', soundmarks: [FOUND_MARK] })
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({
status: 'success',
library: [
{
id: 55,
user_id: 1,
title: 'My Pick',
artist: 'Me',
album: null,
genre: null,
coverart: null,
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
},
],
})
const propose = vi.spyOn(soundmarksApi, 'proposeSong').mockResolvedValue({
status: 'success',
proposal: { id: 200, song: { id: 55, title: 'My Pick', artist: 'Me', album: null, coverart: null }, vote_count: 1, has_voted: true, proposed_by_username: 'me', created_at: '2026-01-01T00:00:00Z' },
})
renderNearby()
await userEvent.click(screen.getByRole('button', { name: 'Find soundmarks near me' }))
await screen.findByText(/Joe's Cafe/)
await userEvent.click(screen.getByRole('button', { name: 'Propose a song' }))
await userEvent.click(await screen.findByText('My Pick'))
await waitFor(() => expect(propose).toHaveBeenCalledWith(FOUND_MARK.id, 55))
})
}) })
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { MapPin, Music2, Pause, Play } from 'lucide-react' import { MapPin, Music2, Pause, Play, Plus, ThumbsUp } from 'lucide-react'
import { Layout } from '../components/Layout' import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button' import { Button } from '../components/ui/Button'
import { EmptyState } from '../components/ui/EmptyState' import { EmptyState } from '../components/ui/EmptyState'
import { SoundmarkMap } from '../components/SoundmarkMap'
import { SongPicker } from '../components/SongPicker'
import { ApiError } from '../api/client' import { ApiError } from '../api/client'
import { fetchSoundmarkStreamUrl, getNearbySoundmarks, type NearbySoundmark } from '../api/soundmarks' import {
fetchSoundmarkStreamUrl,
getNearbySoundmarks,
getProposals,
proposeSong,
removeVote,
voteForProposal,
type NearbySoundmark,
type SoundmarkProposal,
} from '../api/soundmarks'
import { usePlayer } from '../context/PlayerContext' import { usePlayer } from '../context/PlayerContext'
type Status = 'idle' | 'locating' | 'ready' | 'error' type Status = 'idle' | 'locating' | 'ready' | 'error'
...@@ -27,12 +38,17 @@ export function Nearby() { ...@@ -27,12 +38,17 @@ export function Nearby() {
const [status, setStatus] = useState<Status>('idle') const [status, setStatus] = useState<Status>('idle')
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const [soundmarks, setSoundmarks] = useState<NearbySoundmark[]>([]) const [soundmarks, setSoundmarks] = useState<NearbySoundmark[]>([])
const [userLocation, setUserLocation] = useState<{ lat: number; lon: number } | null>(null)
const [proposals, setProposals] = useState<SoundmarkProposal[]>([])
const [showSongPicker, setShowSongPicker] = useState(false)
const [votingKey, setVotingKey] = useState<number | 'propose' | null>(null)
const watchIdRef = useRef<number | null>(null) const watchIdRef = useRef<number | null>(null)
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer() const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
function handlePosition(position: GeolocationPosition) { function handlePosition(position: GeolocationPosition) {
setStatus('ready') setStatus('ready')
setError(null) setError(null)
setUserLocation({ lat: position.coords.latitude, lon: position.coords.longitude })
getNearbySoundmarks(position.coords.latitude, position.coords.longitude) getNearbySoundmarks(position.coords.latitude, position.coords.longitude)
.then((res) => setSoundmarks(res.soundmarks)) .then((res) => setSoundmarks(res.soundmarks))
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to check nearby soundmarks')) .catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to check nearby soundmarks'))
...@@ -78,11 +94,69 @@ export function Nearby() { ...@@ -78,11 +94,69 @@ export function Nearby() {
const active = closest?.song ? toPlayable(closest as NearbySoundmark & { song: NonNullable<NearbySoundmark['song']> }) : null const active = closest?.song ? toPlayable(closest as NearbySoundmark & { song: NonNullable<NearbySoundmark['song']> }) : null
const isCurrent = !!active && currentSong?.id === active.id const isCurrent = !!active && currentSong?.id === active.id
// Refetch proposals when the detected soundmark itself changes (not on every watchPosition
// tick, which produces a fresh `soundmarks` array even when you haven't actually moved to a
// different one).
useEffect(() => {
if (!closest) {
setProposals([])
return
}
getProposals(closest.id)
.then((res) => setProposals(res.proposals))
.catch(() => setProposals([]))
}, [closest?.id])
function refreshAfterVoteChange(soundmarkId: number) {
getProposals(soundmarkId)
.then((res) => setProposals(res.proposals))
.catch(() => {})
// A vote can change which song is currently winning - refresh the nearby result too so
// the "now playing here" card reflects it immediately instead of on the next GPS tick.
if (userLocation) {
getNearbySoundmarks(userLocation.lat, userLocation.lon)
.then((res) => setSoundmarks(res.soundmarks))
.catch(() => {})
}
}
async function handleVoteToggle(proposal: SoundmarkProposal) {
if (!closest) return
setVotingKey(proposal.id)
try {
if (proposal.has_voted) {
await removeVote(closest.id)
} else {
await voteForProposal(closest.id, proposal.id)
}
refreshAfterVoteChange(closest.id)
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to update your vote')
} finally {
setVotingKey(null)
}
}
async function handlePropose(song: { id: number }) {
if (!closest) return
setShowSongPicker(false)
setVotingKey('propose')
try {
await proposeSong(closest.id, song.id)
refreshAfterVoteChange(closest.id)
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to propose that song')
} finally {
setVotingKey(null)
}
}
return ( return (
<Layout title="Soundmarks"> <Layout title="Soundmarks">
<p className="mb-6 text-sm leading-relaxed text-neutral-400"> <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 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. significant here or a local business chose it. You can propose your own pick too - whichever song
has the most votes is what plays.
</p> </p>
{status === 'idle' && ( {status === 'idle' && (
...@@ -112,16 +186,24 @@ export function Nearby() { ...@@ -112,16 +186,24 @@ export function Nearby() {
</div> </div>
)} )}
{status === 'ready' && !active && ( {userLocation && (status === 'ready' || status === 'locating') && (
<div className="mb-4">
<SoundmarkMap userLocation={userLocation} soundmarks={soundmarks} />
</div>
)}
{status === 'ready' && !closest && (
<EmptyState icon={MapPin} message="No soundmark nearby right now - keep moving, we'll keep checking." /> <EmptyState icon={MapPin} message="No soundmark nearby right now - keep moving, we'll keep checking." />
)} )}
{status === 'ready' && active && closest && ( {status === 'ready' && closest && (
<div className="rounded-xl border border-neutral-800 bg-neutral-900 p-3"> <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"> <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} /> <MapPin size={12} strokeWidth={2.5} />
{closest.name} {closest.name}
</p> </p>
{active ? (
<button <button
onClick={() => toggle(active)} onClick={() => toggle(active)}
disabled={isCurrent && streamLoading} disabled={isCurrent && streamLoading}
...@@ -149,9 +231,70 @@ export function Nearby() { ...@@ -149,9 +231,70 @@ export function Nearby() {
)} )}
</span> </span>
</button> </button>
) : (
<div className="flex items-center gap-4 rounded-lg p-1">
<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>
<p className="text-sm text-neutral-400">No anthem here yet - propose one below.</p>
</div>
)}
{closest.description && <p className="mt-3 px-1 text-sm text-neutral-400">{closest.description}</p>} {closest.description && <p className="mt-3 px-1 text-sm text-neutral-400">{closest.description}</p>}
<div className="mt-4 border-t border-neutral-800 pt-3">
<div className="mb-2 flex items-center justify-between px-1">
<p className="text-xs font-medium uppercase tracking-wide text-neutral-500">Proposals</p>
<button
onClick={() => setShowSongPicker(true)}
disabled={votingKey === 'propose'}
className="flex items-center gap-1 text-xs font-medium text-emerald-400 transition-colors hover:text-emerald-300 disabled:opacity-50"
>
<Plus size={13} strokeWidth={2.5} />
Propose a song
</button>
</div> </div>
{proposals.length === 0 ? (
<p className="px-1 text-sm text-neutral-500">
No proposals yet - be the first to suggest a song for this spot.
</p>
) : (
<ul className="divide-y divide-neutral-800/60">
{proposals.map((proposal) => (
<li key={proposal.id} className="flex items-center gap-3 py-2">
<button
onClick={() => handleVoteToggle(proposal)}
disabled={votingKey === proposal.id}
aria-pressed={proposal.has_voted}
aria-label={
proposal.has_voted
? `Remove your vote for ${proposal.song?.title}`
: `Vote for ${proposal.song?.title}`
}
className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full border transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400 disabled:opacity-50 ${
proposal.has_voted
? 'border-emerald-400 bg-emerald-400/10 text-emerald-400'
: 'border-neutral-700 text-neutral-400 hover:text-white'
}`}
>
<ThumbsUp size={13} strokeWidth={2} fill={proposal.has_voted ? 'currentColor' : 'none'} />
</button>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-white">{proposal.song?.title}</p>
<p className="truncate text-xs text-neutral-500">{proposal.song?.artist}</p>
</div>
<span className="shrink-0 text-xs font-medium text-neutral-400">
{proposal.vote_count} {proposal.vote_count === 1 ? 'vote' : 'votes'}
</span>
</li>
))}
</ul>
)} )}
</div>
</div>
)}
{showSongPicker && <SongPicker onClose={() => setShowSongPicker(false)} onSelect={handlePropose} />}
</Layout> </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