mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented drag core and song reorganizing
This commit is contained in:
1 parent
e5c7b67626
commit
b154df430a
5 files changed
+364
-94
No files matched your search
@@ -1412,6 +1412,7 @@ export default function App() {
|
|||||||
onSortingChange={setSorting}
|
onSortingChange={setSorting}
|
||||||
selection={{ selected, onChange: setSelected }}
|
selection={{ selected, onChange: setSelected }}
|
||||||
marked={{ ids: heldInFolder, title: 'Already in your collection' }}
|
marked={{ ids: heldInFolder, title: 'Already in your collection' }}
|
||||||
|
dragFrom={{ origin: 'folder' }}
|
||||||
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
|
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
|
||||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||||
onPlay={playTrack}
|
onPlay={playTrack}
|
||||||
@@ -1447,6 +1448,7 @@ export default function App() {
|
|||||||
sorting={sorting}
|
sorting={sorting}
|
||||||
onSortingChange={setSorting}
|
onSortingChange={setSorting}
|
||||||
onRowContextMenu={(track, x, y) => openMenu(track, x, y, false)}
|
onRowContextMenu={(track, x, y) => openMenu(track, x, y, false)}
|
||||||
|
dragFrom={{ origin: 'device' }}
|
||||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||||
onPlay={playTrack}
|
onPlay={playTrack}
|
||||||
activeTrackId={prepTrack?.id ?? null}
|
activeTrackId={prepTrack?.id ?? null}
|
||||||
@@ -1508,6 +1510,10 @@ export default function App() {
|
|||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
onRemove={playlistEditable ? confirmRemoveFromPlaylist : 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)}
|
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
|
||||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||||
onPlay={playTrack}
|
onPlay={playTrack}
|
||||||
|
|||||||
@@ -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 {
|
import {
|
||||||
flexRender,
|
flexRender,
|
||||||
getCoreRowModel,
|
getCoreRowModel,
|
||||||
@@ -29,7 +29,8 @@ import {
|
|||||||
useSortable,
|
useSortable,
|
||||||
} from '@dnd-kit/sortable'
|
} from '@dnd-kit/sortable'
|
||||||
import { CSS } from '@dnd-kit/utilities'
|
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'
|
import { TRACK_COLUMNS } from '../lib/trackColumns'
|
||||||
|
|
||||||
/** Fields this platform can persist, for the table's per-cell edit gating.
|
/** 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
|
/** 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. */
|
* active: reordering a partial or re-sorted list would lose the real order. */
|
||||||
reorder?: { enabled: boolean; onReorder: (ids: string[]) => void }
|
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. */
|
/** Delete/Backspace removes the selected tracks from this view. */
|
||||||
onRemove?: (ids: string[]) => void
|
onRemove?: (ids: string[]) => void
|
||||||
onRowContextMenu?: (track: Track, x: number, y: number) => void
|
onRowContextMenu?: (track: Track, x: number, y: number) => void
|
||||||
@@ -277,6 +281,7 @@ export function TrackTable({
|
|||||||
positions,
|
positions,
|
||||||
marked,
|
marked,
|
||||||
reorder,
|
reorder,
|
||||||
|
dragFrom,
|
||||||
onRemove,
|
onRemove,
|
||||||
onRowContextMenu,
|
onRowContextMenu,
|
||||||
onHeaderContextMenu,
|
onHeaderContextMenu,
|
||||||
@@ -363,7 +368,7 @@ export function TrackTable({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const clickRow = (index: number, e: { shiftKey: boolean; metaKey: boolean; ctrlKey: boolean }) => {
|
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 id = rows[index].original.id
|
||||||
const toggle = e.metaKey || e.ctrlKey
|
const toggle = e.metaKey || e.ctrlKey
|
||||||
const anchor = indexOf(anchorRef.current)
|
const anchor = indexOf(anchorRef.current)
|
||||||
@@ -381,102 +386,87 @@ export function TrackTable({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- row drag-to-reorder ----------------------------------------------
|
// ---- dragging rows ------------------------------------------------------
|
||||||
// `drop` is the gap the dragged rows would land in (0 = above the first row).
|
// Every table's rows are a drag SOURCE (onto playlists, exports, the deck —
|
||||||
const [drag, setDrag] = useState<{ moving: Set<number>; drop: number } | null>(null)
|
// 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 pressRef = useRef<{ x: number; y: number; index: number } | null>(null)
|
||||||
const justDraggedRef = useRef(false)
|
const tableKey = useRef({}).current
|
||||||
const canDrag = !!reorder?.enabled
|
const dragging = useDragPayload()
|
||||||
|
const ownDrag = dragging?.kind === 'tracks' && dragging.source === tableKey ? dragging : null
|
||||||
|
const movingIds = useMemo(() => new Set(ownDrag?.ids ?? []), [ownDrag])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!canDrag) return
|
|
||||||
let raf = 0
|
|
||||||
let lastY = 0
|
|
||||||
let active: { moving: Set<number>; 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 onMove = (e: PointerEvent) => {
|
||||||
const press = pressRef.current
|
const press = pressRef.current
|
||||||
if (!press) return
|
if (!press || Math.hypot(e.clientX - press.x, e.clientY - press.y) < 6) 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<number>
|
|
||||||
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 = () => {
|
|
||||||
pressRef.current = null
|
pressRef.current = null
|
||||||
if (!active) return
|
// Dragging a selected row carries the whole selection (in the table's
|
||||||
const { moving, drop } = active
|
// order); any other row goes alone and becomes the selection, so what is
|
||||||
active = null
|
// being dragged is visible.
|
||||||
cancelAnimationFrame(raf)
|
const rs = rowsRef.current
|
||||||
document.body.style.userSelect = ''
|
const sel = selectionRef.current
|
||||||
document.body.style.cursor = ''
|
const pressed = rs[press.index]?.original
|
||||||
setDrag(null)
|
if (!pressed) return
|
||||||
// Swallow the click that follows the pointerup, so a drop is not also a
|
let carried: Track[]
|
||||||
// click that re-selects the row it ended on.
|
if (sel?.selected.has(pressed.id)) {
|
||||||
justDraggedRef.current = true
|
carried = rs.filter((r) => sel.selected.has(r.original.id)).map((r) => r.original)
|
||||||
setTimeout(() => (justDraggedRef.current = false), 0)
|
} 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 rs = rowsRef.current.map((r) => r.original)
|
||||||
const kept = rs.filter((_, i) => !moving.has(i))
|
const kept = rs.filter((t) => !ids.has(t.id))
|
||||||
const block = rs.filter((_, i) => moving.has(i))
|
const block = rs.filter((t) => ids.has(t.id))
|
||||||
const at = drop - [...moving].filter((i) => i < drop).length
|
const at = drop - rs.slice(0, drop).filter((t) => ids.has(t.id)).length
|
||||||
const next = [...kept.slice(0, at), ...block, ...kept.slice(at)]
|
const next = [...kept.slice(0, at), ...block, ...kept.slice(at)]
|
||||||
if (next.every((t, i) => t === rs[i])) return
|
if (next.every((t, i) => t === rs[i])) return
|
||||||
setData(next)
|
setData(next)
|
||||||
reorderRef.current?.onReorder(next.map((t) => t.id))
|
reorderRef.current?.onReorder(next.map((t) => t.id))
|
||||||
}
|
},
|
||||||
window.addEventListener('pointermove', onMove)
|
})
|
||||||
window.addEventListener('pointerup', end)
|
const scrollerRef = useCallback(
|
||||||
window.addEventListener('pointercancel', end)
|
(el: HTMLDivElement | null) => {
|
||||||
return () => {
|
parentRef.current = el
|
||||||
cancelAnimationFrame(raf)
|
dropRef(el)
|
||||||
window.removeEventListener('pointermove', onMove)
|
},
|
||||||
window.removeEventListener('pointerup', end)
|
[dropRef],
|
||||||
window.removeEventListener('pointercancel', end)
|
)
|
||||||
document.body.style.userSelect = ''
|
|
||||||
document.body.style.cursor = ''
|
|
||||||
}
|
|
||||||
}, [canDrag])
|
|
||||||
|
|
||||||
// Latest values for the once-attached window listeners.
|
// Latest values for the once-attached window listeners.
|
||||||
const rowsRef = useRef(rows)
|
const rowsRef = useRef(rows)
|
||||||
@@ -485,6 +475,8 @@ export function TrackTable({
|
|||||||
selectionRef.current = selection
|
selectionRef.current = selection
|
||||||
const reorderRef = useRef(reorder)
|
const reorderRef = useRef(reorder)
|
||||||
reorderRef.current = reorder
|
reorderRef.current = reorder
|
||||||
|
const dragFromRef = useRef(dragFrom)
|
||||||
|
dragFromRef.current = dragFrom
|
||||||
|
|
||||||
// Keyboard: ↑/↓ move the selection (Shift extends it), Cmd/Ctrl+A selects
|
// Keyboard: ↑/↓ move the selection (Shift extends it), Cmd/Ctrl+A selects
|
||||||
// every visible row, Esc clears, Delete/Backspace removes (where the view
|
// every visible row, Esc clears, Delete/Backspace removes (where the view
|
||||||
@@ -547,7 +539,8 @@ export function TrackTable({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
ref={parentRef}
|
ref={scrollerRef}
|
||||||
|
data-drag-scroll={bodyOffset.header}
|
||||||
className="h-full overflow-auto px-1.5"
|
className="h-full overflow-auto px-1.5"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
// A click in the empty space below the rows clears the selection.
|
// 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 row = rows[vr.index]
|
||||||
const isSelected = selection?.selected.has(row.original.id) ?? false
|
const isSelected = selection?.selected.has(row.original.id) ?? false
|
||||||
const isActive = activeTrackId === row.original.id
|
const isActive = activeTrackId === row.original.id
|
||||||
const isMoving = drag?.moving.has(vr.index) ?? false
|
const isMoving = movingIds.has(row.original.id)
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
key={row.id}
|
key={row.id}
|
||||||
data-row
|
data-row
|
||||||
className={`group absolute left-0 flex items-center border-b border-ink-850 text-sm ${
|
className={`group absolute left-0 flex items-center border-b border-ink-850 text-sm ${
|
||||||
isSelected ? 'bg-accent-soft/50' : drag ? '' : 'hover:bg-ink-850'
|
isSelected ? 'bg-accent-soft/50' : dragging ? '' : 'hover:bg-ink-850'
|
||||||
} ${isMoving ? 'opacity-40' : ''}`}
|
} ${isMoving ? 'opacity-40' : ''}`}
|
||||||
style={{ top: 0, transform: `translateY(${vr.start - bodyOffset.top}px)`, height: vr.size, width: '100%' }}
|
style={{ top: 0, transform: `translateY(${vr.start - bodyOffset.top}px)`, height: vr.size, width: '100%' }}
|
||||||
onMouseDown={(e) => {
|
onMouseDown={(e) => {
|
||||||
@@ -582,7 +575,7 @@ export function TrackTable({
|
|||||||
if (selection && (e.shiftKey || e.metaKey || e.ctrlKey)) e.preventDefault()
|
if (selection && (e.shiftKey || e.metaKey || e.ctrlKey)) e.preventDefault()
|
||||||
}}
|
}}
|
||||||
onPointerDown={(e) => {
|
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).
|
// Not from a control inside the row (play, stars, an edit field).
|
||||||
if ((e.target as HTMLElement).closest('button, input, textarea, select, a')) return
|
if ((e.target as HTMLElement).closest('button, input, textarea, select, a')) return
|
||||||
pressRef.current = { x: e.clientX, y: e.clientY, index: vr.index }
|
pressRef.current = { x: e.clientX, y: e.clientY, index: vr.index }
|
||||||
@@ -620,10 +613,10 @@ export function TrackTable({
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
{drag && (
|
{dropHint && (
|
||||||
<div
|
<div
|
||||||
className="pointer-events-none absolute left-0 z-10 h-0.5 w-full bg-accent"
|
className="pointer-events-none absolute left-0 z-10 h-0.5 w-full bg-accent"
|
||||||
style={{ top: drag.drop * ROW_HEIGHT - 1 }}
|
style={{ top: dropHint.drop * ROW_HEIGHT - 1 }}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -87,6 +87,13 @@ body,
|
|||||||
overscroll-behavior: none;
|
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 {
|
body {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
background: var(--color-ink-950);
|
background: var(--color-ink-950);
|
||||||
|
|||||||
@@ -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<H> {
|
||||||
|
/** 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<HTMLElement, { current: DropSpec<unknown> }>()
|
||||||
|
|
||||||
|
function set(next: Partial<State>) {
|
||||||
|
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<string, unknown>)[k] === (b as Record<string, unknown>)[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<HTMLElement>('[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<H>(spec: DropSpec<H>): [(el: HTMLElement | null) => void, H | null] {
|
||||||
|
const specRef = useRef(spec as DropSpec<unknown>)
|
||||||
|
specRef.current = spec as DropSpec<unknown>
|
||||||
|
const elRef = useRef<HTMLElement | null>(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(
|
||||||
|
<div
|
||||||
|
className="glass-overlay pointer-events-none fixed left-0 top-0 z-[90] flex max-w-72 flex-col gap-0.5 overflow-hidden rounded-xl px-3 py-1.5 text-xs shadow-lg"
|
||||||
|
style={{ transform: `translate(${s.x + 14}px, ${s.y + 12}px)` }}
|
||||||
|
>
|
||||||
|
<span className="flex min-w-0 items-center gap-1.5 text-text">
|
||||||
|
<Icon name={icon} size={13} className="shrink-0 text-muted" />
|
||||||
|
<span className="truncate">{text}</span>
|
||||||
|
</span>
|
||||||
|
{s.label && <span className="truncate text-[11px] text-accent">{s.label}</span>}
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import App from './App.tsx'
|
|||||||
import { UpdateCheck } from './components/UpdateDialog.tsx'
|
import { UpdateCheck } from './components/UpdateDialog.tsx'
|
||||||
import { AmbientBackdrop } from './components/AmbientBackdrop.tsx'
|
import { AmbientBackdrop } from './components/AmbientBackdrop.tsx'
|
||||||
import { ConfirmHost } from './lib/confirm.tsx'
|
import { ConfirmHost } from './lib/confirm.tsx'
|
||||||
|
import { DragLayer } from './lib/drag.tsx'
|
||||||
import { QuitGuard } from './components/QuitGuard.tsx'
|
import { QuitGuard } from './components/QuitGuard.tsx'
|
||||||
import { preventHistoryNavigation } from './lib/noNavigation.ts'
|
import { preventHistoryNavigation } from './lib/noNavigation.ts'
|
||||||
|
|
||||||
@@ -34,6 +35,8 @@ createRoot(document.getElementById('root')!).render(
|
|||||||
<ConfirmHost />
|
<ConfirmHost />
|
||||||
{/* Save · Discard · Cancel when quitting with unsaved changes. */}
|
{/* Save · Discard · Cancel when quitting with unsaved changes. */}
|
||||||
<QuitGuard />
|
<QuitGuard />
|
||||||
|
{/* The ghost under the cursor while dragging tracks or playlists. */}
|
||||||
|
<DragLayer />
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
</StrictMode>,
|
</StrictMode>,
|
||||||
)
|
)
|
||||||
Reference in new issue
Block a user