Commit 3254e7c0 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Home: drop uploader attribution, add favorite heart to every row

Matches the backend's dedup + unattributed feed: HomeSong no longer carries
a username, and no uploader name is shown anywhere on the page. Added a
favorite heart to HomeSongRow (used by both New Songs/Suggestions and an
expanded album's track list) - an owned song favorites directly, someone
else's claims first via the same useHomeSongPlayback hook already used for
play/add-to-playlist, optimistic with revert-on-failure.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 1120ef80
import { apiFetch } from './client'
/** A song on the global Home feed - belongs to whichever user actually uploaded it (`user_id`/
* `username`), not necessarily the caller. No `is_liked`/`file_path` here (see library.ts's
* LibrarySong) - a viewer can't have liked a song they don't own yet, and a song owned by
* someone else can't be streamed directly until claimed (see useHomeSongPlayback). */
/** A song on the global Home feed - belongs to whichever user actually uploaded it (`user_id`),
* not necessarily the caller, but deliberately not attributed to them anywhere in the UI - the
* feed presents one shared pool of music, not "added by X". No `file_path` here (see
* library.ts's LibrarySong) - a song owned by someone else can't be streamed directly until
* claimed (see useHomeSongPlayback). `is_liked` is only ever true for a song the caller already
* owns; favoriting one that isn't claims it first (same hook). */
export interface HomeSong {
id: number
user_id: number
username: string | null
title: string
artist: string
album: string | null
genre: string | null
coverart: string | null
added_at: string
is_liked: boolean
}
export interface HomeAlbum {
......
......@@ -21,7 +21,6 @@ export function HomeAlbumCard({
const { userId } = useAuth()
const [expanded, setExpanded] = useState(false)
const isOwnAlbum = album.user_id === userId
const uploaderName = album.songs[0]?.username ?? null
function handleOpen() {
if (isOwnAlbum) {
......@@ -49,7 +48,6 @@ export function HomeAlbumCard({
<p className="truncate text-sm font-medium text-on-surface">{album.album}</p>
<p className="truncate text-xs text-on-surface-variant">
{album.artist} · {album.track_count} track{album.track_count === 1 ? '' : 's'}
{!isOwnAlbum && uploaderName ? ` · ${uploaderName}` : ''}
</p>
</div>
</button>
......
import { ListPlus, Music2, Pause, Play } from 'lucide-react'
import { Heart, ListPlus, Music2, Pause, Play } from 'lucide-react'
import type { HomeSong } from '../api/home'
import { useHomeSongPlayback } from '../hooks/useHomeSongPlayback'
/** A row for the Home feed's "Suggestions" section - visually close to SharedSongRow, but a
* Home-feed song can belong to the caller already (plays directly, shows a real now-playing
* state) as well as to someone else (claim-then-play) - see useHomeSongPlayback for which. */
/** A row for the Home feed's "New Songs" and "Suggestions" sections - visually close to
* SharedSongRow, but a Home-feed song can belong to the caller already (plays directly, shows a
* real now-playing state, favorites directly) as well as to someone else (claim-then-act for
* all three) - see useHomeSongPlayback for which. */
export function HomeSongRow({
song,
onAddToPlaylist,
......@@ -12,8 +13,17 @@ export function HomeSongRow({
song: HomeSong
onAddToPlaylist: (song: { id: number; title: string }) => void
}) {
const { isOwnSong, isCurrent, isPlaying, streamLoading, claiming, error, handlePlay, handleAddToPlaylist } =
useHomeSongPlayback(song)
const {
isCurrent,
isPlaying,
streamLoading,
claiming,
error,
isLiked,
handlePlay,
handleAddToPlaylist,
handleToggleFavorite,
} = useHomeSongPlayback(song)
return (
<li className="-mx-1 rounded-xl">
......@@ -53,11 +63,25 @@ export function HomeSongRow({
<p className="truncate text-sm text-on-surface-variant">
{song.artist}
{song.album ? ` · ${song.album}` : ''}
{!isOwnSong && song.username ? ` · ${song.username}` : ''}
</p>
{error && <p className="mt-0.5 truncate text-xs text-error">{error}</p>}
</div>
</button>
<button
onClick={handleToggleFavorite}
disabled={claiming !== null}
aria-label={isLiked ? `Unlike ${song.title}` : `Like ${song.title}`}
aria-pressed={isLiked}
className={`shrink-0 rounded-full p-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed ${
isLiked ? 'text-primary hover:bg-surface-container-high' : 'text-on-surface-variant hover:bg-surface-container-high hover:text-primary'
}`}
>
{claiming === 'favorite' ? (
<span className="block h-[18px] w-[18px] animate-spin rounded-full border-2 border-outline-variant border-t-on-surface" />
) : (
<Heart size={18} strokeWidth={1.75} fill={isLiked ? 'currentColor' : 'none'} />
)}
</button>
<button
onClick={() => handleAddToPlaylist(onAddToPlaylist)}
disabled={claiming !== null}
......
import { useState } from 'react'
import { claimSharedSong } from '../api/library'
import { claimSharedSong, favoriteSong, unfavoriteSong } from '../api/library'
import { ApiError } from '../api/client'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { useAuth } from '../context/AuthContext'
import type { HomeSong } from '../api/home'
/** Shared by HomeSongRow and HomeAlbumCard's expanded track list (the places a Home-feed song
* can be tapped) so the claim-then-play logic isn't duplicated between them. A Home-feed song
* the caller already owns (`user_id === userId`) plays directly via its real library id;
* everyone else's goes through the same claim-then-play mechanism SharedSongRow already uses
* can be tapped) so the claim-then-act logic isn't duplicated between them. A Home-feed song
* the caller already owns (`user_id === userId`) acts directly via its real library id;
* everyone else's goes through the same claim-then-act mechanism SharedSongRow already uses
* for Library's shared search results, since that id belongs to someone else's library row and
* can't be streamed until the caller has their own copy. */
* nothing (streaming, favoriting, playlisting) can happen on it until the caller has their own
* copy. */
export function useHomeSongPlayback(song: HomeSong) {
const { userId } = useAuth()
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const [claiming, setClaiming] = useState<'play' | 'playlist' | null>(null)
const [claiming, setClaiming] = useState<'play' | 'playlist' | 'favorite' | null>(null)
const [error, setError] = useState<string | null>(null)
// Optimistic override, same shape as Library.tsx's own favorite toggle - null means "trust
// the server-supplied song.is_liked" (only ever true for an owned song anyway), set once the
// viewer actually taps the heart so the UI flips immediately instead of waiting on the
// claim+favorite round trip.
const [likedOverride, setLikedOverride] = useState<boolean | null>(null)
const isOwnSong = song.user_id === userId
const isCurrent = isOwnSong && currentSong?.id === song.id
const isLiked = likedOverride ?? song.is_liked
function toPlayable(libraryId: number): PlayableSong {
return { id: libraryId, title: song.title, artist: song.artist, album: song.album, coverart: song.coverart }
......@@ -64,5 +71,24 @@ export function useHomeSongPlayback(song: HomeSong) {
}
}
return { isOwnSong, isCurrent, isPlaying, streamLoading, claiming, error, handlePlay, handleAddToPlaylist }
/** Claims first if the caller doesn't already own this song (same as play/add-to-playlist),
* then favorites/unfavorites the resulting owned copy - optimistic, reverting the heart on
* failure the same way Library.tsx's own toggle does. */
async function handleToggleFavorite() {
const nextLiked = !isLiked
setLikedOverride(nextLiked)
setError(null)
setClaiming('favorite')
try {
const libraryId = await resolveLibraryId()
await (nextLiked ? favoriteSong(libraryId) : unfavoriteSong(libraryId))
} catch (err) {
setLikedOverride(!nextLiked)
setError(err instanceof ApiError ? err.message : `Could not update "${song.title}"`)
} finally {
setClaiming(null)
}
}
return { isOwnSong, isCurrent, isPlaying, streamLoading, claiming, error, isLiked, handlePlay, handleAddToPlaylist, handleToggleFavorite }
}
......@@ -26,25 +26,25 @@ const OTHER_ID = 42
const OWN_SONG = {
id: 10,
user_id: ME_ID,
username: 'me',
title: 'My Own Track',
artist: 'Me',
album: null,
genre: 'Pop',
coverart: null,
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
}
const OTHER_SONG = {
id: 20,
user_id: OTHER_ID,
username: 'stranger',
title: "Someone Else's Track",
artist: 'Nobody',
album: null,
genre: 'Rock',
coverart: null,
added_at: '2026-01-01T00:00:00Z',
is_liked: false,
}
const OWN_ALBUM = {
......@@ -132,6 +132,8 @@ describe('Home', () => {
expect(screen.getByText('My Album')).toBeInTheDocument()
expect(screen.getByText('Suggestions')).toBeInTheDocument()
expect(screen.getByText("Someone Else's Track")).toBeInTheDocument()
// No uploader attribution anywhere on the page - the feed is one shared pool of music.
expect(screen.queryByText(/stranger/)).not.toBeInTheDocument()
})
it('plays a song the caller already owns directly, without claiming it first', async () => {
......@@ -182,6 +184,41 @@ describe('Home', () => {
expect(claimSharedSong).not.toHaveBeenCalled()
})
it('likes a song the caller already owns directly, without claiming it first', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [OWN_SONG], new_albums: [], suggestions: [] })
const claimSharedSong = vi.spyOn(libraryApi, 'claimSharedSong')
const favoriteSong = vi.spyOn(libraryApi, 'favoriteSong').mockResolvedValue({ status: 'success', is_liked: true })
renderHome()
await userEvent.click(await screen.findByRole('button', { name: 'Like My Own Track' }))
await waitFor(() => expect(favoriteSong).toHaveBeenCalledWith(OWN_SONG.id))
expect(claimSharedSong).not.toHaveBeenCalled()
})
it('claims a suggestion from someone else before favoriting it', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [], new_albums: [], suggestions: [OTHER_SONG] })
const claimSharedSong = vi.spyOn(libraryApi, 'claimSharedSong').mockResolvedValue({ status: 'success', library_song_id: 77 })
const favoriteSong = vi.spyOn(libraryApi, 'favoriteSong').mockResolvedValue({ status: 'success', is_liked: true })
renderHome()
await userEvent.click(await screen.findByRole('button', { name: /Like Someone Else's Track/ }))
await waitFor(() => expect(claimSharedSong).toHaveBeenCalledWith("Someone Else's Track", 'Nobody'))
await waitFor(() => expect(favoriteSong).toHaveBeenCalledWith(77))
})
it('reverts the optimistic like on a Home song if the request fails', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [OWN_SONG], new_albums: [], suggestions: [] })
vi.spyOn(libraryApi, 'favoriteSong').mockRejectedValue(new ApiError(500, 'Nope', null))
renderHome()
const heart = await screen.findByRole('button', { name: 'Like My Own Track' })
await userEvent.click(heart)
await waitFor(() => expect(screen.getByRole('button', { name: 'Like My Own Track' })).toBeInTheDocument())
})
it('tapping an album the caller owns navigates to its real detail page', async () => {
vi.spyOn(homeApi, 'getHomeFeed').mockResolvedValue({ status: 'success', latest_songs: [], new_albums: [OWN_ALBUM], suggestions: [] })
......
......@@ -106,7 +106,8 @@ const BACKEND_DONE: DoneGroup[] = [
{
area: 'Home Feed',
items: [
'New GET /home/feed (2026-10-06): a global landing feed, distinct from the per-user Library page - latest_songs (the 8 most-recently-added songs across every user, enriched with the real uploader\'s username), new_albums (grouped by (album, artist, user_id), deliberately not merged across different uploaders of the same album name, same reasoning as /library/shared/search\'s own precedent - no real Album entity exists to reconcile whose coverart wins), and suggestions. Suggestions is explicitly a placeholder, commented as such in code - a lightweight non-personalized pick excluding the caller\'s own songs (and any song matching an identity they already own), softly biased toward genres already in their own library when they have any; a real algorithm driven by search/listening habits is future work, not built yet.',
'New GET /home/feed (2026-10-06): a global landing feed, distinct from the per-user Library page - latest_songs (the 8 most-recently-added songs across every user), new_albums, and suggestions. Suggestions is explicitly a placeholder, commented as such in code - a lightweight non-personalized pick excluding the caller\'s own songs (and any song matching an identity they already own), softly biased toward genres already in their own library when they have any; a real algorithm driven by search/listening habits is future work, not built yet.',
'Deduped + unattributed (2026-10-07): every section is now deduped by (title, artist)/(album, artist) identity - the same song or album tagged by several different users used to eat one display slot per uploader (a popular track could fill most of an 8-item list with copies of itself), now shows once. Albums merge across uploaders by picking one representative copy to display (the caller\'s own, if they have one, so the card can navigate straight to their real album page instead of needing a claim; otherwise the most recently added) rather than literally merging different people\'s track data together - still never reconciles mismatched coverart/track-subsets from different uploads, just avoids showing the same album twice. No uploader identity (username) is attached to any global-feed entry - the feed reads as one shared pool of music, not "added by X". New `is_liked` field (only ever true for a song the caller already owns, via the same liked_song_ids helper library.py uses - now shared from services/favorites.py) powers a favorite heart directly on Home rows.',
],
},
{
......@@ -212,7 +213,7 @@ const FRONTEND_DONE: DoneGroup[] = [
{
area: 'Home',
items: [
'New default landing page (2026-10-06), replacing Library as where you land post-login and at the catch-all route - Library remains a full nav destination, just no longer first. Globe nav icon (Globe2 was already taken by Library\'s "Shared" scope toggle, so a distinct icon avoids visual overlap between the two concepts). Three sections backed by GET /home/feed: "Newly added" (a responsive card grid of the 8 latest songs app-wide), "New albums" (same card grid), "Suggestions" (song rows) - a song the caller already owns plays directly via its real library id, one they don\'t go through the same claim-then-play flow Library\'s shared search already uses (useHomeSongPlayback, shared by the card and row components so the claim logic isn\'t duplicated between them). Tapping an album the caller owns navigates to its real detail page; someone else\'s album (which has no detail page to navigate to - /library/album is caller-scoped) expands its tracks inline instead.',
'New default landing page (2026-10-06), replacing Library as where you land post-login and at the catch-all route - Library remains a full nav destination, just no longer first. Globe nav icon (Globe2 was already taken by Library\'s "Shared" scope toggle, so a distinct icon avoids visual overlap between the two concepts). Three sections backed by GET /home/feed, each with an icon + one-line caption so they read as distinct content types at a glance: "New Songs" (a row list with album-art thumbnails - not a card grid, so it visually reads as "songs" rather than looking identical to the albums grid below it), "New Albums" (a cover-art grid - deliberately a different shape from the songs list), "Suggestions" (row list again). A song the caller already owns plays/favorites/playlists directly via its real library id; everyone else\'s goes through the same claim-then-act flow Library\'s shared search already uses (useHomeSongPlayback, shared by every row/card so the claim logic isn\'t duplicated). Tapping an album the caller owns navigates to its real detail page; someone else\'s album (which has no detail page to navigate to - /library/album is caller-scoped) expands its tracks inline instead. No uploader identity shown anywhere on the page (2026-10-07) - matches the backend feed no longer attaching one. Every song row (New Songs, Suggestions, and an expanded album\'s tracks) also got the same favorite heart Library already has, claiming first if the caller doesn\'t yet own the song.',
],
},
{
......
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