Implemented drag and drop loading

This commit is contained in:
patben8 committed 2026-10-06 23:08:34 +02:00
1 parent 7ba71981c8
commit c87444bda5
12 files changed
+267 -34

No files matched your search

+72 -5
View File
@@ -35,6 +35,21 @@ Two independent apps that talk over HTTP:
- `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the - `adapter.py` — the `LibraryAdapter` / `LibraryDriver` protocols and the
error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422), error tree (`NotFound` → 404, `InvalidCommand` → 400, `Unsupported` → 422),
mapped to status codes once in `main.py` rather than per route. mapped to status codes once in `main.py` rather than per route.
**`move_playlist(node_id, parent_id, index)`** (sidebar drag and drop,
`POST /api/playlists/move`) moves any tree node; `index` counts the new
parent's children WITHOUT the node, and it returns the node's id AFTER
the move — a Traktor folder's / smart playlist's id is its path, so it
changes (playlists keep their UUID, so export sets never need
retargeting). Gated per node on `PlaylistNode.can_move`. Traktor refuses a
folder or smart playlist landing beside a namesake (as rename does);
Rekordbox renumbers `Seq` itself (pyrekordbox's version cannot move to the
top level) and keeps `masterPlaylists6.xml`'s `ParentId` in step;
OneLibrary renumbers `sequenceNo` from 0, and the pdb follows at Save.
`POST /api/playlists/{id}/add` takes `duplicates`: `skip` / `add` / `ask`
(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.
- `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
@@ -811,6 +826,21 @@ Two independent apps that talk over HTTP:
space below the rows creates at the top level, and the new node is named space below the rows creates at the top level, and the new node is named
in place (Esc or an empty name creates nothing). Rename/Delete are on the in place (Esc or an empty name creates nothing). Rename/Delete are on the
same menu and the row's hover buttons, which share one set of actions. same menu and the row's hover buttons, which share one set of actions.
**Drag and drop** (lib/drag.tsx, below): a row is a drag source and a drop
target with ZONES — a playlist's upper/lower half is before/after; a
folder's top/bottom quarter before/after and its middle INTO (appended),
except the bottom quarter of an OPEN folder, which is "first inside"; the
empty space below the rows is "end of the top level". Never into the
dragged node's own subtree, and a drop that would change nothing shows no
indicator. Holding over a collapsed folder opens it after 0.6 s (tracks
too, so nested playlists are reachable). Tracks dropped on a playlist go
through `lib/addTracks.ts` — shared with the context menu's "Add to" —
which ASKS about duplicates where the platform can hold them (decided:
ask each time), and Option/Alt moves them out of the editable playlist
they came from. A device's or Files folder's tracks open `ImportDialog`
(`trackIds` + `target`) / `AddFilesDialog` with the target filled in
(`onAddForeign`), so copy-vs-reference is still asked. Export rows take the
collection's tracks and any playlist/folder (as "Add to export" does).
A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE` A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE`
playlist routes take a `:path` param, a folder name may not contain `/`, playlist routes take a `:path` param, a folder name may not contain `/`,
and renaming onto a sibling folder's name is refused), `QuitGuard` (mounted in `main.tsx`: the desktop shell PREVENTS window close / and renaming onto a sibling folder's name is refused), `QuitGuard` (mounted in `main.tsx`: the desktop shell PREVENTS window close /
@@ -838,7 +868,28 @@ Two independent apps that talk over HTTP:
not dnd-kit sortable**: a SortableContext around the virtualizer loops on its not dnd-kit sortable**: a SortableContext around the virtualizer loops on its
flushSync-driven measurement — which is why playlists were once a separate, flushSync-driven measurement — which is why playlists were once a separate,
non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.) pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.
Every table's rows are a DRAG SOURCE through `lib/drag.tsx` (a selected row
carries the selection, the payload's `lead` is the row grabbed, `dragFrom`
says whose ids they are and which editable playlist an Option-drag leaves);
the in-table reorder is just the table's own drop target.)
**`lib/drag.tsx` — drag and drop across the window** (decided 2026-10-06,
[the discussion](.claude/discussions/discuss-drag-and-drop-2026-10-06.md)):
ONE gesture, the TARGET decides what it means. Pointer events, NOT HTML5
DnD — Tauri's webview captures native drag events for file drops on
Windows. A source calls `beginDrag` past a 6 px threshold (`usePressToDrag`
for plain elements); targets register with `useDropTarget({ hint, label,
onDrop })` and are found by `elementFromPoint` then up the ancestors, the
innermost whose `hint` is non-null winning, so a target declines a spot by
returning null. A module-level store read through narrow
`useSyncExternalStore` selectors: a move re-renders only the target under
the pointer and the ghost (`DragLayer`, mounted in main.tsx), never the
table. Esc cancels (before every other Esc handler); the click after a drop
is swallowed; `data-drag-scroll="<top inset>"` makes an element scroll at a
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.
`ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where = `ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where =
Replace the originals (its option STATES that Save deletes them, since Replace the originals (its option STATES that Save deletes them, since
the choice is remembered and may be preselected) or Save to a folder; In the choice is remembered and may be preselected) or Save to a folder; In
@@ -1055,10 +1106,17 @@ serialization path.** It enforces:
KEY attribute and one `<MUSICAL_KEY>` between LOUDNESS and CUE_V2 in KEY attribute and one `<MUSICAL_KEY>` between LOUDNESS and CUE_V2 in
Traktor's layout; the encoding matches the real collection; a Camelot Traktor's layout; the encoding matches the real collection; a Camelot
collection gets Camelot; an ADDED Pioneer key ("Abm") lands as "6m"; and the collection gets Camelot; an ADDED Pioneer key ("Abm") lands as "6m"; and the
key tag reaches TKEY / `initialkey` in MP3, FLAC and M4A. key tag reaches TKEY / `initialkey` in MP3, FLAC and M4A. And
**`move_playlist`** (O): the COLLECTION is untouched, a move round-trips and
moving back is byte-identical; a folder moves with its subtree and answers
its new path id; into its own descendant / beside a namesake is refused with
nothing changed; a smart playlist moves by its path id; a no-op is not dirty.
The guard that catches serialization regressions like the lxml reformatting bug. The guard that catches serialization regressions like the lxml reformatting bug.
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. Traktor-valid, backup-first, COLLECTION byte-identical, original untouched;
plus the drag-and-drop routes: `/add`'s three `duplicates` modes (`ask`
changes nothing and counts) and `/api/playlists/move` (path id answered,
400 into itself, 404 unknown).
- `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated - `test_timebase.py` — Traktor's MP3 time base: `mp3_gapless` on generated
MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset MP3s (header found after a 1 MB ID3 tag; header-less has none), the offset
in samples (2257 at 44.1 and 48 kHz, 0 header-less / WAV / missing), every in samples (2257 at 44.1 and 48 kHz, 0 header-less / WAV / missing), every
@@ -1126,7 +1184,9 @@ serialization path.** It enforces:
against SQLite). Asserts a no-op save changes zero rows; a one-field edit against SQLite). Asserts a no-op save changes zero rows; a one-field edit
changes exactly two — the track and `agentRegistry.localUpdateCount` — with the changes exactly two — the track and `agentRegistry.localUpdateCount` — with the
counter up by one and the edited row stamped with it; edits are invisible on counter up by one and the edited row stamped with it; edits are invisible on
disk until save; and playlist create/fill/rename/delete round-trip. And disk until save; and playlist create/fill/rename/delete round-trip, and
`move_playlist` (E2) changes only `djmdPlaylist` rows + the counter with
`Seq` 1..n in both parents. And
**removing a track** deletes exactly the rows Rekordbox 7 deletes (measured **removing a track** deletes exactly the rows Rekordbox 7 deletes (measured
2026-10-01 by diffing a removal made in Rekordbox itself: `djmdContent`, 2026-10-01 by diffing a removal made in Rekordbox itself: `djmdContent`,
`djmdCue`, `contentCue`, `contentFile`, `djmdMixerParam`, `djmdSongPlaylist` `djmdCue`, `contentCue`, `contentFile`, `djmdMixerParam`, `djmdSongPlaylist`
@@ -1165,7 +1225,8 @@ serialization path.** It enforces:
changes zero rows, a title edit exactly `content.title` (no counter, as changes zero rows, a title edit exactly `content.title` (no counter, as
rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with rekordbox), dates as `YYYY-MM-DD` text, lookups found-or-created with
`nameForSearch` NULL, a new playlist on top with siblings shifted, entries `nameForSearch` NULL, a new playlist on top with siblings shifted, entries
from 1; and the stick hazards — another app's write refused, an unplugged from 1, a move changing only parent + `sequenceNo` (0..n-1 in both
parents); and the stick hazards — another app's write refused, an unplugged
drive keeps the edits, stale `-shm` deleted, the backup holds the old rows, drive keeps the edits, stale `-shm` deleted, the backup holds the old rows,
the drive never held open, file tags written (title yes, rating no). And the drive never held open, file tags written (title yes, rating no). And
`set_key`: an existing key changes only `content.key_id` and reaches TKEY as `set_key`: an existing key changes only `content.key_id` and reaches TKEY as
@@ -1202,6 +1263,9 @@ serialization path.** It enforces:
companion cue is invented), that the existing 8,485 entries render companion cue is invented), that the existing 8,485 entries render
byte-identically, that the job registry runs/fails/cancels, and that a byte-identically, that the job registry runs/fails/cancels, and that a
cancelled import leaves **no orphaned audio and an untouched collection**. cancelled import leaves **no orphaned audio and an untouched collection**.
And the route with chosen `track_ids` + `into_playlist` + `export_id` (a
device drop): only that track, into the playlist and the export, no drive
folder made.
- `test_grid_detect.py` — beatgrid detection on **synthetic** audio, so the - `test_grid_detect.py` — beatgrid detection on **synthetic** audio, so the
tempo and first beat are known rather than borrowed from another analyser: tempo and first beat are known rather than borrowed from another analyser:
exact integer and non-integer BPMs, the 125 BPM the old detector could not exact integer and non-integer BPMs, the 125 BPM the old detector could not
@@ -1899,6 +1963,9 @@ that number and nothing else — everything derives from it:
yet**, since nothing can be written. Note the OneLibrary work already demonstrated yet**, since nothing can be written. Note the OneLibrary work already demonstrated
creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql` creating an `exportLibrary.db` from nothing, and `fixtures/onelibrary/schema.sql`
is the DDL to do it with. is the DDL to do it with.
- ✅ **Drag and drop** (2026-10-06) — tracks onto playlists / exports / the
deck, playlists around the tree and onto exports; see `lib/drag.tsx` and
the Sidebar under Architecture.
- ✅ **Remote libraries** (2026-10-02) — a Konduktor server in a container - ✅ **Remote libraries** (2026-10-02) — a Konduktor server in a container
(TrueNAS) holds a Traktor or Rekordbox library; the app opens it as (TrueNAS) holds a Traktor or Rekordbox library; the app opens it as
"Remote": browse, prep, edit, Save (versioned on the server), export sticks, "Remote": browse, prep, edit, Save (versioned on the server), export sticks,
+11 -4
View File
@@ -2445,11 +2445,18 @@ def start_import(body: ImportRequest) -> JobStatus:
folder_name = body.folder_name folder_name = body.folder_name
if folder_name is None and STATE.source is not None: if folder_name is None and STATE.source is not None:
folder_name = STATE.source.capabilities().save.library_label folder_name = STATE.source.capabilities().save.library_label
library = STATE.library_id
job = JOBS.submit( def work(handle):
"import", result = importer.run(
lambda handle: importer.run(source, dest, plan, handle, folder_name=folder_name), source, dest, plan, handle, folder_name=folder_name, into_playlist=body.into_playlist,
) )
# As folder add: an export set is Konduktor's data, updated afterwards.
if body.export_id is not None and library is not None:
exports.add(library, body.export_id, track_ids=result["track_ids"])
return result
job = JOBS.submit("import", work)
return JobStatus(**job.as_dict()) return JobStatus(**job.as_dict())
+5
View File
@@ -507,6 +507,11 @@ class ImportRequest(BaseModel):
# Playlists land in a folder named after the drive. Null keeps them at the # Playlists land in a folder named after the drive. Null keeps them at the
# root; the default is filled in from the source's label. # root; the default is filled in from the source's label.
folder_name: str | None = None folder_name: str | None = None
# Device tracks dropped on a collection playlist / an export (drag and
# drop): every imported track — and every one the collection already
# holds — goes into it, as folder add does.
into_playlist: str | None = None
export_id: str | None = None
class Drive(BaseModel): class Drive(BaseModel):
+37
View File
@@ -447,6 +447,43 @@ check("re-importing flags the tracks as already present",
check("but does not refuse them — the user chose to add everything", check("but does not refuse them — the user chose to add everything",
len(plan8.importable) == 2) len(plan8.importable) == 2)
print("== import route: chosen tracks into a playlist and an export (drag and drop) ==")
# Device tracks dropped on a collection playlist open Import with that playlist
# as the target: only the chosen tracks, no drive folder, all into the playlist.
nml9, music9, _ = fresh_collection()
drive9 = Path(tempfile.mkdtemp(prefix="konduktor-import-drive-")) / "Dingus"
shutil.copytree(FIXTURE, drive9, ignore=shutil.ignore_patterns("rekordbox-edited"))
from fastapi.testclient import TestClient # noqa: E402
import konduktor.main as main # noqa: E402
with TestClient(main.app) as c:
check("the collection opens", c.post("/api/library/open", json={"path": str(nml9)}).status_code == 200)
check("the drive opens as a source", c.post("/api/source/open", json={"path": str(drive9)}).status_code == 200)
picked = c.get("/api/source/tracks", params={"limit": 10}).json()
picked = picked["items"][:1]
target = c.post("/api/playlists", json={"name": "Dropped"}).json()["id"]
eset = c.post("/api/exports", json={"name": "Gig", "targets": ["traktor"],
"destination": str(music9.parent / "gig")}).json()["id"]
r = c.post("/api/import", json={"destination": str(music9), "track_ids": [picked[0]["id"]],
"into_playlist": target, "export_id": eset})
check("the import starts", r.status_code == 200, r.text[:200])
job = r.json()
for _ in range(200):
job = c.get(f"/api/jobs/{job['id']}").json()
if job["state"] != "running":
break
time.sleep(0.05)
check("…and finishes", job["state"] == "done", str(job)[:300])
entries = c.get(f"/api/playlists/{target}/tracks").json()
check("the one chosen track lands in the target playlist",
len(entries) == 1 and entries[0]["title"] == picked[0]["title"], str([e["title"] for e in entries]))
names = [n["name"] for n in c.get("/api/playlists").json()]
check("no drive folder is made when no playlist was chosen", "Dingus" not in names, str(names))
ex = next(e for e in c.get("/api/exports").json() if e["id"] == eset)
check("…and it is added to the export too", ex["track_ids"] == [entries[0]["id"]], str(ex["track_ids"]))
c.delete("/api/source")
print() print()
print("RESULT:", "FAILED" if failed else "ALL PASSED") print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+45 -3
View File
@@ -5,6 +5,7 @@ import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { removalNote, writeHint } from './lib/platformCopy' import { 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 { useDropTarget } from './lib/drag'
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'
import { import {
@@ -83,6 +84,9 @@ export default function App() {
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null) const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null)
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
const [importing, setImporting] = useState(false) const [importing, setImporting] = useState(false)
// Device tracks dropped on a collection playlist / export: Import, with
// just those tracks and that target.
const [importDrop, setImportDrop] = useState<{ ids: string[]; target: AddTarget } | null>(null)
// Batch analysis (grid, or Auto Hotcues): a confirm step, then the running // Batch analysis (grid, or Auto Hotcues): a confirm step, then the running
// job, polled into the status bar. ONE at a time across both kinds — the // job, polled into the status bar. ONE at a time across both kinds — the
// backend refuses a second, since a grid run would move the beats a hotcue // backend refuses a second, since a grid run would move the beats a hotcue
@@ -102,9 +106,9 @@ export default function App() {
// Every Remove ▸ action (and the playlist Delete key) confirms first. // Every Remove ▸ action (and the playlist Delete key) confirms first.
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null) const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
const loadTrack = useCallback((t: Track) => { const loadTrack = useCallback((t: Track, origin: TrackOrigin = viewOriginRef.current) => {
setPrepTrack(t) setPrepTrack(t)
setPrepOrigin(viewOriginRef.current) setPrepOrigin(origin)
}, []) }, [])
const playTrack = useCallback( const playTrack = useCallback(
(t: Track) => { (t: Track) => {
@@ -358,6 +362,22 @@ export default function App() {
}, },
[qc, addablePlaylists, duplicatesAllowed, notify, onError], [qc, addablePlaylists, duplicatesAllowed, notify, onError],
) )
// Tracks from a device or a Files folder dropped on a collection playlist or
// export: they are not in the collection yet, so the drop opens the dialog
// that adds them — with that target filled in, and copy-vs-reference still
// asked (decided 2026-10-06).
const addForeign = useCallback(
(origin: TrackOrigin, ids: string[], target: AddTarget) => {
if (origin === 'folder') setAdding({ ids, target })
else if (origin === 'device') setImportDrop({ ids, target })
},
[],
)
const [deckDropRef, deckOver] = useDropTarget<true>({
hint: (p) => (p.kind === 'tracks' ? true : null),
label: (p) => (p.kind === 'tracks' && p.ids.length > 1 ? `Load “${p.lead.title || 'Untitled'}” into the deck` : 'Load into the deck'),
onDrop: (p) => p.kind === 'tracks' && loadTrack(p.lead, p.origin),
})
const removeFromExport = useCallback( const removeFromExport = useCallback(
async (id: string, ids: string[]) => { async (id: string, ids: string[]) => {
try { try {
@@ -1208,7 +1228,27 @@ export default function App() {
/> />
)} )}
{/* Prep strip spans the top of the window; the library sits below it. */} {importDrop && (
<ImportDialog
playlistId={null}
trackIds={importDrop.ids}
target={importDrop.target}
deviceLabel={deviceLabel}
onClose={() => setImportDrop(null)}
onDone={(msg) => {
setImportDrop(null)
notify('success', msg)
}}
onError={onError}
/>
)}
{/* Prep strip spans the top of the window; the library sits below it.
A track dropped on it loads (paused) — the row the drag started on. */}
<div ref={deckDropRef} className="relative shrink-0">
{deckOver && (
<div aria-hidden className="pointer-events-none absolute inset-0 z-10 rounded-[22px] ring-2 ring-accent" />
)}
<CapabilitiesContext.Provider value={deckCaps}> <CapabilitiesContext.Provider value={deckCaps}>
<PrepStrip <PrepStrip
track={prepTrack} track={prepTrack}
@@ -1220,6 +1260,7 @@ export default function App() {
onPlayingChange={setDeckPlaying} onPlayingChange={setDeckPlaying}
/> />
</CapabilitiesContext.Provider> </CapabilitiesContext.Provider>
</div>
<div className="flex min-h-0 flex-1 gap-3"> <div className="flex min-h-0 flex-1 gap-3">
<Sidebar <Sidebar
@@ -1231,6 +1272,7 @@ export default function App() {
onSwitchLibrary={() => setForcePicker(true)} onSwitchLibrary={() => setForcePicker(true)}
onOpenLibrary={(path) => void openForEditing(path)} onOpenLibrary={(path) => void openForEditing(path)}
onDone={(msg) => notify('success', msg)} onDone={(msg) => notify('success', msg)}
onAddForeign={addForeign}
onOpenPathMapping={() => setShowPaths(true)} onOpenPathMapping={() => setShowPaths(true)}
onDiscarded={() => afterBulk(prepTrack ? [prepTrack.id] : [], true)} onDiscarded={() => afterBulk(prepTrack ? [prepTrack.id] : [], true)}
/> />
+4
View File
@@ -441,6 +441,10 @@ export interface ImportRequest {
playlist_ids?: string[] playlist_ids?: string[]
/** Playlists land in a folder named this; null keeps them at the root. */ /** Playlists land in a folder named this; null keeps them at the root. */
folder_name?: string | null folder_name?: string | null
/** 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
export_id?: string | null
} }
export interface ImportPreview { export interface ImportPreview {
+22 -4
View File
@@ -1,6 +1,8 @@
import { useState } from 'react' import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type ExportSet } from '../api' import { api, type ExportSet, type TrackOrigin } from '../api'
import type { AddTarget } from './AddFilesDialog'
import { useCaps } from '../lib/capabilities'
import { ExportDialog } from './ExportDialog' import { ExportDialog } from './ExportDialog'
import { ExportRunDialog } from './ExportRunDialog' import { ExportRunDialog } from './ExportRunDialog'
import type { Source } from './Sidebar' import type { Source } from './Sidebar'
@@ -29,9 +31,10 @@ interface Props {
onSelect: (s: Source) => void onSelect: (s: Source) => void
onDone: (msg: string) => void onDone: (msg: string) => void
onError: (msg: string) => void onError: (msg: string) => void
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
} }
export function ExportsSection({ source, onSelect, onDone, onError }: Props) { export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign }: Props) {
const qc = useQueryClient() const qc = useQueryClient()
const [dialog, setDialog] = useState<{ editing: ExportSet | null } | null>(null) const [dialog, setDialog] = useState<{ editing: ExportSet | null } | null>(null)
const [running, setRunning] = useState<ExportSet | null>(null) const [running, setRunning] = useState<ExportSet | null>(null)
@@ -108,6 +111,7 @@ export function ExportsSection({ source, onSelect, onDone, onError }: Props) {
onEdit={() => setDialog({ editing: set })} onEdit={() => setDialog({ editing: set })}
onRun={() => setRunning(set)} onRun={() => setRunning(set)}
onDone={onDone} onDone={onDone}
onAddForeign={onAddForeign}
onDelete={async () => { onDelete={async () => {
// Deleting a set never touches its destination folder — the files // Deleting a set never touches its destination folder — the files
// already exported are the user's, not Konduktor's to clean up. // already exported are the user's, not Konduktor's to clean up.
@@ -137,6 +141,7 @@ function ExportRow({
onDelete, onDelete,
onDone, onDone,
onError, onError,
onAddForeign,
}: { }: {
set: ExportSet set: ExportSet
source: Source source: Source
@@ -146,8 +151,12 @@ function ExportRow({
onDelete: () => void onDelete: () => void
onDone: (msg: string) => void onDone: (msg: string) => void
onError: (msg: string) => void onError: (msg: string) => void
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
}) { }) {
const qc = useQueryClient() const qc = useQueryClient()
// The COLLECTION's capabilities (the sidebar sits outside the browsed view's
// swap): a device's or folder's tracks must be added to it first.
const caps = useCaps()
const selected = source.kind === 'export' && source.id === set.id const selected = source.kind === 'export' && source.id === set.id
const inside = const inside =
selected || selected ||
@@ -185,11 +194,20 @@ function ExportRow({
qc.invalidateQueries({ queryKey: ['export-loose', set.id] }) qc.invalidateQueries({ queryKey: ['export-loose', set.id] })
} }
const accepts = (p: DragPayload) => const accepts = (p: DragPayload) =>
p.kind === 'tracks' ? p.origin === 'collection' : playlistIdsUnder(p.node).length > 0 p.kind === 'tracks'
? p.origin === 'collection' || (caps.writable && caps.tracks.addable)
: playlistIdsUnder(p.node).length > 0
const [dropRef, over] = useDropTarget<true>({ const [dropRef, over] = useDropTarget<true>({
hint: (p) => (accepts(p) ? true : null), hint: (p) => (accepts(p) ? true : null),
label: () => `Add to export ${set.name}`, label: (p) =>
p.kind === 'tracks' && p.origin === 'device'
? `Import into export ${set.name}…`
: `Add to export ${set.name}${p.kind === 'tracks' && p.origin === 'folder' ? '…' : ''}`,
onDrop: async (p) => { onDrop: async (p) => {
if (p.kind === 'tracks' && p.origin !== 'collection') {
onAddForeign(p.origin, p.ids, { kind: 'export', id: set.id, name: set.name })
return
}
try { try {
if (p.kind === 'tracks') { if (p.kind === 'tracks') {
await api.addToExport(set.id, { track_ids: p.ids }) await api.addToExport(set.id, { track_ids: p.ids })
+34 -11
View File
@@ -4,6 +4,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type ImportPreview, type JobStatus } from '../api' import { api, type ImportPreview, type JobStatus } from '../api'
import { useCaps } from '../lib/capabilities' import { useCaps } from '../lib/capabilities'
import { placedAudioSummary } from '../lib/platformCopy' import { placedAudioSummary } from '../lib/platformCopy'
import type { AddTarget } from './AddFilesDialog'
import { FolderPicker } from './FolderPicker' import { FolderPicker } from './FolderPicker'
import { useServerImportFolder } from './AddFilesDialog' import { useServerImportFolder } from './AddFilesDialog'
@@ -29,13 +30,18 @@ function gb(bytes: number): string {
interface Props { interface Props {
/** Playlist to import, or null for the whole device. */ /** Playlist to import, or null for the whole device. */
playlistId: string | null playlistId: string | null
/** Instead: just these device tracks (dragged out of the device's view). */
trackIds?: string[]
/** Where they go once imported — the playlist or export they were dropped
* on. They are in the collection first either way. */
target?: AddTarget | null
deviceLabel: string deviceLabel: string
onClose: () => void onClose: () => void
onDone: (msg: string) => void onDone: (msg: string) => void
onError: (msg: string) => void onError: (msg: string) => void
} }
export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError }: Props) { export function ImportDialog({ playlistId, trackIds, target, deviceLabel, onClose, onDone, onError }: Props) {
const qc = useQueryClient() const qc = useQueryClient()
// 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
@@ -81,13 +87,15 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
const body = { const body = {
destination, destination,
playlist_ids: playlistId ? [playlistId] : [], playlist_ids: trackIds ? [] : playlistId ? [playlistId] : [],
track_ids: [], track_ids: trackIds ?? [],
folder_name: deviceLabel, folder_name: deviceLabel,
into_playlist: target?.kind === 'playlist' ? target.id : null,
export_id: target?.kind === 'export' ? target.id : null,
} }
const preview = useQuery<ImportPreview>({ const preview = useQuery<ImportPreview>({
queryKey: ['import-preview', destination, playlistId], queryKey: ['import-preview', destination, playlistId, trackIds?.join('\n'), target?.id],
queryFn: () => api.importPreview(body), queryFn: () => api.importPreview(body),
enabled: !!destination && !job, enabled: !!destination && !job,
staleTime: 0, staleTime: 0,
@@ -113,9 +121,16 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
qc.invalidateQueries({ queryKey: ['collection'] }) qc.invalidateQueries({ queryKey: ['collection'] })
qc.invalidateQueries({ queryKey: ['state'] }) qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['facets'] }) qc.invalidateQueries({ queryKey: ['facets'] })
if (target) {
qc.invalidateQueries({ queryKey: ['playlist', target.id] })
qc.invalidateQueries({ queryKey: ['export-contents', target.id] })
qc.invalidateQueries({ queryKey: ['export-tracks', target.id] })
qc.invalidateQueries({ queryKey: ['export-loose', target.id] })
}
onDone( onDone(
`Imported ${r?.tracks ?? 0} track${r?.tracks === 1 ? '' : 's'}` + `Imported ${r?.tracks ?? 0} track${r?.tracks === 1 ? '' : 's'}` +
(r?.playlists ? ` and ${r.playlists} playlist${r.playlists === 1 ? '' : 's'}` : ''), (r?.playlists ? ` and ${r.playlists} playlist${r.playlists === 1 ? '' : 's'}` : '') +
(target ? ` into ${target.name}` : ''),
) )
} else if (next.state === 'failed') { } else if (next.state === 'failed') {
onError(next.error || 'Import failed') onError(next.error || 'Import failed')
@@ -129,7 +144,7 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
return () => { return () => {
if (pollRef.current) window.clearInterval(pollRef.current) if (pollRef.current) window.clearInterval(pollRef.current)
} }
}, [job, qc, onDone, onError]) }, [job, qc, onDone, onError, target])
const start = async () => { const start = async () => {
setStarting(true) setStarting(true)
@@ -174,9 +189,15 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
<div className="w-full max-w-lg glass-overlay"> <div className="w-full max-w-lg glass-overlay">
<div className="border-b border-line px-5 py-3"> <div className="border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text"> <h2 className="text-sm font-semibold text-text">
Import from {deviceLabel} {trackIds
{playlistId ? '' : ' — everything'} ? `Import ${trackIds.length} track${trackIds.length === 1 ? '' : 's'} from ${deviceLabel}`
: `Import from ${deviceLabel}${playlistId ? '' : ' — everything'}`}
</h2> </h2>
{target && (
<p className="mt-0.5 text-xs text-muted">
Into your collection, then into {target.kind === 'export' ? 'the export ' : ''}“{target.name}”.
</p>
)}
</div> </div>
<div className="space-y-4 px-5 py-4 text-sm"> <div className="space-y-4 px-5 py-4 text-sm">
@@ -270,9 +291,11 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
</div> </div>
)} )}
<div className="text-xs text-faint"> {p.playlists.length > 0 && (
Playlists land in a folder called “{deviceLabel}”. <div className="text-xs text-faint">
</div> Playlists land in a folder called “{deviceLabel}”.
</div>
)}
</div> </div>
)} )}
</> </>
+7 -1
View File
@@ -58,11 +58,17 @@ function sections(slots: number): Section[] {
{ keys: [[MOD, 'Click']], action: 'Add to / remove from the selection' }, { keys: [[MOD, 'Click']], action: 'Add to / remove from the selection' },
{ keys: [['Double-click']], action: 'Edit a cell' }, { keys: [['Double-click']], action: 'Edit a cell' },
{ keys: [['Right-click']], action: 'Track menu (header: choose columns)' }, { keys: [['Right-click']], action: 'Track menu (header: choose columns)' },
{ keys: [['Drag rows']], action: 'Onto a playlist or export to add, onto the deck to load, within a playlist to reorder' },
{ keys: [[ALT_KEY, 'Drag']], action: 'Move tracks to another playlist (out of this one)' },
{ keys: [['Esc']], action: 'While dragging: cancel the drag' },
], ],
}, },
{ {
title: 'Sidebar', title: 'Sidebar',
rows: [{ keys: [['Right-click']], action: 'New playlist or folder, rename, delete' }], rows: [
{ keys: [['Right-click']], action: 'New playlist or folder, rename, delete' },
{ keys: [['Drag']], action: 'Rearrange playlists and folders; onto an export to add one' },
],
}, },
{ {
title: 'Fields & dialogs', title: 'Fields & dialogs',
+27 -6
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type PlaylistKind, type PlaylistNode } from '../api' import { api, type PlaylistKind, type PlaylistNode, type TrackOrigin } from '../api'
import type { AddTarget } from './AddFilesDialog'
import { useCaps } from '../lib/capabilities' import { useCaps } from '../lib/capabilities'
import { SaveBar } from './SaveBar' import { SaveBar } from './SaveBar'
import { confirmDiscardUnsaved } from '../lib/unsaved' import { confirmDiscardUnsaved } from '../lib/unsaved'
@@ -53,6 +54,9 @@ interface Props {
/** Open a drive's library as THE library (Devices' "Open for editing…"). */ /** Open a drive's library as THE library (Devices' "Open for editing…"). */
onOpenLibrary: (path: string) => void onOpenLibrary: (path: string) => void
onDone: (msg: string) => void onDone: (msg: string) => void
/** Tracks not in the collection yet (a device's, a folder's) dropped on a
* playlist or export: open the dialog that adds them, target filled in. */
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
onOpenPathMapping: () => void onOpenPathMapping: () => void
/** After unsaved edits were discarded (SaveBar). */ /** After unsaved edits were discarded (SaveBar). */
onDiscarded?: () => void onDiscarded?: () => void
@@ -255,7 +259,11 @@ function NodeRow({
return isFolder && !expanded ? { zone: 'peek' } : null return isFolder && !expanded ? { zone: 'peek' } : null
}, },
label: (p, h, at) => { label: (p, h, at) => {
if (h.zone === 'tracks') return `${moves(p, at.alt) ? 'Move' : 'Add'} to ${node.name}` if (h.zone === 'tracks') {
if (p.kind === 'tracks' && p.origin === 'device') return `Import into ${node.name}…`
if (p.kind === 'tracks' && p.origin === 'folder') return `Add to ${node.name}…`
return `${moves(p, at.alt) ? 'Move' : 'Add'} to ${node.name}`
}
if (h.zone === 'peek') return null if (h.zone === 'peek') return null
return h.zone === 'into' || h.zone === 'first' ? `Move into ${node.name}` : `Move ${h.zone} ${node.name}` return h.zone === 'into' || h.zone === 'first' ? `Move into ${node.name}` : `Move ${h.zone} ${node.name}`
}, },
@@ -430,6 +438,7 @@ export function Sidebar({
onSwitchLibrary, onSwitchLibrary,
onOpenLibrary, onOpenLibrary,
onDone, onDone,
onAddForeign,
onOpenPathMapping, onOpenPathMapping,
onDiscarded, onDiscarded,
}: Props) { }: Props) {
@@ -604,10 +613,12 @@ export function Sidebar({
setDraft(null) setDraft(null)
}, },
onCancelDraft: () => setDraft(null), onCancelDraft: () => setDraft(null),
// Only the collection's own tracks: a device's or a folder's ids mean // A device's or a folder's tracks are not in the collection yet, so they
// nothing to the collection's playlists. // can only come if the collection can ADD tracks — via the add dialog.
acceptsTracks: (node, p) => acceptsTracks: (node, p) =>
caps.writable && node.can_add_tracks && p.origin === 'collection' && p.fromPlaylist !== node.id, caps.writable &&
node.can_add_tracks &&
(p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable),
canMove: (node) => caps.writable && node.can_move, canMove: (node) => caps.writable && node.can_move,
onMoveNode: async (node, parentId, index, into) => { onMoveNode: async (node, parentId, index, into) => {
try { try {
@@ -620,6 +631,10 @@ export function Sidebar({
} }
}, },
onDropTracks: async (node, p, alt) => { onDropTracks: async (node, p, alt) => {
if (p.origin !== 'collection') {
onAddForeign(p.origin, p.ids, { kind: 'playlist', id: node.id, name: node.name })
return
}
try { try {
const msg = await addTracksToPlaylist({ const msg = await addTracksToPlaylist({
qc, qc,
@@ -745,7 +760,13 @@ export function Sidebar({
{menu && <ContextMenu {...menu} onClose={() => setMenu(null)} />} {menu && <ContextMenu {...menu} onClose={() => setMenu(null)} />}
{confirmReq && <ConfirmDialog {...confirmReq} onClose={() => setConfirmReq(null)} />} {confirmReq && <ConfirmDialog {...confirmReq} onClose={() => setConfirmReq(null)} />}
<ExportsSection source={source} onSelect={onSelect} onDone={onDone} onError={onError} /> <ExportsSection
source={source}
onSelect={onSelect}
onDone={onDone}
onError={onError}
onAddForeign={onAddForeign}
/>
<DevicesSection <DevicesSection
source={source} source={source}
+1
View File
@@ -423,6 +423,7 @@ export function TrackTable({
kind: 'tracks', kind: 'tracks',
ids: [...new Set(carried.map((t) => t.id))], ids: [...new Set(carried.map((t) => t.id))],
tracks: carried, tracks: carried,
lead: pressed,
origin: from?.origin ?? 'collection', origin: from?.origin ?? 'collection',
fromPlaylist: from?.playlistId, fromPlaylist: from?.playlistId,
source: tableKey, source: tableKey,
+2
View File
@@ -28,6 +28,8 @@ export type DragPayload =
kind: 'tracks' kind: 'tracks'
ids: string[] ids: string[]
tracks: Track[] tracks: Track[]
/** The row the drag started on — what a drop on the deck loads. */
lead: Track
/** Which library the ids belong to — a device's or a folder's are not /** 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. */ * the collection's, so collection targets must not take them as such. */
origin: TrackOrigin origin: TrackOrigin