Commit dd72364f authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add Posts: song + remix-reply feed, previously backend-only with no UI

Posts had full backend support (create, remix as a reply, fetch a
recursive remix tree) but nothing in the frontend ever called any of
it - no feed, no way to browse or discover a post at all.

New page at /posts: a feed of recent posts (song + caption + author +
remix count), a composer to post a song, and a tree view for an
individual post showing every remix branching off it with a "Remix
this" action at each node. Playback goes through the shared player via
the new cross-user post-stream endpoint.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 93237997
Pipeline #1076 canceled with stage
...@@ -5,6 +5,7 @@ import { Discovery } from './pages/Discovery' ...@@ -5,6 +5,7 @@ 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 { GeoDrops } from './pages/GeoDrops' import { GeoDrops } from './pages/GeoDrops'
import { Posts } from './pages/Posts'
import { Remix } from './pages/Remix' import { Remix } from './pages/Remix'
import { Nearby } from './pages/Nearby' import { Nearby } from './pages/Nearby'
import { BusinessPanel } from './pages/BusinessPanel' import { BusinessPanel } from './pages/BusinessPanel'
...@@ -25,6 +26,7 @@ export function App() { ...@@ -25,6 +26,7 @@ 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="/drops" element={protect(<GeoDrops />)} /> <Route path="/drops" element={protect(<GeoDrops />)} />
<Route path="/posts" element={protect(<Posts />)} />
<Route path="/remix" element={protect(<Remix />)} /> <Route path="/remix" element={protect(<Remix />)} />
<Route path="/nearby" element={protect(<Nearby />)} /> <Route path="/nearby" element={protect(<Nearby />)} />
<Route <Route
......
...@@ -42,6 +42,21 @@ export function getPostTree(postId: number) { ...@@ -42,6 +42,21 @@ export function getPostTree(postId: number) {
return apiFetch<PostTree>(`/social/posts/${postId}/tree`) return apiFetch<PostTree>(`/social/posts/${postId}/tree`)
} }
/** For PlayerContext's `streamUrl` override - fetches a post's song as an authenticated blob,
* regardless of who uploaded it (a post's song_id isn't necessarily the poster's own library
* song). Caller is responsible for calling URL.revokeObjectURL(). */
export async function fetchPostStreamUrl(postId: number): Promise<string> {
const token = getAccessToken()
const res = await fetch(`${API_BASE_URL}/social/posts/${postId}/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)
}
export interface GeoDrop { export interface GeoDrop {
id: number id: number
user_id: number user_id: number
......
...@@ -2,6 +2,7 @@ import type { ReactNode } from 'react' ...@@ -2,6 +2,7 @@ import type { ReactNode } from 'react'
import { Link, useLocation } from 'react-router-dom' import { Link, useLocation } from 'react-router-dom'
import { import {
Compass, Compass,
Disc3,
Headphones, Headphones,
Library, Library,
LogOut, LogOut,
...@@ -28,6 +29,7 @@ const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [ ...@@ -28,6 +29,7 @@ const NAV_ITEMS: { to: string; label: string; icon: LucideIcon }[] = [
{ to: '/discovery', label: 'Discover', icon: Compass }, { to: '/discovery', label: 'Discover', icon: Compass },
{ 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: '/posts', label: 'Posts', icon: Disc3 },
{ to: '/remix', label: 'Remix', icon: Wand2 }, { to: '/remix', label: 'Remix', icon: Wand2 },
{ to: '/nearby', label: 'Soundmarks', icon: MapPin }, { to: '/nearby', label: 'Soundmarks', icon: MapPin },
{ to: '/drops', label: 'Drops', icon: MapPinned }, { to: '/drops', label: 'Drops', icon: MapPinned },
......
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 { Posts } from './Posts'
import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as socialApi from '../api/social'
import * as libraryApi from '../api/library'
const ROOT_POST: socialApi.Post = {
id: 1,
user_id: 5,
username: 'someone',
song: { id: 42, title: 'Original Track', artist: 'Local Band', album: null, coverart: null },
parent_post_id: null,
caption: 'check this out',
created_at: '2026-01-01T00:00:00Z',
remix_count: 1,
}
const CHILD_POST: socialApi.Post = {
id: 2,
user_id: 6,
username: 'remixer',
song: { id: 43, title: 'Remixed Track', artist: 'Someone Else', album: null, coverart: null },
parent_post_id: 1,
caption: 'my take',
created_at: '2026-01-02T00:00:00Z',
}
const TREE: socialApi.PostTree = {
post: ROOT_POST,
children: [{ post: CHILD_POST, children: [] }],
}
const MY_LIBRARY_SONG = {
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',
}
function renderPosts() {
return render(
<MemoryRouter>
<AuthProvider>
<PlayerProvider>
<Posts />
</PlayerProvider>
</AuthProvider>
</MemoryRouter>,
)
}
describe('Posts', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows an empty state when there are no posts', async () => {
vi.spyOn(socialApi, 'listPosts').mockResolvedValue([])
renderPosts()
expect(await screen.findByText(/No posts yet/)).toBeInTheDocument()
})
it('lists posts with song, caption, author, and remix count', async () => {
vi.spyOn(socialApi, 'listPosts').mockResolvedValue([ROOT_POST])
renderPosts()
expect(await screen.findByText('Original Track')).toBeInTheDocument()
expect(screen.getByText('Local Band')).toBeInTheDocument()
expect(screen.getByText('"check this out"')).toBeInTheDocument()
expect(screen.getByText(/someone · 1 remix/)).toBeInTheDocument()
})
it('disables Post until a song has been picked', async () => {
vi.spyOn(socialApi, 'listPosts').mockResolvedValue([])
renderPosts()
await screen.findByText(/No posts yet/)
expect(screen.getByRole('button', { name: 'Post' })).toBeDisabled()
})
it('composes a post by picking a song and adding a caption', async () => {
const listPosts = vi.spyOn(socialApi, 'listPosts')
listPosts.mockResolvedValueOnce([])
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [MY_LIBRARY_SONG] })
const create = vi.spyOn(socialApi, 'createPost').mockResolvedValue({
...ROOT_POST,
id: 3,
song: { id: 55, title: 'My Pick', artist: 'Me', album: null, coverart: null },
})
listPosts.mockResolvedValueOnce([{ ...ROOT_POST, id: 3 }])
renderPosts()
await screen.findByText(/No posts yet/)
await userEvent.click(screen.getByRole('button', { name: 'Choose a song to post' }))
await userEvent.click(await screen.findByText('My Pick'))
expect(screen.getByText('My Pick')).toBeInTheDocument() // now shown as the pending pick
await userEvent.type(screen.getByPlaceholderText('Say something about it (optional)'), 'fresh drop')
await userEvent.click(screen.getByRole('button', { name: 'Post' }))
await waitFor(() => expect(create).toHaveBeenCalledWith(55, 'fresh drop'))
})
it('opens a post to view its remix tree and navigates back to the feed', async () => {
vi.spyOn(socialApi, 'listPosts').mockResolvedValue([ROOT_POST])
vi.spyOn(socialApi, 'getPostTree').mockResolvedValue(TREE)
renderPosts()
await userEvent.click(await screen.findByText('Original Track'))
expect(await screen.findByText('Remixed Track')).toBeInTheDocument()
expect(screen.getByText('Someone Else')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: /Back to feed/ }))
expect(await screen.findByText('"check this out"')).toBeInTheDocument()
expect(screen.queryByText('Remixed Track')).not.toBeInTheDocument()
})
it('remixes a post from the tree view', async () => {
vi.spyOn(socialApi, 'listPosts').mockResolvedValue([ROOT_POST])
const getPostTree = vi.spyOn(socialApi, 'getPostTree')
getPostTree.mockResolvedValueOnce(TREE)
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [MY_LIBRARY_SONG] })
const create = vi.spyOn(socialApi, 'createPost').mockResolvedValue({
...CHILD_POST,
id: 4,
song: { id: 55, title: 'My Pick', artist: 'Me', album: null, coverart: null },
parent_post_id: 1,
})
getPostTree.mockResolvedValueOnce({
post: ROOT_POST,
children: [{ post: CHILD_POST, children: [] }, { post: { ...CHILD_POST, id: 4 }, children: [] }],
})
renderPosts()
await userEvent.click(await screen.findByText('Original Track'))
await screen.findByText('Remixed Track')
const remixButtons = screen.getAllByRole('button', { name: /Remix this/ })
await userEvent.click(remixButtons[0])
await userEvent.click(await screen.findByText('My Pick'))
await waitFor(() => expect(create).toHaveBeenCalledWith(55, '', ROOT_POST.id))
})
it('plays a post through the shared player when tapped', async () => {
vi.spyOn(socialApi, 'listPosts').mockResolvedValue([ROOT_POST])
vi.spyOn(socialApi, 'fetchPostStreamUrl').mockResolvedValue('blob:fake-url')
renderPosts()
await screen.findByText('Original Track')
await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await waitFor(() => expect(socialApi.fetchPostStreamUrl).toHaveBeenCalledWith(ROOT_POST.id))
const card = screen.getByText('"check this out"').closest('li')!
expect(await within(card).findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
})
import { useEffect, useState } from 'react'
import { ArrowLeft, Disc3, Music2, Pause, Play, Plus, Shuffle } from 'lucide-react'
import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button'
import { Input } from '../components/ui/Input'
import { EmptyState } from '../components/ui/EmptyState'
import { SkeletonRow } from '../components/ui/Skeleton'
import { SongPicker } from '../components/SongPicker'
import { ApiError } from '../api/client'
import { createPost, fetchPostStreamUrl, getPostTree, listPosts, type Post, type PostTree } from '../api/social'
import { usePlayer } from '../context/PlayerContext'
function toPlayable(post: Post) {
return {
// Negative to avoid colliding with a real LibrarySong id - see PlayableSong's `streamUrl`
// doc (same convention as the other social features' not-a-real-library-song ids).
id: -post.id,
title: post.song!.title,
artist: post.song!.artist,
album: post.song!.album,
coverart: post.song!.coverart,
streamUrl: () => fetchPostStreamUrl(post.id),
}
}
function PlayButton({ post }: { post: Post }) {
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
if (!post.song) return null
const active = toPlayable(post)
const isCurrent = currentSong?.id === active.id
return (
<button
onClick={() => toggle(active)}
disabled={isCurrent && streamLoading}
aria-label={isCurrent && isPlaying ? 'Pause' : 'Play'}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-neutral-800 text-white transition-colors hover:bg-neutral-700 disabled:cursor-not-allowed"
>
{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={15} strokeWidth={2} fill="currentColor" />
) : (
<Play size={15} strokeWidth={2} fill="currentColor" className="ml-0.5" />
)}
</button>
)
}
function PostRow({ post, onOpen }: { post: Post; onOpen?: () => void }) {
return (
<div className="flex items-center gap-3 p-1">
{post.song?.coverart ? (
<img src={post.song.coverart} alt="" className="h-12 w-12 shrink-0 rounded-lg object-cover" />
) : (
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-neutral-800 text-neutral-600">
<Music2 size={18} strokeWidth={1.75} />
</div>
)}
<button onClick={onOpen} disabled={!onOpen} className="min-w-0 flex-1 text-left disabled:cursor-default">
<p className="truncate text-sm font-medium text-white">{post.song?.title ?? 'Unknown song'}</p>
<p className="truncate text-xs text-neutral-400">{post.song?.artist}</p>
{post.caption && <p className="mt-0.5 truncate text-xs text-neutral-500">"{post.caption}"</p>}
<p className="mt-0.5 text-xs text-neutral-600">
{post.username ?? `user #${post.user_id}`}
{post.remix_count !== undefined && post.remix_count > 0 && ` · ${post.remix_count} remix${post.remix_count === 1 ? '' : 'es'}`}
</p>
</button>
<PlayButton post={post} />
</div>
)
}
function RemixTreeNode({ node, depth, onRemix }: { node: PostTree; depth: number; onRemix: (post: Post) => void }) {
return (
<li>
<div className="rounded-xl border border-neutral-800 bg-neutral-900 p-2">
<PostRow post={node.post} />
<button
onClick={() => onRemix(node.post)}
className="ml-1 flex items-center gap-1 text-xs font-medium text-emerald-400 transition-colors hover:text-emerald-300"
>
<Shuffle size={12} strokeWidth={2.5} />
Remix this
</button>
</div>
{node.children.length > 0 && (
<ul className="mt-2 space-y-2 border-l border-neutral-800 pl-4" style={{ marginLeft: depth === 0 ? 8 : 0 }}>
{node.children.map((child) => (
<RemixTreeNode key={child.post.id} node={child} depth={depth + 1} onRemix={onRemix} />
))}
</ul>
)}
</li>
)
}
export function Posts() {
const [posts, setPosts] = useState<Post[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [showSongPicker, setShowSongPicker] = useState(false)
const [caption, setCaption] = useState('')
const [pendingSong, setPendingSong] = useState<{ id: number; title: string; artist: string } | null>(null)
const [posting, setPosting] = useState(false)
const [openPostId, setOpenPostId] = useState<number | null>(null)
const [tree, setTree] = useState<PostTree | null>(null)
const [treeLoading, setTreeLoading] = useState(false)
const [remixTarget, setRemixTarget] = useState<Post | null>(null)
function refresh() {
setLoading(true)
listPosts()
.then(setPosts)
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to load posts'))
.finally(() => setLoading(false))
}
useEffect(refresh, [])
function openTree(postId: number) {
setOpenPostId(postId)
setTreeLoading(true)
getPostTree(postId)
.then(setTree)
.catch((err) => setError(err instanceof ApiError ? err.message : 'Failed to load this post'))
.finally(() => setTreeLoading(false))
}
async function handlePickSongForNewPost(song: { id: number; title: string; artist: string }) {
setShowSongPicker(false)
setPendingSong(song)
}
async function handlePost() {
if (!pendingSong) return
setPosting(true)
setError(null)
try {
await createPost(pendingSong.id, caption.trim())
setPendingSong(null)
setCaption('')
refresh()
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to post')
} finally {
setPosting(false)
}
}
async function handleRemixPick(song: { id: number }) {
if (!remixTarget) return
const target = remixTarget
setRemixTarget(null)
try {
await createPost(song.id, '', target.id)
if (openPostId !== null) openTree(openPostId)
} catch (err) {
setError(err instanceof ApiError ? err.message : 'Failed to remix that post')
}
}
if (openPostId !== null) {
return (
<Layout title="Post">
<button
onClick={() => {
setOpenPostId(null)
setTree(null)
}}
className="mb-4 flex items-center gap-1.5 text-sm text-neutral-400 transition-colors hover:text-white"
>
<ArrowLeft size={16} strokeWidth={2} />
Back to feed
</button>
{treeLoading && (
<div className="space-y-2">
<SkeletonRow />
<SkeletonRow />
</div>
)}
{error && <p className="mb-4 text-sm text-red-400">{error}</p>}
{tree && (
<ul className="space-y-2">
<RemixTreeNode node={tree} depth={0} onRemix={setRemixTarget} />
</ul>
)}
{remixTarget && <SongPicker onClose={() => setRemixTarget(null)} onSelect={handleRemixPick} />}
</Layout>
)
}
return (
<Layout title="Posts">
<p className="mb-6 text-sm leading-relaxed text-neutral-400">
Post a song, and let others remix it into their own pick - each reply forms a branch, so a post
grows into a whole tree of takes on the same idea.
</p>
<div className="mb-6 rounded-xl border border-neutral-800 bg-neutral-900 p-3">
{pendingSong ? (
<div className="mb-3 flex items-center gap-3 rounded-lg bg-neutral-800/60 p-2">
<Disc3 size={18} strokeWidth={1.75} className="shrink-0 text-neutral-500" />
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-white">{pendingSong.title}</p>
<p className="truncate text-xs text-neutral-400">{pendingSong.artist}</p>
</div>
<button
onClick={() => setPendingSong(null)}
className="shrink-0 text-xs text-neutral-500 hover:text-white"
>
Change
</button>
</div>
) : (
<Button variant="secondary" size="sm" onClick={() => setShowSongPicker(true)} className="mb-3 gap-1.5">
<Plus size={14} strokeWidth={2.5} />
Choose a song to post
</Button>
)}
<Input
value={caption}
onChange={(e) => setCaption(e.target.value)}
placeholder="Say something about it (optional)"
className="mb-3"
/>
<Button onClick={handlePost} disabled={!pendingSong || posting}>
{posting ? 'Posting…' : 'Post'}
</Button>
</div>
{error && <p className="mb-4 text-sm text-red-400">{error}</p>}
{loading && (
<div className="divide-y divide-neutral-800/80">
<SkeletonRow />
<SkeletonRow />
</div>
)}
{!loading && posts.length === 0 && (
<EmptyState icon={Disc3} message="No posts yet - be the first to post a song." />
)}
<ul className="space-y-2">
{posts.map((post) => (
<li key={post.id} className="rounded-xl border border-neutral-800 bg-neutral-900 p-2">
<PostRow post={post} onOpen={() => openTree(post.id)} />
</li>
))}
</ul>
{showSongPicker && <SongPicker onClose={() => setShowSongPicker(false)} onSelect={handlePickSongForNewPost} />}
</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