diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1314995..a50b2ea 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1412,6 +1412,7 @@ export default function App() { onSortingChange={setSorting} selection={{ selected, onChange: setSelected }} marked={{ ids: heldInFolder, title: 'Already in your collection' }} + dragFrom={{ origin: 'folder' }} onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)} onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })} onPlay={playTrack} @@ -1447,6 +1448,7 @@ export default function App() { sorting={sorting} onSortingChange={setSorting} onRowContextMenu={(track, x, y) => openMenu(track, x, y, false)} + dragFrom={{ origin: 'device' }} onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })} onPlay={playTrack} activeTrackId={prepTrack?.id ?? null} @@ -1508,6 +1510,10 @@ export default function App() { : undefined } onRemove={playlistEditable ? confirmRemoveFromPlaylist : undefined} + dragFrom={{ + origin: 'collection', + playlistId: playlistEditable && source.kind === 'playlist' ? source.id : undefined, + }} onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)} onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })} onPlay={playTrack} diff --git a/frontend/src/components/TrackTable.tsx b/frontend/src/components/TrackTable.tsx index e61e2aa..89608fc 100644 --- a/frontend/src/components/TrackTable.tsx +++ b/frontend/src/components/TrackTable.tsx @@ -1,4 +1,4 @@ -import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject } from 'react' +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject } from 'react' import { flexRender, getCoreRowModel, @@ -29,7 +29,8 @@ import { useSortable, } from '@dnd-kit/sortable' import { CSS } from '@dnd-kit/utilities' -import type { Track } from '../api' +import type { Track, TrackOrigin } from '../api' +import { beginDrag, useDragPayload, useDropTarget } from '../lib/drag' import { TRACK_COLUMNS } from '../lib/trackColumns' /** Fields this platform can persist, for the table's per-cell edit gating. @@ -71,6 +72,9 @@ interface Props { /** A view with a manual order. `enabled` is false while a sort or filter is * active: reordering a partial or re-sorted list would lose the real order. */ reorder?: { enabled: boolean; onReorder: (ids: string[]) => void } + /** Where dragged rows come from: whose ids they are, and the editable + * playlist they leave on an Option-drag (move). Defaults to the collection. */ + dragFrom?: { origin: TrackOrigin; playlistId?: string } /** Delete/Backspace removes the selected tracks from this view. */ onRemove?: (ids: string[]) => void onRowContextMenu?: (track: Track, x: number, y: number) => void @@ -277,6 +281,7 @@ export function TrackTable({ positions, marked, reorder, + dragFrom, onRemove, onRowContextMenu, onHeaderContextMenu, @@ -363,7 +368,7 @@ export function TrackTable({ } const clickRow = (index: number, e: { shiftKey: boolean; metaKey: boolean; ctrlKey: boolean }) => { - if (!selection || justDraggedRef.current) return + if (!selection) return const id = rows[index].original.id const toggle = e.metaKey || e.ctrlKey const anchor = indexOf(anchorRef.current) @@ -381,102 +386,87 @@ export function TrackTable({ } } - // ---- row drag-to-reorder ---------------------------------------------- - // `drop` is the gap the dragged rows would land in (0 = above the first row). - const [drag, setDrag] = useState<{ moving: Set; drop: number } | null>(null) + // ---- dragging rows ------------------------------------------------------ + // Every table's rows are a drag SOURCE (onto playlists, exports, the deck — + // lib/drag.tsx); a view with a manual order is also its own drop TARGET, the + // in-table reorder. `drop` is the gap the rows would land in (0 = above the + // first row). const pressRef = useRef<{ x: number; y: number; index: number } | null>(null) - const justDraggedRef = useRef(false) - const canDrag = !!reorder?.enabled + const tableKey = useRef({}).current + const dragging = useDragPayload() + const ownDrag = dragging?.kind === 'tracks' && dragging.source === tableKey ? dragging : null + const movingIds = useMemo(() => new Set(ownDrag?.ids ?? []), [ownDrag]) useEffect(() => { - if (!canDrag) return - let raf = 0 - let lastY = 0 - let active: { moving: Set; drop: number } | null = null - - const dropAt = (clientY: number) => { - const top = bodyRef.current?.getBoundingClientRect().top ?? 0 - return Math.max(0, Math.min(rowsRef.current.length, Math.round((clientY - top) / ROW_HEIGHT))) - } - // Hold near the top/bottom edge to scroll while dragging. - const autoScroll = () => { - const el = parentRef.current - if (el && active) { - const r = el.getBoundingClientRect() - const edge = 48 - const dy = - lastY < r.top + edge + ROW_HEIGHT ? -12 : lastY > r.bottom - edge ? 12 : 0 - if (dy) { - el.scrollTop += dy - active = { ...active, drop: dropAt(lastY) } - setDrag(active) - } - } - raf = requestAnimationFrame(autoScroll) - } const onMove = (e: PointerEvent) => { const press = pressRef.current - if (!press) return - lastY = e.clientY - if (!active) { - if (Math.hypot(e.clientX - press.x, e.clientY - press.y) < 6) return - // Dragging a selected row moves the whole selection; any other row - // moves alone (and becomes the selection, so what moves is visible). - const rs = rowsRef.current - const sel = selectionRef.current - const pressedId = rs[press.index].original.id - let moving: Set - if (sel?.selected.has(pressedId)) { - moving = new Set(rs.flatMap((r, i) => (sel.selected.has(r.original.id) ? [i] : []))) - } else { - moving = new Set([press.index]) - sel?.onChange(new Set([pressedId])) - anchorRef.current = leadRef.current = pressedId - } - active = { moving, drop: dropAt(e.clientY) } - document.body.style.userSelect = 'none' - document.body.style.cursor = 'grabbing' - window.getSelection()?.removeAllRanges() - raf = requestAnimationFrame(autoScroll) - } else { - active = { ...active, drop: dropAt(e.clientY) } - } - setDrag(active) - } - const end = () => { + if (!press || Math.hypot(e.clientX - press.x, e.clientY - press.y) < 6) return pressRef.current = null - if (!active) return - const { moving, drop } = active - active = null - cancelAnimationFrame(raf) - document.body.style.userSelect = '' - document.body.style.cursor = '' - setDrag(null) - // Swallow the click that follows the pointerup, so a drop is not also a - // click that re-selects the row it ended on. - justDraggedRef.current = true - setTimeout(() => (justDraggedRef.current = false), 0) + // Dragging a selected row carries the whole selection (in the table's + // order); any other row goes alone and becomes the selection, so what is + // being dragged is visible. + const rs = rowsRef.current + const sel = selectionRef.current + const pressed = rs[press.index]?.original + if (!pressed) return + let carried: Track[] + if (sel?.selected.has(pressed.id)) { + carried = rs.filter((r) => sel.selected.has(r.original.id)).map((r) => r.original) + } else { + carried = [pressed] + sel?.onChange(new Set([pressed.id])) + anchorRef.current = leadRef.current = pressed.id + } + const from = dragFromRef.current + beginDrag( + { + kind: 'tracks', + ids: [...new Set(carried.map((t) => t.id))], + tracks: carried, + origin: from?.origin ?? 'collection', + fromPlaylist: from?.playlistId, + source: tableKey, + }, + { x: e.clientX, y: e.clientY, alt: e.altKey }, + ) + } + const release = () => (pressRef.current = null) + window.addEventListener('pointermove', onMove) + window.addEventListener('pointerup', release) + window.addEventListener('pointercancel', release) + return () => { + window.removeEventListener('pointermove', onMove) + window.removeEventListener('pointerup', release) + window.removeEventListener('pointercancel', release) + } + }, [tableKey]) + + const [dropRef, dropHint] = useDropTarget<{ drop: number }>({ + hint: (p, at) => { + if (p.kind !== 'tracks' || p.source !== tableKey || !reorderRef.current?.enabled) return null + const top = bodyRef.current?.getBoundingClientRect().top ?? 0 + return { drop: Math.max(0, Math.min(rowsRef.current.length, Math.round((at.y - top) / ROW_HEIGHT))) } + }, + onDrop: (p, { drop }) => { + if (p.kind !== 'tracks') return + const ids = new Set(p.ids) const rs = rowsRef.current.map((r) => r.original) - const kept = rs.filter((_, i) => !moving.has(i)) - const block = rs.filter((_, i) => moving.has(i)) - const at = drop - [...moving].filter((i) => i < drop).length + const kept = rs.filter((t) => !ids.has(t.id)) + const block = rs.filter((t) => ids.has(t.id)) + const at = drop - rs.slice(0, drop).filter((t) => ids.has(t.id)).length const next = [...kept.slice(0, at), ...block, ...kept.slice(at)] if (next.every((t, i) => t === rs[i])) return setData(next) reorderRef.current?.onReorder(next.map((t) => t.id)) - } - window.addEventListener('pointermove', onMove) - window.addEventListener('pointerup', end) - window.addEventListener('pointercancel', end) - return () => { - cancelAnimationFrame(raf) - window.removeEventListener('pointermove', onMove) - window.removeEventListener('pointerup', end) - window.removeEventListener('pointercancel', end) - document.body.style.userSelect = '' - document.body.style.cursor = '' - } - }, [canDrag]) + }, + }) + const scrollerRef = useCallback( + (el: HTMLDivElement | null) => { + parentRef.current = el + dropRef(el) + }, + [dropRef], + ) // Latest values for the once-attached window listeners. const rowsRef = useRef(rows) @@ -485,6 +475,8 @@ export function TrackTable({ selectionRef.current = selection const reorderRef = useRef(reorder) reorderRef.current = reorder + const dragFromRef = useRef(dragFrom) + dragFromRef.current = dragFrom // Keyboard: ↑/↓ move the selection (Shift extends it), Cmd/Ctrl+A selects // every visible row, Esc clears, Delete/Backspace removes (where the view @@ -547,7 +539,8 @@ export function TrackTable({ return (
{ // A click in the empty space below the rows clears the selection. @@ -568,13 +561,13 @@ export function TrackTable({ const row = rows[vr.index] const isSelected = selection?.selected.has(row.original.id) ?? false const isActive = activeTrackId === row.original.id - const isMoving = drag?.moving.has(vr.index) ?? false + const isMoving = movingIds.has(row.original.id) return (
{ @@ -582,7 +575,7 @@ export function TrackTable({ if (selection && (e.shiftKey || e.metaKey || e.ctrlKey)) e.preventDefault() }} onPointerDown={(e) => { - if (!canDrag || e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return + if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return // Not from a control inside the row (play, stars, an edit field). if ((e.target as HTMLElement).closest('button, input, textarea, select, a')) return pressRef.current = { x: e.clientX, y: e.clientY, index: vr.index } @@ -620,10 +613,10 @@ export function TrackTable({
) })} - {drag && ( + {dropHint && (
)}
diff --git a/frontend/src/index.css b/frontend/src/index.css index 98059af..77d4004 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -87,6 +87,13 @@ body, overscroll-behavior: none; } +/* While something is being dragged (lib/drag.tsx), the cursor is the hand + everywhere — buttons and links would otherwise show their own. */ +html.is-dragging, +html.is-dragging * { + cursor: grabbing !important; +} + body { margin: 0; background: var(--color-ink-950); diff --git a/frontend/src/lib/drag.tsx b/frontend/src/lib/drag.tsx new file mode 100644 index 0000000..1e6f754 --- /dev/null +++ b/frontend/src/lib/drag.tsx @@ -0,0 +1,261 @@ +import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react' +import { createPortal } from 'react-dom' +import type { PlaylistNode, Track, TrackOrigin } from '../api' +import { Icon } from './icons' + +/** + * Drag and drop across the whole window: track rows onto sidebar playlists, + * exports and the deck; playlists around the sidebar tree. + * + * ONE gesture, and the drop TARGET decides what it means. A source calls + * `beginDrag` once the pointer has moved past its threshold; targets register + * with `useDropTarget` and are found by hit-testing (`elementFromPoint`, then up + * through the ancestors), so the virtualized table, the sidebar and the deck + * need no shared React tree — and the innermost target that accepts wins, with + * the search falling through to an enclosing one where it declines. + * + * Pointer events, NOT HTML5 drag and drop: Tauri's webview captures native drag + * events for its own file drop on Windows, so HTML5 DnD silently dies in the + * packaged app. + * + * The state lives in a module-level store read through useSyncExternalStore + * with narrow selectors, so a pointer move re-renders only the target under it + * (and the ghost) — never the table. + */ + +export type DragPayload = + | { + kind: 'tracks' + ids: string[] + tracks: Track[] + /** Which library the ids belong to — a device's or a folder's are not + * the collection's, so collection targets must not take them as such. */ + origin: TrackOrigin + /** The editable playlist they were dragged out of, for Option = move. */ + fromPlaylist?: string + /** Identity of the table that started the drag (its own reorder target). */ + source: object + } + | { kind: 'node'; node: PlaylistNode; parentId: string | null } + +export interface DropPoint { + x: number + y: number + /** Option/Alt held: tracks dragged out of a playlist MOVE instead of copy. */ + alt: boolean +} + +export interface DropSpec { + /** The hint for a pointer at `at` over this target — anything the target + * needs to draw and to drop (an insertion index, a before/into/after zone) — + * or null where it does not accept this drop, so the search continues to an + * enclosing target. */ + hint: (p: DragPayload, at: DropPoint, el: HTMLElement) => H | null + /** What a drop here would do, shown on the ghost ("Add to Warmup"). */ + label?: (p: DragPayload, hint: H, at: DropPoint) => string | null + onDrop: (p: DragPayload, hint: H, at: DropPoint) => void +} + +interface State { + payload: DragPayload | null + x: number + y: number + alt: boolean + target: HTMLElement | null + hint: unknown + label: string | null +} + +const IDLE: State = { payload: null, x: 0, y: 0, alt: false, target: null, hint: null, label: null } +let state: State = IDLE +const listeners = new Set<() => void>() +const targets = new Map }>() + +function set(next: Partial) { + state = { ...state, ...next } + listeners.forEach((l) => l()) +} +function subscribe(l: () => void) { + listeners.add(l) + return () => listeners.delete(l) +} + +/** Keep the previous hint object when the new one has the same fields, so a + * target re-renders only when what it draws changes, not on every move. */ +function sameHint(a: unknown, b: unknown): boolean { + if (a === b) return true + if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false + const ka = Object.keys(a) + return ( + ka.length === Object.keys(b).length && + ka.every((k) => (a as Record)[k] === (b as Record)[k]) + ) +} + +/** Find the innermost target under the pointer that accepts, and record its hint. */ +function evaluate() { + const { payload, x, y, alt } = state + if (!payload) return + const at = { x, y, alt } + let el = document.elementFromPoint(x, y) as HTMLElement | null + while (el) { + const spec = targets.get(el) + if (spec) { + const hint = spec.current.hint(payload, at, el) + if (hint != null) { + const keep = state.target === el && sameHint(state.hint, hint) ? state.hint : hint + set({ target: el, hint: keep, label: spec.current.label?.(payload, keep, at) ?? null }) + return + } + } + el = el.parentElement + } + set({ target: null, hint: null, label: null }) +} + +let detach: (() => void) | null = null + +/** Start a drag. Call it once the press has moved past the source's threshold. */ +export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) { + detach?.() + set({ ...IDLE, payload, ...at }) + document.documentElement.classList.add('is-dragging') + window.getSelection()?.removeAllRanges() + + const onMove = (e: PointerEvent) => { + // One notification per move: evaluate() publishes the position with the hint. + state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey } + evaluate() + } + const finish = (drop: boolean) => { + const { payload: p, target, hint, x, y, alt } = state + detach?.() + if (!drop || !p || !target) return + const spec = targets.get(target) + try { + spec?.current.onDrop(p, hint, { x, y, alt }) + } catch (err) { + console.error('drop failed', err) + } + } + const onUp = () => finish(true) + const onCancel = () => finish(false) + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape' && e.type === 'keydown') { + // Before every other Esc handler: cancelling the drag is all Esc does. + e.preventDefault() + e.stopImmediatePropagation() + finish(false) + return + } + if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) { + set({ alt: e.type === 'keydown' }) + evaluate() + } + } + // Hold near the edge of a `data-drag-scroll` element to scroll it. Its + // value is the height covered at the top (a sticky header). + let raf = 0 + const autoScroll = () => { + const { x, y } = state + let scrolled = false + document.querySelectorAll('[data-drag-scroll]').forEach((el) => { + const r = el.getBoundingClientRect() + if (x < r.left || x > r.right || y < r.top - 24 || y > r.bottom + 24) return + const top = r.top + Number(el.dataset.dragScroll || 0) + const edge = 40 + const dy = y < top + edge ? -Math.ceil((top + edge - y) / 4) : y > r.bottom - edge ? Math.ceil((y - r.bottom + edge) / 4) : 0 + if (!dy) return + const before = el.scrollTop + el.scrollTop += Math.max(-20, Math.min(20, dy)) + scrolled ||= el.scrollTop !== before + }) + if (scrolled) evaluate() + raf = requestAnimationFrame(autoScroll) + } + raf = requestAnimationFrame(autoScroll) + + window.addEventListener('pointermove', onMove) + window.addEventListener('pointerup', onUp) + window.addEventListener('pointercancel', onCancel) + window.addEventListener('keydown', onKey, true) + window.addEventListener('keyup', onKey, true) + window.addEventListener('blur', onCancel) + detach = () => { + detach = null + cancelAnimationFrame(raf) + window.removeEventListener('pointermove', onMove) + window.removeEventListener('pointerup', onUp) + window.removeEventListener('pointercancel', onCancel) + window.removeEventListener('keydown', onKey, true) + window.removeEventListener('keyup', onKey, true) + window.removeEventListener('blur', onCancel) + document.documentElement.classList.remove('is-dragging') + // The pointerup that ended the drag is followed by a click on whatever + // is under it; that click is part of the drop, not a click of its own. + const swallow = (e: MouseEvent) => { + e.stopPropagation() + e.preventDefault() + } + window.addEventListener('click', swallow, true) + setTimeout(() => window.removeEventListener('click', swallow, true), 0) + set(IDLE) + } + evaluate() +} + +/** The drag in progress, or null. Changes only when a drag starts or ends. */ +export function useDragPayload(): DragPayload | null { + return useSyncExternalStore(subscribe, () => state.payload) +} + +/** Register an element as a drop target. Returns the ref to attach and the + * current hint while the pointer is over it (null otherwise). */ +export function useDropTarget(spec: DropSpec): [(el: HTMLElement | null) => void, H | null] { + const specRef = useRef(spec as DropSpec) + specRef.current = spec as DropSpec + const elRef = useRef(null) + const ref = useCallback((el: HTMLElement | null) => { + if (elRef.current) targets.delete(elRef.current) + elRef.current = el + if (el) targets.set(el, specRef) + }, []) + useEffect(() => () => { + if (elRef.current) targets.delete(elRef.current) + }, []) + const hint = useSyncExternalStore(subscribe, () => + state.target !== null && state.target === elRef.current ? state.hint : null, + ) + return [ref, hint as H | null] +} + +/** What the ghost says it is carrying. */ +function describe(p: DragPayload): { icon: 'music' | 'playlist' | 'folder' | 'smart'; text: string } { + if (p.kind === 'node') + return { icon: p.node.kind === 'folder' ? 'folder' : p.node.kind === 'smart' ? 'smart' : 'playlist', text: p.node.name } + if (p.ids.length === 1) { + const t = p.tracks[0] + return { icon: 'music', text: t ? [t.artist, t.title].filter(Boolean).join(' – ') || 'Untitled' : '1 track' } + } + return { icon: 'music', text: `${p.ids.length} tracks` } +} + +/** The ghost under the cursor. Mounted once, in main.tsx. */ +export function DragLayer() { + const s = useSyncExternalStore(subscribe, () => state) + if (!s.payload) return null + const { icon, text } = describe(s.payload) + return createPortal( +
+ + + {text} + + {s.label && {s.label}} +
, + document.body, + ) +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 80074f8..0e961fe 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -8,6 +8,7 @@ import App from './App.tsx' import { UpdateCheck } from './components/UpdateDialog.tsx' import { AmbientBackdrop } from './components/AmbientBackdrop.tsx' import { ConfirmHost } from './lib/confirm.tsx' +import { DragLayer } from './lib/drag.tsx' import { QuitGuard } from './components/QuitGuard.tsx' import { preventHistoryNavigation } from './lib/noNavigation.ts' @@ -34,6 +35,8 @@ createRoot(document.getElementById('root')!).render( {/* Save · Discard · Cancel when quitting with unsaved changes. */} + {/* The ghost under the cursor while dragging tracks or playlists. */} + , )