diff --git a/app/api/jobs.py b/app/api/jobs.py index 34d3343b..2b00f6ea 100644 --- a/app/api/jobs.py +++ b/app/api/jobs.py @@ -10,7 +10,7 @@ from pathlib import Path from fastapi import APIRouter, HTTPException, Request -from pydantic import BaseModel +from pydantic import BaseModel, field_validator from app.core.config import ( JOB_ID_RE, @@ -271,6 +271,82 @@ def cancel_job(job_id: str) -> dict: return job.to_state() +_SECTION_ID_RE = re.compile(r"^[a-zA-Z0-9_\-]{1,64}$") +_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{3,8}$") + + +class SectionItem(BaseModel): + id: str + name: str + start: float + end: float + color: str + + @field_validator("id") + @classmethod + def _check_id(cls, v: str) -> str: + if not _SECTION_ID_RE.match(v): + raise ValueError("invalid section id") + return v + + @field_validator("name") + @classmethod + def _check_name(cls, v: str) -> str: + return v.strip()[:64] or "Section" + + @field_validator("color") + @classmethod + def _check_color(cls, v: str) -> str: + if not _COLOR_RE.match(v): + raise ValueError("invalid color") + return v + + @field_validator("start", "end") + @classmethod + def _check_time(cls, v: float) -> float: + if not (0 <= v < 86400): + raise ValueError("time out of range") + return round(v, 3) + + +class SectionsBody(BaseModel): + sections: list[SectionItem] + + +@router.patch("/{job_id}/sections") +def update_sections(job_id: str, body: SectionsBody) -> dict: + if not JOB_ID_RE.match(job_id): + raise HTTPException(status_code=404, detail="job not found") + job = registry_get(job_id) + if job is None: + raise HTTPException(status_code=404, detail="job not found") + + validated = [s.model_dump() for s in body.sections] + job.sections = validated + + job_dir = (JOBS_DIR / job_id).resolve() + if not job_dir.is_relative_to(JOBS_DIR.resolve()): + raise HTTPException(status_code=404, detail="job not found") + meta_path = job_dir / "metadata.json" + + meta: dict = {} + if meta_path.is_file(): + try: + meta = json.loads(meta_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + pass + meta["sections"] = validated + try: + meta_path.write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8") + except OSError as exc: + logger.exception("failed to write sections for %s: %s", job_id, exc) + raise HTTPException(status_code=500, detail="failed to save sections") from exc + + registry_persist(JOBS_DIR) + + return {"job_id": job_id, "sections": validated} + + @router.delete("/{job_id}") def delete_job(job_id: str) -> dict[str, str]: if not JOB_ID_RE.match(job_id): diff --git a/app/api/stems.py b/app/api/stems.py index b66ee557..407c6480 100644 --- a/app/api/stems.py +++ b/app/api/stems.py @@ -1,9 +1,11 @@ from __future__ import annotations +import asyncio + from fastapi import APIRouter, HTTPException -from fastapi.responses import FileResponse +from fastapi.responses import FileResponse, StreamingResponse -from app.core.config import JOB_ID_RE, JOBS_DIR, STEM_NAMES +from app.core.config import JOB_ID_RE, JOBS_DIR, STEM_NAMES, ffmpeg_executable from app.core.registry import get as registry_get router = APIRouter(tags=["stems"]) @@ -30,3 +32,43 @@ def get_stem(job_id: str, name: str) -> FileResponse: if not path.is_file() or not path.is_relative_to(JOBS_DIR.resolve()): raise HTTPException(status_code=404, detail="stem not found") return FileResponse(path, media_type="audio/wav", filename=f"{name}.wav") + + +@router.get("/jobs/{job_id}/stems/{name}.mp3") +async def get_stem_mp3(job_id: str, name: str) -> StreamingResponse: + if not JOB_ID_RE.match(job_id): + raise HTTPException(status_code=404, detail="job not found") + if name not in _ALLOWED_NAMES: + raise HTTPException(status_code=404, detail="unknown stem") + job = registry_get(job_id) + if job is None or job.status != "done": + raise HTTPException(status_code=404, detail="job not ready") + wav_path = (JOBS_DIR / job_id / "stems" / f"{name}.wav").resolve() + if not wav_path.is_file() or not wav_path.is_relative_to(JOBS_DIR.resolve()): + raise HTTPException(status_code=404, detail="stem not found") + + async def _stream(): + proc = await asyncio.create_subprocess_exec( + ffmpeg_executable(), + "-nostdin", "-loglevel", "error", + "-i", str(wav_path), + "-q:a", "2", # VBR ~190 kbps + "-f", "mp3", "pipe:1", + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL, + ) + try: + while True: + chunk = await proc.stdout.read(65536) + if not chunk: + break + yield chunk + finally: + proc.stdout.close() + await proc.wait() + + return StreamingResponse( + _stream(), + media_type="audio/mpeg", + headers={"Content-Disposition": f'attachment; filename="{name}.mp3"'}, + ) diff --git a/app/core/models.py b/app/core/models.py index e16dda6a..d2e66584 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -27,6 +27,11 @@ class Job: key_confidence: int | None = None # 0-100 percent lufs: float | None = None # ITU-R BS.1770 integrated loudness (dB) peak_db: float | None = None # sample peak in dBFS (close to true peak) + dynamic_range: float | None = None # peak_db - integrated LUFS (dB) + tempo_stability: int | None = None # 0-100, beat interval consistency + stem_presence: dict[str, int] | None = None # per-stem RMS 0-100 + sections: list[dict] | None = None # [{id, name, start, end, color}] + tags: list[str] | None = None # YouTube tags + categories, lowercased, max 8 stems: list[dict[str, str]] = field(default_factory=list) # Subset of stems the user chose at submit. The pipeline produces all # 6 regardless (Demucs htdemucs_6s is fixed), but after collect we @@ -58,11 +63,17 @@ def to_state(self) -> dict[str, Any]: "key_confidence": self.key_confidence, "lufs": self.lufs, "peak_db": self.peak_db, + "dynamic_range": self.dynamic_range, + "tempo_stability": self.tempo_stability, + "stem_presence": self.stem_presence, + "sections": self.sections, + "tags": self.tags, "stems": self.stems, "selected_stems": self.selected_stems, "mix_url": self.mix_url, "source_url": self.source_url, "error": self.error, + "created_at": self.created_at, } def to_record(self) -> dict[str, Any]: diff --git a/app/core/registry.py b/app/core/registry.py index ce8661cd..37ca4829 100644 --- a/app/core/registry.py +++ b/app/core/registry.py @@ -153,6 +153,11 @@ def _recover_done_job(job_dir: Path) -> Job | None: key_confidence=meta.get("key_confidence"), lufs=meta.get("lufs"), peak_db=meta.get("peak_db"), + dynamic_range=meta.get("dynamic_range"), + tempo_stability=meta.get("tempo_stability"), + stem_presence=meta.get("stem_presence"), + sections=meta.get("sections"), + tags=meta.get("tags"), ) diff --git a/app/pipeline/analyze.py b/app/pipeline/analyze.py index 476e0a87..8e67b481 100644 --- a/app/pipeline/analyze.py +++ b/app/pipeline/analyze.py @@ -215,6 +215,38 @@ def _load_audio_ffmpeg( return y, sr +def compute_stem_presence(stems_dir: Path, selected_stems: list[str]) -> dict[str, int]: + """Load each extracted stem WAV, compute mean absolute amplitude, normalize + to 0-100. Only the stems that were selected (and therefore extracted) are + measured; the rest are omitted from the returned dict.""" + import numpy as np + + result: dict[str, int] = {} + rms_values: dict[str, float] = {} + + for name in selected_stems: + wav_path = stems_dir / f"{name}.wav" + if not wav_path.is_file(): + continue + loaded = _load_audio_ffmpeg(wav_path, sr=22050, duration=180.0) + if loaded is None: + continue + y, _ = loaded + rms_values[name] = float(np.sqrt(np.mean(y ** 2))) + + if not rms_values: + return result + + max_rms = max(rms_values.values()) + if max_rms < 1e-9: + return {name: 0 for name in rms_values} + + for name, rms in rms_values.items(): + result[name] = max(0, min(100, round(rms / max_rms * 100))) + + return result + + def analyze(job: Job, source: Path) -> tuple[int | None, str | None]: """Best-effort BPM and key detection. On failure, returns (None, None) and leaves job fields untouched -- the chips stay as placeholders.""" @@ -241,7 +273,7 @@ def analyze(job: Job, source: Path) -> tuple[int | None, str | None]: # smear, no kick fundamentals leaking in). y_harmonic, y_percussive = librosa.effects.hpss(y) - tempo_arr, _ = librosa.beat.beat_track(y=y_percussive, sr=sr) + tempo_arr, beat_frames = librosa.beat.beat_track(y=y_percussive, sr=sr) try: tempo = float(tempo_arr[0]) # type: ignore[index] except (TypeError, IndexError): @@ -263,6 +295,22 @@ def analyze(job: Job, source: Path) -> tuple[int | None, str | None]: # it's good enough for a UI display and adds ~50 ms to analyze. lufs, peak_db = _measure_loudness(y, sr) + dynamic_range: float | None = None + if lufs is not None and peak_db is not None: + dynamic_range = round(peak_db - lufs, 1) + + # Beat interval coefficient of variation → stability 0-100. + # CV = std/mean of inter-beat intervals; CV=0 is perfectly metronomic. + tempo_stability: int | None = None + import numpy as np + beat_times = librosa.frames_to_time(beat_frames, sr=sr) + if len(beat_times) > 2: + intervals = np.diff(beat_times) + mean_iv = float(intervals.mean()) + if mean_iv > 0: + cv = float(intervals.std() / mean_iv) + tempo_stability = max(0, min(100, round((1 - min(cv, 1)) * 100))) + _set( job, bpm=bpm, @@ -271,6 +319,8 @@ def analyze(job: Job, source: Path) -> tuple[int | None, str | None]: key_confidence=key_confidence, lufs=lufs, peak_db=peak_db, + dynamic_range=dynamic_range, + tempo_stability=tempo_stability, progress=1.0, stage="Analysis complete", ) diff --git a/app/pipeline/download.py b/app/pipeline/download.py index b13b14c4..d30afd77 100644 --- a/app/pipeline/download.py +++ b/app/pipeline/download.py @@ -213,6 +213,15 @@ def hook(d: dict) -> None: thumbnail=info.get("thumbnail") or meta.get("thumbnail"), ) + raw_tags = [ + t.strip().lower() + for t in (info.get("tags") or []) + (info.get("categories") or []) + if isinstance(t, str) and t.strip() + ] + seen: set[str] = set() + deduped = [t for t in raw_tags if not (t in seen or seen.add(t))] # type: ignore[func-returns-value] + _set(job, tags=deduped[:8] or None) + candidates = sorted(job_dir.glob("source.*")) if not candidates: raise RuntimeError("yt-dlp finished but no source file was produced") diff --git a/app/pipeline/runner.py b/app/pipeline/runner.py index ae27e0a9..921235e9 100644 --- a/app/pipeline/runner.py +++ b/app/pipeline/runner.py @@ -10,7 +10,7 @@ from app.core.config import TIMEOUT_FFMPEG from app.core.models import Job, JobCancelled from app.core.registry import persist as persist_registry -from app.pipeline.analyze import analyze +from app.pipeline.analyze import analyze, compute_stem_presence from app.pipeline.collect import cleanup_source, collect, make_original_track, make_selected_mix from app.pipeline.download import _set, download from app.pipeline.separate import separate @@ -83,6 +83,7 @@ def _run_common(job: Job, source: Path, job_dir: Path) -> None: stems_root = separate(job, source, job_dir) found = collect(job, stems_root, job_dir) stems_dir = job_dir / "stems" + job.stem_presence = compute_stem_presence(stems_dir, found) # Source (100-300 MB or the local upload) is no longer needed after # collect; delete it before the ffmpeg amix steps in case scratch space # is tight. @@ -129,6 +130,10 @@ def _write_metadata(job: Job, job_dir: Path) -> None: "key_confidence": job.key_confidence, "lufs": job.lufs, "peak_db": job.peak_db, + "dynamic_range": job.dynamic_range, + "tempo_stability": job.tempo_stability, + "stem_presence": job.stem_presence, + "tags": job.tags, } try: (job_dir / "metadata.json").write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8") diff --git a/static/css/daw.css b/static/css/daw.css new file mode 100644 index 00000000..ceb0b8a5 --- /dev/null +++ b/static/css/daw.css @@ -0,0 +1,1873 @@ +/* ═══════════════════════════════════════════ + DAW UI — flat dark design + ═══════════════════════════════════════════ */ + +/* ── Reset ── */ +*, *::before, *::after { box-sizing: border-box; } +html, body { margin: 0; padding: 0; height: 100%; background: #0a0d10; overflow: hidden; } +body { font-family: var(--font-sans); color: var(--fg); } +button { font-family: inherit; } +input, textarea { font-family: inherit; } + +/* ── Root ── */ +.daw { + width: 100vw; + height: 100vh; + background: var(--bg); + color: var(--fg); + font-family: var(--font-sans); + font-size: 13px; + line-height: 1.4; + letter-spacing: -0.005em; + display: flex; + flex-direction: column; + overflow: hidden; + /* reset any old .app grid */ + grid-template-columns: none !important; + grid-template-rows: none !important; +} + +/* ── Utilities ── */ +.daw .uplabel { + font-size: 10px; + font-weight: 600; + letter-spacing: 0.12em; + text-transform: uppercase; + color: var(--muted); +} +.daw .num { font-family: var(--font-mono); font-variant-numeric: tabular-nums; } +.daw .hidden { display: none !important; } + +/* ═══════════════════════════════════ + TOPBAR + ═══════════════════════════════════ */ +.daw-topbar { + height: 77px; + flex-shrink: 0; + background: var(--bg-2); + border-bottom: 1px solid var(--border); + display: flex; + align-items: center; + padding: 0 16px; + gap: 14px; +} + +/* Brand */ +.daw-brand { + display: flex; + align-items: center; + gap: 9px; + flex-shrink: 0; +} +.daw-brand img { height: 30px; width: auto; display: block; } +.daw-brand-name { + font-size: 18px; + font-weight: 600; + letter-spacing: -0.015em; + line-height: 1; +} +.daw-brand-name .fg { color: var(--fg); } +.daw-brand-name .accent{ color: var(--accent); } + +.daw-version { + display: none !important; /* version shown in notification panel instead */ +} + +/* Topbar separator */ +.daw-sep { + width: 1px; + height: 28px; + background: var(--border); + flex-shrink: 0; +} + +/* ── Composer pill ── */ +.daw-composer { + flex: 1; + min-width: 0; + height: 50px; + display: flex; + align-items: stretch; + background: var(--panel); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + box-shadow: inset 0 1px 0 rgba(255,255,255,0.02), 0 1px 8px rgba(0,0,0,0.3); + overflow: hidden; +} + +/* URL zone */ +.daw-url-zone { + display: flex; + align-items: center; + gap: 10px; + padding: 0 14px; + flex: 1; + min-width: 0; + cursor: text; +} +/* Hide decorative SVG icons in the topbar */ +.daw-url-zone > svg { display: none; } +.daw-process-btn > svg { display: none; } +.daw-url-zone svg { flex-shrink: 0; } + +.daw-url-zone input[type="url"] { + flex: 1; + min-width: 0; + background: none; + border: none; + outline: none; + color: var(--fg-2); + font-size: 14px; + font-family: inherit; + letter-spacing: -0.005em; +} +.daw-url-zone input[type="url"]::placeholder { color: var(--muted); } + +/* Upload button inside URL zone */ +.daw-upload-btn { + width: 30px; + height: 30px; + flex-shrink: 0; + display: inline-flex; + align-items: center; + justify-content: center; + background: none; + border: 1px solid var(--border); + border-radius: 6px; + color: var(--muted); + cursor: pointer; + transition: background var(--t-fast), color var(--t-fast), border-color var(--t-fast); +} +.daw-upload-btn:hover { background: var(--panel-2); color: var(--fg-2); border-color: var(--border-strong); } + +/* File pill (shown when file selected) */ +.file-pill { + display: flex; + align-items: center; + gap: 6px; + padding: 2px 8px; + border: 1px solid var(--border-strong); + border-radius: 6px; + background: var(--panel-2); + color: var(--fg-2); + font-size: 11px; + white-space: nowrap; + overflow: hidden; +} +.file-pill.hidden { display: none !important; } +.file-name { overflow: hidden; text-overflow: ellipsis; max-width: 140px; } +.file-size { color: var(--muted); flex-shrink: 0; } +.file-clear { + width: 16px; height: 16px; + background: none; border: none; + color: var(--muted); cursor: pointer; + font-size: 14px; line-height: 1; + display: flex; align-items: center; justify-content: center; + border-radius: 3px; flex-shrink: 0; padding: 0; +} +.file-clear:hover { color: var(--fg); background: var(--panel-3); } + +/* url-wrap alias (JS uses .url-wrap for drag events) */ +.daw-url-zone { position: relative; } +.daw-url-zone.drag-over { + background: rgba(244,183,64,0.06); + box-shadow: inset 0 0 0 1px rgba(244,183,64,0.3); +} +.daw-url-zone.has-file input[type="url"] { display: none; } + +/* Composer vertical divider */ +.daw-composer-sep { + width: 1px; + background: var(--border); + align-self: stretch; + margin: 6px 0; + flex-shrink: 0; +} + +/* Stem section */ +.daw-stem-section { + display: flex; + align-items: center; + gap: 10px; + padding: 0 14px; + flex-shrink: 0; +} +.daw-extract-label { + font-size: 10px; + font-weight: 600; + letter-spacing: 0.12em; + text-transform: uppercase; + color: var(--muted); +} +.daw-stem-chips { display: flex; gap: 4px; } + +/* Stem choice buttons */ +.stem-choice { + height: 30px; + padding: 0 11px; + border-radius: 6px; + border: 1px solid var(--border); + background: none; + color: var(--muted-2); + font-size: 12px; + font-weight: 600; + font-family: inherit; + letter-spacing: -0.005em; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 6px; + transition: background var(--t-fast), border-color var(--t-fast), color var(--t-fast); +} +.stem-choice[aria-pressed="true"] { + border-color: color-mix(in srgb, var(--color) 60%, transparent); + background: color-mix(in srgb, var(--color) 14%, transparent); + color: var(--color); +} +.stem-dot { + width: 5px; height: 5px; + border-radius: 50%; + background: currentColor; + opacity: 0.85; +} +.stem-choice[aria-pressed="false"] .stem-dot { opacity: 0.4; } + +/* "All" toggle */ +.stem-choice-all { + border-color: var(--border-strong); + color: var(--fg-2); + font-size: 12px; +} +.stem-choice-all[aria-pressed="true"] { + border-color: var(--accent); + background: rgba(244,183,64,0.12); + color: var(--accent); +} + +/* Process button */ +.daw-process-btn { + height: auto; + padding: 0 20px; + background: linear-gradient(180deg, var(--accent), var(--accent-2)); + border: none; + border-left: 1px solid #b97f1c; + color: #1a1206; + font-weight: 600; + font-size: 14px; + font-family: inherit; + display: inline-flex; + align-items: center; + gap: 7px; + cursor: pointer; + box-shadow: inset 0 1px 0 rgba(255,255,255,0.22); + flex-shrink: 0; + transition: background var(--t-fast); +} +.daw-process-btn:hover { background: linear-gradient(180deg, #f8c054, #e0a032); } +.daw-process-btn:active { transform: translateY(1px); } +.daw-process-btn:disabled { + opacity: 0.8; + cursor: progress; + filter: saturate(0.85); +} + +/* Loading spinner on process btn */ +.daw-process-btn.loading > svg { display: none; } +.daw-process-btn.loading { filter: saturate(0.85); } +.daw-process-btn.loading::before { + content: ""; + width: 14px; height: 14px; flex: 0 0 14px; + border-radius: 50%; + background: conic-gradient(currentColor 0deg 270deg, transparent 270deg 360deg); + -webkit-mask: radial-gradient(farthest-side, transparent calc(100% - 2.5px), #000 0); + mask: radial-gradient(farthest-side, transparent calc(100% - 2.5px), #000 0); + animation: daw-spin 0.85s linear infinite; +} +@keyframes daw-spin { to { transform: rotate(360deg); } } + +/* Icon button */ +.daw-iconbtn { + width: 30px; height: 30px; + display: inline-flex; align-items: center; justify-content: center; + background: transparent; + border: 1px solid transparent; + color: var(--fg-2); + border-radius: 8px; + cursor: pointer; + transition: background var(--t-fast), color var(--t-fast); + flex-shrink: 0; +} +.daw-iconbtn:hover { background: var(--panel-2); border-color: var(--border); color: var(--fg); } +.daw-iconbtn:active { transform: scale(0.96); } + +/* Notification panel */ +.daw-notif-wrap { position: relative; } +.daw-notif-panel { + display: none; + position: absolute; + top: calc(100% + 8px); + right: 0; + width: 280px; + background: var(--panel-2); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + box-shadow: 0 8px 32px rgba(0,0,0,0.5); + z-index: 200; + overflow: hidden; +} +.daw-notif-wrap.open .daw-notif-panel { display: block; } +.daw-notif-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 12px 8px; + border-bottom: 1px solid var(--border); +} +.daw-notif-close { + width: 22px; height: 22px; + background: none; border: none; + color: var(--muted); cursor: pointer; + display: flex; align-items: center; justify-content: center; + border-radius: 5px; +} +.daw-notif-close:hover { background: var(--panel-3); color: var(--fg); } +.daw-notif-list { padding: 8px; display: flex; flex-direction: column; gap: 6px; } +.daw-notif-card { + display: flex; + gap: 10px; + align-items: flex-start; + padding: 10px 12px; + background: var(--panel); + border: 1px solid var(--border); + border-radius: 8px; +} +.daw-notif-release { border-color: rgba(244,183,64,0.25); } +.daw-notif-card-icon { + width: 28px; height: 28px; flex-shrink: 0; + display: flex; align-items: center; justify-content: center; + background: rgba(244,183,64,0.12); + border-radius: 6px; + color: var(--accent); +} +.daw-notif-card-body { flex: 1; min-width: 0; } +.daw-notif-card-title { font-size: 12px; font-weight: 600; color: var(--fg); } +.daw-notif-card-desc { font-size: 11px; color: var(--muted); margin-top: 2px; } + +/* Hidden collapsed strip (JS compat, not shown in new design) */ +.appbar-icon-strip.hidden { display: none !important; } + +/* ═══════════════════════════════════ + BODY LAYOUT + ═══════════════════════════════════ */ +.daw-body { + flex: 1; + display: flex; + min-height: 0; +} + +/* ═══════════════════════════════════ + SIDEBAR / CATALOG + ═══════════════════════════════════ */ +.sidebar { + width: 390px; + flex-shrink: 0; + background: var(--bg-2); + border-right: 1px solid var(--border); + display: flex; +} + +/* Rail */ +.sidebar-rail { + width: 56px; + border-right: 1px solid var(--border); + display: flex; + flex-direction: column; + align-items: center; + padding: 12px 0; + gap: 4px; + flex-shrink: 0; +} + +.rail-btn { + width: 40px; height: 40px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 2px; + border-radius: 8px; + color: var(--muted); + font-size: 9px; + font-family: var(--font-sans); + cursor: pointer; + transition: background var(--t-fast), color var(--t-fast); + border: none; + background: none; + /* remove old pseudo-element strip */ +} +.rail-btn::before { display: none !important; } +.rail-btn:hover { background: var(--panel); color: var(--fg-2); } +.rail-btn.active { color: var(--accent); background: var(--panel); } +.rail-btn svg { flex-shrink: 0; } +.rail-btn span { white-space: nowrap; } + +/* Sidebar body */ +.sidebar-body { + flex: 1; + padding: 12px; + display: flex; + flex-direction: column; + gap: 10px; + min-width: 0; + overflow: hidden; +} + +/* Search */ +.daw-search { + height: 32px; + border: 1px solid var(--border); + background: var(--panel); + border-radius: 8px; + display: flex; + align-items: center; + gap: 8px; + padding: 0 10px; + color: var(--muted); + font-size: 12px; + flex-shrink: 0; +} +.daw-search svg { flex-shrink: 0; } +.daw-search input { + flex: 1; min-width: 0; + border: none; outline: none; + background: transparent; + color: var(--fg); + font: inherit; +} +.daw-search input::placeholder { color: var(--muted); } +.search-kbd { + font-size: 10px; + color: var(--muted-2); + border: 1px solid var(--border); + border-radius: 4px; + padding: 0 5px; + flex-shrink: 0; +} + +/* Lib header row */ +.daw-lib-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 4px; + min-height: 22px; + flex-shrink: 0; +} +.daw-lib-label { + display: flex; + align-items: center; + gap: 4px; +} +.daw-lib-count { color: var(--muted-2); font-weight: 500; margin-left: 4px; } +.new-folder-btn { + display: inline-flex; align-items: center; gap: 5px; + padding: 3px 9px 3px 7px; + background: none; + border: 1px solid var(--border); + border-radius: 5px; + color: var(--muted); + font-size: 11px; font-weight: 500; + cursor: pointer; + white-space: nowrap; + transition: background var(--t-fast), color var(--t-fast), border-color var(--t-fast); +} +.new-folder-btn:hover { + background: var(--panel); + color: var(--fg-2); + border-color: var(--border-2, rgba(255,255,255,0.15)); +} + +/* Lib list (JS populates with .lib-item, .folder, .cat-item) */ +.daw-lib-list { + flex: 1; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 2px; +} + +/* Library item */ +.lib-item { + display: flex; + gap: 10px; + align-items: center; + padding: 8px; + border-radius: 8px; + cursor: pointer; + position: relative; + transition: background var(--t-fast); +} +.lib-item:hover { background: var(--panel); } +.lib-item.active { + background: linear-gradient(90deg, rgba(244,183,64,0.10) 0%, var(--panel-2) 60%); +} +.lib-item.active::before { + content: ''; + position: absolute; left: -2px; top: 6px; bottom: 6px; + width: 3px; border-radius: 2px; + background: var(--accent); +} +.lib-cover { + width: 36px; height: 36px; border-radius: 6px; + display: flex; align-items: center; justify-content: center; + font-size: 9px; font-weight: 700; letter-spacing: 0.1em; + color: rgba(255,255,255,0.85); + flex-shrink: 0; +} +.lib-meta { flex: 1; min-width: 0; } +.lib-meta .t { font-size: 13px; color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.lib-meta .s { font-size: 11px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.lib-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; } + +/* cat-item (legacy catalog items JS creates) */ +.cat-item { + display: flex; + gap: 9px; + align-items: center; + padding: 7px 8px; + border: 1px solid transparent; + border-radius: 8px; + cursor: pointer; + transition: background var(--t-fast), border-color var(--t-fast); +} +.cat-item:hover { background: var(--panel-2); border-color: var(--border); } +.cat-item.active { background: var(--panel-2); border-color: rgba(244,183,64,0.3); } +.cat-thumb { + width: 36px; height: 36px; + border-radius: 6px; flex-shrink: 0; + overflow: hidden; border: 1px solid var(--border); + background: var(--panel); + display: flex; align-items: center; justify-content: center; + color: var(--muted); +} +.cat-thumb svg, .cat-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; } +.cat-meta { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; } +.cat-title { color: var(--fg); font-size: 12px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.cat-sub { color: var(--muted); font-size: 10.5px; display: flex; gap: 5px; white-space: nowrap; overflow: hidden; } +.cat-status { width: 6px; height: 6px; border-radius: 50%; background: #5fbc56; flex-shrink: 0; } +.cat-status.processing { background: var(--accent); animation: cat-pulse 1.4s infinite; } +@keyframes cat-pulse { 0%,100%{opacity:1;} 50%{opacity:0.3;} } +.cat-del { + width: 20px; height: 20px; border: 0; border-radius: 5px; + background: transparent; color: var(--muted); cursor: pointer; + opacity: 0; display: flex; align-items: center; justify-content: center; + padding: 0; flex-shrink: 0; transition: opacity var(--t-fast), background var(--t-fast); +} +.cat-item:hover .cat-del { opacity: 1; } +.cat-del:hover { background: rgba(21,31,39,0.8); color: var(--danger); } + +/* Folder items (legacy catalog) */ +.folder { display: flex; flex-direction: column; } +.folder-head { + --folder-color: var(--accent); + display: flex; align-items: center; gap: 7px; + padding: 6px 8px; border-radius: 7px; + cursor: pointer; color: var(--muted); + transition: background var(--t-fast), color var(--t-fast); + user-select: none; +} +.folder-head:hover { background: var(--panel); color: var(--fg); } +.folder-head .f-chevron { width: 11px; height: 11px; transition: transform 180ms ease; flex-shrink: 0; color: var(--muted); } +.folder.collapsed .folder-head .f-chevron { transform: rotate(-90deg); } +.folder-head .f-icon { width: 13px; height: 13px; flex-shrink: 0; color: var(--folder-color); } +.folder-head .f-name { + font-size: 12px; font-weight: 500; color: inherit; + flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; + background: transparent; border: none; padding: 0; font-family: inherit; outline: none; cursor: inherit; +} +.folder-head .f-count { font-size: 10.5px; color: var(--muted); } +.folder-color-dot { + width: 13px; height: 13px; border: 1px solid rgba(255,255,255,0.22); + border-radius: 999px; background: var(--folder-color); cursor: pointer; padding: 0; + box-shadow: inset 0 0 0 1px rgba(0,0,0,0.22); +} +.folder-head .f-del, +.folder-head .f-subfolder { + width: 18px; height: 18px; border: none; background: transparent; + color: var(--muted); cursor: pointer; opacity: 0; + display: flex; align-items: center; justify-content: center; + border-radius: 4px; padding: 0; transition: opacity var(--t-fast), color var(--t-fast); + flex-shrink: 0; +} +.folder-head:hover .f-del, +.folder-head:hover .f-subfolder { opacity: 1; } +.folder-head .f-del:hover { background: rgba(21,31,39,0.8); color: var(--danger); } +.folder-head .f-subfolder:hover { background: rgba(21,31,39,0.8); color: var(--fg-2); } +/* Drag grip */ +.f-grip { + display: none; align-items: center; justify-content: center; + cursor: grab; color: var(--muted); flex-shrink: 0; + padding: 2px; border-radius: 3px; + transition: color var(--t-fast); +} +.f-grip:active { cursor: grabbing; } +.folder-head:hover .f-grip { display: flex; } +/* Drop indicators for folder reorder / nest */ +.folder.drop-before > .folder-head { box-shadow: 0 -2px 0 var(--accent); border-radius: 7px 7px 0 0; } +.folder.drop-after > .folder-head { box-shadow: 0 2px 0 var(--accent); border-radius: 0 0 7px 7px; } +.folder.drop-into > .folder-head { box-shadow: 0 0 0 1px var(--accent); background: var(--panel); } +/* Folder being dragged */ +.folder.folder-dragging { opacity: 0.35; pointer-events: none; } +/* Subfolder indentation */ +.folder.subfolder { margin-left: 12px; } +.folder-body { display: flex; flex-direction: column; gap: 3px; padding: 3px 0 3px 14px; margin-left: 7px; border-left: 1px solid rgba(157,170,182,0.1); } +.folder.collapsed .folder-body { display: none; } +.folder-empty { color: var(--muted); font-size: 11px; padding: 5px 8px; font-style: italic; } + +/* Folder editor modal */ +.folder-editor-backdrop { + position: fixed; inset: 0; z-index: 80; + display: grid; place-items: center; + background: rgba(3,8,13,0.42); backdrop-filter: blur(2px); +} +.folder-editor { + width: min(300px, calc(100vw - 32px)); + border: 1px solid var(--border-strong); + border-radius: 10px; + background: linear-gradient(180deg, rgba(28,39,48,0.98), rgba(13,21,29,0.98)); + box-shadow: var(--shadow-panel); + padding: 12px; color: var(--fg); font-family: var(--font-mono); +} +.folder-editor-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; font-size: 13px; font-weight: 600; } +.folder-editor-close { width: 24px; height: 24px; border: 1px solid transparent; border-radius: 6px; background: transparent; color: var(--muted); cursor: pointer; display: grid; place-items: center; padding: 0; } +.folder-editor-close:hover { background: rgba(21,31,39,0.8); color: var(--fg); } +.folder-editor-field { display: grid; gap: 7px; margin-bottom: 12px; color: var(--muted); font-size: 10.5px; } +.folder-editor-name { width: 100%; min-height: 34px; border: 1px solid var(--border); border-radius: 7px; background: rgba(10,17,24,0.78); color: var(--fg); font: inherit; font-size: 12px; padding: 0 10px; outline: none; } +.folder-editor-name:focus { border-color: rgba(244,183,64,0.5); box-shadow: 0 0 0 2px rgba(244,183,64,0.12); } +.folder-editor-colors { display: flex; align-items: center; gap: 9px; } +.folder-editor-colors .folder-color-dot { width: 22px; height: 22px; } +.folder-editor-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; } +.folder-editor-actions button { min-height: 30px; border-radius: 7px; font-family: var(--font-mono); font-size: 11px; cursor: pointer; padding: 0 11px; } +.folder-editor-cancel { border: 1px solid var(--border); background: rgba(21,31,39,0.52); color: var(--muted); } +.folder-editor-save { border: 1px solid rgba(244,183,64,0.3); background: rgba(244,183,64,0.16); color: var(--accent); } + +/* Color picker popover */ +.color-picker-popover { + position: absolute; z-index: 90; + background: var(--panel-2); border: 1px solid var(--border-strong); + border-radius: 8px; padding: 8px; display: flex; gap: 6px; + box-shadow: var(--shadow-panel); +} + +/* Collapsed sidebar strip */ +.cat-collapsed-strip { display: none; } +.daw.cat-collapsed .sidebar { width: 56px; } +.daw.cat-collapsed .sidebar-body { display: none; } +.daw.cat-collapsed .cat-collapsed-strip { display: flex; flex-direction: column; gap: 8px; align-items: center; padding: 8px 0; overflow-y: auto; } + +/* ═══════════════════════════════════ + MAIN AREA (#lanes) + ═══════════════════════════════════ */ +.daw-main-col { + flex: 1; + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; +} +.daw-main { + flex: 1; + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; + overflow: hidden; +} + +/* ── Job progress overlay ── */ +.job { + position: absolute; + top: 64px; left: 260px; right: 0; bottom: 56px; + z-index: 20; + background: rgba(11,15,18,0.92); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 16px; + padding: 32px; +} +.job.hidden { display: none !important; } +.job .title { font-size: 15px; font-weight: 600; color: var(--fg); text-align: center; } +.job .stage { font-size: 12px; color: var(--muted); text-align: center; } +.job progress { + width: 280px; max-width: 100%; + height: 4px; + border-radius: 2px; + appearance: none; border: none; + background: var(--panel-3); + overflow: hidden; +} +.job progress::-webkit-progress-bar { background: var(--panel-3); border-radius: 2px; } +.job progress::-webkit-progress-value { background: var(--accent); border-radius: 2px; } +.job progress::-moz-progress-bar { background: var(--accent); border-radius: 2px; } +.job .job-detail { font-size: 11px; color: var(--muted-2); text-align: center; } +.cancel-btn { + height: 30px; padding: 0 16px; + background: var(--panel-2); border: 1px solid var(--border-strong); + color: var(--fg-2); border-radius: 8px; font-size: 12px; + font-family: inherit; cursor: pointer; + transition: background var(--t-fast); +} +.cancel-btn:hover { background: var(--panel-3); color: var(--fg); } +.cancel-btn.hidden { display: none !important; } + +/* Error banner */ +.error { + position: absolute; + top: 64px; left: 260px; right: 0; + z-index: 15; + padding: 12px 20px; + background: rgba(214,90,74,0.12); + border-bottom: 1px solid rgba(214,90,74,0.3); + color: #ff9090; + font-size: 13px; +} +.error.hidden { display: none !important; } + +/* ── Track header ── */ +.daw-track-header { + display: flex; + flex-direction: column; + border-bottom: 1px solid var(--border); + background: var(--bg-2); + flex-shrink: 0; +} + +/* Row 1 */ +.daw-info-row { + display: flex; + border-bottom: 1px solid var(--border); +} + +/* Track card */ +.daw-track-card { + display: flex; + gap: 14px; + align-items: flex-start; + padding: 14px 16px; + flex-shrink: 0; + width: 340px; + border-right: 1px solid var(--border); +} + +/* Metadata cards */ +.daw-meta-card { + flex: 1; + padding: 14px 16px; + border-right: 1px solid var(--border); + display: flex; + flex-direction: column; + gap: 5px; + min-width: 0; +} +.daw-meta-card:last-child { border-right: none; } +.meta-card-label { + font-size: 10px; + font-weight: 600; + letter-spacing: 0.07em; + text-transform: uppercase; + color: var(--muted); +} +.meta-card-main { + display: flex; + align-items: center; + gap: 8px; +} +.meta-card-value { + font-size: 22px; + font-weight: 700; + color: var(--fg); + line-height: 1; + font-family: var(--font-mono); +} +.meta-card-value.accent { color: var(--accent); } +.meta-card-value.stability-high { color: #4caf7d; } +.meta-card-sub { + font-size: 11px; + color: var(--muted); +} +.daw-cover { + width: 64px; height: 64px; + border-radius: 8px; + background: var(--panel-2); + display: flex; align-items: center; justify-content: center; + flex-shrink: 0; color: var(--muted); + position: relative; overflow: hidden; +} +.np-art-placeholder { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; } +.np-art-img { + position: absolute; inset: 0; + width: 100%; height: 100%; object-fit: cover; display: none; +} +.np-art-img[src]:not([src=""]) { display: block; } + +.daw-track-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; } +.daw-track-title { font-size: 16px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.daw-track-sub { font-size: 11px; color: var(--muted); } +.daw-track-time-row { + display: flex; + align-items: center; + gap: 6px; +} +.daw-track-sep { color: var(--border); font-size: 12px; } +.daw-track-stems-label { + font-size: 11px; + color: var(--muted); + display: flex; + align-items: center; + gap: 4px; +} +.daw-track-stems-label::before { + content: ''; + display: inline-block; + width: 7px; height: 7px; + border-radius: 50%; + background: #4caf7d; + flex-shrink: 0; +} +.daw-fav-btn { + margin-left: auto; + background: none; + border: none; + cursor: pointer; + color: var(--muted); + padding: 2px; + display: flex; + align-items: center; + transition: color 150ms; +} +.daw-fav-btn:hover { color: var(--fg); } +.daw-fav-btn.active { color: #e54e4e; } +.daw-fav-btn.active svg { fill: #e54e4e; stroke: #e54e4e; } +.daw-track-details { display: flex; flex-direction: column; gap: 3px; margin-top: 2px; } +.daw-detail-row { display: flex; gap: 8px; align-items: baseline; } +.daw-detail-label { font-size: 11px; color: var(--muted); width: 64px; flex-shrink: 0; } +.daw-detail-val { font-size: 11px; color: var(--fg-2); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.daw-chip { + display: inline-flex; align-items: center; + padding: 2px 8px; + border: 1px solid var(--border); + border-radius: 999px; + background: var(--panel-2); + font-size: 11px; + color: var(--fg-2); + font-family: var(--font-mono); +} + +/* Energy panel */ +.daw-energy-panel { + padding: 12px; + background: var(--panel); + border: 1px solid var(--border); + border-radius: var(--radius); + display: flex; + flex-direction: column; + gap: 6px; + min-width: 0; +} +.daw-energy-header { + display: flex; + align-items: center; + justify-content: space-between; +} +.daw-playhead-label { color: var(--accent); display: flex; align-items: center; gap: 4px; } +.daw-energy-bars { flex: 1; display: flex; flex-direction: column; justify-content: space-between; gap: 4px; } + +/* Energy rows (JS-driven) */ +.energy-row { + display: flex; + align-items: center; + gap: 10px; +} +.energy-row span { + font-size: 11px; + font-weight: 500; + width: 44px; + flex-shrink: 0; +} +.energy-row.vocals span { color: var(--vocals); } +.energy-row.drums span { color: var(--drums); } +.energy-row.bass span { color: var(--bass); } +.energy-row.guitar span { color: var(--guitar); } +.energy-row.piano span { color: var(--piano); } +.energy-row.other span { color: var(--other); } +.energy-row.original span { color: var(--fg-2); } + +.energy-row b { + flex: 1; + height: 6px; + border-radius: 3px; + background: var(--bg); + overflow: hidden; + position: relative; + display: block; +} +.energy-row b::after { + content: ''; + position: absolute; inset: 0; + width: var(--v, 0%); + border-radius: 3px; + transition: width 160ms; +} +.energy-row.vocals b::after { background: var(--vocals); } +.energy-row.drums b::after { background: var(--drums); } +.energy-row.bass b::after { background: var(--bass); } +.energy-row.guitar b::after { background: var(--guitar); } +.energy-row.piano b::after { background: var(--piano); } +.energy-row.other b::after { background: var(--other); opacity: 0.5; } +.energy-row.original b::after { background: var(--fg-2); } + +.energy-row em { + font-style: normal; + font-family: var(--font-mono); + font-size: 11px; + color: var(--fg-2); + width: 36px; + text-align: right; + flex-shrink: 0; +} + +/* Stem presence cards — row 2 */ +.stem-presence-panel { + display: grid; + grid-template-columns: repeat(6, 1fr); +} +.stem-card { + padding: 14px 16px; + border-right: 1px solid var(--border); + display: flex; + flex-direction: column; + gap: 6px; +} +.stem-card:last-child { border-right: none; } +.stem-card-label { + font-size: 10px; + font-weight: 600; + letter-spacing: 0.07em; + text-transform: uppercase; + color: var(--muted); +} +.stem-card-pct { + font-size: 28px; + font-weight: 700; + font-family: var(--font-mono); + line-height: 1; + color: var(--fg); + transition: color 200ms; +} +.stem-card:not(.inactive)[data-stem="vocals"] .stem-card-pct { color: var(--vocals); } +.stem-card:not(.inactive)[data-stem="drums"] .stem-card-pct { color: var(--drums); } +.stem-card:not(.inactive)[data-stem="bass"] .stem-card-pct { color: var(--bass); } +.stem-card:not(.inactive)[data-stem="guitar"] .stem-card-pct { color: var(--guitar); } +.stem-card:not(.inactive)[data-stem="piano"] .stem-card-pct { color: var(--piano); } +.stem-card:not(.inactive)[data-stem="other"] .stem-card-pct { color: var(--other); } +.stem-card.inactive .stem-card-pct { color: var(--muted); } + +/* Analysis panel */ +.daw-analysis-panel { + padding: 12px; + background: var(--panel); + border: 1px solid var(--border); + border-radius: var(--radius); + display: flex; + gap: 16px; + flex-shrink: 0; +} +.daw-analysis-item { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 80px; +} +.daw-analysis-val { display: flex; align-items: center; gap: 8px; margin-top: 2px; } +.daw-analysis-num { + font-size: 22px; + font-weight: 600; + line-height: 1.1; + color: var(--fg); +} +.daw-analysis-num.accent { color: var(--accent); } +.daw-analysis-sub { font-size: 10px; color: var(--muted); margin-top: 2px; } +.daw-analysis-divider { width: 1px; background: var(--border); align-self: stretch; } +.daw-camelot-ring { + width: 28px; height: 28px; border-radius: 50%; + border: 1.5px solid var(--accent); + display: flex; align-items: center; justify-content: center; + font-size: 10px; font-weight: 700; color: var(--accent); + background: rgba(244,183,64,0.08); + font-family: var(--font-mono); +} + +/* ── Section ribbon ── */ +.daw-section-ribbon { + display: flex; + flex-shrink: 0; + border-bottom: 1px solid var(--border); +} +.daw-mixer-label { + width: 300px; + flex-shrink: 0; + background: var(--bg-2); + border-right: 1px solid var(--border); + padding: 6px 14px; + display: flex; + align-items: center; + justify-content: space-between; +} +.daw-label-title { font-size: 12px; font-weight: 600; } +.daw-label-sub { font-size: 9px; } +.daw-sections-header { justify-content: space-between; } +.daw-sections-area { + flex: 1; + position: relative; + height: 36px; + background: var(--bg-2); + overflow: hidden; + user-select: none; +} + +/* Section blocks (sections.js populates) */ +.section-block { + position: absolute; + top: 4px; bottom: 4px; + box-sizing: border-box; + border: 1px solid var(--sc, #4a7fff); + border-radius: 4px; + display: flex; + align-items: center; + overflow: hidden; + cursor: grab; + transition: filter 80ms; +} +.section-block:hover { filter: brightness(1.15); } +.section-block.sec-dragging { cursor: grabbing; filter: brightness(1.2); z-index: 10; } +.section-block.sec-resizing { filter: brightness(1.2); z-index: 10; } + +.section-label { + flex: 1; + padding: 0 6px 0 10px; + font-size: 10px; + font-weight: 700; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--sc, #4a7fff); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + pointer-events: auto; +} + +.section-del { + display: none; + flex-shrink: 0; + width: 16px; height: 16px; + margin-right: 4px; + border: none; background: none; + color: var(--sc, #4a7fff); + font-size: 13px; line-height: 1; + cursor: pointer; border-radius: 3px; + align-items: center; justify-content: center; + opacity: 0.7; +} +.section-del:hover { opacity: 1; background: rgba(0,0,0,0.3); } +.section-block:hover .section-del { display: flex; } + +.section-handle { + position: absolute; + top: 0; bottom: 0; + width: 6px; + cursor: col-resize; + z-index: 2; + flex-shrink: 0; +} +.section-handle-l { left: 0; } +.section-handle-r { right: 0; } +.section-handle:hover { background: rgba(255,255,255,0.12); } + +.section-rename-input { + flex: 1; + min-width: 0; + background: transparent; + border: none; + outline: none; + font: inherit; + font-size: 10px; + font-weight: 700; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--sc, #4a7fff); + padding: 0 6px 0 10px; + caret-color: var(--sc, #4a7fff); +} + +/* Sections save indicator */ +.sections-save-indicator { + display: inline-flex; + align-items: center; + gap: 5px; + font-size: 10px; + color: var(--muted); + white-space: nowrap; + transition: opacity 400ms; +} +.sections-save-indicator.hidden { display: none; } +.sections-save-indicator.saved { color: #4caf7d; } +.sections-save-indicator::before { + content: ""; + display: block; + width: 8px; height: 8px; + border-radius: 50%; + border: 1.5px solid currentColor; + border-top-color: transparent; + animation: sections-spin 600ms linear infinite; +} +.sections-save-indicator.saved::before { + animation: none; + border: none; + width: auto; height: auto; + content: "✓"; + font-size: 11px; +} +@keyframes sections-spin { + to { transform: rotate(360deg); } +} + +/* Add section button — lives in the Sections label column */ +.sections-add-btn-label { + display: inline-flex; align-items: center; gap: 4px; + padding: 3px 8px 3px 6px; + background: none; + border: 1px solid var(--border); + border-radius: 5px; + color: var(--muted); + font-size: 10px; font-weight: 600; + cursor: pointer; + white-space: nowrap; + transition: background var(--t-fast), color var(--t-fast), border-color var(--t-fast); +} +.sections-add-btn-label:hover { + background: var(--panel-2); + color: var(--fg); + border-color: rgba(255,255,255,0.18); +} + +/* Wave label (left column in wave header — Mixer label) */ +.daw-wave-label { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 14px; +} + +/* ── Waveform header ── */ +.daw-wave-header { + display: flex; + flex-shrink: 0; + border-bottom: 1px solid var(--border); +} +.daw-wave-label { + width: 300px; + flex-shrink: 0; + background: var(--bg-2); + border-right: 1px solid var(--border); + min-height: 32px; +} +.daw-ruler-area { + flex: 1; + background: var(--bg-2); + min-height: 32px; +} + +/* Ruler */ +.lanes-ruler { position: relative; height: 18px; } +.lanes-ruler-time { + position: absolute; inset: 0; + font-family: var(--font-mono); + font-size: 9px; + color: var(--muted); +} +.playhead-marker { + position: absolute; + top: -1px; + transform: translateX(-50%); + pointer-events: none; +} + +/* ── Content area (mixer + waveform) ── */ +.daw-content { + flex: 1; + display: flex; + min-height: 0; + overflow: hidden; +} + +/* ── Stems panel (left 300px) ── */ +.daw-stems-panel { + width: 300px; + flex-shrink: 0; + border-right: 1px solid var(--border); + display: flex; + flex-direction: column; + overflow: hidden; + background: var(--bg-2); +} + +/* Stem list rows — kept in DOM for JS hook (.stem-mute/.stem-solo toggling, hidden visually) */ +.stem-list { + position: absolute; + width: 0; height: 0; overflow: hidden; + visibility: hidden; pointer-events: none; + opacity: 0; +} +/* Also update the --lane-h var to match waveform lane height */ +:root { --lane-h: 72px; } /* 70px wave + 2px separator */ +.stem-icon { width: 14px; height: 14px; flex-shrink: 0; } +.stem-mute, .stem-solo { display: none; } +.stem-monitor { display: none; } +.drag-handle { display: none; } +.mini-meter { display: none; } + +/* ── Mixer column (JS-built horizontal lanes) ── */ +.mixer-column { + display: flex; + flex-direction: column; + flex: 1; + min-height: 0; + overflow: hidden; +} + +/* Each mixer row height is driven by --lane-h (set dynamically in JS to fill available space) */ +.lane-header.mx-row { + display: flex; + align-items: center; + gap: 6px; + padding: 0 10px; + height: var(--lane-h, 72px); + min-height: 72px; + max-height: none; + border-bottom: 2px solid var(--border); + background: var(--bg-2); + flex-shrink: 0; + position: relative; + transition: opacity var(--t-base); + box-sizing: border-box; +} +.lane-header.mx-row.muted { opacity: 0.45; } +.lane-header.mx-row.hidden { display: none !important; } + +.lane-stripe { display: none; } + +/* Name + VU stacked vertically */ +.lane-name-vu { + display: flex; + flex-direction: column; + justify-content: center; + gap: 5px; + width: 76px; + flex-shrink: 0; +} + +/* Stem icon — hidden per user preference */ +.mx-icon { display: none; } + +/* Stem name */ +.mx-name { + font-size: 13px; font-weight: 500; + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* Fader (horizontal, native range input) */ +.lane-knob.mx-fader { + flex: 1; + display: flex; + align-items: center; + min-width: 0; +} +.lane-knob-indicator { display: none; } +.mx-fader-input { + -webkit-appearance: none; + appearance: none; + width: 100%; + height: 22px; + background: transparent; + cursor: ew-resize; + outline: none; + margin: 0; +} +.mx-fader-input::-webkit-slider-runnable-track { + height: 4px; + border-radius: 2px; + background: linear-gradient( + to right, + var(--fader-color, #888) 0%, + var(--fader-color, #888) calc(var(--lane-pos, 0.5) * 100%), + rgba(255,255,255,0.08) calc(var(--lane-pos, 0.5) * 100%) + ); +} +.mx-fader-input::-webkit-slider-thumb { + -webkit-appearance: none; + width: 14px; height: 14px; + border-radius: 50%; + background: var(--fader-color, #888); + margin-top: -5px; + border: 2px solid rgba(0,0,0,0.35); + box-shadow: 0 0 0 1px rgba(255,255,255,0.18); + cursor: ew-resize; +} +.mx-fader-input::-moz-range-track { + height: 4px; border-radius: 2px; + background: rgba(255,255,255,0.08); +} +.mx-fader-input::-moz-range-thumb { + width: 14px; height: 14px; + border-radius: 50%; + background: var(--fader-color, #888); + border: 2px solid rgba(0,0,0,0.35); + cursor: ew-resize; +} + +/* VU meter — sits below stem name in .lane-left-col, spans full column width */ +.lane-vu.mx-meter { + position: relative; + height: 5px; + width: 100%; + background: var(--bg); + border: 1px solid var(--border); + border-radius: 3px; + overflow: hidden; + --vu-level: 0%; + --vu-peak: 0%; +} +.lane-vu-bar { + display: none; +} +.lane-vu-bar.mx-meter-fill { + display: block; + position: absolute; + inset: 0 auto 0 0; + width: var(--vu-level, 0%); + background: linear-gradient(90deg, #22c55e 0%, #86efac 80%, #f97316 95%, #ef4444 100%); + border-radius: 2px; + transition: width 40ms linear; +} + +/* dB value */ +.mx-val { + font-family: var(--font-mono); + font-size: 10px; + font-weight: 500; + color: var(--fg); + width: 36px; + text-align: right; + flex-shrink: 0; + font-variant-numeric: tabular-nums; +} + +/* M/S buttons (JS-built) */ +.lane-icon-toggle.mx-btn, +.ms-btn.mx-btn, +.lane-dl.mx-btn { + width: 22px; height: 20px; + background: transparent; + border: 1px solid var(--border-strong); + border-radius: 5px; + color: var(--muted); + font-size: 10px; font-weight: 700; + font-family: var(--font-mono); + letter-spacing: 0.05em; + cursor: pointer; + display: inline-flex; align-items: center; justify-content: center; + transition: background var(--t-fast), color var(--t-fast), border-color var(--t-fast); + flex-shrink: 0; + text-decoration: none; + padding: 0; + opacity: 1; +} +.lane-icon-toggle.mx-btn:hover, +.ms-btn.mx-btn:hover { color: var(--fg); border-color: #3a4550; } + +/* Mute button: "active" = NOT muted (lit up) */ +.lane-icon-toggle.mx-btn.mute.active { color: var(--fg-2); border-color: var(--border-strong); } +.lane-icon-toggle.mx-btn.mute:not(.active) { opacity: 0.35; } + +/* Solo button: "active" = soloed */ +.ms-btn.mx-btn.active { background: rgba(244,183,64,0.18); color: var(--accent); border-color: rgba(244,183,64,0.4); } + +/* Download button */ +.lane-dl.mx-btn { + color: var(--muted); + border-color: transparent; +} +.lane-dl.mx-btn:hover { color: var(--fg); border-color: var(--border); } +.lane-dl.mx-btn svg { width: 13px; height: 13px; } + +/* Unavailable stems — gray entire mixer row and waveform row */ +.lane-header.unavailable { opacity: 0.25; pointer-events: none; } +.stem-waveform-row.unavailable { opacity: 0.2; pointer-events: none; } +.mx-fader-input { touch-action: pan-y; } + +/* ── Waveform panel (right) ── */ +/* Layout only — waves.css handles all visual styling inside (.wave-scroll bg, + golden scrollbar, .loop-region, .waves-grid, .stem-waveform-layer etc.) */ +.daw-wave-panel { + flex: 1; + min-width: 0; + min-height: 0; + display: flex; + flex-direction: column; + overflow: hidden; +} + +/* waves.css gives .wave-editor padding + border-radius for the old rounded panel + style. In the flat DAW layout those are unwanted — strip them. */ +.daw .wave-editor, +.app:not(.is-import) .daw-wave-panel.wave-editor { + padding: 0 !important; + min-height: 0 !important; + border-radius: 0 !important; +} + +/* Our zoom toolbar sits outside .wave-editor (in .daw-wave-header), so + the wave-scroll should fill the full panel height instead of calc(100% - 32px). + Also remove the rounded corners waves.css adds in active state. */ +.daw .wave-scroll { + flex: 1 !important; + height: auto !important; + border-radius: 0 !important; + border: none !important; +} + +/* Establish height chain so waves-column's calc(100%-34px) resolves correctly */ +.daw .wave-canvas { height: 100%; } + +/* In the original layout a 48px stem-icon strip lived INSIDE the wave panel, + offsetting waves-column/multitrack/waveform-layer by 48px. In our layout the + mixer is a separate 300px panel, so all those 48px offsets must be zero. */ +.daw .waves-column, +.app:not(.is-import) .daw-wave-panel .waves-column { + padding-left: 0 !important; + --wave-gutter: 0px !important; +} +/* Show WaveSurfer native bar rendering; hide the SVG overlay layer */ +.daw #multitrack-container { + opacity: 1 !important; + pointer-events: all !important; + position: relative !important; /* in flow → waves-column height driven by WaveSurfer */ + inset: 0 !important; /* waves.css sets inset: 0 0 0 48px; zero left offset */ +} +/* Zero waves.css 48px left offsets that assumed an icon strip inside the wave panel */ +.daw .waves-grid { left: 0 !important; } +.daw .lanes-ruler { margin-left: 0 !important; } +.daw .stem-waveform-layer { + display: none !important; +} +/* waves-column must size naturally now that multitrack is in flow */ +.daw .waves-column { + height: auto !important; + min-height: 0 !important; +} + +.loop-region.hidden { display: none !important; } + +/* Wave loading overlay */ +.wave-loading-overlay { + position: absolute; inset: 0; z-index: 10; + display: flex; flex-direction: column; + align-items: center; justify-content: center; + gap: 16px; + background: rgba(11,15,18,0.88); +} +.wave-loading-overlay.hidden { display: none !important; } +.wave-loading-glow { + width: 80px; height: 80px; border-radius: 50%; + background: radial-gradient(circle, rgba(244,183,64,0.2) 0%, transparent 70%); + animation: daw-pulse 2s ease-in-out infinite; +} +@keyframes daw-pulse { 0%,100%{opacity:0.5;transform:scale(0.9);} 50%{opacity:1;transform:scale(1.1);} } +.wave-loading-lines { + display: flex; gap: 3px; align-items: center; +} +.wave-loading-lines i { + display: block; width: 3px; height: 20px; + background: var(--accent); border-radius: 2px; + animation: daw-bar 1.2s ease-in-out infinite; +} +.wave-loading-lines i:nth-child(2) { animation-delay: 0.1s; } +.wave-loading-lines i:nth-child(3) { animation-delay: 0.2s; } +.wave-loading-lines i:nth-child(4) { animation-delay: 0.3s; } +.wave-loading-lines i:nth-child(5) { animation-delay: 0.4s; } +.wave-loading-lines i:nth-child(6) { animation-delay: 0.5s; } +@keyframes daw-bar { 0%,100%{transform:scaleY(0.4);opacity:0.5;} 50%{transform:scaleY(1.4);opacity:1;} } +.wave-loading-msg { font-size: 12px; color: var(--muted); } + +/* Presence panel (hidden, JS compat) */ +.presence-panel { display: none; } + +/* ── Transport footer ── */ + +.daw-footer { + height: 200px; + flex-shrink: 0; + border-top: 1px solid var(--border); + background: var(--bg-2); + display: flex !important; + flex-direction: column; +} + +.daw-footer-left { + display: flex; + align-items: baseline; + gap: 6px; + min-width: 140px; + flex: 1; +} +.daw-time-big { + font-size: 20px; font-weight: 600; letter-spacing: -0.01em; +} +.daw-time-total { font-size: 13px; color: var(--muted); } +.daw-footer-right { + display: flex; align-items: center; gap: 8px; + min-width: 140px; justify-content: flex-end; + flex: 1; +} +.daw-master-fader { accent-color: var(--accent); cursor: pointer; } +.daw-btn { + display: inline-flex; align-items: center; justify-content: center; + background: var(--panel-2); border: 1px solid var(--border-strong); + color: var(--fg); border-radius: 8px; font-size: 12px; + font-family: inherit; cursor: pointer; + transition: background var(--t-fast); +} +.daw-btn:hover { background: var(--panel-3); } + +/* Transport controls */ +.daw-transport-controls { + display: flex; align-items: center; justify-content: center; gap: 8px; +} +.daw-play-btn { + background: var(--accent); + color: #1a1206; + width: 56px; height: 56px; + border-radius: 50%; border: none; + display: inline-flex; align-items: center; justify-content: center; + cursor: pointer; + box-shadow: 0 2px 10px rgba(244,183,64,0.35), inset 0 1px 0 rgba(255,255,255,0.18); + transition: transform var(--t-fast), box-shadow var(--t-fast); + flex-shrink: 0; +} +.daw-play-btn:hover { box-shadow: 0 2px 16px rgba(244,183,64,0.5), inset 0 1px 0 rgba(255,255,255,0.22); } +.daw-play-btn:active { transform: scale(0.96); } + +/* JS toggles these to show play vs pause icon */ +.btn-transport.playing .pause-icon { display: block !important; } +.btn-transport.playing > svg:first-child { display: none; } + +/* Stop/loop buttons inside the footer transport row */ +.daw-footer .daw-iconbtn.btn-transport { + width: 40px; height: 40px; + border-radius: 9px; + display: inline-flex; align-items: center; justify-content: center; +} + +/* Loop active state */ +.daw-iconbtn.loop.active, +.btn-transport.loop.active { color: var(--accent); } + +/* Export buttons in footer */ +.daw-footer .footer-btn { + padding: 0 14px; + height: 36px; + border-radius: 8px; + gap: 6px; + white-space: nowrap; +} +.daw-footer .footer-btn:disabled { + opacity: 0.4; + cursor: default; +} + +/* ── Footer redesign ── */ + +/* ── Footer layout ── */ +.footer-content { + display: flex; flex-direction: row; align-items: center; + padding: 0 20px; flex: 1; min-height: 0; + justify-content: space-between; +} +.footer-center { + flex: 0 0 auto; + display: flex; flex-direction: column; align-items: center; gap: 6px; + padding: 0 24px; +} +.footer-chips { + flex: 1; + display: flex; align-items: center; justify-content: flex-end; gap: 8px; + min-width: 0; +} + +/* Wave bar at the bottom of the footer */ +.footer-wave-bar { + height: 40px; flex-shrink: 0; + position: relative; overflow: hidden; +} +#footer-waveform { + position: absolute; inset: 0; + width: 100%; height: 100%; display: block; +} +.footer-scrub { + position: absolute; inset: 0; + cursor: pointer; z-index: 2; + background: transparent; +} +.footer-scrub-fill { display: none; } + +/* Track info (art + title + meta) */ +.footer-track { + flex: 1; min-width: 0; overflow: hidden; + display: flex; flex-direction: column; justify-content: center; + gap: 6px; +} +.footer-track-title-row { + display: flex; align-items: center; gap: 8px; min-width: 0; +} +.footer-track-title-row .daw-fav-btn { margin-left: 0; } +.footer-track-title { + min-width: 0; flex-shrink: 1; + font-size: 14px; font-weight: 600; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; + color: var(--fg); +} +.footer-track-body { + display: flex; align-items: flex-start; gap: 10px; min-width: 0; +} +.footer-cover { + width: 56px !important; height: 56px !important; + flex-shrink: 0; +} +.footer-track-body .daw-track-meta { flex: 1; min-width: 0; gap: 4px; } +.footer-track .daw-track-details { gap: 2px; } +.footer-track .daw-detail-label { font-size: 10px; width: 58px; } +.footer-track .daw-detail-val { font-size: 10px; } +.footer-art { + width: 44px; height: 44px; border-radius: 6px; + background: var(--panel-3); flex-shrink: 0; overflow: hidden; + display: none; +} +.footer-art.has-art { display: block; } +.footer-thumb-img { + width: 100%; height: 100%; object-fit: cover; + opacity: 0; transition: opacity 0.2s; +} +.footer-thumb-img.loaded { opacity: 1; } +.footer-info { + display: flex; flex-direction: column; gap: 3px; min-width: 0; +} +.footer-title { + font-size: 13px; font-weight: 600; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; + color: var(--fg); +} +.footer-meta { + font-size: 11px; color: var(--muted); + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} + +/* Time display below transport buttons */ +.footer-time-row { + display: flex; align-items: baseline; gap: 4px; + justify-content: center; +} +.footer-elapsed { + font-size: 17px; font-weight: 700; letter-spacing: -0.03em; color: var(--fg); +} +.footer-total { + font-size: 13px; font-weight: 400; color: var(--muted); +} +.footer-time-sep { font-size: 13px; color: var(--muted); } + +/* Transport buttons */ +.footer-transport { + display: flex; align-items: center; gap: 8px; flex-shrink: 0; +} +.footer-transport .daw-iconbtn.btn-transport { + background: var(--panel-2); + border-color: var(--border-strong); + color: var(--fg-2); +} +.footer-transport .daw-iconbtn.btn-transport:hover { + background: var(--panel-3); + color: var(--fg); +} + +/* Speed + export chip buttons */ +.footer-chip-wrap { + position: relative; flex-shrink: 0; + display: flex; align-items: center; +} +.footer-chip { + display: inline-flex; align-items: center; gap: 6px; + background: var(--panel-2); border: 1px solid var(--border-strong); + color: var(--fg); border-radius: 8px; font-size: 12px; font-weight: 500; + font-family: inherit; cursor: pointer; padding: 0 12px; height: 36px; + white-space: nowrap; + transition: background var(--t-fast); +} +.footer-chip:hover { background: var(--panel-3); } +.footer-chip-primary { + background: var(--accent); color: #1a1206; + border-color: transparent; +} +.footer-chip-primary:hover { background: color-mix(in srgb, var(--accent) 85%, white); } + +.footer-chip-panel { + position: absolute; bottom: calc(100% + 6px); right: 0; z-index: 30; + background: var(--panel-2); border: 1px solid var(--border-strong); + border-radius: 10px; padding: 4px; + min-width: 120px; + box-shadow: 0 8px 24px rgba(0,0,0,0.4); +} +.footer-chip-panel.hidden { display: none !important; } + +.chip-panel-item { + display: flex; align-items: center; gap: 8px; + width: 100%; padding: 7px 12px; + background: none; border: none; border-radius: 7px; + color: var(--fg); font-size: 13px; font-family: inherit; + cursor: pointer; text-align: left; white-space: nowrap; +} +.chip-panel-item:hover { background: var(--panel-3); } +.chip-panel-item.active { color: var(--accent); font-weight: 600; } + +/* ── About dialog ── */ +.about-backdrop { + position: fixed; inset: 0; z-index: 100; + display: grid; place-items: center; + background: rgba(3,8,13,0.55); backdrop-filter: blur(4px); +} +.about-backdrop.hidden { display: none !important; } +.about-card { + width: min(320px, calc(100vw - 32px)); + background: var(--panel-2); border: 1px solid var(--border-strong); + border-radius: 14px; box-shadow: var(--shadow-panel); + padding: 24px; text-align: center; + position: relative; +} +.about-close { + position: absolute; top: 12px; right: 12px; + width: 28px; height: 28px; + background: transparent; border: 1px solid var(--border); + border-radius: 6px; color: var(--muted); + font-size: 16px; cursor: pointer; + display: flex; align-items: center; justify-content: center; +} +.about-close:hover { background: var(--panel-3); color: var(--fg); } +.about-card h2 { margin: 0 0 8px; font-size: 20px; font-family: var(--font-mono); } +.about-version { font-size: 13px; color: var(--muted); margin: 0 0 16px; } +.about-link { + display: block; color: var(--accent); font-size: 13px; + text-decoration: none; font-family: var(--font-mono); +} +.about-link:hover { text-decoration: underline; } + +/* ── Library sections (Recent · Stem Collections · Tags) ── */ +.lib-section { + display: flex; + flex-direction: column; + gap: 4px; + padding-top: 14px; +} +.lib-section + .lib-section { + border-top: 1px solid var(--border); +} +.lib-section-head { + padding: 0 4px 6px; + font-size: 10px; + font-weight: 700; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--muted); +} + +/* Tag chips */ +.lib-tags-row { + display: flex; + flex-wrap: wrap; + gap: 6px; + padding: 2px 0 8px; +} +.lib-tag-chip { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 5px 11px; + background: var(--panel); + border: 1px solid var(--border); + border-radius: 20px; + font-size: 12px; + color: var(--fg-2); + cursor: pointer; + transition: background var(--t-fast), color var(--t-fast), border-color var(--t-fast); + white-space: nowrap; +} +.lib-tag-chip:hover { + background: var(--panel-2); + color: var(--fg); + border-color: rgba(255,255,255,0.15); +} +.lib-tag-chip.active { + background: rgba(244,183,64,0.12); + color: var(--accent); + border-color: rgba(244,183,64,0.3); +} +.lib-tag-count { color: var(--muted); font-size: 11px; } + +/* ── Clear bin bar (trash view only) ── */ +.clear-bin-bar { display: none; padding: 6px 10px 4px; } +.sidebar.trash-view .clear-bin-bar { display: block; } +.sidebar.trash-view .daw-lib-header { display: none; } +.sidebar.favorites-view .daw-lib-header { display: none; } +.clear-bin-btn { + display: flex; align-items: center; gap: 5px; + width: 100%; padding: 6px 10px; border-radius: 6px; + background: rgba(229, 78, 78, 0.12); border: 1px solid rgba(229, 78, 78, 0.28); + color: #e54e4e; font-size: 12px; font-weight: 500; cursor: pointer; + transition: background 150ms, border-color 150ms; +} +.clear-bin-btn:hover { background: rgba(229, 78, 78, 0.22); border-color: rgba(229, 78, 78, 0.5); } +.clear-bin-btn:active { background: rgba(229, 78, 78, 0.32); } + +/* ── App state classes (set by JS) ── */ +/* No track loaded: hide main waveform content */ +.daw.is-import .daw-track-header, +.daw.is-import .daw-section-ribbon, +.daw.is-import .daw-wave-header, +.daw.is-import .daw-content { opacity: 0.3; pointer-events: none; } + +.daw.no-track .daw-track-header, +.daw.no-track .daw-section-ribbon, +.daw.no-track .daw-wave-header, +.daw.no-track .daw-content { opacity: 0.3; pointer-events: none; } + +/* When track is playing */ +.daw-play-btn .pause-icon { display: none; } + +/* ── Responsive: hide zoom in small windows ── */ +@media (max-width: 900px) { + .daw-info-row { flex-wrap: wrap; } + .daw-track-card { width: 100%; border-right: none; border-bottom: 1px solid var(--border); } + .stem-presence-panel { grid-template-columns: repeat(3, 1fr); } +} diff --git a/static/css/variables.css b/static/css/variables.css index 22b9693b..a6f23667 100644 --- a/static/css/variables.css +++ b/static/css/variables.css @@ -1,49 +1,69 @@ +/* ── Design tokens ── */ :root { color-scheme: dark; - --bg: #0a0a0a; - --bg-deep: #050505; - --panel: rgba(15, 24, 30, 0.78); - --panel-2: rgba(21, 31, 39, 0.82); - --panel-hover: rgba(31, 43, 52, 0.88); - --ink: #ececec; - --ink-dim: #9c9c9c; - --ink-faint: #6c6c6c; - --line: rgba(157, 170, 182, 0.14); - --line-strong: rgba(186, 197, 208, 0.24); - --gold: #d8a84a; - --gold-bright: #f1cf82; - --gold-soft: rgba(216, 168, 74, 0.16); - --gold-line: rgba(216, 168, 74, 0.28); - --glass: rgba(14, 23, 30, 0.78); - --glass-strong: rgba(24, 34, 43, 0.82); - --glass-line: rgba(157, 170, 182, 0.16); - --shadow-panel: 0 24px 70px rgba(0, 0, 0, 0.3); - --accent: #6fb060; - --danger: #d65a4a; - --focus-ring: rgba(236, 236, 236, 0.55); - - --header-w: 320px; - --lane-h: 96px; - --radius: 8px; - --radius-sm: 6px; - --radius-xs: 4px; - --border-w: 1px; - - --font-mono: "JetBrains Mono", "SF Mono", "Menlo", "Consolas", monospace; - - --t-fast: 120ms; - --t-base: 180ms; - --easing: cubic-bezier(0.2, 0.8, 0.2, 1); + + /* Surfaces */ + --bg: #0b0f12; + --bg-2: #0f1418; + --panel: #131a1f; + --panel-2: #182026; + --panel-3: #1d262d; + --border: #232c34; + --border-strong: #2e3942; + + /* Text */ + --fg: #e8ecf0; + --fg-2: #c2c9d1; + --muted: #8a939c; + --muted-2: #5d666e; + + /* Stem colours */ + --vocals: #ef4444; + --drums: #f97316; + --bass: #eab308; + --guitar: #22c55e; + --piano: #a855f7; + --other: #9ca3af; + + /* Accent */ + --accent: #f4b740; + --accent-2: #d99a2b; + + /* Legacy compat aliases used by waves.css / player.js */ + --gold: var(--accent); + --gold-bright: #f8c054; + --gold-soft: rgba(244,183,64,0.16); + --gold-line: rgba(244,183,64,0.28); + --ink: var(--fg); + --ink-dim: var(--fg-2); + --ink-faint: var(--muted); + --line: var(--border); + --line-strong: var(--border-strong); + --glass-line: var(--border); + --danger: #d65a4a; + --focus-ring: rgba(236,236,236,0.55); + + /* Typography */ + --font-sans: 'Inter', -apple-system, system-ui, sans-serif; + --font-mono: 'JetBrains Mono', ui-monospace, 'SF Mono', Menlo, Consolas, monospace; + + /* Layout */ + --header-w: 300px; + --lane-h: 86px; + --radius: 10px; + --radius-sm: 8px; + --radius-xs: 6px; + + /* Motion */ + --t-fast: 80ms; + --t-base: 120ms; + --easing: cubic-bezier(0.2,0.8,0.2,1); + --shadow-panel: 0 4px 24px rgba(0,0,0,0.4); } @media (prefers-reduced-motion: reduce) { - :root { - --t-fast: 0ms; - --t-base: 0ms; - } - *, - *::before, - *::after { + :root { --t-fast: 0ms; --t-base: 0ms; } + *, *::before, *::after { animation-duration: 0.001ms !important; animation-iteration-count: 1 !important; transition-duration: 0.001ms !important; diff --git a/static/index.html b/static/index.html index ac3357a5..cd2d3c92 100644 --- a/static/index.html +++ b/static/index.html @@ -3,498 +3,679 @@ - StemDeck + StemDeck — split any track into stems - + - - - - - - - - - + -
- - -
-
-
-
-
-

- -

- ALPHA + +
+ + +
+ +
+ + StemDeck + +
+ + + +
+ + +
+ + +
+ + + + - AI stem separation -
…
+ +
- -
- - + -
-
- Stems to extract - - - - - - -
-
-
-
- - -
-
-
SD
-
- -
-
-
-
-
-
-
- - -
+ + + -
- - - Help - - - -
-
-

Library

- 0 tracks - + +
- + + +
- + +
-
+ +
- + + + + + + + + diff --git a/static/js/catalog.js b/static/js/catalog.js index 91cca9b7..5440eeb4 100644 --- a/static/js/catalog.js +++ b/static/js/catalog.js @@ -1,10 +1,13 @@ // catalog.js — library panel: folders, tracks, collapse, drag-and-drop import { STEM_NAMES } from "./constants.js"; -import { wireUpAudio } from "./player.js"; +import { wireUpAudio, updateFooterTrack } from "./player.js"; +import { initSections } from "./sections.js"; import { bpmChip, keyChip, saveSelectedStems, selectedStems, titleEl } from "./state.js"; +import { fmtTime } from "./utils.js"; const STORAGE_KEY = "stemdeck.folders"; const STORAGE_VERSION = 2; // bump to wipe stale seeded data +const DELETED_JOBS_KEY = "stemdeck.deleted_jobs"; let folders = []; let tracks = {}; @@ -19,13 +22,26 @@ const PROCESSING_STATUSES = new Set(["queued", "downloading", "analyzing", "sepa const FOLDER_COLORS = ["#d8a84a", "#e85f6f", "#64c86f", "#4f9de8", "#a985f4"]; const DEFAULT_FOLDER_COLOR = FOLDER_COLORS[0]; const TRACK_DRAG_TYPE = "application/x-stemdeck-track"; +const FOLDER_DRAG_TYPE = "application/x-stemdeck-folder"; + +function getDeletedJobIds() { + try { return new Set(JSON.parse(localStorage.getItem(DELETED_JOBS_KEY) || "[]")); } + catch { return new Set(); } +} + +function markJobsDeleted(ids) { + const set = getDeletedJobIds(); + for (const id of ids) set.add(id); + try { localStorage.setItem(DELETED_JOBS_KEY, JSON.stringify([...set])); } + catch (e) { console.warn("[catalog] failed to persist deleted jobs", e); } +} function normalizeFolderColor(color) { return FOLDER_COLORS.includes(color) ? color : DEFAULT_FOLDER_COLOR; } -function makeFolder({ id = `f-${Date.now()}`, name = "New folder", collapsed = false, items = [] } = {}) { - return { id, name, collapsed, items, color: DEFAULT_FOLDER_COLOR }; +function makeFolder({ id = `f-${Date.now()}`, name = "New folder", collapsed = false, items = [], parentId = null } = {}) { + return { id, name, collapsed, items, color: DEFAULT_FOLDER_COLOR, parentId: parentId ?? null }; } function ensureTrash() { @@ -46,7 +62,13 @@ function removeTrackFromFolders(trackId) { } function normalizeSource(value) { - return String(value || "").trim(); + const s = String(value || "").trim(); + if (!s) return s; + // Normalize YouTube URLs to the bare video ID so that youtu.be/xxx, + // youtube.com/watch?v=xxx, and variants with &t= / ?si= all match. + const yt = s.match(/(?:youtu\.be\/|[?&]v=)([a-zA-Z0-9_-]{11})/); + if (yt) return `yt:${yt[1]}`; + return s; } function normalizeSearch(value) { @@ -56,11 +78,16 @@ function normalizeSearch(value) { function trackMatchesSearch(track) { const q = normalizeSearch(catalogSearchQuery); if (!q) return true; + if (q.startsWith("#")) { + const tag = q.slice(1); + return (track?.tags ?? []).some((t) => String(t).toLowerCase() === tag); + } return [ track?.title, track?.channel, track?.sourceUrl, ...(track?.stems || []), + ...(track?.tags || []), ].some((value) => String(value || "").toLowerCase().includes(q)); } @@ -106,6 +133,13 @@ function loadState() { if ((data.v ?? 1) >= STORAGE_VERSION) { folders = data.folders ?? []; tracks = data.tracks ?? {}; + // Migrate old timestamp-based "Unsorted" folder to reserved ID. + const oldUnsorted = folders.find((f) => f.id !== TRASH_ID && f.name === "Unsorted" && f.id !== "f-unsorted"); + if (oldUnsorted) { oldUnsorted.id = "f-unsorted"; changed = true; } + // Ensure all folders have parentId field. + for (const f of folders) { + if (!Object.prototype.hasOwnProperty.call(f, "parentId")) { f.parentId = null; changed = true; } + } // Drop title-less entries left over from before metadata persistence. const noTitle = Object.keys(tracks).filter((id) => !tracks[id].title); if (noTitle.length) { @@ -129,7 +163,13 @@ function loadState() { } } } - changed = purgeTrash() || changed; + // Remove trash refs whose track data is missing (orphaned), but don't auto-empty. + const trashFolder = folders.find((f) => f.id === TRASH_ID); + if (trashFolder) { + const before = trashFolder.items.length; + trashFolder.items = trashFolder.items.filter((id) => tracks[id]); + if (trashFolder.items.length !== before) changed = true; + } if (changed) saveState(); } @@ -145,14 +185,31 @@ function saveState() { export function addTrackToLibrary(track) { // track: { id, title, channel, thumb, stems, status, sourceUrl } const existingId = findTrackBySource(track.sourceUrl, track.id); - if (existingId) replaceTrackId(existingId, track.id); - tracks[track.id] = { ...(tracks[track.id] || {}), ...track }; + if (existingId) { + const trash = getTrashFolder(); + const inTrash = trash?.items.includes(existingId); + if (inTrash) { + // Old track was trashed — delete it silently so the new import lands + // in the library instead of inheriting the trash placement. + delete tracks[existingId]; + for (const f of folders) f.items = f.items.filter((id) => id !== existingId); + } else { + replaceTrackId(existingId, track.id); + } + } + const existing = tracks[track.id] || {}; + tracks[track.id] = { + ...existing, + ...track, + createdAt: existing.createdAt ?? track.createdAt ?? (Date.now() / 1000), + favorite: existing.favorite ?? false, + }; const alreadyPlaced = folders.some((folder) => folder.items.includes(track.id)); if (!alreadyPlaced) { // Put into first non-trash folder or create an "Unsorted" folder. let target = folders.find((folder) => folder.id !== TRASH_ID); if (!target) { - target = makeFolder({ id: `f-${Date.now()}`, name: "Unsorted" }); + target = makeFolder({ id: "f-unsorted", name: "Unsorted" }); folders.unshift(target); } target.items.unshift(track.id); @@ -199,37 +256,139 @@ function stateMetadataToTrack(state, fallbackTrack) { keyConfidence: state.key_confidence ?? fallbackTrack.keyConfidence, lufs: state.lufs ?? fallbackTrack.lufs, peakDb: state.peak_db ?? fallbackTrack.peakDb, + stemPresence: state.stem_presence ?? fallbackTrack.stemPresence, + dynamicRange: state.dynamic_range ?? fallbackTrack.dynamicRange, + tempoStability: state.tempo_stability ?? fallbackTrack.tempoStability, + tags: state.tags ?? fallbackTrack.tags ?? [], + sections: state.sections ?? fallbackTrack.sections ?? null, sourceUrl: state.source_url || fallbackTrack.sourceUrl, + mixUrl: state.mix_url ?? fallbackTrack.mixUrl ?? null, + createdAt: fallbackTrack.createdAt ?? state.created_at, + favorite: fallbackTrack.favorite ?? false, }; } +function fmtExtracted(ts) { + if (!ts) return "—"; + return new Date(ts * 1000).toLocaleString("en-US", { + month: "long", day: "numeric", year: "numeric", + hour: "numeric", minute: "2-digit", + }); +} + +function deriveSource(sourceUrl) { + if (!sourceUrl) return "—"; + if (sourceUrl.startsWith("local:")) return "Local file"; + if (sourceUrl.includes("youtube.com") || sourceUrl.includes("youtu.be")) return "YouTube"; + return "Web"; +} + +function deriveQuality(sourceUrl) { + if (!sourceUrl) return "—"; + if (sourceUrl.startsWith("local:")) { + const ext = sourceUrl.split(".").pop()?.toLowerCase(); + if (ext === "wav") return "Lossless (WAV)"; + if (ext === "mp3") return "Compressed (MP3)"; + return "Local file"; + } + if (sourceUrl.includes("youtube.com") || sourceUrl.includes("youtu.be")) return "High"; + return "—"; +} + +function drLabel(dr) { + if (dr < 7) return "Compressed"; + if (dr < 10) return "Moderate"; + if (dr < 14) return "High"; + return "Wide"; +} + +function stabilityLabel(pct) { + if (pct >= 90) return "Very Stable"; + if (pct >= 70) return "Stable"; + if (pct >= 50) return "Moderate"; + return "Variable"; +} + +export function applyStemPresenceCards(stemPresence) { + const cards = document.querySelectorAll(".stem-presence-panel .stem-card"); + cards.forEach((card) => { + const stem = card.dataset.stem; + const pct = stemPresence?.[stem]; + const label = card.querySelector(".stem-card-pct"); + if (pct != null && pct > 0) { + card.classList.remove("inactive"); + if (label) label.textContent = `${pct}%`; + } else { + card.classList.add("inactive"); + if (label) label.textContent = pct === 0 ? "0%" : "—"; + } + }); +} + function applyTrackInfoToPanel(track) { titleEl.textContent = track.title || "Untitled track"; bpmChip.textContent = track.bpm ? `${track.bpm} BPM` : "— BPM"; keyChip.textContent = track.key || "— —"; + updateFooterTrack({ + title: track.title, + thumbnail: track.thumb, + key: track.key, + bpm: track.bpm, + stemCount: (track.audioStems || track.stems || []).filter((s) => (s.name ?? s) !== "original").length || null, + }); + applyStemPresenceCards(track.stemPresence); const summaryKey = document.getElementById("summary-key"); const summaryBpm = document.getElementById("summary-bpm"); const summaryScale = document.getElementById("summary-scale"); + const summaryScaleName = document.getElementById("summary-scale-name"); const summaryConfidence = document.getElementById("summary-confidence"); const summaryConfidenceLabel = document.getElementById("summary-confidence-label"); - const loudnessCard = document.getElementById("loudness-card"); const summaryLufs = document.getElementById("summary-lufs"); const summaryPeak = document.getElementById("summary-peak"); + const summaryDuration = document.getElementById("summary-duration"); if (summaryKey) summaryKey.textContent = track.key || "—"; - if (summaryBpm) { - summaryBpm.textContent = ""; - if (track.bpm) { - const bpmNum = document.createTextNode(`${track.bpm} `); - const bpmUnit = document.createElement("small"); - bpmUnit.textContent = "BPM"; - summaryBpm.append(bpmNum, bpmUnit); - } else { - summaryBpm.innerHTML = "— BPM"; - } - } + if (summaryBpm) summaryBpm.textContent = track.bpm ? String(track.bpm) : "—"; if (summaryScale) summaryScale.textContent = track.scale || ""; + if (summaryScaleName) summaryScaleName.textContent = track.scale || "—"; + if (summaryLufs) summaryLufs.textContent = track.lufs != null ? Number(track.lufs).toFixed(1) : "—"; + if (summaryPeak) summaryPeak.textContent = track.peakDb != null ? `Peak ${Number(track.peakDb).toFixed(1)} dB` : ""; + if (summaryDuration) summaryDuration.textContent = track.duration ? fmtTime(track.duration) : "—"; + + const trackExtracted = document.getElementById("track-extracted"); + const trackSource = document.getElementById("track-source"); + const trackQuality = document.getElementById("track-quality"); + const favBtn = document.getElementById("fav-btn"); + if (trackExtracted) trackExtracted.textContent = fmtExtracted(track.createdAt); + if (trackSource) trackSource.textContent = deriveSource(track.sourceUrl); + if (trackQuality) trackQuality.textContent = deriveQuality(track.sourceUrl); + if (favBtn) { + favBtn.classList.toggle("active", Boolean(track.favorite)); + favBtn.setAttribute("aria-pressed", String(Boolean(track.favorite))); + favBtn.onclick = () => { + if (!_currentTrackId) return; + const t = tracks[_currentTrackId]; + if (!t) return; + t.favorite = !t.favorite; + favBtn.classList.toggle("active", t.favorite); + favBtn.setAttribute("aria-pressed", String(t.favorite)); + saveState(); + }; + } + + const summaryDr = document.getElementById("summary-dr"); + const summaryDrLabel = document.getElementById("summary-dr-label"); + const summaryStability = document.getElementById("summary-stability"); + const summaryStabilityLabel = document.getElementById("summary-stability-label"); + if (summaryDr) summaryDr.textContent = track.dynamicRange != null ? String(track.dynamicRange) : "—"; + if (summaryDrLabel) summaryDrLabel.textContent = track.dynamicRange != null ? drLabel(track.dynamicRange) : ""; + if (summaryStability) { + summaryStability.textContent = track.tempoStability != null ? `${track.tempoStability}%` : "—"; + summaryStability.className = "meta-card-value" + (track.tempoStability != null && track.tempoStability >= 80 ? " stability-high" : ""); + } + if (summaryStabilityLabel) summaryStabilityLabel.textContent = track.tempoStability != null ? stabilityLabel(track.tempoStability) : ""; + if (summaryConfidence) { summaryConfidence.textContent = ""; summaryConfidence.style.removeProperty("--confidence-pct"); @@ -245,14 +404,6 @@ function applyTrackInfoToPanel(track) { summaryConfidenceLabel?.classList.remove("hidden"); } } - if (loudnessCard) { - const hasLoudness = track.lufs != null && track.peakDb != null; - loudnessCard.classList.toggle("hidden", !hasLoudness); - if (hasLoudness) { - if (summaryLufs) summaryLufs.textContent = Number(track.lufs).toFixed(1); - if (summaryPeak) summaryPeak.textContent = Number(track.peakDb).toFixed(1); - } - } } function moveTrackToTrash(trackId) { @@ -266,9 +417,9 @@ function moveTrackToTrash(trackId) { } function setCatalogView(view) { - catalogView = view === "trash" ? "trash" : "library"; + catalogView = ["trash", "favorites"].includes(view) ? view : "library"; const app = document.querySelector(".app"); - if (catalogView === "trash") { + if (catalogView === "trash" || catalogView === "favorites") { app?.classList.remove("cat-collapsed"); localStorage.setItem("stemdeck.catalog.collapsed", "0"); } @@ -292,17 +443,17 @@ async function loadTrackIntoStudio(trackId) { if (!track) return; const hadStoredAudio = Boolean(track.audioStems?.length); - if (!track.audioStems?.length || !hasTrackAnalysis(track)) { - try { - const res = await fetch(`/api/jobs/${trackId}`); - if (res.ok) { - const state = await res.json(); - track = stateMetadataToTrack(state, track); - tracks[trackId] = track; - saveState(); - } - } catch { /* ignore; the stored track may be from a previous server run */ } - } + // Always fetch fresh state so server-side changes (sections, analysis, stems) + // are reflected — cached localStorage data can be stale. + try { + const res = await fetch(`/api/jobs/${trackId}`); + if (res.ok) { + const state = await res.json(); + track = stateMetadataToTrack(state, track); + tracks[trackId] = track; + saveState(); + } + } catch { /* ignore; use stored track if server unreachable */ } if (!track.audioStems?.length) return; if (track.status !== "done" && !hadStoredAudio) return; @@ -317,7 +468,8 @@ async function loadTrackIntoStudio(trackId) { } applyTrackInfoToPanel(track); - wireUpAudio(trackId, track.audioStems, track.duration || 0, track.thumb); + wireUpAudio(trackId, track.audioStems, track.duration || 0, track.thumb, track.mixUrl ?? null); + initSections(trackId, track.sections, track.duration || 0); } export function setCurrentTrack(trackId) { @@ -339,8 +491,11 @@ function createFolder() { } function deleteFolder(folderId) { + if (folderId === TRASH_ID) return; + // Cascade: delete children first. + for (const child of folders.filter((f) => f.parentId === folderId)) deleteFolder(child.id); const idx = folders.findIndex((f) => f.id === folderId); - if (idx === -1 || folders[idx].id === TRASH_ID) return; + if (idx === -1) return; const [folder] = folders.splice(idx, 1); const trash = getTrashFolder(); for (const trackId of folder.items) { @@ -352,6 +507,37 @@ function deleteFolder(folderId) { render(); } +function reorderFolder(draggedId, targetId, before) { + if (draggedId === targetId) return; + const dragged = folders.find((f) => f.id === draggedId); + const target = folders.find((f) => f.id === targetId); + if (!dragged || !target) return; + folders.splice(folders.indexOf(dragged), 1); + const toIdx = folders.indexOf(target); + folders.splice(before ? toIdx : toIdx + 1, 0, dragged); + saveState(); + render(); +} + +function isFolderDescendant(ancestorId, candidateId) { + let cur = folders.find((f) => f.id === candidateId); + while (cur?.parentId) { + if (cur.parentId === ancestorId) return true; + cur = folders.find((f) => f.id === cur.parentId); + } + return false; +} + +function reparentFolder(childId, newParentId) { + if (childId === newParentId) return; + if (isFolderDescendant(childId, newParentId)) return; // would create cycle + const child = folders.find((f) => f.id === childId); + if (!child) return; + child.parentId = newParentId; + saveState(); + render(); +} + let folderEditor = null; function folderColorButtonsHtml(activeColor) { @@ -451,6 +637,7 @@ function openFolderEditor(folderId) { // ─── Drag-and-drop ─── let dragId = null; +let folderDragId = null; function isTrackDragEvent(event) { return dragId != null || Boolean(event?.dataTransfer?.types?.includes(TRACK_DRAG_TYPE)); @@ -564,7 +751,7 @@ function restoreTrackFromTrash(trackId) { trash.items = trash.items.filter((id) => id !== trackId); let target = folders.find((f) => f.id !== TRASH_ID); if (!target) { - target = makeFolder({ id: `f-${Date.now()}`, name: "Unsorted" }); + target = makeFolder({ id: "f-unsorted", name: "Unsorted" }); folders.unshift(target); } if (!target.items.includes(trackId)) target.items.push(trackId); @@ -614,6 +801,58 @@ function wireLibraryDeleteKeys() { }); } +// ─── Rendering helpers ─── + +function getRecentTracks(trashIds, n = 3) { + return Object.entries(tracks) + .filter(([id, t]) => !trashIds.has(id) && t.title) + .sort(([, a], [, b]) => (b.createdAt ?? 0) - (a.createdAt ?? 0)) + .slice(0, n) + .map(([id]) => id); +} + +function getAllTags(trashIds) { + const counts = {}; + for (const [id, track] of Object.entries(tracks)) { + if (trashIds.has(id)) continue; + for (const tag of track.tags ?? []) { + counts[tag] = (counts[tag] || 0) + 1; + } + } + return Object.entries(counts).sort(([, a], [, b]) => b - a); +} + +function makeSectionEl(labelText) { + const section = document.createElement("div"); + section.className = "lib-section"; + const head = document.createElement("div"); + head.className = "lib-section-head"; + head.textContent = labelText; + section.appendChild(head); + return section; +} + +function renderRecentItem(trackId) { + const track = tracks[trackId]; + if (!track) return null; + const el = document.createElement("div"); + el.className = `cat-item${trackId === _currentTrackId ? " active" : ""}`; + el.dataset.id = trackId; + const duration = track.duration ? fmtTime(track.duration) : ""; + const stemCount = track.stems?.length ?? 0; + const sub = [duration, `${stemCount} stem${stemCount !== 1 ? "s" : ""}`].filter(Boolean).join(" · "); + el.innerHTML = ` +
${thumbHtml(track)}
+
+
${track.title ?? "Unknown track"}
+
${sub}
+
+
+ `; + wireTrackDragAndLoad(el, trackId); + return el; +} + // ─── Rendering ─── function thumbHtml(track) { @@ -679,53 +918,76 @@ function renderTrackItem(trackId, { inTrash = false } = {}) { function renderFolder(folder) { const isTrash = folder.id === TRASH_ID; + const isSubfolder = Boolean(folder.parentId); if (!isTrash) folder.color = normalizeFolderColor(folder.color); const el = document.createElement("div"); - el.className = `folder${folder.collapsed ? " collapsed" : ""}`; + el.className = `folder${folder.collapsed ? " collapsed" : ""}${isSubfolder ? " subfolder" : ""}`; el.dataset.id = folder.id; const head = document.createElement("div"); head.className = "folder-head"; if (!isTrash) head.style.setProperty("--folder-color", folder.color); + const folderIcon = isTrash ? `` : ``; + head.innerHTML = ` + ${isTrash ? "" : ` + + `} ${folderIcon} ${folder.name} ${folder.items.length} - ${isTrash ? "" : ``} + ${isTrash ? "" : ` + + + `} `; const body = document.createElement("div"); body.className = "folder-body"; const visibleItems = folder.items.filter((id) => trackMatchesSearch(tracks[id])); + const childFolders = folders.filter((f) => f.parentId === folder.id); - if (catalogSearchQuery && visibleItems.length === 0) { + if (catalogSearchQuery && visibleItems.length === 0 && childFolders.length === 0) { return null; } - if (visibleItems.length === 0) { + if (visibleItems.length === 0 && childFolders.length === 0) { body.innerHTML = 'Empty folder'; } else { for (const id of visibleItems) { const item = renderTrackItem(id); if (item) body.appendChild(item); } + for (const child of childFolders) { + const childEl = renderFolder(child); + if (childEl) body.appendChild(childEl); + } } el.append(head, body); let folderClickTimer = null; - // Toggle folder collapse on a single click. Double-click is reserved for edit. + // Toggle folder collapse on single click. head.addEventListener("click", (e) => { - if (e.target.closest(".f-del")) return; + if (e.target.closest(".f-del, .f-subfolder, .f-grip")) return; if (e.detail !== 1) return; window.clearTimeout(folderClickTimer); folderClickTimer = window.setTimeout(() => { @@ -735,34 +997,85 @@ function renderFolder(folder) { }, 180); }); - // Edit folder name + color on double-click (not for trash). if (!isTrash) { head.addEventListener("dblclick", (e) => { - if (e.target.closest(".f-del")) return; + if (e.target.closest(".f-del, .f-subfolder, .f-grip")) return; window.clearTimeout(folderClickTimer); e.stopPropagation(); openFolderEditor(folder.id); }); } - // Delete head.querySelector(".f-del")?.addEventListener("click", (e) => { e.stopPropagation(); deleteFolder(folder.id); }); - // Drag-over for drop target + head.querySelector(".f-subfolder")?.addEventListener("click", (e) => { + e.stopPropagation(); + const child = makeFolder({ parentId: folder.id }); + folders.push(child); + folder.collapsed = false; + el.classList.remove("collapsed"); + saveState(); + render(); + openFolderEditor(child.id); + }); + + // Folder drag handle — reorder folders. + const grip = head.querySelector(".f-grip"); + if (grip) { + grip.draggable = true; + grip.addEventListener("dragstart", (e) => { + folderDragId = folder.id; + e.dataTransfer.effectAllowed = "move"; + e.dataTransfer.setData(FOLDER_DRAG_TYPE, folder.id); + e.stopPropagation(); + requestAnimationFrame(() => el.classList.add("folder-dragging")); + }); + grip.addEventListener("dragend", () => { + folderDragId = null; + el.classList.remove("folder-dragging"); + for (const f of document.querySelectorAll(".folder.drop-before, .folder.drop-after, .folder.drop-into")) { + f.classList.remove("drop-before", "drop-after", "drop-into"); + } + }); + } + + // Dragover: folder reorder/nest indicator OR track drop target. el.addEventListener("dragover", (e) => { + if (folderDragId && folderDragId !== folder.id && !isTrash) { + if (isFolderDescendant(folderDragId, folder.id)) return; // prevent cycle + e.preventDefault(); + e.dataTransfer.dropEffect = "move"; + const rect = head.getBoundingClientRect(); + const rel = (e.clientY - rect.top) / rect.height; + el.classList.toggle("drop-before", rel < 0.25); + el.classList.toggle("drop-into", rel >= 0.25 && rel < 0.75); + el.classList.toggle("drop-after", rel >= 0.75); + return; + } if (!isTrackDragEvent(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = "move"; el.classList.add("drop-target"); }); el.addEventListener("dragleave", (e) => { - if (!el.contains(e.relatedTarget)) el.classList.remove("drop-target"); + if (!el.contains(e.relatedTarget)) { + el.classList.remove("drop-target", "drop-before", "drop-after", "drop-into"); + } }); el.addEventListener("drop", (e) => { e.preventDefault(); + if (folderDragId && folderDragId !== folder.id && !isTrash) { + const rect = head.getBoundingClientRect(); + const rel = (e.clientY - rect.top) / rect.height; + el.classList.remove("drop-before", "drop-after", "drop-into"); + if (rel < 0.25) reorderFolder(folderDragId, folder.id, true); + else if (rel >= 0.75) reorderFolder(folderDragId, folder.id, false); + else reparentFolder(folderDragId, folder.id); + return; + } el.classList.remove("drop-target"); dropOnFolder(folder.id, getDraggedTrackId(e)); }); @@ -770,10 +1083,34 @@ function renderFolder(folder) { return el; } +function renderStrip(strip, nonTrash) { + if (!strip) return; + const folderTrackIds = new Set(folders.flatMap((folder) => folder.items)); + for (const [trackId, track] of Object.entries(tracks)) { + if (folderTrackIds.has(trackId)) continue; + strip.appendChild(makeStripItem({ + className: trackId === _currentTrackId ? "active" : "", + id: trackId, + title: track.title, + html: thumbHtml(track), + trackId, + })); + } + for (const folder of nonTrash) { + const folderColor = normalizeFolderColor(folder.color); + strip.appendChild(makeStripItem({ + className: "folder-thumb", + id: folder.id, + title: `${folder.name} (${folder.items.length})`, + html: folderThumbHtml(false), + color: folderColor, + })); + } +} + function render() { const list = document.getElementById("catalogList"); const strip = document.getElementById("catalogStrip"); - const count = document.getElementById("catCount"); const catalog = document.getElementById("catalogPanel"); const searchInput = document.getElementById("catalogSearch"); if (!list) return; @@ -783,27 +1120,27 @@ function render() { const trash = getTrashFolder(); const trashIds = new Set(trash?.items || []); - const totalTracks = Object.keys(tracks).filter((id) => !trashIds.has(id)).length; const isTrashView = catalogView === "trash"; + const isFavoritesView = catalogView === "favorites"; + const isLibraryView = !isTrashView && !isFavoritesView; catalog?.classList.toggle("trash-view", isTrashView); - document.querySelector(".rail-library")?.classList.toggle("active", !isTrashView); - document.querySelector(".rail-library")?.setAttribute("aria-pressed", String(!isTrashView)); + catalog?.classList.toggle("favorites-view", isFavoritesView); + + document.querySelector(".rail-library")?.classList.toggle("active", isLibraryView); + document.querySelector(".rail-library")?.setAttribute("aria-pressed", String(isLibraryView)); + document.querySelector(".rail-favorites")?.classList.toggle("active", isFavoritesView); + document.querySelector(".rail-favorites")?.setAttribute("aria-pressed", String(isFavoritesView)); document.querySelector(".rail-trash")?.classList.toggle("active", isTrashView); document.querySelector(".rail-trash")?.setAttribute("aria-pressed", String(isTrashView)); - if (count) { - const n = isTrashView ? trashIds.size : totalTracks; - count.textContent = isTrashView - ? `${n} deleted` - : `${n} track${n !== 1 ? "s" : ""}`; - } + if (searchInput) { - searchInput.placeholder = isTrashView - ? "Search trash…" - : "Search library…"; + searchInput.placeholder = isTrashView ? "Search trash…" : isFavoritesView ? "Search favorites…" : "Search library…"; } - const nonTrash = folders.filter((f) => f.id !== TRASH_ID); + const nonTrash = folders.filter((f) => f.id !== TRASH_ID && !f.parentId); + + // ── Trash view ── if (isTrashView) { const visibleTrashItems = (trash?.items || []).filter((id) => trackMatchesSearch(tracks[id])); if (!trash?.items.length) { @@ -819,42 +1156,85 @@ function render() { return; } - let renderedFolders = 0; + // ── Favorites view ── + if (isFavoritesView) { + const favIds = Object.entries(tracks) + .filter(([id, t]) => !trashIds.has(id) && t.favorite && trackMatchesSearch(t)) + .sort(([, a], [, b]) => (b.createdAt ?? 0) - (a.createdAt ?? 0)) + .map(([id]) => id); + if (!favIds.length) { + list.innerHTML = `${catalogSearchQuery ? "No favorites match your search" : "No favorites yet — click ♥ on a track to save it"}`; + } else { + for (const id of favIds) { + const item = renderRecentItem(id); + if (item) list.appendChild(item); + } + } + renderStrip(strip, nonTrash); + return; + } + + // ── Library view — Recent · Stem Collections · Tags ── + + // Recent section + const recentIds = getRecentTracks(trashIds).filter((id) => trackMatchesSearch(tracks[id])); + if (recentIds.length) { + const section = makeSectionEl("Recent"); + for (const id of recentIds) { + const item = renderRecentItem(id); + if (item) section.appendChild(item); + } + list.appendChild(section); + } + + // Stem Collections section + const collectionsSection = makeSectionEl("Stem Collections"); + let hasCollections = false; for (const folder of nonTrash) { const el = renderFolder(folder); if (!el) continue; - list.appendChild(el); - renderedFolders += 1; + collectionsSection.appendChild(el); + hasCollections = true; } - if (catalogSearchQuery && renderedFolders === 0) { + if (hasCollections) list.appendChild(collectionsSection); + + // Empty state when search yields nothing + if (catalogSearchQuery && !recentIds.length && !hasCollections) { list.innerHTML = 'No tracks match your search'; + return; } - // Collapsed strip: top-level structure only. Show unfiled songs, - // folders only. Trash lives in the side rail. - if (strip) { - const folderTrackIds = new Set(folders.flatMap((folder) => folder.items)); - for (const [trackId, track] of Object.entries(tracks)) { - if (folderTrackIds.has(trackId)) continue; - strip.appendChild(makeStripItem({ - className: trackId === _currentTrackId ? "active" : "", - id: trackId, - title: track.title, - html: thumbHtml(track), - trackId, - })); - } - for (const folder of nonTrash) { - const folderColor = normalizeFolderColor(folder.color); - strip.appendChild(makeStripItem({ - className: "folder-thumb", - id: folder.id, - title: `${folder.name} (${folder.items.length})`, - html: folderThumbHtml(false), - color: folderColor, - })); + // Tags section + const tags = getAllTags(trashIds); + if (tags.length) { + const section = makeSectionEl("Tags"); + const row = document.createElement("div"); + row.className = "lib-tags-row"; + const activeTag = catalogSearchQuery.startsWith("#") ? catalogSearchQuery.slice(1) : null; + for (const [tag, count] of tags) { + const chip = document.createElement("button"); + chip.className = `lib-tag-chip${activeTag === tag ? " active" : ""}`; + chip.type = "button"; + chip.dataset.tag = tag; + chip.innerHTML = `${tag} ${count}`; + chip.addEventListener("click", () => { + const input = document.getElementById("catalogSearch"); + if (catalogSearchQuery === `#${tag}`) { + catalogSearchQuery = ""; + if (input) input.value = ""; + } else { + catalogSearchQuery = `#${tag}`; + if (input) input.value = `#${tag}`; + } + render(); + }); + row.appendChild(chip); } + section.appendChild(row); + list.appendChild(section); } + + renderStrip(strip, nonTrash); } // ─── Catalog panel collapse ─── @@ -868,9 +1248,12 @@ function wireCatalogToggle() { const collapsed = localStorage.getItem("stemdeck.catalog.collapsed") === "1"; if (collapsed) app.classList.add("cat-collapsed"); - toggle.addEventListener("click", () => { - const isNowCollapsed = app.classList.toggle("cat-collapsed"); - localStorage.setItem("stemdeck.catalog.collapsed", isNowCollapsed ? "1" : "0"); + toggle.addEventListener("click", (e) => { + // Only expand — never collapse from within the sidebar. + if (!app.classList.contains("cat-collapsed")) return; + app.classList.remove("cat-collapsed"); + localStorage.setItem("stemdeck.catalog.collapsed", "0"); + toggle.querySelector("input")?.focus(); }); toggle.addEventListener("keydown", (e) => { if (e.code === "Enter" || e.code === "Space") { e.preventDefault(); toggle.click(); } @@ -879,7 +1262,19 @@ function wireCatalogToggle() { function wireCatalogRailViews() { document.querySelector(".rail-library")?.addEventListener("click", () => setCatalogView("library")); + document.querySelector(".rail-favorites")?.addEventListener("click", () => setCatalogView("favorites")); document.querySelector(".rail-trash")?.addEventListener("click", () => setCatalogView("trash")); + document.getElementById("clearBinBtn")?.addEventListener("click", () => { + const trash = getTrashFolder(); + const toDelete = [...(trash?.items || [])]; + markJobsDeleted(toDelete); // persist before purge so reload can't re-import + purgeTrash(); + saveState(); + render(); + for (const id of toDelete) { + fetch(`/api/jobs/${id}`, { method: "DELETE" }).catch(() => {}); + } + }); } function wireCatalogSearch() { @@ -987,8 +1382,12 @@ async function syncWithServer() { const res = await fetch("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/api/jobs", { cache: "no-store" }); if (!res.ok) return; const jobs = await res.json(); + const trashIds = new Set(getTrashFolder()?.items || []); + const deletedIds = getDeletedJobIds(); for (const state of jobs) { if (tracks[state.job_id]) continue; + if (trashIds.has(state.job_id)) continue; // soft-deleted, skip + if (deletedIds.has(state.job_id)) continue; // hard-deleted, skip const track = stateMetadataToTrack(state, { id: state.job_id, status: state.status }); track.id = state.job_id; addTrackToLibrary(track); diff --git a/static/js/job.js b/static/js/job.js index 83facab8..1fe5f5e3 100644 --- a/static/js/job.js +++ b/static/js/job.js @@ -4,10 +4,10 @@ import { eventSource, setEventSource, setCurrentJobId, currentJobId, selectedStems, } from "./state.js"; -import { destroyPlayer } from "./player.js"; -import { wireUpAudio } from "./player.js"; +import { destroyPlayer, wireUpAudio, setWaveformLoading, updateFooterTrack } from "./player.js"; import { stagePhrases } from "./phrases.js"; -import { addTrackToLibrary, setCurrentTrack, updateTrackStatus } from "./catalog.js"; +import { addTrackToLibrary, setCurrentTrack, updateTrackStatus, applyStemPresenceCards } from "./catalog.js"; +import { initSections } from "./sections.js"; // Playful stage label rotation (Claude-Code-style flair). The backend // emits truthful stage strings; we surface them in the small #job-detail @@ -114,7 +114,9 @@ function applyState(state) { keyConfidence: state.key_confidence, lufs: state.lufs, peakDb: state.peak_db, + stemPresence: state.stem_presence, sourceUrl: jobSources.get(state.job_id) || urlInput.value, + createdAt: state.created_at, }); setCurrentTrack(state.job_id); } @@ -124,23 +126,35 @@ function applyState(state) { } if (state.bpm) bpmChip.textContent = `${state.bpm} BPM`; if (state.key) keyChip.textContent = state.key; + if (state.title || state.bpm || state.key || state.thumbnail) { + updateFooterTrack({ + title: state.title, + thumbnail: state.thumbnail, + key: state.key, + bpm: state.bpm, + stemCount: state.stems ? state.stems.filter((s) => s.name !== "original").length : null, + }); + } const summaryKey = document.getElementById("summary-key"); const summaryBpm = document.getElementById("summary-bpm"); const summaryScale = document.getElementById("summary-scale"); + const summaryScaleName = document.getElementById("summary-scale-name"); const summaryConfidence = document.getElementById("summary-confidence"); const summaryConfidenceLabel = document.getElementById("summary-confidence-label"); - const loudnessCard = document.getElementById("loudness-card"); const summaryLufs = document.getElementById("summary-lufs"); const summaryPeak = document.getElementById("summary-peak"); + const summaryDuration = document.getElementById("summary-duration"); if (summaryKey && state.key) summaryKey.textContent = state.key; - if (summaryBpm && state.bpm) { - summaryBpm.textContent = ""; - const bpmNum = document.createTextNode(String(state.bpm) + " "); - const bpmUnit = document.createElement("small"); - bpmUnit.textContent = "BPM"; - summaryBpm.append(bpmNum, bpmUnit); - } + if (summaryBpm && state.bpm) summaryBpm.textContent = String(state.bpm); if (summaryScale && state.scale) summaryScale.textContent = state.scale; + if (summaryScaleName && state.scale) summaryScaleName.textContent = state.scale; + if (summaryLufs && state.lufs != null) summaryLufs.textContent = state.lufs.toFixed(1); + if (summaryPeak && state.peak_db != null) summaryPeak.textContent = `Peak ${state.peak_db.toFixed(1)} dB`; + if (summaryDuration && state.duration) { + const m = Math.floor(state.duration / 60); + const s = Math.floor(state.duration % 60).toString().padStart(2, "0"); + summaryDuration.textContent = `${m.toString().padStart(2, "0")}:${s}`; + } if (summaryConfidence && state.key_confidence != null) { const confidence = Math.max(0, Math.min(100, Number(state.key_confidence))); const confSpan = document.createElement("span"); @@ -151,13 +165,25 @@ function applyState(state) { summaryConfidence.classList.remove("hidden"); summaryConfidenceLabel?.classList.remove("hidden"); } - // LUFS and peak surface only when the analyzer produced numeric values. - // Silence or extremely short clips return null -- we keep the card - // hidden in that case rather than render "— LUFS". - if (loudnessCard && state.lufs != null && state.peak_db != null) { - if (summaryLufs) summaryLufs.textContent = state.lufs.toFixed(1); - if (summaryPeak) summaryPeak.textContent = state.peak_db.toFixed(1); - loudnessCard.classList.remove("hidden"); + const summaryDr = document.getElementById("summary-dr"); + const summaryDrLabel = document.getElementById("summary-dr-label"); + const summaryStability = document.getElementById("summary-stability"); + const summaryStabilityLabel = document.getElementById("summary-stability-label"); + if (summaryDr && state.dynamic_range != null) summaryDr.textContent = String(state.dynamic_range); + if (summaryDrLabel && state.dynamic_range != null) { + const dr = state.dynamic_range; + summaryDrLabel.textContent = dr < 7 ? "Compressed" : dr < 10 ? "Moderate" : dr < 14 ? "High" : "Wide"; + } + if (summaryStability && state.tempo_stability != null) { + summaryStability.textContent = `${state.tempo_stability}%`; + summaryStability.className = "meta-card-value" + (state.tempo_stability >= 80 ? " stability-high" : ""); + } + if (summaryStabilityLabel && state.tempo_stability != null) { + const s = state.tempo_stability; + summaryStabilityLabel.textContent = s >= 90 ? "Very Stable" : s >= 70 ? "Stable" : s >= 50 ? "Moderate" : "Variable"; + } + if (state.stem_presence != null) { + applyStemPresenceCards(state.stem_presence); } // Stage label is owned by the phrase-rotation timer below; we don't // overwrite it from each SSE tick. The truthful backend stage goes @@ -178,11 +204,13 @@ function applyState(state) { if (state.status === "error") { stopJobPolling(); updateTrackStatus(state.job_id, "error"); + setWaveformLoading(false); showError(state.error || "Unknown error"); setSubmitProcessing(false); } else if (state.status === "cancelled") { stopJobPolling(); updateTrackStatus(state.job_id, "cancelled"); + setWaveformLoading(false); jobBox.classList.add("hidden"); setSubmitProcessing(false); } else if (state.status === "done") { @@ -196,7 +224,9 @@ function applyState(state) { state.stems || [], state.duration || 0, state.thumbnail, + state.mix_url ?? null, ); + initSections(state.job_id, state.sections, state.duration || 0); } setSubmitProcessing(false); } @@ -336,6 +366,7 @@ export function wireJobForm() { const postUrlText = document.getElementById("post-url-text"); if (postUrlText) postUrlText.textContent = displayTitle; + setWaveformLoading(true); // Show progress box immediately for file uploads — the HTTP upload of a // large file takes time and the UI would otherwise appear frozen. if (file) { diff --git a/static/js/main.js b/static/js/main.js index 542ec406..4f6d63ca 100644 --- a/static/js/main.js +++ b/static/js/main.js @@ -1,9 +1,9 @@ import { - playBtn, loopBtn, multitrack, loopEnabled, loopStart, loopEnd, + playBtn, loopBtn, multitrack, totalDuration, loopEnabled, loopStart, loopEnd, setLoopStart, setLoopEnd, selectedStems, saveSelectedStems, } from "./state.js"; import { STEM_NAMES, syncStemNamesFromAPI } from "./constants.js"; -import { renderEmptyShell, buildStripStems } from "./player.js"; +import { renderEmptyShell, buildStripStems, downloadCurrentMix, downloadCurrentMixMp3, drawFooterPlaceholder } from "./player.js"; import { wireJobForm, showError } from "./job.js"; import { wireTransportButtons } from "./transport.js"; import { togglePlayPause, updateLoopRegionVisual } from "./transport.js"; @@ -65,18 +65,149 @@ function wireStemChoiceButtons() { } } +function wireAllButton() { + const allBtn = document.getElementById("stemAllBtn"); + if (!allBtn) return; + + function syncAllBtn() { + allBtn.setAttribute("aria-pressed", String(selectedStems.size === STEM_NAMES.length)); + } + + allBtn.addEventListener("click", () => { + const noneSelected = selectedStems.size === 0; + const allSelected = selectedStems.size === STEM_NAMES.length; + if (allSelected) { + selectedStems.clear(); + } else { + for (const n of STEM_NAMES) selectedStems.add(n); + } + saveSelectedStems(); + refreshStemChoiceVisuals(); + buildStripStems(); + syncAllBtn(); + }); + + /* Keep All in sync when individual stems are toggled */ + for (const btn of document.querySelectorAll(".stem-choice[data-stem]")) { + btn.addEventListener("click", syncAllBtn); + } + + syncAllBtn(); +} + // ─── Wire everything up ─── syncStemNamesFromAPI().then(() => buildStripStems()); wireJobForm(); wireTransportButtons(); +wireFooterControls(); +requestAnimationFrame(drawFooterPlaceholder); wireStemListControls(); wireMixerToolbar(); wireStemChoiceButtons(); +wireAllButton(); initCatalog(); wireFileDrop(); wireAppShellControls(); +// ─── Footer: speed dropdown, export dropdown, scrub seek ─── + +function wireFooterControls() { + // ── Speed dropdown ── + const speedBtn = document.getElementById("t-speed-btn"); + const speedPanel = document.getElementById("t-speed-panel"); + const speedLabel = document.getElementById("t-speed-label"); + + function applyRate(rate) { + const audios = multitrack?.audios; + if (audios?.length) { + for (const a of audios) { + const el = (a instanceof HTMLMediaElement) ? a : (a?.media ?? a?.getMediaElement?.()); + if (!(el instanceof HTMLMediaElement)) continue; + el.playbackRate = rate; + if ("preservesPitch" in el) el.preservesPitch = true; + else if ("mozPreservesPitch" in el) el.mozPreservesPitch = true; + } + } + if (speedLabel) speedLabel.textContent = `Speed ${rate === 1 ? "1.0" : rate}×`; + speedPanel?.querySelectorAll(".chip-panel-item").forEach((btn) => { + btn.classList.toggle("active", parseFloat(btn.dataset.rate) === rate); + }); + } + + speedBtn?.addEventListener("click", (e) => { + e.stopPropagation(); + const open = !speedPanel?.classList.contains("hidden"); + closeAllChipPanels(); + if (!open) { + speedPanel?.classList.remove("hidden"); + speedBtn.setAttribute("aria-expanded", "true"); + } + }); + + speedPanel?.addEventListener("click", (e) => { + const item = e.target.closest(".chip-panel-item[data-rate]"); + if (!item) return; + applyRate(parseFloat(item.dataset.rate)); + speedPanel.classList.add("hidden"); + speedBtn?.setAttribute("aria-expanded", "false"); + }); + + // ── Export dropdown ── + const exportBtn = document.getElementById("t-export-btn"); + const exportPanel = document.getElementById("t-export-panel"); + + exportBtn?.addEventListener("click", (e) => { + e.stopPropagation(); + const open = !exportPanel?.classList.contains("hidden"); + closeAllChipPanels(); + if (!open) { + exportPanel?.classList.remove("hidden"); + exportBtn.setAttribute("aria-expanded", "true"); + } + }); + + document.getElementById("t-export-wav")?.addEventListener("click", () => { + downloadCurrentMix(); + exportPanel?.classList.add("hidden"); + exportBtn?.setAttribute("aria-expanded", "false"); + }); + + document.getElementById("t-export-mp3")?.addEventListener("click", () => { + downloadCurrentMixMp3(); + exportPanel?.classList.add("hidden"); + exportBtn?.setAttribute("aria-expanded", "false"); + }); + + // ── Scrub bar seek ── + const scrub = document.getElementById("footer-scrub"); + if (scrub) { + function seekToX(clientX) { + if (!multitrack || !totalDuration) return; + const rect = scrub.getBoundingClientRect(); + const frac = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)); + multitrack.setTime(frac * totalDuration); + } + let _scrubbing = false; + scrub.addEventListener("mousedown", (e) => { + _scrubbing = true; + seekToX(e.clientX); + }); + document.addEventListener("mousemove", (e) => { if (_scrubbing) seekToX(e.clientX); }); + document.addEventListener("mouseup", () => { _scrubbing = false; }); + } + + // ── Close panels on outside click ── + document.addEventListener("click", closeAllChipPanels); +} + +function closeAllChipPanels() { + document.querySelectorAll(".footer-chip-panel:not(.hidden)").forEach((p) => { + p.classList.add("hidden"); + p.previousElementSibling?.setAttribute("aria-expanded", "false"); + }); +} + // ─── File drop on URL input ─── function wireFileDrop() { @@ -153,7 +284,15 @@ function wireFileDrop() { function wireAppShellControls() { document.getElementById("appMenuBtn")?.addEventListener("click", (e) => { e.stopPropagation(); - document.getElementById("catalogToggle")?.click(); + const app = document.querySelector(".app"); + // In trash view: switch back to library. + if (document.querySelector(".sidebar.trash-view, .sidebar.favorites-view")) { + document.querySelector(".rail-library")?.click(); + } + // If collapsed: open. Never collapse from the library button. + if (app?.classList.contains("cat-collapsed")) { + document.getElementById("catalogToggle")?.click(); + } }); } diff --git a/static/js/mixer.js b/static/js/mixer.js index 458c1036..aa0ba55d 100644 --- a/static/js/mixer.js +++ b/static/js/mixer.js @@ -57,18 +57,13 @@ export function applyMix() { const targetGain = effective * masterVolume; - // HTMLAudioElement.volume is capped at [0,1] by the browser spec. - // Values > 1 throw in Firefox/Safari (breaking the whole loop) and - // are silently clamped in Chrome (boost never audible). Route each - // HTMLAudioElement through a Web Audio GainNode instead — gain.value - // accepts any positive number, enabling real boost and reliable mute. const audioEl = multitrack.audios?.[idx]; if (audioEl instanceof HTMLMediaElement) { - // Use the HTMLAudioElement's native volume instead of routing through a - // MediaElementAudioSourceNode. WKWebView (Safari) does not reliably pass - // audio from MediaElementSource → GainNode → destination to the speakers, - // so we stay on the browser's default output path and cap gain at 1.0. - audioEl.volume = Math.min(1, Math.max(0, targetGain)); + // WKWebView does not pass audio through MediaElementSource → GainNode → + // destination. Use the native HTMLAudioElement volume path instead and + // cap at 1.0 (the spec limit). Boost above unity is not supported on + // this platform but basic volume/mute works reliably. + audioEl.volume = Math.max(0, Math.min(1, targetGain)); } else { multitrack.setTrackVolume(idx, targetGain); } @@ -79,8 +74,18 @@ export function updateLaneKnobVisual(knobEl, v) { const frac = Math.max(0, Math.min(1, v / LANE_VOLUME_MAX)); knobEl.style.setProperty("--lane-pos", frac.toFixed(3)); knobEl.setAttribute("aria-valuenow", v.toFixed(2)); + const input = knobEl.querySelector(".mx-fader-input"); + if (input) { + input.value = String(v); + // Set --lane-pos directly on the input so ::webkit-slider-runnable-track + // can see it — WebKit shadow DOM pseudo-elements don't inherit vars from ancestors. + input.style.setProperty("--lane-pos", frac.toFixed(3)); + } const val = knobEl.closest(".lane-header")?.querySelector(".mx-val"); - if (val) val.textContent = String(Math.round(frac * 100)); + if (val) { + const db = v <= 0 ? "-∞" : (20 * Math.log10(v)).toFixed(1); + val.textContent = db === "-∞" ? "-∞" : `${parseFloat(db) > 0 ? "+" : ""}${db}`; + } } export function setLaneVolume(name, v) { @@ -247,72 +252,27 @@ function makeVolumeKnob(stemName, color) { const wrap = document.createElement("div"); wrap.className = "lane-knob mx-fader"; wrap.dataset.stem = stemName; - wrap.tabIndex = 0; - wrap.setAttribute("role", "slider"); - wrap.setAttribute("aria-label", `${STEM_DISPLAY[stemName] || stemName} gain`); - wrap.setAttribute("aria-valuemin", "0"); - wrap.setAttribute("aria-valuemax", String(LANE_VOLUME_MAX)); - wrap.setAttribute("aria-valuenow", "1"); - wrap.title = "Drag to adjust \u00b7 double-click to reset to 0\u00a0dB \u00b7 scroll to nudge"; - - const track = document.createElement("div"); - track.className = "mx-fader-track"; - const fill = document.createElement("div"); - fill.className = "mx-fader-fill"; - fill.style.background = color; - const knob = document.createElement("div"); - knob.className = "mx-fader-knob"; - knob.style.background = color; - track.append(fill, knob); - wrap.appendChild(track); - - // Legacy indicator kept for CSS compat (display:none via widgets.css) - const indicator = document.createElement("div"); - indicator.className = "lane-knob-indicator"; - wrap.appendChild(indicator); - - let dragging = false; - let startX = 0; - let startVolume = 1; - - const onMove = (e) => { - if (!dragging) return; - const dx = e.clientX - startX; - const travelPx = Math.max(1, wrap.getBoundingClientRect().width); - setLaneVolume(stemName, startVolume + dx * (LANE_VOLUME_MAX / travelPx)); - }; - const onUp = () => { - dragging = false; - wrap.classList.remove("dragging"); - document.removeEventListener("pointermove", onMove); - document.removeEventListener("pointerup", onUp); - }; - wrap.addEventListener("pointerdown", (e) => { - dragging = true; - wrap.classList.add("dragging"); - startX = e.clientX; - startVolume = mixerState[stemName]?.volume ?? 1; - document.addEventListener("pointermove", onMove); - document.addEventListener("pointerup", onUp); - e.preventDefault(); - }); + + const input = document.createElement("input"); + input.type = "range"; + input.className = "mx-fader-input"; + input.setAttribute("min", "0"); + input.setAttribute("max", String(LANE_VOLUME_MAX)); + input.setAttribute("step", "0.01"); + input.setAttribute("value", "1"); + input.style.setProperty("--fader-color", color); + input.style.setProperty("--lane-pos", "0.5"); + input.setAttribute("aria-label", `${STEM_DISPLAY[stemName] || stemName} volume`); + input.addEventListener("input", () => setLaneVolume(stemName, parseFloat(input.value))); + input.addEventListener("dblclick", (e) => { e.stopPropagation(); setLaneVolume(stemName, 1); }); + wrap.appendChild(input); + wrap.addEventListener("dblclick", () => setLaneVolume(stemName, 1)); wrap.addEventListener("wheel", (e) => { e.preventDefault(); const cur = mixerState[stemName]?.volume ?? 1; - const step = e.shiftKey ? 0.2 : 0.04; - setLaneVolume(stemName, cur - Math.sign(e.deltaY) * step); + setLaneVolume(stemName, cur - Math.sign(e.deltaY) * (e.shiftKey ? 0.2 : 0.04)); }, { passive: false }); - wrap.addEventListener("keydown", (e) => { - const cur = mixerState[stemName]?.volume ?? 1; - let next = cur; - if (e.code === "ArrowUp" || e.code === "ArrowRight") next = cur + 0.1; - else if (e.code === "ArrowDown" || e.code === "ArrowLeft") next = cur - 0.1; - else if (e.code === "Home") next = 1; - else return; - e.preventDefault(); - setLaneVolume(stemName, next); - }); return wrap; } @@ -399,7 +359,12 @@ export function renderMixerRow(stem) { dl.title = `Download ${display}`; dl.appendChild(downloadIcon()); - row.append(iconCell, nameEl, fader, vu, val, muteBtn, soloBtn, dl); + // Wrap name + VU in a column so VU appears below the name + const nameVuCol = document.createElement("div"); + nameVuCol.className = "lane-name-vu"; + nameVuCol.append(nameEl, vu); + + row.append(iconCell, nameVuCol, fader, val, muteBtn, soloBtn, dl); muteBtn.addEventListener("click", () => toggleStemMute(stem.name)); soloBtn.addEventListener("click", () => toggleStemSolo(stem.name)); diff --git a/static/js/player.js b/static/js/player.js index 56756732..945893bf 100644 --- a/static/js/player.js +++ b/static/js/player.js @@ -13,7 +13,9 @@ import { masterVolume, masterFader, mixerState, setMultitrack, setCurrentJobId, setTrackIndex, setTotalDuration, setLoopEnabled, setLoopStart, setLoopEnd, setMasterVolume, - setWaveZoom, waveScroll, selectedStems, + waveScroll, selectedStems, + footerTitle, footerMeta, footerThumb, + setFooterWaveDrawFn, } from "./state.js"; import { loadMixIntoState, resetMixerState, refreshMixerVisuals, @@ -27,6 +29,7 @@ import { updatePresencePlayhead, } from "./transport.js"; import { stopVuLoop } from "./audio.js"; +import { destroySections } from "./sections.js"; // Stem-selection filter: the import-page stem-choice toggles set // selectedStems (state.js). Backend always processes all 6 -- we @@ -36,11 +39,22 @@ const _STEM_ROW_SELECTORS = [ ".stem-list span[data-stem]", ".presence-bars i[data-stem]", ".presence-labels span", - ".stem-waveform-row[data-stem]", ]; function applyStemSelectionFilter(presentNames) { - const visibleTrackCount = Math.max(1, presentNames.size || TRACK_NAMES.length); + // Waveform rows: original hides if absent; STEM_NAMES rows always show, grayed if absent + for (const el of document.querySelectorAll(".stem-waveform-row[data-stem]")) { + const stem = el.dataset.stem; + if (stem === "original") { + el.classList.toggle("hidden", !presentNames.has(stem)); + el.classList.remove("unavailable"); + } else { + el.classList.remove("hidden"); + el.classList.toggle("unavailable", !presentNames.has(stem)); + } + } + const originalRow = presentNames.has("original") ? 1 : 0; + const visibleTrackCount = originalRow + STEM_NAMES.length; const app = document.querySelector(".app"); app?.style.setProperty("--visible-track-count", String(visibleTrackCount)); app?.style.setProperty( @@ -59,8 +73,9 @@ function applyStemSelectionFilter(presentNames) { for (const name of STEM_NAMES) { if (presentNames.has(name)) visibleMixerNames.push(name); } + const mixerCap = STEM_NAMES.length + (presentNames.has("original") ? 1 : 0); for (const name of STEM_NAMES) { - if (visibleMixerNames.length >= STEM_NAMES.length) break; + if (visibleMixerNames.length >= mixerCap) break; if (!visibleMixerNames.includes(name)) visibleMixerNames.push(name); } const visibleMixerSet = new Set(visibleMixerNames); @@ -103,6 +118,10 @@ function clearStemSelectionFilter() { el.classList.remove("hidden"); } } + for (const el of document.querySelectorAll(".stem-waveform-row[data-stem]")) { + el.classList.remove("hidden"); + el.classList.remove("unavailable"); + } for (const row of document.querySelectorAll(".mixer-column .lane-header[data-stem], .energy-row[data-stem]")) { row.classList.remove("hidden"); row.classList.remove("unavailable"); @@ -134,7 +153,7 @@ function resetAnalysisCards() { function renderPlaceholderTracks() { multitrackContainer.innerHTML = ""; - for (const name of TRACK_NAMES) { + for (const name of ["original", ...STEM_NAMES]) { const ph = document.createElement("div"); ph.className = "lane-placeholder"; ph.dataset.stem = name; @@ -145,11 +164,14 @@ function renderPlaceholderTracks() { const OVERVIEW_WAVE_POINTS = 1500; const STEM_VU_FPS = 30; -const WAVEFORM_LANE_HEIGHT = 64; +const WAVEFORM_LANE_HEIGHT = 70; const WAVEFORM_SEPARATOR_HEIGHT = 2; let visualRenderToken = 0; let visualAudioContext = null; let stemVuRafId = null; +let _footerWavePeaks = null; +let _lastFooterProgress = 0; +const _FOOTER_BARS = 300; function isAudioBufferLike(value) { return value && typeof value.getChannelData === "function"; @@ -480,6 +502,7 @@ function renderAllDecodedVisuals(stems, token) { export function destroyPlayer() { document.querySelector(".app")?.classList.remove("is-import"); document.querySelector(".app")?.classList.add("no-track"); + destroySections(); stopVuLoop(); stopStemVuLoop(); if (multitrack) { @@ -528,7 +551,6 @@ export function destroyPlayer() { setLoopEnd(0); setMasterVolume(0.5); setTrackIndex({}); - setWaveZoom(1); applyWaveZoom(); buildPresenceRuler(0); updateFooterTimes(0); @@ -538,6 +560,13 @@ export function destroyPlayer() { playBtn.classList.remove("playing"); stopBtn.classList.remove("stopped"); loopRegionEl.classList.add("hidden"); + _footerWavePeaks = null; + _lastFooterProgress = 0; + _footerWaveResizeObs?.disconnect(); + setFooterWaveDrawFn(null); + const cv = document.getElementById("footer-waveform"); + if (cv) { const c = cv.getContext("2d"); c?.clearRect(0, 0, cv.width, cv.height); } + updateFooterTrack({}); } export function renderEmptyShell() { @@ -546,10 +575,11 @@ export function renderEmptyShell() { stopStemVuLoop(); ensureMixerStateDefaults(); mixerEl.innerHTML = ""; - for (const name of TRACK_NAMES) { + for (const name of ["original", ...STEM_NAMES]) { const { row } = renderMixerRow({ name, url: "#" }); mixerEl.appendChild(row); } + requestAnimationFrame(() => _applyLaneHeight(1 + STEM_NAMES.length)); applyStemSelectionFilter(new Set(STEM_NAMES)); titleEl.textContent = "Ready to import a track"; bpmChip.textContent = "\u2014 BPM"; @@ -565,7 +595,9 @@ export function renderEmptyShell() { function renderAllMiniWaves(mt, stems) { const wsArr = mt.wavesurfers || mt._wavesurfers; if (!wsArr?.length) return; - stems.forEach((stem, i) => { + stems.forEach((stem) => { + const i = trackIndex[stem.name]; + if (i === undefined) return; const ws = wsArr[i]; if (!ws) return; const color = STEM_COLORS[stem.name] || "#a0a0a0"; @@ -581,11 +613,25 @@ function renderAllMiniWaves(mt, stems) { }); } -function setWaveformLoading(loading) { +let _loadingShownAt = 0; +const _LOADING_MIN_MS = 900; +let _currentStems = []; +let _mixUrl = null; + +export function setWaveformLoading(loading) { const el = document.getElementById("waveLoadingOverlay"); if (!el) return; - el.classList.toggle("hidden", !loading); - if (!loading) el.classList.remove("stalled"); + if (loading) { + _loadingShownAt = performance.now(); + el.classList.remove("hidden"); + } else { + const elapsed = performance.now() - _loadingShownAt; + const delay = Math.max(0, _LOADING_MIN_MS - elapsed); + window.setTimeout(() => { + el.classList.add("hidden"); + el.classList.remove("stalled"); + }, delay); + } } export function buildStripStems() { @@ -605,7 +651,22 @@ export function buildStripStems() { } } -export function wireUpAudio(jobId, stems, duration, thumbnail) { +function _applyLaneHeight(count) { + const wavePanel = document.querySelector(".daw-wave-panel"); + const panelH = wavePanel?.clientHeight ?? 0; + const laneH = panelH > 0 && count > 0 + ? Math.max(WAVEFORM_LANE_HEIGHT, Math.floor(panelH / count)) + : WAVEFORM_LANE_HEIGHT; + const appEl = document.querySelector(".app"); + appEl?.style.setProperty("--lane-h", `${laneH + 2}px`); + appEl?.style.setProperty( + "--wave-widget-track-stack-h", + `${count * laneH + (count - 1) * WAVEFORM_SEPARATOR_HEIGHT}px`, + ); + return laneH; +} + +export function wireUpAudio(jobId, stems, duration, thumbnail, mixUrl = null) { const app = document.querySelector(".app"); app?.classList.remove("is-import"); app?.classList.remove("no-track"); @@ -650,7 +711,16 @@ export function wireUpAudio(jobId, stems, duration, thumbnail) { // original.wav, so it's simply not in `stems` and the mixer/sidebar // rows for it stay hidden.) stems = stems.filter((s) => s.name === "original" || selectedStems.has(s.name)); + _currentStems = stems; + _mixUrl = mixUrl || null; applyStemSelectionFilter(new Set(stems.map((s) => s.name))); + updateFooterTrack({ thumbnail, stemCount: stems.filter((s) => s.name !== "original").length }); + + // Reset and re-init footer waveform from the mix/original stem + _footerWavePeaks = null; + setFooterWaveDrawFn(null); + const mixStem = stems.find((s) => s.name === "original") || stems[0]; + if (mixStem?.url) initFooterWaveform(mixStem.url); for (const stem of stems) { const row = mixerEl.querySelector(`.lane-header[data-stem="${stem.name}"]`); @@ -673,19 +743,27 @@ export function wireUpAudio(jobId, stems, duration, thumbnail) { clearOverviewWaveforms(); renderAllDecodedVisuals(stems, token); - setTrackIndex(Object.fromEntries(stems.map((s, i) => [s.name, i]))); + // "original" is prepended at row 0 only when it actually has a URL so it + // appears at the top. Omitting it when absent avoids a phantom 70px gap. + // STEM_NAMES follow at the next consecutive rows so mixer lanes stay aligned. + const stemsByName = Object.fromEntries(stems.map((s) => [s.name, s])); + const orderedNames = [...(stemsByName["original"] ? ["original"] : []), ...STEM_NAMES]; + setTrackIndex(Object.fromEntries(orderedNames.map((name, i) => [name, i]))); multitrackContainer.innerHTML = ""; + + const laneH = _applyLaneHeight(orderedNames.length); + const mt = Multitrack.create( - stems.map((s, i) => ({ + orderedNames.map((name, i) => ({ id: i, - url: s.url, + url: stemsByName[name]?.url ?? null, draggable: false, startPosition: 0, - volume: 1, + volume: stemsByName[name] ? 1 : 0, options: { - waveColor: STEM_COLORS[s.name] || "#a0a0a0", + waveColor: STEM_COLORS[name] || "#a0a0a0", progressColor: PROGRESS_COLOR, - height: WAVEFORM_LANE_HEIGHT, + height: laneH, barWidth: 3, barGap: 2, barRadius: 2, @@ -702,7 +780,7 @@ export function wireUpAudio(jobId, stems, duration, thumbnail) { // div scrolls. Fitting to view keeps the three perfectly aligned. minPxPerSec: 0, rightButtonDrag: false, - cursorWidth: 1.5, + cursorWidth: 0, cursorColor: "#e54e4e", trackBackground: "transparent", trackBorderColor: "rgba(148, 163, 184, 0.08)", @@ -727,13 +805,13 @@ export function wireUpAudio(jobId, stems, duration, thumbnail) { const ctx = mt.audioContext; console.debug( `[player] canplay — ${stems.length} stems, ctx=${ctx?.state}, audios:`, - mt.audios?.map((a, i) => `${stems[i]?.name}:${a?.constructor?.name}`), + mt.audios?.map((a, i) => `${orderedNames[i]}:${a?.constructor?.name}`), ); - // Log any audio element load errors + // Log load errors only for stems that actually have a source URL mt.audios?.forEach((a, i) => { - if (a instanceof HTMLMediaElement) { + if (a instanceof HTMLMediaElement && stemsByName[orderedNames[i]]?.url) { a.addEventListener("error", () => - console.error(`[player] audio error stem[${i}] ${stems[i]?.name}:`, a.error?.message, a.error?.code), + console.error(`[player] audio error stem[${i}] ${orderedNames[i]}:`, a.error?.message, a.error?.code), { once: true }); } }); @@ -775,6 +853,7 @@ export function wireUpAudio(jobId, stems, duration, thumbnail) { ws.on("play", () => { playBtn.classList.add("playing"); stopBtn.classList.remove("stopped"); + applyMix(); }); ws.on("pause", () => { playBtn.classList.remove("playing"); @@ -783,3 +862,179 @@ export function wireUpAudio(jobId, stems, duration, thumbnail) { ws.on("seeking", updateStopVisual); }); } + +export function drawFooterPlaceholder() { + _drawPlaceholderWave(); + const bar = document.getElementById("footer-waveform")?.closest(".footer-wave-bar"); + if (bar) { + new ResizeObserver(() => { if (!_footerWavePeaks) _drawPlaceholderWave(); }).observe(bar); + } +} + +function _drawPlaceholderWave() { + const canvas = document.getElementById("footer-waveform"); + if (!canvas) return; + const dpr = window.devicePixelRatio || 1; + const w = canvas.clientWidth, h = canvas.clientHeight; + if (!w || !h) return; + canvas.width = Math.round(w * dpr); + canvas.height = Math.round(h * dpr); + const ctx = canvas.getContext("2d"); + ctx.clearRect(0, 0, canvas.width, canvas.height); + const n = 300; + const barW = canvas.width / n; + const gap = 1; + const cy = canvas.height / 2; + for (let i = 0; i < n; i++) { + const t = i / n; + const amp = 0.15 + 0.55 * ( + 0.5 * Math.abs(Math.sin(t * Math.PI * 3.7 + 0.5)) + + 0.3 * Math.abs(Math.sin(t * Math.PI * 9.1 + 1.2)) + + 0.2 * Math.abs(Math.sin(t * Math.PI * 21.3 + 2.8)) + ); + const barH = Math.max(3, amp * canvas.height * 0.78); + const x = Math.round(i * barW); + const nextX = i === n - 1 ? canvas.width : Math.round((i + 1) * barW); + const bw = Math.max(1, nextX - x - gap); + ctx.fillStyle = "rgba(255,255,255,0.07)"; + ctx.fillRect(x, cy - barH / 2, bw, barH); + } +} + +function _drawFooterWave(progress) { + _lastFooterProgress = progress; + const canvas = document.getElementById("footer-waveform"); + if (!canvas) return; + if (!_footerWavePeaks) { _drawPlaceholderWave(); return; } + const dpr = window.devicePixelRatio || 1; + const w = canvas.clientWidth; + const h = canvas.clientHeight; + if (!w || !h) return; + if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) { + canvas.width = Math.round(w * dpr); + canvas.height = Math.round(h * dpr); + } + const ctx = canvas.getContext("2d"); + ctx.clearRect(0, 0, canvas.width, canvas.height); + const n = _footerWavePeaks.length; + let maxAbs = 0; + for (const [mn, mx] of _footerWavePeaks) { + if (mx > maxAbs) maxAbs = mx; + if (-mn > maxAbs) maxAbs = -mn; + } + const norm = maxAbs > 0 ? 1 / maxAbs : 1; + const cy = canvas.height / 2; + const barW = canvas.width / n; + const gap = 1; + const playedIdx = Math.floor(progress * n); + for (let i = 0; i < n; i++) { + const [mn, mx] = _footerWavePeaks[i]; + const top = cy - mx * norm * cy * 0.78; + const bot = cy - mn * norm * cy * 0.78; + const barH = Math.max(3, bot - top); + const x = Math.round(i * barW); + const nextX = i === n - 1 ? canvas.width : Math.round((i + 1) * barW); + const bw = Math.max(1, nextX - x - gap); + ctx.fillStyle = i < playedIdx ? "#f4b740" : "rgba(255,255,255,0.13)"; + ctx.fillRect(x, top, bw, barH); + } + if (progress > 0.001 && progress < 0.999) { + const px = progress * canvas.width; + ctx.beginPath(); + ctx.arc(px, cy, 4 * dpr, 0, Math.PI * 2); + ctx.fillStyle = "#f4b740"; + ctx.fill(); + } +} + +let _footerWaveResizeObs = null; +async function initFooterWaveform(stemUrl) { + const canvas = document.getElementById("footer-waveform"); + if (!canvas || !stemUrl) return; + const AudioCtx = window.AudioContext || window.webkitAudioContext; + if (!AudioCtx) return; + try { + visualAudioContext ??= new AudioCtx(); + const res = await fetch(stemUrl, { cache: "force-cache" }); + if (!res.ok) return; + const buf = await visualAudioContext.decodeAudioData(await res.arrayBuffer()); + _footerWavePeaks = bufferMinMaxPeaks(buf, _FOOTER_BARS); + setFooterWaveDrawFn(_drawFooterWave); + _drawFooterWave(0); + // Redraw on resize so the canvas fills its container correctly + _footerWaveResizeObs?.disconnect(); + _footerWaveResizeObs = new ResizeObserver(() => _drawFooterWave(_lastFooterProgress)); + _footerWaveResizeObs.observe(canvas.parentElement || canvas); + } catch (e) { + console.warn("[player] footer waveform:", e); + } +} + +export function updateFooterTrack({ title, thumbnail, key, bpm, stemCount } = {}) { + if (footerThumb) { + const artEl = footerThumb.closest(".footer-art"); + if (thumbnail) { + footerThumb.src = thumbnail; + footerThumb.onload = () => { + footerThumb.classList.add("loaded"); + artEl?.classList.add("has-art"); + }; + footerThumb.onerror = () => { + footerThumb.classList.remove("loaded"); + artEl?.classList.remove("has-art"); + }; + } else { + footerThumb.removeAttribute("src"); + footerThumb.classList.remove("loaded"); + artEl?.classList.remove("has-art"); + } + } + if (footerTitle && title !== undefined) footerTitle.textContent = title; + if (footerMeta) { + const parts = []; + if (key) parts.push(key); + if (bpm) parts.push(`${Math.round(bpm)} BPM`); + if (stemCount != null) parts.push(`${stemCount} Stems`); + if (key !== undefined || bpm !== undefined || stemCount !== undefined) + footerMeta.textContent = parts.join(" • "); + } +} + +function _triggerDownload(url, filename) { + const fullUrl = url.startsWith("http") ? url : `${location.origin}${url}`; + if (window.__TAURI__?.core?.invoke) { + window.__TAURI__.core.invoke("open_url", { url: fullUrl }); + return; + } + const a = document.createElement("a"); + a.href = fullUrl; + a.download = filename; + document.body.appendChild(a); + a.click(); + a.remove(); +} + +function _exportMixUrl() { + if (_mixUrl) return _mixUrl; + const orig = _currentStems.find((s) => s.name === "original"); + return orig?.url ?? null; +} + +export function downloadCurrentMix() { + const url = _exportMixUrl(); + if (!url) return; + _triggerDownload(url, "mix.wav"); +} + +export function downloadCurrentMixMp3() { + const url = _exportMixUrl(); + if (!url) return; + _triggerDownload(url.replace(/\.wav$/, ".mp3"), "mix.mp3"); +} + +export function downloadCurrentStems() { + const stems = _currentStems.filter((s) => s.name !== "original"); + stems.forEach((s, i) => { + window.setTimeout(() => _triggerDownload(s.url, `${s.name}.wav`), i * 150); + }); +} diff --git a/static/js/sections.js b/static/js/sections.js new file mode 100644 index 00000000..727e3074 --- /dev/null +++ b/static/js/sections.js @@ -0,0 +1,382 @@ +// sections.js — interactive sections bar above the waveform + +const SECTION_COLORS = [ + "#4a7fff", + "#2ab8e8", + "#9a4aff", + "#ff8a20", + "#00c8a0", + "#ff4a90", + "#e8c840", + "#00d4d4", +]; + +const MIN_SEC = 0.5; // minimum section duration in seconds +const DEFAULT_WIDTH_FRAC = 0.12; // default new section = 12% of track + +let _trackId = null; +let _duration = 0; +let _sections = []; +let _container = null; +let _saveTimer = null; + +// ─── Public API ─────────────────────────────────────────── + +export function initSections(trackId, sections, duration) { + _trackId = trackId; + _duration = Math.max(1, duration || 0); + _sections = (sections || []).map((s) => ({ ...s })); + _container = document.getElementById("daw-sections"); + if (!_container) return; + + // Wire the static "Add" button in the label area (may already be wired) + const addBtn = document.getElementById("sectionsAddBtn"); + if (addBtn && !addBtn.dataset.sectionsWired) { + addBtn.dataset.sectionsWired = "1"; + addBtn.addEventListener("click", () => _addSection()); + } + + _render(); +} + +export function destroySections() { + // Flush any pending debounced save before clearing state so switching tracks + // never drops unsaved sections. _save() serializes _sections synchronously + // (JSON.stringify runs before the first await) so it's safe to clear state + // after calling it. + if (_saveTimer !== null) { + clearTimeout(_saveTimer); + _saveTimer = null; + _save(); + } + _hideSaveIndicator(); + _trackId = null; + _sections = []; + _duration = 0; + if (_container) _container.innerHTML = ""; + _container = null; +} + +// ─── Rendering ──────────────────────────────────────────── + +function _render() { + if (!_container) return; + _container.innerHTML = ""; + + const sorted = [..._sections].sort((a, b) => a.start - b.start); + + for (const section of sorted) { + _container.appendChild(_makeSectionEl(section)); + } +} + +function _makeSectionEl(section) { + const pctStart = (section.start / _duration) * 100; + const pctWidth = ((section.end - section.start) / _duration) * 100; + + const el = document.createElement("div"); + el.className = "section-block"; + el.dataset.id = section.id; + el.style.cssText = `left:${pctStart.toFixed(4)}%;width:${pctWidth.toFixed(4)}%;--sc:${section.color}`; + + el.innerHTML = ` +
+ ${_esc(section.name)} + +
+ `; + + el.querySelector(".section-del").addEventListener("click", (e) => { + e.stopPropagation(); + _deleteSection(section.id); + }); + + el.querySelector(".section-label").addEventListener("dblclick", (e) => { + e.stopPropagation(); + _openRename(section.id, el.querySelector(".section-label")); + }); + + _wireDrag(el, section); + for (const h of el.querySelectorAll(".section-handle")) { + _wireResize(h, el, section); + } + + return el; +} + +function _esc(str) { + return String(str) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +// ─── Drag to move ───────────────────────────────────────── + +function _wireDrag(el, section) { + let active = false; + let startX = 0; + let origStart = 0; + + el.addEventListener("pointerdown", (e) => { + if (e.target.closest(".section-handle,.section-del")) return; + active = true; + startX = e.clientX; + origStart = section.start; + el.setPointerCapture(e.pointerId); + el.classList.add("sec-dragging"); + e.preventDefault(); + }); + + el.addEventListener("pointermove", (e) => { + if (!active) return; + const cw = _container.getBoundingClientRect().width; + if (!cw) return; + const dt = ((e.clientX - startX) / cw) * _duration; + const w = section.end - section.start; + section.start = _clampMove(section.id, origStart + dt, w); + section.end = section.start + w; + el.style.left = `${(section.start / _duration) * 100}%`; + }); + + el.addEventListener("pointerup", () => { + if (!active) return; + active = false; + el.classList.remove("sec-dragging"); + _scheduleSave(); + }); + + el.addEventListener("pointercancel", () => { + active = false; + el.classList.remove("sec-dragging"); + }); +} + +// ─── Resize handles ─────────────────────────────────────── + +function _wireResize(handle, el, section) { + const edge = handle.dataset.edge; + let active = false; + let startX = 0; + let origTime = 0; + + handle.addEventListener("pointerdown", (e) => { + active = true; + startX = e.clientX; + origTime = edge === "left" ? section.start : section.end; + handle.setPointerCapture(e.pointerId); + el.classList.add("sec-resizing"); + e.preventDefault(); + e.stopPropagation(); + }); + + handle.addEventListener("pointermove", (e) => { + if (!active) return; + const cw = _container.getBoundingClientRect().width; + if (!cw) return; + const dt = ((e.clientX - startX) / cw) * _duration; + const desired = origTime + dt; + + if (edge === "left") { + const lbound = _leftNeighborEnd(section.id); + const max = section.end - MIN_SEC; + section.start = Math.max(lbound, Math.min(max, desired)); + } else { + const rbound = _rightNeighborStart(section.id); + const min = section.start + MIN_SEC; + section.end = Math.min(rbound, Math.max(min, desired)); + } + + const ps = (section.start / _duration) * 100; + const pw = ((section.end - section.start) / _duration) * 100; + el.style.left = `${ps}%`; + el.style.width = `${pw}%`; + }); + + handle.addEventListener("pointerup", () => { + if (!active) return; + active = false; + el.classList.remove("sec-resizing"); + _scheduleSave(); + }); + + handle.addEventListener("pointercancel", () => { + active = false; + el.classList.remove("sec-resizing"); + }); +} + +// ─── Collision helpers ──────────────────────────────────── + +function _clampMove(id, desiredStart, width) { + let start = Math.max(0, Math.min(_duration - width, desiredStart)); + const end = () => start + width; + const others = _sections.filter((s) => s.id !== id); + + for (const o of others) { + if (start < o.end && end() > o.start) { + // Snap to whichever edge is closer to desired + const snapRight = o.end; + const snapLeft = o.start - width; + const dr = Math.abs(desiredStart - snapRight); + const dl = Math.abs(desiredStart - snapLeft); + start = dl < dr ? Math.max(0, snapLeft) : Math.min(_duration - width, snapRight); + } + } + return start; +} + +function _leftNeighborEnd(id) { + const s = _sections.find((x) => x.id === id); + let bound = 0; + for (const o of _sections) { + if (o.id === id) continue; + if (o.end <= s.end) bound = Math.max(bound, o.end); + } + return bound; +} + +function _rightNeighborStart(id) { + const s = _sections.find((x) => x.id === id); + let bound = _duration; + for (const o of _sections) { + if (o.id === id) continue; + if (o.start >= s.start) bound = Math.min(bound, o.start); + } + return bound; +} + +// ─── CRUD ───────────────────────────────────────────────── + +function _addSection() { + const defW = _duration * DEFAULT_WIDTH_FRAC; + const sorted = [..._sections].sort((a, b) => a.start - b.start); + + // Find first gap ≥ defW + let start = 0; + for (const s of sorted) { + if (s.start - start >= defW) break; + start = Math.max(start, s.end); + } + + // Clamp and verify room + start = Math.min(start, _duration - MIN_SEC); + if (start < 0) return; + const end = Math.min(start + defW, _duration); + if (end - start < MIN_SEC) return; + + // Verify no overlap + if (_sections.some((s) => start < s.end && end > s.start)) return; + + const color = _nextColor(); + const section = { id: _nextId(), name: "Section", start, end, color }; + _sections.push(section); + _render(); + _scheduleSave(); + + // Open rename immediately + const el = _container?.querySelector(`[data-id="${section.id}"]`); + if (el) _openRename(section.id, el.querySelector(".section-label")); +} + +function _deleteSection(id) { + _sections = _sections.filter((s) => s.id !== id); + _render(); + _scheduleSave(); +} + +function _openRename(id, labelEl) { + if (!labelEl) return; + const section = _sections.find((s) => s.id === id); + if (!section) return; + + const input = document.createElement("input"); + input.className = "section-rename-input"; + input.type = "text"; + input.value = section.name; + input.style.setProperty("--sc", section.color); + labelEl.replaceWith(input); + input.focus(); + input.select(); + + const commit = () => { + const n = input.value.trim(); + if (n) section.name = n; + _render(); + _scheduleSave(); + }; + input.addEventListener("blur", commit, { once: true }); + input.addEventListener("keydown", (e) => { + if (e.key === "Enter") { e.preventDefault(); input.blur(); } + if (e.key === "Escape") { input.value = section.name; input.removeEventListener("blur", commit); input.blur(); } + }); +} + +// ─── Persistence ────────────────────────────────────────── + +let _savedTimer = null; + +function _showSaving() { + const el = document.getElementById("sectionsSaveIndicator"); + if (!el) return; + clearTimeout(_savedTimer); + el.textContent = "Saving"; + el.className = "sections-save-indicator"; +} + +function _showSaved() { + const el = document.getElementById("sectionsSaveIndicator"); + if (!el) return; + el.textContent = "Saved"; + el.className = "sections-save-indicator saved"; + _savedTimer = setTimeout(() => { + el.className = "sections-save-indicator hidden"; + }, 1800); +} + +function _hideSaveIndicator() { + const el = document.getElementById("sectionsSaveIndicator"); + if (el) el.className = "sections-save-indicator hidden"; + clearTimeout(_savedTimer); +} + +function _scheduleSave() { + clearTimeout(_saveTimer); + _showSaving(); + _saveTimer = setTimeout(_save, 600); +} + +async function _save() { + if (!_trackId) return; + const id = _trackId; + const body = JSON.stringify({ sections: _sections }); + try { + const res = await fetch(`/api/jobs/${id}/sections`, { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body, + }); + if (!res.ok) { + const detail = await res.text().catch(() => String(res.status)); + console.warn("[sections] save failed:", res.status, detail); + if (id === _trackId) _hideSaveIndicator(); + return; + } + if (id === _trackId) _showSaved(); + } catch (e) { + console.warn("[sections] save failed:", e); + if (id === _trackId) _hideSaveIndicator(); + } +} + +// ─── Utilities ──────────────────────────────────────────── + +function _nextColor() { + const used = new Set(_sections.map((s) => s.color)); + return SECTION_COLORS.find((c) => !used.has(c)) ?? SECTION_COLORS[_sections.length % SECTION_COLORS.length]; +} + +function _nextId() { + return `s${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`; +} diff --git a/static/js/state.js b/static/js/state.js index 55d566b8..14d97904 100644 --- a/static/js/state.js +++ b/static/js/state.js @@ -37,17 +37,16 @@ export const loopRegionEl = $("loop-region"); export const playheadMarker = document.querySelector(".playhead-marker"); export const waveScroll = $("wave-scroll"); export const waveCanvas = $("wave-canvas"); -export const zoomInBtn = $("zoom-in"); -export const zoomOutBtn = $("zoom-out"); -export const zoomFitBtn = $("zoom-fit"); -export const zoomTrack = $("zoom-track"); export const presenceRulerEl = $("presence-ruler"); export const presencePlayheadEl = $("presence-playhead"); export const footerTimeElapsed = $("footer-time-elapsed"); export const footerTimeTotal = $("footer-time-total"); export const stemListEl = document.querySelector(".stem-list"); export const npScrubEl = document.querySelector(".np-scrub"); -export const npScrubFill = document.querySelector(".np-scrub > span"); +export const npScrubFill = $("footer-scrub-fill"); +export const footerTitle = $("footer-title"); +export const footerMeta = $("footer-meta"); +export const footerThumb = $("footer-thumb"); // ─── Mutable state ─── @@ -65,7 +64,6 @@ export let totalDuration = 0; export let loopEnabled = false; export let loopStart = 0; export let loopEnd = 0; -export let waveZoom = 1; // Selected stems for extraction. The set determines (a) which stem // rows render in the studio dashboard after a job completes and (b) @@ -121,9 +119,12 @@ export function setTotalDuration(v) { totalDuration = v; } export function setLoopEnabled(v) { loopEnabled = v; } export function setLoopStart(v) { loopStart = v; } export function setLoopEnd(v) { loopEnd = v; } -export function setWaveZoom(v) { waveZoom = v; } export function setAudioContext(v) { audioContext = v; } export function setMasterVolume(v) { masterVolume = v; } export function setVuRafId(v) { vuRafId = v; } export function setMasterBusGain(v) { masterBusGain = v; } export function setMasterLimiter(v) { masterLimiter = v; } + +// Footer waveform draw callback — set by player.js, called by transport.js +export let footerWaveDrawFn = null; +export function setFooterWaveDrawFn(fn) { footerWaveDrawFn = fn; } diff --git a/static/js/transport.js b/static/js/transport.js index 2288013c..33bfcab0 100644 --- a/static/js/transport.js +++ b/static/js/transport.js @@ -3,17 +3,14 @@ import { playBtn, playMiniBtn, stopBtn, loopBtn, timeEl, masterFader, rulerTime, wavesGrid, loopRegionEl, playheadMarker, multitrack, totalDuration, loopEnabled, loopStart, loopEnd, masterVolume, - waveScroll, waveCanvas, zoomInBtn, zoomOutBtn, zoomFitBtn, zoomTrack, - waveZoom, presenceRulerEl, presencePlayheadEl, - footerTimeElapsed, footerTimeTotal, npScrubFill, - setLoopEnabled, setLoopStart, setLoopEnd, setMasterVolume, setWaveZoom, + waveScroll, waveCanvas, + presenceRulerEl, presencePlayheadEl, + footerTimeElapsed, footerTimeTotal, npScrubFill, footerWaveDrawFn, + setLoopEnabled, setLoopStart, setLoopEnd, setMasterVolume, } from "./state.js"; import { applyMix } from "./mixer.js"; const MIN_LOOP_SEC = 0.2; -const ZOOM_MIN = 1; -const ZOOM_MAX = 32; -const ZOOM_STEP = 1.25; // rulerTime is the canonical timeline reference for both click->time // and time->pixel mapping. The wave-editor lays the ruler and the // waveform body out so they should be horizontally aligned (both gutter @@ -26,8 +23,7 @@ function rulerRect() { } function loopOverlayParent() { - return document.querySelector(".waves-column") - || rulerTime; + return document.querySelector(".waves-column") || rulerTime; } function ensureLoopRegionParent() { @@ -104,10 +100,9 @@ export function updateFooterTimes(currentSec) { if (!totalDuration) return; if (footerTimeElapsed) footerTimeElapsed.textContent = fmtTime(currentSec); if (footerTimeTotal) footerTimeTotal.textContent = fmtTime(totalDuration); - if (npScrubFill) { - const pct = Math.max(0, Math.min(100, (currentSec / totalDuration) * 100)); - npScrubFill.style.width = `${pct}%`; - } + const pct = Math.max(0, Math.min(100, (currentSec / totalDuration) * 100)); + if (npScrubFill) npScrubFill.style.width = `${pct}%`; + footerWaveDrawFn?.(pct / 100); } // Build the presence-panel ruler labels from the actual track duration. @@ -285,103 +280,29 @@ function wireLoopDrag() { // math stays correct without any per-element width logic. export function applyWaveZoom() { - if (!waveCanvas) return; - waveCanvas.style.setProperty("--zoom", String(waveZoom)); const wavesColumn = document.querySelector(".waves-column"); if (wavesColumn) { - waveCanvas.style.setProperty("--wave-playhead-h", `${wavesColumn.clientHeight}px`); + const lanes = document.getElementById("lanes") || waveCanvas; + lanes?.style.setProperty("--wave-playhead-h", `${wavesColumn.clientHeight}px`); } - if (zoomTrack) { - const frac = (Math.log(waveZoom) - Math.log(ZOOM_MIN)) - / (Math.log(ZOOM_MAX) - Math.log(ZOOM_MIN)); - zoomTrack.style.setProperty("--zoom-frac", frac.toFixed(3)); - if ("value" in zoomTrack) zoomTrack.value = String(waveZoom); - } - if (zoomOutBtn) zoomOutBtn.disabled = waveZoom <= ZOOM_MIN + 1e-3; - if (zoomInBtn) zoomInBtn.disabled = waveZoom >= ZOOM_MAX - 1e-3; - if (zoomFitBtn) zoomFitBtn.disabled = Math.abs(waveZoom - 1) < 1e-3; - if (multitrack && totalDuration > 0 && waveScroll) { const baseWidth = waveScroll.clientWidth; if (baseWidth > 0) { - const pxPerSec = (baseWidth * waveZoom) / totalDuration; + const pxPerSec = baseWidth / totalDuration; try { multitrack.zoom(pxPerSec); } catch { /* ignore -- pre-canplay */ } } } } -function setWaveZoomLevel(z) { - const clamped = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, z)); - setWaveZoom(clamped); - applyWaveZoom(); -} - -function zoomToLevelAtClientX(clientX, nextZoom) { - if (!waveScroll) return setWaveZoomLevel(nextZoom); - const rect = waveScroll.getBoundingClientRect(); - const visualToLayout = waveScroll.clientWidth / Math.max(1, rect.width); - const cursorX = Math.max(0, Math.min( - waveScroll.clientWidth, - (clientX - rect.left) * visualToLayout, - )); - const before = waveScroll.scrollLeft + cursorX; - const oldWidth = waveScroll.firstElementChild?.scrollWidth || waveScroll.clientWidth; - setWaveZoomLevel(nextZoom); - const newWidth = waveScroll.firstElementChild?.scrollWidth || waveScroll.clientWidth; - const ratio = oldWidth > 0 ? newWidth / oldWidth : 1; - waveScroll.scrollLeft = before * ratio - cursorX; -} - -function zoomAtClientX(clientX, factor) { - zoomToLevelAtClientX(clientX, waveZoom * factor); -} - -function zoomCenteredOn(factor) { - if (!waveScroll) return setWaveZoomLevel(waveZoom * factor); - const rect = waveScroll.getBoundingClientRect(); - zoomAtClientX(rect.left + rect.width / 2, factor); -} - function wireZoomButtons() { - if (zoomInBtn) { - zoomInBtn.addEventListener("click", () => zoomCenteredOn(ZOOM_STEP)); - } - if (zoomOutBtn) { - zoomOutBtn.addEventListener("click", () => zoomCenteredOn(1 / ZOOM_STEP)); - } - if (zoomFitBtn) { - zoomFitBtn.addEventListener("click", () => { - setWaveZoomLevel(1); - if (waveScroll) waveScroll.scrollLeft = 0; - }); - } - if (zoomTrack) { - zoomTrack.addEventListener("input", () => { - const rect = waveScroll?.getBoundingClientRect(); - const centerX = rect ? rect.left + rect.width / 2 : window.innerWidth / 2; - zoomToLevelAtClientX(centerX, Number(zoomTrack.value) || 1); - }); - } - // Recalculate zoom + playhead height whenever the wave container is resized - // (window resize, sidebar open/close, etc.). Without this, --wave-playhead-h - // stays at the initial pixel height and multitrack's pxPerSec is stale. if (waveScroll) { const ro = new ResizeObserver(() => { if (multitrack && totalDuration > 0) applyWaveZoom(); }); ro.observe(waveScroll); } - - // Cmd/Ctrl + wheel = zoom around cursor; plain vertical wheel pans horizontally - // once the waveform is zoomed wider than the viewport. if (waveScroll) { waveScroll.addEventListener("wheel", (e) => { - if (e.ctrlKey || e.metaKey) { - e.preventDefault(); - const factor = Math.exp(-e.deltaY * 0.002); - zoomAtClientX(e.clientX, factor); - return; - } if (waveScroll.scrollWidth <= waveScroll.clientWidth) return; if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) { e.preventDefault();