mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Compare commits
5
Commits
v0.1.0
...
autohotcue
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7169c8bbe | ||
|
|
986a2cee54 | ||
|
|
5ff79eb118 | ||
|
|
73b793aee6 | ||
|
|
a0dfed9a9e |
No files matched your search
@@ -51,8 +51,17 @@ Two independent apps that talk over HTTP:
|
||||
- `components/` — `CollectionPicker` (startup chooser: Automatic / Open last /
|
||||
Find manually — the last reveals a file browser), `Sidebar` (playlist tree +
|
||||
create/rename/delete), `SaveBar`, `Toolbar` (search/filters + `ColumnsMenu`),
|
||||
`TrackTable` (TanStack Table + Virtual grid; per-row play button, configurable
|
||||
columns, inline double-click editing), `PlaylistEditor` (dnd-kit reorder),
|
||||
`TrackTable` (All Tracks — TanStack Table + **virtualized** grid; per-row play
|
||||
button, configurable columns, inline double-click editing) and `PlaylistTable`
|
||||
(playlists — same columns/cells/play/inline-edit via shared `HeaderRow`/
|
||||
`RowCells`/`PlayButton`, so the two views look identical, PLUS dnd-kit
|
||||
drag-to-reorder + a remove button, header sorting disabled so the manual order
|
||||
stands; `canReorder` is false while a filter/search is active so a partial order
|
||||
can't overwrite the full entry list). `PlaylistTable` is non-virtualized
|
||||
(playlists are small) and feeds `useReactTable` a **stable** empty `sorting`
|
||||
array (`NO_SORTING`): a controlled `state.sorting` that's a fresh `[]` each
|
||||
render with no `onSortingChange` makes TanStack Table re-sync its internal
|
||||
state every commit → infinite re-render loop. Keep that reference stable.
|
||||
`SelectionBar` (bulk add-to-playlist), `ContextMenu` + `EditTagsDialog`
|
||||
(right-click → multi-field metadata + album-art edit), `StatusBar`,
|
||||
`RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`.
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Auto Hotcues — structural boundary detection for DJ cue placement.
|
||||
|
||||
Detection uses the McFee & Ellis (2014) Laplacian structural segmentation as
|
||||
implemented on top of librosa: beat-synchronous CQT features → a
|
||||
sequence-augmented recurrence Laplacian → spectral clustering of beats into
|
||||
section *types* → boundaries at type changes. This is repetition/homogeneity
|
||||
aware (unlike a raw energy-novelty curve), so boundaries land on real musical
|
||||
transitions. Validated on real house tracks: clean, phrase-scale boundaries in
|
||||
~1.5s each; pure-Python (~150MB), no torch/native build; runs on Python 3.14.
|
||||
|
||||
The module is split so the DSP (`detect_boundaries`, needs the audio) is
|
||||
separate from the placement logic (`select_hotcues`, pure arithmetic on the
|
||||
beatgrid) — the latter is unit-testable without audio.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
# Traktor's hotcue bank. Parameterised (not hardcoded at call sites) so it can
|
||||
# grow if a future Traktor allows more than 8 triggerable hotcues.
|
||||
MAX_HOTCUES = 8
|
||||
|
||||
_SR = 22050
|
||||
_N_EIGENVECTORS = 6 # section-type clusters for the Laplacian embedding
|
||||
|
||||
|
||||
def detect_boundaries(audio_path: str, sr: int = _SR) -> tuple[list[tuple[float, float]], float]:
|
||||
"""Detect structural boundaries in a track.
|
||||
|
||||
Returns ``(boundaries, duration)`` where ``boundaries`` is a list of
|
||||
``(time_sec, energy)`` pairs — one per detected section start — and
|
||||
``energy`` is that section's mean RMS normalised to 0..1 across the track
|
||||
(used downstream for positional naming). Sorted by time.
|
||||
"""
|
||||
import librosa
|
||||
from scipy.ndimage import median_filter
|
||||
from scipy.sparse.csgraph import laplacian as csgraph_laplacian
|
||||
from scipy.linalg import eigh
|
||||
import sklearn.cluster
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
duration = len(y) / sr
|
||||
if duration < 1.0:
|
||||
return [], duration
|
||||
|
||||
# Beat-synchronous CQT — the harmonic/timbre backbone of the method.
|
||||
cqt = librosa.amplitude_to_db(np.abs(librosa.cqt(y=y, sr=sr)), ref=np.max)
|
||||
_, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
if len(beats) < 4:
|
||||
return [], duration
|
||||
csync = librosa.util.sync(cqt, beats, aggregate=np.median)
|
||||
beat_times = librosa.frames_to_time(beats, sr=sr)
|
||||
|
||||
# Sequence-augmented recurrence Laplacian (McFee & Ellis 2014):
|
||||
# a repetition graph (which beats sound alike) blended with a local path
|
||||
# graph (consecutive-beat timbral continuity).
|
||||
rec = librosa.segment.recurrence_matrix(csync, width=3, mode="affinity", sym=True)
|
||||
rec = median_filter(rec, size=(1, 7))
|
||||
mfcc = librosa.feature.mfcc(y=y, sr=sr)
|
||||
msync = librosa.util.sync(mfcc, beats)
|
||||
path_dist = np.sum(np.diff(msync, axis=1) ** 2, axis=0)
|
||||
path_sim = np.exp(-path_dist / (np.median(path_dist) + 1e-9))
|
||||
path = np.diag(path_sim, 1) + np.diag(path_sim, -1)
|
||||
deg_path, deg_rec = path.sum(1), rec.sum(1)
|
||||
denom = np.sum((deg_path + deg_rec) ** 2) + 1e-9
|
||||
mu = deg_path.dot(deg_path + deg_rec) / denom
|
||||
graph = mu * rec + (1 - mu) * path
|
||||
|
||||
# Symmetric-normalised Laplacian → eigenvectors → k-means over beats.
|
||||
lap = csgraph_laplacian(graph, normed=True)
|
||||
_, evecs = eigh(lap)
|
||||
evecs = median_filter(evecs, size=(9, 1))
|
||||
k = min(_N_EIGENVECTORS, evecs.shape[1])
|
||||
x = librosa.util.normalize(evecs[:, :k], norm=2, axis=1)
|
||||
ids = sklearn.cluster.KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(x)
|
||||
|
||||
# Boundaries = beats where the section-type label changes (plus the start).
|
||||
bound_beats = [0] + [i for i in range(1, len(ids)) if ids[i] != ids[i - 1]]
|
||||
|
||||
# Per-section mean RMS (energy) for positional naming, normalised 0..1.
|
||||
rms = librosa.feature.rms(y=y)[0]
|
||||
rms_t = librosa.times_like(rms, sr=sr)
|
||||
rms_max = float(rms.max()) or 1.0
|
||||
out: list[tuple[float, float]] = []
|
||||
for j, bi in enumerate(bound_beats):
|
||||
t = float(beat_times[min(bi, len(beat_times) - 1)])
|
||||
t_next = (
|
||||
float(beat_times[min(bound_beats[j + 1], len(beat_times) - 1)])
|
||||
if j + 1 < len(bound_beats)
|
||||
else duration
|
||||
)
|
||||
seg = rms[(rms_t >= t) & (rms_t < max(t_next, t + 1e-3))]
|
||||
energy = float(seg.mean() / rms_max) if len(seg) else 0.0
|
||||
out.append((t, energy))
|
||||
return out, duration
|
||||
|
||||
|
||||
def detect_grid(audio_path: str, sr: int = _SR) -> tuple[float, float]:
|
||||
"""Detect a track's tempo and the time of its first beat.
|
||||
|
||||
Returns ``(bpm, first_beat_sec)`` for building a Traktor beatgrid (BPM +
|
||||
anchor). Uses librosa beat tracking. Half/double-tempo octave errors are
|
||||
left for the user to fix with the ×2 / ÷2 controls (per product decision).
|
||||
"""
|
||||
import librosa
|
||||
|
||||
y, sr = librosa.load(audio_path, sr=sr, mono=True)
|
||||
tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
|
||||
bpm = float(np.ravel(tempo)[0])
|
||||
if bpm <= 0 or len(beats) == 0:
|
||||
raise ValueError("Could not detect a tempo/beat")
|
||||
first_beat = float(librosa.frames_to_time(beats, sr=sr)[0])
|
||||
return bpm, first_beat
|
||||
|
||||
|
||||
def select_hotcues(
|
||||
boundaries: list[tuple[float, float]],
|
||||
*,
|
||||
bpm: float,
|
||||
anchor: float,
|
||||
duration: float,
|
||||
free_slots: list[int],
|
||||
existing_times: list[float],
|
||||
max_cues: int = MAX_HOTCUES,
|
||||
phrase_bars: int = 16,
|
||||
) -> list[dict]:
|
||||
"""Turn raw boundaries into hotcue specs, phrase-snapped to the beatgrid.
|
||||
|
||||
Snaps each boundary to the nearest ``phrase_bars``-bar grid point (which
|
||||
also merges near-duplicates), drops any coinciding with an existing hotcue,
|
||||
caps to the free slots (down-sampling evenly if there are too many), and
|
||||
assigns positional names. Returns dicts with slot/start/name/type/length.
|
||||
"""
|
||||
if not boundaries or not free_slots or bpm <= 0:
|
||||
return []
|
||||
|
||||
beat = 60.0 / bpm
|
||||
phrase = phrase_bars * 4 * beat # seconds per phrase
|
||||
|
||||
# Snap to phrase grid; dedupe (keep the strongest energy seen at each point).
|
||||
snapped: dict[float, float] = {}
|
||||
for t, energy in boundaries:
|
||||
p = anchor + round((t - anchor) / phrase) * phrase
|
||||
p = max(0.0, min(p, duration - beat))
|
||||
snapped[p] = max(snapped.get(p, 0.0), energy)
|
||||
|
||||
# Drop points that collide with an existing (hand-placed) hotcue.
|
||||
def near_existing(t: float) -> bool:
|
||||
return any(abs(t - e) < beat for e in existing_times)
|
||||
|
||||
points = sorted((t, e) for t, e in snapped.items() if not near_existing(t))
|
||||
if not points:
|
||||
return []
|
||||
|
||||
# If more candidates than free slots, down-sample evenly across the track
|
||||
# (keeps intro..outro coverage rather than just the first N).
|
||||
n = min(len(free_slots), max_cues)
|
||||
if len(points) > n:
|
||||
idx = np.linspace(0, len(points) - 1, n).round().astype(int)
|
||||
points = [points[i] for i in sorted(set(idx))]
|
||||
|
||||
names = _name_positionally([t for t, _ in points], [e for _, e in points], duration)
|
||||
slots = sorted(free_slots)[: len(points)]
|
||||
return [
|
||||
{"slot": slot, "start": round(t, 3), "name": name, "type": 0, "length": 0.0}
|
||||
for slot, (t, _), name in zip(slots, points, names)
|
||||
]
|
||||
|
||||
|
||||
def _name_positionally(times: list[float], energies: list[float], duration: float) -> list[str]:
|
||||
"""Positional-hint names from track position + energy trend (not true
|
||||
structural classification — the names are hints; value is the position)."""
|
||||
if not times:
|
||||
return []
|
||||
med = float(np.median(energies))
|
||||
raw: list[str] = []
|
||||
n = len(times)
|
||||
for i, (t, e) in enumerate(zip(times, energies)):
|
||||
frac = t / duration if duration else 0.0
|
||||
prev = energies[i - 1] if i > 0 else e
|
||||
if i == 0 or frac < 0.08:
|
||||
name = "Intro"
|
||||
elif i == n - 1 or frac > 0.85:
|
||||
name = "Outro"
|
||||
elif e - prev > 0.12 and e >= med:
|
||||
name = "Drop"
|
||||
elif prev - e > 0.12:
|
||||
name = "Break"
|
||||
elif e > prev:
|
||||
name = "Build"
|
||||
else:
|
||||
name = "Mid"
|
||||
raw.append(name)
|
||||
# De-duplicate repeated labels with ordinals (Drop, Drop 2, ...).
|
||||
counts: dict[str, int] = {}
|
||||
out: list[str] = []
|
||||
for name in raw:
|
||||
counts[name] = counts.get(name, 0) + 1
|
||||
out.append(name if counts[name] == 1 else f"{name} {counts[name]}")
|
||||
return out
|
||||
@@ -13,11 +13,15 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from . import auto_hotcues as ah
|
||||
from . import prefs
|
||||
from .collection_service import CollectionService
|
||||
from .discovery import describe, detect_collections
|
||||
from .playlist_store import PlaylistError, PlaylistStore
|
||||
from .schemas import (
|
||||
AutoGridRequest,
|
||||
AutoHotcue,
|
||||
AutoHotcuesRequest,
|
||||
CollectionCandidate,
|
||||
CollectionOptions,
|
||||
CollectionStatus,
|
||||
@@ -426,13 +430,80 @@ def create_hotcue(body: SetHotcue) -> TrackCues:
|
||||
"""Create (or reposition + retype) the hotcue in a slot at a position."""
|
||||
try:
|
||||
require_store().set_hotcue(
|
||||
body.track_id, body.slot, body.start, body.type, body.length
|
||||
body.track_id, body.slot, body.start, body.type, body.length, name=body.name
|
||||
)
|
||||
except PlaylistError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
return _sync_cue_edit(body.track_id)
|
||||
|
||||
|
||||
@app.post("/api/tracks/auto-hotcues", response_model=TrackCues)
|
||||
def auto_hotcues(body: AutoHotcuesRequest) -> TrackCues:
|
||||
"""Analyze the track's audio and place structural hotcues into empty slots.
|
||||
|
||||
Detects section boundaries (librosa Laplacian segmentation), snaps them to
|
||||
the track's beatgrid phrases, names them positionally, and places up to
|
||||
MAX_HOTCUES into empty slots only (never overwrites). Requires a beatgrid."""
|
||||
store = require_store()
|
||||
entry = store.model_entry(body.track_id)
|
||||
if entry is None:
|
||||
raise HTTPException(404, "Track not found")
|
||||
cues = _build_track_cues(entry)
|
||||
if not cues.bpm or cues.bpm <= 0 or cues.grid_anchor is None:
|
||||
raise HTTPException(400, "Set a beatgrid before using Auto Hotcues")
|
||||
path = store.audio_path(body.track_id)
|
||||
if path is None or not path.exists():
|
||||
raise HTTPException(400, "Audio file not found (is the drive mounted?)")
|
||||
|
||||
try:
|
||||
boundaries, duration = ah.detect_boundaries(str(path))
|
||||
except Exception as ex: # analysis is best-effort; never 500 the UI
|
||||
raise HTTPException(400, f"Analysis failed: {ex}")
|
||||
|
||||
occupied = {c.hotcue for c in cues.cues if c.hotcue is not None and c.hotcue >= 0}
|
||||
free = [s for s in range(ah.MAX_HOTCUES) if s not in occupied]
|
||||
existing_times = [c.start for c in cues.cues if c.hotcue is not None and c.hotcue >= 0]
|
||||
specs = ah.select_hotcues(
|
||||
boundaries,
|
||||
bpm=cues.bpm,
|
||||
anchor=cues.grid_anchor,
|
||||
duration=duration,
|
||||
free_slots=free,
|
||||
existing_times=existing_times,
|
||||
max_cues=body.max_cues or ah.MAX_HOTCUES,
|
||||
)
|
||||
if not specs:
|
||||
return cues # no confident structure / no free slots — leave untouched
|
||||
try:
|
||||
store.place_hotcues(body.track_id, [AutoHotcue(**s) for s in specs])
|
||||
except PlaylistError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
return _sync_cue_edit(body.track_id)
|
||||
|
||||
|
||||
@app.post("/api/tracks/auto-grid", response_model=TrackCues)
|
||||
def auto_grid(body: AutoGridRequest) -> TrackCues:
|
||||
"""Detect tempo + first beat and build a beatgrid: sets BPM, sets hotcue 1
|
||||
(slot 0) to the first beat, and anchors the grid to that position. Octave
|
||||
(half/double) errors are left for the user to fix with the ×2/÷2 controls."""
|
||||
store = require_store()
|
||||
if store.model_entry(body.track_id) is None:
|
||||
raise HTTPException(404, "Track not found")
|
||||
path = store.audio_path(body.track_id)
|
||||
if path is None or not path.exists():
|
||||
raise HTTPException(400, "Audio file not found (is the drive mounted?)")
|
||||
try:
|
||||
bpm, first_beat = ah.detect_grid(str(path))
|
||||
except Exception as ex: # analysis is best-effort; never 500 the UI
|
||||
raise HTTPException(400, f"Analysis failed: {ex}")
|
||||
try:
|
||||
store.set_grid(body.track_id, bpm=bpm, anchor_sec=first_beat)
|
||||
store.set_hotcue(body.track_id, 0, first_beat, 0) # hotcue 1 = slot 0
|
||||
except PlaylistError as ex:
|
||||
raise HTTPException(400, str(ex))
|
||||
return _sync_cue_edit(body.track_id)
|
||||
|
||||
|
||||
@app.patch("/api/tracks/hotcue", response_model=TrackCues)
|
||||
def edit_hotcue_type(body: SetHotcueType) -> TrackCues:
|
||||
"""Change the type of an existing hotcue (keeps its position)."""
|
||||
|
||||
@@ -282,11 +282,18 @@ class PlaylistStore:
|
||||
return entry
|
||||
|
||||
def set_hotcue(
|
||||
self, track_id: str, slot: int, start_sec: float, cue_type: int, length_sec: float = 0.0
|
||||
self,
|
||||
track_id: str,
|
||||
slot: int,
|
||||
start_sec: float,
|
||||
cue_type: int,
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
) -> None:
|
||||
"""Create (or reposition + retype) the hotcue in `slot` at `start_sec`.
|
||||
|
||||
`length_sec` > 0 makes it a loop (used with cue_type 5)."""
|
||||
`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."."""
|
||||
if not 0 <= slot <= 7:
|
||||
raise PlaylistError(f"Invalid hotcue slot: {slot}")
|
||||
if cue_type not in self.CREATABLE_TYPES:
|
||||
@@ -307,7 +314,7 @@ class PlaylistStore:
|
||||
entry.cue_v2 = []
|
||||
entry.cue_v2.append(
|
||||
CueV2Type(
|
||||
name="n.n.", # Traktor's default name for a manual cue
|
||||
name=name or "n.n.", # Traktor's default name for a manual cue
|
||||
displ_order=0,
|
||||
type=cue_type,
|
||||
start=start_ms,
|
||||
@@ -320,6 +327,30 @@ class PlaylistStore:
|
||||
)
|
||||
self.dirty = True
|
||||
|
||||
def place_hotcues(
|
||||
self, track_id: str, specs: list, *, overwrite: bool = False
|
||||
) -> None:
|
||||
"""Batch-create hotcues from `specs` (each has .slot/.start/.name and
|
||||
optional .type/.length). With `overwrite` False (the default), slots that
|
||||
already hold a hotcue are skipped so hand-placed cues are never clobbered.
|
||||
Used by Auto Hotcues."""
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
occupied = {
|
||||
c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0
|
||||
}
|
||||
for spec in specs:
|
||||
if not overwrite and spec.slot in occupied:
|
||||
continue
|
||||
self.set_hotcue(
|
||||
track_id,
|
||||
spec.slot,
|
||||
spec.start,
|
||||
getattr(spec, "type", 0),
|
||||
getattr(spec, "length", 0.0),
|
||||
name=getattr(spec, "name", None),
|
||||
)
|
||||
|
||||
def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None:
|
||||
"""Change the type of the existing hotcue in `slot` (keeps its position)."""
|
||||
if cue_type not in self.POINT_CUE_TYPES:
|
||||
|
||||
@@ -152,6 +152,24 @@ class SetHotcue(BaseModel):
|
||||
start: float # seconds
|
||||
type: int # 0 cue, 1 fade-in, 2 fade-out, 3 load, 5 loop
|
||||
length: float = 0.0 # seconds (>0 for a loop hotcue)
|
||||
name: str | None = None # cue label; defaults to Traktor's "n.n." when unset
|
||||
|
||||
|
||||
class AutoHotcue(BaseModel):
|
||||
slot: int # 0–7
|
||||
start: float # seconds
|
||||
name: str | None = None # positional label (e.g. "Drop")
|
||||
type: int = 0 # plain cue
|
||||
length: float = 0.0 # seconds (>0 for a loop hotcue)
|
||||
|
||||
|
||||
class AutoHotcuesRequest(BaseModel):
|
||||
track_id: str
|
||||
max_cues: int | None = None # defaults to MAX_HOTCUES (8) server-side
|
||||
|
||||
|
||||
class AutoGridRequest(BaseModel):
|
||||
track_id: str
|
||||
|
||||
|
||||
class SetHotcueType(BaseModel):
|
||||
|
||||
@@ -5,6 +5,10 @@ uvicorn[standard]>=0.34
|
||||
pydantic>=2.11
|
||||
mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF)
|
||||
python-multipart>=0.0.9 # multipart form parsing for cover-art upload
|
||||
# Auto Hotcues: structural segmentation (McFee/Ellis Laplacian). Pure-Python,
|
||||
# ~150MB; numba/llvmlite ship Python 3.14 wheels (verified). No torch/native build.
|
||||
librosa>=0.11
|
||||
scikit-learn>=1.5
|
||||
# Traktor Pro 4 (NML v20) support requires the GitHub master (v4.0.0),
|
||||
# NOT the stale PyPI release (3.1.0), which cannot parse v4 files.
|
||||
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git
|
||||
@@ -292,5 +292,99 @@ with tempfile.TemporaryDirectory() as d:
|
||||
store2.save()
|
||||
check("revert BPM + anchor round-trips to original bytes", work.read_bytes() == original)
|
||||
|
||||
# ---- Invariant F: batch place_hotcues (Auto Hotcues) -------------------
|
||||
print("== F. place_hotcues fills empty slots only, names round-trip, localized ==")
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
from konduktor.schemas import AutoHotcue
|
||||
from traktor_nml_utils import TraktorCollection
|
||||
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
|
||||
store = PlaylistStore(work)
|
||||
entry = store._nml.collection.entry[0]
|
||||
loc = entry.location
|
||||
track_id = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
||||
|
||||
def entry_span(data: bytes, file_name: str):
|
||||
marker = f'FILE="{file_name}"'.encode()
|
||||
i = data.find(marker)
|
||||
start = data.rfind(b"<ENTRY ", 0, i)
|
||||
end = data.find(b"</ENTRY>", i) + len(b"</ENTRY>")
|
||||
return start, end
|
||||
|
||||
# Establish a hand-placed hotcue as the baseline the batch must NOT overwrite.
|
||||
used = {c.hotcue for c in (entry.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0}
|
||||
hand_slot = next(s for s in range(8) if s not in used)
|
||||
store.set_hotcue(track_id, hand_slot, 12.0, 0, name="HAND-PLACED")
|
||||
store.save()
|
||||
original = work.read_bytes()
|
||||
|
||||
# Batch: one spec targets the occupied slot (must be skipped), two fill free slots.
|
||||
store2 = PlaylistStore(work)
|
||||
e2 = store2._nml.collection.entry[0]
|
||||
now_used = {c.hotcue for c in (e2.cue_v2 or []) if c.hotcue is not None and c.hotcue >= 0}
|
||||
free = [s for s in range(8) if s not in now_used][:2]
|
||||
specs = [AutoHotcue(slot=hand_slot, start=99.0, name="SHOULD-NOT-OVERWRITE")]
|
||||
specs += [AutoHotcue(slot=s, start=30.0 + i * 10, name=f"Auto {i}") for i, s in enumerate(free)]
|
||||
store2.place_hotcues(track_id, specs)
|
||||
store2.save()
|
||||
edited = work.read_bytes()
|
||||
|
||||
check("file actually changed", original != edited)
|
||||
|
||||
os_, oe = entry_span(original, loc.file)
|
||||
es_, ee = entry_span(edited, loc.file)
|
||||
check(
|
||||
"everything outside the edited track's ENTRY is byte-identical",
|
||||
original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:],
|
||||
)
|
||||
n = diff_count(original[os_:oe], edited[es_:ee])
|
||||
check(f"edited ENTRY diff is small (<= 6 tag-lines for {len(free)} cues)", n <= 6, f"got {n}")
|
||||
|
||||
reparsed = TraktorCollection(path=work)
|
||||
e0 = reparsed.nml.collection.entry[0]
|
||||
hand = next((c for c in (e0.cue_v2 or []) if c.hotcue == hand_slot), None)
|
||||
check("hand-placed hotcue NOT overwritten (position)", hand is not None and abs(hand.start - 12000.0) < 1)
|
||||
check("hand-placed hotcue NOT overwritten (name)", hand is not None and hand.name == "HAND-PLACED")
|
||||
for i, s in enumerate(free):
|
||||
c = next((c for c in (e0.cue_v2 or []) if c.hotcue == s), None)
|
||||
check(f"auto hotcue slot {s} created", c is not None)
|
||||
check(f"auto hotcue slot {s} name round-trips", c is not None and c.name == f"Auto {i}")
|
||||
check(
|
||||
f"auto hotcue slot {s} START in ms",
|
||||
c is not None and abs(c.start - (30000.0 + i * 10000)) < 1,
|
||||
)
|
||||
|
||||
# ---- Invariant G: select_hotcues placement logic (pure, no audio) ------
|
||||
print("== G. select_hotcues: phrase-snap, empty-slots, names, existing-cue avoidance ==")
|
||||
from konduktor import auto_hotcues as ah # noqa: E402
|
||||
|
||||
# 128 BPM => beat 0.46875s, 16-bar phrase = 30.0s exactly; anchor 0.0.
|
||||
BPM, ANCHOR, DUR = 128.0, 0.0, 300.0
|
||||
# Raw boundaries near (but not exactly on) phrase multiples + a fragmented pair.
|
||||
raw = [(0.3, 0.2), (29.4, 0.5), (30.6, 0.55), (61.0, 0.9), (150.0, 0.3), (270.2, 0.25)]
|
||||
specs = ah.select_hotcues(
|
||||
raw, bpm=BPM, anchor=ANCHOR, duration=DUR,
|
||||
free_slots=[2, 3, 4, 5, 6, 7], existing_times=[], max_cues=8,
|
||||
)
|
||||
starts = [s["start"] for s in specs]
|
||||
check("snaps to 30s phrase grid", all(abs(round(t / 30.0) * 30.0 - t) < 0.01 for t in starts), str(starts))
|
||||
check("fragmented 29.4/30.6 merge to one boundary (30.0)", starts.count(30.0) == 1, str(starts))
|
||||
check("only free slots used, in ascending order", [s["slot"] for s in specs] == sorted(s["slot"] for s in specs) and set(s["slot"] for s in specs) <= {2, 3, 4, 5, 6, 7})
|
||||
check("first cue named Intro", specs and specs[0]["name"] == "Intro")
|
||||
check("last cue named Outro", specs and specs[-1]["name"] == "Outro")
|
||||
check("names are unique (ordinal de-dupe)", len({s["name"] for s in specs}) == len(specs), str([s["name"] for s in specs]))
|
||||
|
||||
# A hotcue already sitting on the 60s phrase must not get a duplicate.
|
||||
specs2 = ah.select_hotcues(
|
||||
raw, bpm=BPM, anchor=ANCHOR, duration=DUR,
|
||||
free_slots=[0, 1, 2, 3, 4, 5, 6, 7], existing_times=[60.0], max_cues=8,
|
||||
)
|
||||
check("boundary colliding with an existing hotcue is dropped", 60.0 not in [s["start"] for s in specs2], str([s["start"] for s in specs2]))
|
||||
|
||||
# No free slots => nothing placed.
|
||||
check("no free slots => empty result", ah.select_hotcues(raw, bpm=BPM, anchor=ANCHOR, duration=DUR, free_slots=[], existing_times=[], max_cues=8) == [])
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
+80
-23
@@ -8,8 +8,7 @@ import {
|
||||
} from './lib/trackColumns'
|
||||
import { Sidebar, type Source } from './components/Sidebar'
|
||||
import { Toolbar, emptyFilters, type Filters } from './components/Toolbar'
|
||||
import { TrackTable } from './components/TrackTable'
|
||||
import { PlaylistEditor } from './components/PlaylistEditor'
|
||||
import { TrackTable, PlaylistTable } from './components/TrackTable'
|
||||
import { SelectionBar } from './components/SelectionBar'
|
||||
import { StatusBar } from './components/StatusBar'
|
||||
import { Toast, type ToastMsg } from './components/Toast'
|
||||
@@ -153,11 +152,46 @@ export default function App() {
|
||||
const isAll = source.kind === 'all'
|
||||
const tracks: Track[] = isAll ? (allTracks.data?.items ?? []) : (playlistTracks.data ?? [])
|
||||
const loading = isAll ? allTracks.isLoading : playlistTracks.isLoading
|
||||
const filtered = useMemo(() => (isAll ? applyFilters(tracks, filters) : tracks), [
|
||||
isAll,
|
||||
tracks,
|
||||
filters,
|
||||
])
|
||||
// Search / filters apply to both the library and playlists (the toolbar is
|
||||
// always visible). In a playlist a filtered view disables drag-reorder — see
|
||||
// `canReorder` below — so a partial order can't overwrite the full entry list.
|
||||
const filtered = useMemo(() => applyFilters(tracks, filters), [tracks, filters])
|
||||
const filtersActive =
|
||||
filters.search !== '' ||
|
||||
filters.genre !== '' ||
|
||||
filters.key !== '' ||
|
||||
filters.bpmMin !== '' ||
|
||||
filters.bpmMax !== '' ||
|
||||
filters.ratingMin > 0 ||
|
||||
filters.hasCues !== 'any'
|
||||
|
||||
// Playlist reorder / remove: persist the new entry order via setEntries, and
|
||||
// optimistically update the cached playlist so the list stays put after a drag
|
||||
// (the TrackTable re-syncs to this on the next render).
|
||||
const reorderPlaylist = useCallback(
|
||||
(ids: string[]) => {
|
||||
if (source.kind !== 'playlist') return
|
||||
const id = source.id
|
||||
qc.setQueryData<Track[]>(['playlist', id], (prev) => {
|
||||
if (!prev) return prev
|
||||
const byId = new Map(prev.map((t) => [t.id, t]))
|
||||
return ids.map((i) => byId.get(i)).filter((t): t is Track => !!t)
|
||||
})
|
||||
api
|
||||
.setEntries(id, ids)
|
||||
.then(() => {
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] }) // refresh counts
|
||||
})
|
||||
.catch((e) => onError((e as Error).message))
|
||||
},
|
||||
[source, qc, onError],
|
||||
)
|
||||
const removeFromPlaylist = useCallback(
|
||||
(trackId: string) =>
|
||||
reorderPlaylist(tracks.filter((t) => t.id !== trackId).map((t) => t.id)),
|
||||
[reorderPlaylist, tracks],
|
||||
)
|
||||
|
||||
const handleOpened = () => {
|
||||
setForcePicker(false)
|
||||
@@ -226,26 +260,28 @@ export default function App() {
|
||||
)}
|
||||
|
||||
{/* Prep strip spans the top of the window; the library sits below it. */}
|
||||
<PrepStrip track={prepTrack} playRequest={playRequest} onError={onError} />
|
||||
<PrepStrip track={prepTrack} playRequest={playRequest} onError={onError} onNotify={notify} />
|
||||
|
||||
<div className="flex min-h-0 flex-1 overflow-hidden">
|
||||
<Sidebar source={source} onSelect={selectSource} onError={onError} />
|
||||
|
||||
<main className="relative flex min-w-0 flex-1 flex-col">
|
||||
{isAll ? (
|
||||
<Toolbar
|
||||
filters={filters}
|
||||
onChange={setFilters}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
onResetColumns={resetColumns}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center gap-3 border-b border-line bg-ink-900 px-4 py-3">
|
||||
{/* Search / filters / column settings — always visible. */}
|
||||
<Toolbar
|
||||
filters={filters}
|
||||
onChange={setFilters}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
onResetColumns={resetColumns}
|
||||
/>
|
||||
{!isAll && (
|
||||
<div className="flex items-center gap-3 border-b border-line bg-ink-900 px-4 py-2">
|
||||
<span className="text-[11px] text-accent">♫</span>
|
||||
<span className="font-semibold text-text">{source.name}</span>
|
||||
<span className="text-xs text-faint">
|
||||
{tracks.length} tracks · drag ⠿ to reorder · × to remove
|
||||
{filtersActive
|
||||
? `${filtered.length} of ${tracks.length} tracks · × to remove · clear the filter to reorder`
|
||||
: `${tracks.length} tracks · drag ⠿ to reorder · × to remove`}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -281,12 +317,33 @@ export default function App() {
|
||||
onColumnSizingChange={setColumnSizing}
|
||||
/>
|
||||
)
|
||||
) : tracks.length === 0 ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-2 text-muted">
|
||||
<div className="text-lg">This playlist is empty</div>
|
||||
<div className="text-sm text-faint">
|
||||
Go to <span className="text-text">All Tracks</span>, select tracks, and add them here.
|
||||
</div>
|
||||
</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-1 text-muted">
|
||||
<div className="text-lg">No tracks match</div>
|
||||
<div className="text-sm text-faint">Try clearing some filters.</div>
|
||||
</div>
|
||||
) : (
|
||||
<PlaylistEditor
|
||||
uuid={(source as { id: string }).id}
|
||||
tracks={tracks}
|
||||
onError={onError}
|
||||
<PlaylistTable
|
||||
tracks={filtered}
|
||||
onRowContextMenu={(track, x, y) => setMenu({ track, x, y })}
|
||||
onPlay={playTrack}
|
||||
onEditField={editField}
|
||||
activeTrackId={prepTrack?.id ?? null}
|
||||
columnVisibility={columnVisibility}
|
||||
columnOrder={columnOrder}
|
||||
columnSizing={columnSizing}
|
||||
onColumnOrderChange={setColumnOrder}
|
||||
onColumnSizingChange={setColumnSizing}
|
||||
onReorder={reorderPlaylist}
|
||||
onRemove={removeFromPlaylist}
|
||||
canReorder={!filtersActive}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
+18
-1
@@ -249,14 +249,31 @@ export const api = {
|
||||
`${API_BASE}/api/tracks/audio?track_id=${encodeURIComponent(trackId)}`,
|
||||
trackCues: (trackId: string) =>
|
||||
getJSON<TrackCues>(`/api/tracks/cues?track_id=${encodeURIComponent(trackId)}`),
|
||||
createHotcue: (trackId: string, slot: number, start: number, type: number, length = 0) =>
|
||||
createHotcue: (
|
||||
trackId: string,
|
||||
slot: number,
|
||||
start: number,
|
||||
type: number,
|
||||
length = 0,
|
||||
name?: string,
|
||||
) =>
|
||||
send<TrackCues>('POST', '/api/tracks/hotcue', {
|
||||
track_id: trackId,
|
||||
slot,
|
||||
start,
|
||||
type,
|
||||
length,
|
||||
name,
|
||||
}),
|
||||
// Backend analyses the audio and places structural hotcues into empty slots.
|
||||
autoHotcues: (trackId: string, maxCues?: number) =>
|
||||
send<TrackCues>('POST', '/api/tracks/auto-hotcues', {
|
||||
track_id: trackId,
|
||||
max_cues: maxCues,
|
||||
}),
|
||||
// Backend detects tempo + first beat: sets BPM, hotcue 1, and grid anchor.
|
||||
autoGrid: (trackId: string) =>
|
||||
send<TrackCues>('POST', '/api/tracks/auto-grid', { track_id: trackId }),
|
||||
setHotcueType: (trackId: string, slot: number, type: number) =>
|
||||
send<TrackCues>('PATCH', '/api/tracks/hotcue', { track_id: trackId, slot, type }),
|
||||
deleteHotcue: (trackId: string, slot: number) =>
|
||||
|
||||
@@ -13,6 +13,9 @@ interface Props {
|
||||
onReset: () => void
|
||||
onToggleLock: () => void
|
||||
onDeleteGrid: () => void
|
||||
/** Detect BPM + first beat and build the grid (sets hotcue 1 + anchor). */
|
||||
onAnalyze: () => void
|
||||
analyzing: boolean
|
||||
}
|
||||
|
||||
const BTN =
|
||||
@@ -39,6 +42,8 @@ export function GridControls({
|
||||
onReset,
|
||||
onToggleLock,
|
||||
onDeleteGrid,
|
||||
onAnalyze,
|
||||
analyzing,
|
||||
}: Props) {
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [val, setVal] = useState('')
|
||||
@@ -194,6 +199,18 @@ export function GridControls({
|
||||
🗑 Grid
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* analyze: detect BPM + first beat, set hotcue 1 + grid anchor */}
|
||||
<div className="flex gap-1">
|
||||
<button
|
||||
className={BTN}
|
||||
onClick={onAnalyze}
|
||||
disabled={analyzing}
|
||||
title="Detect BPM and first beat, then set the grid + hotcue 1 (fix octave with ÷2 / ×2)"
|
||||
>
|
||||
{analyzing ? '…' : 'Analyze'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -4,7 +4,8 @@ import { contrastText, cueColor } from '../lib/cues'
|
||||
interface Props {
|
||||
cues: CuePoint[]
|
||||
selectedSlot: number | null
|
||||
onSlotClick: (slot: number) => void
|
||||
onSlotPress: (slot: number) => void
|
||||
onSlotRelease: (slot: number) => void
|
||||
}
|
||||
|
||||
const SLOTS = [0, 1, 2, 3, 4, 5, 6, 7] // Traktor hotcue slots → labelled 1–8
|
||||
@@ -12,10 +13,12 @@ const SLOTS = [0, 1, 2, 3, 4, 5, 6, 7] // Traktor hotcue slots → labelled 1–
|
||||
/**
|
||||
* The 8 hotcue slots, colour-coded by cue type when assigned (gray when empty).
|
||||
* Rendered as a flex-1 group inside the hotcue row; the parent supplies the row
|
||||
* chrome and the trailing edit controls. Clicking a slot delegates to the parent
|
||||
* (create when empty, jump/trigger when assigned).
|
||||
* chrome and the trailing edit controls. Slots respond to press AND release
|
||||
* (pointer capture, so a release outside the button still fires) so the parent
|
||||
* can implement momentary "cue preview" (play while held). Press creates when
|
||||
* empty and jumps/triggers when assigned; release ends any preview.
|
||||
*/
|
||||
export function HotcueBar({ cues, selectedSlot, onSlotClick }: Props) {
|
||||
export function HotcueBar({ cues, selectedSlot, onSlotPress, onSlotRelease }: Props) {
|
||||
return (
|
||||
<div className="flex flex-1 items-stretch gap-px">
|
||||
{SLOTS.map((slot) => {
|
||||
@@ -25,7 +28,15 @@ export function HotcueBar({ cues, selectedSlot, onSlotClick }: Props) {
|
||||
return (
|
||||
<button
|
||||
key={slot}
|
||||
onClick={() => onSlotClick(slot)}
|
||||
onPointerDown={(e) => {
|
||||
e.preventDefault()
|
||||
// Capture so the matching release fires even if the pointer drifts
|
||||
// off the button before it's let go.
|
||||
e.currentTarget.setPointerCapture(e.pointerId)
|
||||
onSlotPress(slot)
|
||||
}}
|
||||
onPointerUp={() => onSlotRelease(slot)}
|
||||
onPointerCancel={() => onSlotRelease(slot)}
|
||||
title={
|
||||
cue
|
||||
? cue.name && cue.name !== 'n.n.'
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type DragEndEvent,
|
||||
} from '@dnd-kit/core'
|
||||
import {
|
||||
SortableContext,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
arrayMove,
|
||||
} from '@dnd-kit/sortable'
|
||||
import { CSS } from '@dnd-kit/utilities'
|
||||
import { restrictToVerticalAxis, restrictToParentElement } from '@dnd-kit/modifiers'
|
||||
import { api, type Track } from '../api'
|
||||
import { formatBpm, formatDuration, keyColor } from '../lib/format'
|
||||
import { RatingStars } from './RatingStars'
|
||||
|
||||
interface Props {
|
||||
uuid: string
|
||||
tracks: Track[]
|
||||
onError: (msg: string) => void
|
||||
onRowContextMenu?: (track: Track, x: number, y: number) => void
|
||||
}
|
||||
|
||||
function Row({
|
||||
track,
|
||||
index,
|
||||
onRemove,
|
||||
onContextMenu,
|
||||
}: {
|
||||
track: Track
|
||||
index: number
|
||||
onRemove: (id: string) => void
|
||||
onContextMenu?: (track: Track, x: number, y: number) => void
|
||||
}) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
|
||||
useSortable({ id: track.id })
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={{ transform: CSS.Transform.toString(transform), transition }}
|
||||
className={`flex items-center border-b border-ink-850 text-sm ${
|
||||
isDragging ? 'z-10 bg-ink-800 shadow-lg' : 'hover:bg-ink-850'
|
||||
}`}
|
||||
onContextMenu={(e) => {
|
||||
if (!onContextMenu) return
|
||||
e.preventDefault()
|
||||
onContextMenu(track, e.clientX, e.clientY)
|
||||
}}
|
||||
>
|
||||
<button
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
title="Drag to reorder"
|
||||
className="w-8 shrink-0 cursor-grab px-2 text-center text-faint hover:text-text active:cursor-grabbing"
|
||||
>
|
||||
⠿
|
||||
</button>
|
||||
<span className="w-8 shrink-0 text-right text-xs tabular-nums text-faint">
|
||||
{index + 1}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1 px-3 py-2">
|
||||
<div className="truncate font-medium text-text">
|
||||
{track.title || <span className="text-faint">Untitled</span>}
|
||||
</div>
|
||||
<div className="truncate text-xs text-muted">{track.artist}</div>
|
||||
</div>
|
||||
<div className="w-16 shrink-0 px-2 text-right tabular-nums">{formatBpm(track.bpm)}</div>
|
||||
<div className="w-14 shrink-0 px-2 text-center">
|
||||
{track.key ? (
|
||||
<span className="text-xs font-semibold" style={{ color: keyColor(track.key) }}>
|
||||
{track.key}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-faint">—</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-24 shrink-0 px-2">
|
||||
<RatingStars value={track.rating} />
|
||||
</div>
|
||||
<div className="w-14 shrink-0 px-2 text-right tabular-nums text-muted">
|
||||
{formatDuration(track.length)}
|
||||
</div>
|
||||
<button
|
||||
title="Remove from playlist"
|
||||
onClick={() => onRemove(track.id)}
|
||||
className="w-10 shrink-0 px-2 text-center text-faint hover:text-pink"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PlaylistEditor({ uuid, tracks, onError, onRowContextMenu }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [items, setItems] = useState<Track[]>(tracks)
|
||||
|
||||
// Re-sync when the server data changes (initial load, or tracks added elsewhere).
|
||||
useEffect(() => setItems(tracks), [tracks])
|
||||
|
||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }))
|
||||
|
||||
const persist = useMutation({
|
||||
mutationFn: (ids: string[]) => api.setEntries(uuid, ids),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
qc.invalidateQueries({ queryKey: ['playlists'] }) // refresh counts
|
||||
},
|
||||
onError: (e: Error) => onError(e.message),
|
||||
})
|
||||
|
||||
const commit = (next: Track[]) => {
|
||||
setItems(next)
|
||||
// Keep the cached playlist query in sync so navigating away/back is stable.
|
||||
qc.setQueryData(['playlist', uuid], next)
|
||||
persist.mutate(next.map((t) => t.id))
|
||||
}
|
||||
|
||||
const onDragEnd = (e: DragEndEvent) => {
|
||||
const { active, over } = e
|
||||
if (!over || active.id === over.id) return
|
||||
const from = items.findIndex((t) => t.id === active.id)
|
||||
const to = items.findIndex((t) => t.id === over.id)
|
||||
if (from < 0 || to < 0) return
|
||||
commit(arrayMove(items, from, to))
|
||||
}
|
||||
|
||||
const remove = (id: string) => commit(items.filter((t) => t.id !== id))
|
||||
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-2 text-muted">
|
||||
<div className="text-lg">This playlist is empty</div>
|
||||
<div className="text-sm text-faint">
|
||||
Go to <span className="text-text">All Tracks</span>, select tracks, and add them here.
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-auto">
|
||||
<div className="sticky top-0 z-10 flex border-b border-line bg-ink-850 text-[11px] font-semibold uppercase tracking-wider text-muted">
|
||||
<span className="w-8 shrink-0" />
|
||||
<span className="w-8 shrink-0 text-right">#</span>
|
||||
<span className="flex-1 px-3 py-2.5">Title</span>
|
||||
<span className="w-16 shrink-0 px-2 text-right">BPM</span>
|
||||
<span className="w-14 shrink-0 px-2 text-center">Key</span>
|
||||
<span className="w-24 shrink-0 px-2">Rating</span>
|
||||
<span className="w-14 shrink-0 px-2 text-right">Time</span>
|
||||
<span className="w-10 shrink-0" />
|
||||
</div>
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={onDragEnd}
|
||||
modifiers={[restrictToVerticalAxis, restrictToParentElement]}
|
||||
>
|
||||
<SortableContext items={items.map((t) => t.id)} strategy={verticalListSortingStrategy}>
|
||||
{items.map((t, i) => (
|
||||
<Row
|
||||
key={t.id}
|
||||
track={t}
|
||||
index={i}
|
||||
onRemove={remove}
|
||||
onContextMenu={onRowContextMenu}
|
||||
/>
|
||||
))}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -16,6 +16,8 @@ interface Props {
|
||||
/** Bumped by the library's per-row play button to load + auto-play. */
|
||||
playRequest?: number
|
||||
onError?: (msg: string) => void
|
||||
/** Neutral/success feedback (e.g. Auto Hotcues result). */
|
||||
onNotify?: (kind: 'success' | 'error', msg: string) => void
|
||||
}
|
||||
|
||||
function fmt(secs: number): string {
|
||||
@@ -41,9 +43,10 @@ const LOOP_SIZES = [1 / 32, 1 / 16, 1 / 8, 1 / 4, 1 / 2, 1, 2, 4, 8, 16, 32]
|
||||
* Web Audio PlaybackEngine (seamless loops); the same decoded buffer feeds the
|
||||
* scratch engine and both waveform views.
|
||||
*/
|
||||
export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [playing, setPlaying] = useState(false)
|
||||
const [previewing, setPreviewing] = useState(false) // momentary hold-to-play active
|
||||
const [current, setCurrent] = useState(0)
|
||||
const [duration, setDuration] = useState(0)
|
||||
const [ready, setReady] = useState(false)
|
||||
@@ -71,6 +74,12 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
const engagedRef = useRef(false) // scratch engine is dragging or coasting
|
||||
const pendingPlayRef = useRef(false) // a play was requested; start once ready
|
||||
const loadedIdRef = useRef<string | null>(null) // trackId whose buffer is loaded
|
||||
const [autoBusy, setAutoBusy] = useState(false)
|
||||
const [gridBusy, setGridBusy] = useState(false)
|
||||
// Active momentary "cue preview": a hotcue OR the CUE button held while paused
|
||||
// plays from its point and stops on release, unless `latched` (play pressed
|
||||
// during the hold). `id` identifies the holder so its release matches.
|
||||
const previewRef = useRef<{ id: string; start: number; latched: boolean } | null>(null)
|
||||
|
||||
const trackId = track?.id ?? null
|
||||
|
||||
@@ -150,6 +159,8 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
setActiveBeats(null)
|
||||
setCuePoint(0)
|
||||
loopInRef.current = null
|
||||
previewRef.current = null
|
||||
setPreviewing(false)
|
||||
}, [trackId])
|
||||
|
||||
// Analyse once per track; the decoded buffer feeds both the playback and
|
||||
@@ -226,6 +237,19 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
const eng = playbackRef.current
|
||||
if (!eng || !eng.ready) return
|
||||
getCtx() // ensure the context resumes on this user gesture
|
||||
// Play pressed during a momentary cue preview → latch playback on so it
|
||||
// keeps going after the hotcue button is released.
|
||||
const pv = previewRef.current
|
||||
if (pv && !pv.latched) {
|
||||
pv.latched = true
|
||||
setPreviewing(false) // becomes normal (green) playback
|
||||
if (!eng.playing) {
|
||||
eng.play()
|
||||
setPlaying(true)
|
||||
}
|
||||
setCurrent(eng.getPosition())
|
||||
return
|
||||
}
|
||||
if (eng.playing) {
|
||||
eng.pause()
|
||||
setPlaying(false)
|
||||
@@ -236,10 +260,38 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
setCurrent(eng.getPosition())
|
||||
}
|
||||
|
||||
// Start a momentary "cue preview" from `start` for holder `id`: play now, and
|
||||
// remember to stop + return on release (see endPreview) unless it's latched.
|
||||
const beginPreview = (id: string, start: number) => {
|
||||
const eng = playbackRef.current
|
||||
if (!eng || !eng.ready) return
|
||||
previewRef.current = { id, start, latched: false }
|
||||
eng.play()
|
||||
setPlaying(true)
|
||||
setPreviewing(true)
|
||||
}
|
||||
|
||||
// End holder `id`'s momentary preview: stop and return to the point — unless a
|
||||
// play press latched it during the hold, in which case playback continues.
|
||||
const endPreview = (id: string) => {
|
||||
const pv = previewRef.current
|
||||
if (!pv || pv.id !== id) return
|
||||
previewRef.current = null
|
||||
setPreviewing(false)
|
||||
if (pv.latched) return
|
||||
const eng = playbackRef.current
|
||||
if (!eng) return
|
||||
eng.pause()
|
||||
eng.seek(pv.start)
|
||||
setPlaying(false)
|
||||
setCurrent(pv.start)
|
||||
}
|
||||
|
||||
// CUE (Traktor/CDJ-style): while playing, jump back to the cue point and
|
||||
// pause; while paused and away from the cue, drop the cue at the playhead;
|
||||
// while paused and already at the cue, play from it.
|
||||
const handleCue = () => {
|
||||
// while paused and already at the cue, play from it for as long as the button
|
||||
// is held (momentary preview — mirrors the hotcue buttons).
|
||||
const onCuePress = () => {
|
||||
const eng = playbackRef.current
|
||||
if (!eng || !eng.ready) return
|
||||
getCtx()
|
||||
@@ -249,12 +301,17 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
setPlaying(false)
|
||||
setCurrent(cuePoint)
|
||||
} else if (Math.abs(current - cuePoint) > 0.03) {
|
||||
setCuePoint(current)
|
||||
// Drop the cue at the (snapped) playhead and park on it, so the next press
|
||||
// is "at the cue" and previews rather than re-setting.
|
||||
const t = snapTime(current)
|
||||
setCuePoint(t)
|
||||
eng.seek(t)
|
||||
setCurrent(t)
|
||||
} else {
|
||||
eng.play()
|
||||
setPlaying(true)
|
||||
beginPreview('cue', cuePoint)
|
||||
}
|
||||
}
|
||||
const onCueRelease = () => endPreview('cue')
|
||||
|
||||
// A library row's play button bumps `playRequest`: load (if needed) + play.
|
||||
// If the requested track is already loaded and ready, start immediately;
|
||||
@@ -458,32 +515,75 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
return best != null && bestDiff <= beats * 0.05 ? best : null
|
||||
}
|
||||
|
||||
const onSlotClick = async (slot: number) => {
|
||||
// Hotcue slot pressed (mouse/touch down, or key down). Empty slots create a
|
||||
// hotcue; assigned slots jump to their point. When jumping while PAUSED we
|
||||
// also begin a momentary "cue preview" — play from the point for as long as
|
||||
// the button is held (released in onSlotRelease). While already playing, a
|
||||
// press just jumps, as before.
|
||||
const onSlotPress = async (slot: number) => {
|
||||
if (!track) return
|
||||
const cue = hotcueAt(slot)
|
||||
if (cue) {
|
||||
// A loop hotcue jumps to its start AND re-engages a loop of its length.
|
||||
if (cue.type === LOOP_TYPE && cue.length > 0) {
|
||||
seek(cue.start)
|
||||
engagLoop(cue.start, cue.start + cue.length, beatsForLength(cue.length))
|
||||
} else {
|
||||
seek(cue.start)
|
||||
if (!cue) {
|
||||
try {
|
||||
// Setting a hotcue while a loop is active stores it as a loop hotcue.
|
||||
if (loopActive && loopRegion) {
|
||||
const len = loopRegion.end - loopRegion.start
|
||||
applyCueEdit(await api.createHotcue(track.id, slot, loopRegion.start, LOOP_TYPE, len))
|
||||
} else {
|
||||
const t = snapTime(playbackRef.current?.getPosition() ?? current)
|
||||
applyCueEdit(await api.createHotcue(track.id, slot, t, 0))
|
||||
}
|
||||
setSelectedSlot(slot)
|
||||
} catch (e) {
|
||||
onError?.((e as Error).message)
|
||||
}
|
||||
setSelectedSlot(slot)
|
||||
return
|
||||
}
|
||||
setSelectedSlot(slot)
|
||||
const eng = playbackRef.current
|
||||
if (!eng || !eng.ready) return
|
||||
getCtx()
|
||||
// A loop hotcue jumps to its start AND re-engages a loop of its length.
|
||||
if (cue.type === LOOP_TYPE && cue.length > 0) {
|
||||
seek(cue.start)
|
||||
engagLoop(cue.start, cue.start + cue.length, beatsForLength(cue.length))
|
||||
} else {
|
||||
seek(cue.start)
|
||||
}
|
||||
// Paused at press → momentary preview: play while held.
|
||||
if (!eng.playing) beginPreview(`hc:${slot}`, cue.start)
|
||||
}
|
||||
|
||||
// Hotcue slot released (mouse/touch up, or key up). Ends its momentary preview.
|
||||
const onSlotRelease = (slot: number) => endPreview(`hc:${slot}`)
|
||||
|
||||
// Auto Hotcues: the backend analyses the track's audio (librosa structural
|
||||
// segmentation), snaps boundaries to the beatgrid, and fills empty slots only.
|
||||
// Requires a beatgrid (button disabled otherwise).
|
||||
const canAutoCue = !!(cueData?.bpm && cueData.bpm > 0 && cueData.grid_anchor != null)
|
||||
const runAutoHotcues = async () => {
|
||||
if (!track || !canAutoCue || autoBusy) return
|
||||
const hotcueCount = (c: TrackCues | null) =>
|
||||
c?.cues.filter((x) => x.hotcue >= 0).length ?? 0
|
||||
if (hotcueCount(cueData) >= 8) {
|
||||
onError?.('No free hotcue slots — delete some first')
|
||||
return
|
||||
}
|
||||
setAutoBusy(true)
|
||||
try {
|
||||
// Setting a hotcue while a loop is active stores it as a loop hotcue.
|
||||
if (loopActive && loopRegion) {
|
||||
const len = loopRegion.end - loopRegion.start
|
||||
applyCueEdit(await api.createHotcue(track.id, slot, loopRegion.start, LOOP_TYPE, len))
|
||||
const before = hotcueCount(cueData)
|
||||
const fresh = await api.autoHotcues(track.id)
|
||||
applyCueEdit(fresh)
|
||||
const placed = Math.max(0, hotcueCount(fresh) - before)
|
||||
if (placed === 0) {
|
||||
onNotify?.('error', 'No clear structure found — no hotcues placed')
|
||||
} else {
|
||||
const t = snapTime(playbackRef.current?.getPosition() ?? current)
|
||||
applyCueEdit(await api.createHotcue(track.id, slot, t, 0))
|
||||
onNotify?.('success', `Placed ${placed} auto hotcue${placed === 1 ? '' : 's'}`)
|
||||
}
|
||||
setSelectedSlot(slot)
|
||||
} catch (e) {
|
||||
onError?.((e as Error).message)
|
||||
} finally {
|
||||
setAutoBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,29 +620,59 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
// Space → play/pause; 1–8 → the matching hotcue slot; Shift+1–8 → delete it.
|
||||
// Digits are read from e.code (layout-/Shift-independent) and a ref holds the
|
||||
// latest handlers so the listener attaches once and never goes stale.
|
||||
const shortcutsRef = useRef({ toggle, onSlotClick, deleteHotcueSlot })
|
||||
shortcutsRef.current = { toggle, onSlotClick, deleteHotcueSlot }
|
||||
const shortcutsRef = useRef({
|
||||
toggle,
|
||||
onSlotPress,
|
||||
onSlotRelease,
|
||||
deleteHotcueSlot,
|
||||
onCuePress,
|
||||
onCueRelease,
|
||||
})
|
||||
shortcutsRef.current = {
|
||||
toggle,
|
||||
onSlotPress,
|
||||
onSlotRelease,
|
||||
deleteHotcueSlot,
|
||||
onCuePress,
|
||||
onCueRelease,
|
||||
}
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
// Ignore while typing in a field or with a non-Shift modifier held.
|
||||
const t = e.target as HTMLElement | null
|
||||
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
|
||||
if (e.metaKey || e.ctrlKey || e.altKey) return
|
||||
if (e.repeat) return // held key auto-repeats — treat as one press+hold
|
||||
if (e.code === 'Space') {
|
||||
e.preventDefault()
|
||||
shortcutsRef.current.toggle()
|
||||
return
|
||||
}
|
||||
if (e.code === 'KeyC') {
|
||||
e.preventDefault()
|
||||
shortcutsRef.current.onCuePress()
|
||||
return
|
||||
}
|
||||
const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/)
|
||||
if (digit) {
|
||||
e.preventDefault()
|
||||
const slot = Number(digit[1]) - 1
|
||||
if (e.shiftKey) void shortcutsRef.current.deleteHotcueSlot(slot)
|
||||
else void shortcutsRef.current.onSlotClick(slot)
|
||||
else void shortcutsRef.current.onSlotPress(slot)
|
||||
}
|
||||
}
|
||||
// keyup ends a held hotcue's momentary preview (release).
|
||||
const onKeyRelease = (e: KeyboardEvent) => {
|
||||
if (e.code === 'KeyC') shortcutsRef.current.onCueRelease()
|
||||
const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/)
|
||||
if (digit) shortcutsRef.current.onSlotRelease(Number(digit[1]) - 1)
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
window.addEventListener('keyup', onKeyRelease)
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKey)
|
||||
window.removeEventListener('keyup', onKeyRelease)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// ---- beatgrid ---------------------------------------------------------
|
||||
@@ -588,13 +718,26 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
onError?.((e as Error).message)
|
||||
}
|
||||
}
|
||||
// Analyze: backend detects BPM + first beat, sets the grid anchor and hotcue 1.
|
||||
const runAnalyzeGrid = async () => {
|
||||
if (!track || gridBusy) return
|
||||
setGridBusy(true)
|
||||
try {
|
||||
applyCueEdit(await api.autoGrid(track.id))
|
||||
onNotify?.('success', 'Analyzed — set BPM, grid, and hotcue 1')
|
||||
} catch (e) {
|
||||
onError?.((e as Error).message)
|
||||
} finally {
|
||||
setGridBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const selectedCue = selectedSlot != null ? hotcueAt(selectedSlot) : null
|
||||
const showWaves = track && cols && waveStatus === 'ready'
|
||||
const activeLoop = loopActive && loopRegion ? loopRegion : null
|
||||
|
||||
return (
|
||||
<div className="flex h-[21rem] shrink-0 items-stretch gap-px border-b border-line bg-ink-950">
|
||||
<div className="flex h-[23rem] shrink-0 items-stretch gap-px border-b border-line bg-ink-950">
|
||||
{/* Controls */}
|
||||
<div className="flex w-72 shrink-0 flex-col gap-3 bg-ink-900 px-4 py-3">
|
||||
<div className="min-w-0">
|
||||
@@ -626,15 +769,23 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
onReset={resetGrid}
|
||||
onToggleLock={toggleLock}
|
||||
onDeleteGrid={deleteGrid}
|
||||
onAnalyze={runAnalyzeGrid}
|
||||
analyzing={gridBusy}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="mt-auto flex items-center gap-2">
|
||||
<button
|
||||
onClick={handleCue}
|
||||
onPointerDown={(e) => {
|
||||
e.preventDefault()
|
||||
e.currentTarget.setPointerCapture(e.pointerId)
|
||||
onCuePress()
|
||||
}}
|
||||
onPointerUp={onCueRelease}
|
||||
onPointerCancel={onCueRelease}
|
||||
disabled={!ready}
|
||||
className="flex h-11 items-center justify-center rounded-xl border border-line bg-ink-850 px-4 text-sm font-bold tracking-wide text-gold transition-colors hover:border-gold disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-line"
|
||||
title="Cue — set the cue point (paused) or jump back to it (playing)"
|
||||
title="Cue — set the cue point (paused), hold to preview from it, or jump back to it (playing)"
|
||||
>
|
||||
CUE
|
||||
</button>
|
||||
@@ -643,9 +794,11 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
disabled={!ready}
|
||||
className={
|
||||
'flex h-11 w-11 items-center justify-center rounded-xl transition-all active:scale-95 disabled:cursor-not-allowed disabled:opacity-40 ' +
|
||||
(playing
|
||||
? 'bg-mint text-ink-950 shadow-lg shadow-mint/20 hover:brightness-110'
|
||||
: 'border border-line bg-ink-850 text-text hover:border-accent disabled:hover:border-line')
|
||||
(previewing
|
||||
? 'bg-gold text-ink-950 shadow-lg shadow-gold/20 hover:brightness-110'
|
||||
: playing
|
||||
? 'bg-mint text-ink-950 shadow-lg shadow-mint/20 hover:brightness-110'
|
||||
: 'border border-line bg-ink-850 text-text hover:border-accent disabled:hover:border-line')
|
||||
}
|
||||
title={playing ? 'Pause' : 'Play'}
|
||||
>
|
||||
@@ -737,7 +890,8 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
<HotcueBar
|
||||
cues={cueData?.cues ?? []}
|
||||
selectedSlot={selectedSlot}
|
||||
onSlotClick={onSlotClick}
|
||||
onSlotPress={onSlotPress}
|
||||
onSlotRelease={onSlotRelease}
|
||||
/>
|
||||
<div className="flex w-28 items-center justify-center bg-ink-900 px-1">
|
||||
{selectedCue && selectedCue.type === LOOP_TYPE ? (
|
||||
@@ -758,6 +912,18 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={runAutoHotcues}
|
||||
disabled={!canAutoCue || autoBusy}
|
||||
title={
|
||||
canAutoCue
|
||||
? 'Auto-place hotcues at detected phrase boundaries (empty slots only)'
|
||||
: 'Set a beatgrid first'
|
||||
}
|
||||
className="flex w-16 items-center justify-center gap-1 bg-ink-900 text-[11px] font-semibold uppercase tracking-wider text-muted transition-colors hover:bg-ink-800 hover:text-accent disabled:opacity-30 disabled:hover:bg-ink-900 disabled:hover:text-muted"
|
||||
>
|
||||
{autoBusy ? '…' : '✨ Auto'}
|
||||
</button>
|
||||
<button
|
||||
onClick={deleteSelected}
|
||||
disabled={!selectedCue}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRef } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
useReactTable,
|
||||
type ColumnSizingState,
|
||||
type Header,
|
||||
type Row,
|
||||
type SortingState,
|
||||
type VisibilityState,
|
||||
} from '@tanstack/react-table'
|
||||
@@ -18,17 +19,24 @@ import {
|
||||
useSensors,
|
||||
type DragEndEvent,
|
||||
} from '@dnd-kit/core'
|
||||
import { restrictToHorizontalAxis } from '@dnd-kit/modifiers'
|
||||
import { restrictToHorizontalAxis, restrictToVerticalAxis, restrictToParentElement } from '@dnd-kit/modifiers'
|
||||
import {
|
||||
SortableContext,
|
||||
arrayMove,
|
||||
horizontalListSortingStrategy,
|
||||
verticalListSortingStrategy,
|
||||
useSortable,
|
||||
} from '@dnd-kit/sortable'
|
||||
import { CSS } from '@dnd-kit/utilities'
|
||||
import type { Track } from '../api'
|
||||
import { TRACK_COLUMNS } from '../lib/trackColumns'
|
||||
|
||||
const ROW_HEIGHT = 44
|
||||
// Stable reference. A controlled `state.sorting` that's a fresh `[]` each render
|
||||
// (with no `onSortingChange`) makes TanStack Table re-sync its internal state
|
||||
// every commit → infinite re-render loop. Playlists never sort, so share one array.
|
||||
const NO_SORTING: SortingState = []
|
||||
|
||||
interface Selection {
|
||||
selected: Set<string>
|
||||
onToggle: (id: string) => void
|
||||
@@ -36,23 +44,82 @@ interface Selection {
|
||||
allSelected: boolean
|
||||
}
|
||||
|
||||
interface Props {
|
||||
tracks: Track[]
|
||||
sorting: SortingState
|
||||
onSortingChange: (s: SortingState) => void
|
||||
interface CommonProps {
|
||||
columnVisibility: VisibilityState
|
||||
columnOrder: string[]
|
||||
columnSizing: ColumnSizingState
|
||||
onColumnOrderChange: (o: string[]) => void
|
||||
onColumnSizingChange: (s: ColumnSizingState) => void
|
||||
selection?: Selection
|
||||
onRowContextMenu?: (track: Track, x: number, y: number) => void
|
||||
onPlay?: (track: Track) => void
|
||||
onEditField?: (track: Track, field: keyof Track, value: string | number) => void
|
||||
activeTrackId?: string | null
|
||||
}
|
||||
|
||||
/** One draggable + resizable header cell. */
|
||||
interface Props extends CommonProps {
|
||||
tracks: Track[]
|
||||
sorting: SortingState
|
||||
onSortingChange: (s: SortingState) => void
|
||||
selection?: Selection
|
||||
}
|
||||
|
||||
interface PlaylistProps extends CommonProps {
|
||||
tracks: Track[]
|
||||
onReorder: (ids: string[]) => void
|
||||
onRemove: (id: string) => void
|
||||
/** False while a filter/search is active: reordering a filtered subset would
|
||||
* drop the hidden entries, so the drag handle goes inert. */
|
||||
canReorder: boolean
|
||||
}
|
||||
|
||||
/** The per-row play button (shared by the library grid and the playlist list).
|
||||
* Fades in on row hover; stays lit for the active deck track. */
|
||||
function PlayButton({
|
||||
track,
|
||||
isActive,
|
||||
onPlay,
|
||||
}: {
|
||||
track: Track
|
||||
isActive: boolean
|
||||
onPlay: (track: Track) => void
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onPlay(track)
|
||||
}}
|
||||
className={`flex h-6 w-6 items-center justify-center rounded-full transition-colors hover:bg-accent hover:text-ink-950 ${
|
||||
isActive ? 'text-accent opacity-100' : 'text-faint opacity-0 group-hover:opacity-100'
|
||||
}`}
|
||||
title="Play in deck"
|
||||
>
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
|
||||
<path d="M8 5.14v13.72a1 1 0 0 0 1.54.84l10.29-6.86a1 1 0 0 0 0-1.68L9.54 4.3A1 1 0 0 0 8 5.14z" />
|
||||
</svg>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** The configurable data cells for one row — identical in both views. */
|
||||
function RowCells({ row }: { row: Row<Track> }) {
|
||||
return (
|
||||
<>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<div
|
||||
key={cell.id}
|
||||
style={{ width: cell.column.getSize() }}
|
||||
className="flex shrink-0 items-center overflow-hidden px-3"
|
||||
>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** One draggable + resizable header cell. `sortable` is false in playlists,
|
||||
* where the manual order stands (the header still reorders/resizes columns). */
|
||||
function SortableHeader({ header }: { header: Header<Track, unknown> }) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||
id: header.column.id,
|
||||
@@ -95,6 +162,62 @@ function SortableHeader({ header }: { header: Header<Track, unknown> }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** Shared draggable header row (column reorder + resize). */
|
||||
function HeaderRow({
|
||||
headers,
|
||||
sensors,
|
||||
onColumnDragEnd,
|
||||
lead,
|
||||
trail,
|
||||
hasPlay,
|
||||
selection,
|
||||
}: {
|
||||
headers: Header<Track, unknown>[]
|
||||
sensors: ReturnType<typeof useSensors>
|
||||
onColumnDragEnd: (e: DragEndEvent) => void
|
||||
lead?: boolean // playlist drag-handle spacer
|
||||
trail?: boolean // playlist remove spacer
|
||||
hasPlay: boolean
|
||||
selection?: Selection
|
||||
}) {
|
||||
return (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
modifiers={[restrictToHorizontalAxis]}
|
||||
onDragEnd={onColumnDragEnd}
|
||||
>
|
||||
<div className="sticky top-0 z-10 flex border-b border-line bg-ink-850">
|
||||
{lead && <span className="w-8 shrink-0" />}
|
||||
{selection ? (
|
||||
<span className="flex w-10 shrink-0 items-center justify-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selection.allSelected}
|
||||
onChange={selection.onToggleAll}
|
||||
className="accent-accent"
|
||||
title="Select all"
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className="w-10 shrink-0" />
|
||||
)}
|
||||
{hasPlay && <span className="w-9 shrink-0" />}
|
||||
<SortableContext
|
||||
items={headers.map((h) => h.column.id)}
|
||||
strategy={horizontalListSortingStrategy}
|
||||
>
|
||||
{headers.map((header) => (
|
||||
<SortableHeader key={header.id} header={header} />
|
||||
))}
|
||||
</SortableContext>
|
||||
{trail && <span className="w-10 shrink-0" />}
|
||||
</div>
|
||||
</DndContext>
|
||||
)
|
||||
}
|
||||
|
||||
/** The virtualized library grid (All Tracks). */
|
||||
export function TrackTable({
|
||||
tracks,
|
||||
sorting,
|
||||
@@ -131,17 +254,18 @@ export function TrackTable({
|
||||
const virtualizer = useVirtualizer({
|
||||
count: rows.length,
|
||||
getScrollElement: () => parentRef.current,
|
||||
estimateSize: () => 44,
|
||||
estimateSize: () => ROW_HEIGHT,
|
||||
overscan: 12,
|
||||
})
|
||||
const virtualRows = virtualizer.getVirtualItems()
|
||||
|
||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }))
|
||||
const headers = table.getHeaderGroups()[0].headers
|
||||
const leadWidth = 40 + (onPlay ? 36 : 0)
|
||||
const hasPlay = !!onPlay
|
||||
const leadWidth = 40 + (hasPlay ? 36 : 0)
|
||||
const totalWidth = table.getTotalSize() + leadWidth
|
||||
|
||||
const onDragEnd = (e: DragEndEvent) => {
|
||||
const onColumnDragEnd = (e: DragEndEvent) => {
|
||||
const { active, over } = e
|
||||
if (!over || active.id === over.id) return
|
||||
const from = columnOrder.indexOf(active.id as string)
|
||||
@@ -152,112 +276,239 @@ export function TrackTable({
|
||||
|
||||
return (
|
||||
<div ref={parentRef} className="h-full overflow-auto">
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
modifiers={[restrictToHorizontalAxis]}
|
||||
onDragEnd={onDragEnd}
|
||||
>
|
||||
<div style={{ width: totalWidth, minWidth: '100%' }}>
|
||||
{/* Header */}
|
||||
<div className="sticky top-0 z-10 flex border-b border-line bg-ink-850">
|
||||
{selection ? (
|
||||
<span className="flex w-10 shrink-0 items-center justify-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selection.allSelected}
|
||||
onChange={selection.onToggleAll}
|
||||
className="accent-accent"
|
||||
title="Select all"
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className="w-10 shrink-0" />
|
||||
)}
|
||||
{onPlay && <span className="w-9 shrink-0" />}
|
||||
<SortableContext
|
||||
items={headers.map((h) => h.column.id)}
|
||||
strategy={horizontalListSortingStrategy}
|
||||
>
|
||||
{headers.map((header) => (
|
||||
<SortableHeader key={header.id} header={header} />
|
||||
))}
|
||||
</SortableContext>
|
||||
</div>
|
||||
|
||||
{/* Virtualized rows */}
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualRows.map((vr) => {
|
||||
const row = rows[vr.index]
|
||||
const isSelected = selection?.selected.has(row.original.id) ?? false
|
||||
const isActive = activeTrackId === row.original.id
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className={`group absolute left-0 flex items-center border-b border-ink-850 text-sm ${
|
||||
isSelected ? 'bg-accent-soft/50' : 'hover:bg-ink-850'
|
||||
}`}
|
||||
style={{
|
||||
top: 0,
|
||||
transform: `translateY(${vr.start}px)`,
|
||||
height: vr.size,
|
||||
width: '100%',
|
||||
}}
|
||||
onContextMenu={(e) => {
|
||||
if (!onRowContextMenu) return
|
||||
e.preventDefault()
|
||||
onRowContextMenu(row.original, e.clientX, e.clientY)
|
||||
}}
|
||||
>
|
||||
{selection ? (
|
||||
<span className="flex w-10 shrink-0 items-center justify-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isSelected}
|
||||
onChange={() => selection.onToggle(row.original.id)}
|
||||
className="accent-accent"
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className="w-10 shrink-0 pr-2 text-right text-xs tabular-nums text-faint">
|
||||
{vr.index + 1}
|
||||
</span>
|
||||
)}
|
||||
{onPlay && (
|
||||
<span className="flex w-9 shrink-0 items-center justify-center">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onPlay(row.original)
|
||||
}}
|
||||
className={`flex h-6 w-6 items-center justify-center rounded-full transition-colors hover:bg-accent hover:text-ink-950 ${
|
||||
isActive
|
||||
? 'text-accent opacity-100'
|
||||
: 'text-faint opacity-0 group-hover:opacity-100'
|
||||
}`}
|
||||
title="Play in deck"
|
||||
>
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
|
||||
<path d="M8 5.14v13.72a1 1 0 0 0 1.54.84l10.29-6.86a1 1 0 0 0 0-1.68L9.54 4.3A1 1 0 0 0 8 5.14z" />
|
||||
</svg>
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<div
|
||||
key={cell.id}
|
||||
style={{ width: cell.column.getSize() }}
|
||||
className="flex shrink-0 items-center overflow-hidden px-3"
|
||||
>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div style={{ width: totalWidth, minWidth: '100%' }}>
|
||||
<HeaderRow
|
||||
headers={headers}
|
||||
sensors={sensors}
|
||||
onColumnDragEnd={onColumnDragEnd}
|
||||
hasPlay={hasPlay}
|
||||
selection={selection}
|
||||
/>
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualRows.map((vr) => {
|
||||
const row = rows[vr.index]
|
||||
const isSelected = selection?.selected.has(row.original.id) ?? false
|
||||
const isActive = activeTrackId === row.original.id
|
||||
return (
|
||||
<div
|
||||
key={row.id}
|
||||
className={`group absolute left-0 flex items-center border-b border-ink-850 text-sm ${
|
||||
isSelected ? 'bg-accent-soft/50' : 'hover:bg-ink-850'
|
||||
}`}
|
||||
style={{ top: 0, transform: `translateY(${vr.start}px)`, height: vr.size, width: '100%' }}
|
||||
onContextMenu={(e) => {
|
||||
if (!onRowContextMenu) return
|
||||
e.preventDefault()
|
||||
onRowContextMenu(row.original, e.clientX, e.clientY)
|
||||
}}
|
||||
>
|
||||
{selection ? (
|
||||
<span className="flex w-10 shrink-0 items-center justify-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isSelected}
|
||||
onChange={() => selection.onToggle(row.original.id)}
|
||||
className="accent-accent"
|
||||
/>
|
||||
</span>
|
||||
) : (
|
||||
<span className="w-10 shrink-0 pr-2 text-right text-xs tabular-nums text-faint">
|
||||
{vr.index + 1}
|
||||
</span>
|
||||
)}
|
||||
{hasPlay && (
|
||||
<span className="flex w-9 shrink-0 items-center justify-center">
|
||||
{onPlay && <PlayButton track={row.original} isActive={isActive} onPlay={onPlay} />}
|
||||
</span>
|
||||
)}
|
||||
<RowCells row={row} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</DndContext>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** One reorderable playlist row — standard (non-virtualized) dnd-kit sortable,
|
||||
* in normal document flow. This is the proven-stable arrangement; the virtualizer
|
||||
* is intentionally NOT used here (its flushSync-driven measurement loops when
|
||||
* wrapped in a sortable context). */
|
||||
function PlaylistRow({
|
||||
row,
|
||||
index,
|
||||
hasPlay,
|
||||
canReorder,
|
||||
activeTrackId,
|
||||
onPlay,
|
||||
onRemove,
|
||||
onRowContextMenu,
|
||||
}: {
|
||||
row: Row<Track>
|
||||
index: number
|
||||
hasPlay: boolean
|
||||
canReorder: boolean
|
||||
activeTrackId?: string | null
|
||||
onPlay?: (track: Track) => void
|
||||
onRemove: (id: string) => void
|
||||
onRowContextMenu?: (track: Track, x: number, y: number) => void
|
||||
}) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||
id: row.original.id,
|
||||
disabled: !canReorder,
|
||||
})
|
||||
const isActive = activeTrackId === row.original.id
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={{ transform: CSS.Transform.toString(transform), transition, height: ROW_HEIGHT }}
|
||||
className={`group flex items-center border-b border-ink-850 text-sm ${
|
||||
isDragging ? 'relative z-10 bg-ink-800 shadow-lg' : 'hover:bg-ink-850'
|
||||
}`}
|
||||
onContextMenu={(e) => {
|
||||
if (!onRowContextMenu) return
|
||||
e.preventDefault()
|
||||
onRowContextMenu(row.original, e.clientX, e.clientY)
|
||||
}}
|
||||
>
|
||||
{canReorder ? (
|
||||
<button
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
title="Drag to reorder"
|
||||
className="flex w-8 shrink-0 cursor-grab items-center justify-center text-faint hover:text-text active:cursor-grabbing"
|
||||
>
|
||||
⠿
|
||||
</button>
|
||||
) : (
|
||||
<span
|
||||
title="Clear the search / filters to reorder"
|
||||
className="flex w-8 shrink-0 cursor-default items-center justify-center text-faint/25"
|
||||
>
|
||||
⠿
|
||||
</span>
|
||||
)}
|
||||
<span className="w-10 shrink-0 pr-2 text-right text-xs tabular-nums text-faint">
|
||||
{index + 1}
|
||||
</span>
|
||||
{hasPlay && (
|
||||
<span className="flex w-9 shrink-0 items-center justify-center">
|
||||
{onPlay && <PlayButton track={row.original} isActive={isActive} onPlay={onPlay} />}
|
||||
</span>
|
||||
)}
|
||||
<RowCells row={row} />
|
||||
<button
|
||||
title="Remove from playlist"
|
||||
onClick={() => onRemove(row.original.id)}
|
||||
className="flex w-10 shrink-0 items-center justify-center text-faint hover:text-pink"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The playlist view: the same columns / play button / inline editing as the
|
||||
* library, plus drag-to-reorder + remove. Non-virtualized (playlists are small),
|
||||
* which keeps it clear of the react-virtual + dnd-kit re-render loop. */
|
||||
export function PlaylistTable({
|
||||
tracks,
|
||||
columnVisibility,
|
||||
columnOrder,
|
||||
columnSizing,
|
||||
onColumnOrderChange,
|
||||
onColumnSizingChange,
|
||||
onRowContextMenu,
|
||||
onPlay,
|
||||
onEditField,
|
||||
activeTrackId,
|
||||
onReorder,
|
||||
onRemove,
|
||||
canReorder,
|
||||
}: PlaylistProps) {
|
||||
// Local manual order so a drag feels instant; re-syncs when the server data changes.
|
||||
const [items, setItems] = useState<Track[]>(tracks)
|
||||
useEffect(() => setItems(tracks), [tracks])
|
||||
|
||||
const table = useReactTable({
|
||||
data: items,
|
||||
columns: TRACK_COLUMNS,
|
||||
state: { sorting: NO_SORTING, columnVisibility, columnOrder, columnSizing },
|
||||
meta: { onEditField },
|
||||
enableSorting: false, // playlist order is manual
|
||||
onColumnSizingChange: (updater) =>
|
||||
onColumnSizingChange(typeof updater === 'function' ? updater(columnSizing) : updater),
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
enableColumnResizing: true,
|
||||
columnResizeMode: 'onChange',
|
||||
})
|
||||
|
||||
const rows = table.getRowModel().rows
|
||||
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }))
|
||||
const headers = table.getHeaderGroups()[0].headers
|
||||
const hasPlay = !!onPlay
|
||||
const leadWidth = 32 + 40 + (hasPlay ? 36 : 0)
|
||||
const totalWidth = table.getTotalSize() + leadWidth + 40
|
||||
|
||||
const onColumnDragEnd = (e: DragEndEvent) => {
|
||||
const { active, over } = e
|
||||
if (!over || active.id === over.id) return
|
||||
const from = columnOrder.indexOf(active.id as string)
|
||||
const to = columnOrder.indexOf(over.id as string)
|
||||
if (from < 0 || to < 0) return
|
||||
onColumnOrderChange(arrayMove(columnOrder, from, to))
|
||||
}
|
||||
|
||||
const onRowDragEnd = (e: DragEndEvent) => {
|
||||
const { active, over } = e
|
||||
if (!over || active.id === over.id) return
|
||||
const from = items.findIndex((t) => t.id === active.id)
|
||||
const to = items.findIndex((t) => t.id === over.id)
|
||||
if (from < 0 || to < 0) return
|
||||
const next = arrayMove(items, from, to)
|
||||
setItems(next)
|
||||
onReorder(next.map((t) => t.id))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-auto">
|
||||
<div style={{ width: totalWidth, minWidth: '100%' }}>
|
||||
<HeaderRow
|
||||
headers={headers}
|
||||
sensors={sensors}
|
||||
onColumnDragEnd={onColumnDragEnd}
|
||||
hasPlay={hasPlay}
|
||||
lead
|
||||
trail
|
||||
/>
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
modifiers={[restrictToVerticalAxis, restrictToParentElement]}
|
||||
onDragEnd={onRowDragEnd}
|
||||
>
|
||||
<SortableContext
|
||||
items={rows.map((r) => r.original.id)}
|
||||
strategy={verticalListSortingStrategy}
|
||||
>
|
||||
{rows.map((row, i) => (
|
||||
<PlaylistRow
|
||||
key={row.original.id}
|
||||
row={row}
|
||||
index={i}
|
||||
hasPlay={hasPlay}
|
||||
canReorder={canReorder}
|
||||
activeTrackId={activeTrackId}
|
||||
onPlay={onPlay}
|
||||
onRemove={onRemove}
|
||||
onRowContextMenu={onRowContextMenu}
|
||||
/>
|
||||
))}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user