import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react' import { createPortal } from 'react-dom' import type { PlaylistNode, Track, TrackOrigin } from '../api' import { Icon } from './icons' import { hasMod, MOD_KEY } from './modKey' /** * 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. * * Files dragged in from Finder / Explorer ride the same store as a `files` * payload: Tauri reports that drag (with real paths) instead of the webview, * and `lib/fileDrop.ts` feeds it in through `nativeDragStart` / `Move` / `End`, * so the same targets light up and the same ghost names what a drop would do. * * 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[] /** The row the drag started on — what a drop on the deck loads. */ lead: 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 Cmd/Ctrl = move. */ fromPlaylist?: string /** Identity of the table that started the drag (its own reorder target). */ source: object } | { kind: 'node'; node: PlaylistNode; parentId: string | null } /** Files and folders from the OS, as absolute paths. Not yet tracks: a * target hands them to the drop resolver, which reads what is in them. */ | { kind: 'files'; paths: string[] } /** What a playlist or export row takes: track rows, or files from the OS. */ export type TracksOrFiles = Exclude export interface DropPoint { x: number y: number /** Cmd (macOS) / Ctrl held: tracks dragged out of a playlist MOVE instead of copy. */ mod: 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 mod: boolean target: HTMLElement | null hint: unknown label: string | null } const IDLE: State = { payload: null, x: 0, y: 0, mod: 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, mod } = state if (!payload) return const at = { x, y, mod } 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 /** End the drag in progress, dropping on the target under the pointer if `drop`. */ function finish(drop: boolean) { const { payload: p, target, hint, x, y, mod } = state detach?.() if (!drop || !p || !target) return const spec = targets.get(target) try { spec?.current.onDrop(p, hint, { x, y, mod }) } catch (err) { console.error('drop failed', err) } } /** Publish a new drag and start edge auto-scroll. Returns what undoes both. */ function open(payload: DragPayload, at: { x: number; y: number; mod: boolean }): () => void { detach?.() set({ ...IDLE, payload, ...at }) document.documentElement.classList.add('is-dragging') window.getSelection()?.removeAllRanges() // 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). The edge is // thinner than a row and must be HELD for a moment first: otherwise the // first or last visible row cannot be dropped on, because the list scrolls // out from under a pointer resting on it. let raf = 0 const dwell = new Map() const autoScroll = () => { const { x, y } = state let scrolled = false document.querySelectorAll('[data-drag-scroll]').forEach((el) => { const r = el.getBoundingClientRect() const top = r.top + Number(el.dataset.dragScroll || 0) const edge = 20 const inside = x >= r.left && x <= r.right && y >= r.top - 24 && y <= r.bottom + 24 const dy = !inside ? 0 : y < top + edge ? -Math.ceil((top + edge - y) / 3) : y > r.bottom - edge ? Math.ceil((y - r.bottom + edge) / 3) : 0 if (!dy) { dwell.delete(el) return } const since = dwell.get(el) ?? performance.now() dwell.set(el, since) if (performance.now() - since < 250) 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) return () => { cancelAnimationFrame(raf) document.documentElement.classList.remove('is-dragging') set(IDLE) } } /** 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; mod: boolean }) { const close = open(payload, at) const onMove = (e: PointerEvent) => { // One notification per move: evaluate() publishes the position with the hint. state = { ...state, x: e.clientX, y: e.clientY, mod: hasMod(e) } evaluate() } 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 === MOD_KEY && state.mod !== (e.type === 'keydown')) { set({ mod: e.type === 'keydown' }) evaluate() } } 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 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) // 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) close() } evaluate() } /** A drag the OS owns (files from Finder / Explorer): it enters the window… */ export function nativeDragStart(payload: DragPayload, at: { x: number; y: number }) { const close = open(payload, { ...at, mod: false }) detach = () => { detach = null close() } evaluate() } /** …moves over it (window coordinates, CSS pixels)… */ export function nativeDragMove(at: { x: number; y: number }) { if (!state.payload) return state = { ...state, ...at } evaluate() } /** …and is dropped (or leaves the window: `drop` false). */ export function nativeDragEnd(drop: boolean, at?: { x: number; y: number }) { if (drop && at) nativeDragMove(at) finish(drop) } /** A pointerdown handler that starts a drag once the press moves 6 px. A plain * click never moves that far, so the element keeps its click; a press on a * field inside it (a rename input) never drags. `make` is asked at the moment * the drag starts and may return null to refuse. */ export function usePressToDrag(make: () => DragPayload | null): (e: React.PointerEvent) => void { const makeRef = useRef(make) makeRef.current = make return useCallback((e: React.PointerEvent) => { if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return if ((e.target as HTMLElement).closest('input, textarea, select')) return const start = { x: e.clientX, y: e.clientY } const onMove = (m: PointerEvent) => { if (Math.hypot(m.clientX - start.x, m.clientY - start.y) < 6) return stop() const payload = makeRef.current() if (payload) beginDrag(payload, { x: m.clientX, y: m.clientY, mod: hasMod(m) }) } const stop = () => { window.removeEventListener('pointermove', onMove) window.removeEventListener('pointerup', stop) window.removeEventListener('pointercancel', stop) } window.addEventListener('pointermove', onMove) window.addEventListener('pointerup', stop) window.addEventListener('pointercancel', stop) }, []) } /** 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.kind === 'files') return p.paths.length === 1 ? { icon: 'music', text: p.paths[0].split(/[\\/]/).filter(Boolean).pop() ?? p.paths[0] } : { icon: 'music', text: `${p.paths.length} items` } 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, ) }