Compare commits

..
Author SHA1 Message Date
patben8 966f3fe8c5 Bumped version number 2026-10-10 17:42:17 +02:00
patben8 a03b9056a9 Merge pull request #6 from MrPatben8/dev
Implemented dragging engine
2026-10-10 17:40:06 +02:00
patben8 26b556d975 Updated remote protocol version 2026-10-06 23:17:21 +02:00
patben8 c87444bda5 Implemented drag and drop loading 2026-10-06 23:08:34 +02:00
patben8 7ba71981c8 Implemented library rearrangement 2026-10-06 22:51:34 +02:00
patben8 89c7dade25 Tracks can be added to playlists via drag 2026-10-06 22:41:29 +02:00
patben8 b154df430a Implemented drag core and song reorganizing 2026-10-06 22:32:31 +02:00
patben8 e5c7b67626 Implemented playlist reorganizing 2026-10-06 22:25:01 +02:00
patben8 9f79f5a849 Search now includes comments 2026-10-05 23:16:12 +02:00
patben8 c8b86100f0 Track position in playlist can now be typed 2026-10-05 21:01:25 +02:00
patben8 0fac84cb73 Fixed issue with release pipeline 2026-10-04 21:57:40 +02:00
patben8 71ee877784 Merge pull request #5 from MrPatben8/dev
Implemented Key Analysis & Remote Library Management
2026-10-04 18:35:08 +02:00
patben8 920146f2c0 Bumped version number 2026-10-04 18:33:33 +02:00
42 changed files with 1722 additions and 165 deletions

No files matched your search

+5
View File
@@ -145,6 +145,8 @@ jobs:
- name: Build and push - name: Build and push
uses: docker/build-push-action@v6 uses: docker/build-push-action@v6
env:
DOCKER_BUILD_RECORD_UPLOAD: false # no .dockerbuild artifact in the run
with: with:
context: . context: .
file: server/Dockerfile file: server/Dockerfile
@@ -180,6 +182,9 @@ jobs:
- name: Download installers from both builds - name: Download installers from both builds
uses: actions/download-artifact@v4 uses: actions/download-artifact@v4
with: with:
# Only the installers: the run also holds server-image's Docker build
# record, which is not a release asset (and once failed to download).
pattern: konduktor-*
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/… path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
- name: Publish release - name: Publish release
+77 -6
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
@@ -884,7 +935,11 @@ Two independent apps that talk over HTTP:
`ContextMenu` (supports `▸` submenus, section headings, separators and `ContextMenu` (supports `▸` submenus, section headings, separators and
checkbox items that toggle without closing — the header row's right-click checkbox items that toggle without closing — the header row's right-click
column chooser uses those; "Add to" lists column chooser uses those; "Add to" lists
playlists + exports and acts on the whole selection; "Remove ▸" holds playlists + exports and acts on the whole selection; in an editable
playlist "Set Position…" (`SetPositionDialog`, `lib/playlistOrder.ts`)
moves the selection as ONE block in playlist order so its first track
lands at #N — allowed while sorted/filtered, unlike drag, because it
reorders the FULL entry list; "Remove ▸" holds
From this playlist / From this export / Grids / Hotcues / From collection, From this playlist / From this export / Grids / Hotcues / From collection,
each behind a `ConfirmDialog` — as is the playlist Delete key. Enter each behind a `ConfirmDialog` — as is the playlist Delete key. Enter
confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog` confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog`
@@ -1051,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
@@ -1122,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`
@@ -1161,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
@@ -1198,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
@@ -1895,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,
@@ -193,6 +193,7 @@ class OneLibraryAdapter:
can_rename=writable, can_rename=writable,
can_delete=writable, can_delete=writable,
can_contain_children=kind == "folder", can_contain_children=kind == "folder",
can_move=writable,
) )
parent = str(getattr(r, "playlist_id_parent", 0) or 0) parent = str(getattr(r, "playlist_id_parent", 0) or 0)
parents[node_id] = "root" if parent in ("0", "", "None") else parent parents[node_id] = "root" if parent in ("0", "", "None") else parent
@@ -425,6 +426,10 @@ class OneLibraryAdapter:
self._require_writable("Deleting playlists") self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id) self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
self._require_writable("Moving playlists")
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._require_writable("Editing playlists") self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids) return self._store.set_playlist_entries(node_id, track_ids)
@@ -652,6 +652,45 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush() db.flush()
self._journal.record("playlist", "delete", name) self._journal.record("playlist", "delete", name)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s children, renumbering
`sequenceNo` from 0 in both parents as create and delete do. The
Device Library's playlist tree follows at Save (`device_library`
mirrors parent and sort from these rows)."""
db = self._require_db()
row = self._playlist(node_id)
dest = 0
if parent_id:
folder = self._playlist(parent_id)
if int(folder.attribute or 0) != ATTRIBUTE_FOLDER:
raise InvalidCommand("A playlist can only be moved into a folder")
dest = int(folder.playlist_id)
ancestor = folder
while ancestor is not None:
if int(ancestor.playlist_id) == int(row.playlist_id):
raise InvalidCommand("A folder cannot be moved into itself")
up = int(ancestor.playlist_id_parent or 0)
ancestor = self._playlist(str(up)) if up else None
source = int(row.playlist_id_parent or 0)
siblings = self._siblings(dest, excluding=row.playlist_id)
index = max(0, min(int(index), len(siblings)))
order = siblings[:index] + [row] + siblings[index:]
if source == dest and [r.playlist_id for r in order] == [
r.playlist_id for r in self._siblings(dest)
]:
return str(row.playlist_id)
row.playlist_id_parent = dest
for n, r in enumerate(order):
if int(r.sequenceNo or 0) != n:
r.sequenceNo = n
if source != dest:
for n, r in enumerate(self._siblings(source, excluding=row.playlist_id)):
if int(r.sequenceNo or 0) != n:
r.sequenceNo = n
db.flush()
self._journal.record("playlist", "move", row.name)
return str(row.playlist_id)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in order, numbered from 1 (measured).""" """Replace a playlist's contents, in order, numbered from 1 (measured)."""
from pyrekordbox.devicelib_plus import models from pyrekordbox.devicelib_plus import models
@@ -172,6 +172,7 @@ class RekordboxAdapter:
can_rename=writable, can_rename=writable,
can_delete=writable, can_delete=writable,
can_contain_children=kind == "folder", can_contain_children=kind == "folder",
can_move=writable,
) )
parent = str(r.ParentID or "root") parent = str(r.ParentID or "root")
parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent parents[node_id] = "root" if parent in ("0", "", "root", "None") else parent
@@ -276,6 +277,10 @@ class RekordboxAdapter:
self._require_writable("Deleting playlists") self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id) self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
self._require_writable("Moving playlists")
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._require_writable("Editing playlists") self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids) return self._store.set_playlist_entries(node_id, track_ids)
@@ -608,6 +608,79 @@ class RekordboxStore(ReplaceGridCommands):
self._db.delete_playlist(row) self._db.delete_playlist(row)
self._journal.record("playlist", "delete", name) self._journal.record("playlist", "delete", name)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s visible children.
Not pyrekordbox's `move_playlist`: its `parent=None` means "keep the
parent", so nothing can be moved to the top level with it. The same
writes are made here — `ParentID`, the moved row's `updated_at`, and
`Seq` renumbered from 1 in both parents (only rows whose `Seq` changes
are touched) — plus `masterPlaylists6.xml`'s `ParentId`, which
pyrekordbox's version leaves stale. Rekordbox's hidden working lists
share the table and the numbering, so `index` is placed relative to
the VISIBLE siblings and the hidden ones keep their order around it."""
import datetime
from pyrekordbox.masterdb.database import SPECIAL_PLAYLIST_IDS
t = self._tables
row = self._playlist(node_id)
dest = self._playlist(parent_id) if parent_id else None
if dest is not None and int(dest.Attribute or 0) != int(t.PlaylistType.FOLDER):
raise InvalidCommand("A playlist can only be moved into a folder")
ancestor = dest
while ancestor is not None:
if str(ancestor.ID) == str(row.ID):
raise InvalidCommand("A folder cannot be moved into itself")
up = str(ancestor.ParentID or "root")
ancestor = None if up in ("root", "0", "") else self._playlist(up)
def children(key: str) -> list:
return (
self._db.session.query(t.DjmdPlaylist)
.filter(t.DjmdPlaylist.ParentID == key)
.filter(t.DjmdPlaylist.rb_local_deleted == 0)
.order_by(t.DjmdPlaylist.Seq)
.all()
)
old_key = str(row.ParentID or "root")
new_key = str(dest.ID) if dest is not None else "root"
siblings = [c for c in children(new_key) if str(c.ID) != str(row.ID)]
visible = [c for c in siblings if str(c.ID) not in SPECIAL_PLAYLIST_IDS]
index = max(0, min(int(index), len(visible)))
if index < len(visible):
at = siblings.index(visible[index])
else:
at = siblings.index(visible[-1]) + 1 if visible else len(siblings)
order = siblings[:at] + [row] + siblings[at:]
if old_key == new_key and [str(c.ID) for c in order] == [
str(c.ID) for c in children(new_key)
]:
return str(row.ID)
row.ParentID = new_key
with self._db.registry.disabled():
row.updated_at = datetime.datetime.now()
for n, c in enumerate(order, start=1):
if c.Seq != n:
c.Seq = n
if old_key != new_key:
for n, c in enumerate(
(c for c in children(old_key) if str(c.ID) != str(row.ID)), start=1
):
if c.Seq != n:
c.Seq = n
xml = getattr(self._db, "playlist_xml", None)
if xml is not None:
try:
xml.update(row.ID, parent_id=new_key)
except ValueError:
pass # a playlist the XML never listed: nothing to keep in step
self._db.flush()
self._journal.record("playlist", "move", row.Name)
return str(row.ID)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in the given order. """Replace a playlist's contents, in the given order.
@@ -194,6 +194,9 @@ class RemoteAdapter:
def delete_playlist(self, node_id): def delete_playlist(self, node_id):
return self._call("delete_playlist", node_id=node_id) return self._call("delete_playlist", node_id=node_id)
def move_playlist(self, node_id, parent_id, index):
return self._call("move_playlist", node_id=node_id, parent_id=parent_id, index=index)
def set_playlist_entries(self, node_id, track_ids): def set_playlist_entries(self, node_id, track_ids):
return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids)) return self._call("set_playlist_entries", node_id=node_id, track_ids=list(track_ids))
@@ -131,6 +131,10 @@ class TraktorAdapter:
with _translate(): with _translate():
self._store.delete_playlist(node_id) self._store.delete_playlist(node_id)
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
with _translate():
return self._store.move_playlist(node_id, parent_id, index)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents. The adapter resolves each id to its """Replace a playlist's contents. The adapter resolves each id to its
native entry kind, so callers never see Traktor's STEM/TRACK split.""" native entry kind, so callers never see Traktor's STEM/TRACK split."""
@@ -74,7 +74,12 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
"need a manual Import Cover Art to show up." "need a manual Import Cover Art to show up."
), ),
), ),
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True), playlists=PlaylistCapabilities(
folders=True, smart="read_only", reorder=True,
# A playlist's entries are a plain list of PRIMARYKEYs, and Traktor
# itself adds a track twice when asked.
duplicates=True,
),
save=SaveCapabilities( save=SaveCapabilities(
app_name="Traktor", app_name="Traktor",
library_label="collection.nml", library_label="collection.nml",
+77 -1
View File
@@ -160,11 +160,13 @@ class TraktorStore:
can_reorder=True, can_reorder=True,
can_rename=True, can_rename=True,
can_delete=True, can_delete=True,
can_move=True,
) )
if ntype == "SMARTLIST" or node.smartplaylist is not None: if ntype == "SMARTLIST" or node.smartplaylist is not None:
# Rule-based, so it has no static entry list to show or edit. # Rule-based, so it has no static entry list to show or edit.
return PlaylistNode( return PlaylistNode(
id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart" id="sl:" + "/".join(parent_path + [name]), name=name, kind="smart",
can_move=True,
) )
path = parent_path + [name] path = parent_path + [name]
return PlaylistNode( return PlaylistNode(
@@ -175,6 +177,7 @@ class TraktorStore:
can_contain_children=True, can_contain_children=True,
can_rename=True, can_rename=True,
can_delete=True, can_delete=True,
can_move=True,
) )
@staticmethod @staticmethod
@@ -348,6 +351,79 @@ class TraktorStore:
self._note("playlist-delete", node.name) self._note("playlist-delete", node.name)
self.dirty = True self.dirty = True
def _find_node(self, node_id: str) -> Nodetype:
"""Any node by its id: a playlist's UUID, a folder's `fld:` path or a
smart playlist's `sl:` path (its folder path plus its own name)."""
if node_id.startswith("fld:"):
return self._find_folder(node_id)
if node_id.startswith("sl:"):
*folders, name = node_id[len("sl:"):].split("/")
parent = self._find_folder("fld:" + "/".join(folders) if folders else None)
match = next(
(c for c in self._children(parent)
if (c.type == "SMARTLIST" or c.smartplaylist is not None) and c.name == name),
None,
)
if match is None:
raise PlaylistError(f"Smart playlist not found: {node_id}")
return match
node = self._find_playlist_node(node_id)
if node is None:
raise PlaylistError(f"Playlist not found: {node_id}")
return node
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str:
"""Move a node to `index` among `parent_id`'s children (counted without
it) and return its id afterwards — a folder's and a smart playlist's id
is their path of names, so moving one changes it (and its subtree's).
A folder or smart playlist landing beside a namesake of its own kind is
refused, as rename refuses it: the two paths would be one, and one of
them unaddressable. Playlists are UUIDs, so their names may repeat."""
with self._lock:
node = self._find_node(node_id)
if node is self._root():
raise PlaylistError("Cannot move the root folder")
dest = self._find_folder(parent_id)
if dest is node or any(n is dest for n in self._iter_nodes(node)):
raise PlaylistError("A folder cannot be moved into itself")
is_folder = node.playlist is None and node.smartplaylist is None and (
node.type or "FOLDER") == "FOLDER"
is_smart = node.type == "SMARTLIST" or node.smartplaylist is not None
if is_folder or is_smart:
kind = "folder" if is_folder else "smart playlist"
for c in self._children(dest):
same_kind = (
(c.type or "FOLDER") == "FOLDER" and c.playlist is None
and c.smartplaylist is None
) if is_folder else (c.type == "SMARTLIST" or c.smartplaylist is not None)
if c is not node and same_kind and c.name == node.name:
raise PlaylistError(f'There is already a {kind} called "{node.name}" there')
source = self._find_parent_of(node)
if source is None:
raise PlaylistError("Cannot move a top-level node")
siblings = [c for c in self._children(dest) if c is not node]
index = max(0, min(int(index), len(siblings)))
if source is dest and self._children(dest).index(node) == index:
return self._node_id(node, parent_id) # already there
source.subnodes.node.remove(node)
source.subnodes.count = len(source.subnodes.node)
if dest.subnodes is None:
dest.subnodes = Subnodestype(node=[], count=0)
dest.subnodes.node.insert(index, node)
dest.subnodes.count = len(dest.subnodes.node)
self._note("playlist-move", node.name)
self.dirty = True
return self._node_id(node, parent_id)
def _node_id(self, node: Nodetype, parent_id: str | None) -> str:
"""The id `_to_model` gives `node` inside the folder `parent_id`."""
if node.playlist is not None:
return node.playlist.uuid
prefix = parent_id[len("fld:"):] if parent_id and parent_id.startswith("fld:") else ""
tag = "sl:" if (node.type == "SMARTLIST" or node.smartplaylist is not None) else "fld:"
return tag + "/".join(p for p in (prefix, node.name or "(unnamed)") if p)
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None: def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
with self._lock: with self._lock:
node = self._find_playlist_node(playlist_uuid) node = self._find_playlist_node(playlist_uuid)
+6
View File
@@ -247,6 +247,12 @@ class LibraryAdapter(Protocol):
def create_folder(self, name: str, parent_id: str | None = None) -> str: ... def create_folder(self, name: str, parent_id: str | None = None) -> str: ...
def rename_playlist(self, node_id: str, name: str) -> None: ... def rename_playlist(self, node_id: str, name: str) -> None: ...
def delete_playlist(self, node_id: str) -> None: ... def delete_playlist(self, node_id: str) -> None: ...
# Move a node (playlist, folder or smart playlist) to `index` among
# `parent_id`'s children (None = the top level), counted with the moved
# node left out. Returns the node's id AFTER the move: an id is opaque, and
# on a platform that addresses a folder by its path it changes. A folder
# cannot go into itself or a descendant (InvalidCommand).
def move_playlist(self, node_id: str, parent_id: str | None, index: int) -> str: ...
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ... def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int: ...
# ---- commands: adding tracks ---------------------------------------- # ---- commands: adding tracks ----------------------------------------
+3
View File
@@ -106,6 +106,9 @@ class PlaylistCapabilities(BaseModel):
folders: bool = False folders: bool = False
smart: Literal["none", "read_only"] = "none" smart: Literal["none", "read_only"] = "none"
reorder: bool = False reorder: bool = False
# A playlist can hold the same track more than once. Where it cannot, a
# drop of tracks already there skips them rather than asking.
duplicates: bool = False
class PathCapabilities(BaseModel): class PathCapabilities(BaseModel):
+3
View File
@@ -130,6 +130,9 @@ class PlaylistNode(BaseModel):
can_rename: bool = False can_rename: bool = False
can_delete: bool = False can_delete: bool = False
can_contain_children: bool = False # a valid parent for a new playlist can_contain_children: bool = False # a valid parent for a new playlist
# Can be dragged elsewhere in the tree (`move_playlist`): reordered among
# its siblings or moved into another folder.
can_move: bool = False
PlaylistNode.model_rebuild() PlaylistNode.model_rebuild()
+2
View File
@@ -105,6 +105,8 @@ class TrackIndex:
if (t.artist and ql in t.artist.lower()) if (t.artist and ql in t.artist.lower())
or (t.title and ql in t.title.lower()) or (t.title and ql in t.title.lower())
or (t.album and ql in t.album.lower()) or (t.album and ql in t.album.lower())
or (t.comment and ql in t.comment.lower())
or (t.comment2 and ql in t.comment2.lower())
] ]
if genre: if genre:
items = [t for t in items if t.genre == genre] items = [t for t in items if t.genre == genre]
+38 -9
View File
@@ -92,6 +92,8 @@ from .schemas import (
RemapResult, RemapResult,
RenamePlaylist, RenamePlaylist,
SaveResult, SaveResult,
AddEntries,
MovePlaylist,
SetEntries, SetEntries,
SourceCandidate, SourceCandidate,
SourceStatus, SourceStatus,
@@ -1227,6 +1229,7 @@ def create_playlist(body: CreatePlaylist) -> PlaylistNode:
can_reorder=True, can_reorder=True,
can_rename=True, can_rename=True,
can_delete=True, can_delete=True,
can_move=True,
) )
@@ -1241,6 +1244,7 @@ def create_folder(body: CreatePlaylist) -> PlaylistNode:
can_contain_children=True, can_contain_children=True,
can_rename=True, can_rename=True,
can_delete=True, can_delete=True,
can_move=True,
) )
@@ -1265,17 +1269,35 @@ def set_entries(playlist_uuid: str, body: SetEntries) -> dict:
return {"status": "updated", "id": playlist_uuid, "count": n} return {"status": "updated", "id": playlist_uuid, "count": n}
@app.post("/api/playlists/move")
def move_playlist(body: MovePlaylist) -> dict:
"""Move a playlist, folder or smart playlist in the tree. Answers the
node's id AFTER the move, which on some platforms is not the one sent."""
new_id = require_adapter().move_playlist(body.node_id, body.parent_id, body.index)
return {"status": "moved", "id": new_id}
@app.post("/api/playlists/{playlist_uuid}/add") @app.post("/api/playlists/{playlist_uuid}/add")
def add_entries(playlist_uuid: str, body: SetEntries) -> dict: def add_entries(playlist_uuid: str, body: AddEntries) -> dict:
"""Append tracks to a playlist (skips ids already present).""" """Append tracks to a playlist. Tracks already there are skipped, added
again, or — `duplicates="ask"` — counted with nothing changed (see
`AddEntries`). `duplicates` in the answer is how many there were."""
a = require_adapter() a = require_adapter()
current = a.playlist_entries(playlist_uuid) current = a.playlist_entries(playlist_uuid)
if current is None: if current is None:
raise HTTPException(404, f"Playlist not found: {playlist_uuid}") raise HTTPException(404, f"Playlist not found: {playlist_uuid}")
have = set(current) have = set(current)
added = [tid for tid in body.track_ids if tid not in have] dupes = [tid for tid in body.track_ids if tid in have]
n = a.set_playlist_entries(playlist_uuid, current + added) mode = body.duplicates
return {"status": "added", "id": playlist_uuid, "added": len(added), "count": n} if mode != "skip" and not a.capabilities().playlists.duplicates:
mode = "skip"
if mode == "ask" and dupes:
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)
return {"status": "added", "id": playlist_uuid, "added": len(added),
"duplicates": len(dupes), "count": n}
@app.patch("/api/tracks") @app.patch("/api/tracks")
@@ -2423,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())
+3 -2
View File
@@ -34,7 +34,8 @@ from .core.model import AutoHotcue, Track, TrackCues
#: (major, minor). A client speaks to a server of the SAME major whose minor is #: (major, minor). A client speaks to a server of the SAME major whose minor is
#: at least its own: minors only add. Bump the minor for an added route or #: at least its own: minors only add. Bump the minor for an added route or
#: method, the major for anything an older client would misread. #: method, the major for anything an older client would misread.
API_VERSION: tuple[int, int] = (1, 0) #: 1.1 — `move_playlist` (sidebar drag and drop).
API_VERSION: tuple[int, int] = (1, 1)
#: How long a session survives without a heartbeat, and how often the holder #: How long a session survives without a heartbeat, and how often the holder
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback #: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
@@ -73,7 +74,7 @@ _READ = (
) )
_MUTATING = ( _MUTATING = (
"create_playlist", "create_folder", "rename_playlist", "delete_playlist", "create_playlist", "create_folder", "rename_playlist", "delete_playlist",
"set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue", "move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue",
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker", "set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker",
"move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid", "move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid",
"set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks", "set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks",
+19
View File
@@ -21,6 +21,20 @@ class SetEntries(BaseModel):
track_ids: list[str] # ordered; full desired contents of the playlist track_ids: list[str] # ordered; full desired contents of the playlist
class AddEntries(BaseModel):
track_ids: list[str]
# Tracks the playlist already holds: "skip" them, "add" them again (only
# 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"
class MovePlaylist(BaseModel):
node_id: str
parent_id: str | None = None # None = the top level
index: int # among the new parent's children, not counting the node
class EditTrack(BaseModel): class EditTrack(BaseModel):
track_id: str track_id: str
fields: dict[str, str | int | None] fields: dict[str, str | int | None]
@@ -493,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)
+38
View File
@@ -264,6 +264,44 @@ seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist
check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs)) check("and closes the gap among its siblings", seqs == list(range(len(seqs))), str(seqs))
a.close() a.close()
print("== moving playlists (sidebar drag and drop) ==")
drive = fresh_drive()
a = OneLibraryAdapter(drive)
folder = a.create_folder("Gigs")
probe = a.create_playlist("Probe")
a.save()
before = dump(db_of(drive))
check("every node offers can_move", all(n.can_move for n in a.playlist_tree()))
demos = next(n for n in a.playlist_tree() if n.name == "demos")
a.move_playlist(demos.id, folder, 0)
a.move_playlist(probe, None, 1)
tree = a.playlist_tree()
check("a playlist moved into a folder is its child",
[c.id for c in next(n for n in tree if n.id == folder).children] == [demos.id])
check("a playlist moves to the index asked for", [n.id for n in tree] == [folder, probe],
str([n.name for n in tree]))
check("a folder cannot be moved into itself",
_raises(lambda: a.move_playlist(folder, folder, 0), InvalidCommand))
check("nor into a playlist", _raises(lambda: a.move_playlist(probe, demos.id, 0), InvalidCommand))
a.save()
after = dump(db_of(drive))
changes = diff(before, after)
check("only playlist rows change, by UPDATE",
{(t, kind) for t, _, kind, _ in changes} == {("playlist", "UPDATE")}, describe(changes))
check("only parent and sequenceNo columns change",
{c for *_, f in changes for c in f} <= {"playlist_id_parent", "sequenceNo"},
str([f for *_, f in changes]))
for parent in (0, int(folder)):
seqs = sorted(r["sequenceNo"] for r in after["playlist"].values() if r["playlist_id_parent"] == parent)
check(f"sequenceNo stays 0..n-1 under {parent}", seqs == list(range(len(seqs))), str(seqs))
a.close()
reopened = OneLibraryAdapter(drive)
check("the move round-trips through a reopen",
[c.id for c in next(n for n in reopened.playlist_tree() if n.id == folder).children] == [demos.id])
reopened.move_playlist(probe, None, 1)
check("moving a node onto its own place is not an edit", reopened.dirty is False)
reopened.close()
# ---- E: a stick's hazards ------------------------------------------------------------ # ---- E: a stick's hazards ------------------------------------------------------------
print("== another app wrote the drive since it was opened ==") print("== another app wrote the drive since it was opened ==")
drive = fresh_drive() drive = fresh_drive()
+37
View File
@@ -172,6 +172,43 @@ check("COLLECTION still byte-identical after folder delete",
check("unknown folder is 404", check("unknown folder is 404",
client.delete("/api/playlists/fld:No Such Folder").status_code == 404) client.delete("/api/playlists/fld:No Such Folder").status_code == 404)
print("== drag and drop: add with duplicates, move ==")
target = client.post("/api/playlists", json={"name": "Konduktor Drop"}).json()["id"]
first, rest = track_ids[:2], track_ids[2:4]
r = client.post(f"/api/playlists/{target}/add", json={"track_ids": first}).json()
check("a plain add appends", r["added"] == 2 and r["duplicates"] == 0)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1] + rest, "duplicates": "ask"}).json()
check("'ask' with a duplicate changes nothing and counts it",
r["status"] == "duplicates" and r["duplicates"] == 1
and client.get(f"/api/playlists/{target}/tracks").json().__len__() == 2)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1] + rest, "duplicates": "skip"}).json()
check("'skip' adds only the new ones", r["added"] == 2 and r["duplicates"] == 1 and r["count"] == 4)
r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": first[:1], "duplicates": "add"}).json()
check("'add' adds it again (Traktor can hold a track twice)", r["added"] == 1 and r["count"] == 5)
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)
check("capabilities say Traktor holds duplicates",
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
box = client.post("/api/playlists/folders", json={"name": "Konduktor Drop Box"}).json()["id"]
r = client.post("/api/playlists/move", json={"node_id": target, "parent_id": box, "index": 0})
check("move answers the playlist's id", r.status_code == 200 and r.json()["id"] == target)
r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": None, "index": 0})
check("moving a folder answers its (path) id", r.json()["id"] == box)
check("…and it is first at the top level", client.get("/api/playlists").json()[0]["id"] == box)
r = client.post("/api/playlists/move", json={"node_id": box, "parent_id": box, "index": 0})
check("a folder into itself is a 400", r.status_code == 400)
r = client.post("/api/playlists/move", json={"node_id": "nope", "parent_id": None, "index": 0})
check("an unknown node is a 404", r.status_code == 404)
client.delete(f"/api/playlists/{box}")
client.post("/api/save")
check("COLLECTION still byte-identical after drops and moves",
collection_span(WORK.read_bytes()) == collection_before)
print("== original untouched ==") print("== original untouched ==")
check( check(
"original collection.nml never modified", "original collection.nml never modified",
+46
View File
@@ -31,6 +31,7 @@ os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rbfid-appd
from konduktor.adapters.rekordbox import discovery # noqa: E402 from konduktor.adapters.rekordbox import discovery # noqa: E402
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402 from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
from konduktor.core.adapter import InvalidCommand # noqa: E402
failed = False failed = False
@@ -302,6 +303,51 @@ with tempfile.TemporaryDirectory() as d:
folder_reopened.close() folder_reopened.close()
after_folder.close() after_folder.close()
# ---- E2: moving nodes in the tree (sidebar drag and drop) -----------
print("== E2: move_playlist reorders and reparents, touching only playlist rows ==")
clean_copy(REAL, work, closing=[adapter, again, final, reopened])
adapter = RekordboxAdapter(work)
folder_id = adapter.create_folder("Konduktor Move Folder")
a_id = adapter.create_playlist("Konduktor Move A")
b_id = adapter.create_playlist("Konduktor Move B")
adapter.save()
adapter.close()
before = dump(work)
adapter = RekordboxAdapter(work)
check("every node offers can_move", all(n.can_move for n in adapter.playlist_tree()))
adapter.move_playlist(b_id, folder_id, 0)
adapter.move_playlist(a_id, None, 0)
tree = adapter.playlist_tree()
check("a playlist moved into a folder is its child",
[c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id])
check("a playlist moved to index 0 is first at the top level", tree[0].id == a_id,
[n.name for n in tree[:3]])
try:
adapter.move_playlist(folder_id, folder_id, 0)
check("a folder cannot be moved into itself", False)
except InvalidCommand:
check("a folder cannot be moved into itself", True)
adapter.save()
changes = diff(before, dump(work))
check("only djmdPlaylist rows and the counter change",
{t for t, _, _, _ in changes} <= {"djmdPlaylist", "agentRegistry"}, describe(changes))
rows = dump(work)["djmdPlaylist"]
for parent in ("root", folder_id):
seqs = sorted(int(r["Seq"]) for r in rows.values()
if str(r["ParentID"]) == parent and not r["rb_local_deleted"])
check(f"Seq stays 1..n under {parent}", seqs == list(range(1, len(seqs) + 1)), seqs)
adapter.close()
reopened = RekordboxAdapter(work)
tree = reopened.playlist_tree()
check("the moves round-trip through a reopen",
tree[0].id == a_id
and [c.id for c in next(n for n in tree if n.id == folder_id).children] == [b_id])
reopened.move_playlist(b_id, None, len(tree))
check("a playlist moved out of a folder lands last at the top level",
reopened.playlist_tree()[-1].id == b_id)
reopened.close()
again = final = RekordboxAdapter(work)
# ---- F: a cue write touches the cue row AND its mirror --------------- # ---- F: a cue write touches the cue row AND its mirror ---------------
print("== F: a hot cue write is localized, and keeps the mirror in step ==") print("== F: a hot cue write is localized, and keeps the mirror in step ==")
clean_copy(REAL, work, closing=[adapter, again, final, reopened]) clean_copy(REAL, work, closing=[adapter, again, final, reopened])
+105
View File
@@ -1086,5 +1086,110 @@ with tempfile.TemporaryDirectory() as d:
check("N: …and written in Camelot", target.info.key == "1A", target.info.key) check("N: …and written in Camelot", target.info.key == "1A", target.info.key)
# ---- O: moving playlists in the tree ----------------------------------
# Drag and drop in the sidebar. Moving a node relocates its whole block, so
# the guarantee is: the COLLECTION is untouched, the tree reads back as moved,
# and moving it back reproduces the original bytes exactly.
print("\n== O. move_playlist ==")
def _collection_span(data: bytes) -> bytes:
return data[data.find(b"<COLLECTION"):data.find(b"</COLLECTION>")]
def _find(nodes, name):
for n in nodes:
if n.name == name:
return n
hit = _find(n.children, name)
if hit is not None:
return hit
return None
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
before = work.read_bytes()
store = TraktorStore(work)
roots = store.tree()
folders = [n for n in roots if n.kind == "folder" and n.children]
loose = [n for n in roots if n.kind == "playlist"]
if len(folders) < 2 or len(loose) < 2:
print(" [SKIP] the reference collection has too few top-level nodes")
else:
src, dst = folders[0], folders[1]
pl = next((c for c in src.children if c.kind == "playlist"), None) or loose[0]
home = _find(roots, pl.name)
home_parent = next((f.id for f in roots if any(c.id == pl.id for c in f.children)), None)
home_index = ([c.id for c in (src.children if home_parent else roots)].index(pl.id))
check("O: every node offers can_move", all(n.can_move for n in roots))
# A playlist into another folder, at a position.
new_id = store.move_playlist(pl.id, dst.id, 1)
tree = store.tree()
moved_into = next(n for n in tree if n.id == dst.id)
check("O: a playlist keeps its id when moved", new_id == pl.id, new_id)
check("O: …and lands at the index asked for",
len(moved_into.children) > 1 and moved_into.children[1].id == pl.id,
[c.name for c in moved_into.children[:3]])
store.save()
moved = work.read_bytes()
check("O: the COLLECTION is untouched by a move",
_collection_span(moved) == _collection_span(before))
reread = TraktorStore(work).tree()
check("O: the move round-trips through a save",
any(c.id == pl.id for c in next(n for n in reread if n.id == dst.id).children))
# …and back again: byte-identical to the original.
store.move_playlist(pl.id, home_parent, home_index)
store.save()
check("O: moving it back restores the original bytes", work.read_bytes() == before,
f"{diff_count(before, work.read_bytes())} lines differ")
# A folder moves with its subtree, and its id (a path) changes with it.
new_folder = store.move_playlist(src.id, dst.id, 0)
check("O: a moved folder answers its new path id",
new_folder == f"{dst.id}/{src.name}", new_folder)
inner = next(n for n in store.tree() if n.id == dst.id).children[0]
check("O: …and its subtree moved with it",
inner.id == new_folder and len(inner.children) == len(src.children))
child_ids = [c.id for c in inner.children]
check("O: …children keep addressable ids",
all(c.startswith((new_folder.replace("fld:", "sl:") + "/", new_folder + "/"))
or not c.startswith(("fld:", "sl:")) for c in child_ids), child_ids[:3])
# Into itself: refused, nothing changed.
snapshot = store._render()
try:
store.move_playlist(dst.id, new_folder, 0)
check("O: a folder cannot be moved into its own descendant", False)
except PlaylistError:
check("O: a folder cannot be moved into its own descendant",
store._render() == snapshot)
# A namesake folder in the target: refused (two paths would be one).
store.create_folder(src.name, None)
snapshot = store._render()
try:
store.move_playlist(new_folder, None, 0)
check("O: a folder cannot land beside a namesake", False)
except PlaylistError:
check("O: a folder cannot land beside a namesake", store._render() == snapshot)
# A smart playlist moves too, by its path id.
smart = next((c for c in inner.children if c.kind == "smart"), None)
if smart is not None:
sid = store.move_playlist(smart.id, None, 0)
check("O: a smart playlist moves and answers its new id",
sid == f"sl:{smart.name}" and store.tree()[0].id == sid, sid)
# A no-op move leaves the store clean.
fresh = TraktorStore(work)
first = fresh.tree()[0]
fresh.move_playlist(first.id, None, 0)
check("O: moving a node onto its own place is not an edit", not fresh.dirty)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+7
View File
@@ -106,6 +106,13 @@ with tempfile.TemporaryDirectory() as d:
adapter.set_track_metadata(tid, {"genre": "Konduktor Test Genre"}) adapter.set_track_metadata(tid, {"genre": "Konduktor Test Genre"})
check("metadata edit is visible in the projection", check("metadata edit is visible in the projection",
adapter.track(tid).genre == "Konduktor Test Genre") adapter.track(tid).genre == "Konduktor Test Genre")
# search reaches both comments, case-insensitively
adapter.set_track_metadata(tid, {"comment": "Konduktor Search One",
"comment2": "Konduktor Search Two"})
for q in ("search one", "SEARCH TWO"):
hits = adapter.query_tracks(q=q, limit=20000).items
check(f"search {q!r} finds the track by its comment",
[x.id for x in hits] == [tid], f"{len(hits)} hits")
# key — the projection's wheel, mode AND display text all follow # key — the projection's wheel, mode AND display text all follow
t = adapter.set_key(tid, 4, "minor") # 4A = F minor = Open Key 9m t = adapter.set_key(tid, 4, "minor") # 4A = F minor = Open Key 9m
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "frontend", "name": "frontend",
"private": true, "private": true,
"version": "0.2.1", "version": "0.2.4",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
+75 -10
View File
@@ -4,6 +4,8 @@ import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack
import { CapabilitiesContext, slotLabeller } from './lib/capabilities' 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 { 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 {
@@ -30,6 +32,7 @@ import { ImportDialog } from './components/ImportDialog'
import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog' import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog'
import { ConvertStemsDialog } from './components/ConvertStemsDialog' import { ConvertStemsDialog } from './components/ConvertStemsDialog'
import { StemReportDialog } from './components/StemReportDialog' import { StemReportDialog } from './components/StemReportDialog'
import { SetPositionDialog } from './components/SetPositionDialog'
import { Icon } from './lib/icons' import { Icon } from './lib/icons'
import { usePrefsWriter } from './lib/prefs' import { usePrefsWriter } from './lib/prefs'
@@ -39,7 +42,7 @@ function applyFilters(tracks: Track[], f: Filters): Track[] {
const bpmMax = f.bpmMax ? parseFloat(f.bpmMax) : null const bpmMax = f.bpmMax ? parseFloat(f.bpmMax) : null
return tracks.filter((t) => { return tracks.filter((t) => {
if (q) { if (q) {
const hay = `${t.artist ?? ''} ${t.title ?? ''} ${t.album ?? ''}`.toLowerCase() const hay = [t.artist, t.title, t.album, t.comment, t.comment2].filter(Boolean).join(' ').toLowerCase()
if (!hay.includes(q)) return false if (!hay.includes(q)) return false
} }
if (f.genre && t.genre !== f.genre) return false if (f.genre && t.genre !== f.genre) return false
@@ -81,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
@@ -91,6 +97,8 @@ export default function App() {
// Convert to Stems: the dialog's selection, a finished run's Details, and a // Convert to Stems: the dialog's selection, a finished run's Details, and a
// running engine download (which outlives the dialog — decided). // running engine download (which outlives the dialog — decided).
const [stemDialog, setStemDialog] = useState<string[] | null>(null) const [stemDialog, setStemDialog] = useState<string[] | null>(null)
// Set Position…: the tracks being moved within the open playlist.
const [positioning, setPositioning] = useState<string[] | null>(null)
const [stemReport, setStemReport] = useState<StemBatchResult | null>(null) const [stemReport, setStemReport] = useState<StemBatchResult | null>(null)
const [engineJob, setEngineJob] = useState<string | null>(null) const [engineJob, setEngineJob] = useState<string | null>(null)
const [batchCancelling, setBatchCancelling] = useState(false) const [batchCancelling, setBatchCancelling] = useState(false)
@@ -98,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) => {
@@ -339,21 +347,37 @@ export default function App() {
}, },
[refreshExport, exportSets.data, notify, onError], [refreshExport, exportSets.data, notify, onError],
) )
// The same path as a drop on a sidebar playlist (lib/addTracks.ts), so the
// menu and the drag ask about duplicates alike.
const duplicatesAllowed = !!capabilities.data?.playlists.duplicates
const addToPlaylist = useCallback( const addToPlaylist = useCallback(
async (uuid: string, ids: string[]) => { async (uuid: string, ids: string[]) => {
try { try {
const res = await api.addEntries(uuid, ids)
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['playlists'] })
qc.invalidateQueries({ queryKey: ['playlist', uuid] })
const name = addablePlaylists.find((p) => p.id === uuid)?.name ?? 'playlist' const name = addablePlaylists.find((p) => p.id === uuid)?.name ?? 'playlist'
notify('success', `Added ${res.added} track${res.added === 1 ? '' : 's'} to ${name}`) const msg = await addTracksToPlaylist({ qc, playlist: { id: uuid, name }, ids, duplicatesAllowed })
if (msg) notify('success', msg)
} catch (e) { } catch (e) {
onError((e as Error).message) onError((e as Error).message)
} }
}, },
[qc, addablePlaylists, 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 {
@@ -1062,6 +1086,11 @@ export default function App() {
: viewingDevice : viewingDevice
? [] ? []
: [{ label: 'Add to', submenu: addToItems(menu.ids) }]), : [{ label: 'Add to', submenu: addToItems(menu.ids) }]),
// Unlike drag-reorder this stays on while sorted or filtered: it
// moves within the playlist's FULL order, which the # column shows.
...(playlistEditable
? [{ label: 'Set Position…', onClick: () => setPositioning(menu.ids) }]
: []),
...(() => { ...(() => {
const items = removeItems(menu.ids) const items = removeItems(menu.ids)
return items.length ? [{ label: 'Remove', submenu: items }] : [] return items.length ? [{ label: 'Remove', submenu: items }] : []
@@ -1103,6 +1132,14 @@ export default function App() {
/> />
)} )}
{stemReport && <StemReportDialog result={stemReport} onClose={() => setStemReport(null)} />} {stemReport && <StemReportDialog result={stemReport} onClose={() => setStemReport(null)} />}
{positioning && (
<SetPositionDialog
order={tracks.map((t) => t.id)}
ids={positioning}
onMove={reorderPlaylist}
onClose={() => setPositioning(null)}
/>
)}
{editing && ( {editing && (
<EditTagsDialog <EditTagsDialog
track={editing} track={editing}
@@ -1191,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}
@@ -1203,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
@@ -1214,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)}
/> />
@@ -1396,6 +1455,7 @@ export default function App() {
onSortingChange={setSorting} onSortingChange={setSorting}
selection={{ selected, onChange: setSelected }} selection={{ selected, onChange: setSelected }}
marked={{ ids: heldInFolder, title: 'Already in your collection' }} marked={{ ids: heldInFolder, title: 'Already in your collection' }}
dragFrom={{ origin: 'folder' }}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)} onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })} onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack} onPlay={playTrack}
@@ -1431,6 +1491,7 @@ export default function App() {
sorting={sorting} sorting={sorting}
onSortingChange={setSorting} onSortingChange={setSorting}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, false)} onRowContextMenu={(track, x, y) => openMenu(track, x, y, false)}
dragFrom={{ origin: 'device' }}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })} onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack} onPlay={playTrack}
activeTrackId={prepTrack?.id ?? null} activeTrackId={prepTrack?.id ?? null}
@@ -1492,6 +1553,10 @@ export default function App() {
: undefined : undefined
} }
onRemove={playlistEditable ? confirmRemoveFromPlaylist : undefined} onRemove={playlistEditable ? confirmRemoveFromPlaylist : undefined}
dragFrom={{
origin: 'collection',
playlistId: playlistEditable && source.kind === 'playlist' ? source.id : undefined,
}}
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)} onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })} onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
onPlay={playTrack} onPlay={playTrack}
+27 -4
View File
@@ -83,6 +83,8 @@ export interface PlaylistNode {
can_rename: boolean can_rename: boolean
can_delete: boolean can_delete: boolean
can_contain_children: boolean can_contain_children: boolean
/** Can be dragged elsewhere in the tree (reordered, or into a folder). */
can_move: boolean
} }
export type SortField = export type SortField =
@@ -270,7 +272,13 @@ export interface Capabilities {
/** Added files can be left where they are rather than copied. */ /** Added files can be left where they are rather than copied. */
reference: boolean reference: boolean
} }
playlists: { folders: boolean; smart: 'none' | 'read_only'; reorder: boolean } playlists: {
folders: boolean
smart: 'none' | 'read_only'
reorder: boolean
/** A playlist can hold the same track twice (else duplicates are skipped). */
duplicates: boolean
}
/** Path mapping / rewriting / the missing-files check apply to this library. */ /** Path mapping / rewriting / the missing-files check apply to this library. */
paths: { remappable: boolean } paths: { remappable: boolean }
save: SaveCapabilities save: SaveCapabilities
@@ -433,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 {
@@ -988,12 +1000,23 @@ export const api = {
send<{ status: string; count: number }>('PUT', `/api/playlists/${encodeURIComponent(nodeId)}/entries`, { send<{ status: string; count: number }>('PUT', `/api/playlists/${encodeURIComponent(nodeId)}/entries`, {
track_ids: trackIds, track_ids: trackIds,
}), }),
addEntries: (nodeId: string, trackIds: string[]) => /** Append tracks. `duplicates` decides tracks already there: skip them,
send<{ status: string; added: number; count: number }>( * 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') =>
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 }, { track_ids: trackIds, duplicates },
), ),
/** Move a tree node to `index` among `parentId`'s children (null = top
* level), counted without it. Answers its id AFTER the move. */
movePlaylist: (nodeId: string, parentId: string | null, index: number) =>
send<{ status: string; id: string }>('POST', '/api/playlists/move', {
node_id: nodeId,
parent_id: parentId,
index,
}),
getPrefs: () => getJSON<Record<string, unknown>>('/api/prefs'), getPrefs: () => getJSON<Record<string, unknown>>('/api/prefs'),
patchPrefs: (patch: Record<string, unknown>) => patchPrefs: (patch: Record<string, unknown>) =>
send<Record<string, unknown>>('PATCH', '/api/prefs', patch), send<Record<string, unknown>>('PATCH', '/api/prefs', patch),
+17 -1
View File
@@ -10,6 +10,10 @@ export interface ConfirmRequest {
/** `danger` (default) for destructive actions — a pink button; `primary` /** `danger` (default) for destructive actions — a pink button; `primary`
* for a caution that is not destruction, e.g. switching library. */ * for a caution that is not destruction, e.g. switching library. */
tone?: 'danger' | 'primary' tone?: 'danger' | 'primary'
/** A second way to go ahead, as a plain button beside the confirm one
* (e.g. "Add them again" next to "Add 6 new"). Enter still means confirm. */
altLabel?: string
onAlt?: () => void
onConfirm: () => Promise<void> | void onConfirm: () => Promise<void> | void
} }
@@ -19,7 +23,7 @@ interface Props extends ConfirmRequest {
/** A yes/no confirmation for destructive actions. Enter confirms and Esc /** A yes/no confirmation for destructive actions. Enter confirms and Esc
* cancels, so a confirmed Delete key stays a two-keystroke action. */ * cancels, so a confirmed Delete key stays a two-keystroke action. */
export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', onConfirm, onClose }: Props) { export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altLabel, onAlt, onConfirm, onClose }: Props) {
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const confirm = async () => { const confirm = async () => {
@@ -69,6 +73,18 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', onCo
> >
Cancel Cancel
</button> </button>
{altLabel && onAlt && (
<button
onClick={() => {
onAlt()
onClose()
}}
disabled={busy}
className="btn-glass rounded-full px-4 py-1.5 text-sm text-text disabled:opacity-40"
>
{altLabel}
</button>
)}
<button <button
onClick={() => void confirm()} onClick={() => void confirm()}
disabled={busy} disabled={busy}
+66 -3
View File
@@ -1,11 +1,15 @@
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'
import { askConfirm } from '../lib/confirm' import { askConfirm } from '../lib/confirm'
import { Icon } from '../lib/icons' import { Icon } from '../lib/icons'
import { useDropTarget, type DragPayload } from '../lib/drag'
import { playlistIdsUnder } from '../lib/playlistTree'
/** /**
* Exports in the sidebar: each one a named, persisted slice of the library * Exports in the sidebar: each one a named, persisted slice of the library
@@ -27,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)
@@ -105,6 +110,8 @@ export function ExportsSection({ source, onSelect, onDone, onError }: Props) {
onSelect={onSelect} onSelect={onSelect}
onEdit={() => setDialog({ editing: set })} onEdit={() => setDialog({ editing: set })}
onRun={() => setRunning(set)} onRun={() => setRunning(set)}
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.
@@ -132,7 +139,9 @@ function ExportRow({
onEdit, onEdit,
onRun, onRun,
onDelete, onDelete,
onDone,
onError, onError,
onAddForeign,
}: { }: {
set: ExportSet set: ExportSet
source: Source source: Source
@@ -140,9 +149,14 @@ function ExportRow({
onEdit: () => void onEdit: () => void
onRun: () => void onRun: () => void
onDelete: () => void onDelete: () => 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 ||
@@ -170,11 +184,60 @@ function ExportRow({
const data = contents.data const data = contents.data
const expanded = open || inside const expanded = open || inside
// A drop target for the collection's tracks (they become loose tracks) and
// for playlists or folders dragged from the tree (referenced, live, as
// "Add to export" does). Not gated on the library being writable: an export
// set is Konduktor's own data.
const refresh = () => {
qc.invalidateQueries({ queryKey: ['export-contents', set.id] })
qc.invalidateQueries({ queryKey: ['export-tracks', set.id] })
qc.invalidateQueries({ queryKey: ['export-loose', set.id] })
}
const accepts = (p: DragPayload) =>
p.kind === 'tracks'
? p.origin === 'collection' || (caps.writable && caps.tracks.addable)
: playlistIdsUnder(p.node).length > 0
const [dropRef, over] = useDropTarget<true>({
hint: (p) => (accepts(p) ? true : null),
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) => {
if (p.kind === 'tracks' && p.origin !== 'collection') {
onAddForeign(p.origin, p.ids, { kind: 'export', id: set.id, name: set.name })
return
}
try {
if (p.kind === 'tracks') {
await api.addToExport(set.id, { track_ids: p.ids })
onDone(`Added ${p.ids.length} track${p.ids.length === 1 ? '' : 's'} to ${set.name}`)
} else {
const ids = playlistIdsUnder(p.node)
await api.addToExport(set.id, { playlist_ids: ids })
onDone(
p.node.kind === 'folder'
? `Added ${ids.length} playlist${ids.length === 1 ? '' : 's'} from “${p.node.name}” to ${set.name}`
: `Added “${p.node.name}” to ${set.name}`,
)
}
refresh()
} catch (e) {
onError((e as Error).message)
}
},
})
return ( return (
<div> <div>
<div <div
ref={dropRef}
className={`group flex w-full items-center gap-1 rounded-md pr-1 transition-colors ${ className={`group flex w-full items-center gap-1 rounded-md pr-1 transition-colors ${
selected ? 'is-selected text-text' : 'text-muted hover:bg-ink-800 hover:text-text' over
? 'bg-gold/10 text-text ring-1 ring-gold'
: selected
? 'is-selected text-text'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`} }`}
> >
<button <button
+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>
)} )}
</> </>
@@ -0,0 +1,106 @@
import { createPortal } from 'react-dom'
import { useEffect, useRef, useState } from 'react'
import { maxPosition, moveToPosition } from '../lib/playlistOrder'
interface Props {
/** The playlist's full entry order — never the sorted or filtered view, so
* the move is safe whatever the table is showing. */
order: string[]
/** The tracks to move; they keep their playlist order as one block. */
ids: string[]
onMove: (order: string[]) => void
onClose: () => void
}
/** "Set Position…": type where the first selected track should end up. */
export function SetPositionDialog({ order, ids, onMove, onClose }: Props) {
const moving = new Set(ids)
const count = order.filter((id) => moving.has(id)).length
const max = maxPosition(order, moving)
const current = order.findIndex((id) => moving.has(id)) + 1
const [value, setValue] = useState(String(current))
const input = useRef<HTMLInputElement>(null)
useEffect(() => input.current?.select(), [])
const typed = Number.parseInt(value, 10)
const position = Number.isFinite(typed) ? Math.min(Math.max(typed, 1), max) : null
const submit = () => {
if (position === null) return
const next = moveToPosition(order, moving, position)
if (next.some((id, i) => id !== order[i])) onMove(next)
onClose()
}
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const span = (p: number) => (count > 1 ? `#${p}–${p + count - 1}` : `#${p}`)
return createPortal(
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-[3px] p-6"
onClick={onClose}
>
<form
className="w-full max-w-sm overflow-hidden glass-overlay"
onClick={(e) => e.stopPropagation()}
onSubmit={(e) => {
e.preventDefault()
submit()
}}
>
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
Set position
</div>
<div className="space-y-3 px-5 py-4 text-sm text-muted">
<label className="flex items-center gap-2">
<span>{count > 1 ? `Move ${count} tracks to position` : 'Move to position'}</span>
<input
ref={input}
type="number"
inputMode="numeric"
min={1}
max={max}
value={value}
onChange={(e) => setValue(e.target.value)}
className="w-20 rounded-lg well px-2.5 py-1.5 text-sm tabular-nums text-text outline-none focus:ring-1 focus:ring-accent"
/>
<span>of {max}</span>
</label>
<div className="tabular-nums">
{position === null
? 'Type a position.'
: count > 1
? `Will occupy ${span(position)}`
: `Now ${span(current)} · will be ${span(position)}`}
</div>
</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
<button
type="button"
onClick={onClose}
className="btn-glass rounded-full px-4 py-1.5 text-sm text-muted hover:text-text"
>
Cancel
</button>
<button
type="submit"
disabled={position === null}
className="btn-primary rounded-full px-4 py-1.5 text-sm font-semibold disabled:opacity-50"
>
Move
</button>
</div>
</form>
</div>,
document.body,
)
}
+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',
+192 -13
View File
@@ -1,6 +1,7 @@
import { 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'
@@ -11,6 +12,9 @@ import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog'
import { ContextMenu, type MenuItem } from './ContextMenu' import { ContextMenu, type MenuItem } from './ContextMenu'
import { Icon, type IconName } from '../lib/icons' import { Icon, type IconName } from '../lib/icons'
import { PlatformIcon } from '../lib/platformIcons' import { PlatformIcon } from '../lib/platformIcons'
import { addTracksToPlaylist } from '../lib/addTracks'
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload } from '../lib/drag'
import { nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
/** /**
* Which view the main table is showing. * Which view the main table is showing.
@@ -50,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
@@ -57,11 +64,6 @@ interface Props {
// Kind picks the icon; every behavioural question is answered by the node's own // Kind picks the icon; every behavioural question is answered by the node's own
// flags, so nothing here infers what a node can do from what it is called. // flags, so nothing here infers what a node can do from what it is called.
/** Every selectable playlist at or under a node, in tree order. */
function playlistIdsUnder(node: PlaylistNode): string[] {
const here = node.kind === 'folder' ? [] : [node.id]
return [...here, ...(node.children ?? []).flatMap(playlistIdsUnder)]
}
/** The confirm wording for deleting a node. A folder says what goes with it, /** The confirm wording for deleting a node. A folder says what goes with it,
* since the whole subtree is deleted and the row only shows the folder. */ * since the whole subtree is deleted and the row only shows the folder. */
@@ -105,8 +107,27 @@ interface RowActions {
onPickExport: (e: React.MouseEvent<HTMLElement>, node: PlaylistNode) => void onPickExport: (e: React.MouseEvent<HTMLElement>, node: PlaylistNode) => void
onCommitDraft: (name: string) => void onCommitDraft: (name: string) => void
onCancelDraft: () => void onCancelDraft: () => void
/** Whether a drag of tracks may drop on this playlist. */
acceptsTracks: (node: PlaylistNode, p: Extract<DragPayload, { kind: 'tracks' }>) => boolean
/** Tracks dropped on a playlist; `alt` (Option) moves them out of the
* playlist they came from. */
onDropTracks: (node: PlaylistNode, p: Extract<DragPayload, { kind: 'tracks' }>, alt: boolean) => void
/** Whether a node may be dragged elsewhere in the tree. */
canMove: (node: PlaylistNode) => boolean
/** A node dropped in the tree: `index` among `parentId`'s children,
* counted without it (what `move_playlist` takes). */
onMoveNode: (node: PlaylistNode, parentId: string | null, index: number, into: PlaylistNode | null) => void
} }
/** Where a dragged node would land, relative to the row under the pointer:
* `before`/`after` it, `into` it (a folder; appended), or `first` inside it —
* the lower edge of an EXPANDED folder, where the line sits above its first
* child. `tracks` is a track drop on a playlist; `peek` is tracks held over a
* collapsed folder, which opens it and drops nothing. */
type RowHint =
| { zone: 'tracks' | 'peek' }
| { zone: 'before' | 'after' | 'into' | 'first'; parentId: string | null; index: number }
/** The inline name field for a node being created. Enter or clicking away /** The inline name field for a node being created. Enter or clicking away
* commits a non-empty name; Esc (or an empty name) creates nothing. */ * commits a non-empty name; Esc (or an empty name) creates nothing. */
function DraftRow({ function DraftRow({
@@ -156,6 +177,8 @@ function DraftRow({
function NodeRow({ function NodeRow({
node, node,
parentId,
siblings,
depth, depth,
source, source,
onSelect, onSelect,
@@ -166,6 +189,10 @@ function NodeRow({
actions, actions,
}: { }: {
node: PlaylistNode node: PlaylistNode
/** The folder this node sits in; null = the top level. */
parentId: string | null
/** That folder's children, this node included, in order. */
siblings: PlaylistNode[]
depth: number depth: number
source: Source source: Source
onSelect: (s: Source) => void onSelect: (s: Source) => void
@@ -191,14 +218,100 @@ function NodeRow({
setRenamingId(node.id) setRenamingId(node.id)
} }
// A row is a drag SOURCE (onto an export, or elsewhere in the tree) and a
// drop TARGET for tracks. Whether it takes them is the node's own
// `can_add_tracks` plus the library being writable, decided by the sidebar.
const startDrag = usePressToDrag(() => (renaming ? null : { kind: 'node', node, parentId }))
const moves = (p: DragPayload, alt: boolean) =>
p.kind === 'tracks' && alt && !!p.fromPlaylist && p.fromPlaylist !== node.id
// A node held over this row: which zone, and where that puts it. Never into
// itself or anything nested in it; a drop that would leave it exactly where
// it is shows nothing.
const placeNode = (p: Extract<DragPayload, { kind: 'node' }>, y: number, el: HTMLElement): RowHint | null => {
if (!actions.canMove(p.node) || nodeIdsUnder(p.node).has(node.id)) return null
const r = el.getBoundingClientRect()
const f = (y - r.top) / r.height
const opened = expanded && node.children.length > 0
const zone: 'before' | 'after' | 'into' | 'first' = node.can_contain_children
? f < 0.25 ? 'before' : f > 0.75 ? (opened ? 'first' : 'after') : 'into'
: f < 0.5 ? 'before' : 'after'
let target: string | null
let index: number
let current: PlaylistNode[]
if (zone === 'into' || zone === 'first') {
target = node.id
current = node.children
index = zone === 'first' ? 0 : node.children.filter((c) => c.id !== p.node.id).length
} else {
target = parentId
current = siblings
const i = siblings.filter((c) => c.id !== p.node.id).findIndex((c) => c.id === node.id)
index = zone === 'before' ? i : i + 1
}
if (target === p.parentId && current.findIndex((c) => c.id === p.node.id) === index) return null
return { zone, parentId: target, index }
}
const [dropRef, over] = useDropTarget<RowHint>({
hint: (p, at, el) => {
if (p.kind === 'node') return placeNode(p, at.y, el)
if (actions.acceptsTracks(node, p)) return { zone: 'tracks' }
return isFolder && !expanded ? { zone: 'peek' } : null
},
label: (p, h, at) => {
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
return h.zone === 'into' || h.zone === 'first' ? `Move into ${node.name}` : `Move ${h.zone} ${node.name}`
},
onDrop: (p, h, at) => {
if (p.kind === 'tracks') {
if (h.zone === 'tracks') actions.onDropTracks(node, p, at.alt)
} else if ('parentId' in h) {
actions.onMoveNode(p.node, h.parentId, h.index, h.zone === 'into' && !expanded ? node : null)
}
},
})
// Holding a drag over a collapsed folder opens it, so a playlist nested in
// it can be reached without letting go.
const opening = over?.zone === 'into' || over?.zone === 'peek'
useEffect(() => {
if (!opening || expanded) return
const t = setTimeout(() => setOpen(true), 600)
return () => clearTimeout(t)
}, [opening, expanded])
const ringed = over?.zone === 'tracks' || over?.zone === 'into'
const dragging = useDragPayload()
const beingMoved = dragging?.kind === 'node' && dragging.node.id === node.id
const line = over?.zone === 'before' || over?.zone === 'after' || over?.zone === 'first' ? over.zone : null
return ( return (
<div> <div className={beingMoved ? 'opacity-40' : undefined}>
<div <div
ref={dropRef}
data-node-row
onPointerDown={startDrag}
onContextMenu={(e) => actions.onContextMenu(e, node)} onContextMenu={(e) => actions.onContextMenu(e, node)}
className={`group flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${ className={`group relative flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${
selected ? 'is-selected font-medium text-text' : 'text-muted hover:bg-ink-800 hover:text-text' ringed
? 'bg-accent-soft/40 text-text ring-1 ring-accent'
: selected
? 'is-selected font-medium text-text'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`} }`}
> >
{line && (
<span
aria-hidden
className={`pointer-events-none absolute right-1 h-0.5 rounded-full bg-accent ${
line === 'before' ? '-top-px' : '-bottom-px'
}`}
style={{ left: 8 + (line === 'first' ? depth + 1 : depth) * 14 }}
/>
)}
<button <button
onClick={() => { onClick={() => {
if (isFolder) setOpen((o) => !o) if (isFolder) setOpen((o) => !o)
@@ -298,6 +411,8 @@ function NodeRow({
<NodeRow <NodeRow
key={c.id} key={c.id}
node={c} node={c}
parentId={node.id}
siblings={node.children}
depth={depth + 1} depth={depth + 1}
source={source} source={source}
onSelect={onSelect} onSelect={onSelect}
@@ -323,6 +438,7 @@ export function Sidebar({
onSwitchLibrary, onSwitchLibrary,
onOpenLibrary, onOpenLibrary,
onDone, onDone,
onAddForeign,
onOpenPathMapping, onOpenPathMapping,
onDiscarded, onDiscarded,
}: Props) { }: Props) {
@@ -339,8 +455,9 @@ export function Sidebar({
} }
// There is no per-node flag for "you may create a NEW playlist" — the node // There is no per-node flag for "you may create a NEW playlist" — the node
// flags describe existing nodes — so this is the library-level gate. // flags describe existing nodes — so this is the library-level gate.
const canCreate = useCaps().writable const caps = useCaps()
const foldersSupported = useCaps().playlists.folders const canCreate = caps.writable
const foldersSupported = caps.playlists.folders
const { data: playlists, isLoading } = useQuery({ const { data: playlists, isLoading } = useQuery({
queryKey: ['playlists'], queryKey: ['playlists'],
queryFn: api.playlists, queryFn: api.playlists,
@@ -496,8 +613,59 @@ export function Sidebar({
setDraft(null) setDraft(null)
}, },
onCancelDraft: () => setDraft(null), onCancelDraft: () => setDraft(null),
// A device's or a folder's tracks are not in the collection yet, so they
// can only come if the collection can ADD tracks — via the add dialog.
acceptsTracks: (node, p) =>
caps.writable &&
node.can_add_tracks &&
(p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable),
canMove: (node) => caps.writable && node.can_move,
onMoveNode: async (node, parentId, index, into) => {
try {
await api.movePlaylist(node.id, parentId, index)
invalidate()
// Into a COLLAPSED folder the node vanishes from view, so say where.
if (into) onDone(`Moved “${node.name}” into ${into.name}`)
} catch (e) {
onError((e as Error).message)
}
},
onDropTracks: async (node, p, alt) => {
if (p.origin !== 'collection') {
onAddForeign(p.origin, p.ids, { kind: 'playlist', id: node.id, name: node.name })
return
}
try {
const msg = await addTracksToPlaylist({
qc,
playlist: node,
ids: p.ids,
duplicatesAllowed: caps.playlists.duplicates,
moveFrom: alt ? p.fromPlaylist : undefined,
})
if (msg) onDone(msg)
} catch (e) {
onError((e as Error).message)
}
},
} }
// The empty space below the rows: a node dropped there goes to the END of
// the top level. Only the space itself — over a row that declined (a folder
// into its own subtree), nothing happens rather than this.
const roots = playlists ?? []
const [rootDropRef, rootOver] = useDropTarget<{ index: number }>({
hint: (p, at) => {
if (p.kind !== 'node' || !actions.canMove(p.node)) return null
if (document.elementFromPoint(at.x, at.y)?.closest('[data-node-row]')) return null
const index = roots.filter((n) => n.id !== p.node.id).length
if (p.parentId === null && roots.findIndex((n) => n.id === p.node.id) === index) return null
return { index }
},
label: () => 'Move to the top level',
onDrop: (p, h) => p.kind === 'node' && actions.onMoveNode(p.node, null, h.index, null),
})
return ( return (
<aside className="glass flex h-full w-64 shrink-0 flex-col"> <aside className="glass flex h-full w-64 shrink-0 flex-col">
{/* Which library is open — and the way to open a different one. Until {/* Which library is open — and the way to open a different one. Until
@@ -563,6 +731,8 @@ export function Sidebar({
{/* Right-click here (below the rows) creates at the top level; rows {/* Right-click here (below the rows) creates at the top level; rows
stop the event so they get their own menu. */} stop the event so they get their own menu. */}
<div <div
ref={rootDropRef}
data-drag-scroll=""
className="mt-1 min-h-24 flex-1 overflow-y-auto px-2 pb-4" className="mt-1 min-h-24 flex-1 overflow-y-auto px-2 pb-4"
onContextMenu={(e) => openMenu(e, createItems(null))} onContextMenu={(e) => openMenu(e, createItems(null))}
> >
@@ -572,6 +742,8 @@ export function Sidebar({
<NodeRow <NodeRow
key={n.id} key={n.id}
node={n} node={n}
parentId={null}
siblings={playlists}
depth={0} depth={0}
source={source} source={source}
onSelect={onSelect} onSelect={onSelect}
@@ -582,12 +754,19 @@ export function Sidebar({
actions={actions} actions={actions}
/> />
))} ))}
{rootOver && <div aria-hidden className="mx-2 mt-0.5 h-0.5 rounded-full bg-accent" />}
</div> </div>
{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 -1
View File
@@ -59,7 +59,7 @@ export function Toolbar({
value={filters.search} value={filters.search}
onChange={(e) => set({ search: e.target.value })} onChange={(e) => set({ search: e.target.value })}
ref={searchRef} ref={searchRef}
placeholder="Search artist, title, album…" placeholder="Artist, title, album, comment…"
className="well w-72 rounded-full py-1.5 pl-9 pr-8 text-sm text-text outline-none placeholder:text-faint focus:ring-1 focus:ring-accent" className="well w-72 rounded-full py-1.5 pl-9 pr-8 text-sm text-text outline-none placeholder:text-faint focus:ring-1 focus:ring-accent"
/> />
{filters.search && ( {filters.search && (
+88 -94
View File
@@ -1,4 +1,4 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject } from 'react' import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject } from 'react'
import { import {
flexRender, flexRender,
getCoreRowModel, getCoreRowModel,
@@ -29,7 +29,8 @@ import {
useSortable, useSortable,
} from '@dnd-kit/sortable' } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities' import { CSS } from '@dnd-kit/utilities'
import type { Track } from '../api' import type { Track, TrackOrigin } from '../api'
import { beginDrag, useDragPayload, useDropTarget } from '../lib/drag'
import { TRACK_COLUMNS } from '../lib/trackColumns' import { TRACK_COLUMNS } from '../lib/trackColumns'
/** Fields this platform can persist, for the table's per-cell edit gating. /** Fields this platform can persist, for the table's per-cell edit gating.
@@ -71,6 +72,9 @@ interface Props {
/** A view with a manual order. `enabled` is false while a sort or filter is /** A view with a manual order. `enabled` is false while a sort or filter is
* active: reordering a partial or re-sorted list would lose the real order. */ * active: reordering a partial or re-sorted list would lose the real order. */
reorder?: { enabled: boolean; onReorder: (ids: string[]) => void } reorder?: { enabled: boolean; onReorder: (ids: string[]) => void }
/** Where dragged rows come from: whose ids they are, and the editable
* playlist they leave on an Option-drag (move). Defaults to the collection. */
dragFrom?: { origin: TrackOrigin; playlistId?: string }
/** Delete/Backspace removes the selected tracks from this view. */ /** Delete/Backspace removes the selected tracks from this view. */
onRemove?: (ids: string[]) => void onRemove?: (ids: string[]) => void
onRowContextMenu?: (track: Track, x: number, y: number) => void onRowContextMenu?: (track: Track, x: number, y: number) => void
@@ -277,6 +281,7 @@ export function TrackTable({
positions, positions,
marked, marked,
reorder, reorder,
dragFrom,
onRemove, onRemove,
onRowContextMenu, onRowContextMenu,
onHeaderContextMenu, onHeaderContextMenu,
@@ -363,7 +368,7 @@ export function TrackTable({
} }
const clickRow = (index: number, e: { shiftKey: boolean; metaKey: boolean; ctrlKey: boolean }) => { const clickRow = (index: number, e: { shiftKey: boolean; metaKey: boolean; ctrlKey: boolean }) => {
if (!selection || justDraggedRef.current) return if (!selection) return
const id = rows[index].original.id const id = rows[index].original.id
const toggle = e.metaKey || e.ctrlKey const toggle = e.metaKey || e.ctrlKey
const anchor = indexOf(anchorRef.current) const anchor = indexOf(anchorRef.current)
@@ -381,102 +386,88 @@ export function TrackTable({
} }
} }
// ---- row drag-to-reorder ---------------------------------------------- // ---- dragging rows ------------------------------------------------------
// `drop` is the gap the dragged rows would land in (0 = above the first row). // Every table's rows are a drag SOURCE (onto playlists, exports, the deck —
const [drag, setDrag] = useState<{ moving: Set<number>; drop: number } | null>(null) // lib/drag.tsx); a view with a manual order is also its own drop TARGET, the
// in-table reorder. `drop` is the gap the rows would land in (0 = above the
// first row).
const pressRef = useRef<{ x: number; y: number; index: number } | null>(null) const pressRef = useRef<{ x: number; y: number; index: number } | null>(null)
const justDraggedRef = useRef(false) const tableKey = useRef({}).current
const canDrag = !!reorder?.enabled const dragging = useDragPayload()
const ownDrag = dragging?.kind === 'tracks' && dragging.source === tableKey ? dragging : null
const movingIds = useMemo(() => new Set(ownDrag?.ids ?? []), [ownDrag])
useEffect(() => { useEffect(() => {
if (!canDrag) return
let raf = 0
let lastY = 0
let active: { moving: Set<number>; drop: number } | null = null
const dropAt = (clientY: number) => {
const top = bodyRef.current?.getBoundingClientRect().top ?? 0
return Math.max(0, Math.min(rowsRef.current.length, Math.round((clientY - top) / ROW_HEIGHT)))
}
// Hold near the top/bottom edge to scroll while dragging.
const autoScroll = () => {
const el = parentRef.current
if (el && active) {
const r = el.getBoundingClientRect()
const edge = 48
const dy =
lastY < r.top + edge + ROW_HEIGHT ? -12 : lastY > r.bottom - edge ? 12 : 0
if (dy) {
el.scrollTop += dy
active = { ...active, drop: dropAt(lastY) }
setDrag(active)
}
}
raf = requestAnimationFrame(autoScroll)
}
const onMove = (e: PointerEvent) => { const onMove = (e: PointerEvent) => {
const press = pressRef.current const press = pressRef.current
if (!press) return if (!press || Math.hypot(e.clientX - press.x, e.clientY - press.y) < 6) return
lastY = e.clientY
if (!active) {
if (Math.hypot(e.clientX - press.x, e.clientY - press.y) < 6) return
// Dragging a selected row moves the whole selection; any other row
// moves alone (and becomes the selection, so what moves is visible).
const rs = rowsRef.current
const sel = selectionRef.current
const pressedId = rs[press.index].original.id
let moving: Set<number>
if (sel?.selected.has(pressedId)) {
moving = new Set(rs.flatMap((r, i) => (sel.selected.has(r.original.id) ? [i] : [])))
} else {
moving = new Set([press.index])
sel?.onChange(new Set([pressedId]))
anchorRef.current = leadRef.current = pressedId
}
active = { moving, drop: dropAt(e.clientY) }
document.body.style.userSelect = 'none'
document.body.style.cursor = 'grabbing'
window.getSelection()?.removeAllRanges()
raf = requestAnimationFrame(autoScroll)
} else {
active = { ...active, drop: dropAt(e.clientY) }
}
setDrag(active)
}
const end = () => {
pressRef.current = null pressRef.current = null
if (!active) return // Dragging a selected row carries the whole selection (in the table's
const { moving, drop } = active // order); any other row goes alone and becomes the selection, so what is
active = null // being dragged is visible.
cancelAnimationFrame(raf) const rs = rowsRef.current
document.body.style.userSelect = '' const sel = selectionRef.current
document.body.style.cursor = '' const pressed = rs[press.index]?.original
setDrag(null) if (!pressed) return
// Swallow the click that follows the pointerup, so a drop is not also a let carried: Track[]
// click that re-selects the row it ended on. if (sel?.selected.has(pressed.id)) {
justDraggedRef.current = true carried = rs.filter((r) => sel.selected.has(r.original.id)).map((r) => r.original)
setTimeout(() => (justDraggedRef.current = false), 0) } else {
carried = [pressed]
sel?.onChange(new Set([pressed.id]))
anchorRef.current = leadRef.current = pressed.id
}
const from = dragFromRef.current
beginDrag(
{
kind: 'tracks',
ids: [...new Set(carried.map((t) => t.id))],
tracks: carried,
lead: pressed,
origin: from?.origin ?? 'collection',
fromPlaylist: from?.playlistId,
source: tableKey,
},
{ x: e.clientX, y: e.clientY, alt: e.altKey },
)
}
const release = () => (pressRef.current = null)
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', release)
window.addEventListener('pointercancel', release)
return () => {
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', release)
window.removeEventListener('pointercancel', release)
}
}, [tableKey])
const [dropRef, dropHint] = useDropTarget<{ drop: number }>({
hint: (p, at) => {
if (p.kind !== 'tracks' || p.source !== tableKey || !reorderRef.current?.enabled) return null
const top = bodyRef.current?.getBoundingClientRect().top ?? 0
return { drop: Math.max(0, Math.min(rowsRef.current.length, Math.round((at.y - top) / ROW_HEIGHT))) }
},
onDrop: (p, { drop }) => {
if (p.kind !== 'tracks') return
const ids = new Set(p.ids)
const rs = rowsRef.current.map((r) => r.original) const rs = rowsRef.current.map((r) => r.original)
const kept = rs.filter((_, i) => !moving.has(i)) const kept = rs.filter((t) => !ids.has(t.id))
const block = rs.filter((_, i) => moving.has(i)) const block = rs.filter((t) => ids.has(t.id))
const at = drop - [...moving].filter((i) => i < drop).length const at = drop - rs.slice(0, drop).filter((t) => ids.has(t.id)).length
const next = [...kept.slice(0, at), ...block, ...kept.slice(at)] const next = [...kept.slice(0, at), ...block, ...kept.slice(at)]
if (next.every((t, i) => t === rs[i])) return if (next.every((t, i) => t === rs[i])) return
setData(next) setData(next)
reorderRef.current?.onReorder(next.map((t) => t.id)) reorderRef.current?.onReorder(next.map((t) => t.id))
} },
window.addEventListener('pointermove', onMove) })
window.addEventListener('pointerup', end) const scrollerRef = useCallback(
window.addEventListener('pointercancel', end) (el: HTMLDivElement | null) => {
return () => { parentRef.current = el
cancelAnimationFrame(raf) dropRef(el)
window.removeEventListener('pointermove', onMove) },
window.removeEventListener('pointerup', end) [dropRef],
window.removeEventListener('pointercancel', end) )
document.body.style.userSelect = ''
document.body.style.cursor = ''
}
}, [canDrag])
// Latest values for the once-attached window listeners. // Latest values for the once-attached window listeners.
const rowsRef = useRef(rows) const rowsRef = useRef(rows)
@@ -485,6 +476,8 @@ export function TrackTable({
selectionRef.current = selection selectionRef.current = selection
const reorderRef = useRef(reorder) const reorderRef = useRef(reorder)
reorderRef.current = reorder reorderRef.current = reorder
const dragFromRef = useRef(dragFrom)
dragFromRef.current = dragFrom
// Keyboard: ↑/↓ move the selection (Shift extends it), Cmd/Ctrl+A selects // Keyboard: ↑/↓ move the selection (Shift extends it), Cmd/Ctrl+A selects
// every visible row, Esc clears, Delete/Backspace removes (where the view // every visible row, Esc clears, Delete/Backspace removes (where the view
@@ -547,7 +540,8 @@ export function TrackTable({
return ( return (
<div <div
ref={parentRef} ref={scrollerRef}
data-drag-scroll={bodyOffset.header}
className="h-full overflow-auto px-1.5" className="h-full overflow-auto px-1.5"
onClick={(e) => { onClick={(e) => {
// A click in the empty space below the rows clears the selection. // A click in the empty space below the rows clears the selection.
@@ -568,13 +562,13 @@ export function TrackTable({
const row = rows[vr.index] const row = rows[vr.index]
const isSelected = selection?.selected.has(row.original.id) ?? false const isSelected = selection?.selected.has(row.original.id) ?? false
const isActive = activeTrackId === row.original.id const isActive = activeTrackId === row.original.id
const isMoving = drag?.moving.has(vr.index) ?? false const isMoving = movingIds.has(row.original.id)
return ( return (
<div <div
key={row.id} key={row.id}
data-row data-row
className={`group absolute left-0 flex items-center border-b border-ink-850 text-sm ${ className={`group absolute left-0 flex items-center border-b border-ink-850 text-sm ${
isSelected ? 'bg-accent-soft/50' : drag ? '' : 'hover:bg-ink-850' isSelected ? 'bg-accent-soft/50' : dragging ? '' : 'hover:bg-ink-850'
} ${isMoving ? 'opacity-40' : ''}`} } ${isMoving ? 'opacity-40' : ''}`}
style={{ top: 0, transform: `translateY(${vr.start - bodyOffset.top}px)`, height: vr.size, width: '100%' }} style={{ top: 0, transform: `translateY(${vr.start - bodyOffset.top}px)`, height: vr.size, width: '100%' }}
onMouseDown={(e) => { onMouseDown={(e) => {
@@ -582,7 +576,7 @@ export function TrackTable({
if (selection && (e.shiftKey || e.metaKey || e.ctrlKey)) e.preventDefault() if (selection && (e.shiftKey || e.metaKey || e.ctrlKey)) e.preventDefault()
}} }}
onPointerDown={(e) => { onPointerDown={(e) => {
if (!canDrag || e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return
// Not from a control inside the row (play, stars, an edit field). // Not from a control inside the row (play, stars, an edit field).
if ((e.target as HTMLElement).closest('button, input, textarea, select, a')) return if ((e.target as HTMLElement).closest('button, input, textarea, select, a')) return
pressRef.current = { x: e.clientX, y: e.clientY, index: vr.index } pressRef.current = { x: e.clientX, y: e.clientY, index: vr.index }
@@ -620,10 +614,10 @@ export function TrackTable({
</div> </div>
) )
})} })}
{drag && ( {dropHint && (
<div <div
className="pointer-events-none absolute left-0 z-10 h-0.5 w-full bg-accent" className="pointer-events-none absolute left-0 z-10 h-0.5 w-full bg-accent"
style={{ top: drag.drop * ROW_HEIGHT - 1 }} style={{ top: dropHint.drop * ROW_HEIGHT - 1 }}
/> />
)} )}
</div> </div>
+7
View File
@@ -87,6 +87,13 @@ body,
overscroll-behavior: none; overscroll-behavior: none;
} }
/* While something is being dragged (lib/drag.tsx), the cursor is the hand
everywhere — buttons and links would otherwise show their own. */
html.is-dragging,
html.is-dragging * {
cursor: grabbing !important;
}
body { body {
margin: 0; margin: 0;
background: var(--color-ink-950); background: var(--color-ink-950);
+69
View File
@@ -0,0 +1,69 @@
import type { QueryClient } from '@tanstack/react-query'
import { api } from '../api'
import { askChoice } from './confirm'
const plural = (n: number) => `${n} track${n === 1 ? '' : 's'}`
/**
* Add tracks to a playlist — the context menu's "Add to" and a drop on a
* sidebar playlist alike, so the two cannot drift.
*
* Tracks the playlist already holds are ASKED about (decided 2026-10-06), but
* only where the platform can hold a track twice (`playlists.duplicates`);
* elsewhere they are skipped and the message says so. Nothing is asked when
* there are none.
*
* `moveFrom` is an Option-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.
*
* Resolves the message to show, or null when the user cancelled.
*/
export async function addTracksToPlaylist(opts: {
qc: QueryClient
playlist: { id: string; name: string }
ids: string[]
duplicatesAllowed: boolean
moveFrom?: string
}): Promise<string | null> {
const { qc, playlist, ids, duplicatesAllowed, moveFrom } = opts
let res = await api.addEntries(playlist.id, ids, duplicatesAllowed ? 'ask' : 'skip')
if (res.status === 'duplicates') {
const fresh = ids.length - res.duplicates
const all = fresh === 0
const choice = await askChoice({
title: all
? `${ids.length === 1 ? 'This track is' : `All ${ids.length} tracks are`} already in “${playlist.name}”`
: `${plural(res.duplicates)} ${res.duplicates === 1 ? 'is' : 'are'} already in “${playlist.name}”`,
body: all
? ids.length === 1
? 'Add it again, so the playlist holds it twice?'
: 'Add them again, so the playlist holds them twice?'
: `Add only the ${plural(fresh)} not there yet, or add every track — the ${res.duplicates === 1 ? 'one already there' : `${res.duplicates} already there`} a second time?`,
// All of them there: "skip" would add nothing, which is just Cancel —
// so the question is only whether to add them again.
confirmLabel: all ? 'Add again' : `Add ${plural(fresh)}`,
altLabel: all ? undefined : `Add all ${ids.length}`,
tone: 'primary',
})
if (choice === null) return null
res = await api.addEntries(playlist.id, ids, choice === 'alt' || all ? 'add' : 'skip')
}
let moved = false
if (moveFrom && moveFrom !== playlist.id) {
const gone = new Set(ids)
const current = await api.playlistTracks(moveFrom)
await api.setEntries(moveFrom, current.map((t) => t.id).filter((id) => !gone.has(id)))
qc.invalidateQueries({ queryKey: ['playlist', moveFrom] })
moved = true
}
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['playlists'] })
qc.invalidateQueries({ queryKey: ['playlist', playlist.id] })
const skipped = ids.length - res.added
if (moved) return `Moved ${plural(ids.length)} to ${playlist.name}`
if (res.added === 0) return `Nothing added — ${ids.length === 1 ? 'it is' : 'they are all'} already in ${playlist.name}`
return `Added ${plural(res.added)} to ${playlist.name}${skipped > 0 ? ` · ${skipped} already there` : ''}`
}
+15 -7
View File
@@ -12,19 +12,26 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { ConfirmDialog, type ConfirmRequest } from '../components/ConfirmDialog' import { ConfirmDialog, type ConfirmRequest } from '../components/ConfirmDialog'
type Ask = Omit<ConfirmRequest, 'onConfirm'> type Ask = Omit<ConfirmRequest, 'onConfirm' | 'onAlt' | 'altLabel'>
type Pending = { req: Ask; resolve: (ok: boolean) => void } type Choice = 'confirm' | 'alt' | null
type Pending = { req: Ask & { altLabel?: string }; resolve: (choice: Choice) => void }
let open: ((p: Pending) => void) | null = null let open: ((p: Pending) => void) | null = null
/** Show a confirmation and resolve true (confirmed) or false (cancelled). */ /** Show a confirmation and resolve true (confirmed) or false (cancelled). */
export function askConfirm(req: Ask): Promise<boolean> { export function askConfirm(req: Ask): Promise<boolean> {
return askChoice(req).then((c) => c === 'confirm')
}
/** A confirmation with a SECOND way to go ahead (`altLabel`): resolves
* 'confirm', 'alt', or null when cancelled. */
export function askChoice(req: Ask & { altLabel?: string }): Promise<Choice> {
return new Promise((resolve) => { return new Promise((resolve) => {
if (open) open({ req, resolve }) if (open) open({ req, resolve })
// No host mounted (should not happen outside tests): refuse rather than // No host mounted (should not happen outside tests): refuse rather than
// fall back to a native dialog, since a destructive action must not go // fall back to a native dialog, since a destructive action must not go
// ahead unconfirmed. // ahead unconfirmed.
else resolve(false) else resolve(null)
}) })
} }
@@ -34,7 +41,7 @@ export function ConfirmHost() {
useEffect(() => { useEffect(() => {
open = (p) => open = (p) =>
setPending((prev) => { setPending((prev) => {
prev?.resolve(false) // a second ask supersedes an unanswered one prev?.resolve(null) // a second ask supersedes an unanswered one
return p return p
}) })
return () => { return () => {
@@ -45,10 +52,11 @@ export function ConfirmHost() {
return ( return (
<ConfirmDialog <ConfirmDialog
{...pending.req} {...pending.req}
// A promise settles once, so confirm-then-close resolves `true`. // A promise settles once, so confirm-then-close resolves 'confirm'.
onConfirm={() => pending.resolve(true)} onConfirm={() => pending.resolve('confirm')}
onAlt={() => pending.resolve('alt')}
onClose={() => { onClose={() => {
pending.resolve(false) pending.resolve(null)
setPending(null) setPending(null)
}} }}
/> />
+301
View File
@@ -0,0 +1,301 @@
import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'
import { createPortal } from 'react-dom'
import type { PlaylistNode, Track, TrackOrigin } from '../api'
import { Icon } from './icons'
/**
* Drag and drop across the whole window: track rows onto sidebar playlists,
* exports and the deck; playlists around the sidebar tree.
*
* ONE gesture, and the drop TARGET decides what it means. A source calls
* `beginDrag` once the pointer has moved past its threshold; targets register
* with `useDropTarget` and are found by hit-testing (`elementFromPoint`, then up
* through the ancestors), so the virtualized table, the sidebar and the deck
* need no shared React tree — and the innermost target that accepts wins, with
* the search falling through to an enclosing one where it declines.
*
* Pointer events, NOT HTML5 drag and drop: Tauri's webview captures native drag
* events for its own file drop on Windows, so HTML5 DnD silently dies in the
* packaged app.
*
* The state lives in a module-level store read through useSyncExternalStore
* with narrow selectors, so a pointer move re-renders only the target under it
* (and the ghost) — never the table.
*/
export type DragPayload =
| {
kind: 'tracks'
ids: string[]
tracks: Track[]
/** 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
* the collection's, so collection targets must not take them as such. */
origin: TrackOrigin
/** The editable playlist they were dragged out of, for Option = move. */
fromPlaylist?: string
/** Identity of the table that started the drag (its own reorder target). */
source: object
}
| { kind: 'node'; node: PlaylistNode; parentId: string | null }
export interface DropPoint {
x: number
y: number
/** Option/Alt held: tracks dragged out of a playlist MOVE instead of copy. */
alt: boolean
}
export interface DropSpec<H> {
/** The hint for a pointer at `at` over this target — anything the target
* needs to draw and to drop (an insertion index, a before/into/after zone) —
* or null where it does not accept this drop, so the search continues to an
* enclosing target. */
hint: (p: DragPayload, at: DropPoint, el: HTMLElement) => H | null
/** What a drop here would do, shown on the ghost ("Add to Warmup"). */
label?: (p: DragPayload, hint: H, at: DropPoint) => string | null
onDrop: (p: DragPayload, hint: H, at: DropPoint) => void
}
interface State {
payload: DragPayload | null
x: number
y: number
alt: boolean
target: HTMLElement | null
hint: unknown
label: string | null
}
const IDLE: State = { payload: null, x: 0, y: 0, alt: false, target: null, hint: null, label: null }
let state: State = IDLE
const listeners = new Set<() => void>()
const targets = new Map<HTMLElement, { current: DropSpec<unknown> }>()
function set(next: Partial<State>) {
state = { ...state, ...next }
listeners.forEach((l) => l())
}
function subscribe(l: () => void) {
listeners.add(l)
return () => listeners.delete(l)
}
/** Keep the previous hint object when the new one has the same fields, so a
* target re-renders only when what it draws changes, not on every move. */
function sameHint(a: unknown, b: unknown): boolean {
if (a === b) return true
if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false
const ka = Object.keys(a)
return (
ka.length === Object.keys(b).length &&
ka.every((k) => (a as Record<string, unknown>)[k] === (b as Record<string, unknown>)[k])
)
}
/** Find the innermost target under the pointer that accepts, and record its hint. */
function evaluate() {
const { payload, x, y, alt } = state
if (!payload) return
const at = { x, y, alt }
let el = document.elementFromPoint(x, y) as HTMLElement | null
while (el) {
const spec = targets.get(el)
if (spec) {
const hint = spec.current.hint(payload, at, el)
if (hint != null) {
const keep = state.target === el && sameHint(state.hint, hint) ? state.hint : hint
set({ target: el, hint: keep, label: spec.current.label?.(payload, keep, at) ?? null })
return
}
}
el = el.parentElement
}
set({ target: null, hint: null, label: null })
}
let detach: (() => void) | null = null
/** Start a drag. Call it once the press has moved past the source's threshold. */
export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) {
detach?.()
set({ ...IDLE, payload, ...at })
document.documentElement.classList.add('is-dragging')
window.getSelection()?.removeAllRanges()
const onMove = (e: PointerEvent) => {
// One notification per move: evaluate() publishes the position with the hint.
state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey }
evaluate()
}
const finish = (drop: boolean) => {
const { payload: p, target, hint, x, y, alt } = state
detach?.()
if (!drop || !p || !target) return
const spec = targets.get(target)
try {
spec?.current.onDrop(p, hint, { x, y, alt })
} catch (err) {
console.error('drop failed', err)
}
}
const onUp = () => finish(true)
const onCancel = () => finish(false)
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape' && e.type === 'keydown') {
// Before every other Esc handler: cancelling the drag is all Esc does.
e.preventDefault()
e.stopImmediatePropagation()
finish(false)
return
}
if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) {
set({ alt: e.type === 'keydown' })
evaluate()
}
}
// Hold near the edge of a `data-drag-scroll` element to scroll it. Its
// value is the height covered at the top (a sticky header). The edge is
// thinner than a row and must be HELD for a moment first: otherwise the
// first or last visible row cannot be dropped on, because the list scrolls
// out from under a pointer resting on it.
let raf = 0
const dwell = new Map<HTMLElement, number>()
const autoScroll = () => {
const { x, y } = state
let scrolled = false
document.querySelectorAll<HTMLElement>('[data-drag-scroll]').forEach((el) => {
const r = el.getBoundingClientRect()
const top = r.top + Number(el.dataset.dragScroll || 0)
const edge = 20
const inside = x >= r.left && x <= r.right && y >= r.top - 24 && y <= r.bottom + 24
const dy = !inside ? 0 : y < top + edge ? -Math.ceil((top + edge - y) / 3) : y > r.bottom - edge ? Math.ceil((y - r.bottom + edge) / 3) : 0
if (!dy) {
dwell.delete(el)
return
}
const since = dwell.get(el) ?? performance.now()
dwell.set(el, since)
if (performance.now() - since < 250) return
const before = el.scrollTop
el.scrollTop += Math.max(-20, Math.min(20, dy))
scrolled ||= el.scrollTop !== before
})
if (scrolled) evaluate()
raf = requestAnimationFrame(autoScroll)
}
raf = requestAnimationFrame(autoScroll)
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', onUp)
window.addEventListener('pointercancel', onCancel)
window.addEventListener('keydown', onKey, true)
window.addEventListener('keyup', onKey, true)
window.addEventListener('blur', onCancel)
detach = () => {
detach = null
cancelAnimationFrame(raf)
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', onUp)
window.removeEventListener('pointercancel', onCancel)
window.removeEventListener('keydown', onKey, true)
window.removeEventListener('keyup', onKey, true)
window.removeEventListener('blur', onCancel)
document.documentElement.classList.remove('is-dragging')
// The pointerup that ended the drag is followed by a click on whatever
// is under it; that click is part of the drop, not a click of its own.
const swallow = (e: MouseEvent) => {
e.stopPropagation()
e.preventDefault()
}
window.addEventListener('click', swallow, true)
setTimeout(() => window.removeEventListener('click', swallow, true), 0)
set(IDLE)
}
evaluate()
}
/** A pointerdown handler that starts a drag once the press moves 6 px. A plain
* click never moves that far, so the element keeps its click; a press on a
* field inside it (a rename input) never drags. `make` is asked at the moment
* the drag starts and may return null to refuse. */
export function usePressToDrag(make: () => DragPayload | null): (e: React.PointerEvent) => void {
const makeRef = useRef(make)
makeRef.current = make
return useCallback((e: React.PointerEvent) => {
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return
if ((e.target as HTMLElement).closest('input, textarea, select')) return
const start = { x: e.clientX, y: e.clientY }
const onMove = (m: PointerEvent) => {
if (Math.hypot(m.clientX - start.x, m.clientY - start.y) < 6) return
stop()
const payload = makeRef.current()
if (payload) beginDrag(payload, { x: m.clientX, y: m.clientY, alt: m.altKey })
}
const stop = () => {
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', stop)
window.removeEventListener('pointercancel', stop)
}
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', stop)
window.addEventListener('pointercancel', stop)
}, [])
}
/** The drag in progress, or null. Changes only when a drag starts or ends. */
export function useDragPayload(): DragPayload | null {
return useSyncExternalStore(subscribe, () => state.payload)
}
/** Register an element as a drop target. Returns the ref to attach and the
* current hint while the pointer is over it (null otherwise). */
export function useDropTarget<H>(spec: DropSpec<H>): [(el: HTMLElement | null) => void, H | null] {
const specRef = useRef(spec as DropSpec<unknown>)
specRef.current = spec as DropSpec<unknown>
const elRef = useRef<HTMLElement | null>(null)
const ref = useCallback((el: HTMLElement | null) => {
if (elRef.current) targets.delete(elRef.current)
elRef.current = el
if (el) targets.set(el, specRef)
}, [])
useEffect(() => () => {
if (elRef.current) targets.delete(elRef.current)
}, [])
const hint = useSyncExternalStore(subscribe, () =>
state.target !== null && state.target === elRef.current ? state.hint : null,
)
return [ref, hint as H | null]
}
/** What the ghost says it is carrying. */
function describe(p: DragPayload): { icon: 'music' | 'playlist' | 'folder' | 'smart'; text: string } {
if (p.kind === 'node')
return { icon: p.node.kind === 'folder' ? 'folder' : p.node.kind === 'smart' ? 'smart' : 'playlist', text: p.node.name }
if (p.ids.length === 1) {
const t = p.tracks[0]
return { icon: 'music', text: t ? [t.artist, t.title].filter(Boolean).join(' – ') || 'Untitled' : '1 track' }
}
return { icon: 'music', text: `${p.ids.length} tracks` }
}
/** The ghost under the cursor. Mounted once, in main.tsx. */
export function DragLayer() {
const s = useSyncExternalStore(subscribe, () => state)
if (!s.payload) return null
const { icon, text } = describe(s.payload)
return createPortal(
<div
className="glass-overlay pointer-events-none fixed left-0 top-0 z-[90] flex max-w-72 flex-col gap-0.5 overflow-hidden rounded-xl px-3 py-1.5 text-xs shadow-lg"
style={{ transform: `translate(${s.x + 14}px, ${s.y + 12}px)` }}
>
<span className="flex min-w-0 items-center gap-1.5 text-text">
<Icon name={icon} size={13} className="shrink-0 text-muted" />
<span className="truncate">{text}</span>
</span>
{s.label && <span className="truncate text-[11px] text-accent">{s.label}</span>}
</div>,
document.body,
)
}
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest'
import { maxPosition, moveToPosition } from './playlistOrder'
const order = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
const move = (ids: string[], position: number) => moveToPosition(order, new Set(ids), position).join('')
describe('moveToPosition', () => {
it('puts the track AT the position, moving down or up', () => {
expect(move(['B'], 5)).toBe('ACDEBFG')
expect(move(['F'], 2)).toBe('AFBCDEG')
expect(move(['A'], 1)).toBe('ABCDEFG')
})
it('moves a selection as one block in playlist order', () => {
expect(move(['F', 'B'], 2)).toBe('ABFCDEG')
expect(move(['G', 'A', 'D'], 3)).toBe('BCADGEF')
})
it('clamps past either end', () => {
expect(move(['B', 'C'], 99)).toBe('ADEFGBC')
expect(move(['C'], 0)).toBe('CABDEFG')
})
it('moves every entry of a track listed twice', () => {
expect(moveToPosition(['A', 'B', 'A', 'C'], new Set(['A']), 2).join('')).toBe('BAAC')
})
})
describe('maxPosition', () => {
it('leaves room for the block behind its first track', () => {
expect(maxPosition(order, new Set(['B']))).toBe(7)
expect(maxPosition(order, new Set(['B', 'C', 'D']))).toBe(5)
expect(move(['B', 'C', 'D'], 5)).toBe('AEFGBCD')
})
})
+17
View File
@@ -0,0 +1,17 @@
/** A playlist's entry order with `moving` lifted out as one block, kept in
* their PLAYLIST order, and put back so the block's first track lands at the
* 1-based `position` of the result. A position past the end puts the block
* last. A track listed twice in the playlist moves with both entries, since a
* selection is by track id. */
export function moveToPosition(order: string[], moving: ReadonlySet<string>, position: number): string[] {
const block = order.filter((id) => moving.has(id))
const rest = order.filter((id) => !moving.has(id))
const at = Math.min(Math.max(Math.floor(position), 1) - 1, rest.length)
return [...rest.slice(0, at), ...block, ...rest.slice(at)]
}
/** The highest position the block's first track can take: the block's own
* length is what sits behind it. */
export function maxPosition(order: string[], moving: ReadonlySet<string>): number {
return order.length - order.filter((id) => moving.has(id)).length + 1
}
+22
View File
@@ -0,0 +1,22 @@
import type { PlaylistNode } from '../api'
/** Every selectable playlist at or under a node, in tree order. A folder
* contributes its nested playlists, a playlist itself — which is what adding a
* node to an export means: the export stores playlist ids, and a folder is a
* shape in the tree, not a thing with tracks. */
export function playlistIdsUnder(node: PlaylistNode): string[] {
const here = node.kind === 'folder' ? [] : [node.id]
return [...here, ...(node.children ?? []).flatMap(playlistIdsUnder)]
}
/** The ids of a node and everything nested in it — where a dragged folder
* cannot go. */
export function nodeIdsUnder(node: PlaylistNode): Set<string> {
const ids = new Set<string>()
const walk = (n: PlaylistNode) => {
ids.add(n.id)
n.children.forEach(walk)
}
walk(node)
return ids
}
+3
View File
@@ -8,6 +8,7 @@ import App from './App.tsx'
import { UpdateCheck } from './components/UpdateDialog.tsx' import { UpdateCheck } from './components/UpdateDialog.tsx'
import { AmbientBackdrop } from './components/AmbientBackdrop.tsx' import { AmbientBackdrop } from './components/AmbientBackdrop.tsx'
import { ConfirmHost } from './lib/confirm.tsx' import { ConfirmHost } from './lib/confirm.tsx'
import { DragLayer } from './lib/drag.tsx'
import { QuitGuard } from './components/QuitGuard.tsx' import { QuitGuard } from './components/QuitGuard.tsx'
import { preventHistoryNavigation } from './lib/noNavigation.ts' import { preventHistoryNavigation } from './lib/noNavigation.ts'
@@ -34,6 +35,8 @@ createRoot(document.getElementById('root')!).render(
<ConfirmHost /> <ConfirmHost />
{/* Save · Discard · Cancel when quitting with unsaved changes. */} {/* Save · Discard · Cancel when quitting with unsaved changes. */}
<QuitGuard /> <QuitGuard />
{/* The ghost under the cursor while dragging tracks or playlists. */}
<DragLayer />
</QueryClientProvider> </QueryClientProvider>
</StrictMode>, </StrictMode>,
) )