Added batch auto hot cue and reworked remove context menu

This commit is contained in:
patben8 committed 2026-09-25 11:54:09 +02:00
1 parent 76bf142fb4
commit d18db9566c
21 files changed
+1044 -150

No files matched your search

+37 -10
View File
@@ -358,11 +358,18 @@ Two independent apps that talk over HTTP:
`AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per `AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per
slot, a per-slot Replace tick for occupied slots — never remembered, since slot, a per-slot Replace tick for occupied slots — never remembered, since
overwriting is a decision about THIS track — and the template itself overwriting is a decision about THIS track — and the template itself
persisted as `autoCueTemplate` in userprefs), persisted as `autoCueTemplate` in userprefs. Also has a **batch mode** for
the context menu: same template, but it starts a job via `onRun`, and each
tick reads "Replace" and applies to every track in the batch. A Replace
RENAMES the slot's cue — `set_hotcue` keeps the old name only when called
without one, which is what a hand move does),
`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) + `EditTagsDialog` playlists + exports and acts on the whole selection; "Remove ▸" holds
From this playlist / From this export / Grids / Hotcues / From collection,
each behind a `ConfirmDialog` — as is the playlist Delete key. Enter
confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog`
(right-click → multi-field metadata + album-art edit), `StatusBar`, (right-click → multi-field metadata + album-art edit), `StatusBar`,
`RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`, `RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`,
`UpdateDialog` (`UpdateCheck`, mounted in `main.tsx` beside `App` so it shows `UpdateDialog` (`UpdateCheck`, mounted in `main.tsx` beside `App` so it shows
@@ -447,7 +454,10 @@ serialization path.** It enforces:
**flexible (multi-marker) grids** add/move/delete reversibly, `delete_grid` **flexible (multi-marker) grids** add/move/delete reversibly, `delete_grid`
leaves no companion debris (I); **companion cues are ordinary editable leaves no companion debris (I); **companion cues are ordinary editable
hotcues** — move/retype/delete work and never touch the grid marker (J); and hotcues** — move/retype/delete work and never touch the grid marker (J); and
real flexible grids in the collection project correctly (K). real flexible grids in the collection project correctly (K); and
**removing a track from the collection** drops its `<ENTRY>` and its
PRIMARYKEYs from exactly the playlists that held it — the only ADDED lines are
the `ENTRIES=` recounts, every other playlist byte-identical (L).
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.
@@ -492,13 +502,30 @@ serialization path.** It enforces:
(across a tempo change), and the ROUTE end to end on a temp copy of the real (across a tempo change), and the ROUTE end to end on a temp copy of the real
collection — the previous implementation's route returned 500 on every call collection — the previous implementation's route returned 500 on every call
for a week while its helper's tests passed. for a week while its helper's tests passed.
- `test_grid_batch.py` — **batch grid analysis** (context menu → Analyze Grid & - `test_grid_batch.py` — **batch analysis** from the context menu, both
BPM → `POST /api/tracks/grid/auto-batch`, a `jobs.py` job shown in the status `jobs.py` jobs shown in the status bar: Analyze Grid & BPM
bar). Pins the batch-only decisions: locked grids are skipped always, existing (`POST /api/tracks/grid/auto-batch`) and Auto Hotcues…
grids unless `replace_existing`, a failing track is reported not fatal, one (`POST /api/tracks/cue/auto-batch`, one template for every track). Pins the
run at a time, a cancel KEEPS finished tracks (unsaved edits like any other) batch-only decisions: locked grids are skipped always, existing grids unless
and still returns its result, and opening another library cancels the run. `replace_existing`; a hotcue batch analyses a grid FIRST where there is none
Shares `_analyse_grid` with the deck's single-track Analyze. and never touches an existing one, and a ticked Replace applies to every
track; a failing track is reported not fatal; **one batch at a time ACROSS
both kinds** (a grid run would move the beats a hotcue run is placing cues
on); a cancel KEEPS finished tracks (unsaved edits like any other) and still
returns its result; opening another library cancels the run. Each shares its
helper (`_analyse_grid`, `_place_auto_cues`) with the deck's single-track
button.
- `test_bulk_remove.py` — the context menu's **Remove ▸** routes
(`/api/tracks/grid/clear`, `/api/tracks/cue/clear`, `/api/tracks/remove`):
locked grids are kept, clearing hotcues empties the whole bank (loops and the
grid's beat-1 cue too) but never the grid, a removed track leaves the
projection AND its playlists while its audio file is untouched, removal is
gated on `tracks.removable`, and all three are refused while a batch
analysis runs. `remove_tracks` is the protocol's only DESTROYING verb for
tracks; Traktor implements it, Rekordbox and OneLibrary refuse (a Rekordbox
track spans rows in several tables plus ANLZ files, and which Rekordbox
expects deleted together is unmeasured). The journal records it as
`track/remove`, NOT an edit — otherwise history would read "edited 40 tracks".
- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it - `test_picker.py` — the picker's routes. Pins the scoping, because the bug it
replaced was invisible: `/api/library/options` flattened every driver's replaced was invisible: `/api/library/options` flattened every driver's
detections and returned `[0]`, so a plugged-in USB stick could be offered as detections and returned `[0]`, so a plugged-in USB stick could be offered as
@@ -239,6 +239,9 @@ class OneLibraryAdapter:
def add_tracks(self, items: list) -> list[str]: def add_tracks(self, items: list) -> list[str]:
self._refuse("Adding tracks") self._refuse("Adding tracks")
def remove_tracks(self, track_ids: list[str]) -> int:
self._refuse("Removing tracks")
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._refuse("Editing track metadata") self._refuse("Editing track metadata")
@@ -400,6 +400,12 @@ class RekordboxAdapter:
# import target for now. # import target for now.
self._refuse("Adding tracks") self._refuse("Adding tracks")
def remove_tracks(self, track_ids: list[str]) -> int:
# Same shape as adding: a track is a djmdContent row plus its cues,
# playlist rows, contentCue/contentFile mirrors and ANLZ files, and
# which of those Rekordbox expects to be deleted together is unmeasured.
self._refuse("Removing tracks")
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art") self._refuse("Editing cover art")
@@ -150,6 +150,16 @@ class TraktorAdapter:
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
return self._store.cover_art(track_id) return self._store.cover_art(track_id)
# ---- removing tracks ---------------------------------------------------
def remove_tracks(self, track_ids: list[str]) -> int:
with _translate():
n = self._store.remove_entries(track_ids)
if n:
# Rebuilt rather than patched: an entry sharing a removed key went
# too, and the index would otherwise still hold its projection.
self._rebuild()
return n
# ---- adding tracks ---------------------------------------------------- # ---- adding tracks ----------------------------------------------------
def add_tracks(self, items: list) -> list[str]: def add_tracks(self, items: list) -> list[str]:
"""Add tracks that came from somewhere else, with their prep. """Add tracks that came from somewhere else, with their prep.
@@ -59,6 +59,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
rating_max=5, rating_max=5,
editable_fields=sorted(editable_fields), editable_fields=sorted(editable_fields),
media_kinds=["audio", "stem"], media_kinds=["audio", "stem"],
removable=True,
artwork=True, artwork=True,
artwork_note=( artwork_note=(
"Traktor caches its own cover thumbnail, so a replaced image may " "Traktor caches its own cover thumbnail, so a replaced image may "
+56 -1
View File
@@ -418,6 +418,56 @@ class TraktorStore:
self.dirty = True self.dirty = True
return key return key
def remove_entries(self, track_ids: list[str]) -> int:
"""Remove tracks from the collection AND from every playlist; return
how many ENTRYs went.
The mirror of `add_entry`, with the same care about bytes: only the
removed ENTRYs, the `<COLLECTION ENTRIES>` count and the playlists that
actually referenced a removed track change — any other playlist is left
alone rather than rebuilt, so it still renders what it was parsed from.
Playlists must be purged too: a PRIMARYKEY naming a track that is no
longer in COLLECTION is a dangling reference, not an empty slot. The
audio file is never touched — this is the library's record of the track,
like Traktor's own "Delete from Collection".
Matches by primary key in DOCUMENT order, so two ENTRYs sharing a key
(which `iter_entries` warns can happen) both go, where the key→entry
dict would have found only one.
"""
gone = set(track_ids)
with self._lock:
before = self._nml.collection.entry
kept = [e for e in before if self._key_of(e) not in gone]
removed = len(before) - len(kept)
if removed == 0:
return 0
self._nml.collection.entry = kept
self._nml.collection.entries = len(kept)
for key in gone:
if self._entry_by_key.pop(key, None) is not None:
self._track_art.pop(key, None)
self._note("track", "remove", key)
for n in self._iter_nodes(self._root()):
pl = n.playlist
if pl is None or not pl.entry:
continue
entries = [
e for e in pl.entry
if not (e.primarykey is not None and e.primarykey.key in gone)
]
if len(entries) != len(pl.entry):
pl.entry = entries
pl.entries = len(entries)
self.dirty = True
return removed
@staticmethod
def _key_of(entry) -> str | None:
loc = entry.location
return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else None
def iter_entries(self): def iter_entries(self):
"""Every collection ENTRY in document order. """Every collection ENTRY in document order.
@@ -480,7 +530,10 @@ class TraktorStore:
"""Create (or reposition + retype) the hotcue in `slot` at `start_sec`. """Create (or reposition + retype) the hotcue in `slot` at `start_sec`.
`length_sec` > 0 makes it a loop (used with cue_type 5). `name` sets the `length_sec` > 0 makes it a loop (used with cue_type 5). `name` sets the
cue label on create; when unset it falls back to Traktor's "n.n.".""" label: on create it falls back to Traktor's "n.n."; on a replace, None
keeps the old label (a hand move is still the same cue) while a name
renames it (Auto Hotcues' Replace puts a DIFFERENT cue in the slot, and
keeping "Drop 1" on a cue now at "Drop 1 -16" would mislabel it)."""
if not 0 <= slot <= 7: if not 0 <= slot <= 7:
raise PlaylistError(f"Invalid hotcue slot: {slot}") raise PlaylistError(f"Invalid hotcue slot: {slot}")
if cue_type not in self.CREATABLE_TYPES: if cue_type not in self.CREATABLE_TYPES:
@@ -496,6 +549,8 @@ class TraktorStore:
existing.start = start_ms existing.start = start_ms
existing.type = cue_type existing.type = cue_type
existing.len = len_ms existing.len = len_ms
if name is not None:
existing.name = name
else: else:
if entry.cue_v2 is None: if entry.cue_v2 is None:
entry.cue_v2 = [] entry.cue_v2 = []
+6
View File
@@ -135,6 +135,12 @@ class LibraryAdapter(Protocol):
# what `test_save_fidelity.py` checks rather than taking on trust. # what `test_save_fidelity.py` checks rather than taking on trust.
def add_tracks(self, items: list["NewTrack"]) -> list[str]: ... def add_tracks(self, items: list["NewTrack"]) -> list[str]: ...
# Remove tracks from the library — and so from every playlist, since an
# entry naming a track the library no longer has is a dangling reference.
# Never touches audio files. Returns how many were removed; gated on
# `capabilities().tracks.removable`.
def remove_tracks(self, track_ids: list[str]) -> int: ...
# ---- commands: track metadata / art --------------------------------- # ---- commands: track metadata / art ---------------------------------
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ... def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ...
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ... def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
+3
View File
@@ -58,6 +58,9 @@ class TrackCapabilities(BaseModel):
rating_max: int = 5 rating_max: int = 5
editable_fields: list[str] = [] editable_fields: list[str] = []
media_kinds: list[MediaKind] = ["audio"] media_kinds: list[MediaKind] = ["audio"]
# Tracks can be removed from the library (and so from its playlists). The
# audio file is never touched either way.
removable: bool = False
artwork: bool = False artwork: bool = False
artwork_note: str | None = None artwork_note: str | None = None
+14 -2
View File
@@ -68,12 +68,21 @@ class EditJournal:
changed, they simply did not exist before. Counting them here would both changed, they simply did not exist before. Counting them here would both
mislabel the version-history message and drag them through the file-tag mislabel the version-history message and drag them through the file-tag
sync, which has nothing to write for a track whose fields were never sync, which has nothing to write for a track whose fields were never
touched. touched. Excludes tracks REMOVED from the library for the same reason:
"edited 40 tracks" would describe a deletion as an edit.
""" """
removed = self.removed_tracks()
return { return {
c.target c.target
for c in self.changes for c in self.changes
if c.scope == "track" and c.target and c.op != "add" if c.scope == "track" and c.target and c.op not in ("add", "remove")
and c.target not in removed
}
def removed_tracks(self) -> set[str]:
"""Tracks taken out of the library this session."""
return {
c.target for c in self.changes if c.scope == "track" and c.op == "remove" and c.target
} }
def added_tracks(self) -> set[str]: def added_tracks(self) -> set[str]:
@@ -115,6 +124,9 @@ class EditJournal:
n_added = len(self.added_tracks()) n_added = len(self.added_tracks())
if n_added: if n_added:
parts.append(f"added {tracks(n_added)}") parts.append(f"added {tracks(n_added)}")
n_removed = len(self.removed_tracks())
if n_removed:
parts.append(f"removed {tracks(n_removed)} from the collection")
# --- track metadata + cover art (already counted per-track) --- # --- track metadata + cover art (already counted per-track) ---
n_meta = len(self.edited_tracks() | (extra_tracks or set())) n_meta = len(self.edited_tracks() | (extra_tracks or set()))
+164 -23
View File
@@ -36,6 +36,8 @@ from .schemas import (
AutoGridRequest, AutoGridRequest,
AutoCueOutcome, AutoCueOutcome,
AutoHotcue, AutoHotcue,
AutoHotcuesBatchRequest,
TrackIds,
AutoHotcuesRequest, AutoHotcuesRequest,
AutoHotcuesResult, AutoHotcuesResult,
CollectionCandidate, CollectionCandidate,
@@ -149,8 +151,9 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
if not path.exists(): if not path.exists():
raise HTTPException(400, f"Not found: {path}") raise HTTPException(400, f"Not found: {path}")
# A running analysis writes into the library being replaced; stop it. # A running analysis writes into the library being replaced; stop it.
for job in JOBS.active(GRID_JOB): for kind in BATCH_JOBS:
JOBS.cancel(job.id) for job in JOBS.active(kind):
JOBS.cancel(job.id)
try: try:
STATE.open(path) STATE.open(path)
except AdapterError as ex: except AdapterError as ex:
@@ -838,22 +841,35 @@ def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult:
raise HTTPException(404, "Track not found") raise HTTPException(404, "Track not found")
if not cues.grid_markers: if not cues.grid_markers:
raise HTTPException(400, "Set a beatgrid before using Auto Hotcues") raise HTTPException(400, "Set a beatgrid before using Auto Hotcues")
slots = a.capabilities().cues.hotcue_slots _check_cue_slots(a, body.slots)
try:
return _place_auto_cues(a, body.track_id, cues, body.slots)
except _AnalysisError as ex:
raise HTTPException(400, str(ex))
def _check_cue_slots(a, slots: list) -> None:
"""Refuse a template the bank cannot hold — once, before any track is touched."""
n = a.capabilities().cues.hotcue_slots
seen: set[int] = set() seen: set[int] = set()
for r in body.slots: for r in slots:
if not 0 <= r.slot < slots: if not 0 <= r.slot < n:
raise HTTPException(400, f"Slot {r.slot} is outside this library's {slots} hotcues") raise HTTPException(400, f"Slot {r.slot} is outside this library's {n} hotcues")
if r.slot in seen: if r.slot in seen:
raise HTTPException(400, f"Slot {r.slot} is requested twice") raise HTTPException(400, f"Slot {r.slot} is requested twice")
seen.add(r.slot) seen.add(r.slot)
path = a.audio_path(body.track_id)
if path is None or not path.exists():
raise HTTPException(400, "Audio file not found (is the drive mounted?)")
def _place_auto_cues(a, track_id: str, cues: TrackCues, slots: list) -> AutoHotcuesResult:
"""Analyse one gridded track's structure and place the template — shared by
the deck's Auto button and the batch job, so the two cannot drift."""
path = a.audio_path(track_id)
if path is None or not path.exists():
raise _AnalysisError("Audio file not found (is the drive mounted?)")
try: try:
found = structure.analyse(str(path), [(m.start, m.bpm) for m in cues.grid_markers]) found = structure.analyse(str(path), [(m.start, m.bpm) for m in cues.grid_markers])
except Exception as ex: # analysis is best-effort; never 500 the UI except Exception as ex: # analysis is best-effort; never 500 the UI
raise HTTPException(400, f"Analysis failed: {ex}") raise _AnalysisError(f"Analysis failed: {ex}") from ex
existing = { existing = {
c.slot: ah.ExistingCue(c.editable, c.start) c.slot: ah.ExistingCue(c.editable, c.start)
@@ -862,7 +878,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult:
} }
outcomes = ah.plan( outcomes = ah.plan(
found, found,
[ah.SlotRequest(r.slot, r.event, r.offset_beats, r.overwrite) for r in body.slots], [ah.SlotRequest(r.slot, r.event, r.offset_beats, r.overwrite) for r in slots],
existing, existing,
) )
placed = [o for o in outcomes if o.status == ah.PLACED] placed = [o for o in outcomes if o.status == ah.PLACED]
@@ -870,7 +886,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult:
# overwrite=True is safe: `plan` only passes an occupied slot when the # overwrite=True is safe: `plan` only passes an occupied slot when the
# user ticked it, and the adapter still refuses a protected one. # user ticked it, and the adapter still refuses a protected one.
cues = a.place_cues( cues = a.place_cues(
body.track_id, track_id,
[AutoHotcue(slot=o.slot, start=o.start, name=o.name) for o in placed], [AutoHotcue(slot=o.slot, start=o.start, name=o.name) for o in placed],
overwrite=True, overwrite=True,
) )
@@ -892,31 +908,42 @@ def auto_grid(body: AutoGridRequest) -> TrackCues:
raise HTTPException(404, "Track not found") raise HTTPException(404, "Track not found")
try: try:
return _analyse_grid(a, body.track_id) return _analyse_grid(a, body.track_id)
except _GridAnalysisError as ex: except _AnalysisError as ex:
raise HTTPException(400, str(ex)) raise HTTPException(400, str(ex))
class _GridAnalysisError(Exception): class _AnalysisError(Exception):
"""A track that could not be analysed; the message is user-facing.""" """A track that could not be analysed; the message is user-facing."""
# Batch analysis jobs. ONE at a time across both kinds: a grid run replacing a
# track's grid while a hotcue run places cues on the old one would put cues on
# beats that no longer exist.
GRID_JOB = "grid-analysis"
CUE_JOB = "auto-hotcues"
BATCH_JOBS = (GRID_JOB, CUE_JOB)
def _require_no_batch() -> None:
if any(JOBS.active(k) for k in BATCH_JOBS):
raise HTTPException(409, "A batch analysis is already running")
def _analyse_grid(a, track_id: str) -> TrackCues: def _analyse_grid(a, track_id: str) -> TrackCues:
"""Detect and write one track's grid — shared by the deck's Analyze and the """Detect and write one track's grid — shared by the deck's Analyze and the
batch job, so the two cannot come to mean different things.""" batch job, so the two cannot come to mean different things."""
path = a.audio_path(track_id) path = a.audio_path(track_id)
if path is None or not path.exists(): if path is None or not path.exists():
raise _GridAnalysisError("Audio file not found (is the drive mounted?)") raise _AnalysisError("Audio file not found (is the drive mounted?)")
try: try:
found = grid_detect.detect_grid(str(path)) found = grid_detect.detect_grid(str(path))
except Exception as ex: # analysis is best-effort; never 500 the UI except Exception as ex: # analysis is best-effort; never 500 the UI
raise _GridAnalysisError(f"Analysis failed: {ex}") from ex raise _AnalysisError(f"Analysis failed: {ex}") from ex
# "Analysed", not "replace": each platform writes an analysis result in its # "Analysed", not "replace": each platform writes an analysis result in its
# own shape (Traktor pairs the first marker with a beat-1 cue). # own shape (Traktor pairs the first marker with a beat-1 cue).
return a.set_analysed_grid(track_id, [(found.anchor, found.bpm)]) return a.set_analysed_grid(track_id, [(found.anchor, found.bpm)])
GRID_JOB = "grid-analysis"
@app.post("/api/tracks/grid/auto-batch", response_model=JobStatus) @app.post("/api/tracks/grid/auto-batch", response_model=JobStatus)
def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
@@ -930,10 +957,7 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
a = require_adapter() a = require_adapter()
if not a.capabilities().grid.editable: if not a.capabilities().grid.editable:
raise HTTPException(422, "This library's beatgrids cannot be edited") raise HTTPException(422, "This library's beatgrids cannot be edited")
# One at a time: two runs over overlapping selections would analyse the _require_no_batch()
# same track twice and race on its grid.
if JOBS.active(GRID_JOB):
raise HTTPException(409, "Grid analysis is already running")
ids = list(dict.fromkeys(body.track_ids)) ids = list(dict.fromkeys(body.track_ids))
def run(handle) -> dict: def run(handle) -> dict:
@@ -955,7 +979,7 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
try: try:
_analyse_grid(a, track_id) _analyse_grid(a, track_id)
result["analysed"].append(track_id) result["analysed"].append(track_id)
except (_GridAnalysisError, AdapterError) as ex: except (_AnalysisError, AdapterError) as ex:
result["failed"].append({"title": title, "reason": str(ex)}) result["failed"].append({"title": title, "reason": str(ex)})
handle.progress(done=i + 1) handle.progress(done=i + 1)
return result return result
@@ -964,6 +988,57 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus:
return JobStatus(**job.as_dict()) return JobStatus(**job.as_dict())
@app.post("/api/tracks/cue/auto-batch", response_model=JobStatus)
def auto_hotcues_batch(body: AutoHotcuesBatchRequest) -> JobStatus:
"""Place one Auto Hotcues template on many tracks, as a JOB.
A track with no beatgrid gets one analysed first (as "Analyze Grid & BPM"
would), since the events are found on the grid; a track that has one keeps
it untouched. Same contract as the grid batch: written as each track
finishes, a cancel keeps what is done, a failing track is reported and
skipped."""
a = require_adapter()
caps = a.capabilities()
if not caps.writable or caps.cues.hotcue_slots == 0:
raise HTTPException(422, "This library's hotcues cannot be edited")
_check_cue_slots(a, body.slots)
if not body.slots:
raise HTTPException(400, "The template places no cues")
_require_no_batch()
ids = list(dict.fromkeys(body.track_ids))
def run(handle) -> dict:
result = {"tracks": [], "cues_placed": 0, "grids_created": 0, "failed": []}
handle.progress(done=0, total=len(ids))
for i, track_id in enumerate(ids):
if handle.cancelled:
break # keep what is done; return it rather than raise
track = a.track(track_id)
title = (track.title or track_id) if track else track_id
handle.progress(message=title)
try:
cues = a.track_cues(track_id) if track else None
if cues is None:
raise _AnalysisError("Track not found")
if not cues.grid_markers:
if track.grid_locked:
raise _AnalysisError("No beatgrid, and the grid is locked")
if not caps.grid.editable:
raise _AnalysisError("No beatgrid")
cues = _analyse_grid(a, track_id)
result["grids_created"] += 1
placed = _place_auto_cues(a, track_id, cues, body.slots)
result["tracks"].append(track_id)
result["cues_placed"] += sum(o.status == ah.PLACED for o in placed.outcomes)
except (_AnalysisError, AdapterError) as ex:
result["failed"].append({"title": title, "reason": str(ex)})
handle.progress(done=i + 1)
return result
job = JOBS.submit(CUE_JOB, run)
return JobStatus(**job.as_dict())
@app.patch("/api/tracks/cue", response_model=TrackCues) @app.patch("/api/tracks/cue", response_model=TrackCues)
def edit_cue_type(body: SetCueType) -> TrackCues: def edit_cue_type(body: SetCueType) -> TrackCues:
"""Change the type of an existing cue (keeps its position).""" """Change the type of an existing cue (keeps its position)."""
@@ -1020,6 +1095,72 @@ def remove_grid(track_id: str) -> TrackCues:
return require_adapter().delete_grid(track_id) return require_adapter().delete_grid(track_id)
# ---- bulk Remove (the context menu's Remove ▸ submenu) --------------------
#
# Quick in-memory edits, so requests rather than jobs — but refused while a
# batch analysis runs: it would write cues/grids onto a track removed under it.
@app.post("/api/tracks/grid/clear")
def clear_grids(body: TrackIds) -> dict:
"""Delete the beatgrid of every given track. Locked grids are skipped —
a lock is the user saying "leave this grid alone" — and reported."""
a = require_adapter()
if not a.capabilities().grid.editable:
raise HTTPException(422, "This library's beatgrids cannot be edited")
_require_no_batch()
out = {"cleared": 0, "locked": 0, "empty": 0}
for tid in dict.fromkeys(body.track_ids):
track = a.track(tid)
if track is None:
continue
if track.grid_locked:
out["locked"] += 1
elif not (a.track_cues(tid) or TrackCues()).grid_markers:
out["empty"] += 1 # counted from the cues: the projection's count can be approximate
else:
a.delete_grid(tid)
out["cleared"] += 1
return out
@app.post("/api/tracks/cue/clear")
def clear_hotcues(body: TrackIds) -> dict:
"""Empty the whole hotcue bank of every given track — point cues, loops
and the grid's paired beat-1 cue alike (the grid itself is untouched).
Cues the adapter will not edit — Rekordbox memory cues — are kept."""
a = require_adapter()
caps = a.capabilities()
if not caps.writable or caps.cues.hotcue_slots == 0:
raise HTTPException(422, "This library's hotcues cannot be edited")
_require_no_batch()
out = {"tracks": 0, "cues": 0}
for tid in dict.fromkeys(body.track_ids):
cues = a.track_cues(tid)
slots = sorted({
c.slot for c in (cues.cues if cues else [])
if c.role == "hotcue" and c.slot is not None and c.editable
})
for slot in slots:
a.delete_cue(tid, slot)
if slots:
out["tracks"] += 1
out["cues"] += len(slots)
return out
@app.post("/api/tracks/remove")
def remove_tracks(body: TrackIds) -> dict:
"""Remove tracks from the library and every playlist. Audio files are
never touched. An export set referencing one will report it as missing,
which is what export sets do with any track that has gone."""
a = require_adapter()
if not a.capabilities().tracks.removable:
raise HTTPException(422, "Tracks cannot be removed from this library")
_require_no_batch()
return {"removed": a.remove_tracks(list(dict.fromkeys(body.track_ids)))}
@app.patch("/api/tracks/grid/lock", response_model=TrackCues) @app.patch("/api/tracks/grid/lock", response_model=TrackCues)
def edit_grid_lock(body: SetGridLock) -> TrackCues: def edit_grid_lock(body: SetGridLock) -> TrackCues:
"""Toggle Traktor's LOCK flag on a track.""" """Toggle Traktor's LOCK flag on a track."""
+14
View File
@@ -105,6 +105,20 @@ class AutoHotcuesRequest(BaseModel):
slots: list[AutoCueSlot] slots: list[AutoCueSlot]
class TrackIds(BaseModel):
"""A body naming a set of tracks — the bulk Remove commands."""
track_ids: list[str]
class AutoHotcuesBatchRequest(BaseModel):
"""The same template applied to every track. `overwrite` on a slot means
"replace this slot's cue on every track that has one"."""
track_ids: list[str]
slots: list[AutoCueSlot]
class AutoCueOutcome(BaseModel): class AutoCueOutcome(BaseModel):
slot: int slot: int
event: AutoCueEvent event: AutoCueEvent
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate source .venv/bin/activate
fail=0 fail=0
for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
echo "▶ $t" echo "▶ $t"
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
+126
View File
@@ -0,0 +1,126 @@
"""The context menu's Remove ▸ commands, through their routes, on a temp copy.
Removing from the COLLECTION is new — the protocol's only destroying verb for
tracks — and its bytes are pinned by invariant L in `test_save_fidelity.py`.
This pins what the routes decide: which tracks each command skips (locked
grids, memory cues), that "clear hotcues" empties the whole bank but leaves the
grid, that a removed track leaves the projection AND every playlist while its
audio file is untouched, that the capability gates the route, and that a
running batch analysis blocks all three.
"""
from __future__ import annotations
import os
import shutil
import tempfile
import time
from pathlib import Path
from types import SimpleNamespace
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False
def check(label, cond, detail=""):
global failed
print(f" {'✓' if cond else '✗'} {label}" + ("" if cond else f" [{detail}]"))
if not cond:
failed = True
print("== bulk remove ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
os.environ["KONDUKTOR_NML"] = str(work)
from fastapi.testclient import TestClient
import konduktor.main as main
with TestClient(main.app, raise_server_exceptions=False) as c:
a = main.require_adapter()
gridded = [t.id for t in a.tracks if t.grid_marker_count > 0 and not t.grid_locked][:3]
locked = gridded[2]
a.set_grid_lock(locked, True)
bare = next(t.id for t in a.tracks if t.grid_marker_count == 0)
# ---- grids ----------------------------------------------------------
r = c.post("/api/tracks/grid/clear", json={"track_ids": [*gridded, bare]})
check("grid clear answers 200", r.status_code == 200, r.text[:200])
check("…counts cleared / locked / empty",
r.json() == {"cleared": 2, "locked": 1, "empty": 1}, r.text)
check("the grids are gone", all(not a.track_cues(t).grid_markers for t in gridded[:2]))
check("a locked grid is kept", bool(a.track_cues(locked).grid_markers))
# ---- hotcues --------------------------------------------------------
with_cues = [t.id for t in a.tracks
if (cu := a.track_cues(t.id)) and len(cu.grid_markers) > 0
and any(q.slot is not None and q.grid_marker is not None for q in cu.cues)
and sum(q.slot is not None for q in cu.cues) >= 2][:2]
before = {t: a.track_cues(t) for t in with_cues}
n_cues = sum(sum(q.slot is not None for q in cu.cues) for cu in before.values())
r = c.post("/api/tracks/cue/clear", json={"track_ids": with_cues})
check("hotcue clear answers 200", r.status_code == 200, r.text[:200])
check("…counts tracks and cues", r.json() == {"tracks": 2, "cues": n_cues}, f"{r.text} vs {n_cues}")
check("the whole bank is empty, incl. the grid's beat-1 cue",
all(not any(q.slot is not None for q in a.track_cues(t).cues) for t in with_cues))
# Positions and tempos, not the whole marker: its `companion` slot is
# SUPPOSED to become None, since the paired cue was just deleted.
def grid(cu):
return [(m.start, m.bpm) for m in cu.grid_markers]
check("…and the grid itself is untouched (only its pairing ends)",
all(grid(a.track_cues(t)) == grid(before[t]) for t in with_cues)
and all(m.companion is None for t in with_cues for m in a.track_cues(t).grid_markers))
# ---- from collection ------------------------------------------------
caps = c.get("/api/capabilities").json()
check("Traktor advertises removable tracks", caps["tracks"]["removable"] is True)
tree = c.get("/api/playlists").json()
def lists(nodes):
for n in nodes:
yield n
yield from lists(n["children"])
pl = next(n for n in lists(tree) if n.get("count") and n.get("can_add_tracks"))
in_pl = c.get(f"/api/playlists/{pl['id']}/tracks").json()
in_pl = in_pl["tracks"] if isinstance(in_pl, dict) else in_pl
victim = in_pl[0]["id"]
audio = a.audio_path(victim)
existed = audio is not None and audio.exists()
n_before = len(a.tracks)
r = c.post("/api/tracks/remove", json={"track_ids": [victim, victim, "nope"]})
check("remove answers 200", r.status_code == 200, r.text[:200])
check("…and removes exactly one (duplicates / unknowns ignored)", r.json() == {"removed": 1}, r.text)
check("the track leaves the projection", a.track(victim) is None and len(a.tracks) == n_before - 1)
after = c.get(f"/api/playlists/{pl['id']}/tracks").json()
after = after["tracks"] if isinstance(after, dict) else after
check("…and the playlist", all(t["id"] != victim for t in after) and len(after) == len(in_pl) - 1)
check("the audio file is untouched", not existed or audio.exists())
check("the edit is unsaved (Save lights up)", c.get("/api/state").json().get("dirty") is True)
# ---- gating ----------------------------------------------------------
orig_caps = a.capabilities
a.capabilities = lambda: orig_caps().model_copy(update={
"tracks": orig_caps().tracks.model_copy(update={"removable": False})})
r = c.post("/api/tracks/remove", json={"track_ids": [gridded[0]]})
check("remove is refused without the capability", r.status_code == 422, r.text[:200])
a.capabilities = orig_caps
main.grid_detect.detect_grid = lambda p, *a_, **k: (time.sleep(0.05), SimpleNamespace(anchor=0.1, bpm=128.0))[1]
a.audio_path = lambda tid: Path(__file__)
jid = c.post("/api/tracks/grid/auto-batch",
json={"track_ids": [t.id for t in a.tracks][:40], "replace_existing": True}).json()["id"]
for route in ("/api/tracks/grid/clear", "/api/tracks/cue/clear", "/api/tracks/remove"):
r = c.post(route, json={"track_ids": [gridded[0]]})
check(f"{route} is refused while a batch runs", r.status_code == 409, r.text[:200])
c.post(f"/api/jobs/{jid}/cancel")
check("nothing was written to disk (edits stay in memory until Save)",
work.read_bytes() == REAL.read_bytes())
print()
print("FAILED" if failed else "RESULT: ALL PASSED")
raise SystemExit(1 if failed else 0)
+91 -2
View File
@@ -1,9 +1,12 @@
"""Batch grid analysis — the route and its job, on a temp copy of the collection. """Batch analysis — grid and Auto Hotcues jobs, on a temp copy of the collection.
Detection itself is `test_grid_detect.py`'s job; this pins the WIRING, and the Detection itself is `test_grid_detect.py`'s job; this pins the WIRING, and the
decisions only the batch makes: locked grids are skipped always, existing grids decisions only the batch makes: locked grids are skipped always, existing grids
only when asked, a failing track is reported and skipped rather than fatal, a only when asked, a failing track is reported and skipped rather than fatal, a
cancel keeps what is done, and nothing reaches disk before Save. cancel keeps what is done, and nothing reaches disk before Save. Batch Auto
Hotcues adds: one template on every track, a grid analysed first where there is
none (and an existing one left alone), Replace applying to every track, and one
batch job at a time ACROSS both kinds.
""" """
from __future__ import annotations from __future__ import annotations
@@ -14,6 +17,8 @@ import time
from pathlib import Path from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
import numpy as np
REAL = Path(__file__).resolve().parents[1] / "collection.nml" REAL = Path(__file__).resolve().parents[1] / "collection.nml"
failed = False failed = False
@@ -106,6 +111,90 @@ with tempfile.TemporaryDirectory() as d:
n = len(j["result"]["analysed"]) if j["result"] else -1 n = len(j["result"]["analysed"]) if j["result"] else -1
check("…and still returns what it finished", 0 < n < len(many), str(n)) check("…and still returns what it finished", 0 < n < len(many), str(n))
# ---- batch Auto Hotcues --------------------------------------------
print("== batch auto hotcues ==")
main.grid_detect.detect_grid = fake_detect
from konduktor.core import structure
def fake_analyse(path, markers):
bpm = markers[0][1]
st = structure.Structure(beats=np.arange(400) * 60.0 / bpm, bar0=0,
n_bars=100, duration=400 * 60.0 / bpm)
st.events = {"drop_1": 129, "outro": 353} # clear of any beat-0 grid cue
return st
main.structure.analyse = fake_analyse
def free(tid, n):
cu = a.track_cues(tid)
used = {q.slot for q in cu.cues if q.slot is not None}
return [k for k in range(8) if k not in used][:n]
gridded = next(t.id for t in a.tracks if t.grid_marker_count > 0 and not t.grid_locked
and len(free(t.id, 2)) == 2 and t.id not in many)
nogrid = next(t.id for t in a.tracks if t.grid_marker_count == 0
and t.id not in (missing, *bare, *many))
before_grid = a.track_cues(gridded).grid_markers
s0, s1 = free(gridded, 2)
tmpl = [{"slot": s0, "event": "drop_1"}, {"slot": s1, "event": "outro"}]
r = c.post("/api/tracks/cue/auto-batch",
json={"track_ids": [gridded, nogrid, missing], "slots": tmpl})
check("the batch route starts a job", r.status_code == 200, r.text[:200])
j = wait(c, r.json()["id"])
res = j["result"]
check("the job finishes", j["state"] == "done", str(j))
check("both tracks got cues", res["tracks"] == [gridded, nogrid], str(res))
check("a grid is created only where there was none", res["grids_created"] == 1, str(res))
check("an existing grid is left untouched",
a.track_cues(gridded).grid_markers == before_grid)
check("the track without a grid now has one", len(a.track_cues(nogrid).grid_markers) == 1)
names = {q.slot: q.name for q in a.track_cues(gridded).cues if q.slot is not None}
check("the template's cues are placed", names.get(s0) == "Drop 1" and names.get(s1) == "Outro", str(names))
check("placed cues are counted", res["cues_placed"] == 4, str(res))
check("a missing file is reported, not fatal",
len(res["failed"]) == 1 and "not found" in res["failed"][0]["reason"], str(res))
# Occupied slots: kept, unless ticked — and then replaced on every track.
# A fresh beat (16 before the drop), so the one-cue-per-beat rule cannot
# be what decides it.
tmpl2 = [{"slot": s0, "event": "drop_1", "offset_beats": -16}]
res = wait(c, c.post("/api/tracks/cue/auto-batch",
json={"track_ids": [gridded], "slots": tmpl2}).json()["id"])["result"]
check("an occupied slot is kept without Replace", res["cues_placed"] == 0, str(res))
tmpl2[0]["overwrite"] = True
res = wait(c, c.post("/api/tracks/cue/auto-batch",
json={"track_ids": [gridded], "slots": tmpl2}).json()["id"])["result"]
names = {q.slot: q.name for q in a.track_cues(gridded).cues if q.slot is not None}
check("…and replaced with it", names.get(s0) == "Drop 1 -16" and res["cues_placed"] == 1,
f"{names} {res}")
r = c.post("/api/tracks/cue/auto-batch",
json={"track_ids": [gridded], "slots": [{"slot": 99, "event": "outro"}]})
check("a template the bank cannot hold is refused up front", r.status_code == 400, r.text[:200])
r = c.post("/api/tracks/cue/auto-batch", json={"track_ids": [gridded], "slots": []})
check("an empty template is refused", r.status_code == 400, r.text[:200])
# One batch at a time ACROSS kinds.
main.grid_detect.detect_grid = lambda p, *a, **k: (time.sleep(0.05), fake_detect(p))[1]
jid = c.post("/api/tracks/grid/auto-batch",
json={"track_ids": many, "replace_existing": True}).json()["id"]
r = c.post("/api/tracks/cue/auto-batch", json={"track_ids": [gridded], "slots": tmpl})
check("hotcues are refused while a grid run is going", r.status_code == 409, r.text[:200])
c.post(f"/api/jobs/{jid}/cancel")
wait(c, jid)
# Opening another library cancels a running batch.
main.structure.analyse = lambda p, m: (time.sleep(0.05), fake_analyse(p, m))[1]
gridded_many = [t.id for t in a.tracks if t.grid_marker_count > 0][:40]
jid = c.post("/api/tracks/cue/auto-batch",
json={"track_ids": gridded_many, "slots": tmpl}).json()["id"]
time.sleep(0.1)
other = Path(d) / "other.nml"
shutil.copy2(REAL, other)
c.post("/api/library/open", json={"path": str(other)})
check("opening another library cancels the run", wait(c, jid)["state"] == "cancelled")
check("nothing was written to disk (edits stay in memory until Save)", check("nothing was written to disk (edits stay in memory until Save)",
work.read_bytes() == REAL.read_bytes()) work.read_bytes() == REAL.read_bytes())
+1
View File
@@ -307,6 +307,7 @@ print("== every command is refused ==")
COMMANDS = [ COMMANDS = [
("set_track_metadata", lambda: adapter.set_track_metadata(one.id, {"title": "x"})), ("set_track_metadata", lambda: adapter.set_track_metadata(one.id, {"title": "x"})),
("set_cover_art", lambda: adapter.set_cover_art(one.id, b"", "image/png")), ("set_cover_art", lambda: adapter.set_cover_art(one.id, b"", "image/png")),
("remove_tracks", lambda: adapter.remove_tracks([one.id])),
("create_playlist", lambda: adapter.create_playlist("x")), ("create_playlist", lambda: adapter.create_playlist("x")),
("rename_playlist", lambda: adapter.rename_playlist(node.id, "x")), ("rename_playlist", lambda: adapter.rename_playlist(node.id, "x")),
("delete_playlist", lambda: adapter.delete_playlist(node.id)), ("delete_playlist", lambda: adapter.delete_playlist(node.id)),
+3
View File
@@ -296,6 +296,9 @@ with tempfile.TemporaryDirectory() as d:
print("== what Rekordbox genuinely cannot do still refuses, with a reason ==") print("== what Rekordbox genuinely cannot do still refuses, with a reason ==")
commands = { commands = {
"set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"), "set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"),
# A track spans rows in several tables plus ANLZ files; which of them
# Rekordbox expects deleted together is unmeasured.
"remove_tracks": lambda: adapter.remove_tracks([sample.id]),
# Rekordbox genuinely has no per-track grid lock, unlike Traktor's LOCK. # Rekordbox genuinely has no per-track grid lock, unlike Traktor's LOCK.
"set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True), "set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True),
"remap_locations": lambda: adapter.remap_locations(None), "remap_locations": lambda: adapter.remap_locations(None),
+49
View File
@@ -687,5 +687,54 @@ else:
check("K: a marker without a companion projects None", ok_comp) check("K: a marker without a companion projects None", ok_comp)
# ---- Invariant L: removing a track from the collection is localized ---------
print("== L. remove_entries drops the ENTRY and its playlist references, nothing else ==")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
store = TraktorStore(work)
original = store._render()
def pl_nodes(st):
return [n for n in st._iter_nodes(st._root()) if n.playlist is not None]
in_pl = {k for n in pl_nodes(store) for k in store._entry_keys_of(n.playlist)}
target = next(e for e in store._nml.collection.entry
if e.location and store._key_of(e) in in_pl)
key = store._key_of(target)
touched = {n.playlist.uuid for n in pl_nodes(store) if key in store._entry_keys_of(n.playlist)}
untouched = [n.playlist.uuid for n in pl_nodes(store) if n.playlist.uuid not in touched]
n_before = len(store._nml.collection.entry)
removed = store.remove_entries([key, "no/such/track.mp3"])
after = store._render()
check("L: exactly one ENTRY removed (an unknown id is ignored)", removed == 1, str(removed))
import difflib
plus = [d for d in difflib.unified_diff(tag_lines(original), tag_lines(after), n=0)
if d.startswith("+") and not d.startswith("+++")]
# Every ADDED line is a recount — the collection's or a touched playlist's.
# Nothing is rewritten, only removed.
check("L: the only added lines are ENTRIES recounts",
all("ENTRIES=" in d for d in plus) and len(plus) == 1 + len(touched), "\n".join(plus[:6]))
check("L: every other playlist is byte-identical",
all(original[slice(*playlist_block_span(original, u))] == after[slice(*playlist_block_span(after, u))]
for u in untouched))
check("L: the edit journal records a removal, not an edit",
store._journal.removed_tracks() == {key} and not store._journal.edited_tracks())
summary = store._journal.summary()
check("L: …and the history message says so", "removed 1 track from the collection" in summary.lower(), summary)
store.save()
re = TraktorStore(work)
keys = [re._key_of(e) for e in re._nml.collection.entry]
check("L: the track is gone from the collection", key not in keys)
check("L: <COLLECTION ENTRIES> matches the entries", re._nml.collection.entries == len(keys) == n_before - 1)
check("L: …and from every playlist", all(key not in re._entry_keys_of(n.playlist) for n in pl_nodes(re)))
check("L: every playlist's ENTRIES count matches",
all((n.playlist.entries or 0) == len(n.playlist.entry or []) for n in pl_nodes(re)))
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)
+277 -74
View File
@@ -1,9 +1,9 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query' import { useQuery, useQueryClient } from '@tanstack/react-query'
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table' import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table'
import { CapabilitiesContext } from './lib/capabilities' import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { writeHint } from './lib/platformCopy' import { writeHint } from './lib/platformCopy'
import { api, type GridBatchResult, type PlaylistNode, type Track } from './api' import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type Track } from './api'
import { import {
COLUMN_MENU, COLUMN_MENU,
DEFAULT_COLUMN_ORDER, DEFAULT_COLUMN_ORDER,
@@ -18,6 +18,8 @@ import { CollectionPicker } from './components/CollectionPicker'
import { ContextMenu, type MenuItem } from './components/ContextMenu' import { ContextMenu, type MenuItem } from './components/ContextMenu'
import { EditTagsDialog } from './components/EditTagsDialog' import { EditTagsDialog } from './components/EditTagsDialog'
import { AnalyzeGridDialog } from './components/AnalyzeGridDialog' import { AnalyzeGridDialog } from './components/AnalyzeGridDialog'
import { AutoCueDialog } from './components/AutoCueDialog'
import { ConfirmDialog, type ConfirmRequest } from './components/ConfirmDialog'
import { PathMappingDialog } from './components/PathMappingDialog' import { PathMappingDialog } from './components/PathMappingDialog'
import { HistoryPanel } from './components/HistoryPanel' import { HistoryPanel } from './components/HistoryPanel'
import { PrepStrip } from './components/PrepStrip' import { PrepStrip } from './components/PrepStrip'
@@ -62,14 +64,19 @@ export default function App() {
const [prepTrack, setPrepTrack] = useState<Track | null>(null) const [prepTrack, setPrepTrack] = useState<Track | 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)
// Batch grid analysis: the confirm step (only when some tracks already have // Batch analysis (grid, or Auto Hotcues): a confirm step, then the running
// a grid), then the running job, polled into the status bar. // 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
// run is placing cues on.
const [gridConfirm, setGridConfirm] = useState< const [gridConfirm, setGridConfirm] = useState<
{ ids: string[]; existing: number; locked: number } | null { ids: string[]; existing: number; locked: number } | null
>(null) >(null)
const [gridJobId, setGridJobId] = useState<string | null>(null) const [cueBatch, setCueBatch] = useState<{ ids: string[]; withoutGrid: number } | null>(null)
const [gridCancelling, setGridCancelling] = useState(false) const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' } | null>(null)
const [batchCancelling, setBatchCancelling] = useState(false)
const [cuesRefresh, setCuesRefresh] = useState(0) // bump → deck re-reads its cues const [cuesRefresh, setCuesRefresh] = useState(0) // bump → deck re-reads its cues
// Every Remove ▸ action (and the playlist Delete key) confirms first.
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
const playTrack = useCallback((t: Track) => { const playTrack = useCallback((t: Track) => {
setPrepTrack(t) setPrepTrack(t)
@@ -424,28 +431,29 @@ export default function App() {
return m return m
}, [source.kind, tracks]) }, [source.kind, tracks])
const gridJob = useQuery({ const batchJobStatus = useQuery({
queryKey: ['job', gridJobId], queryKey: ['job', batchJob?.id ?? null],
queryFn: () => api.job(gridJobId!), queryFn: () => api.job(batchJob!.id),
enabled: !!gridJobId, enabled: !!batchJob,
refetchInterval: (q) => (q.state.data && q.state.data.state !== 'running' ? false : 400), refetchInterval: (q) => (q.state.data && q.state.data.state !== 'running' ? false : 400),
}) })
const gridDone = gridJob.data?.done ?? 0 const batchDone = batchJobStatus.data?.done ?? 0
useEffect(() => { useEffect(() => {
// Each finished track is an unsaved edit; let the Save button know as they land. // Each finished track is an unsaved edit; let the Save button know as they land.
if (gridDone > 0) qc.invalidateQueries({ queryKey: ['state'] }) if (batchDone > 0) qc.invalidateQueries({ queryKey: ['state'] })
}, [gridDone, qc]) }, [batchDone, qc])
useEffect(() => { useEffect(() => {
const job = gridJob.data const job = batchJobStatus.data
if (!job || job.state === 'running') return if (!job || job.state === 'running' || !batchJob || job.id !== batchJob.id) return
setGridJobId(null) const kind = batchJob.kind
setGridCancelling(false) setBatchJob(null)
setBatchCancelling(false)
if (job.state === 'failed') { if (job.state === 'failed') {
onError(`Grid analysis failed: ${job.error ?? 'unknown error'}`) const what = kind === 'grid' ? 'Grid analysis' : 'Auto Hotcues'
onError(`${what} failed: ${job.error ?? 'unknown error'}`)
return return
} }
const r = job.result as unknown as GridBatchResult | null if (!job.result) return
if (!r) return
qc.invalidateQueries({ queryKey: ['state'] }) qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['tracks'] }) qc.invalidateQueries({ queryKey: ['tracks'] })
qc.invalidateQueries({ queryKey: ['playlist'] }) qc.invalidateQueries({ queryKey: ['playlist'] })
@@ -453,26 +461,44 @@ export default function App() {
qc.invalidateQueries({ queryKey: ['export-playlist-tracks'] }) qc.invalidateQueries({ queryKey: ['export-playlist-tracks'] })
qc.invalidateQueries({ queryKey: ['export-loose'] }) qc.invalidateQueries({ queryKey: ['export-loose'] })
qc.invalidateQueries({ queryKey: ['facets'] }) qc.invalidateQueries({ queryKey: ['facets'] })
if (prepTrack && r.analysed.includes(prepTrack.id)) setCuesRefresh((n) => n + 1) const cancelled = job.state === 'cancelled'
const n = r.analysed.length const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}`
const parts = [ let touched: string[]
`${job.state === 'cancelled' ? 'Cancelled — analyzed' : 'Analyzed'} ${n} track${n === 1 ? '' : 's'}`, let parts: string[]
r.existing ? `skipped ${r.existing} with a grid` : '', let failures: CueBatchResult['failed']
r.locked ? `${r.locked} locked` : '', if (kind === 'grid') {
r.failed.length const r = job.result as unknown as GridBatchResult
? `${r.failed.length} failed (${r.failed[0].title}: ${r.failed[0].reason}${r.failed.length > 1 ? ', …' : ''})` touched = r.analysed
: '', failures = r.failed
].filter(Boolean) parts = [
notify(r.failed.length && n === 0 ? 'error' : 'success', parts.join(' · ')) `${cancelled ? 'Cancelled — analyzed' : 'Analyzed'} ${plural(r.analysed.length, 'track')}`,
r.existing ? `skipped ${r.existing} with a grid` : '',
r.locked ? `${r.locked} locked` : '',
]
} else {
const r = job.result as unknown as CueBatchResult
touched = r.tracks
failures = r.failed
parts = [
`${cancelled ? 'Cancelled — placed' : 'Placed'} ${plural(r.cues_placed, 'cue')} on ${plural(r.tracks.length, 'track')}`,
r.grids_created ? `analyzed ${plural(r.grids_created, 'new grid')}` : '',
]
}
if (failures.length) {
const f = failures[0]
parts.push(`${failures.length} failed (${f.title}: ${f.reason}${failures.length > 1 ? ', …' : ''})`)
}
if (prepTrack && touched.includes(prepTrack.id)) setCuesRefresh((n) => n + 1)
notify(failures.length && touched.length === 0 ? 'error' : 'success', parts.filter(Boolean).join(' · '))
// Only the job's finish matters here; prepTrack is read, not tracked. // Only the job's finish matters here; prepTrack is read, not tracked.
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [gridJob.data]) }, [batchJobStatus.data])
const handleOpened = () => { const handleOpened = () => {
setForcePicker(false) setForcePicker(false)
setSource({ kind: 'all' }) setSource({ kind: 'all' })
setSelected(new Set()) setSelected(new Set())
setGridJobId(null) // the backend cancels it; its result is for the old library setBatchJob(null) // the backend cancels it; its result is for the old library
setFilters(emptyFilters) setFilters(emptyFilters)
setSorting([]) setSorting([])
qc.invalidateQueries() // refetch everything for the newly-opened collection qc.invalidateQueries() // refetch everything for the newly-opened collection
@@ -516,8 +542,8 @@ export default function App() {
setGridConfirm(null) setGridConfirm(null)
try { try {
const job = await api.autoGridBatch(ids, replaceExisting) const job = await api.autoGridBatch(ids, replaceExisting)
setGridCancelling(false) setBatchCancelling(false)
setGridJobId(job.id) setBatchJob({ id: job.id, kind: 'grid' })
} catch (e) { } catch (e) {
onError((e as Error).message) onError((e as Error).message)
} }
@@ -539,6 +565,184 @@ export default function App() {
} }
const canAnalyzeGrid = canEdit && !viewingDevice && !!capabilities.data?.grid.editable const canAnalyzeGrid = canEdit && !viewingDevice && !!capabilities.data?.grid.editable
const startCueBatch = (ids: string[]) => {
const byId = new Map(tracks.map((t) => [t.id, t]))
const withoutGrid = ids.filter((id) => (byId.get(id)?.grid_marker_count ?? 0) === 0).length
setCueBatch({ ids, withoutGrid })
}
// Rejects on failure, so the dialog stays open and shows it can be retried.
const runCueBatch = async (ids: string[], slots: AutoCueSlot[]) => {
const job = await api.autoCuesBatch(ids, slots)
setBatchCancelling(false)
setBatchJob({ id: job.id, kind: 'cues' })
}
const canAutoCue = canEdit && !viewingDevice && (capabilities.data?.cues.hotcue_slots ?? 0) > 0
// ---- Remove ▸ -----------------------------------------------------------
const nTracks = (n: number) => `${n} track${n === 1 ? '' : 's'}`
const trackNoun = (ids: string[]) => {
if (ids.length > 1) return nTracks(ids.length)
const t = tracks.find((x) => x.id === ids[0])
return t?.title ? `“${t.title}”` : 'this track'
}
// Refetch whatever a track list or the deck could be showing. Throws on
// failure (after reporting), so the confirm dialog stays open for a retry.
const afterBulk = (ids: string[], cuesChanged: boolean) => {
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['tracks'] })
qc.invalidateQueries({ queryKey: ['playlist'] })
qc.invalidateQueries({ queryKey: ['playlists'] })
qc.invalidateQueries({ queryKey: ['export-tracks'] })
qc.invalidateQueries({ queryKey: ['export-playlist-tracks'] })
qc.invalidateQueries({ queryKey: ['export-loose'] })
qc.invalidateQueries({ queryKey: ['export-contents'] })
qc.invalidateQueries({ queryKey: ['facets'] })
if (cuesChanged && prepTrack && ids.includes(prepTrack.id)) setCuesRefresh((n) => n + 1)
}
const guard = async (fn: () => Promise<void>) => {
try {
await fn()
} catch (e) {
onError((e as Error).message)
throw e
}
}
const confirmRemoveFromPlaylist = (ids: string[]) =>
setConfirmReq({
title: 'Remove from playlist',
body: (
<p>
Remove {trackNoun(ids)} from <span className="text-text">{playlistNode?.name ?? 'this playlist'}</span>?
The {ids.length === 1 ? 'track stays' : 'tracks stay'} in the collection.
</p>
),
confirmLabel: `Remove ${nTracks(ids.length)}`,
onConfirm: () => {
removeFromPlaylist(ids)
setSelected(new Set())
},
})
const confirmRemoveFromExport = (exportId: string, ids: string[]) => {
const name = exportSets.data?.find((x) => x.id === exportId)?.name ?? 'this export'
setConfirmReq({
title: 'Remove from export',
body: (
<p>
Remove {trackNoun(ids)} from <span className="text-text">{name}</span>? Your library is not
changed.
</p>
),
confirmLabel: `Remove ${nTracks(ids.length)}`,
onConfirm: () =>
guard(async () => {
await removeFromExport(exportId, ids)
setSelected(new Set())
}),
})
}
const confirmClearGrids = (ids: string[]) => {
const locked = tracks.filter((t) => ids.includes(t.id) && t.grid_locked).length
setConfirmReq({
title: 'Remove beatgrids',
body: (
<>
<p>
Delete the beatgrid of {trackNoun(ids)}? Tempo and markers go; the paired beat-1 cue goes
with them. Hotcues are kept.
</p>
{locked > 0 && (
<p className="text-faint">{locked} locked {locked === 1 ? 'grid is' : 'grids are'} kept.</p>
)}
</>
),
confirmLabel: 'Remove grids',
onConfirm: () =>
guard(async () => {
const r = await api.clearGrids(ids)
afterBulk(ids, true)
notify(
'success',
[`Removed ${r.cleared} grid${r.cleared === 1 ? '' : 's'}`, r.locked ? `${r.locked} locked, kept` : '']
.filter(Boolean)
.join(' · '),
)
}),
})
}
const confirmClearHotcues = (ids: string[]) =>
setConfirmReq({
title: 'Remove hotcues',
body: (
<p>
Clear every hotcue on {trackNoun(ids)} — cues, loops and the grid’s beat-1 cue? The beatgrid
itself is kept.
</p>
),
confirmLabel: 'Remove hotcues',
onConfirm: () =>
guard(async () => {
const r = await api.clearHotcues(ids)
afterBulk(ids, true)
notify('success', `Removed ${r.cues} hotcue${r.cues === 1 ? '' : 's'} from ${nTracks(r.tracks)}`)
}),
})
const confirmRemoveTracks = (ids: string[]) =>
setConfirmReq({
title: 'Remove from collection',
body: (
<>
<p>
Remove {trackNoun(ids)} from the collection and from every playlist?
</p>
<p className="text-faint">
The audio {ids.length === 1 ? 'file stays' : 'files stay'} on disk. Nothing is written until you
save, and a save can be rolled back from version history.
</p>
</>
),
confirmLabel: `Remove ${nTracks(ids.length)}`,
onConfirm: () =>
guard(async () => {
const r = await api.removeTracks(ids)
setSelected(new Set())
if (prepTrack && ids.includes(prepTrack.id)) setPrepTrack(null)
afterBulk(ids, false)
notify('success', `Removed ${nTracks(r.removed)} from the collection`)
}),
})
const canClearGrids = canEdit && !viewingDevice && !!capabilities.data?.grid.editable
const canClearCues = canAutoCue
const canRemoveTracks = canEdit && !viewingDevice && !!capabilities.data?.tracks.removable
const exportRootId =
source.kind === 'export' ? source.id : source.kind === 'export-other' ? source.exportId : null
const removeItems = (ids: string[]): MenuItem[] => [
...(playlistEditable
? [{ label: 'From this playlist…', onClick: () => confirmRemoveFromPlaylist(ids) }]
: []),
// Only on the export's ROOT view. Inside a referenced playlist there is
// nothing to remove: the reference is live, and per-track removal would
// need an exclusion list — hidden state deciding what a future export
// contains. Remove the whole playlist, or add tracks instead.
...(exportRootId ? [{ label: 'From this export…', onClick: () => confirmRemoveFromExport(exportRootId, ids) }] : []),
// Removing touches cues and grids a running batch is writing; the backend
// refuses, so the items say why instead of failing on click.
...(canClearGrids
? [{ label: 'Grids…', hint: batchJob ? 'busy' : undefined, disabled: !!batchJob, onClick: () => confirmClearGrids(ids) }]
: []),
...(canClearCues
? [{ label: 'Hotcues…', hint: batchJob ? 'busy' : undefined, disabled: !!batchJob, onClick: () => confirmClearHotcues(ids) }]
: []),
...(canRemoveTracks
? [{ label: 'From collection…', danger: true, hint: batchJob ? 'busy' : undefined, disabled: !!batchJob, onClick: () => confirmRemoveTracks(ids) }]
: []),
]
// The "Add to" submenu. Exports are listed even on a read-only library: // The "Add to" submenu. Exports are listed even on a read-only library:
// adding to one touches no library data — an export is Konduktor's own // adding to one touches no library data — an export is Konduktor's own
// curation. The playlist being viewed is left out; adding a track to the // curation. The playlist being viewed is left out; adding a track to the
@@ -586,43 +790,31 @@ export default function App() {
? [ ? [
{ {
label: 'Analyze Grid & BPM', label: 'Analyze Grid & BPM',
hint: gridJobId ? 'running' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
disabled: !!gridJobId, disabled: !!batchJob,
onClick: () => startGridAnalysis(menu.ids), onClick: () => startGridAnalysis(menu.ids),
}, },
] ]
: []), : []),
// The deck's ✨ Auto covers a single loaded track, with its
// existing cues shown; this is the same template over the selection.
...(canAutoCue
? [
{
label: 'Auto Hotcues…',
hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined,
disabled: !!batchJob,
onClick: () => startCueBatch(menu.ids),
},
]
: []),
// A device's track ids belong to the stick, not the collection, so // A device's track ids belong to the stick, not the collection, so
// there is nothing they could be added to. // there is nothing they could be added to.
...(viewingDevice ? [] : [{ label: 'Add to', submenu: addToItems(menu.ids) }]), ...(viewingDevice ? [] : [{ label: 'Add to', submenu: addToItems(menu.ids) }]),
...(playlistEditable ...(() => {
? [ const items = removeItems(menu.ids)
{ return items.length ? [{ label: 'Remove', submenu: items }] : []
label: menu.ids.length > 1 ? `Remove ${menu.ids.length} from playlist` : 'Remove from playlist', })(),
danger: true,
onClick: () => {
removeFromPlaylist(menu.ids)
setSelected(new Set())
},
},
]
: []),
// Only on the export's ROOT view. Inside a referenced playlist there
// is nothing to remove: the reference is live, and per-track removal
// would need an exclusion list — hidden state deciding what a future
// export contains. Remove the whole playlist, or add tracks instead.
...(source.kind === 'export' || source.kind === 'export-other'
? [
{
label: 'Remove from this export',
onClick: () =>
removeFromExport(
source.kind === 'export' ? source.id : source.exportId,
menu.ids,
),
},
]
: []),
]} ]}
onClose={() => setMenu(null)} onClose={() => setMenu(null)}
/> />
@@ -655,6 +847,17 @@ export default function App() {
onError={onError} onError={onError}
/> />
)} )}
{confirmReq && <ConfirmDialog {...confirmReq} onClose={() => setConfirmReq(null)} />}
{cueBatch && (
<AutoCueDialog
batch={{ count: cueBatch.ids.length, withoutGrid: cueBatch.withoutGrid }}
slotCount={capabilities.data!.cues.hotcue_slots}
slotLabel={slotLabeller(capabilities.data!)}
onRun={(slots) => runCueBatch(cueBatch.ids, slots)}
onClose={() => setCueBatch(null)}
onError={onError}
/>
)}
{gridConfirm && ( {gridConfirm && (
<AnalyzeGridDialog <AnalyzeGridDialog
total={gridConfirm.ids.length} total={gridConfirm.ids.length}
@@ -903,7 +1106,7 @@ export default function App() {
? { enabled: !filtersActive && sorting.length === 0, onReorder: reorderPlaylist } ? { enabled: !filtersActive && sorting.length === 0, onReorder: reorderPlaylist }
: undefined : undefined
} }
onRemove={playlistEditable ? removeFromPlaylist : undefined} onRemove={playlistEditable ? confirmRemoveFromPlaylist : 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}
@@ -925,16 +1128,16 @@ export default function App() {
sourceName={viewName} sourceName={viewName}
selected={viewingDevice ? 0 : selected.size} selected={viewingDevice ? 0 : selected.size}
job={ job={
gridJobId batchJob
? { ? {
label: 'Analyzing', label: batchJob.kind === 'grid' ? 'Analyzing grids' : 'Placing hotcues',
done: gridJob.data?.done ?? 0, done: batchJobStatus.data?.done ?? 0,
total: gridJob.data?.total ?? 0, total: batchJobStatus.data?.total ?? 0,
detail: gridJob.data?.message, detail: batchJobStatus.data?.message,
cancelling: gridCancelling, cancelling: batchCancelling,
onCancel: () => { onCancel: () => {
setGridCancelling(true) setBatchCancelling(true)
api.cancelJob(gridJobId).catch((e) => onError((e as Error).message)) api.cancelJob(batchJob.id).catch((e) => onError((e as Error).message))
}, },
} }
: null : null
+27
View File
@@ -232,6 +232,8 @@ export interface Capabilities {
rating_max: number rating_max: number
editable_fields: TrackField[] editable_fields: TrackField[]
media_kinds: MediaKind[] media_kinds: MediaKind[]
/** Tracks can be removed from the library (audio files are never touched). */
removable: boolean
artwork: boolean artwork: boolean
artwork_note: string | null artwork_note: string | null
} }
@@ -353,6 +355,15 @@ export interface GridBatchResult {
failed: { title: string; reason: string }[] failed: { title: string; reason: string }[]
} }
/** What a batch Auto Hotcues run did. `tracks` got the template (whatever it
* placed on each); `failed` could not be analysed. */
export interface CueBatchResult {
tracks: string[]
cues_placed: number
grids_created: number
failed: { title: string; reason: string }[]
}
export interface SourceCandidate { export interface SourceCandidate {
path: string path: string
/** What a person recognises, e.g. "OneLibrary — Hardy". */ /** What a person recognises, e.g. "OneLibrary — Hardy". */
@@ -676,6 +687,22 @@ export const api = {
/** Many tracks at once, as a job — poll `job()`. Locked grids are always /** Many tracks at once, as a job — poll `job()`. Locked grids are always
* skipped; existing ones unless `replaceExisting`. The finished job's * skipped; existing ones unless `replaceExisting`. The finished job's
* `result` is a `GridBatchResult`. */ * `result` is a `GridBatchResult`. */
/** Auto Hotcues over many tracks, one template for all, as a job. A track
* without a grid gets one analysed first. The finished job's `result` is a
* `CueBatchResult`. */
autoCuesBatch: (trackIds: string[], slots: AutoCueSlot[]) =>
send<JobStatus>('POST', '/api/tracks/cue/auto-batch', { track_ids: trackIds, slots }),
/** Delete these tracks' beatgrids; locked grids are skipped and counted. */
clearGrids: (trackIds: string[]) =>
send<{ cleared: number; locked: number; empty: number }>('POST', '/api/tracks/grid/clear', {
track_ids: trackIds,
}),
/** Empty these tracks' whole hotcue bank (the grid is untouched). */
clearHotcues: (trackIds: string[]) =>
send<{ tracks: number; cues: number }>('POST', '/api/tracks/cue/clear', { track_ids: trackIds }),
/** Remove tracks from the library and every playlist. Audio files stay. */
removeTracks: (trackIds: string[]) =>
send<{ removed: number }>('POST', '/api/tracks/remove', { track_ids: trackIds }),
autoGridBatch: (trackIds: string[], replaceExisting: boolean) => autoGridBatch: (trackIds: string[], replaceExisting: boolean) =>
send<JobStatus>('POST', '/api/tracks/grid/auto-batch', { send<JobStatus>('POST', '/api/tracks/grid/auto-batch', {
track_ids: trackIds, track_ids: trackIds,
+76 -37
View File
@@ -3,6 +3,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'
import { import {
api, api,
type AutoCueEvent, type AutoCueEvent,
type AutoCueSlot,
type AutoHotcuesResult, type AutoHotcuesResult,
type CuePoint, type CuePoint,
type Track, type Track,
@@ -17,6 +18,11 @@ import { formatDuration } from '../lib/format'
* every track the same way — but the per-slot "replace" ticks are NOT: whether * every track the same way — but the per-slot "replace" ticks are NOT: whether
* to overwrite a hand-placed cue is a decision about THIS track, and a * to overwrite a hand-placed cue is a decision about THIS track, and a
* remembered tick would silently clobber the next track's cues. * remembered tick would silently clobber the next track's cues.
*
* Batch mode (`batch` instead of `track`) edits the same remembered template but
* does not run it: it hands the slots to `onRun`, which starts a job. There is
* no single track to show existing cues for, so each slot's tick reads "Replace
* existing" and applies to every track in the batch — still never remembered.
*/ */
export const AUTO_CUE_EVENTS: { id: AutoCueEvent; label: string }[] = [ export const AUTO_CUE_EVENTS: { id: AutoCueEvent; label: string }[] = [
@@ -64,18 +70,33 @@ function loadTemplate(prefs: Record<string, unknown> | undefined, slots: number)
}) })
} }
interface Props { type Props = {
track: Track
slotCount: number slotCount: number
slotLabel: (slot: number) => string slotLabel: (slot: number) => string
/** The track's current hotcues by slot, to mark occupied rows. */
existing: Map<number, CuePoint>
onClose: () => void onClose: () => void
onDone: (result: AutoHotcuesResult) => void
onError: (msg: string) => void onError: (msg: string) => void
} } & (
| {
track: Track
/** The track's current hotcues by slot, to mark occupied rows. */
existing: Map<number, CuePoint>
onDone: (result: AutoHotcuesResult) => void
batch?: undefined
onRun?: undefined
}
| {
track?: undefined
existing?: undefined
onDone?: undefined
/** How many tracks the template will be applied to. */
batch: { count: number; withoutGrid: number }
/** Start the batch; resolve once it has started. */
onRun: (slots: AutoCueSlot[]) => Promise<void>
}
)
export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose, onDone, onError }: Props) { export function AutoCueDialog(props: Props) {
const { slotCount, slotLabel, onClose, onError } = props
const qc = useQueryClient() const qc = useQueryClient()
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
const [rows, setRows] = useState<Row[] | null>(null) const [rows, setRows] = useState<Row[] | null>(null)
@@ -114,14 +135,15 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose,
.patchPrefs({ [PREF_KEY]: template }) .patchPrefs({ [PREF_KEY]: template })
.then((p) => qc.setQueryData(['prefs'], p)) .then((p) => qc.setQueryData(['prefs'], p))
.catch(() => {}) .catch(() => {})
const slots: AutoCueSlot[] = rows.flatMap((r, slot) =>
r.event ? [{ slot, event: r.event, offset_beats: r.offset, overwrite: replace.has(slot) }] : [],
)
try { try {
const result = await api.autoCues( if (props.batch) {
track.id, await props.onRun(slots)
rows.flatMap((r, slot) => } else {
r.event ? [{ slot, event: r.event, offset_beats: r.offset, overwrite: replace.has(slot) }] : [], props.onDone(await api.autoCues(props.track.id, slots))
), }
)
onDone(result)
onClose() onClose()
} catch (e) { } catch (e) {
onError((e as Error).message) onError((e as Error).message)
@@ -138,7 +160,9 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose,
<div className="border-b border-line px-5 py-4"> <div className="border-b border-line px-5 py-4">
<div className="text-[15px] font-semibold tracking-tight">Auto Hotcues</div> <div className="text-[15px] font-semibold tracking-tight">Auto Hotcues</div>
<div className="truncate text-xs text-muted"> <div className="truncate text-xs text-muted">
{track.artist} — {track.title} {props.batch
? `${props.batch.count} tracks — the same slots on every one`
: `${props.track.artist} — ${props.track.title}`}
</div> </div>
</div> </div>
@@ -147,13 +171,31 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose,
<span>Slot</span> <span>Slot</span>
<span>Event</span> <span>Event</span>
<span className="text-center">Offset (beats)</span> <span className="text-center">Offset (beats)</span>
<span>Existing cue</span> <span>{props.batch ? 'Occupied slot' : 'Existing cue'}</span>
</div> </div>
{rows === null ? ( {rows === null ? (
<div className="py-6 text-center text-sm text-muted">Loading…</div> <div className="py-6 text-center text-sm text-muted">Loading…</div>
) : ( ) : (
rows.map((r, slot) => { rows.map((r, slot) => {
const cue = existing.get(slot) const cue = props.existing?.get(slot)
const tick = (label: string, title?: string) => (
<label className="flex min-w-0 items-center gap-1.5 text-xs text-muted" title={title}>
<input
type="checkbox"
checked={replace.has(slot)}
disabled={!r.event}
onChange={(e) =>
setReplace((s) => {
const n = new Set(s)
if (e.target.checked) n.add(slot)
else n.delete(slot)
return n
})
}
/>
<span className="truncate">{label}</span>
</label>
)
return ( return (
<div key={slot} className="grid grid-cols-[2rem_1fr_9rem_7.5rem] items-center gap-2 py-1"> <div key={slot} className="grid grid-cols-[2rem_1fr_9rem_7.5rem] items-center gap-2 py-1">
<span className="flex h-7 w-7 items-center justify-center rounded bg-ink-800 text-xs font-bold text-text"> <span className="flex h-7 w-7 items-center justify-center rounded bg-ink-800 text-xs font-bold text-text">
@@ -197,26 +239,11 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose,
+ +
</button> </button>
</div> </div>
{cue ? ( {props.batch ? (
tick('Replace', 'Replace the cue in this slot on every track that has one')
) : cue ? (
cue.editable ? ( cue.editable ? (
<label className="flex min-w-0 items-center gap-1.5 text-xs text-muted" title={cue.name ?? ''}> tick(`Replace ${cue.name || formatDuration(cue.start)}`, cue.name ?? '')
<input
type="checkbox"
checked={replace.has(slot)}
disabled={!r.event}
onChange={(e) =>
setReplace((s) => {
const n = new Set(s)
if (e.target.checked) n.add(slot)
else n.delete(slot)
return n
})
}
/>
<span className="truncate">
Replace {cue.name || formatDuration(cue.start)}
</span>
</label>
) : ( ) : (
<span className="truncate text-xs text-faint" title="This cue belongs to the beatgrid and is never replaced"> <span className="truncate text-xs text-faint" title="This cue belongs to the beatgrid and is never replaced">
Grid cue (kept) Grid cue (kept)
@@ -229,6 +256,12 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose,
) )
}) })
)} )}
{props.batch && props.batch.withoutGrid > 0 && (
<p className="mt-3 text-[11px] leading-relaxed text-gold">
{props.batch.withoutGrid} of these {props.batch.withoutGrid === 1 ? 'has' : 'have'} no
beatgrid — {props.batch.withoutGrid === 1 ? 'it' : 'they'}’ll get one analyzed first.
</p>
)}
<p className="mt-3 text-[11px] leading-relaxed text-faint"> <p className="mt-3 text-[11px] leading-relaxed text-faint">
Events are found on the beatgrid, counting bar 1 from its first marker — if drops land a Events are found on the beatgrid, counting bar 1 from its first marker — if drops land a
bar or two off, move the grid marker onto the first downbeat. Occupied slots are kept bar or two off, move the grid marker onto the first downbeat. Occupied slots are kept
@@ -250,7 +283,13 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose,
disabled={busy || rows === null || active === 0} disabled={busy || rows === null || active === 0}
className="rounded-md bg-accent px-4 py-1.5 text-sm font-semibold text-ink-950 hover:brightness-110 disabled:opacity-40" className="rounded-md bg-accent px-4 py-1.5 text-sm font-semibold text-ink-950 hover:brightness-110 disabled:opacity-40"
> >
{busy ? 'Analyzing…' : `Analyze & place ${active} cue${active === 1 ? '' : 's'}`} {busy
? props.batch
? 'Starting…'
: 'Analyzing…'
: props.batch
? `Place ${active} cue${active === 1 ? '' : 's'} on ${props.batch.count} tracks`
: `Analyze & place ${active} cue${active === 1 ? '' : 's'}`}
</button> </button>
</div> </div>
</div> </div>
+79
View File
@@ -0,0 +1,79 @@
import { useEffect, useState, type ReactNode } from 'react'
export interface ConfirmRequest {
title: string
/** What will happen, in a sentence or two. */
body: ReactNode
/** The confirm button's label, e.g. "Remove 3 tracks". */
confirmLabel: string
onConfirm: () => Promise<void> | void
}
interface Props extends ConfirmRequest {
onClose: () => void
}
/** A yes/no confirmation for destructive actions. Enter confirms and Esc
* cancels, so a confirmed Delete key stays a two-keystroke action. */
export function ConfirmDialog({ title, body, confirmLabel, onConfirm, onClose }: Props) {
const [busy, setBusy] = useState(false)
const confirm = async () => {
if (busy) return
setBusy(true)
try {
await onConfirm()
onClose()
} catch {
setBusy(false) // the caller has already reported it; allow a retry
}
}
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape' && !busy) onClose()
// A focused button handles its own Enter — otherwise tabbing to Cancel
// and pressing Enter would run the destructive action.
if (e.key === 'Enter' && !(e.target instanceof HTMLButtonElement)) {
e.preventDefault()
void confirm()
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
})
return (
<div
aria-modal="true"
className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-6"
onClick={() => !busy && onClose()}
>
<div
className="w-full max-w-sm overflow-hidden rounded-xl border border-line bg-ink-900 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
{title}
</div>
<div className="space-y-2 px-5 py-4 text-sm text-muted">{body}</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
<button
onClick={onClose}
disabled={busy}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text disabled:opacity-40"
>
Cancel
</button>
<button
onClick={() => void confirm()}
disabled={busy}
className="rounded-md bg-pink px-4 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110 disabled:opacity-50"
>
{confirmLabel}
</button>
</div>
</div>
</div>
)
}