Commit 03069f85 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add PWA installability, system back button, swipe-to-queue/delete

Makes Stax installable via Add to Home Screen (manifest + service
worker, cobalt-themed icons incl. maskable variants), makes the
Android/browser back button close overlays one level at a time instead
of navigating away (useBackButtonClose, stack-based to handle nested
overlays correctly), and adds swipe gestures on Library rows: right to
queue (PlayerContext.addToQueue, appends without touching playback),
left to delete (confirm + calls the existing but previously
unwired DELETE /library/{file_id} endpoint).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent c0c5d56c
Pipeline #1146 passed with stage
in 7 minutes and 53 seconds
......@@ -3,11 +3,14 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#131313" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="Stax" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="" />
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet" />
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -35,6 +35,7 @@
"tailwindcss": "^4.3.3",
"typescript": "~6.0.2",
"vite": "^8.2.0",
"vite-plugin-pwa": "^1.3.0",
"vitest": "^4.1.10"
}
}
......@@ -35,6 +35,13 @@ export function searchLibrary(query: string) {
})
}
/** Deletes the song from disk and from every playlist it's part of, not just this list - the
* backend cascades PlaylistTrack rows itself, so callers don't need to reconcile playlists
* separately after this resolves. */
export function deleteLibrarySong(fileId: number) {
return apiFetch<{ status: string }>(`/library/${fileId}`, { method: 'DELETE' })
}
/** synced_lyrics is [seconds, text][] - real LRC line timing when a synced source was found
* (see the backend's fetch_lyrics), used to drive the highlighted line-by-line lyrics view.
* Null when only plain-text lyrics (or nothing) exists - callers fall back to `lyrics`. */
......
......@@ -4,6 +4,7 @@ import { addToPlaylist, createPlaylist, getPlaylists, type LibrarySong, type Pla
import { ApiError } from '../api/client'
import { Button } from './ui/Button'
import { Input } from './ui/Input'
import { useBackButtonClose } from '../hooks/useBackButtonClose'
interface AddToPlaylistModalProps {
song: LibrarySong
......@@ -40,6 +41,11 @@ export function AddToPlaylistModal({ song, onClose }: AddToPlaylistModalProps) {
return () => document.removeEventListener('keydown', onKeyDown)
}, [onClose])
// Always true, not conditional on some local open state - this component only exists in the
// tree while the modal should be showing (the caller mounts/unmounts it), so "open" for the
// back button's purposes is simply "mounted".
useBackButtonClose(true, onClose)
async function handleAdd(playlist: Playlist) {
setBusyId(playlist.id)
setError(null)
......
......@@ -20,6 +20,7 @@ import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { getLyrics } from '../api/library'
import { EmptyState } from './ui/EmptyState'
import { useMountTransition } from '../hooks/useMountTransition'
import { useBackButtonClose } from '../hooks/useBackButtonClose'
const ANIMATION_MS = 300
......@@ -141,6 +142,13 @@ export function FullPlayer() {
if (showLyrics) activeLineRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [activeLineIndex, showLyrics])
// Two nested back-button levels, matching the two real navigation states here (the player
// itself, and the Queue screen pushed on top of it). Lyrics deliberately doesn't get one - as
// the comment on this component explains, it's an in-place crossfade, not a navigation, and
// Escape already backs out of it above.
useBackButtonClose(visible, collapse)
useBackButtonClose(queueOpen, closeQueue)
if (!mounted || !currentSong) return null
function openQueue() {
......
......@@ -24,6 +24,7 @@ import { Button } from './ui/Button'
import { NowPlayingBar } from './NowPlayingBar'
import { FullPlayer } from './FullPlayer'
import { PlaybackErrorToast } from './PlaybackErrorToast'
import { useBackButtonClose } from '../hooks/useBackButtonClose'
// Rooms/Channels/Posts share one "Social" destination and Nearby/Drops share one
// "Soundmarks" destination (both merged 2026-08-23) - each hub page owns its own in-page
......@@ -51,6 +52,7 @@ export function Layout({ title, children }: { title: string; children: ReactNode
const { currentSong } = usePlayer()
const location = useLocation()
const [moreOpen, setMoreOpen] = useState(false)
useBackButtonClose(moreOpen, () => setMoreOpen(false))
async function handleLogout() {
// No reload needed: once isAuthenticated flips false, the ProtectedRoute/RequireRole
......
......@@ -3,6 +3,7 @@ import { Check, Music2, X } from 'lucide-react'
import { getLibrary, type LibrarySong } from '../api/library'
import { Button } from './ui/Button'
import { Input } from './ui/Input'
import { useBackButtonClose } from '../hooks/useBackButtonClose'
export const MAX_REMIX_SONGS = 5
......@@ -38,6 +39,8 @@ export function RemixSongPicker({ selected, onChange, onClose }: RemixSongPicker
return () => document.removeEventListener('keydown', onKeyDown)
}, [onClose])
useBackButtonClose(true, onClose)
const q = query.trim().toLowerCase()
const filtered = q ? library.filter((s) => s.title.toLowerCase().includes(q) || s.artist.toLowerCase().includes(q)) : library
......
......@@ -3,6 +3,7 @@ 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'
import { useBackButtonClose } from '../hooks/useBackButtonClose'
type Tab = 'mine' | 'public'
type PickableSong = LibrarySong | PublicLibrarySong
......@@ -52,6 +53,8 @@ export function SongPicker({ onSelect, onClose }: SongPickerProps) {
return () => document.removeEventListener('keydown', onKeyDown)
}, [onClose])
useBackButtonClose(true, onClose)
const list = tab === 'mine' ? myLibrary : publicResults
return (
......
......@@ -7,18 +7,21 @@ import * as streamApi from '../api/stream'
const SONG_A: PlayableSong = { id: 1, title: 'Song A', artist: 'Artist A' }
const SONG_B: PlayableSong = { id: 2, title: 'Song B', artist: 'Artist B' }
const SONG_C: PlayableSong = { id: 3, title: 'Song C', artist: 'Artist C' }
const SONG_D: PlayableSong = { id: 4, title: 'Song D', artist: 'Artist D' }
const QUEUE = [SONG_A, SONG_B, SONG_C]
function Probe() {
const {
currentSong,
queue,
isPlaying,
hasNext,
hasPrevious,
isShuffled,
repeatMode,
playbackError,
toggle,
addToQueue,
next,
previous,
toggleShuffle,
......@@ -28,6 +31,7 @@ function Probe() {
return (
<div>
<span data-testid="current">{currentSong?.title ?? 'none'}</span>
<span data-testid="is-playing">{String(isPlaying)}</span>
<span data-testid="queue-order">{queue.map((s) => s.title).join(',')}</span>
<span data-testid="has-next">{String(hasNext)}</span>
<span data-testid="has-previous">{String(hasPrevious)}</span>
......@@ -36,6 +40,8 @@ function Probe() {
<span data-testid="playback-error">{playbackError ?? 'none'}</span>
<button onClick={() => toggle(SONG_A, QUEUE)}>Play A</button>
<button onClick={() => toggle(SONG_C, QUEUE)}>Play C</button>
<button onClick={() => addToQueue(SONG_D)}>Queue D</button>
<button onClick={() => addToQueue(SONG_A)}>Queue A</button>
<button onClick={next}>Next</button>
<button onClick={previous}>Previous</button>
<button onClick={toggleShuffle}>Toggle Shuffle</button>
......@@ -94,6 +100,50 @@ describe('PlayerContext queue navigation', () => {
})
})
describe('PlayerContext addToQueue', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('appends to the queue without starting or otherwise touching playback', async () => {
renderProbe()
await userEvent.click(screen.getByText('Queue D'))
expect(screen.getByTestId('queue-order')).toHaveTextContent('Song D')
expect(screen.getByTestId('current')).toHaveTextContent('none')
expect(screen.getByTestId('is-playing')).toHaveTextContent('false')
})
it('appends after the current song without interrupting playback', async () => {
vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderProbe()
await userEvent.click(screen.getByText('Play A'))
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song A'))
await waitFor(() => expect(screen.getByTestId('is-playing')).toHaveTextContent('true'))
await userEvent.click(screen.getByText('Queue D'))
expect(screen.getByTestId('queue-order')).toHaveTextContent('Song A,Song B,Song C,Song D')
// Still the same track, still playing - adding to the queue is not a playback action.
expect(screen.getByTestId('current')).toHaveTextContent('Song A')
expect(screen.getByTestId('is-playing')).toHaveTextContent('true')
})
it('is a no-op when the song is already in the queue', async () => {
vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderProbe()
await userEvent.click(screen.getByText('Play A'))
await waitFor(() => expect(screen.getByTestId('current')).toHaveTextContent('Song A'))
await userEvent.click(screen.getByText('Queue A')) // Song A is already in QUEUE
expect(screen.getByTestId('queue-order')).toHaveTextContent('Song A,Song B,Song C')
})
})
describe('PlayerContext shuffle', () => {
afterEach(() => {
vi.restoreAllMocks()
......
......@@ -47,6 +47,10 @@ interface PlayerContextValue {
* from (e.g. the whole library) so skipping stays within that context. Defaults to a
* single-song queue when omitted. */
toggle: (song: PlayableSong, queue?: PlayableSong[]) => void
/** Appends a song to the end of the queue without touching playback - unlike `toggle`, this
* never starts, stops, or replaces whatever's currently playing (or isn't). A no-op if the
* song is already queued, rather than moving it to the end. */
addToQueue: (song: PlayableSong) => void
pause: () => void
next: () => void
/** Restarts the current track if more than a few seconds in (Spotify convention),
......@@ -247,6 +251,16 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
[currentSong, isPlaying, pause, playSong],
)
// originalQueueRef is updated separately from (not derived from) the live `queue` update
// below - when shuffled, `queue` is in shuffled order, but originalQueueRef must stay the
// real unshuffled order so turning shuffle back off doesn't lose the append or corrupt it.
const addToQueue = useCallback((song: PlayableSong) => {
setQueue((prev) => (prev.some((s) => s.id === song.id) ? prev : [...prev, song]))
if (!originalQueueRef.current.some((s) => s.id === song.id)) {
originalQueueRef.current = [...originalQueueRef.current, song]
}
}, [])
return (
<PlayerContext.Provider
value={{
......@@ -263,6 +277,7 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
repeatMode,
playbackError,
toggle,
addToQueue,
pause,
next,
previous,
......
import { act, renderHook } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useBackButtonClose } from './useBackButtonClose'
/** Simulates a real back-button press - dispatching this is what jsdom's own history.back()
* would eventually cause in a real browser, but doing it directly keeps these tests
* deterministic instead of depending on jsdom's own (slower, less predictable) navigation
* timing. */
function pressBack() {
window.dispatchEvent(new PopStateEvent('popstate'))
}
describe('useBackButtonClose', () => {
afterEach(() => {
vi.restoreAllMocks()
// No manual history reset here - @testing-library/react auto-unmounts every renderHook
// after each test, which runs the hook's own effect cleanup (consuming any entry it still
// owns). Every test below measures history.length as a delta from a lengthBefore snapshot
// taken in that same test, not an absolute value, so leftover growth across tests is
// harmless. (A prior version of this cleanup tried `while (window.history.state)
// window.history.back()` - jsdom's history.back() queues navigation as an async task and
// never updates `state` synchronously, so that loop spun forever queuing tasks and OOM'd
// the test worker.)
})
it('pushes a history entry while open, and calls onClose on a back press', () => {
const onClose = vi.fn()
const lengthBefore = window.history.length
renderHook(() => useBackButtonClose(true, onClose))
expect(window.history.length).toBe(lengthBefore + 1)
expect(onClose).not.toHaveBeenCalled()
act(() => pressBack())
expect(onClose).toHaveBeenCalledTimes(1)
})
it('does not push anything while closed', () => {
const onClose = vi.fn()
const lengthBefore = window.history.length
renderHook(() => useBackButtonClose(false, onClose))
expect(window.history.length).toBe(lengthBefore)
})
it('consumes its own history entry when closed some other way (not the back button)', async () => {
const onClose = vi.fn()
const backSpy = vi.spyOn(window.history, 'back')
const { rerender } = renderHook(({ open }) => useBackButtonClose(open, onClose), {
initialProps: { open: true },
})
rerender({ open: false })
expect(backSpy).toHaveBeenCalledTimes(1)
// The consumed entry doesn't re-trigger onClose - closing this way already handled it.
expect(onClose).not.toHaveBeenCalled()
// jsdom's history.back() doesn't fire popstate synchronously - it queues it through two
// *chained* setTimeout(0) tasks internally (traverseByDelta schedules a task that itself
// schedules the one that actually fires the event), so waiting a single tick is a race
// that happens to win when this file runs alone but loses under load in the full suite.
// Waiting on the real event directly (rather than counting ticks) is immune to however
// many internal hops jsdom uses. This flush matters because the pending real popstate,
// left unconsumed, lands during a *later* test and silently swallows that test's own
// (synthetic, directly-dispatched) popstate instead.
await act(
() =>
new Promise<void>((resolve) => {
window.addEventListener('popstate', () => resolve(), { once: true })
}),
)
})
it('a single back press closes only the top-most of two nested overlays', () => {
const closeOuter = vi.fn()
const closeInner = vi.fn()
renderHook(() => useBackButtonClose(true, closeOuter))
renderHook(() => useBackButtonClose(true, closeInner))
act(() => pressBack())
expect(closeInner).toHaveBeenCalledTimes(1)
expect(closeOuter).not.toHaveBeenCalled()
act(() => pressBack())
expect(closeOuter).toHaveBeenCalledTimes(1)
})
it('always calls the latest onClose without re-pushing on every re-render', () => {
const firstClose = vi.fn()
const secondClose = vi.fn()
const { rerender } = renderHook(({ onClose }) => useBackButtonClose(true, onClose), {
initialProps: { onClose: firstClose },
})
const lengthAfterOpen = window.history.length
// A caller passing an inline (non-memoized) callback re-renders with a new function
// identity constantly - that alone must not push a second history entry.
rerender({ onClose: secondClose })
expect(window.history.length).toBe(lengthAfterOpen)
act(() => pressBack())
expect(secondClose).toHaveBeenCalledTimes(1)
expect(firstClose).not.toHaveBeenCalled()
})
})
import { useEffect, useRef } from 'react'
// A shared stack, not one push/listener pair per hook instance - popstate is a single global
// event with no way to tell which pushState call it corresponds to, so if two overlays
// nested on top of each other (e.g. FullPlayer's Queue screen on top of FullPlayer itself)
// each ran their own independent listener, one back press would incorrectly close *both* at
// once instead of backing out one level at a time. Only the top of the stack ever responds.
const stack: (() => void)[] = []
let listenerAttached = false
// Incremented right before this module calls history.back() itself (to consume a leftover
// entry when an overlay closes some other way - an explicit X, Escape, picking an item), so
// the resulting popstate is recognized as self-inflicted and skipped rather than incorrectly
// popping and closing whatever's now on top of the stack.
let suppressNextPopstate = 0
function ensureListener() {
if (listenerAttached) return
listenerAttached = true
window.addEventListener('popstate', () => {
if (suppressNextPopstate > 0) {
suppressNextPopstate--
return
}
stack.pop()?.()
})
}
/** Makes the browser/Android system back button close this overlay instead of leaving the
* page underneath it - pushes one history entry while `isOpen`, and treats popping it as
* "the user backed out of this", calling onClose. If the overlay instead closes some other
* way while still open, the leftover history entry is consumed on cleanup so the *next* real
* back press does what's expected rather than silently eating a dead entry. */
export function useBackButtonClose(isOpen: boolean, onClose: () => void) {
// Ref, not a dependency - an inline onClose the caller doesn't memoize would otherwise
// re-run this effect (and push a fresh history entry) on every unrelated re-render while
// the overlay stays open.
const onCloseRef = useRef(onClose)
onCloseRef.current = onClose
const entryRef = useRef<(() => void) | null>(null)
useEffect(() => {
if (!isOpen) return
ensureListener()
window.history.pushState({}, '')
const callback = () => onCloseRef.current()
stack.push(callback)
entryRef.current = callback
return () => {
if (!entryRef.current) return
const idx = stack.lastIndexOf(entryRef.current)
entryRef.current = null
if (idx !== -1) {
// Still on the stack, so this close wasn't the back button - consume the entry now.
stack.splice(idx, 1)
suppressNextPopstate++
window.history.back()
}
// else: already popped by the listener itself (a real back press caused this close) -
// the history entry's already gone, nothing left to clean up.
}
}, [isOpen])
}
import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { useSwipeAction } from './useSwipeAction'
function SwipeRow({ onSwipeLeft, onSwipeRight }: { onSwipeLeft?: () => void; onSwipeRight?: () => void }) {
const { deltaX, swiping, handlers } = useSwipeAction({ onSwipeLeft, onSwipeRight })
return (
<div data-testid="row" data-delta={deltaX} data-swiping={swiping} {...handlers}>
row
</div>
)
}
// pointerId defaults to 0 for all these - a single simulated pointer per test is enough to
// exercise the gesture math, and the id-matching guard itself is checked separately below.
function drag(el: HTMLElement, points: number[]) {
fireEvent.pointerDown(el, { clientX: points[0], pointerId: 1 })
for (const x of points.slice(1)) {
fireEvent.pointerMove(el, { clientX: x, pointerId: 1 })
}
}
describe('useSwipeAction', () => {
it('reports deltaX and swiping while dragging right', () => {
render(<SwipeRow onSwipeRight={vi.fn()} />)
const row = screen.getByTestId('row')
drag(row, [0, 40])
expect(row.dataset.delta).toBe('40')
expect(row.dataset.swiping).toBe('true')
})
it('fires onSwipeRight and resets when released past the threshold', () => {
const onSwipeRight = vi.fn()
render(<SwipeRow onSwipeRight={onSwipeRight} />)
const row = screen.getByTestId('row')
drag(row, [0, 100])
fireEvent.pointerUp(row, { clientX: 100, pointerId: 1 })
expect(onSwipeRight).toHaveBeenCalledTimes(1)
expect(row.dataset.delta).toBe('0')
expect(row.dataset.swiping).toBe('false')
})
it('fires onSwipeLeft when dragged left past the threshold', () => {
const onSwipeLeft = vi.fn()
render(<SwipeRow onSwipeLeft={onSwipeLeft} />)
const row = screen.getByTestId('row')
drag(row, [0, -100])
fireEvent.pointerUp(row, { clientX: -100, pointerId: 1 })
expect(onSwipeLeft).toHaveBeenCalledTimes(1)
})
it('does not fire when released short of the threshold', () => {
const onSwipeRight = vi.fn()
render(<SwipeRow onSwipeRight={onSwipeRight} />)
const row = screen.getByTestId('row')
drag(row, [0, 30])
fireEvent.pointerUp(row, { clientX: 30, pointerId: 1 })
expect(onSwipeRight).not.toHaveBeenCalled()
expect(row.dataset.delta).toBe('0')
})
it('clamps to zero in a direction with no handler configured', () => {
const onSwipeRight = vi.fn()
// No onSwipeLeft passed - a leftward drag should never move the row at all.
render(<SwipeRow onSwipeRight={onSwipeRight} />)
const row = screen.getByTestId('row')
drag(row, [0, -100])
expect(row.dataset.delta).toBe('0')
fireEvent.pointerUp(row, { clientX: -100, pointerId: 1 })
expect(onSwipeRight).not.toHaveBeenCalled()
})
it('cancelling the gesture resets without firing either handler', () => {
const onSwipeRight = vi.fn()
render(<SwipeRow onSwipeRight={onSwipeRight} />)
const row = screen.getByTestId('row')
drag(row, [0, 100])
fireEvent.pointerCancel(row, { clientX: 100, pointerId: 1 })
expect(onSwipeRight).not.toHaveBeenCalled()
expect(row.dataset.delta).toBe('0')
expect(row.dataset.swiping).toBe('false')
})
it('ignores move/up events from an unrelated pointer id', () => {
const onSwipeRight = vi.fn()
render(<SwipeRow onSwipeRight={onSwipeRight} />)
const row = screen.getByTestId('row')
fireEvent.pointerDown(row, { clientX: 0, pointerId: 1 })
// A second, unrelated pointer moving shouldn't affect the drag already in progress.
fireEvent.pointerMove(row, { clientX: 100, pointerId: 2 })
expect(row.dataset.delta).toBe('0')
})
})
import { useRef, useState } from 'react'
interface UseSwipeActionOptions {
/** Called when the row is swiped left past `threshold` and released. */
onSwipeLeft?: () => void
/** Called when the row is swiped right past `threshold` and released. */
onSwipeRight?: () => void
/** Pixels the row must be dragged before releasing counts as a swipe rather than an
* abandoned drag or a tap that happened to move a little. */
threshold?: number
}
interface UseSwipeActionResult {
/** Current horizontal drag offset in pixels - feed straight into a translateX transform. */
deltaX: number
/** True for the duration of an active pointer drag - use to disable the row's own transition
* so it tracks the finger 1:1 instead of animating behind it. */
swiping: boolean
handlers: {
onPointerDown: (e: React.PointerEvent) => void
onPointerMove: (e: React.PointerEvent) => void
onPointerUp: (e: React.PointerEvent) => void
onPointerCancel: (e: React.PointerEvent) => void
}
}
/** Pointer-events-based horizontal swipe gesture, no gesture library - built for a list row
* that reveals one action per direction (e.g. swipe right to queue, swipe left to delete).
* Doesn't touch the DOM itself: callers apply `deltaX` as a transform and `swiping` to gate
* their own transition, and should set `touch-action: pan-y` on the swiped element so the
* browser still handles vertical list scrolling natively instead of every scroll attempt
* getting hijacked as a failed horizontal swipe. */
export function useSwipeAction({ onSwipeLeft, onSwipeRight, threshold = 72 }: UseSwipeActionOptions): UseSwipeActionResult {
const [deltaX, setDeltaX] = useState(0)
const [swiping, setSwiping] = useState(false)
const startXRef = useRef(0)
// Not state - this only exists to reject stray events from a second simultaneous pointer
// (e.g. a two-finger touch) while the first one is still dragging.
const pointerIdRef = useRef<number | null>(null)
function onPointerDown(e: React.PointerEvent) {
if (e.pointerType === 'mouse' && e.button !== 0) return
startXRef.current = e.clientX
pointerIdRef.current = e.pointerId
// Keeps events targeting this element even once the finger moves past its edges -
// otherwise a fast swipe would stop reporting moves the instant it left the row's bounds.
e.currentTarget.setPointerCapture(e.pointerId)
setSwiping(true)
}
function onPointerMove(e: React.PointerEvent) {
if (pointerIdRef.current !== e.pointerId) return
let dx = e.clientX - startXRef.current
// Clamped to zero (not just left unclamped) in whichever direction has no handler, so a
// row with only one action configured doesn't visually drag in the direction that does
// nothing on release.
if (dx > 0 && !onSwipeRight) dx = 0
if (dx < 0 && !onSwipeLeft) dx = 0
setDeltaX(dx)
}
function onPointerUp(e: React.PointerEvent) {
if (pointerIdRef.current !== e.pointerId) return
pointerIdRef.current = null
setSwiping(false)
if (deltaX >= threshold) onSwipeRight?.()
else if (deltaX <= -threshold) onSwipeLeft?.()
setDeltaX(0)
}
// A cancelled gesture (browser took over for native scrolling, capture was lost, ...) is not
// a completed one - reset without checking the threshold or firing either handler, unlike
// onPointerUp above.
function onPointerCancel(e: React.PointerEvent) {
if (pointerIdRef.current !== e.pointerId) return
pointerIdRef.current = null
setSwiping(false)
setDeltaX(0)
}
return {
deltaX,
swiping,
handlers: { onPointerDown, onPointerMove, onPointerUp, onPointerCancel },
}
}
import { render, screen, waitFor, within } from '@testing-library/react'
import { fireEvent, 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'
......@@ -22,6 +22,17 @@ const SONG = {
added_at: '2026-01-01T00:00:00Z',
}
const SONG_2 = { ...SONG, id: 2, title: 'Rio', album: 'Rio' }
// Fires the full pointer drag sequence useSwipeAction listens for, targeting a descendant
// (e.g. the row's Play button) since the handlers live on an ancestor and pointer events
// bubble the same way in jsdom as in a real browser.
function swipe(target: HTMLElement, fromX: number, toX: number) {
fireEvent.pointerDown(target, { clientX: fromX, pointerId: 1 })
fireEvent.pointerMove(target, { clientX: toX, pointerId: 1 })
fireEvent.pointerUp(target, { clientX: toX, pointerId: 1 })
}
function renderLibrary() {
return render(
<MemoryRouter>
......@@ -186,4 +197,93 @@ describe('Library', () => {
expect(await screen.findByText('Invisible')).toBeInTheDocument()
})
it('swiping a row right adds it to the queue without starting playback', async () => {
// Only "Invisible" is in the loaded library, so playing it gives a single-song queue -
// "Rio" (found via search below) is genuinely not in that queue yet, unlike if both songs
// had loaded together (SongRow's own `queue` prop is the whole list it's rendered from,
// so swiping a row from the *same* list it's already queued from would be a no-op).
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
vi.spyOn(libraryApi, 'searchLibrary').mockResolvedValue({ status: 'success', songs: [SONG_2], albums: [] })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderLibrary()
const rowA = (await screen.findByText('Invisible')).closest('li')!
await userEvent.click(within(rowA).getByRole('button', { name: 'Play' }))
await waitFor(() => expect(fetchStreamUrl).toHaveBeenCalledWith(1))
await userEvent.type(screen.getByPlaceholderText('Search songs and albums'), 'rio')
const rowB = (await screen.findByText('Rio')).closest('li')!
swipe(within(rowB).getByRole('button', { name: 'Play' }), 0, 100)
// Swiping must not itself trigger playback of the swiped song.
expect(fetchStreamUrl).not.toHaveBeenCalledWith(2)
await userEvent.click(screen.getByRole('button', { name: /Open player/ }))
// FullPlayer mounts a frame after isExpanded flips (see useMountTransition) - findBy waits
// for that instead of assuming it's already in the DOM right after the click.
const dialog = await screen.findByRole('dialog', { name: /Now playing/ })
await userEvent.click(within(dialog).getByRole('button', { name: 'Open queue' }))
// Scoped to the dialog - Library's own "Add Rio to a playlist" button also matches /Rio/.
expect(await within(dialog).findByRole('button', { name: /Rio/ })).toBeInTheDocument()
})
it('swiping a row left prompts to confirm, then deletes it and removes it from the list', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG, SONG_2] })
const deleteLibrarySong = vi.spyOn(libraryApi, 'deleteLibrarySong').mockResolvedValue({ status: 'success' })
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true)
renderLibrary()
const row = (await screen.findByText('Invisible')).closest('li')!
swipe(within(row).getByRole('button', { name: 'Play' }), 0, -100)
expect(confirmSpy).toHaveBeenCalledWith(expect.stringContaining('Invisible'))
await waitFor(() => expect(deleteLibrarySong).toHaveBeenCalledWith(1))
await waitFor(() => expect(screen.queryByText('Invisible')).not.toBeInTheDocument())
// The other song is untouched.
expect(screen.getByText('Rio')).toBeInTheDocument()
})
it('does not delete when the confirm dialog is dismissed', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
const deleteLibrarySong = vi.spyOn(libraryApi, 'deleteLibrarySong')
vi.spyOn(window, 'confirm').mockReturnValue(false)
renderLibrary()
const row = (await screen.findByText('Invisible')).closest('li')!
swipe(within(row).getByRole('button', { name: 'Play' }), 0, -100)
expect(deleteLibrarySong).not.toHaveBeenCalled()
expect(screen.getByText('Invisible')).toBeInTheDocument()
})
it('shows an error and keeps the song if deletion fails', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
vi.spyOn(libraryApi, 'deleteLibrarySong').mockRejectedValue(new ApiError(500, 'Delete failed', null))
vi.spyOn(window, 'confirm').mockReturnValue(true)
renderLibrary()
const row = (await screen.findByText('Invisible')).closest('li')!
swipe(within(row).getByRole('button', { name: 'Play' }), 0, -100)
expect(await screen.findByText('Delete failed')).toBeInTheDocument()
expect(screen.getByText('Invisible')).toBeInTheDocument()
})
it('does not swipe past a small drag that falls short of the threshold', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
const deleteLibrarySong = vi.spyOn(libraryApi, 'deleteLibrarySong')
const confirmSpy = vi.spyOn(window, 'confirm')
renderLibrary()
const row = (await screen.findByText('Invisible')).closest('li')!
swipe(within(row).getByRole('button', { name: 'Play' }), 0, -20)
expect(confirmSpy).not.toHaveBeenCalled()
expect(deleteLibrarySong).not.toHaveBeenCalled()
})
})
import { useEffect, useState } from 'react'
import { ListPlus, Music2, Pause, Play, Search } from 'lucide-react'
import { getLibrary, searchLibrary, type AlbumMatch, type LibrarySong } from '../api/library'
import { ListMusic, ListPlus, Music2, Pause, Play, Search, Trash2 } from 'lucide-react'
import { deleteLibrarySong, getLibrary, searchLibrary, type AlbumMatch, type LibrarySong } from '../api/library'
import { ApiError } from '../api/client'
import { Layout } from '../components/Layout'
import { AddToPlaylistModal } from '../components/AddToPlaylistModal'
......@@ -8,6 +8,7 @@ import { Input } from '../components/ui/Input'
import { SkeletonRow } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'
import { usePlayer, type PlayableSong } from '../context/PlayerContext'
import { useSwipeAction } from '../hooks/useSwipeAction'
function toPlayable(song: LibrarySong): PlayableSong {
return {
......@@ -20,22 +21,60 @@ function toPlayable(song: LibrarySong): PlayableSong {
}
}
const SWIPE_VISUAL_MAX = 120
/** One playable row - shared by the full library list, search's "Songs" section, and an
* expanded album's tracks, so play/pause/add-to-playlist behavior stays identical everywhere
* a song can appear instead of being reimplemented per context. */
* a song can appear instead of being reimplemented per context. Also swipeable: right to queue
* (non-destructive, fires immediately), left to delete (destructive, `onDelete` owns the
* confirm step since it also owns the list state that needs updating after). */
function SongRow({
song,
queue,
onAddToPlaylist,
onDelete,
}: {
song: LibrarySong
queue: LibrarySong[]
onAddToPlaylist: (song: LibrarySong) => void
onDelete: (song: LibrarySong) => void
}) {
const { currentSong, isPlaying, isLoading: streamLoading, toggle } = usePlayer()
const { currentSong, isPlaying, isLoading: streamLoading, toggle, addToQueue } = usePlayer()
const isCurrent = currentSong?.id === song.id
const { deltaX, swiping, handlers } = useSwipeAction({
onSwipeRight: () => addToQueue(toPlayable(song)),
onSwipeLeft: () => onDelete(song),
})
const visualDelta = Math.max(-SWIPE_VISUAL_MAX, Math.min(SWIPE_VISUAL_MAX, deltaX))
return (
<li className="group -mx-1 flex items-center gap-1 rounded-xl border border-transparent pr-2 transition-colors hover:border-outline-variant hover:bg-surface-container">
<li className="group relative -mx-1 overflow-hidden rounded-xl">
{/* Colored panels revealed from each edge as the row is dragged - only one is ever
visible since useSwipeAction clamps deltaX to zero in whichever direction has no
registered handler, and both directions are wired here. */}
<div className="absolute inset-0 flex items-stretch" aria-hidden="true">
<div
className="flex items-center gap-2 overflow-hidden bg-primary/15 pl-4 text-primary"
style={{ width: Math.max(0, visualDelta) }}
>
<ListMusic size={18} strokeWidth={2} className="shrink-0" />
</div>
<div className="flex-1" />
<div
className="flex items-center justify-end gap-2 overflow-hidden bg-error/15 pr-4 text-error"
style={{ width: Math.max(0, -visualDelta) }}
>
<Trash2 size={18} strokeWidth={2} className="shrink-0" />
</div>
</div>
<div
{...handlers}
style={{ transform: `translateX(${visualDelta}px)`, touchAction: 'pan-y' }}
className={`relative flex items-center gap-1 rounded-xl border border-transparent bg-background pr-2 ${
swiping ? '' : 'transition-transform duration-200 ease-out'
} ${deltaX === 0 ? 'hover:border-outline-variant hover:bg-surface-container' : ''}`}
>
{/* The whole row plays the song, not just the little icon on the right - the icon is
now a status indicator rendered inside this same button, not a separate control.
The "add to playlist" button is a sibling, not nested inside this one, so it can
......@@ -89,6 +128,7 @@ function SongRow({
>
<ListPlus size={18} strokeWidth={1.75} />
</button>
</div>
</li>
)
}
......@@ -102,6 +142,7 @@ export function Library() {
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [addingSong, setAddingSong] = useState<LibrarySong | null>(null)
const [deleteError, setDeleteError] = useState<string | null>(null)
const [query, setQuery] = useState('')
const [searchResults, setSearchResults] = useState<{ songs: LibrarySong[]; albums: AlbumMatch[] } | null>(null)
......@@ -130,6 +171,31 @@ export function Library() {
return () => clearTimeout(handle)
}, [query])
// Owns the confirm step (not SongRow) since it's also the one that has to reconcile the
// song's removal across every local list it can appear in - the full library, the current
// search's Songs section, and any album groupings within that search.
async function handleDelete(song: LibrarySong) {
if (!window.confirm(`Delete "${song.title}"? This can't be undone.`)) return
setDeleteError(null)
try {
await deleteLibrarySong(song.id)
setSongs((prev) => prev.filter((s) => s.id !== song.id))
setSearchResults((prev) =>
prev
? {
songs: prev.songs.filter((s) => s.id !== song.id),
albums: prev.albums
.map((album) => ({ ...album, songs: album.songs.filter((s) => s.id !== song.id) }))
.filter((album) => album.songs.length > 0)
.map((album) => ({ ...album, track_count: album.songs.length })),
}
: prev,
)
} catch (err) {
setDeleteError(err instanceof ApiError ? err.message : `Could not delete "${song.title}"`)
}
}
const isSearching = searchResults !== null
return (
......@@ -152,6 +218,7 @@ export function Library() {
</div>
)}
{error && <p className="text-sm text-error">{error}</p>}
{deleteError && <p className="text-sm text-error">{deleteError}</p>}
{!loading && !error && !isSearching && songs.length === 0 && (
<EmptyState icon={Music2} message="No songs yet - tag something from Telegram to see it here." />
)}
......@@ -198,7 +265,7 @@ export function Library() {
{expanded && (
<ul className="mb-2 space-y-1 pl-4">
{album.songs.map((s) => (
<SongRow key={s.id} song={s} queue={album.songs} onAddToPlaylist={setAddingSong} />
<SongRow key={s.id} song={s} queue={album.songs} onAddToPlaylist={setAddingSong} onDelete={handleDelete} />
))}
</ul>
)}
......@@ -213,7 +280,7 @@ export function Library() {
<h2 className="mb-2 text-xs font-semibold uppercase tracking-[0.1em] text-primary">Songs</h2>
<ul className="space-y-1">
{searchResults.songs.map((song) => (
<SongRow key={song.id} song={song} queue={searchResults.songs} onAddToPlaylist={setAddingSong} />
<SongRow key={song.id} song={song} queue={searchResults.songs} onAddToPlaylist={setAddingSong} onDelete={handleDelete} />
))}
</ul>
</div>
......@@ -222,7 +289,7 @@ export function Library() {
) : (
<ul className="space-y-1">
{songs.map((song) => (
<SongRow key={song.id} song={song} queue={songs} onAddToPlaylist={setAddingSong} />
<SongRow key={song.id} song={song} queue={songs} onAddToPlaylist={setAddingSong} onDelete={handleDelete} />
))}
</ul>
)}
......
......@@ -39,7 +39,7 @@ describe('Roadmap', () => {
// To-do lists - a "ready" item that moved out of backend once this pass's work landed,
// and its frontend counterpart that's now unblocked by the same work.
expect(screen.getByText('Channels: vibe sets, stories, showcase screens')).toBeInTheDocument()
expect(screen.getByText('Delete buttons for library songs, playlists, and playlist tracks')).toBeInTheDocument()
expect(screen.getByText('Delete buttons + confirm dialogs for playlists and playlist tracks')).toBeInTheDocument()
// A "needs design" idea split into its own backend half and frontend half.
expect(screen.getByText('Migrate off SQLite to PostgreSQL + PostGIS')).toBeInTheDocument()
expect(screen.getByText('Wire a "save to library" action for liked Discovery matches')).toBeInTheDocument()
......
......@@ -186,6 +186,7 @@ const FRONTEND_DONE: DoneGroup[] = [
'Universal search box: separate Songs and Albums result sections while searching (an album expands to show/play its tracks) - replaces the plain list rather than filtering it in place',
'Playlists page: list, create, view tracks, playback',
'Add-to-playlist modal from the Library page (add existing or create-and-add)',
'Delete-from-library (2026-08-31): swipe a Library row left past a threshold to reveal and trigger delete (right instead adds to queue) - confirms via the same window.confirm pattern already used for soundmark delete, then removes the file on disk and reconciles the song out of every local list it could be showing in (the full library, the current search\'s Songs section, and any album groupings within it)',
],
},
{
......@@ -204,18 +205,21 @@ const FRONTEND_DONE: DoneGroup[] = [
'24h history, swipe UI',
],
},
{
area: 'PWA & Navigation',
items: [
'Installable as a real app (2026-08-31): vite-plugin-pwa generates a manifest.webmanifest + service worker at build time, standalone display, cobalt-themed icons (incl. maskable variants for Android\'s adaptive-icon safe zone) - "Add to Home Screen" on iOS/Android now launches Stax in its own window, not a browser tab. Deliberately no runtimeCaching config: only the built app shell is precached, so authenticated/streamed/API requests always hit the network fresh rather than risking a stale or cross-account cache hit',
'System/Android back button closes overlays instead of leaving the page underneath them (2026-08-31): useBackButtonClose pushes one history entry per open overlay onto a shared stack (not one popstate listener per instance, since a single back press must close only the top-most of several nested overlays - e.g. FullPlayer\'s Queue screen on top of FullPlayer itself - not all of them at once) - wired into FullPlayer (+ its Queue screen as a second nested level), Layout\'s mobile More sheet, AddToPlaylistModal, SongPicker, and RemixSongPicker',
'Swipe gestures on Library rows (2026-08-31): useSwipeAction (pointer-events based, no gesture library) drives a swipe-right-to-queue / swipe-left-to-delete interaction, sharing the same PlayerContext.addToQueue used elsewhere - queueing appends without touching whatever is currently playing, unlike toggle() which replaces the whole queue and starts playback',
],
},
]
const FRONTEND_TODO: WorkItem[] = [
{
item: 'Delete buttons for library songs, playlists, and playlist tracks',
status: 'ready',
note: 'Backend now supports all three (shipped 2026-08-18) - no UI calls them yet.',
},
{
item: 'Confirm dialogs on destructive actions',
item: 'Delete buttons + confirm dialogs for playlists and playlist tracks',
status: 'ready',
note: 'Only one destructive action (deleting a soundmark) has a confirm dialog today - worth a real pass now that song/playlist/track deletes exist too.',
note: 'Library songs got both (2026-08-31, swipe-to-delete + window.confirm) - playlists and individual playlist tracks still have neither, despite the backend supporting all three deletes since 2026-08-18.',
},
{
item: 'Channels: vibe sets, stories, showcase screens',
......
......@@ -14,3 +14,9 @@ window.URL.revokeObjectURL = vi.fn()
// (not a no-op, genuinely undefined) - anything that auto-scrolls a new message/item into
// view (e.g. RoomView's chat) throws without this.
window.HTMLElement.prototype.scrollIntoView = vi.fn()
// jsdom has PointerEvent but never implemented the Pointer Capture APIs - useSwipeAction calls
// setPointerCapture on every drag start, which throws "not a function" without this.
window.Element.prototype.setPointerCapture = vi.fn()
window.Element.prototype.releasePointerCapture = vi.fn()
window.Element.prototype.hasPointerCapture = vi.fn(() => false)
......@@ -3,6 +3,7 @@ import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import basicSsl from '@vitejs/plugin-basic-ssl'
import { VitePWA } from 'vite-plugin-pwa'
// https://vite.dev/config/
export default defineConfig(({ mode }) => {
......@@ -27,7 +28,39 @@ export default defineConfig(({ mode }) => {
// dev can run over https:// directly on <ip>:5173 - no public CA will issue a real cert for
// a bare IP (only for a domain), so a self-signed one plus a one-time browser click-through
// is the tradeoff for skipping the domain+reverse-proxy setup.
plugins: [react(), tailwindcss(), basicSsl()],
plugins: [
react(),
tailwindcss(),
basicSsl(),
VitePWA({
// autoUpdate (not the prompt-based strategy) - a fast-moving app benefits more from
// always running the latest deploy than from asking the user to confirm an update.
registerType: 'autoUpdate',
manifest: {
name: 'Stax',
short_name: 'Stax',
description: 'Discover, tag, and remix music from your own uploads and Telegram chats.',
theme_color: '#131313',
background_color: '#131313',
display: 'standalone',
start_url: '/library',
icons: [
{ src: '/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
{ src: '/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },
{ src: '/icon-maskable-192.png', sizes: '192x192', type: 'image/png', purpose: 'maskable' },
{ src: '/icon-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
],
},
// Deliberately no runtimeCaching config here - the default workbox setup only
// precaches the built app shell (JS/CSS/HTML/icons), never touching API calls or
// authenticated media streams. Those carry a ?token= and per-user auth state that a
// cache could easily serve stale or to the wrong account; they're left to hit the
// network exactly as they do today, same as before this plugin existed.
workbox: {
globPatterns: ['**/*.{js,css,html,svg,png,ico}'],
},
}),
],
server: {
host: true,
port: 5173,
......
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