Improved drag to import dialog

This commit is contained in:
patben8 committed 2026-10-17 22:53:37 +02:00
1 parent bf427a628e
commit 518542c7bb
15 files changed
+180 -35

No files matched your search

+43 -7
View File
@@ -6,7 +6,7 @@ import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy'
import { invalidateTrackLists } from './lib/trackQueries'
import { addTracksToPlaylist } from './lib/addTracks'
import { useDragPayload, useDropTarget } from './lib/drag'
import { isForeign, useDragPayload, useDropTarget, type TracksOrFiles } from './lib/drag'
import { useNativeFileDrop } from './lib/fileDrop'
import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
import { confirmDiscardUnsaved } from './lib/unsaved'
@@ -383,10 +383,10 @@ export default function App() {
// menu and the drag ask about duplicates alike.
const duplicatesAllowed = !!capabilities.data?.playlists.duplicates
const addToPlaylist = useCallback(
async (uuid: string, ids: string[]) => {
async (uuid: string, ids: string[], index: number | null = null) => {
try {
const name = addablePlaylists.find((p) => p.id === uuid)?.name ?? 'playlist'
const msg = await addTracksToPlaylist({ qc, playlist: { id: uuid, name }, ids, duplicatesAllowed })
const msg = await addTracksToPlaylist({ qc, playlist: { id: uuid, name }, ids, duplicatesAllowed, index })
if (msg) notify('success', msg)
} catch (e) {
onError((e as Error).message)
@@ -439,7 +439,7 @@ export default function App() {
// rows, nothing to add first — straight into the target, if there is one.
const held = r.tracks.filter((t) => r.files[t.id]).map((t) => t.id)
if (held.length === r.tracks.length) {
if (target?.kind === 'playlist') void addToPlaylist(target.id, held)
if (target?.kind === 'playlist') void addToPlaylist(target.id, held, target.index)
else if (target) void addToExport(target.id, held)
else
notify(
@@ -473,7 +473,7 @@ export default function App() {
const files = folderFilesRef.current
// Rows that are all collection tracks already: nothing to add first.
if (ids.every((id) => files[id])) {
if (target.kind === 'playlist') void addToPlaylist(target.id, ids)
if (target.kind === 'playlist') void addToPlaylist(target.id, ids, target.index)
else void addToExport(target.id, ids)
} else setAdding({ ids: ids.map((id) => files[id] ?? id), target })
} else if (origin === 'device') setImportDrop({ ids, target })
@@ -666,6 +666,31 @@ export default function App() {
return find(playlists.data ?? [])
}, [source, playlists.data])
const playlistEditable = canEdit && !!playlistNode?.can_reorder
// Files, a Files folder's rows or a device's dropped on the open playlist's
// table: added to the collection and — unless the dialog's tick is cleared —
// into this playlist at the insertion line (decided 2026-10-17). A library
// that cannot add tracks leaves the drop to App's root target, which says why.
const playlistDrop = useMemo(() => {
if (!playlistEditable || !canAddFiles || source.kind !== 'playlist' || !playlistNode?.can_add_tracks) return undefined
const { id, name } = playlistNode
return {
label: `Add to ${name}…`,
onDrop: (p: TracksOrFiles, index: number | null) => {
const target: AddTarget = { kind: 'playlist', id, name, index }
if (p.kind === 'files') void dropFiles(p.paths, target)
else if (p.origin === 'folder' || p.origin === 'device') addForeign(p.origin, p.ids, target)
},
}
}, [playlistEditable, canAddFiles, source, playlistNode, dropFiles, addForeign])
// The same where no table is drawn: an empty playlist, or filters hiding
// every row (never both at once, so they share the one target).
const [emptyDropRef, emptyDropOver] = useDropTarget<true>({
hint: (p) => (playlistDrop && isForeign(p) ? true : null),
label: () => playlistDrop?.label ?? null,
onDrop: (p) => {
if (isForeign(p)) playlistDrop?.onDrop(p, null)
},
})
// A playlist's own 1-based positions, so the # column still means "where in
// the playlist" once the view is sorted or filtered.
const playlistPositions = useMemo(() => {
@@ -1763,14 +1788,24 @@ export default function App() {
/>
)
) : tracks.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center gap-2 text-muted">
<div
ref={emptyDropRef}
className={`flex h-full flex-col items-center justify-center gap-2 text-muted ${
emptyDropOver ? 'rounded-lg outline-2 -outline-offset-2 outline-accent' : ''
}`}
>
<div className="text-lg">This playlist is empty</div>
<div className="text-sm text-faint">
Go to <span className="text-text">All Tracks</span>, select tracks, and add them here.
</div>
</div>
) : filtered.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center gap-1 text-muted">
<div
ref={emptyDropRef}
className={`flex h-full flex-col items-center justify-center gap-1 text-muted ${
emptyDropOver ? 'rounded-lg outline-2 -outline-offset-2 outline-accent' : ''
}`}
>
<div className="text-lg">No tracks match</div>
<div className="text-sm text-faint">Try clearing some filters.</div>
</div>
@@ -1787,6 +1822,7 @@ export default function App() {
: undefined
}
onRemove={playlistEditable ? confirmRemoveFromPlaylist : undefined}
foreignDrop={playlistDrop}
dragFrom={{
origin: 'collection',
playlistId: playlistEditable && source.kind === 'playlist' ? source.id : undefined,
+7 -2
View File
@@ -467,6 +467,8 @@ export interface ImportRequest {
/** Every imported track (and any already held) also goes into this
* collection playlist / export — a drop of device tracks on one. */
into_playlist?: string | null
/** Where in it (a drop between rows); null appends. */
into_playlist_index?: number | null
export_id?: string | null
}
@@ -533,6 +535,8 @@ export interface FolderAddRequest {
/** Required for `copy`. */
destination?: string | null
playlist_id?: string | null
/** Where in it (a drop between rows); null appends. */
playlist_index?: number | null
export_id?: string | null
}
@@ -1058,11 +1062,12 @@ export const api = {
/** Append tracks. `duplicates` decides tracks already there: skip them,
* add them again (where `playlists.duplicates`), or `ask` — nothing changes
* and the answer's `status: 'duplicates'` says how many, to ask and resend. */
addEntries: (nodeId: string, trackIds: string[], duplicates: 'skip' | 'add' | 'ask' = 'skip') =>
/** `index`: insert at this position among the current entries; null appends. */
addEntries: (nodeId: string, trackIds: string[], duplicates: 'skip' | 'add' | 'ask' = 'skip', index: number | null = null) =>
send<{ status: 'added' | 'duplicates'; added: number; duplicates: number; count: number }>(
'POST',
`/api/playlists/${encodeURIComponent(nodeId)}/add`,
{ track_ids: trackIds, duplicates },
{ track_ids: trackIds, duplicates, index },
),
/** Move a tree node to `index` among `parentId`'s children (null = top
* level), counted without it. Answers its id AFTER the move. */
+27 -2
View File
@@ -32,7 +32,10 @@ import { FolderPicker } from './FolderPicker'
* A playlist or export target still needs the files in the collection first —
* both hold collection track ids — so the dialog says so rather than doing it
* silently. Files the collection already holds are not added again, but still
* go into the target.
* go into the target. A PLAYLIST target can be unticked (`usePlaylistToggle`,
* on each time, never remembered — decided 2026-10-17): a drop on a playlist
* is usually meant for it, but a drop on its open table may only be "into
* the collection" aimed loosely.
*/
const POLL_MS = 300
@@ -47,6 +50,25 @@ export interface AddTarget {
kind: 'playlist' | 'export'
id: string
name: string
/** A playlist: insert at this position among its entries (a drop between
* its rows); absent appends. */
index?: number | null
}
/** The add dialogs' "Also add to <playlist>" tick: on, unless unticked this
* time. Answers the target actually in force (null = the collection only).
* Exports have no tick — "Add to export" is the whole of that gesture. */
export function usePlaylistToggle(requested: AddTarget | null | undefined) {
const [on, setOn] = useState(true)
const offered = requested?.kind === 'playlist'
const target = offered && !on ? null : (requested ?? null)
const toggle = offered ? (
<label className="flex cursor-pointer items-center gap-2 text-xs text-muted">
<input type="checkbox" checked={on} onChange={(e) => setOn(e.target.checked)} className="accent-accent" />
Also add to “{requested.name}”
</label>
) : null
return { target, toggle }
}
/** Where tracks headed for the collection come from: another library's or a
@@ -74,8 +96,9 @@ function removableWarning(p: FolderAddPreview, newCount: number): string {
return `${what} on ${where}. They will go missing from your collection whenever ${unplugged} unplugged.`
}
export function AddFilesDialog({ trackIds, target, note, onClose, onDone, onError }: Props) {
export function AddFilesDialog({ trackIds, target: requested, note, onClose, onDone, onError }: Props) {
const qc = useQueryClient()
const { target, toggle } = usePlaylistToggle(requested)
// The LIBRARY's capabilities (this dialog is mounted outside the browsed
// view's swapped context). A library that places its own audio — a stick —
// decides copy vs in place itself, so there is nothing to ask.
@@ -115,6 +138,7 @@ export function AddFilesDialog({ trackIds, target, note, onClose, onDone, onErro
mode: places ? 'copy' : (mode ?? 'reference'),
destination: !places && mode === 'copy' ? folder : null,
playlist_id: target?.kind === 'playlist' ? target.id : null,
playlist_index: target?.kind === 'playlist' ? (target.index ?? null) : null,
export_id: target?.kind === 'export' ? target.id : null,
}
@@ -255,6 +279,7 @@ export function AddFilesDialog({ trackIds, target, note, onClose, onDone, onErro
<div className="space-y-4 px-5 py-4 text-sm">
{!job && (
<>
{toggle}
{target && (
<div className="text-xs text-muted">
{target.kind === 'playlist' ? 'Playlists' : 'Exports'} hold tracks from your
+5 -2
View File
@@ -6,7 +6,7 @@ import { useCaps } from '../lib/capabilities'
import { placedAudioSummary } from '../lib/platformCopy'
import type { AddTarget } from './AddFilesDialog'
import { FolderPicker } from './FolderPicker'
import { useServerImportFolder } from './AddFilesDialog'
import { useServerImportFolder, usePlaylistToggle } from './AddFilesDialog'
/**
* Import a browsed device into the loaded collection.
@@ -41,8 +41,9 @@ interface Props {
onError: (msg: string) => void
}
export function ImportDialog({ playlistId, trackIds, target, deviceLabel, onClose, onDone, onError }: Props) {
export function ImportDialog({ playlistId, trackIds, target: requested, deviceLabel, onClose, onDone, onError }: Props) {
const qc = useQueryClient()
const { target, toggle } = usePlaylistToggle(requested)
// The BASE folder, and whether to put this device's audio in its own
// subfolder of it. Kept apart rather than as one path because they are two
// different decisions: where your music lives, and how one import is filed
@@ -91,6 +92,7 @@ export function ImportDialog({ playlistId, trackIds, target, deviceLabel, onClos
track_ids: trackIds ?? [],
folder_name: deviceLabel,
into_playlist: target?.kind === 'playlist' ? target.id : null,
into_playlist_index: target?.kind === 'playlist' ? (target.index ?? null) : null,
export_id: target?.kind === 'export' ? target.id : null,
}
@@ -203,6 +205,7 @@ export function ImportDialog({ playlistId, trackIds, target, deviceLabel, onClos
<div className="space-y-4 px-5 py-4 text-sm">
{!job && (
<>
{toggle}
{places && p && (
<div className="rounded well px-3 py-2 text-xs text-muted">
{placedAudioSummary(caps.save, p.copied ?? 0, p.in_place ?? 0)}
+25 -6
View File
@@ -30,7 +30,7 @@ import {
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import type { Track, TrackOrigin } from '../api'
import { beginDrag, useDragPayload, useDropTarget } from '../lib/drag'
import { beginDrag, isForeign, useDragPayload, useDropTarget, type TracksOrFiles } from '../lib/drag'
import { hasMod } from '../lib/modKey'
import { TRACK_COLUMNS } from '../lib/trackColumns'
@@ -76,6 +76,11 @@ interface Props {
/** Where dragged rows come from: whose ids they are, and the editable
* playlist they leave on a Cmd/Ctrl-drag (move). Defaults to the collection. */
dragFrom?: { origin: TrackOrigin; playlistId?: string }
/** Things from outside the library dropped on the table — files from the
* OS, a Files folder's or a device's rows — headed for this view's
* playlist. `index` is the insertion line while `reorder` is enabled (the
* rows ARE the entry list then), else null: appended. */
foreignDrop?: { label: string; onDrop: (p: TracksOrFiles, index: number | null) => void }
/** Delete/Backspace removes the selected tracks from this view. */
onRemove?: (ids: string[]) => void
/** `viewIds` is every row's id in the order shown (sorted, filtered). */
@@ -285,6 +290,7 @@ export function TrackTable({
positions,
marked,
reorder,
foreignDrop,
dragFrom,
onRemove,
onRowContextMenu,
@@ -447,14 +453,25 @@ export function TrackTable({
}
}, [tableKey])
const [dropRef, dropHint] = useDropTarget<{ drop: number }>({
// The table's own rows (reorder) and, where `foreignDrop` is given,
// things from outside the library (see the prop).
const foreignDropRef = useRef(foreignDrop)
foreignDropRef.current = foreignDrop
const [dropRef, dropHint] = useDropTarget<{ drop: number | null }>({
hint: (p, at) => {
if (p.kind !== 'tracks' || p.source !== tableKey || !reorderRef.current?.enabled) return null
const own = p.kind === 'tracks' && p.source === tableKey
if (!own && !(foreignDropRef.current && isForeign(p))) return null
if (!reorderRef.current?.enabled) return own ? null : { drop: 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))) }
},
label: (p) => (p.kind === 'tracks' && p.source === tableKey ? null : (foreignDropRef.current?.label ?? null)),
onDrop: (p, { drop }) => {
if (p.kind !== 'tracks') return
if (p.kind !== 'tracks' || p.source !== tableKey) {
if (isForeign(p)) foreignDropRef.current?.onDrop(p, drop)
return
}
if (drop === null) return
const ids = new Set(p.ids)
const rs = rowsRef.current.map((r) => r.original)
const kept = rs.filter((t) => !ids.has(t.id))
@@ -547,7 +564,9 @@ export function TrackTable({
<div
ref={scrollerRef}
data-drag-scroll={bodyOffset.header}
className="h-full overflow-auto px-1.5"
className={`h-full overflow-auto px-1.5 ${
dropHint && dropHint.drop === null ? 'rounded-lg outline-2 -outline-offset-2 outline-accent' : ''
}`}
onClick={(e) => {
// A click in the empty space below the rows clears the selection.
const t = e.target as HTMLElement
@@ -621,7 +640,7 @@ export function TrackTable({
</div>
)
})}
{dropHint && (
{dropHint && dropHint.drop !== null && (
<div
className="pointer-events-none absolute left-0 z-10 h-0.5 w-full bg-accent"
style={{ top: dropHint.drop * ROW_HEIGHT - 1 }}
+7 -3
View File
@@ -13,6 +13,9 @@ const plural = (n: number) => `${n} track${n === 1 ? '' : 's'}`
* elsewhere they are skipped and the message says so. Nothing is asked when
* there are none.
*
* `index` inserts them at that position (a drop between a playlist's rows);
* without it they are appended.
*
* `moveFrom` is a Cmd/Ctrl-drag out of another (editable) playlist: once the
* tracks are in the target they leave the source. Cancelling the duplicates
* question cancels the move too.
@@ -25,9 +28,10 @@ export async function addTracksToPlaylist(opts: {
ids: string[]
duplicatesAllowed: boolean
moveFrom?: string
index?: number | null
}): Promise<string | null> {
const { qc, playlist, ids, duplicatesAllowed, moveFrom } = opts
let res = await api.addEntries(playlist.id, ids, duplicatesAllowed ? 'ask' : 'skip')
const { qc, playlist, ids, duplicatesAllowed, moveFrom, index = null } = opts
let res = await api.addEntries(playlist.id, ids, duplicatesAllowed ? 'ask' : 'skip', index)
if (res.status === 'duplicates') {
const fresh = ids.length - res.duplicates
const all = fresh === 0
@@ -47,7 +51,7 @@ export async function addTracksToPlaylist(opts: {
tone: 'primary',
})
if (choice === null) return null
res = await api.addEntries(playlist.id, ids, choice === 'alt' || all ? 'add' : 'skip')
res = await api.addEntries(playlist.id, ids, choice === 'alt' || all ? 'add' : 'skip', index)
}
let moved = false
+5
View File
@@ -52,6 +52,11 @@ export type DragPayload =
/** What a playlist or export row takes: track rows, or files from the OS. */
export type TracksOrFiles = Exclude<DragPayload, { kind: 'node' }>
/** From outside the library: files from the OS, or a Files folder's or a
* device's rows — what has to be ADDED before a playlist can hold it. */
export const isForeign = (p: DragPayload): p is TracksOrFiles =>
p.kind === 'files' || (p.kind === 'tracks' && (p.origin === 'folder' || p.origin === 'device'))
export interface DropPoint {
x: number
y: number