From cba250153d9418aab611886ce86fabb796aa14e3 Mon Sep 17 00:00:00 2001 From: ZortexSenpai Date: Tue, 10 Nov 2026 15:01:34 +0100 Subject: [PATCH] fix: fixed player queue lagging --- src/overlays/now-playing/QueuePanel.tsx | 187 ++++++++++++++++++--- src/overlays/now-playing/queueDrag.test.ts | 52 ++++++ src/overlays/now-playing/queueDrag.ts | 153 +++++++++++++++++ src/stores/playerStore.test.ts | 39 +++++ src/stores/playerStore.ts | 9 +- 5 files changed, 405 insertions(+), 35 deletions(-) create mode 100644 src/overlays/now-playing/queueDrag.test.ts create mode 100644 src/overlays/now-playing/queueDrag.ts diff --git a/src/overlays/now-playing/QueuePanel.tsx b/src/overlays/now-playing/QueuePanel.tsx index d3ea0bd..5a5f95f 100644 --- a/src/overlays/now-playing/QueuePanel.tsx +++ b/src/overlays/now-playing/QueuePanel.tsx @@ -1,6 +1,8 @@ -import { AnimatePresence, Reorder, motion } from "motion/react"; +import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { AnimatePresence, motion } from "motion/react"; import { ListPlus, ListX, Pause, Play as PlayIcon, X } from "lucide-react"; import { useQueryClient } from "@tanstack/react-query"; +import { defaultRangeExtractor, useVirtualizer, type Range } from "@tanstack/react-virtual"; import { Tabs } from "radix-ui"; import { formatDuration, formatRelativeDate } from "../../lib/format"; import { useT } from "../../lib/i18n"; @@ -14,6 +16,7 @@ import { useUiStore, type QueuePanelTab } from "../../stores/uiStore"; import { CoverImage } from "../../components/library/CoverImage"; import { TrackContextMenu } from "../../components/library/TrackContextMenu"; import { IconButton } from "../../components/ui/Button"; +import { displacement, ROW_HEIGHT, useQueueDrag } from "./queueDrag"; /** Same selection pill as the sidebar, so it reads as glass in liquid mode. */ const tabClass = (active: boolean) => @@ -22,6 +25,48 @@ const tabClass = (active: boolean) => }`; const emptyClass = "px-2 py-8 text-center text-xs text-faint"; +const headingClass = "px-2 pb-1 text-[11px] font-medium tracking-wide text-faint uppercase"; + +const rowSize = () => ROW_HEIGHT; + +/** + * Lays out only the rows in view of the tab's scroll container, plus a few + * either side: a Queue can hold thousands of Songs, and rendering them all + * made the panel take seconds to open. `keep` stays rendered wherever it is. + */ +function useRows( + scrollElement: HTMLElement | null, + count: number, + getItemKey: (index: number) => string, + keep?: number, +) { + const listRef = useRef(null); + // Where the list starts in the scroll container, below the headings and the + // Now playing row (the container is `relative`, so offsetTop is just that). + const [scrollMargin, setScrollMargin] = useState(0); + useLayoutEffect(() => { + setScrollMargin(listRef.current?.offsetTop ?? 0); + }); + const rangeExtractor = useCallback( + (range: Range) => { + const indexes = defaultRangeExtractor(range); + return keep === undefined || indexes.includes(keep) + ? indexes + : [...indexes, keep].sort((a, b) => a - b); + }, + [keep], + ); + const virtualizer = useVirtualizer({ + count, + getScrollElement: () => scrollElement, + estimateSize: rowSize, + overscan: 8, + scrollMargin, + getItemKey, + rangeExtractor, + }); + return { listRef, virtualizer, scrollMargin }; +} /** One Song in either tab: the Queue's items and the Play History's Plays. */ function Row({ @@ -122,15 +167,108 @@ function PlayRow({ play }: { play: Play }) { ); } -function PlayHistoryList() { +/** The Queue after the current item, in an order you can drag. */ +function NextUp({ scrollElement }: { scrollElement: HTMLElement | null }) { + const t = useT(); + const queue = usePlayerStore((s) => s.queue); + const queueIndex = usePlayerStore((s) => s.queueIndex); + const upcoming = useMemo(() => queue.slice(queueIndex + 1), [queue, queueIndex]); + + const onDrop = useCallback((queueId: string, to: number) => { + const { queue, queueIndex, moveInQueue } = usePlayerStore.getState(); + const from = queue.findIndex((item) => item.queueId === queueId); + // Started playing (or was removed) mid-drag: it's no longer up next. + if (from <= queueIndex) return; + moveInQueue(from, Math.min(queueIndex + 1 + to, queue.length - 1)); + }, []); + const { drag, onPointerDown } = useQueueDrag(scrollElement, upcoming.length, onDrop); + + const getItemKey = useCallback((index: number) => upcoming[index].queueId, [upcoming]); + const { listRef, virtualizer, scrollMargin } = useRows( + scrollElement, + upcoming.length, + getItemKey, + drag?.from, + ); + + if (upcoming.length === 0) return null; + return ( + <> +
{t("queue.nextUp")}
+
+ {virtualizer.getVirtualItems().map((row) => { + const item = upcoming[row.index]; + const dragging = drag?.queueId === item.queueId; + // The dragged row follows the pointer; the ones it passes step aside. + const dy = !drag + ? 0 + : dragging + ? drag.dy + : displacement(row.index, drag.from, drag.to) * ROW_HEIGHT; + return ( +
onPointerDown(e, row.index, item.queueId)} + // The dragged row is lifted onto a solid tile: hover won't light it + // up while it holds the pointer, and it passes over other rows. + // The rest slide only mid-drag: on the drop they move to their + // new slots and shed the shift in one frame, which mustn't animate. + className={`absolute inset-x-0 cursor-grab ${ + dragging + ? "z-10 rounded-md bg-surface-2 shadow-lg" + : drag + ? "transition-transform duration-150" + : "" + }`} + style={{ + top: row.start - scrollMargin, + height: ROW_HEIGHT, + transform: dy ? `translateY(${dy}px)` : undefined, + }} + > + +
+ ); + })} +
+ + ); +} + +function PlayHistoryList({ scrollElement }: { scrollElement: HTMLElement | null }) { const t = useT(); const { data: plays } = usePlayHistory(); + // A Song played twice is two Plays, so the Song id alone is no key; when it + // started tells them apart, and stays put as new Plays arrive on top. + const getItemKey = useCallback( + (index: number) => `${plays![index].playedAt}-${plays![index].song.id}`, + [plays], + ); + const { listRef, virtualizer, scrollMargin } = useRows( + scrollElement, + plays?.length ?? 0, + getItemKey, + ); // Still loading. One that can't be read arrives as empty (see readPlayHistory). if (!plays) return null; if (plays.length === 0) return

{t("queue.nothingPlayed")}

; - // A Song played twice is two Plays, so the Song id alone is no key; when it - // started tells them apart, and stays put as new Plays arrive on top. - return plays.map((play) => ); + return ( +
+ {virtualizer.getVirtualItems().map((row) => ( +
+ +
+ ))} +
+ ); } function ClearPlayHistoryButton() { @@ -169,10 +307,12 @@ export function QueuePanel() { const queue = usePlayerStore((s) => s.queue); const queueIndex = usePlayerStore((s) => s.queueIndex); const liquid = usePrefsStore((s) => s.prefs.layout) === "liquid"; - const { setUpcoming, clearQueue } = usePlayerStore.getState(); + const { clearQueue } = usePlayerStore.getState(); + // Each tab scrolls itself, and only the open one is mounted. + const [queueScroll, setQueueScroll] = useState(null); + const [playHistoryScroll, setPlayHistoryScroll] = useState(null); const current = queueIndex >= 0 ? queue[queueIndex] : null; - const upcoming = queue.slice(queueIndex + 1); // Liquid: a floating glass panel inset by the shell padding (top/right-3) // and clearing the player bar (12px padding + 84px bar + 12px gap = 108px). @@ -239,38 +379,31 @@ export function QueuePanel() { - + {queue.length === 0 ? (

{t("queue.empty")}

) : ( <> {current && ( <> -
- {t("queue.nowPlaying")} -
+
{t("queue.nowPlaying")}
)} - {upcoming.length > 0 && ( - <> -
- {t("queue.nextUp")} -
- - {upcoming.map((item) => ( - - - - ))} - - - )} + )}
- - + + diff --git a/src/overlays/now-playing/queueDrag.test.ts b/src/overlays/now-playing/queueDrag.test.ts new file mode 100644 index 0000000..ccac127 --- /dev/null +++ b/src/overlays/now-playing/queueDrag.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from "vitest"; +import { displacement, dropIndex, edgeScrollSpeed, ROW_HEIGHT } from "./queueDrag"; + +describe("dropIndex", () => { + it("stays in its slot until dragged past half a row", () => { + expect(dropIndex(3, ROW_HEIGHT / 2 - 1, 10)).toBe(3); + expect(dropIndex(3, -(ROW_HEIGHT / 2 - 1), 10)).toBe(3); + }); + + it("lands a whole number of rows away, either way", () => { + expect(dropIndex(3, 2 * ROW_HEIGHT, 10)).toBe(5); + expect(dropIndex(3, -2 * ROW_HEIGHT - 10, 10)).toBe(1); + }); + + it("can't land before the first row or after the last", () => { + expect(dropIndex(1, -5 * ROW_HEIGHT, 10)).toBe(0); + expect(dropIndex(8, 5 * ROW_HEIGHT, 10)).toBe(9); + }); +}); + +describe("displacement", () => { + it("moves the rows between up when dragging down", () => { + expect([0, 1, 2, 3, 4, 5].map((i) => displacement(i, 1, 4))).toEqual([0, 0, -1, -1, -1, 0]); + }); + + it("moves the rows between down when dragging up", () => { + expect([0, 1, 2, 3, 4, 5].map((i) => displacement(i, 4, 1))).toEqual([0, 1, 1, 1, 0, 0]); + }); + + it("moves nothing while the row hangs over its own slot", () => { + expect([0, 1, 2].map((i) => displacement(i, 1, 1))).toEqual([0, 0, 0]); + }); +}); + +describe("edgeScrollSpeed", () => { + it("doesn't scroll away from the edges", () => { + expect(edgeScrollSpeed(300, 100, 600)).toBe(0); + }); + + it("scrolls up near the top and down near the bottom", () => { + expect(edgeScrollSpeed(110, 100, 600)).toBeLessThan(0); + expect(edgeScrollSpeed(590, 100, 600)).toBeGreaterThan(0); + }); + + it("speeds up toward the edge, up to a limit past it", () => { + expect(Math.abs(edgeScrollSpeed(110, 100, 600))).toBeGreaterThan( + Math.abs(edgeScrollSpeed(140, 100, 600)), + ); + expect(edgeScrollSpeed(0, 100, 600)).toBe(-12); + expect(edgeScrollSpeed(900, 100, 600)).toBe(12); + }); +}); diff --git a/src/overlays/now-playing/queueDrag.ts b/src/overlays/now-playing/queueDrag.ts new file mode 100644 index 0000000..5f82304 --- /dev/null +++ b/src/overlays/now-playing/queueDrag.ts @@ -0,0 +1,153 @@ +// Drag-to-reorder for the queue panel's "Next up" list. The list is +// virtualized (a Queue can hold thousands of Songs and rendering every row made +// the panel take seconds to open), so a library that needs every row in the DOM +// to reorder won't do; with rows of one fixed height, where a row lands is +// plain arithmetic instead. + +import { + useCallback, + useEffect, + useRef, + useState, + type PointerEvent as ReactPointerEvent, +} from "react"; + +/** Every row in the queue panel is this tall: py-1.5 around a size-10 cover. */ +export const ROW_HEIGHT = 52; + +/** How far the pointer moves before a press on a row becomes a drag, so clicks still click. */ +const DRAG_THRESHOLD = 4; + +/** Where a row dragged `dy` px from its slot `from` lands among `count` rows. */ +export function dropIndex(from: number, dy: number, count: number): number { + return Math.max(0, Math.min(count - 1, from + Math.round(dy / ROW_HEIGHT))); +} + +/** + * How many rows the row at `index` steps aside while the row from `from` hangs + * over `to`: the ones in between shift one place to make room for it. + */ +export function displacement(index: number, from: number, to: number): -1 | 0 | 1 { + if (from < to && index > from && index <= to) return -1; + if (to < from && index >= to && index < from) return 1; + return 0; +} + +/** + * Pixels to scroll per frame with the pointer at `y`, near the top or bottom + * edge of a scroll area spanning `top`–`bottom`: faster the closer to the edge. + */ +export function edgeScrollSpeed( + y: number, + top: number, + bottom: number, + zone = 48, + max = 12, +): number { + const depth = y < top + zone ? y - (top + zone) : y > bottom - zone ? y - (bottom - zone) : 0; + return Math.round(max * Math.max(-1, Math.min(1, depth / zone))); +} + +export interface QueueDrag { + queueId: string; + /** The row's own slot. */ + from: number; + /** The slot it lands in if dropped now. */ + to: number; + /** How far it has been dragged from its slot, scrolling included. */ + dy: number; +} + +/** + * Pointer handling for dragging rows of the list in `scrollElement` (scrolling + * it when held near an edge). `onDrop` gets the slot the row landed in. + */ +export function useQueueDrag( + scrollElement: HTMLElement | null, + count: number, + onDrop: (queueId: string, to: number) => void, +) { + const [drag, setDrag] = useState(null); + // Tears down the drag in progress, should the list unmount mid-drag. + const stop = useRef<(() => void) | null>(null); + useEffect(() => () => stop.current?.(), []); + + const onPointerDown = useCallback( + (e: ReactPointerEvent, from: number, queueId: string) => { + if (e.button !== 0 || !scrollElement) return; + const row = e.currentTarget; + const pointerId = e.pointerId; + const startY = e.clientY; + const startScroll = scrollElement.scrollTop; + let pointerY = startY; + let active = false; + let frame = 0; + let lastDy: number | null = null; + + const dragged = () => pointerY - startY + scrollElement.scrollTop - startScroll; + + // Runs every frame while dragging, so holding still at an edge keeps scrolling. + const tick = () => { + const { top, bottom } = scrollElement.getBoundingClientRect(); + scrollElement.scrollTop += edgeScrollSpeed(pointerY, top, bottom); + const dy = dragged(); + if (dy !== lastDy) { + lastDy = dy; + setDrag({ queueId, from, to: dropIndex(from, dy, count), dy }); + } + frame = requestAnimationFrame(tick); + }; + + const move = (ev: PointerEvent) => { + if (ev.pointerId !== pointerId) return; + pointerY = ev.clientY; + if (active || Math.abs(pointerY - startY) < DRAG_THRESHOLD) return; + active = true; + // Only now, not on press: captured from the start, a plain click on + // the row's buttons would land on the row instead. + row.setPointerCapture(pointerId); + frame = requestAnimationFrame(tick); + }; + + const teardown = () => { + window.removeEventListener("pointermove", move); + window.removeEventListener("pointerup", up); + window.removeEventListener("pointercancel", teardown); + cancelAnimationFrame(frame); + stop.current = null; + setDrag(null); + }; + + const up = (ev: PointerEvent) => { + if (ev.pointerId !== pointerId) return; + teardown(); + if (!active) return; + swallowNextClick(); + onDrop(queueId, dropIndex(from, dragged(), count)); + }; + + stop.current?.(); + stop.current = teardown; + window.addEventListener("pointermove", move); + window.addEventListener("pointerup", up); + window.addEventListener("pointercancel", teardown); + }, + [scrollElement, count, onDrop], + ); + + return { drag, onPointerDown }; +} + +/** + * The release that ends a drag still clicks whatever it started on (say, the + * cover's play button). + */ +function swallowNextClick() { + const swallow = (e: MouseEvent) => { + e.stopPropagation(); + e.preventDefault(); + }; + window.addEventListener("click", swallow, { capture: true, once: true }); + // No click follows when the release lands somewhere else; don't eat a later one. + setTimeout(() => window.removeEventListener("click", swallow, { capture: true }), 0); +} diff --git a/src/stores/playerStore.test.ts b/src/stores/playerStore.test.ts index d7ca585..b94eee7 100644 --- a/src/stores/playerStore.test.ts +++ b/src/stores/playerStore.test.ts @@ -185,6 +185,45 @@ describe("playNow", () => { }); }); +describe("moveInQueue", () => { + const ids = () => usePlayerStore.getState().queue.map((i) => i.queueId); + + beforeEach(() => { + invoke.mockClear(); + usePlayerStore.setState({ + queue: ["q1", "q2", "q3", "q4", "q5"].map((id) => item(id, song(id))), + queueIndex: 1, + }); + }); + + it("moves an upcoming item down, and the ones it passes up", () => { + usePlayerStore.getState().moveInQueue(2, 4); + + expect(ids()).toEqual(["q1", "q2", "q4", "q5", "q3"]); + }); + + it("moves an upcoming item up, and the ones it passes down", () => { + usePlayerStore.getState().moveInQueue(4, 2); + + expect(ids()).toEqual(["q1", "q2", "q5", "q3", "q4"]); + }); + + it("leaves the current item current, and doesn't restart it", () => { + usePlayerStore.getState().moveInQueue(3, 2); + + expect(usePlayerStore.getState().currentItem()?.queueId).toBe("q2"); + expect(playedTrackIds()).toEqual([]); + }); + + it("ignores a move to where the item already is, or out of range", () => { + const queue = usePlayerStore.getState().queue; + usePlayerStore.getState().moveInQueue(3, 3); + usePlayerStore.getState().moveInQueue(3, 9); + + expect(usePlayerStore.getState().queue).toBe(queue); + }); +}); + describe("saveQueueSnapshotNow", () => { const setSaveQueue = (saveQueue: boolean) => usePrefsStore.setState({ prefs: { ...usePrefsStore.getState().prefs, saveQueue } }); diff --git a/src/stores/playerStore.ts b/src/stores/playerStore.ts index 49b7f96..9867146 100644 --- a/src/stores/playerStore.ts +++ b/src/stores/playerStore.ts @@ -54,9 +54,8 @@ interface PlayerStore { playNow: (song: Song) => void; addToQueue: (songs: Song[]) => void; removeFromQueue: (queueId: string) => void; + /** Move the item at `from` to `to` (drag-reorder in the queue panel); the current one keeps playing. */ moveInQueue: (from: number, to: number) => void; - /** Replace everything after the current track (drag-reorder in the queue panel). */ - setUpcoming: (items: QueueItem[]) => void; jumpTo: (queueId: string) => void; /** Drop everything except the playing track (if any). */ clearQueue: () => void; @@ -300,12 +299,6 @@ export const usePlayerStore = create((set, get) => { syncNext(); }, - setUpcoming: (items) => { - const { queue, queueIndex } = get(); - set({ queue: [...queue.slice(0, queueIndex + 1), ...items] }); - syncNext(); - }, - moveInQueue: (from, to) => { const { queue, queueIndex } = get(); if (from === to || from < 0 || from >= queue.length || to < 0 || to >= queue.length) return;