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

+12 -2
View File
@@ -49,7 +49,10 @@ Two independent apps that talk over HTTP:
(nothing changes, the count comes back so the UI can ask and resend); (nothing changes, the count comes back so the UI can ask and resend);
`add` only where `capabilities.playlists.duplicates` — Traktor only, since `add` only where `capabilities.playlists.duplicates` — Traktor only, since
OneLibrary's `playlist_content` is keyed on (playlist, content) and 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 - `capabilities.py` — `Capabilities`: what the loaded library can persist, so
the UI can gate controls instead of branching on the platform. the UI can gate controls instead of branching on the platform.
- `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over - `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 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, could not be dropped on. Targets: playlist + export rows (Sidebar,
ExportsSection), the tree's zones, the table's reorder, and the DECK 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 <playlist>" (`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 **Files from Finder / Explorer** (decided 2026-10-13) ride the same store
as a `files` payload: `lib/fileDrop.ts` feeds Tauri's `onDragDropEvent` as a `files` payload: `lib/fileDrop.ts` feeds Tauri's `onDragDropEvent`
(real paths; a plain browser has none, so no file drop there) through (real paths; a plain browser has none, so no file drop there) through
+6 -4
View File
@@ -317,6 +317,7 @@ def run(
folder_name: str | None = None, folder_name: str | None = None,
reference: bool = False, reference: bool = False,
into_playlist: str | None = None, into_playlist: str | None = None,
into_playlist_index: int | None = None,
) -> dict: ) -> dict:
"""Perform the import. Returns a summary dict for the job result. """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 `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 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 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 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 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…") handle.progress(message="Adding to the playlist…")
current = dest.playlist_entries(into_playlist) or [] current = dest.playlist_entries(into_playlist) or []
have = set(current) have = set(current)
dest.set_playlist_entries( fresh = [i for i in all_ids if i not in have]
into_playlist, current + [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( playlists_made = _rebuild_playlists(
source, dest, plan, by_source, folder_name, handle source, dest, plan, by_source, folder_name, handle
+4 -1
View File
@@ -1309,7 +1309,8 @@ def add_entries(playlist_uuid: str, body: AddEntries) -> dict:
return {"status": "duplicates", "id": playlist_uuid, "added": 0, return {"status": "duplicates", "id": playlist_uuid, "added": 0,
"duplicates": len(dupes), "count": len(current)} "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] 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), return {"status": "added", "id": playlist_uuid, "added": len(added),
"duplicates": len(dupes), "count": n} "duplicates": len(dupes), "count": n}
@@ -2572,6 +2573,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
source, dest, plan, handle, source, dest, plan, handle,
reference=in_place or body.mode == "reference", reference=in_place or body.mode == "reference",
into_playlist=body.playlist_id, 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 # 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. # updated after the library has been saved rather than inside it.
@@ -2658,6 +2660,7 @@ def start_import(body: ImportRequest) -> JobStatus:
def work(handle): def work(handle):
result = importer.run( result = importer.run(
source, dest, plan, handle, folder_name=folder_name, into_playlist=body.into_playlist, 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. # As folder add: an export set is Konduktor's data, updated afterwards.
if body.export_id is not None and library is not None: if body.export_id is not None and library is not None:
+5
View File
@@ -27,6 +27,9 @@ class AddEntries(BaseModel):
# where `playlists.duplicates`, else skipped), or "ask" — change nothing and # where `playlists.duplicates`, else skipped), or "ask" — change nothing and
# report how many, so the UI can ask and send again with skip/add. # report how many, so the UI can ask and send again with skip/add.
duplicates: Literal["skip", "add", "ask"] = "skip" 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): class MovePlaylist(BaseModel):
@@ -545,6 +548,7 @@ class ImportRequest(BaseModel):
# drop): every imported track — and every one the collection already # drop): every imported track — and every one the collection already
# holds — goes into it, as folder add does. # holds — goes into it, as folder add does.
into_playlist: str | None = None into_playlist: str | None = None
into_playlist_index: int | None = None # where in it (see AddEntries.index)
export_id: str | None = None export_id: str | None = None
@@ -613,6 +617,7 @@ class FolderAddRequest(BaseModel):
mode: Literal["copy", "reference"] mode: Literal["copy", "reference"]
destination: str | None = None # required for `copy` destination: str | None = None # required for `copy`
playlist_id: str | None = None playlist_id: str | None = None
playlist_index: int | None = None # where in it (see AddEntries.index)
export_id: str | None = None export_id: str | None = None
+5 -1
View File
@@ -181,7 +181,9 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
three_dir = music / "Deeper" three_dir = music / "Deeper"
c.get("/api/folder/tracks", params={"path": str(three_dir)}) c.get("/api/folder/tracks", params={"path": str(three_dir)})
dest = Path(tempfile.mkdtemp()) / "Imported" 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() p = c.post("/api/folder/add/preview", json=req).json()
check("the preview sizes the copy", p["total_bytes"] > 0, str(p)) check("the preview sizes the copy", p["total_bytes"] > 0, str(p))
job = wait(c, c.post("/api/folder/add", json=req).json()) 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", check("the entry points at the copy", a.audio_path(copied_id) == dest / "three.flac",
str(a.audio_path(copied_id))) str(a.audio_path(copied_id)))
check("the original is untouched", (three_dir / "three.flac").is_file()) 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", check("copy without a destination is refused",
c.post("/api/folder/add", json={"track_ids": [str(one)], "mode": "copy"}).status_code == 400) c.post("/api/folder/add", json={"track_ids": [str(one)], "mode": "copy"}).status_code == 400)
check("an unscanned file cannot be added", check("an unscanned file cannot be added",
+10
View File
@@ -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", r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json() json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json()
check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1) 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", check("capabilities say Traktor holds duplicates",
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True) client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
+4 -1
View File
@@ -511,7 +511,10 @@ with tempfile.TemporaryDirectory() as d:
_raises(lambda: adapter.set_cue_color(cue_track.id, 6, red), NotFound)) _raises(lambda: adapter.set_cue_color(cue_track.id, 6, red), NotFound))
print("== beatgrid edits ==") 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: if grid_track:
check("a gridded track starts with at least one marker", check("a gridded track starts with at least one marker",
len(adapter.track_cues(grid_track.id).grid_markers) >= 1) len(adapter.track_cues(grid_track.id).grid_markers) >= 1)
+15 -4
View File
@@ -172,9 +172,16 @@ with TestClient(main.app) as c:
got = ROOT / "folder-1.m4a" got = ROOT / "folder-1.m4a"
got.write_bytes(r.content) got.write_bytes(r.content)
check("…and serves them", r.status_code == 200 and np.array_equal(decode(got), decode(stem, 2))) 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"]} # All three files are HELD, and a held file's row IS the collection track
check("the listing marks the stem file as a stem track and the MP3 as audio", # (decided 2026-10-10): its id and media_kind are the collection's, so the
kinds.get(str(stem)) == "stem" and kinds.get(str(plain)) == "audio", str(kinds)) # MP3 whose entry carries <STEMS> 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 ==") print("== adding a stem file to the collection ==")
extra_dir = ROOT / "More" extra_dir = ROOT / "More"
@@ -182,7 +189,11 @@ with TestClient(main.app) as c:
extra = extra_dir / "Other.stem.m4a" extra = extra_dir / "Other.stem.m4a"
shutil.copy2(stem, extra) shutil.copy2(stem, extra)
extra_plain = make_mp3(extra_dir / "Other.mp3", seed=9) 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"] 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)], job = c.post("/api/folder/add", json={"track_ids": [str(extra), str(extra_plain)],
"mode": "reference", "playlist_id": pl_id}).json() "mode": "reference", "playlist_id": pl_id}).json()
+43 -7
View File
@@ -6,7 +6,7 @@ import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy' import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy'
import { invalidateTrackLists } from './lib/trackQueries' import { invalidateTrackLists } from './lib/trackQueries'
import { addTracksToPlaylist } from './lib/addTracks' 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 { 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 { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
import { confirmDiscardUnsaved } from './lib/unsaved' import { confirmDiscardUnsaved } from './lib/unsaved'
@@ -383,10 +383,10 @@ export default function App() {
// menu and the drag ask about duplicates alike. // menu and the drag ask about duplicates alike.
const duplicatesAllowed = !!capabilities.data?.playlists.duplicates const duplicatesAllowed = !!capabilities.data?.playlists.duplicates
const addToPlaylist = useCallback( const addToPlaylist = useCallback(
async (uuid: string, ids: string[]) => { async (uuid: string, ids: string[], index: number | null = null) => {
try { try {
const name = addablePlaylists.find((p) => p.id === uuid)?.name ?? 'playlist' 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) if (msg) notify('success', msg)
} catch (e) { } catch (e) {
onError((e as Error).message) 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. // 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) const held = r.tracks.filter((t) => r.files[t.id]).map((t) => t.id)
if (held.length === r.tracks.length) { 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 if (target) void addToExport(target.id, held)
else else
notify( notify(
@@ -473,7 +473,7 @@ export default function App() {
const files = folderFilesRef.current const files = folderFilesRef.current
// Rows that are all collection tracks already: nothing to add first. // Rows that are all collection tracks already: nothing to add first.
if (ids.every((id) => files[id])) { 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 void addToExport(target.id, ids)
} else setAdding({ ids: ids.map((id) => files[id] ?? id), target }) } else setAdding({ ids: ids.map((id) => files[id] ?? id), target })
} else if (origin === 'device') setImportDrop({ ids, target }) } else if (origin === 'device') setImportDrop({ ids, target })
@@ -666,6 +666,31 @@ export default function App() {
return find(playlists.data ?? []) return find(playlists.data ?? [])
}, [source, playlists.data]) }, [source, playlists.data])
const playlistEditable = canEdit && !!playlistNode?.can_reorder 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 // A playlist's own 1-based positions, so the # column still means "where in
// the playlist" once the view is sorted or filtered. // the playlist" once the view is sorted or filtered.
const playlistPositions = useMemo(() => { const playlistPositions = useMemo(() => {
@@ -1763,14 +1788,24 @@ export default function App() {
/> />
) )
) : tracks.length === 0 ? ( ) : 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-lg">This playlist is empty</div>
<div className="text-sm text-faint"> <div className="text-sm text-faint">
Go to <span className="text-text">All Tracks</span>, select tracks, and add them here. Go to <span className="text-text">All Tracks</span>, select tracks, and add them here.
</div> </div>
</div> </div>
) : filtered.length === 0 ? ( ) : 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-lg">No tracks match</div>
<div className="text-sm text-faint">Try clearing some filters.</div> <div className="text-sm text-faint">Try clearing some filters.</div>
</div> </div>
@@ -1787,6 +1822,7 @@ export default function App() {
: undefined : undefined
} }
onRemove={playlistEditable ? confirmRemoveFromPlaylist : undefined} onRemove={playlistEditable ? confirmRemoveFromPlaylist : undefined}
foreignDrop={playlistDrop}
dragFrom={{ dragFrom={{
origin: 'collection', origin: 'collection',
playlistId: playlistEditable && source.kind === 'playlist' ? source.id : undefined, 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 /** Every imported track (and any already held) also goes into this
* collection playlist / export — a drop of device tracks on one. */ * collection playlist / export — a drop of device tracks on one. */
into_playlist?: string | null into_playlist?: string | null
/** Where in it (a drop between rows); null appends. */
into_playlist_index?: number | null
export_id?: string | null export_id?: string | null
} }
@@ -533,6 +535,8 @@ export interface FolderAddRequest {
/** Required for `copy`. */ /** Required for `copy`. */
destination?: string | null destination?: string | null
playlist_id?: string | null playlist_id?: string | null
/** Where in it (a drop between rows); null appends. */
playlist_index?: number | null
export_id?: string | null export_id?: string | null
} }
@@ -1058,11 +1062,12 @@ export const api = {
/** Append tracks. `duplicates` decides tracks already there: skip them, /** Append tracks. `duplicates` decides tracks already there: skip them,
* add them again (where `playlists.duplicates`), or `ask` — nothing changes * add them again (where `playlists.duplicates`), or `ask` — nothing changes
* and the answer's `status: 'duplicates'` says how many, to ask and resend. */ * 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 }>( send<{ status: 'added' | 'duplicates'; added: number; duplicates: number; count: number }>(
'POST', 'POST',
`/api/playlists/${encodeURIComponent(nodeId)}/add`, `/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 /** Move a tree node to `index` among `parentId`'s children (null = top
* level), counted without it. Answers its id AFTER the move. */ * 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 — * 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 * 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 * 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 const POLL_MS = 300
@@ -47,6 +50,25 @@ export interface AddTarget {
kind: 'playlist' | 'export' kind: 'playlist' | 'export'
id: string id: string
name: 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 /** 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.` 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 qc = useQueryClient()
const { target, toggle } = usePlaylistToggle(requested)
// The LIBRARY's capabilities (this dialog is mounted outside the browsed // The LIBRARY's capabilities (this dialog is mounted outside the browsed
// view's swapped context). A library that places its own audio — a stick — // 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. // 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'), mode: places ? 'copy' : (mode ?? 'reference'),
destination: !places && mode === 'copy' ? folder : null, destination: !places && mode === 'copy' ? folder : null,
playlist_id: target?.kind === 'playlist' ? target.id : 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, 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"> <div className="space-y-4 px-5 py-4 text-sm">
{!job && ( {!job && (
<> <>
{toggle}
{target && ( {target && (
<div className="text-xs text-muted"> <div className="text-xs text-muted">
{target.kind === 'playlist' ? 'Playlists' : 'Exports'} hold tracks from your {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 { placedAudioSummary } from '../lib/platformCopy'
import type { AddTarget } from './AddFilesDialog' import type { AddTarget } from './AddFilesDialog'
import { FolderPicker } from './FolderPicker' import { FolderPicker } from './FolderPicker'
import { useServerImportFolder } from './AddFilesDialog' import { useServerImportFolder, usePlaylistToggle } from './AddFilesDialog'
/** /**
* Import a browsed device into the loaded collection. * Import a browsed device into the loaded collection.
@@ -41,8 +41,9 @@ interface Props {
onError: (msg: string) => void 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 qc = useQueryClient()
const { target, toggle } = usePlaylistToggle(requested)
// The BASE folder, and whether to put this device's audio in its own // 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 // 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 // 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 ?? [], track_ids: trackIds ?? [],
folder_name: deviceLabel, folder_name: deviceLabel,
into_playlist: target?.kind === 'playlist' ? target.id : null, 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, 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"> <div className="space-y-4 px-5 py-4 text-sm">
{!job && ( {!job && (
<> <>
{toggle}
{places && p && ( {places && p && (
<div className="rounded well px-3 py-2 text-xs text-muted"> <div className="rounded well px-3 py-2 text-xs text-muted">
{placedAudioSummary(caps.save, p.copied ?? 0, p.in_place ?? 0)} {placedAudioSummary(caps.save, p.copied ?? 0, p.in_place ?? 0)}
+25 -6
View File
@@ -30,7 +30,7 @@ import {
} from '@dnd-kit/sortable' } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities' import { CSS } from '@dnd-kit/utilities'
import type { Track, TrackOrigin } from '../api' 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 { hasMod } from '../lib/modKey'
import { TRACK_COLUMNS } from '../lib/trackColumns' import { TRACK_COLUMNS } from '../lib/trackColumns'
@@ -76,6 +76,11 @@ interface Props {
/** Where dragged rows come from: whose ids they are, and the editable /** 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. */ * playlist they leave on a Cmd/Ctrl-drag (move). Defaults to the collection. */
dragFrom?: { origin: TrackOrigin; playlistId?: string } 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. */ /** Delete/Backspace removes the selected tracks from this view. */
onRemove?: (ids: string[]) => void onRemove?: (ids: string[]) => void
/** `viewIds` is every row's id in the order shown (sorted, filtered). */ /** `viewIds` is every row's id in the order shown (sorted, filtered). */
@@ -285,6 +290,7 @@ export function TrackTable({
positions, positions,
marked, marked,
reorder, reorder,
foreignDrop,
dragFrom, dragFrom,
onRemove, onRemove,
onRowContextMenu, onRowContextMenu,
@@ -447,14 +453,25 @@ export function TrackTable({
} }
}, [tableKey]) }, [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) => { 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 const top = bodyRef.current?.getBoundingClientRect().top ?? 0
return { drop: Math.max(0, Math.min(rowsRef.current.length, Math.round((at.y - top) / ROW_HEIGHT))) } 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 }) => { 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 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((t) => !ids.has(t.id)) const kept = rs.filter((t) => !ids.has(t.id))
@@ -547,7 +564,9 @@ export function TrackTable({
<div <div
ref={scrollerRef} ref={scrollerRef}
data-drag-scroll={bodyOffset.header} 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) => { 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.
const t = e.target as HTMLElement const t = e.target as HTMLElement
@@ -621,7 +640,7 @@ export function TrackTable({
</div> </div>
) )
})} })}
{dropHint && ( {dropHint && dropHint.drop !== null && (
<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: dropHint.drop * ROW_HEIGHT - 1 }} 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 * elsewhere they are skipped and the message says so. Nothing is asked when
* there are none. * 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 * `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 * tracks are in the target they leave the source. Cancelling the duplicates
* question cancels the move too. * question cancels the move too.
@@ -25,9 +28,10 @@ export async function addTracksToPlaylist(opts: {
ids: string[] ids: string[]
duplicatesAllowed: boolean duplicatesAllowed: boolean
moveFrom?: string moveFrom?: string
index?: number | null
}): Promise<string | null> { }): Promise<string | null> {
const { qc, playlist, ids, duplicatesAllowed, moveFrom } = opts const { qc, playlist, ids, duplicatesAllowed, moveFrom, index = null } = opts
let res = await api.addEntries(playlist.id, ids, duplicatesAllowed ? 'ask' : 'skip') let res = await api.addEntries(playlist.id, ids, duplicatesAllowed ? 'ask' : 'skip', index)
if (res.status === 'duplicates') { if (res.status === 'duplicates') {
const fresh = ids.length - res.duplicates const fresh = ids.length - res.duplicates
const all = fresh === 0 const all = fresh === 0
@@ -47,7 +51,7 @@ export async function addTracksToPlaylist(opts: {
tone: 'primary', tone: 'primary',
}) })
if (choice === null) return null 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 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. */ /** What a playlist or export row takes: track rows, or files from the OS. */
export type TracksOrFiles = Exclude<DragPayload, { kind: 'node' }> 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 { export interface DropPoint {
x: number x: number
y: number y: number