From d848efaf501b43ed31f20895da476f89097e259d Mon Sep 17 00:00:00 2001 From: Ben Date: Sat, 4 Jul 2026 22:43:00 +0200 Subject: [PATCH] Made UI improvements --- .gitignore | 3 + backend/konduktor/discovery.py | 62 +++++ backend/konduktor/main.py | 18 ++ backend/konduktor/prefs.py | 39 +++ backend/konduktor/schemas.py | 13 + frontend/src/App.tsx | 10 +- frontend/src/api.ts | 14 + frontend/src/components/CollectionPicker.tsx | 267 +++++++++++++------ frontend/src/components/MainWaveform.tsx | 37 ++- frontend/src/components/OverviewWaveform.tsx | 29 +- frontend/src/components/PrepStrip.tsx | 84 +++++- frontend/src/components/Sidebar.tsx | 9 +- frontend/src/components/TrackTable.tsx | 36 ++- frontend/src/lib/cues.ts | 27 ++ frontend/src/lib/waveform.ts | 33 ++- 15 files changed, 563 insertions(+), 118 deletions(-) create mode 100644 backend/konduktor/discovery.py create mode 100644 backend/konduktor/prefs.py diff --git a/.gitignore b/.gitignore index 37209fa..6571116 100644 --- a/.gitignore +++ b/.gitignore @@ -35,3 +35,6 @@ Thumbs.db *.log .env .env.* + +# Local user preferences (not shared) +backend/userprefs.json diff --git a/backend/konduktor/discovery.py b/backend/konduktor/discovery.py new file mode 100644 index 0000000..9c53270 --- /dev/null +++ b/backend/konduktor/discovery.py @@ -0,0 +1,62 @@ +"""Locate Traktor collections in their default install locations. + +Traktor stores each version's data under a versioned folder: + ~/Documents/Native Instruments/Traktor /collection.nml +This is the same relative path on macOS and Windows (both under the user's +Documents folder), so a single glob covers both. +""" +from __future__ import annotations + +import re +from pathlib import Path + +_VERSION_RE = re.compile(r"(\d+(?:\.\d+)*)") + + +def _traktor_root() -> Path: + return Path.home() / "Documents" / "Native Instruments" + + +def _version_key(version: str | None) -> tuple[int, ...]: + """Sortable tuple for a dotted version string; missing/odd → lowest.""" + if not version: + return (0,) + try: + return tuple(int(p) for p in version.split(".")) + except ValueError: + return (0,) + + +def describe(path: Path) -> dict: + """Build a candidate record for a collection.nml path. The label/version + come from the parent folder name (e.g. 'Traktor 4.5.0').""" + parent = path.parent.name + m = _VERSION_RE.search(parent) + exists = path.is_file() + return { + "path": str(path), + "label": parent or path.name, + "version": m.group(1) if m else None, + "modified": (path.stat().st_mtime if exists else None), + "exists": exists, + } + + +def detect_collections() -> list[dict]: + """All Traktor collection.nml files found in default locations, newest + Traktor version first (then most-recently-modified).""" + root = _traktor_root() + found: list[dict] = [] + if not root.is_dir(): + return found + for d in sorted(root.iterdir()): + if not d.is_dir() or not d.name.lower().startswith("traktor"): + continue + nml = d / "collection.nml" + if nml.is_file(): + found.append(describe(nml)) + found.sort( + key=lambda c: (_version_key(c["version"]), c["modified"] or 0.0), + reverse=True, + ) + return found diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 6b607ef..da4d53f 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -13,9 +13,13 @@ 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 .collection_service import CollectionService +from .discovery import describe, detect_collections from .playlist_store import PlaylistError, PlaylistStore from .schemas import ( + CollectionCandidate, + CollectionOptions, CollectionStatus, CreatePlaylist, CuePoint, @@ -121,9 +125,23 @@ def open_collection(body: OpenCollection) -> CollectionStatus: raise HTTPException(400, f"Not a valid Traktor collection: {ex}") except Exception as ex: # noqa: BLE001 raise HTTPException(400, f"Could not parse as a Traktor collection: {ex}") + prefs.set_last_collection(str(path)) return collection_status() +@app.get("/api/collection/options", response_model=CollectionOptions) +def collection_options() -> CollectionOptions: + """Startup shortcuts for the picker: the best auto-detected Traktor + collection and the last one opened (may no longer exist → exists=False).""" + detected = detect_collections() + auto = CollectionCandidate(**detected[0]) if detected else None + recent = None + last = prefs.get_last_collection() + if last: + recent = CollectionCandidate(**describe(Path(last))) + return CollectionOptions(auto=auto, recent=recent) + + @app.get("/api/fs/list", response_model=FsListing) def fs_list(path: str | None = None) -> FsListing: """List directories and .nml files for the in-app file browser.""" diff --git a/backend/konduktor/prefs.py b/backend/konduktor/prefs.py new file mode 100644 index 0000000..4c60dcc --- /dev/null +++ b/backend/konduktor/prefs.py @@ -0,0 +1,39 @@ +"""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". +""" +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" + + +def load_prefs() -> dict: + try: + data = json.loads(_PREFS_PATH.read_text()) + return data if isinstance(data, dict) else {} + except (OSError, ValueError): + return {} + + +def save_prefs(prefs: dict) -> None: + try: + _PREFS_PATH.write_text(json.dumps(prefs, indent=2)) + except OSError: + pass # non-fatal — prefs are a convenience, not a requirement + + +def get_last_collection() -> str | None: + val = load_prefs().get("last_collection") + return val if isinstance(val, str) else None + + +def set_last_collection(path: str) -> None: + prefs = load_prefs() + prefs["last_collection"] = path + save_prefs(prefs) diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index fccd3f2..46c9ecf 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -178,6 +178,19 @@ class OpenCollection(BaseModel): path: str +class CollectionCandidate(BaseModel): + path: str + label: str # folder name, e.g. "Traktor 4.5.0" + version: str | None = None # "4.5.0" + modified: float | None = None # collection.nml mtime, epoch seconds + exists: bool = True + + +class CollectionOptions(BaseModel): + auto: CollectionCandidate | None = None # best auto-detected (latest version) + recent: CollectionCandidate | None = None # last opened (from userprefs) + + class FsEntry(BaseModel): name: str path: str diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 5996eb7..4c65f46 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -45,6 +45,12 @@ export default function App() { const [menu, setMenu] = useState<{ track: Track; x: number; y: number } | null>(null) const [editing, setEditing] = useState(null) const [prepTrack, setPrepTrack] = useState(null) + const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays + + const playTrack = useCallback((t: Track) => { + setPrepTrack(t) + setPlayRequest((n) => n + 1) + }, []) const notify = useCallback((kind: ToastMsg['kind'], text: string) => { setToast({ id: Date.now(), kind, text }) @@ -144,7 +150,7 @@ export default function App() { )} {/* Prep strip spans the top of the window; the library sits below it. */} - +
@@ -183,6 +189,8 @@ export default function App() { allSelected: selected.size > 0 && selected.size === filtered.length, }} onRowContextMenu={(track, x, y) => setMenu({ track, x, y })} + onPlay={playTrack} + activeTrackId={prepTrack?.id ?? null} /> ) ) : ( diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 3d45261..b9e0431 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -125,6 +125,19 @@ export interface CollectionStatus { playlists: number | null } +export interface CollectionCandidate { + path: string + label: string + version: string | null + modified: number | null // epoch seconds + exists: boolean +} + +export interface CollectionOptions { + auto: CollectionCandidate | null // best auto-detected (latest Traktor version) + recent: CollectionCandidate | null // last opened (may no longer exist) +} + export interface FsEntry { name: string path: string @@ -183,6 +196,7 @@ export const api = { collection: () => getJSON('/api/collection'), openCollection: (path: string) => send('POST', '/api/collection/open', { path }), + collectionOptions: () => getJSON('/api/collection/options'), listDir: (path?: string) => getJSON(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`), diff --git a/frontend/src/components/CollectionPicker.tsx b/frontend/src/components/CollectionPicker.tsx index 27efc33..6eefce7 100644 --- a/frontend/src/components/CollectionPicker.tsx +++ b/frontend/src/components/CollectionPicker.tsx @@ -7,13 +7,55 @@ interface Props { onCancel?: () => void // shown only when switching from an already-loaded collection } +function formatWhen(sec: number | null): string { + if (!sec) return 'unknown' + return new Date(sec * 1000).toLocaleString(undefined, { + dateStyle: 'medium', + timeStyle: 'short', + }) +} + +function OptionCard({ + icon, + title, + subtitle, + disabled, + busy, + onClick, +}: { + icon: string + title: string + subtitle: string + disabled?: boolean + busy?: boolean + onClick: () => void +}) { + return ( + + ) +} + export function CollectionPicker({ onOpened, onCancel }: Props) { + const [mode, setMode] = useState<'choose' | 'browse'>('choose') const [dir, setDir] = useState(undefined) // undefined => home const [manual, setManual] = useState('') + const options = useQuery({ queryKey: ['collectionOptions'], queryFn: api.collectionOptions }) const listing = useQuery({ queryKey: ['fs', dir ?? '~'], queryFn: () => api.listDir(dir), + enabled: mode === 'browse', }) const open = useMutation({ @@ -22,23 +64,34 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { }) const data = listing.data + const opt = options.data + const auto = opt?.auto ?? null + const recent = opt?.recent ?? null + const recentAvailable = !!recent && recent.exists return (
{/* Header */}
-
- K -
Select your Traktor collection
- Choose a collection.nml file to open. + {mode === 'choose' + ? 'Open automatically, resume your last one, or browse.' + : 'Choose a collection.nml file to open.'}
+ {mode === 'browse' && ( + + )} {onCancel && ( - - - {data?.path ?? 'Loading…'} - -
- - {/* Listing */} -
- {listing.isLoading &&
Loading…
} - {data && data.dirs.length === 0 && data.files.length === 0 && ( -
No folders or .nml files here.
- )} - {data?.dirs.map((d) => ( - - ))} - {data?.files.map((f) => ( - - ))} -
- - {/* Manual path + errors */} -
- {open.isError && ( -
- {(open.error as Error).message} -
- )} -
- setManual(e.target.value)} - onKeyDown={(e) => { - if (e.key === 'Enter' && manual.trim()) open.mutate(manual.trim()) - }} - placeholder="…or paste a full path to collection.nml" - className="min-w-0 flex-1 rounded-md border border-line bg-ink-850 px-3 py-2 font-mono text-xs text-text outline-none placeholder:text-faint focus:border-accent" + {mode === 'choose' ? ( + /* ---- Chooser ---- */ +
+ auto && open.mutate(auto.path)} /> - + recent && open.mutate(recent.path)} + /> + setMode('browse')} + /> + + {open.isError && ( +
+ {(open.error as Error).message} +
+ )}
-
+ ) : ( + /* ---- Manual browser ---- */ + <> + {/* Path bar */} +
+ + + + {data?.path ?? 'Loading…'} + +
+ + {/* Listing */} +
+ {listing.isLoading &&
Loading…
} + {data && data.dirs.length === 0 && data.files.length === 0 && ( +
No folders or .nml files here.
+ )} + {data?.dirs.map((d) => ( + + ))} + {data?.files.map((f) => ( + + ))} +
+ + {/* Manual path + errors */} +
+ {open.isError && ( +
+ {(open.error as Error).message} +
+ )} +
+ setManual(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && manual.trim()) open.mutate(manual.trim()) + }} + placeholder="…or paste a full path to collection.nml" + className="min-w-0 flex-1 rounded-md border border-line bg-ink-850 px-3 py-2 font-mono text-xs text-text outline-none placeholder:text-faint focus:border-accent" + /> + +
+
+ + )}
) diff --git a/frontend/src/components/MainWaveform.tsx b/frontend/src/components/MainWaveform.tsx index db2a5a8..b4b0a51 100644 --- a/frontend/src/components/MainWaveform.tsx +++ b/frontend/src/components/MainWaveform.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState } from 'react' import type { CuePoint } from '../api' -import { drawBeatgrid, drawCues, drawLoop } from '../lib/cues' +import { drawBeatgrid, drawCuePoint, drawCues, drawLoop } from '../lib/cues' import { paintWave, type WaveColumn } from '../lib/waveform' interface Props { @@ -8,6 +8,7 @@ interface Props { currentTime: number duration: number cues: CuePoint[] + cuePoint: number | null bpm: number | null gridAnchor: number | null loop: { start: number; end: number } | null @@ -34,6 +35,7 @@ export function MainWaveform({ currentTime, duration, cues, + cuePoint, bpm, gridAnchor, loop, @@ -83,12 +85,37 @@ export function MainWaveform({ if (cues.length) { drawCues(ctx, cues, w, h, dpr, timeToX, true) } + if (cuePoint != null && cuePoint >= startSec && cuePoint <= endSec) { + drawCuePoint(ctx, Math.round(timeToX(cuePoint)), h, dpr) + } } - // Fixed centre playhead. - const pw = Math.max(2, Math.round(2 * dpr)) - ctx.fillStyle = '#e6e9ef' - ctx.fillRect(Math.floor(w / 2) - Math.floor(pw / 2), 0, pw, h) + // Fixed centre playhead — red core with a translucent black outline so it + // separates from the waveform, plus inward-pointing triangle caps top and + // bottom that anchor the eye in the quiet margins. + const core = Math.max(2, Math.round(2 * dpr)) + const edge = Math.max(1, Math.round(dpr)) + const cx = Math.floor(w / 2) + const px = cx - Math.floor(core / 2) + ctx.fillStyle = 'rgba(0,0,0,0.5)' + ctx.fillRect(px - edge, 0, core + edge * 2, h) + ctx.fillStyle = '#ff3b30' + ctx.fillRect(px, 0, core, h) + + const cap = Math.round(6 * dpr) + ctx.fillStyle = '#ff3b30' + ctx.beginPath() + ctx.moveTo(cx - cap, 0) + ctx.lineTo(cx + cap, 0) + ctx.lineTo(cx, cap) + ctx.closePath() + ctx.fill() + ctx.beginPath() + ctx.moveTo(cx - cap, h) + ctx.lineTo(cx + cap, h) + ctx.lineTo(cx, h - cap) + ctx.closePath() + ctx.fill() } const drawRef = useRef(draw) diff --git a/frontend/src/components/OverviewWaveform.tsx b/frontend/src/components/OverviewWaveform.tsx index 2ecb206..f399e61 100644 --- a/frontend/src/components/OverviewWaveform.tsx +++ b/frontend/src/components/OverviewWaveform.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef } from 'react' import type { CuePoint } from '../api' -import { drawCues, drawLoop } from '../lib/cues' +import { drawCuePoint, drawCues, drawLoop } from '../lib/cues' import { paintWave, type WaveColumn } from '../lib/waveform' interface Props { @@ -8,6 +8,7 @@ interface Props { currentTime: number duration: number cues: CuePoint[] + cuePoint: number | null loop: { start: number; end: number } | null onSeek: (t: number) => void } @@ -17,13 +18,22 @@ interface Props { * offscreen canvas) with a moving playhead + dimmed played region. Click to * seek anywhere in the track. */ -export function OverviewWaveform({ cols, currentTime, duration, cues, loop, onSeek }: Props) { +export function OverviewWaveform({ + cols, + currentTime, + duration, + cues, + cuePoint, + loop, + onSeek, +}: Props) { const wrapRef = useRef(null) const canvasRef = useRef(null) const cacheRef = useRef(null) const timeRef = useRef(0) const durRef = useRef(0) const cuesRef = useRef(cues) + const cuePointRef = useRef(cuePoint) const loopRef = useRef(loop) const renderCache = useCallback(() => { @@ -60,9 +70,15 @@ export function OverviewWaveform({ cols, currentTime, duration, cues, loop, onSe if (lp) drawLoop(ctx, (lp.start / dur) * w, (lp.end / dur) * w, h, dpr) // Cue markers (no beatgrid/labels in the overview). drawCues(ctx, cuesRef.current, w, h, dpr, (t) => (t / dur) * w, false) + const cp = cuePointRef.current + if (cp != null) drawCuePoint(ctx, Math.round((cp / dur) * w), h, dpr) const pw = Math.max(2, Math.round(2 * dpr)) - ctx.fillStyle = '#e6e9ef' - ctx.fillRect(px - Math.floor(pw / 2), 0, pw, h) + const px0 = px - Math.floor(pw / 2) + const po = Math.max(1, Math.round(dpr)) + ctx.fillStyle = 'rgba(0,0,0,0.6)' + ctx.fillRect(px0 - po, 0, pw + po * 2, h) + ctx.fillStyle = '#ff3b30' + ctx.fillRect(px0, 0, pw, h) } }, []) @@ -97,12 +113,13 @@ export function OverviewWaveform({ cols, currentTime, duration, cues, loop, onSe draw() }, [currentTime, duration, draw]) - // Redraw when the cue set or loop changes. + // Redraw when the cue set, cue point, or loop changes. useEffect(() => { cuesRef.current = cues + cuePointRef.current = cuePoint loopRef.current = loop draw() - }, [cues, loop, draw]) + }, [cues, cuePoint, loop, draw]) const seek = (e: React.MouseEvent) => { if (!duration) return diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 380495e..cdcf57e 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -13,6 +13,8 @@ import { OverviewWaveform } from './OverviewWaveform' interface Props { /** The track currently loaded into the prep deck, if any. */ track: Track | null + /** Bumped by the library's per-row play button to load + auto-play. */ + playRequest?: number onError?: (msg: string) => void } @@ -39,7 +41,7 @@ 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, onError }: Props) { +export function PrepStrip({ track, playRequest = 0, onError }: Props) { const qc = useQueryClient() const [playing, setPlaying] = useState(false) const [current, setCurrent] = useState(0) @@ -50,6 +52,7 @@ export function PrepStrip({ track, onError }: Props) { const [cueData, setCueData] = useState(null) const [snap, setSnap] = useState(true) const [selectedSlot, setSelectedSlot] = useState(null) + const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only) // Loop state (transient — persisted only when saved as a hotcue later). const [loopRegion, setLoopRegion] = useState<{ start: number; end: number } | null>(null) @@ -65,6 +68,8 @@ export function PrepStrip({ track, onError }: Props) { const wasPlayingRef = useRef(false) const scratchRafRef = useRef(0) const engagedRef = useRef(false) // scratch engine is dragging or coasting + const pendingPlayRef = useRef(false) // a play was requested; start once ready + const loadedIdRef = useRef(null) // trackId whose buffer is loaded const trackId = track?.id ?? null @@ -100,6 +105,7 @@ export function PrepStrip({ track, onError }: Props) { setLoopRegion(null) setLoopActive(false) setActiveBeats(null) + setCuePoint(0) loopInRef.current = null }, [trackId]) @@ -133,6 +139,13 @@ export function PrepStrip({ track, onError }: Props) { playbackRef.current.load(ctx, res.buffer) setDuration(res.buffer.duration) setReady(true) + loadedIdRef.current = trackId + // A play was requested (library row button) → start now that it's ready. + if (pendingPlayRef.current) { + pendingPlayRef.current = false + playbackRef.current.play() + setPlaying(true) + } }) .catch(() => { if (!cancelled) setWaveStatus('error') @@ -180,6 +193,43 @@ export function PrepStrip({ track, onError }: Props) { setCurrent(eng.getPosition()) } + // 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 = () => { + const eng = playbackRef.current + if (!eng || !eng.ready) return + getCtx() + if (eng.playing) { + eng.pause() + eng.seek(cuePoint) + setPlaying(false) + setCurrent(cuePoint) + } else if (Math.abs(current - cuePoint) > 0.03) { + setCuePoint(current) + } else { + eng.play() + setPlaying(true) + } + } + + // A library row's play button bumps `playRequest`: load (if needed) + play. + // If the requested track is already loaded and ready, start immediately; + // otherwise flag it and the analysis effect starts playback once ready. + useEffect(() => { + if (playRequest === 0) return + pendingPlayRef.current = true + const eng = playbackRef.current + if (loadedIdRef.current === trackId && eng?.ready) { + pendingPlayRef.current = false + getCtx() + eng.play() + setPlaying(true) + setCurrent(eng.getPosition()) + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [playRequest]) + // Follow the Web Audio clock while playing (high-res → smooth playhead). useEffect(() => { if (!playing) return @@ -494,16 +544,38 @@ export function PrepStrip({ track, onError }: Props) { /> )} -
+
+ -
+
{fmt(current)} / {fmt(duration)}
@@ -528,6 +600,7 @@ export function PrepStrip({ track, onError }: Props) { currentTime={current} duration={duration} cues={cueData?.cues ?? []} + cuePoint={cuePoint} bpm={cueData?.bpm ?? null} gridAnchor={cueData?.grid_anchor ?? null} loop={activeLoop} @@ -549,6 +622,7 @@ export function PrepStrip({ track, onError }: Props) { currentTime={current} duration={duration} cues={cueData?.cues ?? []} + cuePoint={cuePoint} loop={activeLoop} onSeek={seekManual} /> diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index cbce89f..db2c806 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -184,14 +184,7 @@ export function Sidebar({ source, onSelect, onError }: Props) { return (