Compare commits

...
9 Commits
Author SHA1 Message Date
patben8 75deded209 Improved version number unification 2026-07-09 00:34:25 +02:00
patben8 6504623aac Github Actions: simplified upload artifact structure 2026-07-09 00:12:29 +02:00
patben8 179ea69633 Github actions: build and release on push/merge on main 2026-07-09 00:06:47 +02:00
patben8 38b84a9279 Created build action 2026-07-08 23:51:37 +02:00
patben8 060cd28474 Unified version numbers 2026-07-08 23:45:33 +02:00
patben8 54015049d3 Fixed column sorting and reordering issue 2026-07-08 22:03:51 +02:00
patben8 b130f1469e Implemented path remapping 2026-07-08 21:54:58 +02:00
patben8 1e8c53e693 Implemented beat jumping 2026-07-08 14:48:38 +02:00
patben8 f52c19f14d Merge pull request #1 from MrPatben8/autohotcue
Implemented Autohotcue
2026-07-08 14:16:18 +02:00
22 changed files with 1365 additions and 30 deletions

No files matched your search

+149
View File
@@ -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/**/*
+20
View File
@@ -158,6 +158,26 @@ frontend at `http://localhost:5173`.
- Python 3.14 note: pin dependencies loosely enough to get prebuilt wheels - Python 3.14 note: pin dependencies loosely enough to get prebuilt wheels
(older `pydantic-core` pins force a from-source Rust build that fails). (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).
- **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 ## Roadmap
- ✅ Phase 1 — backend core + read-only API - ✅ Phase 1 — backend core + read-only API
+5
View File
@@ -28,6 +28,11 @@ for pkg in ("uvloop", "httptools", "websockets"):
# Imported by name, not statically discoverable. # Imported by name, not statically discoverable.
hiddenimports += ["multipart", "anyio"] 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( a = Analysis(
["sidecar.py"], ["sidecar.py"],
pathex=[], pathex=[],
+33 -1
View File
@@ -1,3 +1,35 @@
"""Konduktor — Traktor library management & track preparation.""" """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()
+72 -1
View File
@@ -13,10 +13,12 @@ from fastapi import FastAPI, File, Form, HTTPException, Query, Response, UploadF
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse from fastapi.responses import FileResponse
from . import __version__
from . import auto_hotcues as ah from . import auto_hotcues as ah
from . import prefs from . import prefs
from .collection_service import CollectionService from .collection_service import CollectionService
from .discovery import describe, detect_collections from .discovery import describe, detect_collections
from .path_mapping import PathMapping
from .playlist_store import PlaylistError, PlaylistStore from .playlist_store import PlaylistError, PlaylistStore
from .schemas import ( from .schemas import (
AutoGridRequest, AutoGridRequest,
@@ -35,7 +37,11 @@ from .schemas import (
FsListing, FsListing,
GridEdit, GridEdit,
OpenCollection, OpenCollection,
PathMappingInfo,
PlaylistNode, PlaylistNode,
PrefixSuggestions,
RemapPreview,
RemapResult,
RenamePlaylist, RenamePlaylist,
SaveResult, SaveResult,
SetEntries, SetEntries,
@@ -48,7 +54,7 @@ from .schemas import (
TrackPage, TrackPage,
) )
app = FastAPI(title="Konduktor API", version="0.4.0") app = FastAPI(title="Konduktor API", version=__version__)
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
@@ -82,6 +88,11 @@ class AppState:
# only commit to the new collection if BOTH succeed. # only commit to the new collection if BOTH succeed.
service = CollectionService(path) service = CollectionService(path)
store = PlaylistStore(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 self.path, self.service, self.store = path, service, store
@@ -153,6 +164,66 @@ def collection_options() -> CollectionOptions:
return CollectionOptions(auto=auto, recent=recent) 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
(backup-first). 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, backup=None)
outcome = store.save()
return RemapResult(rewritten=count, backup=str(outcome.backup))
@app.get("/api/prefs") @app.get("/api/prefs")
def get_prefs() -> dict: def get_prefs() -> dict:
"""The full persisted user-preferences blob (UI layout, last collection…).""" """The full persisted user-preferences blob (UI layout, last collection…)."""
+127
View File
@@ -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
+133 -8
View File
@@ -43,6 +43,7 @@ from traktor_nml_utils.models.collection import (
) )
from xsdata.formats.dataclass.serializers import XmlSerializer from xsdata.formats.dataclass.serializers import XmlSerializer
from .path_mapping import PathMapping
from .schemas import PlaylistNode from .schemas import PlaylistNode
@@ -70,6 +71,8 @@ class PlaylistStore:
self.nml_path = Path(nml_path) self.nml_path = Path(nml_path)
self._lock = threading.RLock() self._lock = threading.RLock()
self.dirty = False self.dirty = False
# Active OS-path prefix remapping (empty = identity). Survives _load().
self._path_mapping = PathMapping()
self._load() self._load()
# ---- load ---------------------------------------------------------- # ---- load ----------------------------------------------------------
@@ -440,6 +443,30 @@ class PlaylistStore:
self._track_art[track_id] = (data, mime) self._track_art[track_id] = (data, mime)
self.dirty = True 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: def cover_art(self, track_id: str) -> tuple[bytes, str] | None:
"""Staged replacement if present, else the file's current embedded art.""" """Staged replacement if present, else the file's current embedded art."""
from . import file_tags from . import file_tags
@@ -450,19 +477,116 @@ class PlaylistStore:
entry = self._entry_by_key.get(track_id) entry = self._entry_by_key.get(track_id)
if entry is None or entry.location is None: if entry is None or entry.location is None:
return None return None
loc = entry.location path = self._resolve(entry.location)
return file_tags.read_cover(file_tags.resolve_path(loc.volume, loc.dir, loc.file)) return file_tags.read_cover(path) if path else None
def audio_path(self, track_id: str) -> "Path | None": def audio_path(self, track_id: str) -> "Path | None":
"""Resolve a track's audio file to an OS path (for playback streaming).""" """Resolve a track's audio file to an OS path (for playback streaming)."""
from . import file_tags
with self._lock: with self._lock:
entry = self._entry_by_key.get(track_id) entry = self._entry_by_key.get(track_id)
if entry is None or entry.location is None: if entry is None or entry.location is None:
return None return None
loc = entry.location return self._resolve(entry.location)
return file_tags.resolve_path(loc.volume, loc.dir, loc.file)
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.dirty = True
return len(key_remap)
def _entry_field_value(self, entry: Entrytype, field: str): def _entry_field_value(self, entry: Entrytype, field: str):
"""Read a single editable field's current value from the model, in the """Read a single editable field's current value from the model, in the
@@ -504,8 +628,9 @@ class PlaylistStore:
entry = self._entry_by_key.get(track_id) entry = self._entry_by_key.get(track_id)
if entry is None or entry.location is None: if entry is None or entry.location is None:
continue continue
loc = entry.location path = self._resolve(entry.location)
path = file_tags.resolve_path(loc.volume, loc.dir, loc.file) if path is None:
continue
r = None r = None
if track_id in self._track_edits: if track_id in self._track_edits:
meta = {f: self._entry_field_value(entry, f) for f in self._track_edits[track_id]} meta = {f: self._entry_field_value(entry, f) for f in self._track_edits[track_id]}
+29
View File
@@ -37,6 +37,35 @@ def update_prefs(patch: dict) -> dict:
return prefs 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: def get_last_collection() -> str | None:
val = load_prefs().get("last_collection") val = load_prefs().get("last_collection")
return val if isinstance(val, str) else None return val if isinstance(val, str) else None
+43 -1
View File
@@ -1,7 +1,7 @@
"""API response models (Pydantic).""" """API response models (Pydantic)."""
from __future__ import annotations from __future__ import annotations
from pydantic import BaseModel from pydantic import BaseModel, ConfigDict, Field
class Track(BaseModel): class Track(BaseModel):
@@ -221,3 +221,45 @@ class FsListing(BaseModel):
home: str home: str
dirs: list[FsEntry] dirs: list[FsEntry]
files: list[FsEntry] # .nml files only 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
backup: str | None = None # path of the .bak written before 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
+126
View File
@@ -386,5 +386,131 @@ check("boundary colliding with an existing hotcue is dropped", 60.0 not in [s["s
# No free slots => nothing placed. # 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) == []) 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") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "frontend", "name": "frontend",
"private": true, "private": true,
"version": "0.0.0", "version": "0.1.1",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
+4 -1
View File
@@ -1,6 +1,9 @@
[package] [package]
name = "app" 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" description = "A Tauri App"
authors = ["you"] authors = ["you"]
license = "" license = ""
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "Konduktor", "productName": "Konduktor",
"version": "0.1.0", "version": "../package.json",
"identifier": "com.liquidicestudios.konduktor", "identifier": "com.liquidicestudios.konduktor",
"build": { "build": {
"frontendDist": "../dist", "frontendDist": "../dist",
+10
View File
@@ -15,6 +15,7 @@ import { Toast, type ToastMsg } from './components/Toast'
import { CollectionPicker } from './components/CollectionPicker' import { CollectionPicker } from './components/CollectionPicker'
import { ContextMenu } from './components/ContextMenu' import { ContextMenu } from './components/ContextMenu'
import { EditTagsDialog } from './components/EditTagsDialog' import { EditTagsDialog } from './components/EditTagsDialog'
import { PathMappingDialog } from './components/PathMappingDialog'
import { PrepStrip } from './components/PrepStrip' import { PrepStrip } from './components/PrepStrip'
function applyFilters(tracks: Track[], f: Filters): Track[] { function applyFilters(tracks: Track[], f: Filters): Track[] {
@@ -47,6 +48,7 @@ export default function App() {
const [forcePicker, setForcePicker] = useState(false) const [forcePicker, setForcePicker] = useState(false)
const [menu, setMenu] = useState<{ track: Track; x: number; y: number } | null>(null) const [menu, setMenu] = useState<{ track: Track; x: number; y: number } | null>(null)
const [editing, setEditing] = useState<Track | null>(null) const [editing, setEditing] = useState<Track | null>(null)
const [showPaths, setShowPaths] = useState(false)
const [prepTrack, setPrepTrack] = useState<Track | null>(null) const [prepTrack, setPrepTrack] = useState<Track | null>(null)
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
@@ -258,6 +260,13 @@ export default function App() {
onError={onError} onError={onError}
/> />
)} )}
{showPaths && (
<PathMappingDialog
onClose={() => setShowPaths(false)}
onNotify={notify}
onError={onError}
/>
)}
{/* Prep strip spans the top of the window; the library sits below it. */} {/* Prep strip spans the top of the window; the library sits below it. */}
<PrepStrip track={prepTrack} playRequest={playRequest} onError={onError} onNotify={notify} /> <PrepStrip track={prepTrack} playRequest={playRequest} onError={onError} onNotify={notify} />
@@ -273,6 +282,7 @@ export default function App() {
columnVisibility={columnVisibility} columnVisibility={columnVisibility}
onColumnVisibilityChange={setColumnVisibility} onColumnVisibilityChange={setColumnVisibility}
onResetColumns={resetColumns} onResetColumns={resetColumns}
onOpenPathMapping={() => setShowPaths(true)}
/> />
{!isAll && ( {!isAll && (
<div className="flex items-center gap-3 border-b border-line bg-ink-900 px-4 py-2"> <div className="flex items-center gap-3 border-b border-line bg-ink-900 px-4 py-2">
+42
View File
@@ -158,6 +158,34 @@ export interface SaveResult {
playlists: number playlists: number
} }
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
backup: string | null
}
export interface PrefixSuggestions {
primary: string
groups: { prefix: string; count: number }[]
}
// API origin. In the packaged desktop app the frontend is served from // 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 // 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>) // injects window.__KONDUKTOR_API__ (the sidecar's http://127.0.0.1:<port>)
@@ -211,6 +239,20 @@ export const api = {
listDir: (path?: string) => listDir: (path?: string) =>
getJSON<FsListing>(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`), 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 (backup-first).
remapPaths: (from: string, to: string) =>
send<RemapResult>('POST', '/api/collection/remap-paths', { from, to }),
stats: () => getJSON<Stats>('/api/stats'), stats: () => getJSON<Stats>('/api/stats'),
facets: () => getJSON<Facets>('/api/facets'), facets: () => getJSON<Facets>('/api/facets'),
playlists: () => getJSON<PlaylistNode[]>('/api/playlists'), playlists: () => getJSON<PlaylistNode[]>('/api/playlists'),
@@ -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>
)
}
@@ -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.backup ? ` Backup: ${res.backup.split('/').pop()}` : ''),
)
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 (a backup is
written first). 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="max-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>
)
}
+69 -1
View File
@@ -4,6 +4,7 @@ import { api, type Track, type TrackCues } from '../api'
import { analyzeWaveform, type WaveColumn } from '../lib/waveform' import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
import { ScratchEngine } from '../lib/scratchEngine' import { ScratchEngine } from '../lib/scratchEngine'
import { PlaybackEngine } from '../lib/playbackEngine' import { PlaybackEngine } from '../lib/playbackEngine'
import { BeatJumpControls, BEAT_JUMP_SIZES } from './BeatJumpControls'
import { GridControls } from './GridControls' import { GridControls } from './GridControls'
import { HotcueBar } from './HotcueBar' import { HotcueBar } from './HotcueBar'
import { LoopControls } from './LoopControls' import { LoopControls } from './LoopControls'
@@ -57,6 +58,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const [selectedSlot, setSelectedSlot] = useState<number | null>(null) const [selectedSlot, setSelectedSlot] = useState<number | null>(null)
const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only) const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only)
const [secPerView, setSecPerView] = useState(DEFAULT_SEC) // main-waveform zoom (persisted) 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). // Loop state (transient — persisted only when saved as a hotcue later).
const [loopRegion, setLoopRegion] = useState<{ start: number; end: number } | null>(null) const [loopRegion, setLoopRegion] = useState<{ start: number; end: number } | null>(null)
@@ -109,6 +111,26 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
} }
}, [secPerView]) }, [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 => { const getCtx = (): AudioContext => {
if (!audioCtxRef.current) { if (!audioCtxRef.current) {
audioCtxRef.current = new (window.AudioContext ?? audioCtxRef.current = new (window.AudioContext ??
@@ -360,6 +382,31 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
seek(t) 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 ---------------------------------------------------------- // ---- scratch ----------------------------------------------------------
const finalizeScratch = () => { const finalizeScratch = () => {
cancelAnimationFrame(scratchRafRef.current) cancelAnimationFrame(scratchRafRef.current)
@@ -627,6 +674,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
deleteHotcueSlot, deleteHotcueSlot,
onCuePress, onCuePress,
onCueRelease, onCueRelease,
beatJump,
}) })
shortcutsRef.current = { shortcutsRef.current = {
toggle, toggle,
@@ -635,6 +683,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
deleteHotcueSlot, deleteHotcueSlot,
onCuePress, onCuePress,
onCueRelease, onCueRelease,
beatJump,
} }
useEffect(() => { useEffect(() => {
const onKey = (e: KeyboardEvent) => { const onKey = (e: KeyboardEvent) => {
@@ -653,6 +702,16 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
shortcutsRef.current.onCuePress() shortcutsRef.current.onCuePress()
return 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])$/) const digit = e.code.match(/^(?:Digit|Numpad)([1-8])$/)
if (digit) { if (digit) {
e.preventDefault() e.preventDefault()
@@ -678,6 +737,8 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
// ---- beatgrid --------------------------------------------------------- // ---- beatgrid ---------------------------------------------------------
const gridBpm = cueData?.bpm ?? null const gridBpm = cueData?.bpm ?? null
const gridAnchor = cueData?.grid_anchor ?? 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 }) => { const editGrid = async (patch: { bpm?: number; anchor?: number }) => {
if (!track) return if (!track) return
@@ -737,7 +798,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const activeLoop = loopActive && loopRegion ? loopRegion : null const activeLoop = loopActive && loopRegion ? loopRegion : null
return ( return (
<div className="flex h-[23rem] 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 */} {/* Controls */}
<div className="flex w-72 shrink-0 flex-col gap-3 bg-ink-900 px-4 py-3"> <div className="flex w-72 shrink-0 flex-col gap-3 bg-ink-900 px-4 py-3">
<div className="min-w-0"> <div className="min-w-0">
@@ -817,6 +878,13 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
{fmt(current)} / {fmt(duration)} {fmt(current)} / {fmt(duration)}
</div> </div>
</div> </div>
<BeatJumpControls
beats={jumpBeats}
onStep={stepJumpSize}
onJump={beatJump}
disabled={!canBeatJump}
/>
</div> </div>
{/* Waveforms + loop/hotcue controls. */} {/* Waveforms + loop/hotcue controls. */}
+64
View File
@@ -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 -7
View File
@@ -2,14 +2,20 @@ import { useEffect } from 'react'
export interface ToastMsg { export interface ToastMsg {
id: number id: number
kind: 'success' | 'error' kind: 'success' | 'error' | 'warning'
text: string 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 }) { export function Toast({ toast, onClose }: { toast: ToastMsg | null; onClose: () => void }) {
useEffect(() => { useEffect(() => {
if (!toast) return if (!toast) return
const t = setTimeout(onClose, toast.kind === 'error' ? 6000 : 4000) const t = setTimeout(onClose, toast.kind === 'success' ? 4000 : 6000)
return () => clearTimeout(t) return () => clearTimeout(t)
}, [toast, onClose]) }, [toast, onClose])
@@ -17,11 +23,7 @@ export function Toast({ toast, onClose }: { toast: ToastMsg | null; onClose: ()
return ( return (
<div className="pointer-events-none fixed inset-x-0 top-4 z-50 flex justify-center"> <div className="pointer-events-none fixed inset-x-0 top-4 z-50 flex justify-center">
<div <div
className={`pointer-events-auto max-w-lg rounded-lg border px-4 py-2.5 text-sm shadow-xl ${ className={`pointer-events-auto max-w-lg rounded-lg border px-4 py-2.5 text-sm shadow-xl ${KIND_CLS[toast.kind]}`}
toast.kind === 'error'
? 'border-pink/40 bg-ink-800 text-pink'
: 'border-mint/40 bg-ink-800 text-mint'
}`}
> >
{toast.text} {toast.text}
</div> </div>
+4
View File
@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query'
import type { VisibilityState } from '@tanstack/react-table' import type { VisibilityState } from '@tanstack/react-table'
import { api } from '../api' import { api } from '../api'
import { ColumnsMenu } from './ColumnsMenu' import { ColumnsMenu } from './ColumnsMenu'
import { SettingsMenu } from './SettingsMenu'
export interface Filters { export interface Filters {
search: string search: string
@@ -29,6 +30,7 @@ interface Props {
columnVisibility: VisibilityState columnVisibility: VisibilityState
onColumnVisibilityChange: (v: VisibilityState) => void onColumnVisibilityChange: (v: VisibilityState) => void
onResetColumns: () => void onResetColumns: () => void
onOpenPathMapping: () => void
} }
const selectCls = const selectCls =
@@ -40,6 +42,7 @@ export function Toolbar({
columnVisibility, columnVisibility,
onColumnVisibilityChange, onColumnVisibilityChange,
onResetColumns, onResetColumns,
onOpenPathMapping,
}: Props) { }: Props) {
const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets }) const { data: facets } = useQuery({ queryKey: ['facets'], queryFn: api.facets })
const set = (patch: Partial<Filters>) => onChange({ ...filters, ...patch }) const set = (patch: Partial<Filters>) => onChange({ ...filters, ...patch })
@@ -145,6 +148,7 @@ export function Toolbar({
onChange={onColumnVisibilityChange} onChange={onColumnVisibilityChange}
onReset={onResetColumns} onReset={onResetColumns}
/> />
<SettingsMenu onOpenPathMapping={onOpenPathMapping} />
</div> </div>
</div> </div>
) )
+34 -8
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState, type MutableRefObject } from 'react'
import { import {
flexRender, flexRender,
getCoreRowModel, getCoreRowModel,
@@ -119,12 +119,21 @@ function RowCells({ row }: { row: Row<Track> }) {
} }
/** One draggable + resizable header cell. `sortable` is false in playlists, /** One draggable + resizable header cell. `sortable` is false in playlists,
* where the manual order stands (the header still reorders/resizes columns). */ * where the manual order stands (the header still reorders/resizes columns).
function SortableHeader({ header }: { header: Header<Track, unknown> }) { * `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({ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: header.column.id, id: header.column.id,
}) })
const sorted = header.column.getIsSorted() const sorted = header.column.getIsSorted()
const toggleSort = header.column.getToggleSortingHandler()
return ( return (
<div <div
ref={setNodeRef} ref={setNodeRef}
@@ -140,7 +149,12 @@ function SortableHeader({ header }: { header: Header<Track, unknown> }) {
<button <button
{...attributes} {...attributes}
{...listeners} {...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" 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())} {flexRender(header.column.columnDef.header, header.getContext())}
@@ -180,12 +194,24 @@ function HeaderRow({
hasPlay: boolean hasPlay: boolean
selection?: Selection 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 ( return (
<DndContext <DndContext
sensors={sensors} sensors={sensors}
collisionDetection={closestCenter} collisionDetection={closestCenter}
modifiers={[restrictToHorizontalAxis]} modifiers={[restrictToHorizontalAxis]}
onDragEnd={onColumnDragEnd} 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"> <div className="sticky top-0 z-10 flex border-b border-line bg-ink-850">
{lead && <span className="w-8 shrink-0" />} {lead && <span className="w-8 shrink-0" />}
@@ -208,7 +234,7 @@ function HeaderRow({
strategy={horizontalListSortingStrategy} strategy={horizontalListSortingStrategy}
> >
{headers.map((header) => ( {headers.map((header) => (
<SortableHeader key={header.id} header={header} /> <SortableHeader key={header.id} header={header} draggedRef={draggedRef} />
))} ))}
</SortableContext> </SortableContext>
{trail && <span className="w-10 shrink-0" />} {trail && <span className="w-10 shrink-0" />}
@@ -259,7 +285,7 @@ export function TrackTable({
}) })
const virtualRows = virtualizer.getVirtualItems() 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 headers = table.getHeaderGroups()[0].headers
const hasPlay = !!onPlay const hasPlay = !!onPlay
const leadWidth = 40 + (hasPlay ? 36 : 0) const leadWidth = 40 + (hasPlay ? 36 : 0)
@@ -446,7 +472,7 @@ export function PlaylistTable({
}) })
const rows = table.getRowModel().rows const rows = table.getRowModel().rows
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } })) const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }))
const headers = table.getHeaderGroups()[0].headers const headers = table.getHeaderGroups()[0].headers
const hasPlay = !!onPlay const hasPlay = !!onPlay
const leadWidth = 32 + 40 + (hasPlay ? 36 : 0) const leadWidth = 32 + 40 + (hasPlay ? 36 : 0)