mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73f7fc4282 | ||
|
|
b8b466b608 | ||
|
|
bd85d6794c | ||
|
|
ed2b72c749 | ||
|
|
f19a662bd3 | ||
|
|
41111c7c4c | ||
|
|
e8d2c66e06 | ||
|
|
75deded209 | ||
|
|
6504623aac | ||
|
|
179ea69633 | ||
|
|
38b84a9279 | ||
|
|
060cd28474 | ||
|
|
54015049d3 | ||
|
|
b130f1469e | ||
|
|
1e8c53e693 | ||
|
|
f52c19f14d | ||
|
|
c7169c8bbe | ||
|
|
986a2cee54 | ||
|
|
5ff79eb118 | ||
|
|
73b793aee6 | ||
|
|
a0dfed9a9e |
No files matched your search
@@ -0,0 +1,149 @@
|
||||
name: Build desktop apps
|
||||
|
||||
# Compiles the Konduktor desktop app (Tauri + frozen Python sidecar) for macOS
|
||||
# and Windows on every push to main, then publishes both installers as a new
|
||||
# GitHub Release under an auto-incrementing tag. Also runnable on demand.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
# A newer push to main supersedes an in-flight build.
|
||||
concurrency:
|
||||
group: build-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
# macOS runner is Apple Silicon (arm64). For an Intel build too, add a
|
||||
# macos-13 entry with triple x86_64-apple-darwin.
|
||||
- os: macos-latest
|
||||
triple: aarch64-apple-darwin
|
||||
- os: windows-latest
|
||||
triple: x86_64-pc-windows-msvc
|
||||
runs-on: ${{ matrix.os }}
|
||||
name: ${{ matrix.os }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Rust (stable + ${{ matrix.triple }})
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.triple }}
|
||||
|
||||
# Cache the Rust build of the Tauri app between runs.
|
||||
- name: Cache Rust
|
||||
uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
workspaces: frontend/src-tauri
|
||||
|
||||
- name: Set up Node 20
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Set up Python 3.12
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
# --- Step 1: freeze the FastAPI backend into a single-file sidecar ---
|
||||
# build_sidecar.* stages it as
|
||||
# frontend/src-tauri/binaries/konduktor-sidecar-<triple>[.exe]
|
||||
# which tauri.conf.json's externalBin bundles into the app.
|
||||
- name: Install backend deps
|
||||
working-directory: backend
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements.txt -r requirements-build.txt
|
||||
|
||||
- name: Build backend sidecar (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
working-directory: backend
|
||||
env:
|
||||
PY: python # build_sidecar.sh defaults to .venv/bin/python
|
||||
run: |
|
||||
chmod +x build_sidecar.sh
|
||||
./build_sidecar.sh
|
||||
|
||||
- name: Build backend sidecar (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
working-directory: backend
|
||||
shell: pwsh
|
||||
run: .\build_sidecar.ps1 # falls back to `python` when no .venv
|
||||
|
||||
# --- Step 2: build the Tauri app (its beforeBuildCommand runs the Vite build) ---
|
||||
- name: Install frontend deps
|
||||
working-directory: frontend
|
||||
run: npm ci
|
||||
|
||||
- name: Build Tauri app
|
||||
working-directory: frontend
|
||||
run: npx tauri build
|
||||
|
||||
# Stage the single installer per OS into a flat folder. Uploading one
|
||||
# directory (not multiple bundle subpaths) keeps the artifact root at
|
||||
# ./installer, so the zip holds the bare file — no nested dmg/ or nsis/
|
||||
# folder. We ship the DMG on macOS and the NSIS -setup.exe on Windows
|
||||
# (the .msi is intentionally left out).
|
||||
- name: Stage installer (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
run: |
|
||||
mkdir -p installer
|
||||
cp frontend/src-tauri/target/release/bundle/dmg/*.dmg installer/
|
||||
|
||||
- name: Stage installer (Windows)
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force installer | Out-Null
|
||||
Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe installer/
|
||||
|
||||
- name: Upload installer
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: konduktor-${{ runner.os }}
|
||||
if-no-files-found: error
|
||||
path: installer/*
|
||||
|
||||
# Gather both platforms' installers and publish them as a single new Release.
|
||||
# Runs once, after both builds succeed, so the two matrix jobs never race to
|
||||
# create the same tag/release.
|
||||
release:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # required to create the tag + release
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# App version from the single source of truth, frontend/package.json (the
|
||||
# same value Tauri names the installers from). The run number is appended
|
||||
# as a -b<N> suffix to keep each push's tag/release unique → e.g. v0.1.1-b42.
|
||||
- name: Resolve version
|
||||
id: version
|
||||
run: echo "version=$(jq -r .version frontend/package.json)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Download installers from both builds
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
|
||||
|
||||
- name: Publish release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: v${{ steps.version.outputs.version }}-b${{ github.run_number }}
|
||||
name: Konduktor v${{ steps.version.outputs.version }}-b${{ github.run_number }}
|
||||
target_commitish: ${{ github.sha }}
|
||||
generate_release_notes: true # auto changelog from commits/PRs since last release
|
||||
fail_on_unmatched_files: true
|
||||
files: artifacts/**/*
|
||||
+4
-1
@@ -18,11 +18,14 @@ frontend/dist-ssr/
|
||||
# The collection is personal, large, and irreplaceable — don't commit it.
|
||||
# Remove this if you deliberately want to version a sample .nml.
|
||||
*.nml
|
||||
# Backups Konduktor will create before any write (Phase 3+).
|
||||
# Legacy pre-git backups (superseded by version history; left ignored so any
|
||||
# old .bak files on disk stay out of git).
|
||||
*.nml.bak
|
||||
*.nml.backup
|
||||
*.nml.*.bak
|
||||
backups/
|
||||
# Version-history git repos, if a dev points KONDUKTOR_DATA_DIR inside the repo.
|
||||
history/
|
||||
|
||||
# ---- Editor / OS ----
|
||||
.vscode/
|
||||
|
||||
@@ -51,11 +51,28 @@ 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`.
|
||||
`RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`,
|
||||
`UpdateDialog` (`UpdateCheck`, mounted in `main.tsx` beside `App` so it shows
|
||||
even on the picker screen: on startup fetches the latest GitHub release and,
|
||||
if its tag's **semver part** is newer than `__APP_VERSION__` — build-number
|
||||
`-b<N>` bumps don't count — shows an update dialog with the release's
|
||||
"What's Changed" bullets; Download opens the release page in the system
|
||||
browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open`
|
||||
outside Tauri; "Skip this version" persists `skippedUpdateVersion` to
|
||||
userprefs via `/api/prefs`; all failures are silent).
|
||||
- **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it —
|
||||
transport (play/pause, CUE), two waveforms (`MainWaveform` scrolling+zoomable
|
||||
— its zoom is owned by `PrepStrip` so it survives track switches and persists,
|
||||
@@ -149,6 +166,29 @@ frontend at `http://localhost:5173`.
|
||||
- Python 3.14 note: pin dependencies loosely enough to get prebuilt wheels
|
||||
(older `pydantic-core` pins force a from-source Rust build that fails).
|
||||
|
||||
## Versioning
|
||||
|
||||
**There is ONE source of truth for the app version: the `version` field in
|
||||
[frontend/package.json](frontend/package.json).** To release a new version, bump
|
||||
that number and nothing else — everything derives from it:
|
||||
|
||||
- **Tauri / installers** — `tauri.conf.json` sets `"version": "../package.json"`,
|
||||
so the `.dmg`/`.exe` names + bundle version come from `package.json`.
|
||||
- **Backend API** — `konduktor/__init__.py` `_read_version()` reads
|
||||
`package.json` (dev: `<repo>/frontend/package.json`; frozen sidecar: bundled at
|
||||
the PyInstaller root via `sys._MEIPASS`, added in `konduktor-sidecar.spec`).
|
||||
`main.py` uses this for the FastAPI `version`. Falls back to `"0.0.0"` if not
|
||||
found (cosmetic, must never crash startup).
|
||||
- **Frontend / update check** — `vite.config.ts` bakes it in at build time as
|
||||
the `__APP_VERSION__` global (declared in `src/vite-env.d.ts`); `UpdateCheck`
|
||||
compares it against the latest GitHub release tag on startup.
|
||||
- **CI release** — `.github/workflows/build.yml` reads it with
|
||||
`jq .version frontend/package.json` and tags each push
|
||||
`v<version>-b<run_number>` (release name `Konduktor v<version>-b<run_number>`).
|
||||
The `-b<N>` suffix keeps every push's tag/release unique.
|
||||
- **NOT a source**: `src-tauri/Cargo.toml` `version` is inert Rust crate metadata
|
||||
(Tauri uses the config's `../package.json`); don't treat it as the app version.
|
||||
|
||||
## Roadmap
|
||||
|
||||
- ✅ Phase 1 — backend core + read-only API
|
||||
|
||||
@@ -158,10 +158,20 @@ The installers land in `frontend\src-tauri\target\release\bundle\` (an `.msi` an
|
||||
an NSIS `-setup.exe`). See [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the full
|
||||
walkthrough and Windows-specific notes.
|
||||
|
||||
> **Note:** builds are currently **unsigned**, so the first launch is flagged by
|
||||
> the OS — on macOS right-click → **Open** to get past Gatekeeper; on Windows
|
||||
> click **More info → Run anyway** past SmartScreen. The macOS `.dmg` is
|
||||
> Apple-Silicon (`aarch64`) only.
|
||||
> **First launch — getting past the OS security prompt.** Builds are
|
||||
> **ad-hoc signed, not notarized** (no paid Apple/Windows developer cert yet), so
|
||||
> the OS flags them the first time. This is expected — the app isn't damaged.
|
||||
>
|
||||
> - **macOS:** right-click the app → **Open** → **Open** (or System Settings →
|
||||
> Privacy & Security → **Open Anyway** after the first blocked attempt). If it
|
||||
> still refuses — common for a `.dmg` downloaded via a browser, which macOS
|
||||
> quarantines — clear the quarantine flag once from Terminal:
|
||||
> ```bash
|
||||
> xattr -cr /Applications/Konduktor.app
|
||||
> ```
|
||||
> - **Windows:** click **More info → Run anyway** past SmartScreen.
|
||||
>
|
||||
> The macOS `.dmg` is Apple-Silicon (`aarch64`) only.
|
||||
|
||||
> **Faster local builds:** `npx tauri build --debug --bundles app` skips the
|
||||
> optimizer and the installer, giving you a runnable app in seconds — handy while
|
||||
|
||||
@@ -11,6 +11,15 @@ PY="${PY:-.venv/bin/python}"
|
||||
"$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec
|
||||
echo "Built: $ROOT/dist/konduktor-sidecar"
|
||||
|
||||
# NOTE: do NOT re-codesign this binary. PyInstaller already ad-hoc signs the
|
||||
# one-file bootloader AND its packed libraries (Python.framework, etc.) with a
|
||||
# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`)
|
||||
# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework
|
||||
# fails with "different Team IDs" and the sidecar dies on launch (which makes
|
||||
# the Tauri app panic: "backend sidecar did not report a port"). The app bundle
|
||||
# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`,
|
||||
# which seals this binary without re-signing it.
|
||||
|
||||
# Stage for Tauri: the sidecar must be named with the host target triple so the
|
||||
# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.)
|
||||
if command -v rustc >/dev/null 2>&1; then
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
# - traktor-nml-utils parses/serializes via xsdata, which discovers plugins at
|
||||
# runtime → collect_submodules('xsdata')
|
||||
# - python-multipart is imported as `multipart` by starlette → hidden import
|
||||
# - dulwich (version-history backups) imports git backends dynamically →
|
||||
# collect_submodules('dulwich')
|
||||
from PyInstaller.utils.hooks import collect_submodules, collect_all
|
||||
|
||||
hiddenimports = []
|
||||
@@ -15,7 +17,7 @@ datas = []
|
||||
binaries = []
|
||||
|
||||
# Dynamically-imported subpackages.
|
||||
for pkg in ("uvicorn", "xsdata"):
|
||||
for pkg in ("uvicorn", "xsdata", "dulwich"):
|
||||
hiddenimports += collect_submodules(pkg)
|
||||
|
||||
# Native standard extras — grab modules + shared libs + any data.
|
||||
@@ -28,6 +30,11 @@ for pkg in ("uvloop", "httptools", "websockets"):
|
||||
# Imported by name, not statically discoverable.
|
||||
hiddenimports += ["multipart", "anyio"]
|
||||
|
||||
# Bundle the canonical version file so konduktor.__version__ can read it at
|
||||
# runtime from sys._MEIPASS (frontend/package.json is the single source of the
|
||||
# app version — see konduktor/__init__.py). Path is relative to this spec.
|
||||
datas += [("../frontend/package.json", ".")]
|
||||
|
||||
a = Analysis(
|
||||
["sidecar.py"],
|
||||
pathex=[],
|
||||
|
||||
@@ -1,3 +1,35 @@
|
||||
"""Konduktor — Traktor library management & track preparation."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _read_version() -> str:
|
||||
"""Return the app version — the single source of truth is
|
||||
``frontend/package.json`` (also what Tauri names the installers from).
|
||||
|
||||
- Dev / source checkout: read it from the repo, two levels up from this
|
||||
package (``<repo>/frontend/package.json``).
|
||||
- Frozen sidecar: ``package.json`` is bundled at the PyInstaller root (see
|
||||
``konduktor-sidecar.spec``), reachable via ``sys._MEIPASS``.
|
||||
|
||||
Falls back to ``"0.0.0"`` if it can't be located (the FastAPI version string
|
||||
is cosmetic, so a miss must never crash startup).
|
||||
"""
|
||||
candidates = []
|
||||
meipass = getattr(sys, "_MEIPASS", None)
|
||||
if meipass:
|
||||
candidates.append(Path(meipass) / "package.json")
|
||||
candidates.append(Path(__file__).resolve().parents[2] / "frontend" / "package.json")
|
||||
for path in candidates:
|
||||
try:
|
||||
return json.loads(path.read_text(encoding="utf-8"))["version"]
|
||||
except Exception:
|
||||
continue
|
||||
return "0.0.0"
|
||||
|
||||
|
||||
__version__ = _read_version()
|
||||
@@ -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
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Per-collection version history backed by a purely-local git repo (dulwich).
|
||||
|
||||
Replaces the old ``.bak`` copy-on-save. Every Konduktor write to a collection is
|
||||
committed to a small git repo — one per collection — living in the app-data dir
|
||||
(NOT next to the user's collection). Git's delta packing makes near-identical
|
||||
NMLs almost free, so we keep full history forever; a manual "delete all history"
|
||||
is the only pruning.
|
||||
|
||||
Design rules:
|
||||
* ALL git interaction is confined to this module.
|
||||
* EVERY public function is best-effort: it swallows its own errors (returning a
|
||||
safe empty/None value) so a history failure can never break a save or an open.
|
||||
* The tracked file is a fixed name inside each repo (``collection.nml``); the
|
||||
repo is keyed by a hash of the collection's absolute OS path (mirrors prefs'
|
||||
path-based keying). Collection identity is therefore the OS path — moving the
|
||||
collection starts a fresh history (same fragility prefs already accepts).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from dulwich import porcelain
|
||||
from dulwich.repo import Repo
|
||||
|
||||
from . import paths
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_TRACKED_NAME = "collection.nml"
|
||||
_AUTHOR = b"Konduktor <konduktor@localhost>"
|
||||
|
||||
|
||||
@dataclass
|
||||
class HistoryEntry:
|
||||
id: str # full commit sha (hex)
|
||||
timestamp: str # ISO 8601, UTC
|
||||
summary: str # first line of the commit message
|
||||
|
||||
|
||||
# ---- repo location -----------------------------------------------------------
|
||||
|
||||
def _key(nml_path: Path) -> str:
|
||||
return hashlib.sha256(str(Path(nml_path).resolve()).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def _repo_dir(nml_path: Path) -> Path:
|
||||
return paths.app_data_dir() / "history" / _key(nml_path)
|
||||
|
||||
|
||||
def _tracked_file(repo_dir: Path) -> Path:
|
||||
return repo_dir / _TRACKED_NAME
|
||||
|
||||
|
||||
def _write_meta(repo_dir: Path, nml_path: Path) -> None:
|
||||
"""A tiny sidecar recording which collection this repo belongs to (for
|
||||
debugging / a friendly display name). Best-effort."""
|
||||
try:
|
||||
meta = {"path": str(Path(nml_path).resolve()), "name": Path(nml_path).parent.name}
|
||||
(repo_dir / ".meta.json").write_text(json.dumps(meta, indent=2))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _open_or_init(nml_path: Path) -> Path:
|
||||
"""Ensure the collection's repo exists; return its directory."""
|
||||
repo_dir = _repo_dir(nml_path)
|
||||
if not (repo_dir / ".git").exists():
|
||||
repo_dir.mkdir(parents=True, exist_ok=True)
|
||||
porcelain.init(str(repo_dir))
|
||||
_write_meta(repo_dir, nml_path)
|
||||
return repo_dir
|
||||
|
||||
|
||||
def _head_blob(repo: Repo) -> bytes | None:
|
||||
"""The tracked file's bytes at HEAD, or None if the repo has no commits."""
|
||||
try:
|
||||
head = repo.head()
|
||||
except KeyError:
|
||||
return None
|
||||
commit = repo[head]
|
||||
tree = repo[commit.tree]
|
||||
_mode, blob_sha = tree[_TRACKED_NAME.encode()]
|
||||
return repo[blob_sha].data
|
||||
|
||||
|
||||
# ---- public API --------------------------------------------------------------
|
||||
|
||||
def commit(nml_path: Path, data: bytes, message: str, app_version: str) -> str | None:
|
||||
"""Commit ``data`` as the collection's newest version. Deduped: if ``data``
|
||||
is byte-identical to HEAD, no commit is made and None is returned. Returns
|
||||
the new commit sha (hex) on success, None on dedup or any failure."""
|
||||
try:
|
||||
repo_dir = _open_or_init(nml_path)
|
||||
with Repo(str(repo_dir)) as repo:
|
||||
if _head_blob(repo) == data:
|
||||
return None # nothing changed since last version
|
||||
path = _tracked_file(repo_dir)
|
||||
path.write_bytes(data)
|
||||
porcelain.add(str(repo_dir), paths=[str(path)])
|
||||
msg = f"{message}\n\nApp-Version: {app_version}".encode()
|
||||
sha = porcelain.commit(str(repo_dir), message=msg, author=_AUTHOR, committer=_AUTHOR)
|
||||
return sha.decode() if isinstance(sha, bytes) else str(sha)
|
||||
except Exception: # best-effort — history must never break a save
|
||||
log.exception("history.commit failed for %s", nml_path)
|
||||
return None
|
||||
|
||||
|
||||
def ensure_baseline(nml_path: Path) -> None:
|
||||
"""Commit the current on-disk collection as an "as I found it" baseline.
|
||||
Deduped, so re-opening an unchanged collection is a no-op. Best-effort."""
|
||||
try:
|
||||
data = Path(nml_path).read_bytes()
|
||||
except OSError:
|
||||
return
|
||||
commit(nml_path, data, "Baseline — opened collection", _app_version())
|
||||
|
||||
|
||||
def list_history(nml_path: Path) -> list[HistoryEntry]:
|
||||
"""All versions, newest first. Empty list if no history / on any failure."""
|
||||
repo_dir = _repo_dir(nml_path)
|
||||
if not (repo_dir / ".git").exists():
|
||||
return []
|
||||
try:
|
||||
entries: list[HistoryEntry] = []
|
||||
with Repo(str(repo_dir)) as repo:
|
||||
try:
|
||||
repo.head()
|
||||
except KeyError:
|
||||
return []
|
||||
for e in repo.get_walker():
|
||||
c = e.commit
|
||||
ts = datetime.fromtimestamp(c.commit_time, tz=timezone.utc).isoformat()
|
||||
summary = c.message.decode("utf-8", "replace").splitlines()[0] if c.message else ""
|
||||
entries.append(HistoryEntry(id=c.id.decode(), timestamp=ts, summary=summary))
|
||||
return entries
|
||||
except Exception:
|
||||
log.exception("history.list_history failed for %s", nml_path)
|
||||
return []
|
||||
|
||||
|
||||
def read_version(nml_path: Path, commit_id: str) -> bytes | None:
|
||||
"""The tracked collection bytes at a specific commit, or None on failure."""
|
||||
repo_dir = _repo_dir(nml_path)
|
||||
if not (repo_dir / ".git").exists():
|
||||
return None
|
||||
try:
|
||||
with Repo(str(repo_dir)) as repo:
|
||||
c = repo[commit_id.encode()]
|
||||
tree = repo[c.tree]
|
||||
_mode, blob_sha = tree[_TRACKED_NAME.encode()]
|
||||
return repo[blob_sha].data
|
||||
except Exception:
|
||||
log.exception("history.read_version failed for %s @ %s", nml_path, commit_id)
|
||||
return None
|
||||
|
||||
|
||||
def clear_history(nml_path: Path) -> None:
|
||||
"""Delete ALL version history for a collection (removes its repo). Best-effort."""
|
||||
try:
|
||||
shutil.rmtree(_repo_dir(nml_path), ignore_errors=True)
|
||||
except Exception:
|
||||
log.exception("history.clear_history failed for %s", nml_path)
|
||||
|
||||
|
||||
def _app_version() -> str:
|
||||
from . import __version__
|
||||
|
||||
return __version__
|
||||
+188
-5
@@ -13,11 +13,17 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from . import prefs
|
||||
from . import __version__
|
||||
from . import auto_hotcues as ah
|
||||
from . import history, prefs
|
||||
from .collection_service import CollectionService
|
||||
from .discovery import describe, detect_collections
|
||||
from .path_mapping import PathMapping
|
||||
from .playlist_store import PlaylistError, PlaylistStore
|
||||
from .schemas import (
|
||||
AutoGridRequest,
|
||||
AutoHotcue,
|
||||
AutoHotcuesRequest,
|
||||
CollectionCandidate,
|
||||
CollectionOptions,
|
||||
CollectionStatus,
|
||||
@@ -30,8 +36,13 @@ from .schemas import (
|
||||
FsEntry,
|
||||
FsListing,
|
||||
GridEdit,
|
||||
HistoryEntry,
|
||||
OpenCollection,
|
||||
PathMappingInfo,
|
||||
PlaylistNode,
|
||||
PrefixSuggestions,
|
||||
RemapPreview,
|
||||
RemapResult,
|
||||
RenamePlaylist,
|
||||
SaveResult,
|
||||
SetEntries,
|
||||
@@ -44,7 +55,7 @@ from .schemas import (
|
||||
TrackPage,
|
||||
)
|
||||
|
||||
app = FastAPI(title="Konduktor API", version="0.4.0")
|
||||
app = FastAPI(title="Konduktor API", version=__version__)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
@@ -78,7 +89,15 @@ class AppState:
|
||||
# only commit to the new collection if BOTH succeed.
|
||||
service = CollectionService(path)
|
||||
store = PlaylistStore(path)
|
||||
# Apply this collection's saved OS-path remapping (per-machine, keyed by
|
||||
# the collection's local path) so runtime translation is live on open.
|
||||
saved = prefs.get_path_mapping(str(path))
|
||||
if saved:
|
||||
store.set_path_mapping(PathMapping.make(saved["from"], saved["to"]))
|
||||
self.path, self.service, self.store = path, service, store
|
||||
# Version history: record an "as I found it" baseline (deduped, so
|
||||
# re-opening an unchanged collection is a no-op). Best-effort.
|
||||
history.ensure_baseline(path)
|
||||
|
||||
|
||||
STATE = AppState()
|
||||
@@ -149,6 +168,67 @@ def collection_options() -> CollectionOptions:
|
||||
return CollectionOptions(auto=auto, recent=recent)
|
||||
|
||||
|
||||
@app.get("/api/collection/path-mapping", response_model=PathMappingInfo)
|
||||
def get_path_mapping() -> PathMappingInfo:
|
||||
"""The current collection's saved OS-path remapping (blank if none)."""
|
||||
require_store()
|
||||
saved = prefs.get_path_mapping(str(STATE.path))
|
||||
if saved:
|
||||
return PathMappingInfo.model_validate({"from": saved["from"], "to": saved["to"]})
|
||||
return PathMappingInfo()
|
||||
|
||||
|
||||
@app.put("/api/collection/path-mapping", response_model=PathMappingInfo)
|
||||
def put_path_mapping(body: PathMappingInfo) -> PathMappingInfo:
|
||||
"""Set (or, with blank prefixes, clear) the current collection's remapping.
|
||||
Persists to userprefs AND updates the live store so playback/analysis
|
||||
re-resolve immediately — no reopen needed. Never touches the .nml."""
|
||||
store = require_store()
|
||||
mapping = PathMapping.make(body.from_, body.to)
|
||||
prefs.set_path_mapping(
|
||||
str(STATE.path), mapping.from_prefix or None, mapping.to_prefix or None
|
||||
)
|
||||
store.set_path_mapping(mapping)
|
||||
return PathMappingInfo.model_validate(
|
||||
{"from": mapping.from_prefix, "to": mapping.to_prefix}
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/collection/path-mapping/suggest", response_model=PrefixSuggestions)
|
||||
def suggest_path_prefix() -> PrefixSuggestions:
|
||||
"""Auto-detected `from` prefix candidates (common directory per volume),
|
||||
so the editor can prefill the stored prefix."""
|
||||
store = require_store()
|
||||
return PrefixSuggestions.model_validate(store.path_prefix_suggestions())
|
||||
|
||||
|
||||
@app.get("/api/collection/path-mapping/preview", response_model=RemapPreview)
|
||||
def preview_path_mapping(
|
||||
from_: str = Query("", alias="from"), to: str = Query("")
|
||||
) -> RemapPreview:
|
||||
"""Validate a candidate mapping before saving/committing: how many tracks
|
||||
match `from` and how many exist at `to`."""
|
||||
store = require_store()
|
||||
return RemapPreview.model_validate(store.remap_preview(PathMapping.make(from_, to)))
|
||||
|
||||
|
||||
@app.post("/api/collection/remap-paths", response_model=RemapResult)
|
||||
def remap_paths(body: PathMappingInfo) -> RemapResult:
|
||||
"""Write-back: permanently rewrite matching track LOCATIONs (and the
|
||||
playlist references that join to them) to the `to` prefix, then save (a
|
||||
version-history commit is written). Destructive and OS-specific — the UI
|
||||
warns accordingly."""
|
||||
store = require_store()
|
||||
mapping = PathMapping.make(body.from_, body.to)
|
||||
if mapping.empty:
|
||||
raise HTTPException(400, "Both a `from` and `to` prefix are required")
|
||||
count = store.remap_locations(mapping)
|
||||
if count == 0:
|
||||
return RemapResult(rewritten=0, commit=None)
|
||||
outcome = store.save()
|
||||
return RemapResult(rewritten=count, commit=outcome.commit)
|
||||
|
||||
|
||||
@app.get("/api/prefs")
|
||||
def get_prefs() -> dict:
|
||||
"""The full persisted user-preferences blob (UI layout, last collection…)."""
|
||||
@@ -426,13 +506,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)."""
|
||||
@@ -502,11 +649,47 @@ async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...))
|
||||
def save() -> SaveResult:
|
||||
store = require_store()
|
||||
if not store.dirty:
|
||||
return SaveResult(saved=False, backup=None, playlists=store.count_playlists())
|
||||
return SaveResult(saved=False, commit=None, playlists=store.count_playlists())
|
||||
outcome = store.save()
|
||||
return SaveResult(
|
||||
saved=True,
|
||||
backup=str(outcome.backup),
|
||||
commit=outcome.commit,
|
||||
playlists=store.count_playlists(),
|
||||
file_tags=[FileTagOutcome(**r.__dict__) for r in outcome.tag_results],
|
||||
)
|
||||
|
||||
|
||||
# ---- version history --------------------------------------------------
|
||||
|
||||
|
||||
@app.get("/api/history", response_model=list[HistoryEntry])
|
||||
def get_history() -> list[HistoryEntry]:
|
||||
"""All saved versions of the current collection, newest first."""
|
||||
require_store()
|
||||
return [HistoryEntry(**e.__dict__) for e in history.list_history(STATE.path)]
|
||||
|
||||
|
||||
@app.post("/api/history/{commit_id}/restore", response_model=CollectionStatus)
|
||||
def restore_version(commit_id: str) -> CollectionStatus:
|
||||
"""Restore the collection to a past version. Writes that version back as a
|
||||
NEW forward save (a fresh commit on top of history — never a rewind), then
|
||||
reloads. The user should close Traktor first (it overwrites on exit)."""
|
||||
require_store()
|
||||
data = history.read_version(STATE.path, commit_id)
|
||||
if data is None:
|
||||
raise HTTPException(404, f"Version not found: {commit_id}")
|
||||
path = STATE.path
|
||||
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||
tmp.write_bytes(data)
|
||||
tmp.replace(path)
|
||||
history.commit(path, data, f"Restored version {commit_id[:8]}", __version__)
|
||||
STATE.open(path) # rebuild read + edit models from the restored file
|
||||
return collection_status()
|
||||
|
||||
|
||||
@app.delete("/api/history")
|
||||
def clear_history() -> dict:
|
||||
"""Permanently delete ALL version history for the current collection."""
|
||||
require_store()
|
||||
history.clear_history(STATE.path)
|
||||
return {"status": "cleared"}
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Per-collection OS-path prefix remapping.
|
||||
|
||||
A Traktor collection stores absolute audio-file paths. When the same collection
|
||||
is used on another machine (a portable USB that mounts elsewhere, a relocated
|
||||
library), those paths aren't reachable. A ``PathMapping`` translates a stored
|
||||
path prefix (``from_prefix``) to a local one (``to_prefix``).
|
||||
|
||||
This module is intentionally pure (no I/O beyond ``~`` expansion) so it can be
|
||||
unit-tested and reused by both the runtime resolver (``PlaylistStore``) and the
|
||||
write-back operation. See ``file_tags.resolve_path`` for the LOCATION -> OS path
|
||||
step this composes with.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
_WIN_DRIVE = re.compile(r"^([A-Za-z]:)[\\/](.*)$")
|
||||
_MAC_VOLUME = re.compile(r"^/Volumes/([^/]+)/(.*)$")
|
||||
|
||||
|
||||
def _norm(prefix: str | None) -> str:
|
||||
"""Normalize a prefix for matching: expand ``~``, strip a trailing slash."""
|
||||
if not prefix:
|
||||
return ""
|
||||
p = os.path.expanduser(prefix.strip())
|
||||
# Strip a single trailing separator (both / and \) but keep a bare root.
|
||||
if len(p) > 1:
|
||||
p = p.rstrip("/\\")
|
||||
return p
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PathMapping:
|
||||
"""A single ``from_prefix`` -> ``to_prefix`` OS-path prefix substitution."""
|
||||
|
||||
from_prefix: str = ""
|
||||
to_prefix: str = ""
|
||||
|
||||
@classmethod
|
||||
def make(cls, from_prefix: str | None, to_prefix: str | None) -> "PathMapping":
|
||||
return cls(_norm(from_prefix), _norm(to_prefix))
|
||||
|
||||
@property
|
||||
def empty(self) -> bool:
|
||||
return not self.from_prefix or not self.to_prefix
|
||||
|
||||
def matches(self, os_path: Path) -> bool:
|
||||
"""True if ``os_path`` is at or under ``from_prefix`` (segment-aware,
|
||||
so ``/a/b`` matches ``/a/b`` and ``/a/b/c`` but not ``/a/bc``)."""
|
||||
if self.empty:
|
||||
return False
|
||||
s = str(os_path)
|
||||
if s == self.from_prefix:
|
||||
return True
|
||||
return s.startswith(self.from_prefix + os.sep) or s.startswith(self.from_prefix + "/")
|
||||
|
||||
def apply(self, os_path: Path) -> Path:
|
||||
"""Rebase ``os_path`` from ``from_prefix`` onto ``to_prefix``. Returns the
|
||||
path unchanged when it doesn't match (non-matching tracks untouched)."""
|
||||
if not self.matches(os_path):
|
||||
return os_path
|
||||
rest = str(os_path)[len(self.from_prefix):]
|
||||
# `rest` starts with a separator (or is empty when the path == from_prefix).
|
||||
return Path(self.to_prefix + rest)
|
||||
|
||||
|
||||
def common_dir_prefix(paths: list[str]) -> str:
|
||||
"""Longest directory prefix shared by all ``paths`` (segment-aware).
|
||||
|
||||
Operates on each path's parent directory, so the result is always a folder
|
||||
(never a partial filename), and degrades to ``""`` when the paths share no
|
||||
common root. Used to auto-suggest the ``from`` prefix in the remap editor.
|
||||
"""
|
||||
if not paths:
|
||||
return ""
|
||||
dirs = [p.replace("\\", "/").rsplit("/", 1)[0] for p in paths]
|
||||
common: list[str] = []
|
||||
for segs in zip(*(d.split("/") for d in dirs)):
|
||||
if len(set(segs)) == 1:
|
||||
common.append(segs[0])
|
||||
else:
|
||||
break
|
||||
return "/".join(common)
|
||||
|
||||
|
||||
def _traktor_dir(posix_body: str) -> str:
|
||||
"""Convert a POSIX directory body (leading+trailing '/', e.g. '/Music/')
|
||||
to Traktor's '/:'-segmented form ('/:Music/:')."""
|
||||
return posix_body.replace("/", "/:")
|
||||
|
||||
|
||||
def os_path_to_location(os_path: Path) -> tuple[str, str, str]:
|
||||
"""Inverse of ``file_tags.resolve_path``: build a Traktor
|
||||
``(volume, dir, file)`` from an OS path, for the platform implied by the
|
||||
path's shape. Round-trips with ``resolve_path``.
|
||||
|
||||
Used by write-back only; the produced LOCATION is valid for the OS whose
|
||||
path shape it matches (Windows drive, macOS ``/Volumes`` mount, or a POSIX
|
||||
boot path -> ``Macintosh HD``).
|
||||
"""
|
||||
# Derive the filename from the string (not Path.name) so a Windows-style
|
||||
# path is handled even when this runs on a POSIX host, and vice-versa.
|
||||
s = str(os_path)
|
||||
|
||||
m = _WIN_DRIVE.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # e.g. "E:"
|
||||
body = m.group(2).replace("\\", "/") # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
m = _MAC_VOLUME.match(s)
|
||||
if m:
|
||||
volume = m.group(1) # mounted volume name
|
||||
body = m.group(2) # "Music/x.mp3"
|
||||
name = body.rsplit("/", 1)[-1]
|
||||
dir_body = "/" + body[: len(body) - len(name)] # "/Music/"
|
||||
return volume, _traktor_dir(dir_body), name
|
||||
|
||||
# POSIX boot volume, e.g. "/Users/you/Music/x.mp3".
|
||||
name = s.rsplit("/", 1)[-1]
|
||||
dir_body = s[: len(s) - len(name)] # "/Users/you/Music/"
|
||||
return "Macintosh HD", _traktor_dir(dir_body), name
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Resolves the app's per-OS, user-writable data directory.
|
||||
|
||||
Everything Konduktor persists that is NOT part of the user's collection lives
|
||||
here: `userprefs.json` and the per-collection version-history git repos. It must
|
||||
be a real writable location — the package-relative path prefs.py used to use is
|
||||
read-only/ephemeral in a frozen PyInstaller build (`sys._MEIPASS`).
|
||||
|
||||
Resolution order:
|
||||
1. ``KONDUKTOR_DATA_DIR`` env var (tests point this at a temp dir to stay
|
||||
isolated from the real user data).
|
||||
2. platformdirs' per-OS user-data dir
|
||||
(~/Library/Application Support/Konduktor, %LOCALAPPDATA%\\Konduktor, …).
|
||||
|
||||
Best-effort: any failure to create the dir degrades to returning the path
|
||||
anyway; callers already treat all data I/O as best-effort.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import platformdirs
|
||||
|
||||
_APP_NAME = "Konduktor"
|
||||
_APP_AUTHOR = "Liquid Ice Studios"
|
||||
|
||||
|
||||
def app_data_dir() -> Path:
|
||||
"""The user-writable directory for Konduktor's persisted app data."""
|
||||
override = os.environ.get("KONDUKTOR_DATA_DIR")
|
||||
base = Path(override) if override else Path(platformdirs.user_data_dir(_APP_NAME, _APP_AUTHOR))
|
||||
try:
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
except OSError:
|
||||
pass # non-fatal — callers handle missing/unwritable data dirs
|
||||
return base
|
||||
@@ -6,7 +6,8 @@ Design goals:
|
||||
exact formatting; lxml does not),
|
||||
* surgical — the ~14 MB COLLECTION stays byte-identical (we splice only the
|
||||
<PLAYLISTS> span back into the original file bytes),
|
||||
* safe — a timestamped .bak is written before every save.
|
||||
* safe — every save is committed to the collection's version history (see
|
||||
``history.py``); the commit is additive and never alters the saved bytes.
|
||||
|
||||
We edit the parsed dataclass model in memory (create/rename/delete/set-entries),
|
||||
then on save render the full model, extract just the freshly-rendered
|
||||
@@ -17,9 +18,7 @@ Playlists are identified by their stable UUID; folders by a synthetic path id
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
import uuid as uuidlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
@@ -43,6 +42,8 @@ from traktor_nml_utils.models.collection import (
|
||||
)
|
||||
from xsdata.formats.dataclass.serializers import XmlSerializer
|
||||
|
||||
from . import __version__, history
|
||||
from .path_mapping import PathMapping
|
||||
from .schemas import PlaylistNode
|
||||
|
||||
|
||||
@@ -61,7 +62,7 @@ class FileTagResult:
|
||||
|
||||
@dataclass
|
||||
class SaveOutcome:
|
||||
backup: Path
|
||||
commit: str | None # sha of the version-history commit (None if deduped/failed)
|
||||
tag_results: list[FileTagResult]
|
||||
|
||||
|
||||
@@ -70,6 +71,8 @@ class PlaylistStore:
|
||||
self.nml_path = Path(nml_path)
|
||||
self._lock = threading.RLock()
|
||||
self.dirty = False
|
||||
# Active OS-path prefix remapping (empty = identity). Survives _load().
|
||||
self._path_mapping = PathMapping()
|
||||
self._load()
|
||||
|
||||
# ---- load ----------------------------------------------------------
|
||||
@@ -88,8 +91,15 @@ class PlaylistStore:
|
||||
self._track_edits: dict[str, set[str]] = {}
|
||||
# track_id -> (image_bytes, mime) of staged replacement cover art
|
||||
self._track_art: dict[str, tuple[bytes, str]] = {}
|
||||
# (category, detail, track_id) events this session -> commit summary.
|
||||
# track_id lets prep edits report how many distinct tracks were affected.
|
||||
self._edit_events: list[tuple[str, str | None, str | None]] = []
|
||||
self.dirty = False
|
||||
|
||||
def _note(self, category: str, detail: str | None = None, track_id: str | None = None) -> None:
|
||||
"""Record a human-meaningful edit for the next commit's summary."""
|
||||
self._edit_events.append((category, detail, track_id))
|
||||
|
||||
def _root(self) -> Nodetype:
|
||||
node = self._nml.playlists.node if self._nml.playlists else None
|
||||
if node is None:
|
||||
@@ -196,6 +206,7 @@ class PlaylistStore:
|
||||
)
|
||||
folder.subnodes.node.append(node)
|
||||
folder.subnodes.count = len(folder.subnodes.node)
|
||||
self._note("playlist-create", name)
|
||||
self.dirty = True
|
||||
return new_uuid
|
||||
|
||||
@@ -205,6 +216,7 @@ class PlaylistStore:
|
||||
if node is None:
|
||||
raise PlaylistError(f"Playlist not found: {playlist_uuid}")
|
||||
node.name = name
|
||||
self._note("playlist-rename", name)
|
||||
self.dirty = True
|
||||
|
||||
def delete_playlist(self, playlist_uuid: str) -> None:
|
||||
@@ -217,6 +229,7 @@ class PlaylistStore:
|
||||
raise PlaylistError("Cannot delete a top-level node")
|
||||
parent.subnodes.node.remove(node)
|
||||
parent.subnodes.count = len(parent.subnodes.node)
|
||||
self._note("playlist-delete", node.name)
|
||||
self.dirty = True
|
||||
|
||||
def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None:
|
||||
@@ -230,6 +243,7 @@ class PlaylistStore:
|
||||
for key, ptype in entries
|
||||
]
|
||||
pl.entries = len(pl.entry)
|
||||
self._note("playlist-entries", node.name)
|
||||
self.dirty = True
|
||||
|
||||
# ---- track metadata editing ---------------------------------------
|
||||
@@ -282,11 +296,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 +328,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,
|
||||
@@ -318,8 +339,35 @@ class PlaylistStore:
|
||||
grid=None,
|
||||
)
|
||||
)
|
||||
# "add" only when it's a genuinely new hotcue; repositioning/retyping
|
||||
# an existing slot is a "modify" (keeps the net add/remove count honest).
|
||||
self._note("hotcue", "modify" if existing is not None else "add", track_id)
|
||||
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:
|
||||
@@ -330,12 +378,16 @@ class PlaylistStore:
|
||||
if cue is None:
|
||||
raise PlaylistError(f"Hotcue {slot} is not set")
|
||||
cue.type = cue_type
|
||||
self._note("hotcue", "modify", track_id)
|
||||
self.dirty = True
|
||||
|
||||
def delete_hotcue(self, track_id: str, slot: int) -> None:
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
entry.cue_v2 = [c for c in (entry.cue_v2 or []) if c.hotcue != slot]
|
||||
before = entry.cue_v2 or []
|
||||
entry.cue_v2 = [c for c in before if c.hotcue != slot]
|
||||
if len(entry.cue_v2) != len(before): # only count an actual removal
|
||||
self._note("hotcue", "delete", track_id)
|
||||
self.dirty = True
|
||||
|
||||
# ---- beatgrid -----------------------------------------------------
|
||||
@@ -385,6 +437,7 @@ class PlaylistStore:
|
||||
grid=GridType(bpm=grid_bpm),
|
||||
)
|
||||
)
|
||||
self._note("grid", "edit", track_id)
|
||||
self.dirty = True
|
||||
|
||||
def delete_grid(self, track_id: str) -> None:
|
||||
@@ -393,12 +446,14 @@ class PlaylistStore:
|
||||
entry.cue_v2 = [
|
||||
c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is None
|
||||
]
|
||||
self._note("grid", "delete", track_id)
|
||||
self.dirty = True
|
||||
|
||||
def set_lock(self, track_id: str, locked: bool) -> None:
|
||||
with self._lock:
|
||||
entry = self._entry_or_raise(track_id)
|
||||
entry.lock = 1 if locked else None
|
||||
self._note("lock", "on" if locked else "off", track_id)
|
||||
self.dirty = True
|
||||
|
||||
# ---- cover art -----------------------------------------------------
|
||||
@@ -409,6 +464,30 @@ class PlaylistStore:
|
||||
self._track_art[track_id] = (data, mime)
|
||||
self.dirty = True
|
||||
|
||||
def set_path_mapping(self, mapping: PathMapping) -> None:
|
||||
"""Set the active OS-path prefix remapping (applied at resolve time)."""
|
||||
with self._lock:
|
||||
self._path_mapping = mapping
|
||||
|
||||
def _resolve(self, loc) -> "Path | None":
|
||||
"""Resolve a LOCATION to an OS path, applying the active path mapping.
|
||||
|
||||
The single FS chokepoint: LOCATION -> `resolve_path` -> prefix remap.
|
||||
Falls back to the un-remapped path when the remapped target doesn't
|
||||
exist, so a misconfigured mapping never makes a present file unreachable.
|
||||
"""
|
||||
from . import file_tags
|
||||
|
||||
if loc is None:
|
||||
return None
|
||||
base = file_tags.resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if self._path_mapping.empty:
|
||||
return base
|
||||
remapped = self._path_mapping.apply(base)
|
||||
if remapped == base:
|
||||
return base
|
||||
return remapped if remapped.exists() else base
|
||||
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
|
||||
"""Staged replacement if present, else the file's current embedded art."""
|
||||
from . import file_tags
|
||||
@@ -419,19 +498,117 @@ class PlaylistStore:
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None or entry.location is None:
|
||||
return None
|
||||
loc = entry.location
|
||||
return file_tags.read_cover(file_tags.resolve_path(loc.volume, loc.dir, loc.file))
|
||||
path = self._resolve(entry.location)
|
||||
return file_tags.read_cover(path) if path else None
|
||||
|
||||
def audio_path(self, track_id: str) -> "Path | None":
|
||||
"""Resolve a track's audio file to an OS path (for playback streaming)."""
|
||||
from . import file_tags
|
||||
|
||||
with self._lock:
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None or entry.location is None:
|
||||
return None
|
||||
loc = entry.location
|
||||
return file_tags.resolve_path(loc.volume, loc.dir, loc.file)
|
||||
return self._resolve(entry.location)
|
||||
|
||||
def path_prefix_suggestions(self) -> dict:
|
||||
"""Auto-suggest ``from`` prefixes by resolving every track's LOCATION and
|
||||
finding the common directory prefix per volume. Returns a ``primary``
|
||||
(the largest group's prefix) plus per-group prefixes ranked by track
|
||||
count, so the editor can prefill and offer alternatives."""
|
||||
from collections import defaultdict
|
||||
|
||||
from . import file_tags
|
||||
from .path_mapping import common_dir_prefix
|
||||
|
||||
with self._lock:
|
||||
groups: dict[str, list[str]] = defaultdict(list)
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
groups[loc.volume or ""].append(
|
||||
str(file_tags.resolve_path(loc.volume, loc.dir, loc.file))
|
||||
)
|
||||
ranked = sorted(
|
||||
(
|
||||
{"prefix": common_dir_prefix(paths), "count": len(paths)}
|
||||
for paths in groups.values()
|
||||
),
|
||||
key=lambda g: g["count"],
|
||||
reverse=True,
|
||||
)
|
||||
ranked = [g for g in ranked if g["prefix"]]
|
||||
return {"primary": ranked[0]["prefix"] if ranked else "", "groups": ranked[:5]}
|
||||
|
||||
def remap_preview(self, mapping: PathMapping) -> dict:
|
||||
"""How a mapping would affect the collection, without changing anything:
|
||||
total tracks, how many match ``from``, and how many exist at ``to``
|
||||
(plus a few samples). Powers the mapping editor's validation line."""
|
||||
from . import file_tags
|
||||
|
||||
with self._lock:
|
||||
total = matched = existing = 0
|
||||
samples: list[dict] = []
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
total += 1
|
||||
base = file_tags.resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if mapping.matches(base):
|
||||
matched += 1
|
||||
target = mapping.apply(base)
|
||||
ok = target.exists()
|
||||
if ok:
|
||||
existing += 1
|
||||
if len(samples) < 5:
|
||||
samples.append({"from": str(base), "to": str(target), "exists": ok})
|
||||
return {"total": total, "matched": matched, "existing": existing, "samples": samples}
|
||||
|
||||
def remap_locations(self, mapping: PathMapping) -> int:
|
||||
"""Permanently rewrite matching track LOCATIONs to the mapping's ``to``
|
||||
prefix — a deliberate library move (write-back).
|
||||
|
||||
Because ``track_id`` IS the LOCATION key (``volume+dir+file``), every
|
||||
playlist ``PRIMARYKEY`` that referenced a moved track is rewritten too,
|
||||
so playlists keep pointing at their tracks. Non-matching entries are
|
||||
untouched. Returns the number of tracks rewritten; the caller saves.
|
||||
"""
|
||||
from . import file_tags
|
||||
from .path_mapping import os_path_to_location
|
||||
|
||||
if mapping.empty:
|
||||
return 0
|
||||
with self._lock:
|
||||
key_remap: dict[str, str] = {}
|
||||
for e in self._nml.collection.entry:
|
||||
loc = e.location
|
||||
if not loc:
|
||||
continue
|
||||
base = file_tags.resolve_path(loc.volume, loc.dir, loc.file)
|
||||
if not mapping.matches(base):
|
||||
continue
|
||||
target = mapping.apply(base)
|
||||
volume, dir_, file = os_path_to_location(target)
|
||||
old_key = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
||||
new_key = f"{volume or ''}{dir_ or ''}{file or ''}"
|
||||
if old_key == new_key:
|
||||
continue # no-op (e.g. from == to); leave byte-identical
|
||||
loc.volume, loc.dir, loc.file = volume, dir_, file
|
||||
key_remap[old_key] = new_key
|
||||
if not key_remap:
|
||||
return 0
|
||||
# Rewrite playlist entry primary keys that referenced moved tracks.
|
||||
for node in self._iter_nodes(self._root()):
|
||||
pl = node.playlist
|
||||
if pl is None or not pl.entry:
|
||||
continue
|
||||
for entry in pl.entry:
|
||||
pk = entry.primarykey
|
||||
if pk and pk.key in key_remap:
|
||||
pk.key = key_remap[pk.key]
|
||||
self._note("remap", str(len(key_remap)))
|
||||
self.dirty = True
|
||||
return len(key_remap)
|
||||
|
||||
def _entry_field_value(self, entry: Entrytype, field: str):
|
||||
"""Read a single editable field's current value from the model, in the
|
||||
@@ -454,15 +631,106 @@ class PlaylistStore:
|
||||
# ---- persistence ---------------------------------------------------
|
||||
def save(self) -> "SaveOutcome":
|
||||
with self._lock:
|
||||
backup = self._backup()
|
||||
new_data = self._render()
|
||||
tmp = self.nml_path.with_suffix(self.nml_path.suffix + ".tmp")
|
||||
tmp.write_bytes(new_data)
|
||||
tmp.replace(self.nml_path)
|
||||
# Best-effort: sync the edited fields into each edited track's file.
|
||||
tag_results = self._sync_file_tags()
|
||||
self._load() # clears dirty + _track_edits
|
||||
return SaveOutcome(backup=backup, tag_results=tag_results)
|
||||
# Version history: commit the saved bytes (additive — never touches the
|
||||
# file we just wrote). Summary is computed before _load() clears state.
|
||||
commit = history.commit(self.nml_path, new_data, self._edit_summary(), __version__)
|
||||
self._load() # clears dirty + _track_edits + _edit_events
|
||||
return SaveOutcome(commit=commit, tag_results=tag_results)
|
||||
|
||||
def _edit_summary(self) -> str:
|
||||
"""A one-line, human-readable summary of this session's edits, used as the
|
||||
version-history commit message (e.g. "Edited 3 tracks; renamed playlist
|
||||
'House'; added 6 hotcues; edited beatgrid on 2 tracks").
|
||||
|
||||
Prep edits are collapsed to meaningful aggregates rather than raw op
|
||||
counts: hotcues report their NET change (created − removed), and beatgrid/
|
||||
lock edits report how many distinct tracks were affected — so tweaking one
|
||||
grid ten times reads as "1 track", not "10 edits"."""
|
||||
parts: list[str] = []
|
||||
|
||||
def tracks(n: int) -> str:
|
||||
return f"{n} track{'' if n == 1 else 's'}"
|
||||
|
||||
# --- track metadata + cover art (already counted per-track) ---
|
||||
n_meta = len(self._track_edits.keys() | self._track_art.keys())
|
||||
if n_meta:
|
||||
parts.append(f"edited {tracks(n_meta)}")
|
||||
|
||||
# --- playlists (name-bearing) ---
|
||||
pl_names: dict[str, list[str]] = {}
|
||||
for cat, detail, _tid in self._edit_events:
|
||||
if cat.startswith("playlist-") and detail:
|
||||
pl_names.setdefault(cat, []).append(detail)
|
||||
for cat, verb in (
|
||||
("playlist-create", "created"),
|
||||
("playlist-rename", "renamed"),
|
||||
("playlist-delete", "deleted"),
|
||||
("playlist-entries", "reordered"),
|
||||
):
|
||||
names = pl_names.get(cat, [])
|
||||
if not names:
|
||||
continue
|
||||
if len(names) <= 2:
|
||||
joined = ", ".join(f"'{n}'" for n in names)
|
||||
parts.append(f"{verb} playlist{'' if len(names) == 1 else 's'} {joined}")
|
||||
else:
|
||||
parts.append(f"{verb} {len(names)} playlists")
|
||||
|
||||
# --- hotcues: net change in count, scoped by how many tracks were touched ---
|
||||
hc_add = hc_del = 0
|
||||
hc_tracks: set[str] = set()
|
||||
grid_edit: set[str] = set()
|
||||
grid_del: set[str] = set()
|
||||
lock_on: set[str] = set()
|
||||
lock_off: set[str] = set()
|
||||
for cat, detail, tid in self._edit_events:
|
||||
if cat == "hotcue":
|
||||
if tid:
|
||||
hc_tracks.add(tid)
|
||||
if detail == "add":
|
||||
hc_add += 1
|
||||
elif detail == "delete":
|
||||
hc_del += 1
|
||||
elif cat == "grid":
|
||||
(grid_edit if detail == "edit" else grid_del).add(tid or "")
|
||||
elif cat == "lock":
|
||||
(lock_on if detail == "on" else lock_off).add(tid or "")
|
||||
|
||||
if hc_tracks:
|
||||
net = hc_add - hc_del
|
||||
scope = f" across {tracks(len(hc_tracks))}" if len(hc_tracks) > 1 else ""
|
||||
if net > 0:
|
||||
parts.append(f"added {net} hotcue{'' if net == 1 else 's'}{scope}")
|
||||
elif net < 0:
|
||||
parts.append(f"removed {-net} hotcue{'' if -net == 1 else 's'}{scope}")
|
||||
else: # net zero but there was activity (moves / retypes / add-then-delete)
|
||||
parts.append(f"adjusted hotcues{scope}")
|
||||
|
||||
# --- beatgrids & lock: per-track counts ---
|
||||
if grid_edit:
|
||||
parts.append(f"edited beatgrid on {tracks(len(grid_edit))}")
|
||||
if grid_del:
|
||||
parts.append(f"deleted beatgrid on {tracks(len(grid_del))}")
|
||||
if lock_on:
|
||||
parts.append(f"locked {tracks(len(lock_on))}")
|
||||
if lock_off:
|
||||
parts.append(f"unlocked {tracks(len(lock_off))}")
|
||||
|
||||
# --- path remap ---
|
||||
for cat, detail, _tid in self._edit_events:
|
||||
if cat == "remap" and detail:
|
||||
parts.append(f"remapped {detail} file paths")
|
||||
|
||||
if not parts:
|
||||
return "Saved changes"
|
||||
summary = "; ".join(parts)
|
||||
return summary[0].upper() + summary[1:]
|
||||
|
||||
def _sync_file_tags(self) -> list["FileTagResult"]:
|
||||
from . import file_tags
|
||||
@@ -473,8 +741,9 @@ class PlaylistStore:
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None or entry.location is None:
|
||||
continue
|
||||
loc = entry.location
|
||||
path = file_tags.resolve_path(loc.volume, loc.dir, loc.file)
|
||||
path = self._resolve(entry.location)
|
||||
if path is None:
|
||||
continue
|
||||
r = None
|
||||
if track_id in self._track_edits:
|
||||
meta = {f: self._entry_field_value(entry, f) for f in self._track_edits[track_id]}
|
||||
@@ -502,17 +771,3 @@ class PlaylistStore:
|
||||
s = restore_traktor_float_format(s, self._nml)
|
||||
s = format_traktor_layout(s)
|
||||
return s.encode("utf-8")
|
||||
|
||||
def _backup(self) -> Path:
|
||||
# Backups live in a `backups/` folder next to the collection, not beside
|
||||
# the file itself (keeps the collection's directory clean).
|
||||
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
|
||||
backup_dir = self.nml_path.parent / "backups"
|
||||
backup_dir.mkdir(exist_ok=True)
|
||||
backup = backup_dir / f"{self.nml_path.name}.{stamp}.bak"
|
||||
n = 1
|
||||
while backup.exists():
|
||||
backup = backup_dir / f"{self.nml_path.name}.{stamp}-{n}.bak"
|
||||
n += 1
|
||||
shutil.copy2(self.nml_path, backup)
|
||||
return backup
|
||||
@@ -1,20 +1,35 @@
|
||||
"""Tiny persisted user-preferences store.
|
||||
|
||||
Kept as a self-contained JSON file that travels with the app (resolved relative
|
||||
to this package, not a per-OS config dir) so it works the same on every platform
|
||||
and when the app is moved. Best-effort: any I/O error degrades to "no prefs".
|
||||
A self-contained JSON file in the app's per-OS user-writable data dir (see
|
||||
``paths.app_data_dir``) so it survives a frozen/packaged build and works the same
|
||||
on every platform. Best-effort: any I/O error degrades to "no prefs".
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
# backend/userprefs.json — one level up from the package (konduktor/).
|
||||
_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json"
|
||||
from . import paths
|
||||
|
||||
# userprefs.json in the app-data dir. Older versions kept it package-relative
|
||||
# (backend/userprefs.json); _migrate_legacy() copies that in once on first use.
|
||||
_PREFS_PATH = paths.app_data_dir() / "userprefs.json"
|
||||
_LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json"
|
||||
|
||||
|
||||
def _migrate_legacy() -> None:
|
||||
"""One-time: if the new file is absent but a legacy package-relative one
|
||||
exists, copy it into the app-data dir. Best-effort."""
|
||||
try:
|
||||
if not _PREFS_PATH.exists() and _LEGACY_PREFS_PATH.exists():
|
||||
_PREFS_PATH.write_bytes(_LEGACY_PREFS_PATH.read_bytes())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def load_prefs() -> dict:
|
||||
try:
|
||||
_migrate_legacy()
|
||||
data = json.loads(_PREFS_PATH.read_text())
|
||||
return data if isinstance(data, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
@@ -37,6 +52,35 @@ def update_prefs(patch: dict) -> dict:
|
||||
return prefs
|
||||
|
||||
|
||||
def get_path_mapping(collection_path: str) -> dict | None:
|
||||
"""The saved ``{from, to}`` OS-path remapping for a collection, or None.
|
||||
|
||||
Keyed by the collection's current OS path (the mapping is per-machine data,
|
||||
so the local path is a natural, machine-specific key)."""
|
||||
mappings = load_prefs().get("path_mappings")
|
||||
if isinstance(mappings, dict):
|
||||
m = mappings.get(collection_path)
|
||||
if isinstance(m, dict):
|
||||
return {"from": m.get("from") or "", "to": m.get("to") or ""}
|
||||
return None
|
||||
|
||||
|
||||
def set_path_mapping(
|
||||
collection_path: str, from_prefix: str | None, to_prefix: str | None
|
||||
) -> None:
|
||||
"""Persist (or, when either prefix is blank, clear) a collection's mapping."""
|
||||
prefs = load_prefs()
|
||||
mappings = prefs.get("path_mappings")
|
||||
if not isinstance(mappings, dict):
|
||||
mappings = {}
|
||||
if from_prefix and to_prefix:
|
||||
mappings[collection_path] = {"from": from_prefix, "to": to_prefix}
|
||||
else:
|
||||
mappings.pop(collection_path, None)
|
||||
prefs["path_mappings"] = mappings
|
||||
save_prefs(prefs)
|
||||
|
||||
|
||||
def get_last_collection() -> str | None:
|
||||
val = load_prefs().get("last_collection")
|
||||
return val if isinstance(val, str) else None
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""API response models (Pydantic)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class Track(BaseModel):
|
||||
@@ -114,11 +114,17 @@ class FileTagOutcome(BaseModel):
|
||||
|
||||
class SaveResult(BaseModel):
|
||||
saved: bool
|
||||
backup: str | None = None
|
||||
commit: str | None = None # sha of the version-history commit (None if deduped)
|
||||
playlists: int
|
||||
file_tags: list[FileTagOutcome] = []
|
||||
|
||||
|
||||
class HistoryEntry(BaseModel):
|
||||
id: str # commit sha
|
||||
timestamp: str # ISO 8601, UTC
|
||||
summary: str # human-readable edit summary
|
||||
|
||||
|
||||
class CuePoint(BaseModel):
|
||||
name: str | None = None
|
||||
type: int # Traktor: 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop
|
||||
@@ -152,6 +158,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):
|
||||
@@ -203,3 +227,45 @@ class FsListing(BaseModel):
|
||||
home: str
|
||||
dirs: list[FsEntry]
|
||||
files: list[FsEntry] # .nml files only
|
||||
|
||||
|
||||
# ---- path remapping ----
|
||||
# `from` is a Python keyword, so the field is `from_` with a `from` alias
|
||||
# (populate_by_name lets it be set either way; responses serialize as "from").
|
||||
|
||||
|
||||
class PathMappingInfo(BaseModel):
|
||||
"""A per-collection OS-path prefix remapping (blank prefixes = no mapping)."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
from_: str = Field(default="", alias="from")
|
||||
to: str = ""
|
||||
|
||||
|
||||
class RemapSample(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
from_: str = Field(alias="from")
|
||||
to: str
|
||||
exists: bool
|
||||
|
||||
|
||||
class RemapPreview(BaseModel):
|
||||
total: int # tracks with a resolvable location
|
||||
matched: int # how many match the `from` prefix
|
||||
existing: int # of matched, how many exist at the `to` target
|
||||
samples: list[RemapSample] = []
|
||||
|
||||
|
||||
class RemapResult(BaseModel):
|
||||
rewritten: int # tracks whose LOCATION was rewritten
|
||||
commit: str | None = None # sha of the version-history commit for the rewrite
|
||||
|
||||
|
||||
class PrefixGroup(BaseModel):
|
||||
prefix: str # common directory prefix of a group of tracks
|
||||
count: int # tracks sharing it
|
||||
|
||||
|
||||
class PrefixSuggestions(BaseModel):
|
||||
primary: str # best guess for the `from` prefix (largest group)
|
||||
groups: list[PrefixGroup] = [] # alternatives, ranked by count
|
||||
@@ -5,6 +5,15 @@ 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
|
||||
# Version-history backups: a self-contained git impl (no system git needed;
|
||||
# ships prebuilt py3.14 wheels, no from-source build) + a per-OS user-writable
|
||||
# app-data dir. Both bundle cleanly into the frozen sidecar.
|
||||
dulwich>=0.22
|
||||
platformdirs>=4.0
|
||||
# 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
|
||||
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
|
||||
source .venv/bin/activate
|
||||
|
||||
fail=0
|
||||
for t in test_save_fidelity.py test_phase3.py; do
|
||||
for t in test_save_fidelity.py test_phase3.py test_history.py; do
|
||||
echo "──────────────────────────────────────────"
|
||||
echo "▶ $t"
|
||||
echo "──────────────────────────────────────────"
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Version-history tests (git-backed backups replacing the old .bak scheme).
|
||||
|
||||
Runs against a COPY of the collection (never the original), with an isolated
|
||||
throwaway app-data dir. Verifies:
|
||||
* opening a collection records a baseline commit
|
||||
* a save adds a commit with a non-empty edit summary
|
||||
* a byte-identical save is deduped (no new commit)
|
||||
* list_history is newest-first
|
||||
* restoring an earlier version round-trips the .nml bytes AND adds a
|
||||
"Restored …" commit (a forward save, not a rewind)
|
||||
* clear_history removes the repo
|
||||
* no .bak files are left next to the collection
|
||||
|
||||
Run: `python test_history.py` in the backend venv (see run_tests.sh).
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
work_dir = Path(tempfile.mkdtemp(prefix="konduktor-history-"))
|
||||
WORK = work_dir / "collection.nml"
|
||||
shutil.copy2(REAL, WORK)
|
||||
|
||||
os.environ["KONDUKTOR_NML"] = str(WORK)
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = str(work_dir / "appdata")
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
from konduktor import history, main # noqa: E402
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
failed = True
|
||||
|
||||
|
||||
client = TestClient(main.app)
|
||||
|
||||
|
||||
def first_playlist(nodes):
|
||||
for n in nodes:
|
||||
if n["type"] == "PLAYLIST":
|
||||
return n
|
||||
if n.get("children"):
|
||||
found = first_playlist(n["children"])
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
|
||||
print("== baseline on open ==")
|
||||
hist = client.get("/api/history").json()
|
||||
check("baseline commit exists", len(hist) == 1)
|
||||
check("baseline summary set", hist and "Baseline" in hist[0]["summary"])
|
||||
|
||||
original_bytes = WORK.read_bytes()
|
||||
|
||||
print("== save records a commit ==")
|
||||
pl = first_playlist(client.get("/api/playlists").json())
|
||||
new_name = pl["name"] + " ✎"
|
||||
r = client.patch(f"/api/playlists/{pl['id']}", json={"name": new_name})
|
||||
check("rename ok", r.status_code == 200)
|
||||
res = client.post("/api/save").json()
|
||||
check("save reports a commit", bool(res["commit"]))
|
||||
hist = client.get("/api/history").json()
|
||||
check("history grew to 2", len(hist) == 2)
|
||||
check("newest is the rename", hist and new_name in hist[0]["summary"])
|
||||
check("newest-first ordering", "Baseline" in hist[-1]["summary"])
|
||||
|
||||
print("== dedup: byte-identical save makes no commit ==")
|
||||
# Force a save with no real change: rename back and forth nets a re-render of the
|
||||
# same content is not guaranteed; instead call history.commit directly with HEAD.
|
||||
head_bytes = WORK.read_bytes()
|
||||
before = len(client.get("/api/history").json())
|
||||
dup = history.commit(WORK, head_bytes, "should be deduped", "test")
|
||||
after = len(client.get("/api/history").json())
|
||||
check("dedup returns None", dup is None)
|
||||
check("dedup adds no commit", after == before)
|
||||
|
||||
print("== restore round-trips bytes + adds a forward commit ==")
|
||||
hist = client.get("/api/history").json()
|
||||
baseline_id = hist[-1]["id"]
|
||||
count_before = len(hist)
|
||||
rr = client.post(f"/api/history/{baseline_id}/restore")
|
||||
check("restore ok", rr.status_code == 200)
|
||||
check("restored bytes == original", WORK.read_bytes() == original_bytes)
|
||||
hist = client.get("/api/history").json()
|
||||
check("restore added a commit", len(hist) == count_before + 1)
|
||||
check("restore commit labelled", hist and "Restored" in hist[0]["summary"])
|
||||
|
||||
print("== read_version returns the right blob ==")
|
||||
check("baseline blob == original", history.read_version(WORK, baseline_id) == original_bytes)
|
||||
|
||||
print("== no .bak litter ==")
|
||||
check("no .bak files next to collection", not list(work_dir.glob("*.bak")))
|
||||
check("no backups/ dir next to collection", not (work_dir / "backups").exists())
|
||||
|
||||
print("== clear_history removes the repo ==")
|
||||
cr = client.delete("/api/history")
|
||||
check("clear ok", cr.status_code == 200)
|
||||
check("history empty after clear", client.get("/api/history").json() == [])
|
||||
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Runs against a COPY of the collection (never the original). Verifies:
|
||||
* create / add-tracks / reorder / rename / delete all work
|
||||
* save creates a backup and produces a Traktor-parseable file
|
||||
* save records a version-history commit and produces a Traktor-parseable file
|
||||
* the COLLECTION section is byte-identical after save (truly surgical)
|
||||
* changes survive a reload
|
||||
"""
|
||||
@@ -26,6 +26,8 @@ shutil.copy2(REAL, WORK)
|
||||
REAL_STAT = (REAL.stat().st_size, REAL.stat().st_mtime)
|
||||
|
||||
os.environ["KONDUKTOR_NML"] = str(WORK)
|
||||
# Isolate version history + prefs to a throwaway dir (never the real app data).
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = str(work_dir / "appdata")
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
from traktor_nml_utils import TraktorCollection # noqa: E402
|
||||
@@ -79,9 +81,11 @@ check("state is dirty before save", st["dirty"] is True)
|
||||
print("== save ==")
|
||||
res = client.post("/api/save").json()
|
||||
check("saved", res["saved"] is True)
|
||||
backup = Path(res["backup"])
|
||||
check("backup file exists", backup.exists())
|
||||
check("backup matches original size", backup.stat().st_size == REAL.stat().st_size)
|
||||
check("commit recorded", bool(res["commit"]))
|
||||
hist = client.get("/api/history").json()
|
||||
check("history has baseline + this save", len(hist) >= 2)
|
||||
check("newest history summary non-empty", bool(hist[0]["summary"]))
|
||||
check("no .bak litter next to collection", not list(work_dir.glob("*.bak")))
|
||||
st = client.get("/api/state").json()
|
||||
check("state clean after save", st["dirty"] is False)
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ two invariants against a COPY of the real collection:
|
||||
|
||||
Run: `python test_save_fidelity.py` in the backend venv (see run_tests.sh).
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -23,6 +24,10 @@ from pathlib import Path
|
||||
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
# Isolate version-history commits (triggered by every save()) to a throwaway dir
|
||||
# so the tests never touch the real app-data dir. Set before importing konduktor.
|
||||
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fidelity-appdata-")
|
||||
|
||||
REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
|
||||
from konduktor.collection_service import CollectionService # noqa: E402
|
||||
@@ -292,5 +297,225 @@ 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) == [])
|
||||
|
||||
# ---- Invariant H: path write-back is localized + round-trips -----------
|
||||
print("== H. remap_locations rewrites LOCATIONs (+ playlist keys), localized, round-trips ==")
|
||||
from collections import Counter # noqa: E402
|
||||
|
||||
from konduktor.file_tags import resolve_path # noqa: E402
|
||||
from konduktor.path_mapping import PathMapping, os_path_to_location # noqa: E402
|
||||
from traktor_nml_utils import TraktorCollection # noqa: E402
|
||||
|
||||
|
||||
def _key(loc):
|
||||
return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
|
||||
|
||||
|
||||
def _entry_span_by_file(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
|
||||
|
||||
|
||||
# H1: a track NOT in any playlist -> only its own <ENTRY> changes; revert round-trips.
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
original = work.read_bytes()
|
||||
|
||||
store = PlaylistStore(work)
|
||||
pl_keys = {
|
||||
k
|
||||
for n in store._iter_nodes(store._root())
|
||||
if n.playlist
|
||||
for k in store._entry_keys_of(n.playlist)
|
||||
}
|
||||
file_counts = Counter(
|
||||
e.location.file for e in store._nml.collection.entry if e.location and e.location.file
|
||||
)
|
||||
target = next(
|
||||
e
|
||||
for e in store._nml.collection.entry
|
||||
if e.location
|
||||
and _key(e.location) not in pl_keys
|
||||
and file_counts[e.location.file] == 1 # unique filename → clean span masking
|
||||
)
|
||||
loc = target.location
|
||||
old_file = loc.file
|
||||
from_prefix = str(resolve_path(loc.volume, loc.dir, loc.file))
|
||||
to_prefix = "/Volumes/KONDUKTOR_TEST_H1/remapped__unique__one.mp3"
|
||||
|
||||
n = store.remap_locations(PathMapping.make(from_prefix, to_prefix))
|
||||
store.save()
|
||||
edited = work.read_bytes()
|
||||
|
||||
check("H1: exactly one track rewritten", n == 1, f"got {n}")
|
||||
check("H1: file actually changed", original != edited)
|
||||
|
||||
os_, oe = _entry_span_by_file(original, old_file)
|
||||
es_, ee = _entry_span_by_file(edited, "remapped__unique__one.mp3")
|
||||
check(
|
||||
"H1: everything outside the moved ENTRY is byte-identical",
|
||||
original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:],
|
||||
)
|
||||
|
||||
reparsed = TraktorCollection(path=work)
|
||||
moved = next(
|
||||
e
|
||||
for e in reparsed.nml.collection.entry
|
||||
if e.location and e.location.file == "remapped__unique__one.mp3"
|
||||
)
|
||||
check("H1: moved ENTRY has the new VOLUME", moved.location.volume == "KONDUKTOR_TEST_H1")
|
||||
|
||||
# Reverting (to -> from) round-trips to the original bytes exactly.
|
||||
store2 = PlaylistStore(work)
|
||||
store2.remap_locations(PathMapping.make(to_prefix, from_prefix))
|
||||
store2.save()
|
||||
check("H1: revert round-trips to original bytes", work.read_bytes() == original)
|
||||
|
||||
# H2: a track that IS in a playlist -> its PRIMARYKEY is rewritten too.
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
|
||||
store = PlaylistStore(work)
|
||||
# A collection entry whose key appears in at least one playlist.
|
||||
pl_keys = {
|
||||
k
|
||||
for node in store._iter_nodes(store._root())
|
||||
if node.playlist
|
||||
for k in store._entry_keys_of(node.playlist)
|
||||
}
|
||||
target = next(
|
||||
e for e in store._nml.collection.entry if e.location and _key(e.location) in pl_keys
|
||||
)
|
||||
loc = target.location
|
||||
old_key = _key(loc)
|
||||
from_prefix = str(resolve_path(loc.volume, loc.dir, loc.file))
|
||||
to_prefix = "/Volumes/KONDUKTOR_TEST_H2/remapped__playlist__one.mp3"
|
||||
new_key = "".join(os_path_to_location(Path(to_prefix)))
|
||||
|
||||
n = store.remap_locations(PathMapping.make(from_prefix, to_prefix))
|
||||
store.save()
|
||||
|
||||
check("H2: at least one track rewritten", n >= 1)
|
||||
|
||||
reparsed = TraktorCollection(path=work)
|
||||
moved = next(
|
||||
(
|
||||
e
|
||||
for e in reparsed.nml.collection.entry
|
||||
if e.location and e.location.file == "remapped__playlist__one.mp3"
|
||||
),
|
||||
None,
|
||||
)
|
||||
check("H2: collection ENTRY location rewritten", moved is not None)
|
||||
|
||||
store3 = PlaylistStore(work)
|
||||
all_pl_keys = {
|
||||
k
|
||||
for node in store3._iter_nodes(store3._root())
|
||||
if node.playlist
|
||||
for k in store3._entry_keys_of(node.playlist)
|
||||
}
|
||||
check("H2: old playlist PRIMARYKEY gone", old_key not in all_pl_keys)
|
||||
check("H2: new playlist PRIMARYKEY present", new_key in all_pl_keys)
|
||||
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
Generated
+12
-3
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.0.0",
|
||||
"version": "0.1.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "frontend",
|
||||
"version": "0.0.0",
|
||||
"version": "0.1.1",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/modifiers": "^9.0.0",
|
||||
@@ -15,6 +15,7 @@
|
||||
"@tanstack/react-query": "^5.101.2",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@tanstack/react-virtual": "^3.14.5",
|
||||
"@tauri-apps/plugin-shell": "^2.3.5",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7"
|
||||
},
|
||||
@@ -1229,7 +1230,6 @@
|
||||
"version": "2.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.11.1.tgz",
|
||||
"integrity": "sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
@@ -1468,6 +1468,15 @@
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/plugin-shell": {
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-shell/-/plugin-shell-2.3.5.tgz",
|
||||
"integrity": "sha512-jewtULhiQ7lI7+owCKAjc8tYLJr92U16bPOeAa472LHJdgaibLP83NcfAF2e+wkEcA53FxKQAZ7byDzs2eeizg==",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.10.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@tybys/wasm-util": {
|
||||
"version": "0.10.3",
|
||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"version": "0.1.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -17,6 +17,7 @@
|
||||
"@tanstack/react-query": "^5.101.2",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@tanstack/react-virtual": "^3.14.5",
|
||||
"@tauri-apps/plugin-shell": "^2.3.5",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7"
|
||||
},
|
||||
|
||||
Generated
+1
-1
@@ -77,7 +77,7 @@ checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"
|
||||
|
||||
[[package]]
|
||||
name = "app"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
[package]
|
||||
name = "app"
|
||||
version = "0.1.0"
|
||||
# Rust crate metadata only — NOT the app version. The bundled app version comes
|
||||
# from frontend/package.json (see tauri.conf.json `"version": "../package.json"`),
|
||||
# so this value is inert for the installer/bundle and needn't be kept in sync.
|
||||
version = "0.1.1"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
license = ""
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"main"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default"
|
||||
"core:default",
|
||||
"shell:allow-open"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!--
|
||||
The backend is a PyInstaller one-file binary: at launch it extracts its
|
||||
bundled Python.framework to a temp dir and dlopen()s it. Tauri signs every
|
||||
nested binary with the hardened runtime (adhoc,runtime), which enforces
|
||||
library validation — and the extracted framework has a different Team ID
|
||||
than the ad-hoc-signed bootloader, so it's rejected ("different Team IDs")
|
||||
and the sidecar dies on launch. Disabling library validation lets it load.
|
||||
-->
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
|
||||
"productName": "Konduktor",
|
||||
"version": "0.1.0",
|
||||
"version": "../package.json",
|
||||
"identifier": "com.liquidicestudios.konduktor",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
@@ -27,6 +27,10 @@
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"macOS": {
|
||||
"signingIdentity": "-",
|
||||
"entitlements": "entitlements.plist"
|
||||
},
|
||||
"android": {
|
||||
"debugApplicationIdSuffix": ".debug"
|
||||
}
|
||||
|
||||
+98
-17
@@ -8,14 +8,15 @@ 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'
|
||||
import { CollectionPicker } from './components/CollectionPicker'
|
||||
import { ContextMenu } from './components/ContextMenu'
|
||||
import { EditTagsDialog } from './components/EditTagsDialog'
|
||||
import { PathMappingDialog } from './components/PathMappingDialog'
|
||||
import { HistoryPanel } from './components/HistoryPanel'
|
||||
import { PrepStrip } from './components/PrepStrip'
|
||||
|
||||
function applyFilters(tracks: Track[], f: Filters): Track[] {
|
||||
@@ -48,6 +49,8 @@ export default function App() {
|
||||
const [forcePicker, setForcePicker] = useState(false)
|
||||
const [menu, setMenu] = useState<{ track: Track; x: number; y: number } | null>(null)
|
||||
const [editing, setEditing] = useState<Track | null>(null)
|
||||
const [showPaths, setShowPaths] = useState(false)
|
||||
const [showHistory, setShowHistory] = useState(false)
|
||||
const [prepTrack, setPrepTrack] = useState<Track | null>(null)
|
||||
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
|
||||
|
||||
@@ -153,11 +156,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)
|
||||
@@ -224,28 +262,50 @@ export default function App() {
|
||||
onError={onError}
|
||||
/>
|
||||
)}
|
||||
{showPaths && (
|
||||
<PathMappingDialog
|
||||
onClose={() => setShowPaths(false)}
|
||||
onNotify={notify}
|
||||
onError={onError}
|
||||
/>
|
||||
)}
|
||||
{showHistory && (
|
||||
<HistoryPanel
|
||||
onClose={() => setShowHistory(false)}
|
||||
onNotify={notify}
|
||||
onError={onError}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 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} />
|
||||
<Sidebar
|
||||
source={source}
|
||||
onSelect={selectSource}
|
||||
onError={onError}
|
||||
onOpenHistory={() => setShowHistory(true)}
|
||||
/>
|
||||
|
||||
<main className="relative flex min-w-0 flex-1 flex-col">
|
||||
{isAll ? (
|
||||
{/* Search / filters / column settings — always visible. */}
|
||||
<Toolbar
|
||||
filters={filters}
|
||||
onChange={setFilters}
|
||||
columnVisibility={columnVisibility}
|
||||
onColumnVisibilityChange={setColumnVisibility}
|
||||
onResetColumns={resetColumns}
|
||||
onOpenPathMapping={() => setShowPaths(true)}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center gap-3 border-b border-line bg-ink-900 px-4 py-3">
|
||||
{!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 +341,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}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
+74
-2
@@ -154,10 +154,44 @@ export interface FsListing {
|
||||
|
||||
export interface SaveResult {
|
||||
saved: boolean
|
||||
backup: string | null
|
||||
commit: string | null
|
||||
playlists: number
|
||||
}
|
||||
|
||||
export interface HistoryEntry {
|
||||
id: string
|
||||
timestamp: string
|
||||
summary: string
|
||||
}
|
||||
|
||||
export interface PathMapping {
|
||||
from: string
|
||||
to: string
|
||||
}
|
||||
|
||||
export interface RemapSample {
|
||||
from: string
|
||||
to: string
|
||||
exists: boolean
|
||||
}
|
||||
|
||||
export interface RemapPreview {
|
||||
total: number
|
||||
matched: number
|
||||
existing: number
|
||||
samples: RemapSample[]
|
||||
}
|
||||
|
||||
export interface RemapResult {
|
||||
rewritten: number
|
||||
commit: string | null
|
||||
}
|
||||
|
||||
export interface PrefixSuggestions {
|
||||
primary: string
|
||||
groups: { prefix: string; count: number }[]
|
||||
}
|
||||
|
||||
// API origin. In the packaged desktop app the frontend is served from
|
||||
// tauri://localhost, so it can't use relative /api paths — the Tauri shell
|
||||
// injects window.__KONDUKTOR_API__ (the sidecar's http://127.0.0.1:<port>)
|
||||
@@ -211,6 +245,20 @@ export const api = {
|
||||
listDir: (path?: string) =>
|
||||
getJSON<FsListing>(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`),
|
||||
|
||||
// ---- path remapping (per-collection OS-path prefix translation) ----
|
||||
getPathMapping: () => getJSON<PathMapping>('/api/collection/path-mapping'),
|
||||
suggestPrefix: () =>
|
||||
getJSON<PrefixSuggestions>('/api/collection/path-mapping/suggest'),
|
||||
putPathMapping: (m: PathMapping) =>
|
||||
send<PathMapping>('PUT', '/api/collection/path-mapping', m),
|
||||
previewRemap: (from: string, to: string) =>
|
||||
getJSON<RemapPreview>(
|
||||
`/api/collection/path-mapping/preview?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`,
|
||||
),
|
||||
// Write-back: permanently rewrite matching LOCATIONs in the .nml (committed to history).
|
||||
remapPaths: (from: string, to: string) =>
|
||||
send<RemapResult>('POST', '/api/collection/remap-paths', { from, to }),
|
||||
|
||||
stats: () => getJSON<Stats>('/api/stats'),
|
||||
facets: () => getJSON<Facets>('/api/facets'),
|
||||
playlists: () => getJSON<PlaylistNode[]>('/api/playlists'),
|
||||
@@ -241,6 +289,13 @@ export const api = {
|
||||
patchPrefs: (patch: Record<string, unknown>) =>
|
||||
send<Record<string, unknown>>('PATCH', '/api/prefs', patch),
|
||||
save: () => send<SaveResult>('POST', '/api/save'),
|
||||
|
||||
// ---- version history ----
|
||||
history: () => getJSON<HistoryEntry[]>('/api/history'),
|
||||
restoreVersion: (id: string) =>
|
||||
send<CollectionStatus>('POST', `/api/history/${id}/restore`),
|
||||
clearHistory: () => send<{ status: string }>('DELETE', '/api/history'),
|
||||
|
||||
editTrack: (trackId: string, fields: Record<string, string | number | null>) =>
|
||||
send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }),
|
||||
artUrl: (trackId: string) =>
|
||||
@@ -249,14 +304,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) =>
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/** Jump-size cycle, in beats. Fractional sizes allow fine micro-nudging. */
|
||||
export const BEAT_JUMP_SIZES = [0.25, 0.5, 1, 2, 4, 8, 16, 32]
|
||||
|
||||
interface Props {
|
||||
/** Current jump size (one of BEAT_JUMP_SIZES). */
|
||||
beats: number
|
||||
/** Step the jump size down (-1) / up (+1) through BEAT_JUMP_SIZES. */
|
||||
onStep: (dir: -1 | 1) => void
|
||||
/** Jump the playhead back (-1) / forward (+1) by `beats`. */
|
||||
onJump: (dir: -1 | 1) => void
|
||||
/** Disabled when the loaded track has no beatgrid. */
|
||||
disabled: boolean
|
||||
}
|
||||
|
||||
const BTN =
|
||||
'flex h-7 w-7 shrink-0 items-center justify-center rounded border border-line bg-ink-850 ' +
|
||||
'text-xs font-semibold text-text transition-colors hover:border-accent disabled:opacity-30 ' +
|
||||
'disabled:hover:border-line'
|
||||
|
||||
/** Beats-only readout: 0.25 → "1/4", 0.5 → "1/2", else the integer. */
|
||||
function sizeLabel(beats: number): string {
|
||||
if (beats === 0.25) return '1/4'
|
||||
if (beats === 0.5) return '1/2'
|
||||
return String(beats)
|
||||
}
|
||||
|
||||
/**
|
||||
* Beat-jump control cluster (Traktor/Serato equivalent): step the jump size,
|
||||
* then jump the playhead forward/back by that many beats — phase-preserving,
|
||||
* playback-only. Presentational + controlled; PrepStrip owns the size state and
|
||||
* performs the actual seek. Disabled wholesale when the track is ungridded.
|
||||
*/
|
||||
export function BeatJumpControls({ beats, onStep, onJump, disabled }: Props) {
|
||||
const atMin = beats <= BEAT_JUMP_SIZES[0]
|
||||
const atMax = beats >= BEAT_JUMP_SIZES[BEAT_JUMP_SIZES.length - 1]
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="mr-0.5 text-[10px] font-semibold uppercase tracking-wider text-faint">
|
||||
Jump
|
||||
</span>
|
||||
<button
|
||||
className={BTN}
|
||||
onClick={() => onStep(-1)}
|
||||
disabled={disabled || atMin}
|
||||
title="Smaller jump size"
|
||||
>
|
||||
−
|
||||
</button>
|
||||
<span className="w-9 text-center text-xs font-semibold tabular-nums text-text">
|
||||
{sizeLabel(beats)}
|
||||
</span>
|
||||
<button
|
||||
className={BTN}
|
||||
onClick={() => onStep(1)}
|
||||
disabled={disabled || atMax}
|
||||
title="Larger jump size"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
<span className="mx-0.5 w-px self-stretch bg-line" aria-hidden />
|
||||
<button
|
||||
className={BTN}
|
||||
onClick={() => onJump(-1)}
|
||||
disabled={disabled}
|
||||
title="Jump back (←)"
|
||||
>
|
||||
◀
|
||||
</button>
|
||||
<button
|
||||
className={BTN}
|
||||
onClick={() => onJump(1)}
|
||||
disabled={disabled}
|
||||
title="Jump forward (→)"
|
||||
>
|
||||
▶
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type HistoryEntry } from '../api'
|
||||
import type { ToastMsg } from './Toast'
|
||||
|
||||
interface Props {
|
||||
onClose: () => void
|
||||
onNotify: (kind: ToastMsg['kind'], text: string) => void
|
||||
onError: (msg: string) => void
|
||||
}
|
||||
|
||||
function formatWhen(iso: string): string {
|
||||
const d = new Date(iso)
|
||||
if (Number.isNaN(d.getTime())) return iso
|
||||
return d.toLocaleString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})
|
||||
}
|
||||
|
||||
// Backend joins the summary's parts with "; " (e.g. "Added 6 hotcues; edited
|
||||
// beatgrid on 3 tracks"). Split them back out so each renders as its own chip
|
||||
// that wraps — far more scannable than one truncated run-on line.
|
||||
function summaryChips(summary: string): string[] {
|
||||
return summary
|
||||
.split('; ')
|
||||
.map((p) => p.trim())
|
||||
.filter(Boolean)
|
||||
.map((p) => p.charAt(0).toUpperCase() + p.slice(1))
|
||||
}
|
||||
|
||||
/**
|
||||
* Version history browser for the current collection. Every save is a commit in
|
||||
* a purely-local git repo (see backend history.py); this lists them newest-first
|
||||
* and lets the user restore any past version (written back as a new forward save)
|
||||
* or wipe the entire history. Restore overwrites the collection on disk, so the
|
||||
* user must close Traktor first (it rewrites the .nml on exit).
|
||||
*/
|
||||
export function HistoryPanel({ onClose, onNotify, onError }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const history = useQuery({ queryKey: ['history'], queryFn: api.history })
|
||||
const [confirmingId, setConfirmingId] = useState<string | null>(null)
|
||||
const [clearing, setClearing] = useState(false)
|
||||
|
||||
const restore = useMutation({
|
||||
mutationFn: (id: string) => api.restoreVersion(id),
|
||||
onSuccess: () => {
|
||||
// A restore swaps the whole collection — refetch everything.
|
||||
qc.invalidateQueries()
|
||||
onNotify('success', 'Restored — the library now reflects that version.')
|
||||
setConfirmingId(null)
|
||||
onClose()
|
||||
},
|
||||
onError: (e: Error) => {
|
||||
onError(e.message)
|
||||
setConfirmingId(null)
|
||||
},
|
||||
})
|
||||
|
||||
const clear = useMutation({
|
||||
mutationFn: () => api.clearHistory(),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['history'] })
|
||||
onNotify('success', 'Version history deleted.')
|
||||
setClearing(false)
|
||||
},
|
||||
onError: (e: Error) => {
|
||||
onError(e.message)
|
||||
setClearing(false)
|
||||
},
|
||||
})
|
||||
|
||||
const entries = history.data ?? []
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-6"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="flex max-h-[85vh] w-full max-w-xl flex-col 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">
|
||||
<div className="text-[15px] font-semibold tracking-tight">Version History</div>
|
||||
<div className="text-xs text-muted">
|
||||
Every save is a restorable version of this collection. Close Traktor before
|
||||
restoring — it overwrites the collection on exit.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">
|
||||
{history.isLoading ? (
|
||||
<div className="py-8 text-center text-sm text-faint">Loading…</div>
|
||||
) : entries.length === 0 ? (
|
||||
<div className="py-8 text-center text-sm text-faint">
|
||||
No versions yet. Saving a change records the first one.
|
||||
</div>
|
||||
) : (
|
||||
<ul className="space-y-1.5">
|
||||
{entries.map((e: HistoryEntry, i: number) => {
|
||||
const isCurrent = i === 0
|
||||
const isConfirming = confirmingId === e.id
|
||||
return (
|
||||
<li
|
||||
key={e.id}
|
||||
className="group flex items-start gap-3 rounded-md border border-line bg-ink-850 px-3 py-2"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
{isCurrent && (
|
||||
<span className="rounded bg-mint/15 px-1.5 py-0.5 text-[10px] font-medium text-mint">
|
||||
current
|
||||
</span>
|
||||
)}
|
||||
{summaryChips(e.summary).map((chip, ci) => (
|
||||
<span
|
||||
key={ci}
|
||||
className="rounded bg-ink-800 px-1.5 py-0.5 text-xs text-text"
|
||||
>
|
||||
{chip}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-1 text-[11px] text-faint">
|
||||
{formatWhen(e.timestamp)} · {e.id.slice(0, 8)}
|
||||
</div>
|
||||
</div>
|
||||
{isConfirming ? (
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
<button
|
||||
onClick={() => restore.mutate(e.id)}
|
||||
disabled={restore.isPending}
|
||||
className="rounded-md bg-gold px-2.5 py-1 text-xs font-medium text-ink-950 hover:brightness-110 disabled:opacity-50"
|
||||
>
|
||||
{restore.isPending ? 'Restoring…' : 'Restore'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setConfirmingId(null)}
|
||||
className="rounded-md px-2 py-1 text-xs text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setConfirmingId(e.id)}
|
||||
disabled={isCurrent}
|
||||
title={isCurrent ? 'This is the current version' : 'Restore this version'}
|
||||
className="mt-0.5 shrink-0 rounded-md border border-line px-2.5 py-1 text-xs text-muted opacity-0 transition-opacity hover:bg-ink-800 hover:text-text group-hover:opacity-100 disabled:cursor-not-allowed disabled:opacity-0"
|
||||
>
|
||||
Restore
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Destructive: wipe the whole history. */}
|
||||
<div className="border-t border-line px-5 py-3">
|
||||
{clearing ? (
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-[11px] text-gold">
|
||||
Permanently delete ALL {entries.length} version
|
||||
{entries.length === 1 ? '' : 's'}? This can't be undone.
|
||||
</span>
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
<button
|
||||
onClick={() => clear.mutate()}
|
||||
disabled={clear.isPending}
|
||||
className="rounded-md bg-gold px-2.5 py-1 text-xs font-medium text-ink-950 hover:brightness-110 disabled:opacity-50"
|
||||
>
|
||||
{clear.isPending ? 'Deleting…' : 'Yes, delete all'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setClearing(false)}
|
||||
className="rounded-md px-2 py-1 text-xs text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-between">
|
||||
<button
|
||||
onClick={() => setClearing(true)}
|
||||
disabled={entries.length === 0}
|
||||
className="rounded-md border border-gold/50 px-2.5 py-1 text-xs text-gold hover:bg-gold/10 disabled:opacity-40"
|
||||
>
|
||||
Delete all history…
|
||||
</button>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</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.'
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type RemapPreview } from '../api'
|
||||
import type { ToastMsg } from './Toast'
|
||||
|
||||
interface Props {
|
||||
onClose: () => void
|
||||
onNotify: (kind: ToastMsg['kind'], text: string) => void
|
||||
onError: (msg: string) => void
|
||||
}
|
||||
|
||||
const inputCls =
|
||||
'w-full rounded-md border border-line bg-ink-850 px-2.5 py-1.5 text-sm text-text outline-none focus:border-accent placeholder:text-faint'
|
||||
|
||||
/**
|
||||
* Per-collection OS-path remapping editor. Lets the user translate the stored
|
||||
* audio-file path prefix to a locally-reachable one (portable USB / relocated
|
||||
* library). Saving the mapping is non-destructive — the .nml is never touched;
|
||||
* only how Konduktor resolves files for playback/analysis/tags changes.
|
||||
*/
|
||||
export function PathMappingDialog({ onClose, onNotify, onError }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const saved = useQuery({ queryKey: ['pathMapping'], queryFn: api.getPathMapping })
|
||||
const suggest = useQuery({ queryKey: ['prefixSuggest'], queryFn: api.suggestPrefix })
|
||||
|
||||
const [from, setFrom] = useState('')
|
||||
const [to, setTo] = useState('')
|
||||
const hydrated = useRef(false)
|
||||
const [preview, setPreview] = useState<RemapPreview | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [browsing, setBrowsing] = useState(false)
|
||||
const [confirming, setConfirming] = useState(false)
|
||||
const [committing, setCommitting] = useState(false)
|
||||
|
||||
// Hydrate once: prefer the saved mapping; otherwise prefill `from` with the
|
||||
// auto-detected prefix. Defer until the suggestion resolves when we'd need it.
|
||||
useEffect(() => {
|
||||
if (hydrated.current || !saved.data) return
|
||||
if (!saved.data.from && suggest.isLoading) return
|
||||
hydrated.current = true
|
||||
setTo(saved.data.to)
|
||||
setFrom(saved.data.from || suggest.data?.primary || '')
|
||||
}, [saved.data, suggest.isLoading, suggest.data])
|
||||
|
||||
// Live validation preview (debounced) — how many tracks match / exist.
|
||||
useEffect(() => {
|
||||
if (!from.trim() || !to.trim()) {
|
||||
setPreview(null)
|
||||
return
|
||||
}
|
||||
const t = window.setTimeout(() => {
|
||||
api
|
||||
.previewRemap(from.trim(), to.trim())
|
||||
.then(setPreview)
|
||||
.catch(() => setPreview(null))
|
||||
}, 350)
|
||||
return () => window.clearTimeout(t)
|
||||
}, [from, to])
|
||||
|
||||
const saveMapping = async () => {
|
||||
setSaving(true)
|
||||
try {
|
||||
await api.putPathMapping({ from: from.trim(), to: to.trim() })
|
||||
// Re-resolve everything that depends on the file path.
|
||||
qc.invalidateQueries({ queryKey: ['pathMapping'] })
|
||||
qc.invalidateQueries({ queryKey: ['tracks'] })
|
||||
const cleared = !from.trim() || !to.trim()
|
||||
onNotify('success', cleared ? 'Path mapping cleared.' : 'Path mapping saved.')
|
||||
onClose()
|
||||
} catch (e) {
|
||||
onError(e instanceof Error ? e.message : 'Failed to save mapping')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const commit = async () => {
|
||||
setCommitting(true)
|
||||
try {
|
||||
const res = await api.remapPaths(from.trim(), to.trim())
|
||||
// Locations changed, so track ids changed — refetch library + state.
|
||||
qc.invalidateQueries({ queryKey: ['tracks'] })
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
if (res.rewritten === 0) {
|
||||
onNotify('warning', 'No tracks matched — nothing was rewritten.')
|
||||
} else {
|
||||
onNotify(
|
||||
'success',
|
||||
`Rewrote ${res.rewritten} track path${res.rewritten === 1 ? '' : 's'}.` +
|
||||
(res.commit ? ` Version: ${res.commit.slice(0, 8)}` : ''),
|
||||
)
|
||||
onClose()
|
||||
}
|
||||
} catch (e) {
|
||||
onError(e instanceof Error ? e.message : 'Failed to rewrite paths')
|
||||
} finally {
|
||||
setCommitting(false)
|
||||
setConfirming(false)
|
||||
}
|
||||
}
|
||||
|
||||
const canCommit = !!from.trim() && !!to.trim()
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-6"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="flex max-h-[85vh] w-full max-w-xl flex-col 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">
|
||||
<div className="text-[15px] font-semibold tracking-tight">Path Remapping</div>
|
||||
<div className="text-xs text-muted">
|
||||
Translate the collection's stored file paths to where they live on this machine.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-xs font-medium text-muted">Stored prefix (from)</label>
|
||||
<input
|
||||
value={from}
|
||||
onChange={(e) => setFrom(e.target.value)}
|
||||
placeholder="/Volumes/OLD_USB/Music"
|
||||
className={inputCls}
|
||||
/>
|
||||
<div className="text-[11px] text-faint">
|
||||
The path prefix as saved in the collection (may not exist on this machine).
|
||||
</div>
|
||||
{suggest.data && suggest.data.groups.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-1.5 pt-0.5">
|
||||
<span className="text-[11px] text-faint">Detected:</span>
|
||||
{suggest.data.groups
|
||||
.filter((g) => g.prefix && g.prefix !== from)
|
||||
.map((g) => (
|
||||
<button
|
||||
key={g.prefix}
|
||||
onClick={() => setFrom(g.prefix)}
|
||||
title={`${g.count} tracks`}
|
||||
className="max-w-full truncate rounded border border-line px-1.5 py-0.5 text-[11px] text-accent hover:bg-ink-800"
|
||||
>
|
||||
{g.prefix} · {g.count}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-xs font-medium text-muted">Local prefix (to)</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={to}
|
||||
onChange={(e) => setTo(e.target.value)}
|
||||
placeholder="/Users/you/Music"
|
||||
className={inputCls}
|
||||
/>
|
||||
<button
|
||||
onClick={() => setBrowsing((b) => !b)}
|
||||
className="shrink-0 rounded-md border border-line px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
{browsing ? 'Close' : 'Browse…'}
|
||||
</button>
|
||||
</div>
|
||||
{browsing && (
|
||||
<FolderBrowser
|
||||
initial={to.trim() || undefined}
|
||||
onPick={(path) => {
|
||||
setTo(path)
|
||||
setBrowsing(false)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Validation preview */}
|
||||
{preview && (
|
||||
<div className="rounded-md border border-line bg-ink-850 px-3 py-2 text-xs">
|
||||
{preview.matched === 0 ? (
|
||||
<span className="text-gold">
|
||||
No tracks match “{from.trim()}”. Check the stored prefix.
|
||||
</span>
|
||||
) : (
|
||||
<span className={preview.existing === preview.matched ? 'text-mint' : 'text-gold'}>
|
||||
{preview.matched} of {preview.total} tracks match; {preview.existing} of{' '}
|
||||
{preview.matched} exist at the target.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Write-back: permanent, destructive move. Clearly separated. */}
|
||||
<div className="mt-2 space-y-2 rounded-md border border-gold/40 bg-gold/5 px-3 py-3">
|
||||
<div className="text-xs font-semibold text-gold">Make permanent</div>
|
||||
<p className="text-[11px] leading-relaxed text-muted">
|
||||
Rewrites the matching file paths directly in the collection (saved to
|
||||
version history). Use this only when you've moved the library for good — it
|
||||
bakes in <span className="text-text">this machine's</span> paths and will
|
||||
break the collection on other machines/OSes.
|
||||
</p>
|
||||
{confirming ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[11px] text-gold">Rewrite {preview?.matched ?? 0} paths?</span>
|
||||
<button
|
||||
onClick={commit}
|
||||
disabled={committing || !canCommit}
|
||||
className="rounded-md bg-gold px-2.5 py-1 text-xs font-medium text-ink-950 hover:brightness-110 disabled:opacity-50"
|
||||
>
|
||||
{committing ? 'Rewriting…' : 'Yes, rewrite'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setConfirming(false)}
|
||||
className="rounded-md px-2.5 py-1 text-xs text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setConfirming(true)}
|
||||
disabled={!canCommit}
|
||||
className="rounded-md border border-gold/50 px-2.5 py-1 text-xs text-gold hover:bg-gold/10 disabled:opacity-40"
|
||||
>
|
||||
Rewrite collection paths…
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={saveMapping}
|
||||
disabled={saving}
|
||||
className="rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110 disabled:opacity-50"
|
||||
>
|
||||
{saving ? 'Saving…' : 'Save mapping'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** A compact directory-only browser for choosing the local prefix. */
|
||||
function FolderBrowser({
|
||||
initial,
|
||||
onPick,
|
||||
}: {
|
||||
initial?: string
|
||||
onPick: (path: string) => void
|
||||
}) {
|
||||
const [dir, setDir] = useState<string | undefined>(initial)
|
||||
const listing = useQuery({ queryKey: ['fs', dir ?? '~'], queryFn: () => api.listDir(dir) })
|
||||
const data = listing.data
|
||||
|
||||
return (
|
||||
<div className="mt-2 overflow-hidden rounded-md border border-line bg-ink-850">
|
||||
<div className="flex items-center gap-1 border-b border-line px-2 py-1.5">
|
||||
<button
|
||||
onClick={() => setDir(data?.home)}
|
||||
className="rounded px-2 py-0.5 text-xs text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
Home
|
||||
</button>
|
||||
<button
|
||||
onClick={() => data?.parent && setDir(data.parent)}
|
||||
disabled={!data?.parent}
|
||||
className="rounded px-2 py-0.5 text-xs text-muted hover:bg-ink-800 hover:text-text disabled:opacity-40"
|
||||
>
|
||||
Up
|
||||
</button>
|
||||
<span className="ml-1 flex-1 truncate text-right text-[11px] text-faint" dir="rtl">
|
||||
{data?.path ?? '…'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-48 overflow-y-auto">
|
||||
{data?.dirs.length ? (
|
||||
data.dirs.map((d) => (
|
||||
<button
|
||||
key={d.path}
|
||||
onClick={() => setDir(d.path)}
|
||||
className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm text-text hover:bg-ink-800"
|
||||
>
|
||||
<span className="text-faint">📁</span>
|
||||
<span className="truncate">{d.name}</span>
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<div className="px-3 py-2 text-xs text-faint">No subfolders.</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="border-t border-line px-2 py-1.5">
|
||||
<button
|
||||
onClick={() => data?.path && onPick(data.path)}
|
||||
disabled={!data?.path}
|
||||
className="w-full rounded-md bg-ink-800 px-3 py-1.5 text-sm text-text hover:bg-ink-700 disabled:opacity-50"
|
||||
>
|
||||
Use this folder
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { api, type Track, type TrackCues } from '../api'
|
||||
import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
|
||||
import { ScratchEngine } from '../lib/scratchEngine'
|
||||
import { PlaybackEngine } from '../lib/playbackEngine'
|
||||
import { BeatJumpControls, BEAT_JUMP_SIZES } from './BeatJumpControls'
|
||||
import { GridControls } from './GridControls'
|
||||
import { HotcueBar } from './HotcueBar'
|
||||
import { LoopControls } from './LoopControls'
|
||||
@@ -16,6 +17,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 +44,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)
|
||||
@@ -54,6 +58,7 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
const [selectedSlot, setSelectedSlot] = useState<number | null>(null)
|
||||
const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only)
|
||||
const [secPerView, setSecPerView] = useState(DEFAULT_SEC) // main-waveform zoom (persisted)
|
||||
const [jumpBeats, setJumpBeats] = useState(4) // beat-jump size in beats (persisted)
|
||||
|
||||
// Loop state (transient — persisted only when saved as a hotcue later).
|
||||
const [loopRegion, setLoopRegion] = useState<{ start: number; end: number } | null>(null)
|
||||
@@ -71,6 +76,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
|
||||
|
||||
@@ -100,6 +111,26 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
}
|
||||
}, [secPerView])
|
||||
|
||||
// Beat-jump size persists the same way (survives track switches + restarts).
|
||||
const jumpHydratedRef = useRef(false)
|
||||
const jumpSaveTimer = useRef<number | null>(null)
|
||||
useEffect(() => {
|
||||
if (jumpHydratedRef.current || !prefsQuery.data) return
|
||||
jumpHydratedRef.current = true
|
||||
const b = (prefsQuery.data as { beatJumpBeats?: unknown }).beatJumpBeats
|
||||
if (typeof b === 'number' && BEAT_JUMP_SIZES.includes(b)) setJumpBeats(b)
|
||||
}, [prefsQuery.data])
|
||||
useEffect(() => {
|
||||
if (!jumpHydratedRef.current) return // don't clobber saved prefs pre-hydration
|
||||
if (jumpSaveTimer.current) window.clearTimeout(jumpSaveTimer.current)
|
||||
jumpSaveTimer.current = window.setTimeout(() => {
|
||||
api.patchPrefs({ beatJumpBeats: jumpBeats }).catch(() => {})
|
||||
}, 500)
|
||||
return () => {
|
||||
if (jumpSaveTimer.current) window.clearTimeout(jumpSaveTimer.current)
|
||||
}
|
||||
}, [jumpBeats])
|
||||
|
||||
const getCtx = (): AudioContext => {
|
||||
if (!audioCtxRef.current) {
|
||||
audioCtxRef.current = new (window.AudioContext ??
|
||||
@@ -150,6 +181,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 +259,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 +282,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 +323,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;
|
||||
@@ -303,6 +382,31 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
seek(t)
|
||||
}
|
||||
|
||||
// ---- beat jump --------------------------------------------------------
|
||||
// Step the jump size through BEAT_JUMP_SIZES, clamping at both ends (no wrap).
|
||||
const stepJumpSize = (dir: -1 | 1) => {
|
||||
setJumpBeats((b) => {
|
||||
const i = BEAT_JUMP_SIZES.indexOf(b)
|
||||
const next = Math.min(BEAT_JUMP_SIZES.length - 1, Math.max(0, (i < 0 ? 4 : i) + dir))
|
||||
return BEAT_JUMP_SIZES[next]
|
||||
})
|
||||
}
|
||||
|
||||
// Move the playhead exactly `jumpBeats` beats fwd/back, preserving sub-beat
|
||||
// phase (pure translation, no grid snap). Like seekManual, jumping escapes an
|
||||
// active loop. seek() clamps to [0, duration], preserves play/pause state.
|
||||
const beatJump = (dir: -1 | 1) => {
|
||||
const eng = playbackRef.current
|
||||
const bpm = cueData?.bpm ?? null
|
||||
if (!eng || !bpm || bpm <= 0) return
|
||||
if (loopActive) {
|
||||
eng.setLoopEnabled(false)
|
||||
setLoopActive(false)
|
||||
}
|
||||
eng.seek(eng.getPosition() + dir * jumpBeats * (60 / bpm))
|
||||
setCurrent(eng.getPosition())
|
||||
}
|
||||
|
||||
// ---- scratch ----------------------------------------------------------
|
||||
const finalizeScratch = () => {
|
||||
cancelAnimationFrame(scratchRafRef.current)
|
||||
@@ -458,20 +562,15 @@ 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)
|
||||
}
|
||||
setSelectedSlot(slot)
|
||||
return
|
||||
}
|
||||
if (!cue) {
|
||||
try {
|
||||
// Setting a hotcue while a loop is active stores it as a loop hotcue.
|
||||
if (loopActive && loopRegion) {
|
||||
@@ -485,6 +584,54 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
} catch (e) {
|
||||
onError?.((e as Error).message)
|
||||
}
|
||||
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 {
|
||||
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 {
|
||||
onNotify?.('success', `Placed ${placed} auto hotcue${placed === 1 ? '' : 's'}`)
|
||||
}
|
||||
} catch (e) {
|
||||
onError?.((e as Error).message)
|
||||
} finally {
|
||||
setAutoBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const changeSelectedType = async (type: number) => {
|
||||
@@ -520,34 +667,78 @@ 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,
|
||||
beatJump,
|
||||
})
|
||||
shortcutsRef.current = {
|
||||
toggle,
|
||||
onSlotPress,
|
||||
onSlotRelease,
|
||||
deleteHotcueSlot,
|
||||
onCuePress,
|
||||
onCueRelease,
|
||||
beatJump,
|
||||
}
|
||||
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
|
||||
}
|
||||
if (e.code === 'ArrowLeft') {
|
||||
e.preventDefault()
|
||||
shortcutsRef.current.beatJump(-1)
|
||||
return
|
||||
}
|
||||
if (e.code === 'ArrowRight') {
|
||||
e.preventDefault()
|
||||
shortcutsRef.current.beatJump(1)
|
||||
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 ---------------------------------------------------------
|
||||
const gridBpm = cueData?.bpm ?? null
|
||||
const gridAnchor = cueData?.grid_anchor ?? null
|
||||
// Beat jump needs a tempo to size beats; disabled on ungridded tracks.
|
||||
const canBeatJump = ready && gridBpm != null && gridBpm > 0
|
||||
|
||||
const editGrid = async (patch: { bpm?: number; anchor?: number }) => {
|
||||
if (!track) return
|
||||
@@ -588,13 +779,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-[25.5rem] 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 +830,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,7 +855,9 @@ 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
|
||||
(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')
|
||||
}
|
||||
@@ -664,6 +878,13 @@ export function PrepStrip({ track, playRequest = 0, onError }: Props) {
|
||||
{fmt(current)} / {fmt(duration)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BeatJumpControls
|
||||
beats={jumpBeats}
|
||||
onStep={stepJumpSize}
|
||||
onJump={beatJump}
|
||||
disabled={!canBeatJump}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Waveforms + loop/hotcue controls. */}
|
||||
@@ -737,7 +958,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 +980,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}
|
||||
|
||||
@@ -7,7 +7,7 @@ interface Props {
|
||||
}
|
||||
|
||||
// Bottom-of-sidebar save control. Shows unsaved-changes state and writes to the
|
||||
// NML (backup-first). On-disk saving is gated server-side by KONDUKTOR_ALLOW_WRITE.
|
||||
// NML; every save is recorded in the collection's version history.
|
||||
export function SaveBar({ onError }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [justSaved, setJustSaved] = useState<string | null>(null)
|
||||
@@ -17,9 +17,9 @@ export function SaveBar({ onError }: Props) {
|
||||
mutationFn: api.save,
|
||||
onSuccess: (res) => {
|
||||
qc.invalidateQueries({ queryKey: ['state'] })
|
||||
if (res.saved && res.backup) {
|
||||
const name = res.backup.split('/').pop()
|
||||
setJustSaved(`Saved · backup ${name}`)
|
||||
qc.invalidateQueries({ queryKey: ['history'] })
|
||||
if (res.saved && res.commit) {
|
||||
setJustSaved(`Saved · version ${res.commit.slice(0, 8)}`)
|
||||
setTimeout(() => setJustSaved(null), 6000)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
interface Props {
|
||||
onOpenPathMapping: () => void
|
||||
}
|
||||
|
||||
/** Overflow menu for low-frequency, collection-level settings. Currently holds
|
||||
* path remapping; the natural home for future advanced settings. */
|
||||
export function SettingsMenu({ onOpenPathMapping }: Props) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onDoc = (e: MouseEvent) => {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)
|
||||
}
|
||||
document.addEventListener('mousedown', onDoc)
|
||||
return () => document.removeEventListener('mousedown', onDoc)
|
||||
}, [open])
|
||||
|
||||
const item =
|
||||
'flex w-full flex-col items-start rounded px-2 py-1.5 text-left hover:bg-ink-800'
|
||||
|
||||
return (
|
||||
<div ref={ref} className="relative">
|
||||
<button
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
className="flex items-center justify-center rounded-md border border-line bg-ink-850 px-2 py-1.5 text-muted transition-colors hover:border-ink-600 hover:text-text"
|
||||
title="Settings"
|
||||
aria-label="Settings"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="h-5 w-5"
|
||||
>
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
|
||||
</svg>
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute right-0 z-30 mt-1 w-56 rounded-md border border-line bg-ink-850 p-1 shadow-2xl">
|
||||
<button
|
||||
onClick={() => {
|
||||
onOpenPathMapping()
|
||||
setOpen(false)
|
||||
}}
|
||||
className={item}
|
||||
>
|
||||
<span className="text-sm text-text">Path remapping…</span>
|
||||
<span className="text-[11px] text-faint">
|
||||
Point the collection at moved or relocated files
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -9,6 +9,7 @@ interface Props {
|
||||
source: Source
|
||||
onSelect: (s: Source) => void
|
||||
onError: (msg: string) => void
|
||||
onOpenHistory: () => void
|
||||
}
|
||||
|
||||
const icons: Record<string, string> = {
|
||||
@@ -157,7 +158,7 @@ function NodeRow({
|
||||
)
|
||||
}
|
||||
|
||||
export function Sidebar({ source, onSelect, onError }: Props) {
|
||||
export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [newName, setNewName] = useState('')
|
||||
@@ -245,6 +246,13 @@ export function Sidebar({ source, onSelect, onError }: Props) {
|
||||
))}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={onOpenHistory}
|
||||
className="flex items-center justify-center gap-2 border-t border-line px-4 py-2 text-center text-xs text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
Collection Version History
|
||||
</button>
|
||||
|
||||
<SaveBar onError={onError} />
|
||||
</aside>
|
||||
)
|
||||
|
||||
@@ -2,14 +2,20 @@ import { useEffect } from 'react'
|
||||
|
||||
export interface ToastMsg {
|
||||
id: number
|
||||
kind: 'success' | 'error'
|
||||
kind: 'success' | 'error' | 'warning'
|
||||
text: string
|
||||
}
|
||||
|
||||
const KIND_CLS: Record<ToastMsg['kind'], string> = {
|
||||
error: 'border-pink/40 bg-ink-800 text-pink',
|
||||
warning: 'border-gold/40 bg-ink-800 text-gold',
|
||||
success: 'border-mint/40 bg-ink-800 text-mint',
|
||||
}
|
||||
|
||||
export function Toast({ toast, onClose }: { toast: ToastMsg | null; onClose: () => void }) {
|
||||
useEffect(() => {
|
||||
if (!toast) return
|
||||
const t = setTimeout(onClose, toast.kind === 'error' ? 6000 : 4000)
|
||||
const t = setTimeout(onClose, toast.kind === 'success' ? 4000 : 6000)
|
||||
return () => clearTimeout(t)
|
||||
}, [toast, onClose])
|
||||
|
||||
@@ -17,11 +23,7 @@ export function Toast({ toast, onClose }: { toast: ToastMsg | null; onClose: ()
|
||||
return (
|
||||
<div className="pointer-events-none fixed inset-x-0 top-4 z-50 flex justify-center">
|
||||
<div
|
||||
className={`pointer-events-auto max-w-lg rounded-lg border px-4 py-2.5 text-sm shadow-xl ${
|
||||
toast.kind === 'error'
|
||||
? 'border-pink/40 bg-ink-800 text-pink'
|
||||
: 'border-mint/40 bg-ink-800 text-mint'
|
||||
}`}
|
||||
className={`pointer-events-auto max-w-lg rounded-lg border px-4 py-2.5 text-sm shadow-xl ${KIND_CLS[toast.kind]}`}
|
||||
>
|
||||
{toast.text}
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import type { VisibilityState } from '@tanstack/react-table'
|
||||
import { api } from '../api'
|
||||
import { ColumnsMenu } from './ColumnsMenu'
|
||||
import { SettingsMenu } from './SettingsMenu'
|
||||
|
||||
export interface Filters {
|
||||
search: string
|
||||
@@ -29,6 +30,7 @@ interface Props {
|
||||
columnVisibility: VisibilityState
|
||||
onColumnVisibilityChange: (v: VisibilityState) => void
|
||||
onResetColumns: () => void
|
||||
onOpenPathMapping: () => void
|
||||
}
|
||||
|
||||
const selectCls =
|
||||
@@ -40,6 +42,7 @@ export function Toolbar({
|
||||
columnVisibility,
|
||||
onColumnVisibilityChange,
|
||||
onResetColumns,
|
||||
onOpenPathMapping,
|
||||
}: Props) {
|
||||
const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets })
|
||||
const set = (patch: Partial<Filters>) => onChange({ ...filters, ...patch })
|
||||
@@ -145,6 +148,7 @@ export function Toolbar({
|
||||
onChange={onColumnVisibilityChange}
|
||||
onReset={onResetColumns}
|
||||
/>
|
||||
<SettingsMenu onOpenPathMapping={onOpenPathMapping} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRef } from 'react'
|
||||
import { useEffect, useRef, useState, type MutableRefObject } 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,28 +44,96 @@ 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. */
|
||||
function SortableHeader({ header }: { header: Header<Track, unknown> }) {
|
||||
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).
|
||||
* `draggedRef` is set true for the duration of a reorder so the stray `click`
|
||||
* the browser fires after a drag doesn't also toggle the sort. */
|
||||
function SortableHeader({
|
||||
header,
|
||||
draggedRef,
|
||||
}: {
|
||||
header: Header<Track, unknown>
|
||||
draggedRef: MutableRefObject<boolean>
|
||||
}) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
|
||||
id: header.column.id,
|
||||
})
|
||||
const sorted = header.column.getIsSorted()
|
||||
const toggleSort = header.column.getToggleSortingHandler()
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
@@ -73,7 +149,12 @@ function SortableHeader({ header }: { header: Header<Track, unknown> }) {
|
||||
<button
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
onClick={header.column.getToggleSortingHandler()}
|
||||
onClick={(e) => {
|
||||
// A reorder-drag ends with a stray click on the header — ignore it so
|
||||
// dragging a column doesn't also flip its sort direction.
|
||||
if (draggedRef.current) return
|
||||
toggleSort?.(e)
|
||||
}}
|
||||
className="flex flex-1 cursor-grab items-center gap-1 px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wider text-muted hover:text-text active:cursor-grabbing"
|
||||
>
|
||||
{flexRender(header.column.columnDef.header, header.getContext())}
|
||||
@@ -95,6 +176,74 @@ 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
|
||||
}) {
|
||||
// True while (and just after) a column is being reordered, so the trailing
|
||||
// click a drag emits is swallowed instead of toggling the sort.
|
||||
const draggedRef = useRef(false)
|
||||
return (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
modifiers={[restrictToHorizontalAxis]}
|
||||
onDragStart={() => {
|
||||
draggedRef.current = true
|
||||
}}
|
||||
onDragEnd={(e) => {
|
||||
onColumnDragEnd(e)
|
||||
// Clear on the next tick — after the synchronous post-drag click fires.
|
||||
setTimeout(() => {
|
||||
draggedRef.current = false
|
||||
}, 0)
|
||||
}}
|
||||
>
|
||||
<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} draggedRef={draggedRef} />
|
||||
))}
|
||||
</SortableContext>
|
||||
{trail && <span className="w-10 shrink-0" />}
|
||||
</div>
|
||||
</DndContext>
|
||||
)
|
||||
}
|
||||
|
||||
/** The virtualized library grid (All Tracks). */
|
||||
export function TrackTable({
|
||||
tracks,
|
||||
sorting,
|
||||
@@ -131,17 +280,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 sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }))
|
||||
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,40 +302,14 @@ 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"
|
||||
<HeaderRow
|
||||
headers={headers}
|
||||
sensors={sensors}
|
||||
onColumnDragEnd={onColumnDragEnd}
|
||||
hasPlay={hasPlay}
|
||||
selection={selection}
|
||||
/>
|
||||
</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]
|
||||
@@ -197,12 +321,7 @@ export function TrackTable({
|
||||
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%',
|
||||
}}
|
||||
style={{ top: 0, transform: `translateY(${vr.start}px)`, height: vr.size, width: '100%' }}
|
||||
onContextMenu={(e) => {
|
||||
if (!onRowContextMenu) return
|
||||
e.preventDefault()
|
||||
@@ -223,41 +342,199 @@ export function TrackTable({
|
||||
{vr.index + 1}
|
||||
</span>
|
||||
)}
|
||||
{onPlay && (
|
||||
{hasPlay && (
|
||||
<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>
|
||||
{onPlay && <PlayButton track={row.original} isActive={isActive} onPlay={onPlay} />}
|
||||
</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>
|
||||
))}
|
||||
<RowCells row={row} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</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: 8 } }))
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api } from '../api'
|
||||
|
||||
/**
|
||||
* Startup update check against GitHub Releases.
|
||||
*
|
||||
* Compares the running version (`__APP_VERSION__`, baked from package.json at
|
||||
* build time) with the latest release's tag (`v<version>-b<N>` — only the
|
||||
* semver part counts, so a new build of the same version is NOT an update).
|
||||
* Failures are silent: an update check must never nag about itself.
|
||||
* "Skip this version" persists `skippedUpdateVersion` to userprefs.json via
|
||||
* the prefs API, keyed by the semver part, so a later version re-triggers.
|
||||
*/
|
||||
|
||||
const REPO = 'MrPatben8/konduktor'
|
||||
|
||||
interface GithubRelease {
|
||||
tag_name: string
|
||||
html_url: string
|
||||
body: string | null
|
||||
}
|
||||
|
||||
async function fetchLatestRelease(): Promise<GithubRelease> {
|
||||
const res = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, {
|
||||
headers: { Accept: 'application/vnd.github+json' },
|
||||
})
|
||||
if (!res.ok) throw new Error(`GitHub responded ${res.status}`)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
/** The semver triple at the start of a version/tag string ("v0.1.2-b7" → [0,1,2]). */
|
||||
function parseVersion(s: string): [number, number, number] | null {
|
||||
const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(s.trim())
|
||||
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null
|
||||
}
|
||||
|
||||
function isNewer(a: [number, number, number], b: [number, number, number]): boolean {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (a[i] !== b[i]) return a[i] > b[i]
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* The "What's Changed" bullet lines from an auto-generated release body
|
||||
* (section ends at the next heading or the Full Changelog link). If the
|
||||
* section is missing (hand-written notes), fall back to the whole body.
|
||||
* The auto-generated "by @user in <PR url>" credit suffix is stripped.
|
||||
*/
|
||||
function whatsChanged(body: string | null): string[] {
|
||||
if (!body) return []
|
||||
const lines = body.split(/\r?\n/)
|
||||
const start = lines.findIndex((l) => /^#{2,4}\s+what'?s changed/i.test(l.trim()))
|
||||
const out: string[] = []
|
||||
for (const raw of lines.slice(start + 1)) {
|
||||
const line = raw.trim()
|
||||
if (start !== -1 && (/^#{1,4}\s/.test(line) || line.startsWith('**Full Changelog**'))) break
|
||||
if (line) {
|
||||
out.push(
|
||||
line.replace(/^[*-]\s+/, '').replace(/\s+by\s+@[\w-]+\s+in\s+https?:\/\/\S+$/i, ''),
|
||||
)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Open a URL in the system browser (Tauri shell-open in the desktop app). */
|
||||
async function openExternal(url: string) {
|
||||
if ('__TAURI_INTERNALS__' in window) {
|
||||
try {
|
||||
const { open } = await import('@tauri-apps/plugin-shell')
|
||||
await open(url)
|
||||
return
|
||||
} catch {
|
||||
// fall through to window.open
|
||||
}
|
||||
}
|
||||
window.open(url, '_blank', 'noopener')
|
||||
}
|
||||
|
||||
/** Render a changelog line, turning bare URLs into links (PR URLs as #N). */
|
||||
function ChangelogLine({ text }: { text: string }) {
|
||||
const parts = text.split(/(https?:\/\/\S+)/g)
|
||||
return (
|
||||
<>
|
||||
{parts.map((part, i) => {
|
||||
if (!/^https?:\/\//.test(part)) return <span key={i}>{part}</span>
|
||||
const pr = /\/pull\/(\d+)/.exec(part)
|
||||
return (
|
||||
<a
|
||||
key={i}
|
||||
href={part}
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
openExternal(part)
|
||||
}}
|
||||
className="text-accent hover:underline"
|
||||
>
|
||||
{pr ? `#${pr[1]}` : part}
|
||||
</a>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function UpdateCheck() {
|
||||
const qc = useQueryClient()
|
||||
const [dismissed, setDismissed] = useState(false)
|
||||
const [skipVersion, setSkipVersion] = useState(false)
|
||||
|
||||
const release = useQuery({
|
||||
queryKey: ['latestRelease'],
|
||||
queryFn: fetchLatestRelease,
|
||||
staleTime: Infinity,
|
||||
retry: false,
|
||||
})
|
||||
// Shares App's ['prefs'] cache entry.
|
||||
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
|
||||
|
||||
const latest = release.data
|
||||
const latestVer = latest ? parseVersion(latest.tag_name) : null
|
||||
const currentVer = parseVersion(__APP_VERSION__)
|
||||
const latestSemver = latestVer?.join('.')
|
||||
const updateAvailable = !!(latestVer && currentVer && isNewer(latestVer, currentVer))
|
||||
const skipped = !!latestSemver && prefs.data?.skippedUpdateVersion === latestSemver
|
||||
|
||||
// Wait for prefs before showing so a skipped version never flashes the dialog.
|
||||
if (dismissed || !updateAvailable || !latest || !prefs.isSuccess || skipped) return null
|
||||
|
||||
const close = () => {
|
||||
if (skipVersion && latestSemver) {
|
||||
api
|
||||
.patchPrefs({ skippedUpdateVersion: latestSemver })
|
||||
.then((p) => qc.setQueryData(['prefs'], p))
|
||||
.catch(() => {})
|
||||
}
|
||||
setDismissed(true)
|
||||
}
|
||||
|
||||
const download = () => {
|
||||
openExternal(latest.html_url)
|
||||
setDismissed(true)
|
||||
}
|
||||
|
||||
const changes = whatsChanged(latest.body)
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-6"
|
||||
onClick={close}
|
||||
>
|
||||
<div
|
||||
className="flex max-h-[80vh] w-full max-w-md flex-col 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">
|
||||
<div className="text-[15px] font-semibold tracking-tight">Update available</div>
|
||||
<div className="text-xs text-muted">
|
||||
Konduktor <span className="text-accent">{latest.tag_name}</span> is out — you have v
|
||||
{__APP_VERSION__}.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">
|
||||
<div className="mb-2 text-xs font-medium text-muted">What's changed</div>
|
||||
{changes.length ? (
|
||||
<ul className="space-y-1.5">
|
||||
{changes.map((line, i) => (
|
||||
<li key={i} className="flex gap-2 text-sm text-text">
|
||||
<span className="text-faint">•</span>
|
||||
<span className="min-w-0 break-words">
|
||||
<ChangelogLine text={line} />
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<div className="text-sm text-faint">No release notes.</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 border-t border-line px-5 py-3">
|
||||
<label className="flex cursor-pointer items-center gap-2 text-xs text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={skipVersion}
|
||||
onChange={(e) => setSkipVersion(e.target.checked)}
|
||||
className="accent-accent"
|
||||
/>
|
||||
Skip this version
|
||||
</label>
|
||||
<div className="flex-1" />
|
||||
<button
|
||||
onClick={close}
|
||||
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
Skip
|
||||
</button>
|
||||
<button
|
||||
onClick={download}
|
||||
className="rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110"
|
||||
>
|
||||
Download
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
import { UpdateCheck } from './components/UpdateDialog.tsx'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -17,6 +18,8 @@ createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
{/* Mounted beside App so the update dialog shows even on the picker screen. */}
|
||||
<UpdateCheck />
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
/** The app version from package.json, injected by vite.config.ts `define`. */
|
||||
declare const __APP_VERSION__: string
|
||||
@@ -1,9 +1,17 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// The app's own version, from the single source of truth (package.json), baked
|
||||
// in at build time as __APP_VERSION__ (used by the startup update check).
|
||||
const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
|
||||
|
||||
// Proxy /api to the FastAPI backend so the frontend can use same-origin fetches.
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
define: {
|
||||
__APP_VERSION__: JSON.stringify(pkg.version),
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
|
||||
Reference in new issue
Block a user