From 518542c7bb940384cdc0a0cf23413d45ef39cb7c Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Sat, 17 Oct 2026 22:52:59 +0200 Subject: [PATCH] Improved drag to import dialog --- CLAUDE.md | 14 +++++- backend/konduktor/importer.py | 10 +++-- backend/konduktor/main.py | 5 ++- backend/konduktor/schemas.py | 5 +++ backend/test_folders.py | 6 ++- backend/test_phase3.py | 10 +++++ backend/test_rekordbox_adapter.py | 5 ++- backend/test_stem_playback.py | 19 ++++++-- frontend/src/App.tsx | 50 +++++++++++++++++++--- frontend/src/api.ts | 9 +++- frontend/src/components/AddFilesDialog.tsx | 29 ++++++++++++- frontend/src/components/ImportDialog.tsx | 7 ++- frontend/src/components/TrackTable.tsx | 31 +++++++++++--- frontend/src/lib/addTracks.ts | 10 +++-- frontend/src/lib/drag.tsx | 5 +++ 15 files changed, 180 insertions(+), 35 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a3cb70f..7611846 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -49,7 +49,10 @@ Two independent apps that talk over HTTP: (nothing changes, the count comes back so the UI can ask and resend); `add` only where `capabilities.playlists.duplicates` — Traktor only, since OneLibrary's `playlist_content` is keyed on (playlist, content) and - rekordbox's tolerance of a repeat is unmeasured. + rekordbox's tolerance of a repeat is unmeasured. An optional `index` + inserts among the CURRENT entries (a drop between a table's rows); + folder add (`playlist_index`) and device import (`into_playlist_index`) + take the same. - `capabilities.py` — `Capabilities`: what the loaded library can persist, so the UI can gate controls instead of branching on the platform. - `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over @@ -955,7 +958,14 @@ Two independent apps that talk over HTTP: 20 px edge after a 250 ms dwell — any less and the first/last visible row could not be dropped on. Targets: playlist + export rows (Sidebar, ExportsSection), the tree's zones, the table's reorder, and the DECK - (App), which loads the grabbed row paused, in its own origin. + (App), which loads the grabbed row paused, in its own origin. An open + editable playlist's TABLE (and its empty / no-match state) also takes + files and Files/device rows (`TrackTable.foreignDrop`, `drag.isForeign`; + decided 2026-10-17): the add dialog opens with the playlist as target at + the insertion line — appended while sorted/filtered — and both add + dialogs offer "Also add to " (`usePlaylistToggle`), ticked + every time, never remembered; unticked = the collection only. Wherever + a playlist is the target, the sidebar's drop included. **Files from Finder / Explorer** (decided 2026-10-13) ride the same store as a `files` payload: `lib/fileDrop.ts` feeds Tauri's `onDragDropEvent` (real paths; a plain browser has none, so no file drop there) through diff --git a/backend/konduktor/importer.py b/backend/konduktor/importer.py index 69decb5..ecb0add 100644 --- a/backend/konduktor/importer.py +++ b/backend/konduktor/importer.py @@ -317,6 +317,7 @@ def run( folder_name: str | None = None, reference: bool = False, into_playlist: str | None = None, + into_playlist_index: int | None = None, ) -> dict: """Perform the import. Returns a summary dict for the job result. @@ -332,7 +333,8 @@ def run( `reference` adds each file WHERE IT IS instead of copying it, so there is no destination and nothing to roll back. `into_playlist` appends every planned track — the new ones and those the destination already held — to one of the - destination's playlists before the save, so both land in one commit. + destination's playlists before the save, so both land in one commit; + `into_playlist_index` inserts them there instead (a drop between rows). A destination that PLACES ITS OWN AUDIO (`tracks.places_audio`: a OneLibrary stick) overrides both: `dest.place_audio` names each copy's target, or says @@ -446,9 +448,9 @@ def run( handle.progress(message="Adding to the playlist…") current = dest.playlist_entries(into_playlist) or [] have = set(current) - dest.set_playlist_entries( - into_playlist, current + [i for i in all_ids if i not in have] - ) + fresh = [i for i in all_ids if i not in have] + at = len(current) if into_playlist_index is None else max(0, min(len(current), into_playlist_index)) + dest.set_playlist_entries(into_playlist, current[:at] + fresh + current[at:]) playlists_made = _rebuild_playlists( source, dest, plan, by_source, folder_name, handle diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index ef2df1c..d48cfe0 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -1309,7 +1309,8 @@ def add_entries(playlist_uuid: str, body: AddEntries) -> dict: return {"status": "duplicates", "id": playlist_uuid, "added": 0, "duplicates": len(dupes), "count": len(current)} added = list(body.track_ids) if mode == "add" else [t for t in body.track_ids if t not in have] - n = a.set_playlist_entries(playlist_uuid, current + added) if added else len(current) + at = len(current) if body.index is None else max(0, min(len(current), body.index)) + n = a.set_playlist_entries(playlist_uuid, current[:at] + added + current[at:]) if added else len(current) return {"status": "added", "id": playlist_uuid, "added": len(added), "duplicates": len(dupes), "count": n} @@ -2572,6 +2573,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus: source, dest, plan, handle, reference=in_place or body.mode == "reference", into_playlist=body.playlist_id, + into_playlist_index=body.playlist_index, ) # Export sets are Konduktor's own data, not the library's, so they are # updated after the library has been saved rather than inside it. @@ -2658,6 +2660,7 @@ def start_import(body: ImportRequest) -> JobStatus: def work(handle): result = importer.run( source, dest, plan, handle, folder_name=folder_name, into_playlist=body.into_playlist, + into_playlist_index=body.into_playlist_index, ) # As folder add: an export set is Konduktor's data, updated afterwards. if body.export_id is not None and library is not None: diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 965358a..30f8c9d 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -27,6 +27,9 @@ class AddEntries(BaseModel): # where `playlists.duplicates`, else skipped), or "ask" — change nothing and # report how many, so the UI can ask and send again with skip/add. duplicates: Literal["skip", "add", "ask"] = "skip" + # Insert at this position among the playlist's CURRENT entries (a drop + # between rows); None appends. Clamped to the list. + index: int | None = None class MovePlaylist(BaseModel): @@ -545,6 +548,7 @@ class ImportRequest(BaseModel): # drop): every imported track — and every one the collection already # holds — goes into it, as folder add does. into_playlist: str | None = None + into_playlist_index: int | None = None # where in it (see AddEntries.index) export_id: str | None = None @@ -613,6 +617,7 @@ class FolderAddRequest(BaseModel): mode: Literal["copy", "reference"] destination: str | None = None # required for `copy` playlist_id: str | None = None + playlist_index: int | None = None # where in it (see AddEntries.index) export_id: str | None = None diff --git a/backend/test_folders.py b/backend/test_folders.py index ee8d443..8f9a836 100644 --- a/backend/test_folders.py +++ b/backend/test_folders.py @@ -181,7 +181,9 @@ with TestClient(main.app, raise_server_exceptions=False) as c: three_dir = music / "Deeper" c.get("/api/folder/tracks", params={"path": str(three_dir)}) dest = Path(tempfile.mkdtemp()) / "Imported" - req = {"track_ids": [str(three_dir / "three.flac")], "mode": "copy", "destination": str(dest)} + # Dropped between the playlist's rows: inserted there, not appended. + req = {"track_ids": [str(three_dir / "three.flac")], "mode": "copy", "destination": str(dest), + "playlist_id": playlist, "playlist_index": 1} p = c.post("/api/folder/add/preview", json=req).json() check("the preview sizes the copy", p["total_bytes"] > 0, str(p)) job = wait(c, c.post("/api/folder/add", json=req).json()) @@ -191,6 +193,8 @@ with TestClient(main.app, raise_server_exceptions=False) as c: check("the entry points at the copy", a.audio_path(copied_id) == dest / "three.flac", str(a.audio_path(copied_id))) check("the original is untouched", (three_dir / "three.flac").is_file()) + check("it went into the playlist AT the index", a.playlist_entries(playlist) == [added, copied_id, new], + str(a.playlist_entries(playlist))) check("copy without a destination is refused", c.post("/api/folder/add", json={"track_ids": [str(one)], "mode": "copy"}).status_code == 400) check("an unscanned file cannot be added", diff --git a/backend/test_phase3.py b/backend/test_phase3.py index 1ffed2c..b88f55d 100644 --- a/backend/test_phase3.py +++ b/backend/test_phase3.py @@ -191,6 +191,16 @@ check("'add' adds it again (Traktor can hold a track twice)", r["added"] == 1 an r = client.post(f"/api/playlists/{target}/add", json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json() check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1) +more = [t["id"] for t in client.get("/api/tracks", params={"limit": 50}).json()["items"] + if t["id"] not in track_ids][:2] +before = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] +r = client.post(f"/api/playlists/{target}/add", json={"track_ids": more[:1], "index": 1}).json() +after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] +check("an index inserts there (a drop between rows)", + r["added"] == 1 and after == before[:1] + more[:1] + before[1:]) +client.post(f"/api/playlists/{target}/add", json={"track_ids": more[1:2], "index": 999}) +after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()] +check("an index past the end appends", after[-1] == more[1]) check("capabilities say Traktor holds duplicates", client.get("/api/capabilities").json()["playlists"]["duplicates"] is True) diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index 439dc53..aec5450 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -511,7 +511,10 @@ with tempfile.TemporaryDirectory() as d: _raises(lambda: adapter.set_cue_color(cue_track.id, 6, red), NotFound)) print("== beatgrid edits ==") - grid_track = next((t for t in adapter.tracks if t.bpm), None) + # Long enough for a marker at 60 s: a grid is stored per beat, only up to + # the track's end, and the library's first BPM track became a 1 s Sampler + # WAV ("House 1"), where a marker at 60 s simply vanished. + grid_track = next((t for t in adapter.tracks if t.bpm and (t.length or 0) >= 90), None) if grid_track: check("a gridded track starts with at least one marker", len(adapter.track_cues(grid_track.id).grid_markers) >= 1) diff --git a/backend/test_stem_playback.py b/backend/test_stem_playback.py index 758ea7d..22c005d 100644 --- a/backend/test_stem_playback.py +++ b/backend/test_stem_playback.py @@ -172,9 +172,16 @@ with TestClient(main.app) as c: got = ROOT / "folder-1.m4a" got.write_bytes(r.content) check("…and serves them", r.status_code == 200 and np.array_equal(decode(got), decode(stem, 2))) - kinds = {t["id"]: t["media_kind"] for t in listing.json()["tracks"]} - check("the listing marks the stem file as a stem track and the MP3 as audio", - kinds.get(str(stem)) == "stem" and kinds.get(str(plain)) == "audio", str(kinds)) + # All three files are HELD, and a held file's row IS the collection track + # (decided 2026-10-10): its id and media_kind are the collection's, so the + # MP3 whose entry carries lists as a stem track. What the FILE says + # is checked on loose files below. + body = listing.json() + kinds = {t["id"]: t["media_kind"] for t in body["tracks"]} + check("held files list as their collection tracks, mapped back to the files", + body["files"].get(stem_id) == str(stem) and body["files"].get(tagged_id) == str(tagged), str(body["files"])) + check("…with the collection's media kind", + kinds.get(tagged_id) == "stem" and kinds.get(plain_id) == "audio", str(kinds)) print("== adding a stem file to the collection ==") extra_dir = ROOT / "More" @@ -182,7 +189,11 @@ with TestClient(main.app) as c: extra = extra_dir / "Other.stem.m4a" shutil.copy2(stem, extra) extra_plain = make_mp3(extra_dir / "Other.mp3", seed=9) - assert c.get("/api/folder/tracks", params={"path": str(extra_dir)}).status_code == 200 + loose = c.get("/api/folder/tracks", params={"path": str(extra_dir)}) + assert loose.status_code == 200 + kinds = {t["id"]: t["media_kind"] for t in loose.json()["tracks"]} + check("a LOOSE stem file lists as a stem track (its box), the MP3 beside it as audio", + kinds.get(str(extra)) == "stem" and kinds.get(str(extra_plain)) == "audio", str(kinds)) pl_id = c.post("/api/playlists", json={"name": "Stem Adds"}).json()["id"] job = c.post("/api/folder/add", json={"track_ids": [str(extra), str(extra_plain)], "mode": "reference", "playlist_id": pl_id}).json() diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 02ca0f3..9f48c59 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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({ + 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 ? ( -
+
This playlist is empty
Go to All Tracks, select tracks, and add them here.
) : filtered.length === 0 ? ( -
+
No tracks match
Try clearing some filters.
@@ -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, diff --git a/frontend/src/api.ts b/frontend/src/api.ts index eec4a49..2ee17d5 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -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. */ diff --git a/frontend/src/components/AddFilesDialog.tsx b/frontend/src/components/AddFilesDialog.tsx index f707bdb..91ac891 100644 --- a/frontend/src/components/AddFilesDialog.tsx +++ b/frontend/src/components/AddFilesDialog.tsx @@ -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 " 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 ? ( + + ) : 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
{!job && ( <> + {toggle} {target && (
{target.kind === 'playlist' ? 'Playlists' : 'Exports'} hold tracks from your diff --git a/frontend/src/components/ImportDialog.tsx b/frontend/src/components/ImportDialog.tsx index fb495ed..87cc1e2 100644 --- a/frontend/src/components/ImportDialog.tsx +++ b/frontend/src/components/ImportDialog.tsx @@ -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
{!job && ( <> + {toggle} {places && p && (
{placedAudioSummary(caps.save, p.copied ?? 0, p.in_place ?? 0)} diff --git a/frontend/src/components/TrackTable.tsx b/frontend/src/components/TrackTable.tsx index e09bd85..c1df37f 100644 --- a/frontend/src/components/TrackTable.tsx +++ b/frontend/src/components/TrackTable.tsx @@ -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({
{ // 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({
) })} - {dropHint && ( + {dropHint && dropHint.drop !== null && (
`${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 { - 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 diff --git a/frontend/src/lib/drag.tsx b/frontend/src/lib/drag.tsx index 6b5c35c..acbd2f3 100644 --- a/frontend/src/lib/drag.tsx +++ b/frontend/src/lib/drag.tsx @@ -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 +/** 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