Update to Metro UI.
This commit is contained in:
1 parent
84541e3fa3
commit
a4da97b2f3
55 files changed
+19867
-1410
No files matched your search
+213
@@ -829,3 +829,216 @@ integration pattern (LyricsCanvas component with `useEffect` mount, `two.bind('u
|
||||
for RAF, ResizeObserver for resize, `useEffect` for style prop changes); 6 implementation
|
||||
phases; and risk notes (clipPath injection stability, font loading timing, HiDPI,
|
||||
StrictMode double-mount, long-song virtualisation, Safari feGaussianBlur performance).
|
||||
|
||||
### 2026-03-11 — StemEngine WebUI.md updated: LyricsLivePreview MetroUI scope
|
||||
|
||||
**Updated — `StemEngine WebUI.md`:**
|
||||
Added `LyricsLivePreview` as a component that also receives MetroUI treatment. The plan
|
||||
now distinguishes two layers: (1) the lyrics rendering canvas (RAF/Two.js — NOT touched
|
||||
by MetroUI) and (2) the surrounding UI shell (transport controls, style picker, speaker
|
||||
management, LRC editor — all reskinned with MetroUI). New section added with ASCII layout
|
||||
diagram, full MetroUI component mapping (radio tiles for style mode, sliders for seek/
|
||||
volume/font-size/shadow, color-picker for accent colours, switch for stroke/shadow
|
||||
toggles, listview for speakers, Metro textarea for LRC editor). Phase 4 note updated to
|
||||
reflect only the outer panel shell changes; new Phase 7 added for the full LyricsLivePreview
|
||||
UI shell reskin. "What Does NOT Change" table split into rendering canvas (unchanged) and
|
||||
UI shell (changes in Phase 7).
|
||||
|
||||
### 2026-03-11 — MetroUI Phase 1: install + app shell
|
||||
|
||||
**Backup created — `frontend-backup/`:**
|
||||
Full copy of `frontend/` (excluding `node_modules`) at `/home/translator/docker/appdata/stemengine/frontend-backup/`.
|
||||
|
||||
**Modified — `frontend/package.json`:**
|
||||
Added `"@olton/metroui": "^5.1.20"` to dependencies. Installed automatically on next container
|
||||
start via `npm install --prefer-offline` in `start.sh`. Tailwind packages kept — removed in Phase 6.
|
||||
|
||||
**Modified — `frontend/src/main.tsx`:**
|
||||
Added MetroUI CSS imports after `index.css`:
|
||||
```ts
|
||||
import '@olton/metroui/dist/css/metro.css'
|
||||
import '@olton/metroui/dist/css/icons.css'
|
||||
```
|
||||
MetroUI JS not imported yet (not needed until JS-initialised components are used in later phases).
|
||||
|
||||
**Modified — `frontend/src/context/ThemeContext.tsx`:**
|
||||
Added `root.setAttribute('data-theme', r)` alongside the existing `classList.add/remove('dark')`.
|
||||
Both Tailwind dark mode (`.dark` class) and MetroUI dark mode (`data-theme="dark"`) are now set
|
||||
simultaneously, so Tailwind inner pages and the new MetroUI shell both honour the user's theme.
|
||||
|
||||
**Modified — `frontend/src/index.css`:**
|
||||
Added migration comment block explaining coexistence of Tailwind + MetroUI.
|
||||
Tailwind `@tailwind` directives kept — removed in Phase 6.
|
||||
|
||||
**Modified — `frontend/src/App.tsx`:**
|
||||
Rewrote AppShell JSX to use MetroUI `app-bar` structure. Key changes:
|
||||
- Outer `div` uses inline flex styles (no Tailwind)
|
||||
- `<header>` uses MetroUI `app-bar` / `app-bar-brand` / `app-bar-item ml-auto` classes
|
||||
- Brand logo: gradient square icon + StemEngine wordmark in MetroUI flat button
|
||||
- GPU status button: MetroUI `button cycle flat`, with accent colour for error state
|
||||
- Settings button: MetroUI `button cycle flat`, highlighted with accent hex when active
|
||||
- Accent gradient line (3 px) above app-bar using `--brand-500` CSS variable
|
||||
- Inner pages (Separator, ProjectDetail, Settings, Sidebar, GlobalAudioBar) completely
|
||||
untouched — still render with their existing Tailwind classes
|
||||
- Phase annotations in comments mark what is migrated in which future phase
|
||||
|
||||
---
|
||||
|
||||
## 2026-03-11
|
||||
|
||||
### MetroUI Phase 2 — Sidebar redesign (`Sidebar.tsx`)
|
||||
|
||||
**File:** `frontend/src/components/Sidebar.tsx`
|
||||
|
||||
All business logic (React Query queries, state, handlers) identical to the Tailwind version.
|
||||
Only the JSX and class names were changed.
|
||||
|
||||
Key changes:
|
||||
- Outer `<aside>` uses inline styles + `sidebar-open`/`sidebar-closed` CSS classes (from
|
||||
`index.css`) — no Tailwind layout classes
|
||||
- Toggle button: MetroUI `button cycle flat` with circular inline style
|
||||
- **Active jobs accordion**: React state `jobsOpen` controls open/close; header uses a shared
|
||||
`sectionHeaderStyle` object (inline styles matching Metro section headers); amber badge count
|
||||
- **`ActiveJobItem`**: inline styles replacing Tailwind card; MetroUI `button cycle flat` for
|
||||
cancel button; Lucide `StatusDot` icons styled with `var(--color-*)` CSS variables
|
||||
- **`ProjectTile`** (replaces `ProjectItem`): inline-styled row with hover state via
|
||||
`useState(hovered)`, brand-accent border/background when `isOpen`, MetroUI `button cycle flat`
|
||||
for delete; opacity-based reveal on hover
|
||||
- **`SubsonicPanel`** accordion: React state `open`; same `sectionHeaderStyle` header with
|
||||
`var(--color-blue)` accent; native `<input>` styled with inline border/background; search
|
||||
button styled inline with `var(--color-blue)` background
|
||||
- **`ImportedFileRow`** extracted as separate component to enable hover state for action buttons
|
||||
- **Collapsed strip**: Lucide icons + count badges using inline `var(--color-gray)` — no Tailwind
|
||||
- `data-role` attributes deliberately avoided throughout to prevent MetroUI JS DOM conflicts
|
||||
with React's virtual DOM; all accordion behavior is React-state-controlled
|
||||
- `var(--border-color)`, `var(--background)`, `var(--body-background)`, `var(--color-*)` MetroUI
|
||||
CSS variables used for theme-aware colours (light/dark respected automatically via
|
||||
`data-theme` set by `ThemeContext`)
|
||||
|
||||
---
|
||||
|
||||
## 2026-03-11 (continued)
|
||||
|
||||
### MetroUI Phase 3 — Separator page + FileUpload
|
||||
|
||||
**Files:**
|
||||
- `frontend/src/pages/Separator.tsx`
|
||||
- `frontend/src/components/FileUpload.tsx`
|
||||
|
||||
All business logic (state, queries, effects, handlers) unchanged. Tailwind replaced with
|
||||
MetroUI CSS classes + inline styles. Sub-components `JobStatus` and `ResultFiles` left
|
||||
unchanged (still Tailwind, to be migrated in Phase 4+).
|
||||
|
||||
Key changes — **FileUpload.tsx**:
|
||||
- Replaced Tailwind class string with inline `style` object
|
||||
- Added React `dragOver` state for visual drag-over feedback (accent border colour + light tint)
|
||||
- `onDragLeave` handler added to clear drag state
|
||||
|
||||
Key changes — **Separator.tsx**:
|
||||
- Removed `SELECT_CLS`, `INPUT_CLS`, `SLIDER_CLS` Tailwind string constants; replaced with
|
||||
`fieldLabel`, `ctrl`, `card` `CSSProperties` objects at module level
|
||||
- Page header: inline `h2`/`p` styles
|
||||
- Input-mode toggle: flex segmented button pair — active button gets `accentColor` background
|
||||
(upload) or `var(--color-blue)` (imported)
|
||||
- Selected file indicator: `card` style with brand accent border
|
||||
- Imported files empty state: dashed-border div with centered icon + text
|
||||
- **`ImportedFileButton`** extracted as separate function (for hover state); active selection
|
||||
shows accent left-border + tinted background
|
||||
- Model/format grid: CSS `grid` (3 columns) with `ctrl` styled native `<select>` elements
|
||||
- BS-RoFormer info box: violet-tinted border + background
|
||||
- Project name: `ctrl` styled `<input type="text">`
|
||||
- Preset type: `ctrl` styled `<select>` + description text
|
||||
- Static options panel: `card` style with `ctrl` select
|
||||
- Dynamic options panel: `card` style; native `<input type="range">` sliders; percentage readout
|
||||
- Preset preview: brand-tinted border box with `<code>` pre-formatted structure
|
||||
- Submit: MetroUI `button primary` class, full-width
|
||||
- Auto Pipeline: inline amber-bordered/tinted button
|
||||
- Success result box: green-tinted border inline
|
||||
- `JobStatus` and `ResultFiles` still use Tailwind internally — visually mixed until Phase 4
|
||||
|
||||
---
|
||||
|
||||
## 2026-03-11
|
||||
|
||||
### Phase 4 — MetroUI CSS migration: ProjectDetail.tsx
|
||||
|
||||
Replaced all targeted Tailwind CSS classes in `frontend/src/pages/ProjectDetail.tsx` with MetroUI classes and inline `style={{}}` objects. No business logic, state, handlers, or out-of-scope functions were touched.
|
||||
|
||||
**Changes made (13 edits + 2 cleanup passes):**
|
||||
|
||||
1. **STEM_COLORS** — Changed from Tailwind class strings to `{ bg, border, color }` objects using RGBA/CSS-var theme colors.
|
||||
2. **JobBadge** — Replaced Tailwind span with inline `style` using MetroUI CSS vars (`--color-green`, `--color-amber`, `--color-red`, `--border-color`).
|
||||
3. **DownloadButton** — Replaced anchor classes with `className="button flat"` + inline style.
|
||||
4. **StemChipButton** — Replaced Tailwind-colored anchor with fully inline `style` using the new STEM_COLORS object.
|
||||
5. **StemReprocessButton** (return JSX) — Replaced relative wrapper, trigger button, dropdown panel, family tabs, model list, and cancel button with `button flat` / `button cycle flat` classes and inline styles using `--border-color`, `--body-background`, `--background`.
|
||||
6. **StemRenameButton** — Replaced editing input and action buttons with inline styles and `button cycle flat` classes; normal state uses `button cycle flat`.
|
||||
7. **StemsSection** header and list — Replaced collapsible header and stem-row cards with inline styles; accent color via `rgb(var(--brand-500, 59 130 246))`.
|
||||
8. **MixesSection** header — Replaced collapsible header with inline-style flex layout.
|
||||
9. **MixesSection** sub-tabs, generate buttons, error/result box — Replaced all Tailwind with inline styles; generate button uses `className="button"`.
|
||||
10. **MidiSection** header — Replaced with violet-colored inline-style header using `--color-violet`.
|
||||
11. **AbcSection** header — Replaced with green-colored inline-style header using `--color-green`.
|
||||
12. **LyricsSection** header — Replaced with sky-blue inline-style header using `--color-blue`.
|
||||
13. **Main ProjectDetail export** — Replaced loading spinner, error state, header, delete button, and all section wrappers with inline styles and MetroUI button classes.
|
||||
- **Cleanup:** Replaced 2× `bulkErr` Tailwind paragraphs and 3× "no items" italic paragraphs with inline styles. Two remaining occurrences (inside StemAbcRow and StemLyricsRow) were left untouched per scope rules.
|
||||
|
||||
---
|
||||
|
||||
### Phase 5 — MetroUI CSS migration: Settings.tsx
|
||||
|
||||
Replaced all remaining Tailwind CSS classes in `frontend/src/pages/Settings.tsx` with inline `style={{}}` objects using MetroUI CSS variables. Changed the tab navigation from a horizontal pill bar to a **vertical left-side sidebar nav**. No business logic, state, or handlers were changed.
|
||||
|
||||
**Components migrated (5 edits):**
|
||||
|
||||
1. **Toggle** — Replaced Tailwind `translate-x`/`bg-brand-500`/`bg-slate-300` with a fully inline animated switch using `rgb(var(--brand-500))` and `var(--border-color)`; added `type="button"`, `role="switch"`, `aria-checked`.
|
||||
2. **MaintenanceSettings** — Replaced `space-y-8`, `flex items-center gap-3 pb-4 border-b`, icon wrapper `p-2 bg-slate-100 rounded-lg`, and `space-y-3` list with inline flex/gap/border styles matching the shared `sHdr`/`sCard` pattern.
|
||||
3. **PowerSettings** — Removed `btnBase`/`btnActive` Tailwind class strings; replaced header, GPU banner, VRAM tier card grid (with active/disabled states), and AI Transcription toggle rows with inline styles using `rgb(var(--brand-500))`, `var(--color-green)`, `var(--color-red)`, `var(--border-color)`.
|
||||
4. **IntegrationsSettings** — Replaced `space-y-8` outer wrapper, `flex items-center gap-3 pb-4 border-b` header, all `className` inputs/buttons (including password field, Save, Remove) with inline styles; MetroUI `button primary` class used for Save; status messages use `var(--color-green)` / `var(--color-red)`.
|
||||
5. **Settings (main export)** — Removed horizontal pill tab bar (`hidden sm:flex`, `sm:hidden` mobile select). Replaced with a **vertical sidebar nav** (176 px wide, `flex-col gap-2`) alongside a content panel in a two-column flex layout. Active nav item uses `rgba(var(--brand-500), 0.1)` background and brand color text. Added `ElementType` to `react` type import to replace `React.ElementType` reference.
|
||||
|
||||
**CSS vars used throughout:** `--border-color`, `--body-background`, `--background`, `rgb(var(--brand-500, 59 130 246))`, `var(--color-green)`, `var(--color-amber)`, `var(--color-red)`.
|
||||
|
||||
---
|
||||
|
||||
### Phase 6 — GlobalAudioBar reskin + Tailwind audit
|
||||
|
||||
**GlobalAudioBar.tsx** — Full reskin per Phase 6 spec:
|
||||
- Outer strip: `position: fixed` bottom with `var(--border-color)` top border, `var(--body-background)` background, `backdrop-filter: blur`.
|
||||
- Play/Pause: replaced Tailwind rounded-full + `bg-brand-500` with inline `rgb(var(--brand-500))` circle; MetroUI `button cycle` class kept.
|
||||
- Time spans, seek slider, volume slider: all inline styles; `accentColor` uses `rgb(var(--brand-500))`.
|
||||
- Mute and dismiss buttons: MetroUI `button cycle flat`.
|
||||
- Tailwind `className` fully removed from the component.
|
||||
|
||||
**Tailwind remnant sweep** — All previously-migrated components audited and cleaned:
|
||||
|
||||
1. **App.tsx** — Removed `className="sm:hidden"` from mobile backdrop div (now pure inline style); replaced `max-w-3xl mx-auto px-2 sm:px-4 py-4 sm:py-6` + `rounded-2xl border border-slate-200 ...` wrapper with inline styles using `var(--border-color)` and `var(--body-background)`; replaced Tailwind `<footer>` classes with inline style; moved `ml-auto` from className to inline `marginLeft: 'auto'`.
|
||||
|
||||
2. **JobStatus.tsx** — Full rewrite of the render: all `className="flex items-center gap-2 text-xs text-red-500"` etc. replaced with shared `row` style object + CSS vars (`var(--color-red)`, `var(--color-green)`, `var(--color-amber)`, brand color); `truncate` replaced with inline `overflow: hidden, textOverflow: ellipsis`; `animate-spin` removed (Tailwind animation — icon unchanged, class dropped).
|
||||
|
||||
3. **ResultFiles.tsx** — Replaced `space-y-2` wrapper, anchor Tailwind link row, and `Download` icon classes with inline styles; anchor uses MetroUI `button flat` class + inline border style.
|
||||
|
||||
4. **SettingsPanel.tsx** — Full rewrite: modal overlay, backdrop, panel shell, header, theme toggle buttons, Full Settings row, and description text all converted to inline styles + CSS vars; close button uses MetroUI `button cycle flat`.
|
||||
|
||||
5. **DynamicMixPlayer.tsx** — Replaced `space-y-3`, `flex flex-wrap`, play button (`rounded-full bg-brand-500`), seek/volume range sliders (`accent-brand-500`), master volume section, and stem M/S buttons + sliders with inline styles; mute button uses MetroUI `button cycle flat`; M/S active states use `var(--color-red)` / `var(--color-amber)`.
|
||||
|
||||
6. **AutoPipelineDialog.tsx** — Full rewrite of the fixed bottom-right dialog: outer shell, header (Zap amber icon), body (project name input, pipeline step rows, live progress step list, error/success banners), footer (Dismiss/Cancel + Run Pipeline/Close buttons) all converted to inline styles; `StepIcon` colors use CSS vars; MetroUI `button primary` for Close; amber background for Run button.
|
||||
|
||||
7. **Settings.tsx** — Fixed `getStatusIcon()` helper: replaced `w-4 h-4 text-green-500` etc. Tailwind icon classNames with inline `style` + CSS vars.
|
||||
|
||||
**Excluded from Phase 6 sweep (per plan):**
|
||||
- `LyricsLivePreview.tsx` — Phase 7 scope.
|
||||
- `KaraokeEditor.tsx` — explicitly excluded (canvas engine, never to be reskinned).
|
||||
- `ProjectDetail.tsx` — was Phase 4; a handful of sub-row classNames (StemAbcRow, StemLyricsRow) remain per Phase 4 scope notes.
|
||||
|
||||
**Post-sweep status:** `grep className=` on all non-excluded TSX files returns only MetroUI class names (`button`, `button cycle flat`, `button primary`, `button flat`, `app-bar`, `app-bar-brand`, `app-bar-item`, `sidebar-open/closed`, `icon`). Zero Tailwind utility classes remain in the migrated scope.
|
||||
|
||||
---
|
||||
|
||||
### Phase 6 — Bug fixes (post-migration)
|
||||
|
||||
Three regressions introduced in Phase 6 corrected:
|
||||
|
||||
1. **Sidebar overlay blocking clicks** — Removing `sm:hidden` from the mobile backdrop div caused it to render on all screen sizes, blocking content on desktop. Restored `className="sm:hidden"` since Tailwind is still active.
|
||||
|
||||
2. **Dark mode not switching** — Components now rely on `var(--body-background)`, `var(--border-color)` etc. instead of Tailwind `dark:` classes. These CSS custom properties were only being set if MetroUI's own CSS defined them under `[data-theme="dark"]`. `ThemeContext.tsx` updated to explicitly set all required CSS variables via `root.style.setProperty(...)` in the `apply()` function, guaranteeing correct values for both themes regardless of MetroUI's internal CSS. Light values: `--body-background: #ffffff`, `--border-color: #e2e8f0`, etc. Dark values: `--body-background: #0f172a`, `--border-color: #334155`, etc. Semantic colors (`--color-green`, `--color-red`, `--color-amber`, `--color-blue`, `--color-violet`, `--color-teal`) set once (theme-neutral).
|
||||
|
||||
3. **VRAM tier card text overflow** — Card `<button>` elements in PowerSettings had no width constraint or overflow control, causing description text to bleed across adjacent cards. Added `width: '100%'`, `minWidth: 0`, `overflow: 'hidden'`, `boxSizing: 'border-box'` to the button, and `overflowWrap: 'break-word'`, `wordBreak: 'break-word'`, `width: '100%'` to the description `<span>`.
|
||||
+96
-8
@@ -297,12 +297,89 @@ Fixed bottom strip, unchanged in function. Reskin with MetroUI:
|
||||
|
||||
---
|
||||
|
||||
## KaraokeEditor & LyricsLivePreview
|
||||
## KaraokeEditor
|
||||
|
||||
**These components are NOT reskinned.** They are complex custom canvas/DOM components
|
||||
with their own internal style systems (direct colour constants, inline styles).
|
||||
They will be wrapped in a MetroUI `data-role="panel"` shell but their internals remain
|
||||
unchanged. This is explicitly called out because they must not be broken by the migration.
|
||||
**Internal rendering is NOT reskinned.** It is a custom canvas + DOM timing-table
|
||||
component with its own internal colour constants and inline styles.
|
||||
It will be wrapped in a MetroUI `data-role="panel"` shell (title bar + collapse toggle)
|
||||
but its internals remain unchanged. This is explicitly called out because it must not
|
||||
be broken by the migration.
|
||||
|
||||
---
|
||||
|
||||
## LyricsLivePreview
|
||||
|
||||
`LyricsLivePreview` has two distinct layers with different treatment:
|
||||
|
||||
### Lyrics display canvas — NOT reskinned with MetroUI
|
||||
|
||||
The animated lyrics rendering area (scrolling lines, word-fill gradient, glow/blur
|
||||
effects) is driven by a custom RAF loop with direct DOM/style mutations (and per the
|
||||
`Karaoke Renderer (Two JS).md` plan, will be replaced by a Two.js SVG scene). MetroUI
|
||||
does not touch this area.
|
||||
|
||||
### UI shell — reskinned with MetroUI
|
||||
|
||||
All the surrounding controls and panels are standard HTML UI and are fully reskinned:
|
||||
|
||||
```
|
||||
┌─ Lyrics Preview ─────────────────────────────────────── [⛶] [▼] ┐
|
||||
│ │
|
||||
│ ┌──────────────────────────────────────────────────────────────┐ │
|
||||
│ │ [lyrics display canvas — Two.js / custom RAF, unchanged] │ │
|
||||
│ └──────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌─ Transport ──────────────────────────────────────────────────┐ │
|
||||
│ │ [◀◀] [▶] [▶▶] ══════════════●══════ 0:32 / 3:47 🔊 ─● │ │
|
||||
│ └──────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌─ Style ──────────────────────────────────────── [▼] ─────────┐ │
|
||||
│ │ [scroll] [fade] [karaoke] [glow] [blur] ← Metro radio tiles│ │
|
||||
│ │ Font [select ▼] Size [──●──] Align [L] [C] [R] │ │
|
||||
│ │ Highlight ■ Word fill ■ Text ■ Bg ■ │ │
|
||||
│ │ [•] Stroke width [─●─] color ■ │ │
|
||||
│ │ [•] Shadow x [─●─] y [─●─] blur [─●─] color ■ │ │
|
||||
│ └──────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌─ Speakers ───────────────────────────────────── [▼] ─────────┐ │
|
||||
│ │ ● SPEAKER_00 [name input] │ │
|
||||
│ │ ● SPEAKER_01 [name input] │ │
|
||||
│ └──────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌─ LRC Editor ─────────────────────────────────── [▼] ─────────┐ │
|
||||
│ │ [textarea] [Apply] [Reset] │ │
|
||||
│ └──────────────────────────────────────────────────────────────┘ │
|
||||
└───────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**MetroUI components:**
|
||||
|
||||
| UI element | MetroUI |
|
||||
|------------|---------|
|
||||
| Outer panel shell | `data-role="panel"` with `data-collapsible="true"` |
|
||||
| Visual style selector | Metro tile grid with `data-role="radio"` (one tile per style mode) |
|
||||
| Transport play/pause | `<button class="button cycle primary">` |
|
||||
| Seek bar | `data-role="slider"` |
|
||||
| Volume slider | `data-role="slider"` with mute toggle button |
|
||||
| Time display | `<span class="badge">` |
|
||||
| Font family | `data-role="select"` |
|
||||
| Font size | `data-role="slider"` with numeric readout |
|
||||
| Text alignment | Three-button `<button class="button">` group (L / C / R) |
|
||||
| Colour pickers (highlight, fill, text, bg) | `data-role="color-picker"` or `data-role="input" data-type="color"` |
|
||||
| Stroke / shadow toggles | `data-role="switch"` |
|
||||
| Stroke width, shadow x/y/blur | `data-role="slider"` |
|
||||
| Speaker list | `data-role="listview"` — each row has a colour swatch + editable name input |
|
||||
| Speaker colour assignment | Metro accent colour tile row |
|
||||
| LRC text editor | `<textarea class="metro-input" rows="8">` |
|
||||
| Editor apply/reset buttons | `<button class="button primary">` / `<button class="button">` |
|
||||
| Timing shift slider | `data-role="slider"` (−15 s … +15 s) with numeric readout |
|
||||
| Fullscreen toggle | `<button class="button square">` with `mif-expand` icon |
|
||||
|
||||
**Style picker as collapsible panel (default collapsed):**
|
||||
The full style picker is wrapped in a `data-role="panel"` with `data-collapsible="true"`
|
||||
and `data-collapsed="true"` so it doesn't dominate the view. A single gear icon button
|
||||
in the lyrics panel title bar expands it. The transport controls remain always visible
|
||||
below the canvas.
|
||||
|
||||
---
|
||||
|
||||
@@ -343,10 +420,10 @@ MetroUI's built-in accent palette names (`blue`, `violet`, `crimson`, `green`,
|
||||
4. Job progress + toast notifications.
|
||||
|
||||
### Phase 4 — ProjectDetail page
|
||||
1. Panel sections (Stems, Karaoke Editor, Dynamic Mix, Lyrics Preview).
|
||||
1. Panel sections (Stems, Karaoke Editor, Dynamic Mix, Lyrics Preview outer shell).
|
||||
2. Stem tiles with badges + progress.
|
||||
3. Action button dropdowns.
|
||||
*(KaraokeEditor and LyricsLivePreview interiors untouched.)*
|
||||
*(KaraokeEditor internals and the LyricsLivePreview rendering canvas untouched.)*
|
||||
|
||||
### Phase 5 — Settings page
|
||||
1. Vertical tab nav.
|
||||
@@ -361,6 +438,16 @@ MetroUI's built-in accent palette names (`blue`, `violet`, `crimson`, `green`,
|
||||
3. Audit icon usage — decide lucide SVG vs MetroUI icon font.
|
||||
4. Cross-browser / dark-mode QA pass.
|
||||
|
||||
### Phase 7 — LyricsLivePreview UI shell
|
||||
1. Transport controls: play/pause cycle button, seek slider, volume slider + mute, time badge.
|
||||
2. Visual style selector: Metro radio tile row (scroll / fade / karaoke / glow / blur).
|
||||
3. Style picker panel: font select, size/alignment sliders, colour pickers, stroke/shadow switches + sliders.
|
||||
4. Speaker listview: colour swatch tiles + inline name inputs.
|
||||
5. LRC text editor: Metro textarea + apply/reset buttons.
|
||||
6. Timing shift slider.
|
||||
7. Fullscreen button (mif-expand icon).
|
||||
8. Verify the lyrics rendering canvas is visually unaffected (no MetroUI classes inside it).
|
||||
|
||||
---
|
||||
|
||||
## What Does NOT Change
|
||||
@@ -368,7 +455,8 @@ MetroUI's built-in accent palette names (`blue`, `violet`, `crimson`, `green`,
|
||||
| Item | Reason |
|
||||
|------|--------|
|
||||
| `KaraokeEditor.tsx` internals | Custom canvas engine; MetroUI-independent |
|
||||
| `LyricsLivePreview.tsx` internals | Custom RAF renderer |
|
||||
| `LyricsLivePreview.tsx` — lyrics rendering canvas | Custom RAF / Two.js scene; MetroUI-independent |
|
||||
| `LyricsLivePreview.tsx` — UI shell (transport, style picker, speakers, editor) | **Does change** — reskinned with MetroUI in Phase 7 |
|
||||
| `api/client.ts` | Pure data layer |
|
||||
| `utils/` | Pure logic |
|
||||
| `ThemeContext.tsx` logic | Only the DOM attribute changes |
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
I have created the following plan after thorough exploration and analysis of the codebase. Follow the below plan verbatim. Trust the files and references. Do not re-verify what's written in the plan. Explore only when absolutely necessary. First implement all the proposed file changes and then I'll review all the changes together at the end.
|
||||
|
||||
## Observations
|
||||
|
||||
`LyricsLivePreview.tsx` is a single ~2,350-line monolith. The lyrics canvas is the `renderLyricsArea()` helper (lines 1899–1983), which wraps a `scrollDivRef` `<div>` containing one of five `render*Style()` functions. The RAF loop (lines 1083–1158) drives timing and directly mutates `activeWordSpanRef.style.backgroundImage` using `WebkitBackgroundClip: text`. `two.js` is **not** in `package.json` yet. All other subsystems (audio, transport, style picker, speaker management, LRC editor, `KaraokeEditor`) are untouched by this migration.
|
||||
|
||||
## Approach
|
||||
|
||||
Extract the lyrics canvas into a new `LyricsCanvas.tsx` component backed by Two.js SVG renderer, then replace the `renderLyricsArea()` call in `LyricsLivePreview` with `<LyricsCanvas>`. A companion `svgUtils.ts` encapsulates all raw SVG DOM injection. The migration follows the six phases in the spec document, keeping every non-rendering concern in `LyricsLivePreview` unchanged.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 0 — Install Two.js and TypeScript Types
|
||||
|
||||
Add `two.js` and `@types/two.js` to `file:frontend/package.json` dependencies:
|
||||
```
|
||||
npm install two.js @types/two.js
|
||||
```
|
||||
Also add `@types/two.js` if a community type package exists; otherwise declare a module shim in `src/types.ts` or a `two.js.d.ts` file.
|
||||
|
||||
---
|
||||
|
||||
### Step 1 — Create `src/utils/svgUtils.ts`
|
||||
|
||||
Encapsulate all raw SVG DOM manipulation that Two.js doesn't expose natively. This module is the only place that touches `_renderer.elem` internals.
|
||||
|
||||
Provide the following exports:
|
||||
|
||||
| Function | Purpose |
|
||||
|---|---|
|
||||
| `ensureDefs(svgEl: SVGSVGElement): SVGDefsElement` | Returns or creates the `<defs>` element inside the Two.js SVG root |
|
||||
| `injectClipPath(defs, id, x, y, height): SVGRectElement` | Creates `<clipPath id="…"><rect …/></clipPath>` in defs; returns the `<rect>` for per-frame width mutation |
|
||||
| `removeClipPath(defs, id)` | Removes a `<clipPath>` by id — called when a line leaves the window |
|
||||
| `injectFilter(defs, id, type: 'glow' \| 'blur', params): SVGElement` | Creates `<filter>` with `<feDropShadow>` (glow) or `<feGaussianBlur>` (blur); returns the inner filter primitive for per-frame `stdDeviation` updates |
|
||||
| `applyClipPath(twoTextElem, id)` | Sets `clip-path="url(#…)"` on a Two.js `Text` element's underlying SVG node |
|
||||
| `applyFilter(twoGroupElem, id)` | Sets `filter="url(#…)"` on a Two.js `Group` element's underlying SVG node |
|
||||
|
||||
---
|
||||
|
||||
### Step 2 — Define `SceneState` type in `src/components/LyricsCanvas.tsx`
|
||||
|
||||
Create the new file. Define the internal scene state interface:
|
||||
|
||||
```
|
||||
interface WordUnit {
|
||||
behindText: Two.Text
|
||||
frontText: Two.Text
|
||||
clipRect: SVGRectElement | null // null for non-karaoke styles
|
||||
measuredWidth: number
|
||||
startTime: number
|
||||
duration: number
|
||||
}
|
||||
|
||||
interface LineRecord {
|
||||
group: Two.Group
|
||||
wordUnits: WordUnit[]
|
||||
dotCircle: Two.Circle | null
|
||||
lineIdx: number
|
||||
}
|
||||
|
||||
interface SceneState {
|
||||
two: Two
|
||||
linesGroup: Two.Group
|
||||
bgRect: Two.Rectangle
|
||||
fadeTop: Two.Rectangle
|
||||
fadeBottom: Two.Rectangle
|
||||
lineRecords: LineRecord[]
|
||||
metricsCanvas: HTMLCanvasElement
|
||||
metricsCtx: CanvasRenderingContext2D
|
||||
metricsCache: Map<string, number>
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 3 — Implement `LyricsCanvas` props interface
|
||||
|
||||
The component receives everything the current `renderLyricsArea()` needs, passed as refs or stable values to avoid re-mounting the Two.js scene on every style change:
|
||||
|
||||
```
|
||||
interface LyricsCanvasProps {
|
||||
lines: LrcLine[]
|
||||
currentTimeRef: React.RefObject<number>
|
||||
visualStyle: LyricsVisualStyle
|
||||
style: StyleState
|
||||
speakerColorFn: (id: string) => string
|
||||
isFullscreen: boolean
|
||||
// cover art overlay is kept in LyricsLivePreview (HTML layer above the canvas)
|
||||
}
|
||||
```
|
||||
|
||||
Pass `style` as a ref internally (`styleRef`) so the Two.js update loop always reads the latest values without triggering a scene rebuild.
|
||||
|
||||
---
|
||||
|
||||
### Step 4 — Implement `buildScene(two, lines, style, speakerColorFn)` (Phase 1)
|
||||
|
||||
Called once on mount and on full rebuild triggers (font change, `lines` array structural change).
|
||||
|
||||
1. Clear `two.scene` children.
|
||||
2. Add `bgRect` — `Two.Rectangle` sized to `two.width × two.height`, filled with `style.bgColor`.
|
||||
3. Add `linesGroup` — `Two.Group` with `translation.y = two.height / 2`.
|
||||
4. For each line in `lines` (virtualised: only ±10 around active index are added initially):
|
||||
- Create `lineGroup` (`Two.Group`).
|
||||
- Compute `lineY = lineIdx * lineStride` where `lineStride = style.fontSize * style.lineSpacing * 1.4`.
|
||||
- For inactive lines: add a single `Two.Text` with `fill = style.textColor`, `opacity = 0.35`.
|
||||
- For the active line: build `wordsGroup` with `WordUnit` entries (see Step 5).
|
||||
- If speaker changes at this line: add `Two.Circle` dot at left edge.
|
||||
- Add `lineGroup` to `linesGroup`.
|
||||
5. Add `fadeTop` and `fadeBottom` — `Two.Rectangle` objects with SVG `linearGradient` fills injected via `svgUtils` (transparent→bgColor and bgColor→transparent). These sit above `linesGroup` in Z-order.
|
||||
6. Use `document.fonts.ready` before calling `buildScene` to ensure custom web fonts are loaded before `measureText` runs.
|
||||
|
||||
---
|
||||
|
||||
### Step 5 — Implement `buildWordUnits(line, lineGroup, style, svgDefs, lineIdx)` (Phase 3)
|
||||
|
||||
Called for the active line during `buildScene` and when the active line changes.
|
||||
|
||||
1. Create a hidden `<canvas>` (or reuse `sceneState.metricsCtx`) and set `font = "${fontWeight} ${fontSize}px ${fontFamily}"`.
|
||||
2. Iterate words, calling `measureWord(text, font, metricsCache)` for each. Accumulate `cursorX` to get each word's `x` position. Center the total line width: `startX = (two.width - totalWidth) / 2` (or left/right for other `textAlign` values).
|
||||
3. For each word, create a `WordUnit`:
|
||||
- `behindText` — `Two.Text` at `(wordX, lineY)`, `fill = 'none'`, `stroke = strokeColor`, `linewidth = strokeWidth * 2`. Apply shadow SVG filter via `svgUtils.injectFilter` + `svgUtils.applyFilter`.
|
||||
- `frontText` — `Two.Text` at same position, `fill = style.textColor` (dim state). Inject `<clipPath>` via `svgUtils.injectClipPath` with `width = 0`. Apply via `svgUtils.applyClipPath`.
|
||||
- Store `clipRect`, `measuredWidth`, `startTime = word.time`, `duration` (next word time − this word time).
|
||||
4. Add all `WordUnit` groups to `lineGroup` in Z-order: `behindText` first, `frontText` second.
|
||||
|
||||
---
|
||||
|
||||
### Step 6 — Implement `updateScene(sceneState, time, lines, style, visualStyle, speakerColorFn)` (Phase 2 + 3)
|
||||
|
||||
This is the body of `two.bind('update', fn)`. It must be fast — no allocations in the hot path.
|
||||
|
||||
```
|
||||
sequenceDiagram
|
||||
participant RAF as two.bind update
|
||||
participant Scene as SceneState
|
||||
participant SVG as SVG DOM
|
||||
|
||||
RAF->>Scene: findActiveLine(lines, time) → activeIdx
|
||||
RAF->>Scene: linesGroup.translation.y lerp toward targetY (0.12 factor)
|
||||
loop each lineRecord
|
||||
RAF->>Scene: compute dist = |lineRecord.lineIdx - activeIdx|
|
||||
RAF->>Scene: lerp lineRecord.group.opacity toward target opacity
|
||||
RAF->>Scene: lerp lineRecord.group.scale toward target scale
|
||||
end
|
||||
RAF->>Scene: updateWordFills(time, activeIdx)
|
||||
loop each WordUnit in active lineRecord
|
||||
RAF->>SVG: clipRect.setAttribute('width', frac * measuredWidth)
|
||||
end
|
||||
```
|
||||
|
||||
**Scroll / fade styles:** no `wordUnits` — only `opacity` and `scale` lerp on `lineGroup`.
|
||||
|
||||
**Karaoke / glow / blur styles:** additionally run `updateWordFills`.
|
||||
|
||||
**Active line change detection:** when `activeIdx` changes, call `activateLineGroup(newIdx)` which:
|
||||
- Tears down old active line's `WordUnit` clip paths (calls `svgUtils.removeClipPath` for each).
|
||||
- Rebuilds `WordUnit` entries for the new active line via `buildWordUnits`.
|
||||
- Resets inactive line groups to single `Two.Text` (no word units).
|
||||
|
||||
**Virtualisation:** keep only lines within `activeIdx ± 10` in `linesGroup`. Lines outside this window have their `lineGroup.visible = false`.
|
||||
|
||||
---
|
||||
|
||||
### Step 7 — Implement style-specific SVG filter effects (Phase 4)
|
||||
|
||||
**Glow style:**
|
||||
- In `buildScene`, inject one `<filter id="glow-active">` with `<feDropShadow dx="0" dy="0" stdDeviation="${style.glowSize}" flood-color="${glowColor}"/>` into `<defs>`.
|
||||
- In `activateLineGroup`, call `svgUtils.applyFilter(activeLineGroup, 'glow-active')`.
|
||||
- In `updateScene`, when `style.glowSize` or `glowColor` changes, update `feDropShadow.stdDeviation` and `feDropShadow.floodColor` attributes directly.
|
||||
|
||||
**Blur style:**
|
||||
- Inject one `<filter id="blur-inactive">` with `<feGaussianBlur stdDeviation="0"/>`.
|
||||
- In `updateScene`, per inactive line: `blurPrimitive.setAttribute('stdDeviation', String(Math.min(dist * 1.5, 6)))`.
|
||||
- Gate behind a Safari capability check: if `CSS.supports('backdrop-filter', 'blur(1px)')` is false and `navigator.userAgent` contains `Safari`, fall back to `opacity` dimming only.
|
||||
|
||||
---
|
||||
|
||||
### Step 8 — Implement `applyStyleOptions(sceneState, style)` (property-only updates)
|
||||
|
||||
Called from a `useEffect` in `LyricsCanvas` when `style` changes but no rebuild is needed (colour, opacity, style mode changes):
|
||||
|
||||
- Update `bgRect.fill`.
|
||||
- Update all inactive `Two.Text` fill colours.
|
||||
- Update `frontText.fill` on word units.
|
||||
- Update glow/blur filter parameters.
|
||||
- If `fontFamily` or `fontSize` changed: trigger full `buildScene` rebuild (clear metrics cache first).
|
||||
|
||||
---
|
||||
|
||||
### Step 9 — Implement `LyricsCanvas` React component
|
||||
|
||||
```
|
||||
useEffect (mount once):
|
||||
1. new Two({ type: Two.Types.svg, autostart: true, fitted: true })
|
||||
2. two.appendTo(containerRef.current)
|
||||
3. document.fonts.ready.then(() => buildScene(...))
|
||||
4. two.bind('update', () => updateScene(...))
|
||||
5. ResizeObserver → two.width/height update → rebuildLayout (re-centre linesGroup, recompute lineStride)
|
||||
6. cleanup: two.pause(), two.unbind('update'), ro.disconnect(), remove domElement
|
||||
|
||||
useEffect [style.fontFamily, style.fontSize]:
|
||||
→ clear metricsCache, trigger full buildScene rebuild
|
||||
|
||||
useEffect [style (other properties)]:
|
||||
→ applyStyleOptions(sceneState, style)
|
||||
|
||||
useEffect [lines]:
|
||||
→ diff line count; add/remove lineGroups as needed
|
||||
|
||||
return: <div ref={containerRef} style={{ width: '100%', height: '100%' }} />
|
||||
```
|
||||
|
||||
The `currentTimeRef` is read directly inside `two.bind('update')` — no React state involved.
|
||||
|
||||
---
|
||||
|
||||
### Step 10 — Wire `LyricsCanvas` into `LyricsLivePreview`
|
||||
|
||||
In `LyricsLivePreview.tsx`:
|
||||
|
||||
1. Remove `scrollDivRef`, `translateYRef`, `activeLineRef`, `activeWordSpanRef` refs (they are now internal to `LyricsCanvas`).
|
||||
2. Remove the `useLayoutEffect` that computed `translateY` (lines 1195–1202) — replaced by Two.js lerp.
|
||||
3. Remove `handleRecenter` function — the Two.js scene auto-centres; if a recenter button is still desired, expose a `recenterRef` callback prop on `LyricsCanvas`.
|
||||
4. Remove the RAF loop's direct DOM gradient write block (lines 1137–1150) — Two.js update loop handles this.
|
||||
5. In `renderLyricsArea()`, replace the `<div ref={containerRef}>` + `<div ref={scrollDivRef}>` + `render*Style()` call stack with:
|
||||
```tsx
|
||||
<LyricsCanvas
|
||||
lines={lines}
|
||||
currentTimeRef={currentTimeRef}
|
||||
visualStyle={visualStyle}
|
||||
style={style}
|
||||
speakerColorFn={getSpeakerColor}
|
||||
isFullscreen={isFullscreen}
|
||||
/>
|
||||
```
|
||||
6. Keep the cover art overlay `<div>` and hidden `<img>` as absolute-positioned HTML above the canvas (they are already `position: absolute` inside `containerRef`). Move `containerRef` to wrap both `LyricsCanvas` and the overlay.
|
||||
7. Keep the `maskImage` / `WebkitMaskImage` gradient fade on the container `<div>` — it applies to the SVG element as a CSS mask and works correctly.
|
||||
|
||||
---
|
||||
|
||||
### Step 11 — Remove deprecated code (Phase 5 + 6)
|
||||
|
||||
After verifying visual parity across all five styles:
|
||||
|
||||
- Delete the `KaraokeWord` function component (lines 255–389).
|
||||
- Delete `renderScrollStyle`, `renderFadeStyle`, `renderKaraokeStyle`, `renderGlowStyle`, `renderBlurStyle` functions.
|
||||
- Delete `lineStrokeVal`, `lineShadowVal`, `lineNeedsLayer` computed values.
|
||||
- Delete `activeWordSpanRef`, `scrollDivRef`, `translateYRef`, `activeLineRef` refs.
|
||||
- Remove the `WebkitBackgroundClip` / `backgroundClip: 'text'` / `WebkitTextFillColor: 'transparent'` patterns entirely.
|
||||
|
||||
---
|
||||
|
||||
### Step 12 — `StyleState` additions for Two.js
|
||||
|
||||
The existing `StyleState` in `LyricsLivePreview` already covers all needed properties (`glowSize`, `strokeEnabled`, `strokeWidth`, `strokeColor`, `shadowEnabled`, `shadowBlur`, `shadowX`, `shadowY`, `shadowColor`, `shadowOpacity`, `scaleX`, `scaleY`). No new style state fields are required. The `karaokeMode: 'fill' | 'pop'` field maps to the SVG clipRect sweep (`fill`) vs. instant colour switch (`pop`) in `updateWordFills`.
|
||||
|
||||
---
|
||||
|
||||
### File Summary
|
||||
|
||||
| File | Action |
|
||||
|---|---|
|
||||
| `file:frontend/package.json` | Add `two.js` dependency |
|
||||
| `file:frontend/src/utils/svgUtils.ts` | **New** — raw SVG injection helpers |
|
||||
| `file:frontend/src/components/LyricsCanvas.tsx` | **New** — Two.js scene component |
|
||||
| `file:frontend/src/components/LyricsLivePreview.tsx` | Replace `renderLyricsArea` internals with `<LyricsCanvas>`; remove deprecated render functions and refs |
|
||||
@@ -0,0 +1,885 @@
|
||||
I have created the following plan after thorough exploration and analysis of the codebase. Follow the below plan verbatim. Trust the files and references. Do not re-verify what's written in the plan. Explore only when absolutely necessary. First implement all the proposed file changes and then I'll review all the changes together at the end.
|
||||
|
||||
# StemEngine PWA Optimization Plan
|
||||
|
||||
## Observations
|
||||
|
||||
The frontend is a Vite + React app with MetroUI CSS framework and Tailwind CSS. A basic PWA setup exists: `manifest.webmanifest` is present, `sw.js` is registered, and `index.html` has PWA meta tags. However, the service worker is minimal (cache-first for assets, network-first for navigation), and there are no optimizations for offline-first functionality, installability signals, or mobile-specific UX. The app currently lacks: (1) proper asset versioning/cache busting, (2) offline data persistence, (3) install prompts, (4) responsive design refinements for mobile, (5) performance metrics tracking, (6) background sync for long-running jobs.
|
||||
|
||||
## Approach
|
||||
|
||||
Enhance the PWA to be fully installable and functional on desktop and mobile by: (1) upgrading the service worker with Workbox integration for intelligent caching, (2) adding IndexedDB for offline project/job state persistence, (3) implementing install UI prompts and app shortcuts, (4) optimizing bundle size and lazy-loading routes, (5) adding a manifest-driven install banner, (6) implementing background sync for job polling, (7) refining mobile viewport and touch interactions, (8) adding offline fallback pages, (9) monitoring performance with Web Vitals, (10) creating platform-specific app icons and splash screens.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 0 — Upgrade Dependencies for PWA Tooling
|
||||
|
||||
Add to `file:frontend/package.json`:
|
||||
```json
|
||||
{
|
||||
"dependencies": {
|
||||
"workbox-window": "^7.0.0",
|
||||
"idb": "^8.0.0",
|
||||
"web-vitals": "^3.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite-plugin-pwa": "^0.17.0",
|
||||
"workbox-cli": "^7.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `vite-plugin-pwa` will auto-generate the service worker and manifest. `idb` provides a Promise-based IndexedDB wrapper. `web-vitals` tracks Core Web Vitals. `workbox-window` enables advanced SW communication from the app.
|
||||
|
||||
---
|
||||
|
||||
### Step 1 — Configure Vite PWA Plugin
|
||||
|
||||
Update `file:frontend/vite.config.ts`:
|
||||
|
||||
```typescript
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { VitePWA } from 'vite-plugin-pwa'
|
||||
import { resolve } from 'path'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react(),
|
||||
VitePWA({
|
||||
registerType: 'autoUpdate',
|
||||
includeAssets: ['favicon.ico', 'icon.svg', 'robots.txt'],
|
||||
manifest: {
|
||||
name: 'StemEngine',
|
||||
short_name: 'StemEngine',
|
||||
description: 'Audio processing toolkit — stem separation, lyrics sync, MIDI transcription',
|
||||
theme_color: '#3B82F6',
|
||||
background_color: '#030712',
|
||||
display: 'standalone',
|
||||
orientation: 'portrait-primary',
|
||||
scope: '/',
|
||||
start_url: '/',
|
||||
icons: [
|
||||
{
|
||||
src: '/icon-192.png',
|
||||
sizes: '192x192',
|
||||
type: 'image/png',
|
||||
purpose: 'any',
|
||||
},
|
||||
{
|
||||
src: '/icon-512.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png',
|
||||
purpose: 'any',
|
||||
},
|
||||
{
|
||||
src: '/icon-maskable-192.png',
|
||||
sizes: '192x192',
|
||||
type: 'image/png',
|
||||
purpose: 'maskable',
|
||||
},
|
||||
{
|
||||
src: '/icon-maskable-512.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png',
|
||||
purpose: 'maskable',
|
||||
},
|
||||
],
|
||||
screenshots: [
|
||||
{
|
||||
src: '/screenshot-540x720.png',
|
||||
sizes: '540x720',
|
||||
type: 'image/png',
|
||||
form_factor: 'narrow',
|
||||
},
|
||||
{
|
||||
src: '/screenshot-1280x720.png',
|
||||
sizes: '1280x720',
|
||||
type: 'image/png',
|
||||
form_factor: 'wide',
|
||||
},
|
||||
],
|
||||
shortcuts: [
|
||||
{
|
||||
name: 'New Separation',
|
||||
short_name: 'Separate',
|
||||
description: 'Start a new stem separation job',
|
||||
url: '/?tab=separate',
|
||||
icons: [{ src: '/icon-96.png', sizes: '96x96', type: 'image/png' }],
|
||||
},
|
||||
{
|
||||
name: 'Projects',
|
||||
short_name: 'Projects',
|
||||
description: 'View all projects',
|
||||
url: '/?tab=projects',
|
||||
icons: [{ src: '/icon-96.png', sizes: '96x96', type: 'image/png' }],
|
||||
},
|
||||
{
|
||||
name: 'Settings',
|
||||
short_name: 'Settings',
|
||||
description: 'App settings and preferences',
|
||||
url: '/?tab=settings',
|
||||
icons: [{ src: '/icon-96.png', sizes: '96x96', type: 'image/png' }],
|
||||
},
|
||||
],
|
||||
categories: ['productivity', 'utilities'],
|
||||
},
|
||||
workbox: {
|
||||
globPatterns: ['**/*.{js,css,html,svg,png,jpg,jpeg,gif,webp,woff,woff2,ttf,eot}'],
|
||||
runtimeCaching: [
|
||||
{
|
||||
urlPattern: /^https:\/\/fonts\.(googleapis|gstatic)\.com\/.*/i,
|
||||
handler: 'CacheFirst',
|
||||
options: {
|
||||
cacheName: 'google-fonts-cache',
|
||||
expiration: { maxEntries: 20, maxAgeSeconds: 60 * 60 * 24 * 365 }, // 1 year
|
||||
},
|
||||
},
|
||||
{
|
||||
urlPattern: /^\/api\/.*/,
|
||||
handler: 'NetworkFirst',
|
||||
options: {
|
||||
cacheName: 'api-cache',
|
||||
networkTimeoutSeconds: 5,
|
||||
expiration: { maxEntries: 50, maxAgeSeconds: 60 * 5 }, // 5 min
|
||||
},
|
||||
},
|
||||
],
|
||||
skipWaiting: true,
|
||||
clientsClaim: true,
|
||||
},
|
||||
devOptions: {
|
||||
enabled: true,
|
||||
navigateFallback: 'index.html',
|
||||
suppressWarnings: true,
|
||||
},
|
||||
}),
|
||||
],
|
||||
build: {
|
||||
outDir: '../backend/static',
|
||||
emptyOutDir: true,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks: {
|
||||
'vendor-react': ['react', 'react-dom'],
|
||||
'vendor-ui': ['@olton/metroui', 'lucide-react'],
|
||||
'vendor-query': ['@tanstack/react-query'],
|
||||
'vendor-audio': ['tone', '@tonejs/midi', 'abcjs'],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': resolve(__dirname, './src'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:8000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
This config auto-generates `sw.js` and `manifest.webmanifest` with intelligent caching strategies. The `manualChunks` split the bundle into smaller pieces for better caching.
|
||||
|
||||
---
|
||||
|
||||
### Step 2 — Create `src/utils/db.ts` — IndexedDB Wrapper
|
||||
|
||||
Implement a Promise-based IndexedDB layer for offline state persistence:
|
||||
|
||||
```typescript
|
||||
// Stores: projects, jobs, jobFiles, lrcCache, settings
|
||||
// Each store has a schema with indexes for efficient querying
|
||||
```
|
||||
|
||||
Provide these exports:
|
||||
|
||||
| Function | Purpose |
|
||||
|---|---|
|
||||
| `initDB(): Promise<IDBDatabase>` | Opens/creates the StemEngine database with all stores |
|
||||
| `saveProject(project: Project): Promise<void>` | Persist a project locally |
|
||||
| `getProject(id: string): Promise<Project \| null>` | Retrieve a project from IndexedDB |
|
||||
| `listProjects(): Promise<Project[]>` | List all cached projects |
|
||||
| `deleteProject(id: string): Promise<void>` | Remove a project from IndexedDB |
|
||||
| `saveJob(job: Job): Promise<void>` | Cache a job record |
|
||||
| `getJob(id: string): Promise<Job \| null>` | Retrieve a job |
|
||||
| `listJobsByProject(projectId: string): Promise<Job[]>` | Get all jobs for a project |
|
||||
| `saveLrcCache(projectId: string, lrc: string): Promise<void>` | Cache LRC text for offline access |
|
||||
| `getLrcCache(projectId: string): Promise<string \| null>` | Retrieve cached LRC |
|
||||
| `clearOldCache(maxAgeDays: number): Promise<void>` | Prune old entries to manage quota |
|
||||
|
||||
Use the `idb` library for cleaner syntax than raw IndexedDB.
|
||||
|
||||
---
|
||||
|
||||
### Step 3 — Create `src/utils/offlineSync.ts` — Background Sync & Offline Queue
|
||||
|
||||
Implement a queue for operations that fail offline and should retry when online:
|
||||
|
||||
```typescript
|
||||
interface QueuedOperation {
|
||||
id: string
|
||||
type: 'createJob' | 'updateJob' | 'deleteProject'
|
||||
payload: any
|
||||
timestamp: number
|
||||
retries: number
|
||||
}
|
||||
```
|
||||
|
||||
Provide these exports:
|
||||
|
||||
| Function | Purpose |
|
||||
|---|---|
|
||||
| `enqueueOperation(op: QueuedOperation): Promise<void>` | Add an operation to the offline queue |
|
||||
| `processQueue(): Promise<void>` | Attempt to sync all queued operations (called on online event) |
|
||||
| `getQueuedOps(): Promise<QueuedOperation[]>` | List pending operations |
|
||||
| `removeQueuedOp(id: string): Promise<void>` | Remove a queued operation after successful sync |
|
||||
|
||||
On app startup, check `navigator.onLine` and call `processQueue()` if online. Listen to `online` event to retry.
|
||||
|
||||
---
|
||||
|
||||
### Step 4 — Create `src/hooks/useInstallPrompt.ts` — Install Banner Hook
|
||||
|
||||
Implement a React hook that captures the `beforeinstallprompt` event and exposes install UI:
|
||||
|
||||
```typescript
|
||||
interface UseInstallPromptReturn {
|
||||
canInstall: boolean
|
||||
isInstalled: boolean
|
||||
promptInstall: () => Promise<void>
|
||||
dismissPrompt: () => void
|
||||
}
|
||||
```
|
||||
|
||||
The hook:
|
||||
1. Listens for `beforeinstallprompt` event and stores the prompt.
|
||||
2. Checks `window.matchMedia('(display-mode: standalone)')` to detect if already installed.
|
||||
3. Exposes `promptInstall()` to trigger the native install dialog.
|
||||
4. Dismisses the prompt after user action (install or cancel).
|
||||
|
||||
---
|
||||
|
||||
### Step 5 — Create `src/components/InstallBanner.tsx` — Install UI
|
||||
|
||||
A dismissible banner that appears on first visit (not installed) with:
|
||||
- "Install StemEngine" button → calls `promptInstall()`
|
||||
- "Dismiss" button → hides banner for 7 days (localStorage)
|
||||
- Only shown on mobile or if `canInstall === true`
|
||||
- Styled with MetroUI classes for consistency
|
||||
|
||||
---
|
||||
|
||||
### Step 6 — Create `src/hooks/useWebVitals.ts` — Performance Monitoring
|
||||
|
||||
Integrate `web-vitals` to track Core Web Vitals (LCP, FID, CLS, TTFB):
|
||||
|
||||
```typescript
|
||||
interface VitalsData {
|
||||
lcp?: number
|
||||
fid?: number
|
||||
cls?: number
|
||||
ttfb?: number
|
||||
}
|
||||
```
|
||||
|
||||
The hook:
|
||||
1. Calls `getCLS()`, `getFID()`, `getLCP()`, `getTTFB()` from `web-vitals`.
|
||||
2. Logs metrics to console in dev, sends to analytics endpoint in production.
|
||||
3. Stores metrics in IndexedDB for historical analysis.
|
||||
|
||||
---
|
||||
|
||||
### Step 7 — Update `src/main.tsx` — Register Service Worker & Initialize PWA
|
||||
|
||||
```typescript
|
||||
import { Workbox } from 'workbox-window'
|
||||
import { initDB } from './utils/db'
|
||||
import { processQueue } from './utils/offlineSync'
|
||||
import { trackWebVitals } from './hooks/useWebVitals'
|
||||
|
||||
// Initialize IndexedDB
|
||||
initDB().catch(console.error)
|
||||
|
||||
// Register service worker (Workbox)
|
||||
if ('serviceWorker' in navigator) {
|
||||
const wb = new Workbox('/sw.js')
|
||||
|
||||
// Prompt user to reload when a new SW is ready
|
||||
wb.addEventListener('controlling', () => {
|
||||
window.location.reload()
|
||||
})
|
||||
|
||||
wb.register().catch(console.error)
|
||||
}
|
||||
|
||||
// Sync offline queue when online
|
||||
window.addEventListener('online', () => {
|
||||
processQueue().catch(console.error)
|
||||
})
|
||||
|
||||
// Track Web Vitals
|
||||
trackWebVitals()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 8 — Update `src/App.tsx` — Add Install Banner & Offline Indicator
|
||||
|
||||
In the `AppShell` component:
|
||||
|
||||
1. Import `useInstallPrompt` and `InstallBanner`.
|
||||
2. Add `<InstallBanner />` below the AppBar (or in a modal).
|
||||
3. Add an offline indicator (red dot + "Offline" label) in the AppBar when `!navigator.onLine`.
|
||||
4. Disable API calls and show cached data when offline.
|
||||
|
||||
---
|
||||
|
||||
### Step 9 — Update API Client (`src/api/client.ts`) — Offline Fallback
|
||||
|
||||
Wrap all API calls with offline detection:
|
||||
|
||||
```typescript
|
||||
async function apiCall<T>(endpoint: string, options?: RequestInit): Promise<T> {
|
||||
if (!navigator.onLine) {
|
||||
// Try to return cached data from IndexedDB
|
||||
const cached = await getCachedResponse(endpoint)
|
||||
if (cached) return cached
|
||||
throw new Error('Offline and no cached data available')
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(endpoint, options)
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
||||
const data = await response.json()
|
||||
|
||||
// Cache successful responses
|
||||
await cacheResponse(endpoint, data)
|
||||
return data
|
||||
} catch (error) {
|
||||
// On network error, try cache
|
||||
const cached = await getCachedResponse(endpoint)
|
||||
if (cached) return cached
|
||||
throw error
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 10 — Create `src/components/OfflineNotice.tsx` — Offline UI
|
||||
|
||||
A persistent banner that appears when offline:
|
||||
- "You are offline. Some features may be limited."
|
||||
- Shows cached data age: "Last synced 5 minutes ago"
|
||||
- Disappears when online
|
||||
- Styled with MetroUI warning colors
|
||||
|
||||
---
|
||||
|
||||
### Step 11 — Optimize Bundle Size
|
||||
|
||||
Update `file:frontend/vite.config.ts` with code-splitting and lazy loading:
|
||||
|
||||
1. **Route-based code splitting:** Use `React.lazy()` for `Separator`, `ProjectDetail`, `SettingsPage`.
|
||||
2. **Dynamic imports:** Lazy-load heavy libraries like `abcjs`, `tone` only when needed.
|
||||
3. **Tree-shaking:** Ensure unused MetroUI components are removed (configure MetroUI imports).
|
||||
4. **Compression:** Enable gzip/brotli in the backend server config.
|
||||
|
||||
---
|
||||
|
||||
### Step 12 — Create App Icons & Splash Screens
|
||||
|
||||
Generate and place in `file:frontend/public/`:
|
||||
|
||||
| File | Size | Purpose |
|
||||
|---|---|---|
|
||||
| `icon-192.png` | 192×192 | Home screen icon (Android) |
|
||||
| `icon-512.png` | 512×512 | Splash screen icon |
|
||||
| `icon-maskable-192.png` | 192×192 | Adaptive icon (Android 8+) |
|
||||
| `icon-maskable-512.png` | 512×512 | Adaptive icon large |
|
||||
| `icon-96.png` | 96×96 | App shortcuts |
|
||||
| `screenshot-540x720.png` | 540×720 | Mobile screenshot (narrow) |
|
||||
| `screenshot-1280x720.png` | 1280×720 | Desktop screenshot (wide) |
|
||||
| `favicon.ico` | 32×32 | Browser tab icon |
|
||||
| `robots.txt` | — | SEO: disallow `/api/` |
|
||||
|
||||
Use a tool like `sharp` or online icon generators to create these from a base SVG.
|
||||
|
||||
---
|
||||
|
||||
### Step 13 — Update `file:frontend/index.html` — Enhanced PWA Meta Tags
|
||||
|
||||
```html
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, user-scalable=no" />
|
||||
<meta name="description" content="Audio processing toolkit — stem separation, lyrics sync, MIDI transcription" />
|
||||
<meta name="theme-color" content="#3B82F6" />
|
||||
|
||||
<!-- PWA Manifest (auto-generated by vite-plugin-pwa) -->
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
|
||||
<!-- Icons -->
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="/icon-192.png" />
|
||||
|
||||
<!-- iOS PWA -->
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-title" content="StemEngine" />
|
||||
|
||||
<!-- Splash screen (iOS) -->
|
||||
<link rel="apple-touch-startup-image" href="/splash-1125x2436.png" media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3)" />
|
||||
|
||||
<!-- Safe area insets for notched devices -->
|
||||
<meta name="viewport-fit" content="cover" />
|
||||
|
||||
<!-- Disable zoom on iOS (improves UX) -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
|
||||
<title>StemEngine</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 14 — Create `src/utils/mobileOptimizations.ts` — Mobile UX Enhancements
|
||||
|
||||
Implement mobile-specific optimizations:
|
||||
|
||||
```typescript
|
||||
// Disable double-tap zoom (improves responsiveness)
|
||||
document.addEventListener('touchstart', (e) => {
|
||||
if (e.touches.length > 1) e.preventDefault()
|
||||
}, { passive: false })
|
||||
|
||||
// Prevent pull-to-refresh on iOS (optional)
|
||||
document.body.addEventListener('touchmove', (e) => {
|
||||
if (window.scrollY === 0) e.preventDefault()
|
||||
}, { passive: false })
|
||||
|
||||
// Detect notch/safe area and apply padding
|
||||
const safeAreaInsetTop = parseInt(getComputedStyle(document.documentElement).getPropertyValue('env(safe-area-inset-top)'))
|
||||
if (safeAreaInsetTop > 0) {
|
||||
document.documentElement.style.setProperty('--safe-area-top', `${safeAreaInsetTop}px`)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 15 — Update `file:frontend/src/index.css` — Mobile Viewport Optimizations
|
||||
|
||||
```css
|
||||
/* Prevent layout shift on mobile */
|
||||
html {
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
/* Safe area support for notched devices */
|
||||
body {
|
||||
padding-top: max(0px, env(safe-area-inset-top));
|
||||
padding-left: max(0px, env(safe-area-inset-left));
|
||||
padding-right: max(0px, env(safe-area-inset-right));
|
||||
padding-bottom: max(0px, env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
/* Improve touch targets on mobile */
|
||||
@media (max-width: 640px) {
|
||||
button, input[type="button"], input[type="submit"] {
|
||||
min-height: 44px;
|
||||
min-width: 44px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Prevent text selection on long press (improves UX) */
|
||||
body {
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
input, textarea, [contenteditable] {
|
||||
-webkit-user-select: text;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
/* Smooth scrolling */
|
||||
html {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
/* Prevent iOS zoom on input focus */
|
||||
input, textarea, select {
|
||||
font-size: 16px;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 16 — Create `src/hooks/useOnlineStatus.ts` — Online/Offline Hook
|
||||
|
||||
```typescript
|
||||
function useOnlineStatus(): boolean {
|
||||
const [isOnline, setIsOnline] = useState(navigator.onLine)
|
||||
|
||||
useEffect(() => {
|
||||
const handleOnline = () => setIsOnline(true)
|
||||
const handleOffline = () => setIsOnline(false)
|
||||
|
||||
window.addEventListener('online', handleOnline)
|
||||
window.addEventListener('offline', handleOffline)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('online', handleOnline)
|
||||
window.removeEventListener('offline', handleOffline)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return isOnline
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 17 — Create `public/robots.txt` — SEO
|
||||
|
||||
```
|
||||
User-agent: *
|
||||
Disallow: /api/
|
||||
Disallow: /admin/
|
||||
Allow: /
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 18 — Update Backend Server Config — PWA Headers
|
||||
|
||||
In the backend (Flask/FastAPI at `file:backend/app.py` or equivalent), set these headers for all responses:
|
||||
|
||||
```python
|
||||
# Cache-Control headers for static assets
|
||||
@app.after_request
|
||||
def set_cache_headers(response):
|
||||
if request.path.startswith('/static/'):
|
||||
# Versioned assets (hashed filenames) — cache forever
|
||||
response.headers['Cache-Control'] = 'public, max-age=31536000, immutable'
|
||||
elif request.path in ['/', '/index.html']:
|
||||
# HTML — revalidate frequently
|
||||
response.headers['Cache-Control'] = 'public, max-age=3600, must-revalidate'
|
||||
else:
|
||||
# API — no cache
|
||||
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
|
||||
|
||||
# Security headers
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
|
||||
response.headers['X-XSS-Protection'] = '1; mode=block'
|
||||
|
||||
# CORS headers (if serving to external clients)
|
||||
response.headers['Access-Control-Allow-Origin'] = '*'
|
||||
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
|
||||
|
||||
return response
|
||||
```
|
||||
|
||||
**Docker-specific notes:**
|
||||
- The backend runs inside a container; ensure the app serves static files from `/app/backend/static` (where Vite builds output).
|
||||
- Use a reverse proxy (nginx) in front of the backend to handle caching headers and compression more efficiently.
|
||||
- Set `PYTHONUNBUFFERED=1` in the Dockerfile to ensure logs stream to stdout (visible in `docker logs`).
|
||||
|
||||
---
|
||||
|
||||
### Step 19 — Create `src/utils/backgroundSync.ts` — Background Sync for Jobs
|
||||
|
||||
Implement periodic polling for job status updates (when online). In a Docker container, the backend may be on a different port or hostname, so use relative URLs (`/api/...`):
|
||||
|
||||
```typescript
|
||||
interface BackgroundSyncConfig {
|
||||
pollIntervalMs: number
|
||||
maxRetries: number
|
||||
}
|
||||
|
||||
function startJobPolling(projectId: string, config: BackgroundSyncConfig) {
|
||||
const pollJob = async () => {
|
||||
if (!navigator.onLine) return
|
||||
try {
|
||||
// Use relative URL — Docker reverse proxy handles routing
|
||||
const response = await fetch(`/api/projects/${projectId}/jobs`)
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
||||
const jobs = await response.json()
|
||||
await Promise.all(jobs.map(j => saveJob(j)))
|
||||
} catch (error) {
|
||||
console.error('Job polling failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const intervalId = setInterval(pollJob, config.pollIntervalMs)
|
||||
return () => clearInterval(intervalId)
|
||||
}
|
||||
```
|
||||
|
||||
**Docker-specific notes:**
|
||||
- The frontend and backend are in separate containers; use relative URLs (`/api/...`) so the reverse proxy (nginx) routes them correctly.
|
||||
- Do not hardcode `http://localhost:8000` — that only works in dev mode with Vite proxy.
|
||||
- In production (Docker), the reverse proxy handles `/api/` → backend container routing.
|
||||
|
||||
---
|
||||
|
||||
### Step 20 — Testing & Validation Checklist
|
||||
|
||||
| Test | Method |
|
||||
|---|---|
|
||||
| **Install prompt** | Open on mobile/desktop, check for install banner |
|
||||
| **Offline mode** | Disable network in DevTools, verify cached data loads |
|
||||
| **Service worker** | Check DevTools → Application → Service Workers |
|
||||
| **Cache strategy** | Verify assets cached, API calls network-first |
|
||||
| **Web Vitals** | Run Lighthouse audit, check Core Web Vitals |
|
||||
| **Icons & manifest** | Validate with `https://www.pwabuilder.com/` |
|
||||
| **Responsive design** | Test on iPhone, Android, iPad, desktop |
|
||||
| **Touch interactions** | Verify 44px+ touch targets, no double-tap zoom |
|
||||
| **Offline queue** | Create job offline, verify sync when online |
|
||||
| **Background sync** | Verify job polling continues in background |
|
||||
|
||||
---
|
||||
|
||||
## File Summary
|
||||
|
||||
| File | Action |
|
||||
|---|---|
|
||||
| `file:frontend/package.json` | Add PWA dependencies (`workbox-window`, `idb`, `web-vitals`, `vite-plugin-pwa`) |
|
||||
| `file:frontend/vite.config.ts` | Configure `vite-plugin-pwa`, code-splitting, caching strategies |
|
||||
| `file:frontend/index.html` | Add enhanced PWA meta tags, safe area support |
|
||||
| `file:frontend/src/main.tsx` | Register Workbox SW, initialize DB, track Web Vitals |
|
||||
| `file:frontend/src/index.css` | Add mobile viewport optimizations, safe area support |
|
||||
| `file:frontend/src/App.tsx` | Add `InstallBanner`, offline indicator, `useOnlineStatus` |
|
||||
| `file:frontend/src/api/client.ts` | Wrap API calls with offline fallback, caching; use relative URLs |
|
||||
| `file:frontend/src/utils/db.ts` | **New** — IndexedDB wrapper for offline state |
|
||||
| `file:frontend/src/utils/offlineSync.ts` | **New** — Offline operation queue & sync |
|
||||
| `file:frontend/src/utils/backgroundSync.ts` | **New** — Job polling & background sync (relative URLs) |
|
||||
| `file:frontend/src/utils/mobileOptimizations.ts` | **New** — Mobile UX enhancements |
|
||||
| `file:frontend/src/hooks/useInstallPrompt.ts` | **New** — Install prompt hook |
|
||||
| `file:frontend/src/hooks/useOnlineStatus.ts` | **New** — Online/offline status hook |
|
||||
| `file:frontend/src/hooks/useWebVitals.ts` | **New** — Web Vitals tracking |
|
||||
| `file:frontend/src/components/InstallBanner.tsx` | **New** — Install UI banner |
|
||||
| `file:frontend/src/components/OfflineNotice.tsx` | **New** — Offline indicator |
|
||||
| `file:frontend/public/manifest.webmanifest` | Auto-generated by `vite-plugin-pwa` |
|
||||
| `file:frontend/public/sw.js` | Auto-generated by `vite-plugin-pwa` |
|
||||
| `file:frontend/public/robots.txt` | **New** — SEO robots file |
|
||||
| `file:frontend/public/icon-*.png` | **New** — App icons (192, 512, maskable variants) |
|
||||
| `file:frontend/public/screenshot-*.png` | **New** — App store screenshots |
|
||||
| `file:frontend/public/splash-*.png` | **New** — iOS splash screens |
|
||||
| `file:backend/app.py` (or equivalent) | Add Cache-Control & security headers |
|
||||
| `file:docker-compose.yml` | **Update** — Ensure frontend & backend containers can communicate; add nginx reverse proxy |
|
||||
| `file:nginx.conf` | **New** — Reverse proxy config for PWA headers, compression, routing |
|
||||
| `file:Dockerfile.frontend` | **Update** — Build Vite app, serve from `/app/frontend/dist` |
|
||||
| `file:Dockerfile.backend` | **Update** — Set `PYTHONUNBUFFERED=1`, serve static files from `/app/backend/static` |
|
||||
|
||||
---
|
||||
|
||||
## Docker-Specific Adjustments
|
||||
|
||||
### Networking & Reverse Proxy
|
||||
|
||||
In a Docker environment, the frontend and backend run in separate containers. Use a reverse proxy (nginx) to:
|
||||
1. Serve the frontend static files (from `/app/frontend/dist`).
|
||||
2. Route `/api/` requests to the backend container.
|
||||
3. Apply PWA headers (Cache-Control, CORS, security headers).
|
||||
4. Enable gzip/brotli compression.
|
||||
|
||||
**Example `docker-compose.yml` structure:**
|
||||
```yaml
|
||||
services:
|
||||
frontend:
|
||||
build: ./frontend
|
||||
# Frontend container only builds; nginx serves the dist folder
|
||||
|
||||
backend:
|
||||
build: ./backend
|
||||
environment:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
# Backend API runs on port 8000 (internal)
|
||||
|
||||
nginx:
|
||||
image: nginx:latest
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- ./nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
- ./frontend/dist:/usr/share/nginx/html:ro
|
||||
depends_on:
|
||||
- backend
|
||||
```
|
||||
|
||||
**Example `nginx.conf` (simplified):**
|
||||
```nginx
|
||||
upstream backend {
|
||||
server backend:8000;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
# Serve frontend static files
|
||||
location / {
|
||||
root /usr/share/nginx/html;
|
||||
try_files $uri $uri/ /index.html;
|
||||
|
||||
# Cache-Control for HTML
|
||||
location = /index.html {
|
||||
add_header Cache-Control "public, max-age=3600, must-revalidate";
|
||||
}
|
||||
|
||||
# Cache-Control for versioned assets
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
gzip on;
|
||||
gzip_types text/plain text/css application/javascript image/svg+xml;
|
||||
}
|
||||
}
|
||||
|
||||
# Proxy API requests to backend
|
||||
location /api/ {
|
||||
proxy_pass http://backend;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# No caching for API
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
}
|
||||
|
||||
# Security headers
|
||||
add_header X-Content-Type-Options "nosniff";
|
||||
add_header X-Frame-Options "SAMEORIGIN";
|
||||
add_header X-XSS-Protection "1; mode=block";
|
||||
}
|
||||
```
|
||||
|
||||
### Build & Deployment
|
||||
|
||||
1. **Frontend build:** Vite outputs to `frontend/dist` (configured in `vite.config.ts` as `outDir: '../backend/static'` — adjust for Docker).
|
||||
2. **Backend static serving:** The backend serves `static/` folder (where frontend build output goes).
|
||||
3. **Docker build:** Use multi-stage builds to keep image size small.
|
||||
|
||||
**Example `Dockerfile.frontend`:**
|
||||
```dockerfile
|
||||
FROM node:18-alpine AS build
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/nginx.conf
|
||||
EXPOSE 80
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
```
|
||||
|
||||
### Service Worker & HTTPS
|
||||
|
||||
Service workers require **HTTPS** in production (except `localhost`). In Docker:
|
||||
1. Use Let's Encrypt + certbot for SSL certificates.
|
||||
2. Configure nginx to redirect HTTP → HTTPS.
|
||||
3. Update `manifest.webmanifest` to use `https://` URLs for icons.
|
||||
|
||||
### Environment Variables
|
||||
|
||||
Use Docker environment variables to configure API endpoints:
|
||||
|
||||
**In `frontend/src/api/client.ts`:**
|
||||
```typescript
|
||||
const API_BASE = process.env.REACT_APP_API_BASE || '/api'
|
||||
|
||||
async function apiCall<T>(endpoint: string, options?: RequestInit): Promise<T> {
|
||||
const url = `${API_BASE}${endpoint}`
|
||||
// ... rest of implementation
|
||||
}
|
||||
```
|
||||
|
||||
**In `docker-compose.yml`:**
|
||||
```yaml
|
||||
services:
|
||||
frontend:
|
||||
environment:
|
||||
REACT_APP_API_BASE: "/api" # Relative URL — nginx routes it
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase 1 — Core PWA Setup (Days 1–2)
|
||||
- Install dependencies, configure `vite-plugin-pwa`
|
||||
- Create IndexedDB wrapper (`db.ts`)
|
||||
- Update `main.tsx` to register Workbox SW
|
||||
- Test manifest generation and icon validation
|
||||
- **Docker:** Verify Vite build output location
|
||||
|
||||
### Phase 2 — Offline Support (Days 3–4)
|
||||
- Implement offline queue (`offlineSync.ts`)
|
||||
- Update API client with offline fallback; use relative URLs
|
||||
- Create `useOnlineStatus` hook
|
||||
- Add `OfflineNotice` component
|
||||
- **Docker:** Test API routing through nginx proxy
|
||||
|
||||
### Phase 3 — Install & Mobile UX (Days 5–6)
|
||||
- Implement `useInstallPrompt` hook
|
||||
- Create `InstallBanner` component
|
||||
- Add mobile optimizations (`mobileOptimizations.ts`)
|
||||
- Update `index.css` with safe area support
|
||||
- **Docker:** Ensure manifest is served with correct MIME type
|
||||
|
||||
### Phase 4 — Performance & Monitoring (Days 7–8)
|
||||
- Integrate Web Vitals tracking
|
||||
- Implement background sync for jobs (relative URLs)
|
||||
- Optimize bundle size with code-splitting
|
||||
- Run Lighthouse audit and fix issues
|
||||
- **Docker:** Configure nginx gzip compression
|
||||
|
||||
### Phase 5 — Docker & Deployment (Days 9–10)
|
||||
- Create multi-stage Dockerfiles for frontend & backend
|
||||
- Set up nginx reverse proxy with PWA headers
|
||||
- Configure SSL/HTTPS with Let's Encrypt
|
||||
- Test offline workflows in Docker environment
|
||||
- Validate service worker registration and caching
|
||||
|
||||
---
|
||||
|
||||
## Risk Mitigation
|
||||
|
||||
| Risk | Mitigation |
|
||||
|---|---|
|
||||
| **IndexedDB quota exceeded** | Implement `clearOldCache()` to prune entries; monitor quota with `navigator.storage.estimate()` |
|
||||
| **Service worker stale cache** | Use Workbox's automatic versioning; set `skipWaiting: true` to update immediately |
|
||||
| **Offline data conflicts** | Queue operations with timestamps; on sync, server wins (last-write-wins) |
|
||||
| **iOS PWA limitations** | Test on real iOS device; use `apple-mobile-web-app-*` meta tags; provide fallback for unsupported features |
|
||||
| **Large bundle size** | Use code-splitting and lazy loading; monitor with `vite-plugin-visualizer` |
|
||||
| **Background sync not working** | Implement fallback polling; test on real device (DevTools simulation is unreliable) |
|
||||
| **Safe area insets not applied** | Test on notched devices; use `env(safe-area-inset-*)` in CSS |
|
||||
| **Docker container networking** | Use container names (e.g., `backend:8000`) in nginx upstream; ensure `docker-compose` network is set up |
|
||||
| **Frontend build output location** | Verify Vite `outDir` matches where nginx serves static files; use absolute paths in Docker |
|
||||
| **Service worker HTTPS requirement** | Use Let's Encrypt in production; localhost works without HTTPS for testing |
|
||||
| **API endpoint routing** | Use relative URLs (`/api/...`) in frontend; nginx reverse proxy handles routing to backend container |
|
||||
| **Cache invalidation in Docker** | Use Vite's hash-based filenames; nginx caches versioned assets forever, HTML revalidates frequently |
|
||||
| **Environment variable injection** | Use Docker `ENV` or `docker-compose` `environment:` to pass API base URL to frontend build |
|
||||
@@ -19,8 +19,8 @@
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-title" content="StemEngine" />
|
||||
<link rel="apple-touch-icon" href="/icon.svg" />
|
||||
<script type="module" crossorigin src="/assets/index-CbPgJQFv.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-eZreWOFb.css">
|
||||
<script type="module" crossorigin src="/assets/index-CLGPiso6.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-C8mDx5-m.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>StemEngine</title>
|
||||
|
||||
<!-- PWA manifest -->
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
|
||||
<!-- Favicon -->
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
|
||||
<!-- Theme color (browser chrome on Android, tab bar tint) -->
|
||||
<meta name="theme-color" content="#3B82F6" />
|
||||
|
||||
<!-- iOS PWA -->
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-title" content="StemEngine" />
|
||||
<link rel="apple-touch-icon" href="/icon.svg" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
+2691
File diff suppressed because it is too large.
Load diff
Executable
+39
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"name": "stemengine-frontend",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/archivo": "^5.0.0",
|
||||
"@fontsource/eb-garamond": "^5.0.0",
|
||||
"@fontsource/inter": "^5.0.0",
|
||||
"@fontsource/libre-baskerville": "^5.0.0",
|
||||
"@fontsource/oswald": "^5.0.0",
|
||||
"@fontsource/poppins": "^5.0.0",
|
||||
"@fontsource/roboto": "^5.0.0",
|
||||
"@fontsource/work-sans": "^5.0.0",
|
||||
"@fontsource/young-serif": "^5.0.0",
|
||||
"@tanstack/react-query": "^5.0.0",
|
||||
"@tonejs/midi": "^2.0.28",
|
||||
"abcjs": "^6.6.2",
|
||||
"lucide-react": "^0.294.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"tone": "^14.7.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.37",
|
||||
"@types/react-dom": "^18.2.15",
|
||||
"@vitejs/plugin-react": "^4.2.0",
|
||||
"autoprefixer": "^10.4.16",
|
||||
"postcss": "^8.4.32",
|
||||
"tailwindcss": "^3.3.6",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^5.0.0"
|
||||
}
|
||||
}
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||
<defs>
|
||||
<linearGradient id="g" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" stop-color="#3B82F6"/>
|
||||
<stop offset="100%" stop-color="#1D4ED8"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<!-- Full-bleed background (maskable safe zone = center 80%) -->
|
||||
<rect width="512" height="512" fill="url(#g)"/>
|
||||
<!-- Music2 icon from Lucide, original 24×24, scaled ×15, centered in 512×512 -->
|
||||
<!-- Content bounding box: ~3..21 in x, ~3..21 in y → 18×18 units → 270×270 px -->
|
||||
<!-- Translate so content center (12,12 orig) maps to (256,256) -->
|
||||
<!-- translateX = 256 - 12×15 = 76 translateY = 256 - 12×15 = 76 -->
|
||||
<g transform="translate(76,76) scale(15)"
|
||||
stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none">
|
||||
<path d="M9 18V5l12-2v13"/>
|
||||
<circle cx="6" cy="18" r="3"/>
|
||||
<circle cx="18" cy="16" r="3"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 961 B |
Executable
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "StemEngine",
|
||||
"short_name": "StemEngine",
|
||||
"description": "Audio processing toolkit — stem separation, lyrics sync, MIDI transcription",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"orientation": "any",
|
||||
"background_color": "#030712",
|
||||
"theme_color": "#3B82F6",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon.svg",
|
||||
"sizes": "any",
|
||||
"type": "image/svg+xml",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
// StemEngine Service Worker
|
||||
// Minimal implementation for PWA installability.
|
||||
// API responses are intentionally NOT cached (all data is dynamic/local).
|
||||
// The app shell (HTML/JS/CSS) is cached so the UI loads instantly on repeat visits.
|
||||
|
||||
const CACHE = 'stemengine-v1'
|
||||
|
||||
// Assets to pre-cache on install
|
||||
const SHELL = ['/']
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(
|
||||
caches.open(CACHE).then((cache) => cache.addAll(SHELL))
|
||||
)
|
||||
// Activate immediately — don't wait for old tabs to close
|
||||
self.skipWaiting()
|
||||
})
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
// Delete old caches from previous versions
|
||||
event.waitUntil(
|
||||
caches.keys().then((keys) =>
|
||||
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
|
||||
).then(() => self.clients.claim())
|
||||
)
|
||||
})
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const { request } = event
|
||||
const url = new URL(request.url)
|
||||
|
||||
// Let API calls and non-GET requests go straight to the network
|
||||
if (request.method !== 'GET' || url.pathname.startsWith('/api/')) {
|
||||
event.respondWith(fetch(request))
|
||||
return
|
||||
}
|
||||
|
||||
// For navigation requests: network-first, fall back to cached shell
|
||||
if (request.mode === 'navigate') {
|
||||
event.respondWith(
|
||||
fetch(request).catch(() => caches.match('/'))
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// For static assets: cache-first
|
||||
event.respondWith(
|
||||
caches.match(request).then((cached) => {
|
||||
if (cached) return cached
|
||||
return fetch(request).then((response) => {
|
||||
if (response.ok) {
|
||||
const clone = response.clone()
|
||||
caches.open(CACHE).then((cache) => cache.put(request, clone))
|
||||
}
|
||||
return response
|
||||
})
|
||||
})
|
||||
)
|
||||
})
|
||||
Executable
+273
@@ -0,0 +1,273 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Music2, Settings, Cpu } from 'lucide-react'
|
||||
import Separator from './pages/Separator'
|
||||
import ProjectDetail from './pages/ProjectDetail'
|
||||
import SettingsPage, { applyFont, applyAccent } from './pages/Settings'
|
||||
import { ThemeProvider } from './context/ThemeContext'
|
||||
import Sidebar from './components/Sidebar'
|
||||
import GlobalAudioBar from './components/GlobalAudioBar'
|
||||
import { listProjects, deleteProject, getGpuInfo, resetGpu } from './api/client'
|
||||
import type { Project } from './types'
|
||||
|
||||
interface ProjectTab {
|
||||
id: string
|
||||
label: string // e.g. "Demucs v4_MP3 (256 kbps)"
|
||||
name: string // e.g. "Artist - Title"
|
||||
}
|
||||
|
||||
interface GpuInfo {
|
||||
cuda_available: boolean
|
||||
cuda_ok: boolean
|
||||
name: string | null
|
||||
free_mb: number
|
||||
total_mb: number
|
||||
}
|
||||
|
||||
function AppShell() {
|
||||
const [activeTabId, setActiveTabId] = useState<string>(
|
||||
() => localStorage.getItem('stemengine-active-tab') ?? 'separate'
|
||||
)
|
||||
const [projectTabs, setProjectTabs] = useState<ProjectTab[]>([])
|
||||
const [sidebarOpen, setSidebarOpen] = useState(() => window.innerWidth >= 640)
|
||||
|
||||
// GPU state
|
||||
const [gpuInfo, setGpuInfo] = useState<GpuInfo | null>(null)
|
||||
const [gpuResetting, setGpuResetting] = useState(false)
|
||||
|
||||
// Persist active tab so it survives a page refresh
|
||||
useEffect(() => {
|
||||
localStorage.setItem('stemengine-active-tab', activeTabId)
|
||||
}, [activeTabId])
|
||||
|
||||
// Apply saved font and accent color on mount
|
||||
useEffect(() => {
|
||||
applyFont(localStorage.getItem('stemengine-font') ?? 'system')
|
||||
applyAccent(localStorage.getItem('stemengine-accent') ?? 'blue')
|
||||
}, [])
|
||||
|
||||
// Load all projects from DB on mount → restore persistent tabs
|
||||
useEffect(() => {
|
||||
listProjects()
|
||||
.then((projects: Project[]) => {
|
||||
const tabs = projects.map((p) => ({
|
||||
id: p.id,
|
||||
label: p.tab_label || p.name,
|
||||
name: p.name,
|
||||
}))
|
||||
setProjectTabs(tabs)
|
||||
// If the restored tab is a project that no longer exists, go home
|
||||
setActiveTabId((current) => {
|
||||
if (current === 'separate' || current === 'settings') return current
|
||||
return tabs.find((t) => t.id === current) ? current : 'separate'
|
||||
})
|
||||
})
|
||||
.catch(() => {/* ignore – server may not be ready yet */})
|
||||
}, [])
|
||||
|
||||
// Poll GPU info on mount + every 30 s
|
||||
useEffect(() => {
|
||||
async function fetchGpu() {
|
||||
try {
|
||||
setGpuInfo(await getGpuInfo())
|
||||
} catch { /* server not ready yet */ }
|
||||
}
|
||||
fetchGpu()
|
||||
const id = setInterval(fetchGpu, 30_000)
|
||||
return () => clearInterval(id)
|
||||
}, [])
|
||||
|
||||
async function handleGpuReset() {
|
||||
setGpuResetting(true)
|
||||
try {
|
||||
await resetGpu()
|
||||
setGpuInfo(await getGpuInfo())
|
||||
} catch { /* ignore */ }
|
||||
setGpuResetting(false)
|
||||
}
|
||||
|
||||
// Auto-reset when the GPU context is marked failed (e.g. after Whisper fallback)
|
||||
const gpuContextFailed = gpuInfo?.cuda_available === true && gpuInfo.cuda_ok === false
|
||||
useEffect(() => {
|
||||
if (gpuContextFailed && !gpuResetting) {
|
||||
handleGpuReset()
|
||||
}
|
||||
}, [gpuContextFailed])
|
||||
|
||||
// Called by Separator when a separation job finishes
|
||||
const handleSeparationComplete = useCallback(
|
||||
(projectId: string, tabLabel: string, projectName: string) => {
|
||||
setProjectTabs((prev) => {
|
||||
if (prev.find((t) => t.id === projectId)) return prev
|
||||
return [...prev, { id: projectId, label: tabLabel, name: projectName }]
|
||||
})
|
||||
setActiveTabId(projectId)
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
// Close (delete) a project tab
|
||||
async function handleCloseTab(projectId: string, projectName: string) {
|
||||
const label = projectTabs.find((t) => t.id === projectId)?.label || projectName
|
||||
if (!window.confirm(`Delete "${label}"?\n\nThis will permanently remove the project and all its files.`)) return
|
||||
|
||||
try {
|
||||
await deleteProject(projectId)
|
||||
} catch {
|
||||
// If delete fails, still remove from tabs (project may already be gone)
|
||||
}
|
||||
setProjectTabs((prev) => prev.filter((t) => t.id !== projectId))
|
||||
if (activeTabId === projectId) setActiveTabId('separate')
|
||||
}
|
||||
|
||||
// Called from sidebar when a project is deleted there
|
||||
function handleDeleteProjectFromSidebar(project: Project) {
|
||||
setProjectTabs((prev) => prev.filter((t) => t.id !== project.id))
|
||||
if (activeTabId === project.id) setActiveTabId('separate')
|
||||
}
|
||||
|
||||
// Open a project tab from sidebar click — adds it if not already open
|
||||
function handleOpenProject(project: Project) {
|
||||
setProjectTabs((prev) => {
|
||||
if (prev.find((t) => t.id === project.id)) return prev
|
||||
return [...prev, {
|
||||
id: project.id,
|
||||
label: project.tab_label || project.name,
|
||||
name: project.name,
|
||||
}]
|
||||
})
|
||||
setActiveTabId(project.id)
|
||||
}
|
||||
|
||||
// Derive GPU button appearance
|
||||
const gpuError = gpuInfo ? (!gpuInfo.cuda_ok || !gpuInfo.cuda_available) : false
|
||||
const gpuTitle = gpuInfo
|
||||
? gpuInfo.cuda_available
|
||||
? `${gpuInfo.name ?? 'GPU'} · ${gpuInfo.free_mb} / ${gpuInfo.total_mb} MB free${!gpuInfo.cuda_ok ? ' · Context error — click to reset' : ''}`
|
||||
: 'CUDA unavailable — click to attempt reset'
|
||||
: 'GPU status unknown'
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col overflow-hidden">
|
||||
{/* ── Header ── */}
|
||||
<header className="shrink-0 border-b border-slate-200 dark:border-gray-800 bg-white dark:bg-gray-950 z-20">
|
||||
<div className="h-1 bg-gradient-to-r from-brand-500 via-purple-500 to-rose-500" />
|
||||
|
||||
<div className="px-4 py-2.5 flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => setActiveTabId('separate')}
|
||||
title="Home"
|
||||
className="flex items-center gap-2 flex-1 min-w-0 hover:opacity-80 transition-opacity text-left"
|
||||
>
|
||||
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-brand-500 to-brand-700 flex items-center justify-center shrink-0 shadow-md shadow-brand-500/30">
|
||||
<Music2 className="w-4 h-4 text-white" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="text-base font-bold text-slate-900 dark:text-white tracking-tight">StemEngine</span>
|
||||
<span className="text-xs text-slate-400 dark:text-gray-600 ml-2 hidden sm:inline">Audio processing toolkit</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* GPU status button */}
|
||||
<button
|
||||
onClick={handleGpuReset}
|
||||
title={gpuTitle}
|
||||
className={`relative p-2 rounded-xl border transition-all ${
|
||||
gpuError
|
||||
? 'border-red-400 bg-red-50 dark:bg-red-950/30 text-red-500 dark:text-red-400 hover:border-red-500'
|
||||
: 'border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-900 text-slate-400 dark:text-gray-600 hover:text-brand-600 dark:hover:text-brand-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Cpu className={`w-4 h-4 ${gpuResetting ? 'animate-pulse' : ''}`} />
|
||||
{/* status dot */}
|
||||
{gpuInfo && (
|
||||
<span className={`absolute top-1 right-1 w-1.5 h-1.5 rounded-full ${
|
||||
!gpuInfo.cuda_available ? 'bg-slate-400 dark:bg-gray-600'
|
||||
: !gpuInfo.cuda_ok ? 'bg-red-500 animate-pulse'
|
||||
: 'bg-emerald-400'
|
||||
}`} />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTabId('settings')}
|
||||
title="Settings"
|
||||
className={`p-2 rounded-xl border transition-all ${
|
||||
activeTabId === 'settings'
|
||||
? 'border-brand-500 bg-brand-50 dark:bg-brand-950/30 text-brand-600 dark:text-brand-400'
|
||||
: 'border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-900 text-slate-500 hover:text-brand-600 dark:text-gray-400 dark:hover:text-brand-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Settings className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* ── Body: sidebar + main ── */}
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
|
||||
{/* Backdrop — tapping it closes the sidebar on mobile */}
|
||||
{sidebarOpen && (
|
||||
<div
|
||||
className="sm:hidden fixed inset-0 z-20 bg-black/40"
|
||||
onClick={() => setSidebarOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Sidebar
|
||||
isOpen={sidebarOpen}
|
||||
onToggle={() => setSidebarOpen((v) => !v)}
|
||||
onOpenProject={(p) => { handleOpenProject(p); setSidebarOpen(false) }}
|
||||
onDeleteProject={handleDeleteProjectFromSidebar}
|
||||
openTabIds={projectTabs.map((t) => t.id)}
|
||||
/>
|
||||
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-slate-100 dark:bg-gray-950">
|
||||
|
||||
{/* Page content */}
|
||||
<main className="flex-1 overflow-y-auto pb-12">
|
||||
{activeTabId === 'settings' ? (
|
||||
<SettingsPage />
|
||||
) : (
|
||||
<div className="max-w-3xl mx-auto px-2 sm:px-4 py-4 sm:py-6">
|
||||
<div className="rounded-2xl border border-slate-200 dark:border-gray-800 bg-white dark:bg-gray-900/60 p-3 sm:p-6 shadow-sm dark:shadow-xl">
|
||||
{activeTabId === 'separate' ? (
|
||||
<Separator
|
||||
onSeparationComplete={handleSeparationComplete}
|
||||
onOpenSettings={() => {
|
||||
localStorage.setItem('stemengine-settings-initial-tab', 'autopipeline')
|
||||
setActiveTabId('settings')
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<ProjectDetail
|
||||
id={activeTabId}
|
||||
onDelete={() => {
|
||||
const tab = projectTabs.find((t) => t.id === activeTabId)
|
||||
if (tab) handleCloseTab(tab.id, tab.name)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<footer className="mt-6 text-center text-xs text-slate-400 dark:text-gray-700">
|
||||
StemEngine · Demucs · BS-RoFormer · Omnizart · wav2vec2
|
||||
</footer>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Floating playback bar — persists across page navigation */}
|
||||
<GlobalAudioBar />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<AppShell />
|
||||
</ThemeProvider>
|
||||
)
|
||||
}
|
||||
Executable
+569
@@ -0,0 +1,569 @@
|
||||
import type {
|
||||
Job,
|
||||
ModelOption,
|
||||
FormatOption,
|
||||
ModeOption,
|
||||
PresetsResponse,
|
||||
LyricsSource,
|
||||
LyricsData,
|
||||
DynamicLevels,
|
||||
LyricsStyleOptions,
|
||||
SubsonicSong,
|
||||
SubsonicConfig,
|
||||
ImportedFile,
|
||||
Project,
|
||||
ProjectDetail,
|
||||
ModelDownloadInfo,
|
||||
ModelDownloadProgress,
|
||||
} from '../types'
|
||||
|
||||
const BASE = '/api'
|
||||
|
||||
async function request<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(url, init)
|
||||
if (!res.ok) {
|
||||
const text = await res.text()
|
||||
throw new Error(`${res.status}: ${text}`)
|
||||
}
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
// ---------- Jobs ----------
|
||||
|
||||
export const getJob = (id: string) =>
|
||||
request<Job>(`${BASE}/jobs/${id}`)
|
||||
|
||||
export const listJobs = () =>
|
||||
request<Job[]>(`${BASE}/jobs`)
|
||||
|
||||
export const cancelJob = (id: string) =>
|
||||
request<{ detail: string }>(`${BASE}/jobs/${id}`, { method: 'DELETE' })
|
||||
|
||||
export const downloadUrl = (jobId: string, filename: string) =>
|
||||
`${BASE}/jobs/${jobId}/download/${encodeURIComponent(filename)}`
|
||||
|
||||
// ---------- Separate ----------
|
||||
|
||||
export const getSepModels = () =>
|
||||
request<ModelOption[]>(`${BASE}/separate/models`)
|
||||
|
||||
export const getSepFormats = () =>
|
||||
request<FormatOption[]>(`${BASE}/separate/formats`)
|
||||
|
||||
export const getPresets = () =>
|
||||
request<PresetsResponse>(`${BASE}/separate/presets`)
|
||||
|
||||
export const submitSeparate = (
|
||||
file: File,
|
||||
model: string,
|
||||
outputFormat: string,
|
||||
options?: {
|
||||
presetType?: string
|
||||
staticOption?: string
|
||||
dynamicLevels?: DynamicLevels
|
||||
projectName?: string
|
||||
sepPowerPreset?: string
|
||||
}
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
fd.append('model', model)
|
||||
fd.append('output_format', outputFormat)
|
||||
|
||||
if (options?.presetType) {
|
||||
fd.append('preset_type', options.presetType)
|
||||
}
|
||||
if (options?.staticOption) {
|
||||
fd.append('static_option', options.staticOption)
|
||||
}
|
||||
if (options?.dynamicLevels) {
|
||||
fd.append('dynamic_levels', JSON.stringify(options.dynamicLevels))
|
||||
}
|
||||
if (options?.projectName) {
|
||||
fd.append('project_name', options.projectName)
|
||||
}
|
||||
if (options?.sepPowerPreset) {
|
||||
fd.append('sep_power_preset', options.sepPowerPreset)
|
||||
}
|
||||
|
||||
return request<{ job_id: string; preset_type: string; project_name?: string }>(
|
||||
`${BASE}/separate`,
|
||||
{ method: 'POST', body: fd }
|
||||
)
|
||||
}
|
||||
|
||||
// ---------- Transcribe ----------
|
||||
|
||||
export const getTranscribeModes = () =>
|
||||
request<ModeOption[]>(`${BASE}/transcribe/modes`)
|
||||
|
||||
export const submitTranscribe = (file: File, mode: string) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
fd.append('mode', mode)
|
||||
return request<{ job_id: string }>(`${BASE}/transcribe`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- ABC Convert ----------
|
||||
|
||||
export const submitAbcConvert = (files: File[], songTitle: string) => {
|
||||
const fd = new FormData()
|
||||
files.forEach((f) => fd.append('files', f))
|
||||
fd.append('song_title', songTitle)
|
||||
return request<{ job_id: string }>(`${BASE}/abc-convert`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- Pipeline ----------
|
||||
|
||||
export const submitPipeline = (
|
||||
file: File,
|
||||
sepModel: string,
|
||||
sepFormat: string,
|
||||
transcribeMode: string,
|
||||
songTitle: string,
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
fd.append('sep_model', sepModel)
|
||||
fd.append('sep_format', sepFormat)
|
||||
fd.append('transcribe_mode', transcribeMode)
|
||||
fd.append('song_title', songTitle)
|
||||
return request<{ job_id: string }>(`${BASE}/pipeline`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- LRC Alignment ----------
|
||||
|
||||
export const getLyricsSources = () =>
|
||||
request<LyricsSource[]>(`${BASE}/lrc/sources`)
|
||||
|
||||
export const extractLyrics = (file: File) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
return request<LyricsData>(`${BASE}/lrc/extract`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
export const submitLrcAlign = (
|
||||
audio: File,
|
||||
options: {
|
||||
lyricsSource: string
|
||||
lyricsText?: string
|
||||
outputFilename?: string
|
||||
styleOptions?: LyricsStyleOptions
|
||||
}
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('audio', audio)
|
||||
fd.append('lyrics_source', options.lyricsSource)
|
||||
|
||||
if (options.lyricsText) {
|
||||
fd.append('lyrics_text', options.lyricsText)
|
||||
}
|
||||
if (options.outputFilename) {
|
||||
fd.append('output_filename', options.outputFilename)
|
||||
}
|
||||
if (options.styleOptions) {
|
||||
fd.append('style_options', JSON.stringify(options.styleOptions))
|
||||
}
|
||||
|
||||
return request<{ job_id: string }>(`${BASE}/lrc/align`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
export const submitLrcAlignWithFile = (
|
||||
audio: File,
|
||||
lyricsFile: File,
|
||||
outputFilename?: string,
|
||||
styleOptions?: LyricsStyleOptions
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('audio', audio)
|
||||
fd.append('lyrics_file', lyricsFile)
|
||||
|
||||
if (outputFilename) {
|
||||
fd.append('output_filename', outputFilename)
|
||||
}
|
||||
if (styleOptions) {
|
||||
fd.append('style_options', JSON.stringify(styleOptions))
|
||||
}
|
||||
|
||||
return request<{ job_id: string }>(`${BASE}/lrc/align-with-file`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
export const submitLrcAlignExisting = (
|
||||
projectName: string,
|
||||
options: {
|
||||
lyricsSource: string
|
||||
lyricsText?: string
|
||||
outputFilename?: string
|
||||
styleOptions?: LyricsStyleOptions
|
||||
}
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('project_name', projectName)
|
||||
fd.append('lyrics_source', options.lyricsSource)
|
||||
|
||||
if (options.lyricsText) {
|
||||
fd.append('lyrics_text', options.lyricsText)
|
||||
}
|
||||
if (options.outputFilename) {
|
||||
fd.append('output_filename', options.outputFilename)
|
||||
}
|
||||
if (options.styleOptions) {
|
||||
fd.append('style_options', JSON.stringify(options.styleOptions))
|
||||
}
|
||||
|
||||
return request<{ job_id: string }>(`${BASE}/lrc/align-existing`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- Quick-action helpers (from existing project/job on server) ----------
|
||||
|
||||
export const submitTranscribeFromProject = (projectName: string, mode = 'music') => {
|
||||
const fd = new FormData()
|
||||
fd.append('project_name', projectName)
|
||||
fd.append('mode', mode)
|
||||
return request<{ job_id: string; stem: string }>(`${BASE}/transcribe/from-project`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
export const submitAbcConvertFromJob = (sourceJobId: string, songTitle = '') => {
|
||||
const fd = new FormData()
|
||||
fd.append('source_job_id', sourceJobId)
|
||||
fd.append('song_title', songTitle)
|
||||
return request<{ job_id: string }>(`${BASE}/abc-convert/from-job`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- Subsonic ----------
|
||||
|
||||
export const getSubsonicConfig = () =>
|
||||
request<SubsonicConfig>(`${BASE}/subsonic/config`)
|
||||
|
||||
export const saveSubsonicConfig = (url: string, username: string, password: string) =>
|
||||
request<SubsonicConfig>(`${BASE}/subsonic/config`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url, username, password }),
|
||||
})
|
||||
|
||||
export const deleteSubsonicConfig = () =>
|
||||
request<SubsonicConfig>(`${BASE}/subsonic/config`, { method: 'DELETE' })
|
||||
|
||||
export const searchSubsonic = (q: string, count = 20) =>
|
||||
request<SubsonicSong[]>(`${BASE}/subsonic/search?q=${encodeURIComponent(q)}&count=${count}`)
|
||||
|
||||
export const importSubsonicSong = (song: SubsonicSong) =>
|
||||
request<ImportedFile>(`${BASE}/subsonic/import`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id: song.id, title: song.title, artist: song.artist, suffix: song.suffix }),
|
||||
})
|
||||
|
||||
export const listImports = () =>
|
||||
request<ImportedFile[]>(`${BASE}/subsonic/imports`)
|
||||
|
||||
export const deleteImport = (filename: string) =>
|
||||
request<{ detail: string }>(`${BASE}/subsonic/imports/${encodeURIComponent(filename)}`, { method: 'DELETE' })
|
||||
|
||||
// ---------- Separate from imported file ----------
|
||||
|
||||
export const submitSeparateFromPath = (
|
||||
filePath: string,
|
||||
model: string,
|
||||
outputFormat: string,
|
||||
options?: {
|
||||
presetType?: string
|
||||
staticOption?: string
|
||||
dynamicLevels?: DynamicLevels
|
||||
projectName?: string
|
||||
sepPowerPreset?: string
|
||||
}
|
||||
) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file_path', filePath)
|
||||
fd.append('model', model)
|
||||
fd.append('output_format', outputFormat)
|
||||
if (options?.presetType) fd.append('preset_type', options.presetType)
|
||||
if (options?.staticOption) fd.append('static_option', options.staticOption)
|
||||
if (options?.dynamicLevels) fd.append('dynamic_levels', JSON.stringify(options.dynamicLevels))
|
||||
if (options?.projectName) fd.append('project_name', options.projectName)
|
||||
if (options?.sepPowerPreset) fd.append('sep_power_preset', options.sepPowerPreset)
|
||||
return request<{ job_id: string; preset_type: string }>(`${BASE}/separate/from-path`, { method: 'POST', body: fd })
|
||||
}
|
||||
|
||||
// ---------- Projects ----------
|
||||
|
||||
export const listProjects = () =>
|
||||
request<Project[]>(`${BASE}/projects`)
|
||||
|
||||
export const getProjectDetail = (id: string) =>
|
||||
request<ProjectDetail>(`${BASE}/projects/${id}`)
|
||||
|
||||
export const deleteProject = (id: string) =>
|
||||
request<{ detail: string }>(`${BASE}/projects/${id}`, { method: 'DELETE' })
|
||||
|
||||
export const transcribeProject = (id: string, stemName: string, mode: string) =>
|
||||
request<{ job_id: string }>(`${BASE}/projects/${id}/transcribe`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ stem_name: stemName, mode }),
|
||||
})
|
||||
|
||||
export const abcProject = (id: string, stemName: string, songTitle?: string) =>
|
||||
request<{ job_id: string }>(`${BASE}/projects/${id}/abc`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ stem_name: stemName, song_title: songTitle }),
|
||||
})
|
||||
|
||||
export const mixProject = (
|
||||
id: string,
|
||||
presetType: 'static' | 'dynamic',
|
||||
opts?: { staticOption?: string; dynamicLevels?: Record<string, number> }
|
||||
) =>
|
||||
request<{ job_id: string }>(`${BASE}/projects/${id}/mix`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
preset_type: presetType,
|
||||
static_option: opts?.staticOption,
|
||||
dynamic_levels: opts?.dynamicLevels,
|
||||
}),
|
||||
})
|
||||
|
||||
export const lrcProject = (
|
||||
id: string,
|
||||
stemName: string,
|
||||
opts: {
|
||||
lyricsSource: string
|
||||
lyricsText?: string
|
||||
outputFilename?: string
|
||||
timingPrecision?: 'word' | 'syllable'
|
||||
lrcPowerPreset?: string
|
||||
}
|
||||
) =>
|
||||
request<{ job_id: string }>(`${BASE}/projects/${id}/lrc`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
stem_name: stemName,
|
||||
lyrics_source: opts.lyricsSource,
|
||||
lyrics_text: opts.lyricsText,
|
||||
output_filename: opts.outputFilename,
|
||||
timing_precision: opts.timingPrecision ?? 'word',
|
||||
lrc_power_preset: opts.lrcPowerPreset ?? 'standard',
|
||||
}),
|
||||
})
|
||||
|
||||
// ---------- Stem Reprocessing ----------
|
||||
|
||||
export const reprocessStem = (
|
||||
projectId: string,
|
||||
stemName: string,
|
||||
model: string,
|
||||
options?: {
|
||||
outputFormat?: string
|
||||
}
|
||||
) =>
|
||||
request<{ job_id: string }>(`${BASE}/projects/${projectId}/reprocess`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
stem_name: stemName,
|
||||
model,
|
||||
output_format: options?.outputFormat ?? 'mp3',
|
||||
}),
|
||||
})
|
||||
|
||||
// ---------- Lyric Transcription (Whisper AI) ----------
|
||||
|
||||
export const lyricTranscribeProject = (
|
||||
projectId: string,
|
||||
stemName: string,
|
||||
opts?: {
|
||||
model?: string
|
||||
language?: string
|
||||
task?: 'transcribe' | 'translate'
|
||||
outputFormats?: string[]
|
||||
initialPrompt?: string
|
||||
temperature?: number
|
||||
wordTimestamps?: boolean
|
||||
conditionOnPreviousText?: boolean
|
||||
beamSize?: number
|
||||
diarize?: boolean
|
||||
lrcPowerPreset?: string
|
||||
phonemeAlign?: boolean
|
||||
lsyncAlign?: boolean
|
||||
twoPass?: boolean
|
||||
vocalStyle?: string
|
||||
explicit?: boolean
|
||||
}
|
||||
) => {
|
||||
const wordTs = opts?.wordTimestamps ?? true
|
||||
const phonemeAlign = opts?.phonemeAlign ?? false
|
||||
const lsyncAlign = opts?.lsyncAlign ?? false
|
||||
// lsyncAlign requires word-level timestamps to write syllable data into ELRC
|
||||
const effectiveWordTs = wordTs || lsyncAlign
|
||||
const defaultFormats = effectiveWordTs
|
||||
? (phonemeAlign ? ['sylrc', 'elrc', 'lrc', 'txt'] : ['elrc', 'lrc', 'txt'])
|
||||
: ['lrc', 'txt']
|
||||
return request<{ job_id: string }>(`${BASE}/projects/${projectId}/lyric-transcribe`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
stem_name: stemName,
|
||||
model: opts?.model ?? 'large-v2',
|
||||
language: opts?.language || undefined,
|
||||
task: opts?.task ?? 'transcribe',
|
||||
output_formats: opts?.outputFormats ?? defaultFormats,
|
||||
initial_prompt: opts?.initialPrompt,
|
||||
temperature: opts?.temperature ?? 0.0,
|
||||
word_timestamps: effectiveWordTs,
|
||||
condition_on_previous_text: opts?.conditionOnPreviousText ?? true,
|
||||
beam_size: opts?.beamSize ?? undefined,
|
||||
engine: 'whisperx',
|
||||
diarize: opts?.diarize ?? false,
|
||||
lrc_power_preset: opts?.lrcPowerPreset ?? 'standard',
|
||||
phoneme_align: phonemeAlign,
|
||||
lsync_align: opts?.lsyncAlign ?? false,
|
||||
two_pass: opts?.twoPass ?? false,
|
||||
vocal_style: opts?.vocalStyle ?? 'general',
|
||||
explicit: opts?.explicit ?? false,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- Stem Rename ----------
|
||||
|
||||
export const renameStem = (
|
||||
projectId: string,
|
||||
stemName: string,
|
||||
newName: string
|
||||
) =>
|
||||
request<{ success: boolean; new_path: string }>(`${BASE}/projects/${projectId}/rename-stem`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
stem_name: stemName,
|
||||
new_name: newName,
|
||||
}),
|
||||
})
|
||||
|
||||
// ---------- Per-Instrument Models ----------
|
||||
|
||||
export const getPerInstrumentModels = () =>
|
||||
request<ModelOption[]>(`${BASE}/separate/per-instrument-models`)
|
||||
|
||||
// ---------- Model Management ----------
|
||||
|
||||
export const listModels = () =>
|
||||
request<ModelDownloadInfo[]>(`${BASE}/models/list`)
|
||||
|
||||
export const downloadModel = (modelId: string) =>
|
||||
request<{ success: boolean; message: string }>(`${BASE}/models/download`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model_id: modelId }),
|
||||
})
|
||||
|
||||
export const pauseModelDownload = (modelId: string) =>
|
||||
request<{ success: boolean; message: string }>(`${BASE}/models/pause`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model_id: modelId }),
|
||||
})
|
||||
|
||||
export const resumeModelDownload = (modelId: string) =>
|
||||
request<{ success: boolean; message: string }>(`${BASE}/models/resume`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model_id: modelId }),
|
||||
})
|
||||
|
||||
export const cancelModelDownload = (modelId: string) =>
|
||||
request<{ success: boolean; message: string }>(`${BASE}/models/cancel`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ model_id: modelId }),
|
||||
})
|
||||
|
||||
export const deleteModel = (modelId: string) =>
|
||||
request<{ success: boolean; message: string }>(`${BASE}/models/${modelId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
export const getModelProgress = (modelId: string) =>
|
||||
request<ModelDownloadProgress>(`${BASE}/models/progress/${modelId}`)
|
||||
|
||||
export const getAllModelProgress = () =>
|
||||
request<Record<string, ModelDownloadProgress>>(`${BASE}/models/progress`)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Project cleanup / maintenance
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const cleanupVerify = () =>
|
||||
request<{ projects_with_missing_files: { project_id: string; name: string; missing_files: string[] }[]; total: number }>(
|
||||
`${BASE}/projects/cleanup/verify`
|
||||
)
|
||||
|
||||
export const cleanupWriteMetadata = () =>
|
||||
request<{ written: number; errors: { project: string; error: string }[] }>(
|
||||
`${BASE}/projects/cleanup/write-metadata`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
|
||||
export const cleanupRenameStems = () =>
|
||||
request<{ renamed: number; errors: { project: string; file: string; error: string }[] }>(
|
||||
`${BASE}/projects/cleanup/rename-stems`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
|
||||
export const cleanupPurgeOrphaned = () =>
|
||||
request<{ purged: number }>(
|
||||
`${BASE}/projects/cleanup/purge-orphaned`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
|
||||
export const cleanupCleanLrcFiles = () =>
|
||||
request<{ files_modified: number; lines_removed: number; errors: { file: string; error: string }[] }>(
|
||||
`${BASE}/projects/cleanup/clean-lrc-files`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
|
||||
// ── System ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export const getGpuInfo = () =>
|
||||
request<{ cuda_available: boolean; cuda_ok: boolean; name: string | null; total_mb: number; free_mb: number }>(
|
||||
`${BASE}/system/gpu-info`
|
||||
)
|
||||
|
||||
export const resetGpu = () =>
|
||||
request<{ ok: boolean; cuda_available: boolean; cuda_ok: boolean }>(
|
||||
`${BASE}/system/gpu-reset`,
|
||||
{ method: 'POST' }
|
||||
)
|
||||
|
||||
// ── Settings ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AppSettings {
|
||||
hf_token_set: boolean
|
||||
whisper_model: string
|
||||
sep_power: string
|
||||
whisper_word_ts: boolean
|
||||
whisper_condition_prev: boolean
|
||||
whisper_phoneme_align: boolean
|
||||
auto_steps: unknown[]
|
||||
auto_model: string
|
||||
auto_format: string
|
||||
auto_presets: unknown[]
|
||||
}
|
||||
|
||||
export const getAppSettings = () =>
|
||||
request<AppSettings>(`${BASE}/settings`)
|
||||
|
||||
export const patchAppSettings = (patch: Partial<AppSettings & { hf_token: string }>) =>
|
||||
request<AppSettings>(`${BASE}/settings`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(patch),
|
||||
})
|
||||
|
||||
export const deleteHfToken = () =>
|
||||
request<{ hf_token_set: boolean }>(`${BASE}/settings/hf-token`, { method: 'DELETE' })
|
||||
File diff suppressed because it is too large.
Load diff
+387
@@ -0,0 +1,387 @@
|
||||
/**
|
||||
* AutoPipelineDialog
|
||||
*
|
||||
* Lean "confirm & run" modal. Pipeline options (model, format, steps) are
|
||||
* configured in Settings → Auto Pipeline. This dialog just shows a summary
|
||||
* of the stored settings, accepts a project name, and orchestrates execution.
|
||||
*/
|
||||
import { useState, useRef } from 'react'
|
||||
import { X, Zap, Loader2, CheckCircle2, XCircle, Music2, Mic2, AlignLeft, Settings, BookmarkPlus } from 'lucide-react'
|
||||
import {
|
||||
submitSeparate, submitSeparateFromPath,
|
||||
getJob, reprocessStem, transcribeProject, lyricTranscribeProject, lrcProject,
|
||||
} from '../api/client'
|
||||
import type { Job } from '../types'
|
||||
import {
|
||||
readAutoModel, readAutoFormat, readAutoSteps, stepLabel,
|
||||
} from '../utils/autoPipeline'
|
||||
import type { AutoStep } from '../utils/autoPipeline'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface AutoPipelineTarget {
|
||||
file?: File
|
||||
filePath?: string
|
||||
filename: string
|
||||
initialProjectName?: string
|
||||
}
|
||||
|
||||
interface Props {
|
||||
target: AutoPipelineTarget
|
||||
onClose: () => void
|
||||
/** Called when the full pipeline completes successfully. */
|
||||
onComplete?: (projectId: string, projectName: string) => void
|
||||
/** Called to navigate the user to Settings → Auto Pipeline tab. */
|
||||
onOpenSettings?: () => void
|
||||
}
|
||||
|
||||
type Phase = 'idle' | 'running' | 'done' | 'error'
|
||||
|
||||
interface StepStatus {
|
||||
label: string
|
||||
status: 'pending' | 'running' | 'done' | 'error'
|
||||
detail?: string
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Poll helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const MAX_RETRIES = 2
|
||||
|
||||
async function withRetry<T>(
|
||||
fn: () => Promise<T>,
|
||||
signal: AbortSignal | undefined,
|
||||
onRetry: (retryNum: number) => void,
|
||||
): Promise<T> {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
return await fn()
|
||||
} catch (e) {
|
||||
if (e instanceof Error && e.message === 'Cancelled') throw e
|
||||
if (signal?.aborted) throw new Error('Cancelled')
|
||||
if (attempt >= MAX_RETRIES) throw e
|
||||
onRetry(attempt + 1)
|
||||
await new Promise<void>((res, rej) => {
|
||||
const t = setTimeout(res, 3000)
|
||||
signal?.addEventListener('abort', () => { clearTimeout(t); rej(new Error('Cancelled')) })
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function pollUntilDone(jobId: string, signal?: AbortSignal): Promise<Job> {
|
||||
for (;;) {
|
||||
if (signal?.aborted) throw new Error('Cancelled')
|
||||
const job = await getJob(jobId)
|
||||
if (job.status === 'done') return job
|
||||
if (job.status === 'error') throw new Error(job.error || 'Job failed')
|
||||
if (job.status === 'cancelled') throw new Error('Job was cancelled')
|
||||
await new Promise<void>((res, rej) => {
|
||||
const t = setTimeout(res, 2500)
|
||||
signal?.addEventListener('abort', () => { clearTimeout(t); rej(new Error('Cancelled')) })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Step icon
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function StepIcon({ step }: { step: AutoStep }) {
|
||||
if (step.type === 'reprocess') return <Music2 className="w-3.5 h-3.5 text-purple-500" />
|
||||
if (step.type === 'midi') return <Mic2 className="w-3.5 h-3.5 text-emerald-500" />
|
||||
if (step.type === 'lyricsAlign') return <BookmarkPlus className="w-3.5 h-3.5 text-teal-500" />
|
||||
return <AlignLeft className="w-3.5 h-3.5 text-sky-500" />
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Component
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export default function AutoPipelineDialog({ target, onClose, onComplete, onOpenSettings }: Props) {
|
||||
const model = readAutoModel()
|
||||
const format = readAutoFormat()
|
||||
const steps = readAutoSteps()
|
||||
|
||||
const [projName, setProjName] = useState(
|
||||
target.initialProjectName ?? target.filename.replace(/\.[^/.]+$/, '')
|
||||
)
|
||||
const [phase, setPhase] = useState<Phase>('idle')
|
||||
const [stepStats, setStepStats] = useState<StepStatus[]>([])
|
||||
const [errMsg, setErrMsg] = useState<string | null>(null)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
|
||||
function patchStep(idx: number, patch: Partial<StepStatus>) {
|
||||
setStepStats(prev => prev.map((s, i) => i === idx ? { ...s, ...patch } : s))
|
||||
}
|
||||
|
||||
async function run() {
|
||||
setErrMsg(null)
|
||||
setPhase('running')
|
||||
const ctrl = new AbortController()
|
||||
abortRef.current = ctrl
|
||||
|
||||
// Build step labels upfront (separation is always first, then stored steps)
|
||||
const initialStats: StepStatus[] = [
|
||||
{ label: 'Stem separation', status: 'pending' },
|
||||
...steps.map(s => ({ label: stepLabel(s), status: 'pending' as const })),
|
||||
]
|
||||
setStepStats(initialStats)
|
||||
|
||||
let stepIdx = 0
|
||||
const retry = (n: number) => patchStep(stepIdx, { detail: `Retrying (${n}/${MAX_RETRIES})…` })
|
||||
|
||||
try {
|
||||
// ── Stage 0: Separation ────────────────────────────────────────────
|
||||
patchStep(stepIdx, { status: 'running' })
|
||||
|
||||
const sepPowerPreset = localStorage.getItem('stemengine-sep-power') ?? 'standard'
|
||||
const sepOpts = { presetType: 'stems_only', projectName: projName || undefined, sepPowerPreset }
|
||||
|
||||
const sepJob = await withRetry(async () => {
|
||||
patchStep(stepIdx, { detail: 'Submitting…' })
|
||||
const { job_id: sepJobId } = target.file
|
||||
? await submitSeparate(target.file, model, format, sepOpts)
|
||||
: await submitSeparateFromPath(target.filePath!, model, format, sepOpts)
|
||||
patchStep(stepIdx, { detail: 'Running…' })
|
||||
return pollUntilDone(sepJobId, ctrl.signal)
|
||||
}, ctrl.signal, retry)
|
||||
|
||||
const projectId = sepJob.result?.project_id
|
||||
const resolvedName = sepJob.result?.project_name ?? projName
|
||||
|
||||
patchStep(stepIdx, { status: 'done', detail: resolvedName })
|
||||
stepIdx++
|
||||
|
||||
// ── Configured steps ──────────────────────────────────────────────
|
||||
for (const step of steps) {
|
||||
patchStep(stepIdx, { status: 'running' })
|
||||
|
||||
if (step.type === 'reprocess' && projectId) {
|
||||
await withRetry(async () => {
|
||||
patchStep(stepIdx, { detail: `Reprocessing "${step.stem}"…` })
|
||||
const { job_id } = await reprocessStem(projectId, step.stem, step.model)
|
||||
await pollUntilDone(job_id, ctrl.signal)
|
||||
}, ctrl.signal, retry)
|
||||
patchStep(stepIdx, { status: 'done' })
|
||||
|
||||
} else if (step.type === 'midi' && projectId) {
|
||||
await withRetry(async () => {
|
||||
patchStep(stepIdx, { detail: 'Transcribing vocals to MIDI…' })
|
||||
const { job_id } = await transcribeProject(projectId, 'vocals', step.mode)
|
||||
await pollUntilDone(job_id, ctrl.signal)
|
||||
}, ctrl.signal, retry)
|
||||
patchStep(stepIdx, { status: 'done', detail: step.mode })
|
||||
|
||||
} else if (step.type === 'lyrics' && projectId) {
|
||||
const wordTs = localStorage.getItem('stemengine-whisper-word-ts') !== 'false'
|
||||
await withRetry(async () => {
|
||||
patchStep(stepIdx, { detail: `WhisperX ${step.whisperModel}…` })
|
||||
const { job_id: transcribeJobId } = await lyricTranscribeProject(projectId, 'vocals', {
|
||||
model: step.whisperModel,
|
||||
wordTimestamps: wordTs,
|
||||
diarize: step.diarize,
|
||||
lsyncAlign: step.lsyncAlign ?? false,
|
||||
twoPass: step.twoPass ?? false,
|
||||
vocalStyle: step.vocalStyle ?? 'general',
|
||||
explicit: step.explicit ?? false,
|
||||
})
|
||||
await pollUntilDone(transcribeJobId, ctrl.signal)
|
||||
}, ctrl.signal, retry)
|
||||
patchStep(stepIdx, { status: 'done', detail: step.whisperModel })
|
||||
|
||||
} else if (step.type === 'lyricsAlign' && projectId) {
|
||||
await withRetry(async () => {
|
||||
patchStep(stepIdx, { detail: `${step.timingPrecision}-level alignment…` })
|
||||
const { job_id: alignJobId } = await lrcProject(projectId, 'vocals', {
|
||||
lyricsSource: 'auto',
|
||||
timingPrecision: step.timingPrecision,
|
||||
lrcPowerPreset: localStorage.getItem('stemengine-sep-power') ?? 'standard',
|
||||
})
|
||||
await pollUntilDone(alignJobId, ctrl.signal)
|
||||
}, ctrl.signal, retry)
|
||||
patchStep(stepIdx, { status: 'done', detail: step.timingPrecision })
|
||||
}
|
||||
|
||||
stepIdx++
|
||||
}
|
||||
|
||||
setPhase('done')
|
||||
if (projectId) onComplete?.(projectId, resolvedName)
|
||||
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e)
|
||||
if (msg === 'Cancelled') { setPhase('idle'); setStepStats([]); return }
|
||||
setErrMsg(msg)
|
||||
setStepStats(prev => prev.map((s, i) => i === stepIdx ? { ...s, status: 'error', detail: msg } : s))
|
||||
setPhase('error')
|
||||
}
|
||||
}
|
||||
|
||||
function cancel() { abortRef.current?.abort() }
|
||||
|
||||
const running = phase === 'running'
|
||||
const finished = phase === 'done' || phase === 'error'
|
||||
const canRun = !!(target.file || target.filePath)
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 right-4 z-50 w-96 rounded-2xl bg-white dark:bg-gray-900 border border-slate-200 dark:border-gray-700 shadow-2xl flex flex-col max-h-[85vh]">
|
||||
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3 px-5 py-4 border-b border-slate-200 dark:border-gray-800 shrink-0">
|
||||
<Zap className="w-5 h-5 text-amber-500 shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<h2 className="text-sm font-bold text-slate-900 dark:text-white">Auto Pipeline</h2>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-400 truncate">{target.filename}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={running ? cancel : onClose}
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 dark:hover:text-gray-200 transition-colors"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="flex-1 overflow-y-auto p-5 space-y-4">
|
||||
|
||||
{/* Project name */}
|
||||
{!running && !finished && (
|
||||
<label className="space-y-1 block">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Project Name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={projName}
|
||||
onChange={e => setProjName(e.target.value)}
|
||||
placeholder="Artist - Title"
|
||||
className="w-full rounded-lg bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-3 py-2 text-sm text-slate-900 dark:text-gray-100 focus:border-brand-500 focus:outline-none"
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{/* Pipeline summary (shown before run) */}
|
||||
{!running && !finished && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Pipeline ({1 + steps.length} step{steps.length !== 0 ? 's' : ''})
|
||||
</span>
|
||||
{onOpenSettings && (
|
||||
<button
|
||||
onClick={onOpenSettings}
|
||||
className="flex items-center gap-1 text-xs text-brand-500 hover:text-brand-600 dark:text-brand-400 transition-colors"
|
||||
>
|
||||
<Settings className="w-3 h-3" />
|
||||
Edit in Settings
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Separation step */}
|
||||
<div className="flex items-center gap-2.5 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/50 border border-slate-200 dark:border-gray-700">
|
||||
<Music2 className="w-3.5 h-3.5 text-brand-500 shrink-0" />
|
||||
<span className="text-sm text-slate-700 dark:text-gray-200 flex-1">Stem Separation</span>
|
||||
<span className="text-xs text-slate-400 dark:text-gray-500 truncate max-w-32">
|
||||
{model} · {format}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{steps.length === 0 && (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-500 italic px-1">
|
||||
No extra steps configured.{' '}
|
||||
{onOpenSettings && (
|
||||
<button onClick={onOpenSettings} className="text-brand-500 hover:underline">
|
||||
Add steps in Settings →
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{steps.map((step, i) => (
|
||||
<div key={i} className="flex items-center gap-2.5 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/50 border border-slate-200 dark:border-gray-700">
|
||||
<StepIcon step={step} />
|
||||
<span className="text-sm text-slate-700 dark:text-gray-200 flex-1 truncate">
|
||||
{stepLabel(step)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Live progress */}
|
||||
{stepStats.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<span className="text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Progress
|
||||
</span>
|
||||
{stepStats.map((s, i) => (
|
||||
<div key={i} className="flex items-start gap-3">
|
||||
<div className="mt-0.5 shrink-0">
|
||||
{s.status === 'running' && <Loader2 className="w-4 h-4 text-brand-500 animate-spin" />}
|
||||
{s.status === 'done' && <CheckCircle2 className="w-4 h-4 text-emerald-500" />}
|
||||
{s.status === 'error' && <XCircle className="w-4 h-4 text-red-500" />}
|
||||
{s.status === 'pending' && <div className="w-4 h-4 rounded-full border-2 border-slate-300 dark:border-gray-600" />}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className={`text-sm font-medium ${
|
||||
s.status === 'running' ? 'text-brand-600 dark:text-brand-400'
|
||||
: s.status === 'done' ? 'text-emerald-700 dark:text-emerald-300'
|
||||
: s.status === 'error' ? 'text-red-600 dark:text-red-400'
|
||||
: 'text-slate-500 dark:text-gray-500'
|
||||
}`}>{s.label}</p>
|
||||
{s.detail && <p className="text-xs text-slate-400 dark:text-gray-500 truncate">{s.detail}</p>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{errMsg && (
|
||||
<div className="rounded-lg bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-800 px-4 py-3 text-sm text-red-700 dark:text-red-300">
|
||||
{errMsg}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === 'done' && (
|
||||
<div className="rounded-lg bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-800 px-4 py-3 text-sm text-emerald-700 dark:text-emerald-300 font-medium">
|
||||
Pipeline complete!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="px-5 py-4 border-t border-slate-200 dark:border-gray-800 shrink-0 flex gap-3">
|
||||
{!finished && (
|
||||
<>
|
||||
<button
|
||||
onClick={running ? cancel : onClose}
|
||||
className="flex-1 rounded-lg border border-slate-300 dark:border-gray-600 px-4 py-2.5 text-sm font-medium text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-gray-800 transition-colors"
|
||||
>
|
||||
{running ? 'Cancel' : 'Dismiss'}
|
||||
</button>
|
||||
<button
|
||||
onClick={run}
|
||||
disabled={running || !canRun}
|
||||
className="flex-1 rounded-lg bg-amber-500 hover:bg-amber-400 disabled:bg-slate-200 disabled:text-slate-400 dark:disabled:bg-gray-800 dark:disabled:text-gray-500 px-4 py-2.5 text-sm font-bold text-white disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
{running
|
||||
? <><Loader2 className="w-4 h-4 animate-spin" />Running…</>
|
||||
: <><Zap className="w-4 h-4" />Run Pipeline</>}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{finished && (
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="flex-1 rounded-lg bg-brand-600 hover:bg-brand-500 px-4 py-2.5 text-sm font-bold text-white transition-colors"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
import { useRef, useEffect, useState, useCallback } from 'react'
|
||||
import { Volume2, VolumeX } from 'lucide-react'
|
||||
import { registerPlayback, unregisterPlayback, publishMeta, clearMeta } from '../utils/audioRegistry'
|
||||
|
||||
interface Stem {
|
||||
name: string
|
||||
label: string
|
||||
url: string
|
||||
}
|
||||
|
||||
interface Props {
|
||||
stems: Stem[]
|
||||
title?: string
|
||||
onLevelChange?: (name: string, value: number) => void
|
||||
}
|
||||
|
||||
export default function DynamicMixPlayer({ stems, title, onLevelChange }: Props) {
|
||||
const audioRefs = useRef<Record<string, HTMLAudioElement>>({})
|
||||
const gainRefs = useRef<Record<string, GainNode>>({})
|
||||
const audioCtxRef = useRef<AudioContext | null>(null)
|
||||
|
||||
const [isPlaying, setIsPlaying] = useState(false)
|
||||
const [currentTime, setCurrentTime] = useState(0)
|
||||
const [duration, setDuration] = useState(0)
|
||||
const [loaded, setLoaded] = useState<Record<string, boolean>>({})
|
||||
|
||||
const [gains, setGains] = useState<Record<string, number>>(() =>
|
||||
stems.reduce((acc, s) => ({ ...acc, [s.name]: 1.0 }), {})
|
||||
)
|
||||
const [masterVolume, setMasterVolume] = useState(1)
|
||||
const [isMuted, setIsMuted] = useState(false)
|
||||
const [preMuteVolume, setPreMuteVolume] = useState(1)
|
||||
const [mutedStems, setMutedStems] = useState<Record<string, boolean>>({})
|
||||
const [soloedStems, setSoloedStems] = useState<Record<string, boolean>>({})
|
||||
|
||||
// Whether this player is "owning" the global floating bar
|
||||
const isActiveRef = useRef(false)
|
||||
|
||||
// Stable stop callback for the global audio registry
|
||||
const stopPlayback = useCallback(() => {
|
||||
isActiveRef.current = false
|
||||
Object.values(audioRefs.current).forEach(a => a.pause())
|
||||
setIsPlaying(false)
|
||||
clearMeta()
|
||||
}, [])
|
||||
|
||||
// Stop audio + unregister when unmounted.
|
||||
// unregisterPlayback alone only removes the _current reference — it does NOT
|
||||
// pause the audio elements, so they keep playing after navigation.
|
||||
useEffect(() => () => {
|
||||
stopPlayback()
|
||||
unregisterPlayback(stopPlayback)
|
||||
}, [stopPlayback])
|
||||
|
||||
// Lazily create the shared AudioContext on first interaction (browser autoplay policy)
|
||||
function getCtx(): AudioContext {
|
||||
if (!audioCtxRef.current) {
|
||||
audioCtxRef.current = new AudioContext()
|
||||
}
|
||||
return audioCtxRef.current
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const ctx = getCtx()
|
||||
|
||||
stems.forEach((stem) => {
|
||||
if (audioRefs.current[stem.name]) return // already wired up
|
||||
|
||||
const audio = new Audio(stem.url)
|
||||
audio.preload = 'metadata'
|
||||
audio.crossOrigin = 'anonymous'
|
||||
|
||||
audio.addEventListener('loadedmetadata', () => {
|
||||
setDuration((d) => Math.max(d, audio.duration || 0))
|
||||
setLoaded((l) => ({ ...l, [stem.name]: true }))
|
||||
})
|
||||
audio.addEventListener('error', () => {
|
||||
setLoaded((l) => ({ ...l, [stem.name]: false }))
|
||||
})
|
||||
|
||||
// Route through Web Audio — all MediaElementSourceNodes in the same
|
||||
// AudioContext share one clock, eliminating independent-element drift.
|
||||
const source = ctx.createMediaElementSource(audio)
|
||||
const gain = ctx.createGain()
|
||||
source.connect(gain)
|
||||
gain.connect(ctx.destination)
|
||||
|
||||
audioRefs.current[stem.name] = audio
|
||||
gainRefs.current[stem.name] = gain
|
||||
})
|
||||
|
||||
// RAF loop — read playback position from the first element
|
||||
let raf: number
|
||||
function tick() {
|
||||
const first = Object.values(audioRefs.current)[0]
|
||||
if (first) setCurrentTime(first.currentTime)
|
||||
raf = requestAnimationFrame(tick)
|
||||
}
|
||||
raf = requestAnimationFrame(tick)
|
||||
|
||||
return () => cancelAnimationFrame(raf)
|
||||
}, [stems])
|
||||
|
||||
const togglePlay = useCallback(async () => {
|
||||
const ctx = getCtx()
|
||||
const audios = Object.values(audioRefs.current)
|
||||
|
||||
if (isPlaying) {
|
||||
audios.forEach((a) => a.pause())
|
||||
// Don't unregister — keep bar visible showing paused state.
|
||||
// A new player registering will call stopPlayback(), which clears.
|
||||
setIsPlaying(false)
|
||||
} else {
|
||||
registerPlayback(stopPlayback)
|
||||
isActiveRef.current = true
|
||||
// Publish immediately so the bar appears at once — don't wait for the
|
||||
// next RAF tick or effect cycle (there is a window between clearMeta()
|
||||
// from the old player and the effect re-running for this player).
|
||||
publishMeta(
|
||||
{ title: title ?? 'Dynamic Mix', isPlaying: true, currentTime, duration, volume: isMuted ? 0 : masterVolume },
|
||||
{ toggle: () => togglePlayRef.current(), seek: handleSeek, setVolume: (v) => updateMasterVolumeRef.current(v) }
|
||||
)
|
||||
// Suspend the audio clock, seek & start all elements, then resume —
|
||||
// guarantees all stems begin from the same audio frame simultaneously.
|
||||
await ctx.suspend()
|
||||
audios.forEach((a) => {
|
||||
a.currentTime = currentTime
|
||||
a.play().catch(() => {})
|
||||
})
|
||||
await ctx.resume()
|
||||
setIsPlaying(true)
|
||||
}
|
||||
}, [isPlaying, currentTime, duration, title, masterVolume, isMuted, stopPlayback])
|
||||
|
||||
function handleSeek(t: number) {
|
||||
setCurrentTime(t)
|
||||
Object.values(audioRefs.current).forEach((a) => {
|
||||
a.currentTime = t
|
||||
})
|
||||
}
|
||||
|
||||
// Keep a ref to togglePlay so the bar always calls the latest version
|
||||
const togglePlayRef = useRef(togglePlay)
|
||||
useEffect(() => { togglePlayRef.current = togglePlay }, [togglePlay])
|
||||
|
||||
// Keep a ref to updateMasterVolume so the bar's setVolume always uses fresh state
|
||||
const updateMasterVolumeRef = useRef(updateMasterVolume)
|
||||
updateMasterVolumeRef.current = updateMasterVolume
|
||||
|
||||
// Publish state to the global floating bar whenever anything relevant changes
|
||||
useEffect(() => {
|
||||
if (!isActiveRef.current) return
|
||||
publishMeta(
|
||||
{ title: title ?? 'Dynamic Mix', isPlaying, currentTime, duration, volume: isMuted ? 0 : masterVolume },
|
||||
{ toggle: () => togglePlayRef.current(), seek: handleSeek, setVolume: (v) => updateMasterVolumeRef.current(v) }
|
||||
)
|
||||
// handleSeek is recreated each render but is stateless; refs stay fresh
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isPlaying, currentTime, duration, title, masterVolume, isMuted])
|
||||
|
||||
// Apply GainNode values based on current mute/solo/master state
|
||||
function applyGains(overrides: {
|
||||
name?: string
|
||||
gain?: number
|
||||
master?: number
|
||||
muted?: boolean
|
||||
mutedStems?: Record<string, boolean>
|
||||
soloedStems?: Record<string, boolean>
|
||||
} = {}) {
|
||||
const resolvedMaster = overrides.master ?? masterVolume
|
||||
const resolvedMuted = overrides.muted ?? isMuted
|
||||
const resolvedMutes = overrides.mutedStems ?? mutedStems
|
||||
const resolvedSolos = overrides.soloedStems ?? soloedStems
|
||||
const anySolo = Object.values(resolvedSolos).some(Boolean)
|
||||
|
||||
Object.entries(gainRefs.current).forEach(([n, gn]) => {
|
||||
const stemGain = overrides.name === n ? (overrides.gain ?? gains[n] ?? 1) : (gains[n] ?? 1)
|
||||
const stemMuted = resolvedMutes[n] ?? false
|
||||
const stemSoloed = resolvedSolos[n] ?? false
|
||||
const effective = (resolvedMuted || stemMuted || (anySolo && !stemSoloed))
|
||||
? 0
|
||||
: Math.min(2, resolvedMaster * stemGain)
|
||||
gn.gain.value = effective
|
||||
})
|
||||
}
|
||||
|
||||
function updateGain(name: string, value: number) {
|
||||
setGains((g) => ({ ...g, [name]: value }))
|
||||
applyGains({ name, gain: value })
|
||||
onLevelChange?.(name, value)
|
||||
}
|
||||
|
||||
function updateMasterVolume(value: number) {
|
||||
setMasterVolume(value)
|
||||
setIsMuted(false)
|
||||
applyGains({ master: value, muted: false })
|
||||
}
|
||||
|
||||
function toggleMute() {
|
||||
if (isMuted) {
|
||||
setIsMuted(false)
|
||||
setMasterVolume(preMuteVolume)
|
||||
applyGains({ master: preMuteVolume, muted: false })
|
||||
} else {
|
||||
setPreMuteVolume(masterVolume)
|
||||
setIsMuted(true)
|
||||
applyGains({ muted: true })
|
||||
}
|
||||
}
|
||||
|
||||
function toggleStemMute(name: string) {
|
||||
setMutedStems((m) => {
|
||||
const next = { ...m, [name]: !(m[name] ?? false) }
|
||||
applyGains({ mutedStems: next })
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
function toggleStemSolo(name: string) {
|
||||
setSoloedStems((s) => {
|
||||
const next = { ...s, [name]: !(s[name] ?? false) }
|
||||
applyGains({ soloedStems: next })
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const allLoaded = stems.every((s) => loaded[s.name] !== false)
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Playback controls */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
onClick={togglePlay}
|
||||
disabled={!allLoaded}
|
||||
className="flex items-center justify-center w-9 h-9 rounded-full bg-brand-500 text-white hover:bg-brand-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shrink-0"
|
||||
>
|
||||
{isPlaying ? (
|
||||
<svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
|
||||
<rect x="6" y="4" width="4" height="16" />
|
||||
<rect x="14" y="4" width="4" height="16" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={duration || 1}
|
||||
step={0.1}
|
||||
value={currentTime}
|
||||
onChange={(e) => handleSeek(parseFloat(e.target.value))}
|
||||
className="flex-1 min-w-[80px] h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
/>
|
||||
<span className="text-xs tabular-nums text-slate-500 dark:text-gray-400 shrink-0">
|
||||
{formatTime(currentTime)} / {formatTime(duration)}
|
||||
</span>
|
||||
|
||||
{/* Master volume */}
|
||||
<div className="flex items-center gap-1.5 pl-2 border-l border-slate-200 dark:border-gray-700 shrink-0">
|
||||
<button
|
||||
onClick={toggleMute}
|
||||
className="p-1.5 rounded-md text-slate-500 dark:text-gray-400 hover:text-slate-700 dark:hover:text-gray-200 hover:bg-slate-100 dark:hover:bg-gray-800 transition-colors"
|
||||
title={isMuted ? 'Unmute' : 'Mute'}
|
||||
>
|
||||
{isMuted || masterVolume === 0 ? (
|
||||
<VolumeX className="w-4 h-4" />
|
||||
) : (
|
||||
<Volume2 className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={isMuted ? 0 : masterVolume}
|
||||
onChange={(e) => updateMasterVolume(parseFloat(e.target.value))}
|
||||
className="w-16 sm:w-20 h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
title="Master Volume"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stem level sliders */}
|
||||
<div className="space-y-2 pt-2 border-t border-slate-200 dark:border-gray-700">
|
||||
{stems.map((stem) => (
|
||||
<div key={stem.name} className="flex items-center gap-1.5">
|
||||
<span className="text-xs font-medium text-slate-600 dark:text-gray-400 w-12 sm:w-16 truncate capitalize">
|
||||
{stem.label}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => toggleStemMute(stem.name)}
|
||||
title={mutedStems[stem.name] ? 'Unmute' : 'Mute'}
|
||||
className={`w-6 h-6 text-xs font-bold rounded transition-colors flex-shrink-0 ${
|
||||
mutedStems[stem.name]
|
||||
? 'bg-red-500 text-white'
|
||||
: 'bg-slate-200 dark:bg-gray-700 text-slate-600 dark:text-gray-400 hover:bg-slate-300 dark:hover:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
M
|
||||
</button>
|
||||
<button
|
||||
onClick={() => toggleStemSolo(stem.name)}
|
||||
title={soloedStems[stem.name] ? 'Unsolo' : 'Solo'}
|
||||
className={`w-6 h-6 text-xs font-bold rounded transition-colors flex-shrink-0 ${
|
||||
soloedStems[stem.name]
|
||||
? 'bg-yellow-400 text-black'
|
||||
: 'bg-slate-200 dark:bg-gray-700 text-slate-600 dark:text-gray-400 hover:bg-slate-300 dark:hover:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
S
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={2}
|
||||
step={0.1}
|
||||
value={gains[stem.name] ?? 1.0}
|
||||
onChange={(e) => updateGain(stem.name, parseFloat(e.target.value))}
|
||||
className="flex-1 h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
/>
|
||||
<span className="text-xs tabular-nums text-slate-500 dark:text-gray-400 w-9 text-right">
|
||||
{Math.round((gains[stem.name] ?? 1.0) * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function formatTime(s: number): string {
|
||||
const m = Math.floor(s / 60)
|
||||
const sec = Math.floor(s % 60)
|
||||
return `${m}:${sec.toString().padStart(2, '0')}`
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import React, { useCallback } from 'react'
|
||||
import { Upload } from 'lucide-react'
|
||||
|
||||
interface Props {
|
||||
label?: string
|
||||
accept?: string
|
||||
onFiles: (files: File[]) => void
|
||||
}
|
||||
|
||||
export default function FileUpload({ label = 'Drop files here', accept, onFiles }: Props) {
|
||||
const handleDrop = useCallback(
|
||||
(e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
const files = Array.from(e.dataTransfer.files)
|
||||
if (files.length) onFiles(files)
|
||||
},
|
||||
[onFiles]
|
||||
)
|
||||
|
||||
const handleChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files || [])
|
||||
if (files.length) onFiles(files)
|
||||
e.target.value = '' // reset for re-upload
|
||||
},
|
||||
[onFiles]
|
||||
)
|
||||
|
||||
return (
|
||||
<label
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={handleDrop}
|
||||
className="flex flex-col items-center justify-center gap-3 px-6 py-10 rounded-xl border-2 border-dashed border-slate-300 dark:border-gray-700 bg-slate-50 dark:bg-gray-900/50 hover:border-brand-400 dark:hover:border-brand-500 hover:bg-slate-100 dark:hover:bg-gray-800/50 transition-colors cursor-pointer"
|
||||
>
|
||||
<Upload className="w-8 h-8 text-slate-400 dark:text-gray-600" />
|
||||
<span className="text-sm text-slate-600 dark:text-gray-400 text-center">{label}</span>
|
||||
<input type="file" accept={accept} onChange={handleChange} className="hidden" />
|
||||
</label>
|
||||
)
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { Volume2, VolumeX, X } from 'lucide-react'
|
||||
import { getMeta, getActions, subscribePlayback, stopCurrent } from '../utils/audioRegistry'
|
||||
import type { PlaybackMeta } from '../utils/audioRegistry'
|
||||
|
||||
function fmtTime(s: number): string {
|
||||
const m = Math.floor(s / 60)
|
||||
return `${m}:${Math.floor(s % 60).toString().padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export default function GlobalAudioBar() {
|
||||
const [meta, setMeta] = useState<PlaybackMeta | null>(() => getMeta())
|
||||
const prevVolumeRef = useRef(1)
|
||||
|
||||
useEffect(() => subscribePlayback(() => setMeta(getMeta())), [])
|
||||
|
||||
if (!meta) return null
|
||||
|
||||
const { title, isPlaying, currentTime, duration, volume } = meta
|
||||
|
||||
function handleMuteToggle() {
|
||||
if (volume === 0) {
|
||||
getActions().setVolume(prevVolumeRef.current || 1)
|
||||
} else {
|
||||
prevVolumeRef.current = volume
|
||||
getActions().setVolume(0)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-0 left-0 right-0 z-50 border-t border-slate-200 dark:border-gray-800 bg-white/95 dark:bg-gray-950/95 backdrop-blur-sm shadow-[0_-2px_8px_rgba(0,0,0,0.06)] dark:shadow-[0_-2px_8px_rgba(0,0,0,0.4)]">
|
||||
<div className="max-w-3xl mx-auto px-4 h-12 flex items-center gap-3">
|
||||
|
||||
{/* Play / Pause */}
|
||||
<button
|
||||
onClick={() => getActions().toggle()}
|
||||
className="flex items-center justify-center w-7 h-7 rounded-full bg-brand-500 text-white hover:bg-brand-600 transition-colors shrink-0"
|
||||
title={isPlaying ? 'Pause' : 'Play'}
|
||||
>
|
||||
{isPlaying ? (
|
||||
<svg className="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
|
||||
<rect x="6" y="4" width="4" height="16" />
|
||||
<rect x="14" y="4" width="4" height="16" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Current time */}
|
||||
<span className="text-xs tabular-nums text-slate-400 dark:text-gray-500 shrink-0 w-8 text-right">
|
||||
{fmtTime(currentTime)}
|
||||
</span>
|
||||
|
||||
{/* Seek slider */}
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={duration || 1}
|
||||
step={0.1}
|
||||
value={currentTime}
|
||||
onChange={e => getActions().seek(parseFloat(e.target.value))}
|
||||
className="flex-1 h-1.5 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500 min-w-0"
|
||||
/>
|
||||
|
||||
{/* Duration */}
|
||||
<span className="text-xs tabular-nums text-slate-400 dark:text-gray-500 shrink-0 w-8">
|
||||
{fmtTime(duration)}
|
||||
</span>
|
||||
|
||||
{/* Title */}
|
||||
<span
|
||||
className="text-xs font-medium text-slate-500 dark:text-gray-500 truncate shrink min-w-0 max-w-[120px] sm:max-w-[180px]"
|
||||
title={title}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
|
||||
{/* Volume */}
|
||||
<div className="flex items-center gap-1 shrink-0 pl-2 border-l border-slate-200 dark:border-gray-700">
|
||||
<button
|
||||
onClick={handleMuteToggle}
|
||||
className="p-1 rounded text-slate-400 dark:text-gray-500 hover:text-slate-600 dark:hover:text-gray-300 transition-colors"
|
||||
title={volume === 0 ? 'Unmute' : 'Mute'}
|
||||
>
|
||||
{volume === 0 ? <VolumeX className="w-3.5 h-3.5" /> : <Volume2 className="w-3.5 h-3.5" />}
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.05}
|
||||
value={volume}
|
||||
onChange={e => getActions().setVolume(parseFloat(e.target.value))}
|
||||
className="w-14 h-1.5 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
title="Volume"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Dismiss */}
|
||||
<button
|
||||
onClick={stopCurrent}
|
||||
className="p-1 rounded text-slate-400 dark:text-gray-500 hover:text-slate-600 dark:hover:text-gray-300 transition-colors shrink-0 ml-1"
|
||||
title="Stop and close"
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Loader2, CheckCircle, XCircle, AlertCircle } from 'lucide-react'
|
||||
import { getJob } from '../api/client'
|
||||
import type { Job } from '../types'
|
||||
|
||||
interface Props {
|
||||
jobId: string
|
||||
onDone?: (job: Job) => void
|
||||
}
|
||||
|
||||
export default function JobStatus({ jobId, onDone }: Props) {
|
||||
const [job, setJob] = useState<Job | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
let timeout: ReturnType<typeof setTimeout>
|
||||
|
||||
async function poll() {
|
||||
try {
|
||||
const j = await getJob(jobId)
|
||||
if (cancelled) return
|
||||
setJob(j)
|
||||
setError(null)
|
||||
|
||||
if (j.status === 'done' || j.status === 'error' || j.status === 'cancelled') {
|
||||
if (j.status === 'done') onDone?.(j)
|
||||
return
|
||||
}
|
||||
|
||||
timeout = setTimeout(poll, 2000)
|
||||
} catch (e) {
|
||||
if (cancelled) return
|
||||
setError(String(e))
|
||||
timeout = setTimeout(poll, 5000)
|
||||
}
|
||||
}
|
||||
|
||||
poll()
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}, [jobId, onDone])
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-xs text-red-500">
|
||||
<XCircle className="w-4 h-4" />
|
||||
Error: {error}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!job) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-xs text-slate-500">
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Loading…
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const statusConfig: Record<string, { icon: React.ReactNode; text: string; color: string }> = {
|
||||
queued: { icon: <Loader2 className="w-4 h-4 animate-spin text-amber-500" />, text: 'Queued…', color: 'text-amber-600' },
|
||||
running: { icon: <Loader2 className="w-4 h-4 animate-spin text-brand-500" />, text: job.progress || 'Running…', color: 'text-brand-600' },
|
||||
done: { icon: <CheckCircle className="w-4 h-4 text-emerald-500" />, text: 'Complete', color: 'text-emerald-600' },
|
||||
error: { icon: <XCircle className="w-4 h-4 text-red-500" />, text: `Error: ${job.error || 'Failed'}`, color: 'text-red-600' },
|
||||
cancelled: { icon: <AlertCircle className="w-4 h-4 text-slate-400" />, text: 'Cancelled', color: 'text-slate-500' },
|
||||
}
|
||||
|
||||
const config = statusConfig[job.status]
|
||||
|
||||
return (
|
||||
<div className={`flex items-center gap-2 text-xs ${config.color}`}>
|
||||
{config.icon}
|
||||
<span className="truncate">{config.text}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,841 @@
|
||||
/**
|
||||
* KaraokeEditor — Aegisub-style lyrics timing editor.
|
||||
*
|
||||
* Phase 1: Waveform canvas with click-to-seek and real-time playhead.
|
||||
* Phase 2: Timing table with active-row highlight + scroll.
|
||||
* Phase 3: Inline start-time and text editing with LRC reconstruction.
|
||||
* Phase 4: Waveform zoom + horizontal scroll, line markers, arrow-key navigation.
|
||||
*/
|
||||
import { useState, useEffect, useRef, Fragment } from 'react'
|
||||
import type { MutableRefObject, MouseEvent as ReactMouseEvent, KeyboardEvent as ReactKeyboardEvent, ChangeEvent as ReactChangeEvent } from 'react'
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface LrcWordKE {
|
||||
time: number
|
||||
text: string
|
||||
isWordEnd: boolean
|
||||
}
|
||||
|
||||
export interface LrcLineKE {
|
||||
time: number
|
||||
text: string
|
||||
words: LrcWordKE[]
|
||||
speaker?: string
|
||||
}
|
||||
|
||||
export interface KaraokeEditorProps {
|
||||
lines: LrcLineKE[]
|
||||
currentTimeRef: MutableRefObject<number>
|
||||
duration: number
|
||||
/** Single-track audio URL. May be undefined in multi-stem mode. */
|
||||
audioUrl: string | undefined
|
||||
onSeek: (t: number) => void
|
||||
/** Called whenever the user commits an inline edit — passes the full reconstructed LRC string. */
|
||||
onLrcChange?: (newLrc: string) => void
|
||||
}
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
const BUCKET_COUNT = 1200
|
||||
const CANVAS_HEIGHT = 80 // CSS px
|
||||
const TABLE_HEIGHT = 200 // CSS px
|
||||
const MAX_ZOOM = 32
|
||||
|
||||
const PLAYED_COLOR = '#60a5fa' // blue-400
|
||||
const UNPLAYED_COLOR = '#1e3a5f' // dark blue-tinted bar
|
||||
const UNPLAYED_BG = '#0f172a' // slate-900 background
|
||||
const PLAYHEAD_COLOR = '#f1f5f9' // slate-100
|
||||
const MARKER_COLOR = 'rgba(100,116,139,0.55)' // slate-500/55
|
||||
const MARKER_ACTIVE_COLOR = 'rgba(96,165,250,0.9)' // blue-400/90
|
||||
const WORD_MARKER_COLOR = 'rgba(251,191,36,0.7)' // amber-400
|
||||
const WORD_MARKER_DRAG_COLOR = '#fbbf24' // amber-400 bright
|
||||
const WORD_MARKER_HIT_PX = 8 // ±px hit zone for drag
|
||||
|
||||
const ROW_ACTIVE_BG = 'rgba(96, 165, 250, 0.15)'
|
||||
const ROW_ACTIVE_FG = '#e2e8f0' // slate-200
|
||||
const ROW_DIM_FG = '#475569' // slate-600
|
||||
const ROW_NUM_FG = '#334155' // slate-700
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function downsample(channelData: Float32Array, buckets: number): Float32Array {
|
||||
const peaks = new Float32Array(buckets)
|
||||
const chunkSize = Math.ceil(channelData.length / buckets)
|
||||
for (let i = 0; i < buckets; i++) {
|
||||
let peak = 0
|
||||
const start = i * chunkSize
|
||||
const end = Math.min(start + chunkSize, channelData.length)
|
||||
for (let j = start; j < end; j++) {
|
||||
const abs = Math.abs(channelData[j])
|
||||
if (abs > peak) peak = abs
|
||||
}
|
||||
peaks[i] = peak
|
||||
}
|
||||
return peaks
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw one frame of the waveform canvas.
|
||||
* Accounts for zoom and scrollFrac; draws line-start markers and the playhead.
|
||||
*/
|
||||
function drawFrame(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
peaks: Float32Array | null,
|
||||
lines: LrcLineKE[],
|
||||
w: number,
|
||||
h: number,
|
||||
fraction: number, // 0–1 playback progress
|
||||
zoom: number,
|
||||
scrollFrac: number, // 0..(1−1/zoom)
|
||||
duration: number,
|
||||
activeLineIdx: number,
|
||||
wordLine?: LrcLineKE | null,
|
||||
dragPreview?: { wordIdx: number; time: number } | null,
|
||||
) {
|
||||
ctx.clearRect(0, 0, w, h)
|
||||
|
||||
const totalBuckets = BUCKET_COUNT
|
||||
const visibleBuckets = totalBuckets / zoom
|
||||
const startBucket = Math.min(scrollFrac * totalBuckets, totalBuckets - visibleBuckets)
|
||||
|
||||
// Playhead x in canvas pixels
|
||||
const playBucket = fraction * totalBuckets
|
||||
const cutoffX = ((playBucket - startBucket) / visibleBuckets) * w
|
||||
|
||||
// ── Bars ──
|
||||
if (peaks) {
|
||||
const barW = w / visibleBuckets
|
||||
const mid = h / 2
|
||||
for (let i = 0; i < Math.ceil(visibleBuckets); i++) {
|
||||
const bucket = Math.floor(startBucket) + i
|
||||
if (bucket >= totalBuckets) break
|
||||
const x = i * barW
|
||||
const barH = Math.max(1, peaks[bucket] * h * 0.9)
|
||||
ctx.fillStyle = x < cutoffX ? PLAYED_COLOR : UNPLAYED_COLOR
|
||||
ctx.fillRect(x, mid - barH / 2, Math.max(1, barW - 0.5), barH)
|
||||
}
|
||||
} else {
|
||||
ctx.fillStyle = UNPLAYED_COLOR
|
||||
ctx.fillRect(0, h / 2 - 1, w, 2)
|
||||
}
|
||||
|
||||
// ── Line-start markers (ticks at the top of the canvas) ──
|
||||
const dur = Math.max(duration, 0.001)
|
||||
for (let li = 0; li < lines.length; li++) {
|
||||
const lineBucket = (lines[li].time / dur) * totalBuckets
|
||||
if (lineBucket < startBucket - 1 || lineBucket > startBucket + visibleBuckets + 1) continue
|
||||
const x = Math.round(((lineBucket - startBucket) / visibleBuckets) * w)
|
||||
const isAct = li === activeLineIdx
|
||||
ctx.fillStyle = isAct ? MARKER_ACTIVE_COLOR : MARKER_COLOR
|
||||
ctx.fillRect(x, 0, 1, isAct ? 10 : 5)
|
||||
}
|
||||
|
||||
// ── Word-start markers (amber ticks for the expanded line) ──
|
||||
if (wordLine) {
|
||||
for (let wi = 0; wi < wordLine.words.length; wi++) {
|
||||
const t = (dragPreview?.wordIdx === wi ? dragPreview.time : wordLine.words[wi].time)
|
||||
const bucket = (t / dur) * totalBuckets
|
||||
if (bucket < startBucket - 1 || bucket > startBucket + visibleBuckets + 1) continue
|
||||
const x = Math.round(((bucket - startBucket) / visibleBuckets) * w)
|
||||
ctx.fillStyle = dragPreview?.wordIdx === wi ? WORD_MARKER_DRAG_COLOR : WORD_MARKER_COLOR
|
||||
ctx.fillRect(x, 0, 2, 14)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Playhead ──
|
||||
if (cutoffX >= 0 && cutoffX <= w) {
|
||||
ctx.fillStyle = PLAYHEAD_COLOR
|
||||
ctx.fillRect(Math.round(cutoffX) - 1, 0, 2, h)
|
||||
}
|
||||
}
|
||||
|
||||
/** Format seconds as `m:ss.xx` for display and LRC output. */
|
||||
function formatTs(s: number): string {
|
||||
const m = Math.floor(s / 60)
|
||||
const sec = (s % 60).toFixed(2)
|
||||
return `${m}:${sec.padStart(5, '0')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a user-typed timestamp back to seconds.
|
||||
* Accepts `m:ss`, `m:ss.x`, `m:ss.xx`. Returns null on failure.
|
||||
*/
|
||||
function parseTs(raw: string): number | null {
|
||||
const m = raw.trim().match(/^(\d+):(\d{2}(?:\.\d{1,2})?)$/)
|
||||
if (!m) return null
|
||||
const t = parseInt(m[1], 10) * 60 + parseFloat(m[2])
|
||||
return isFinite(t) && t >= 0 ? t : null
|
||||
}
|
||||
|
||||
/** Reconstruct a full LRC/ELRC string from a lines array. */
|
||||
function reconstructLrc(lines: LrcLineKE[]): string {
|
||||
return lines.map(line => {
|
||||
const lineTs = `[${formatTs(line.time)}]`
|
||||
const spTag = line.speaker ? `|sp:${line.speaker}|` : ''
|
||||
if (line.words.length > 0) {
|
||||
const wordPart = line.words
|
||||
.map((w, i) => `<${formatTs(w.time)}>${w.text}${w.isWordEnd && i < line.words.length - 1 ? ' ' : ''}`)
|
||||
.join('')
|
||||
return `${lineTs}${spTag}${wordPart}`
|
||||
}
|
||||
return `${lineTs}${spTag}${line.text}`
|
||||
}).join('\n')
|
||||
}
|
||||
|
||||
/** Same scan as `findActiveLine` in LyricsLivePreview. */
|
||||
function findActiveLine(lines: LrcLineKE[], t: number): number {
|
||||
let idx = -1
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (t >= lines[i].time) idx = i
|
||||
else break
|
||||
}
|
||||
return idx
|
||||
}
|
||||
|
||||
// ─── WaveformCanvas ───────────────────────────────────────────────────────────
|
||||
|
||||
interface WaveformCanvasProps extends Pick<KaraokeEditorProps, 'currentTimeRef' | 'duration' | 'audioUrl' | 'onSeek' | 'lines'> {
|
||||
selectedLineIdx: number | null
|
||||
onWordTimeDrag: (wordIdx: number, newTime: number) => void
|
||||
}
|
||||
|
||||
function WaveformCanvas({
|
||||
currentTimeRef, duration, audioUrl, onSeek, lines,
|
||||
selectedLineIdx, onWordTimeDrag,
|
||||
}: WaveformCanvasProps) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const peaksRef = useRef<Float32Array | null>(null)
|
||||
const rafRef = useRef<number | null>(null)
|
||||
const lastFracRef = useRef(-1)
|
||||
const dirtyRef = useRef(true) // force-redraw flag
|
||||
const linesRef = useRef(lines)
|
||||
linesRef.current = lines
|
||||
const selectedLineIdxRef = useRef<number | null>(null)
|
||||
selectedLineIdxRef.current = selectedLineIdx
|
||||
const dragStateRef = useRef<{ active: boolean; wordIdx: number; hasMoved: boolean } | null>(null)
|
||||
const dragPreviewRef = useRef<{ wordIdx: number; time: number } | null>(null)
|
||||
// Stable callback refs — lets pointer-events effect use [] deps without stale closures
|
||||
const onSeekRef = useRef(onSeek); onSeekRef.current = onSeek
|
||||
const onWordTimeDragRef = useRef(onWordTimeDrag); onWordTimeDragRef.current = onWordTimeDrag
|
||||
const durationRef = useRef(duration); durationRef.current = duration
|
||||
|
||||
// Zoom & scroll — kept in both state (for React re-render of controls) and refs (for RAF)
|
||||
const [zoom, setZoom] = useState(1)
|
||||
const [scroll, setScroll] = useState(0)
|
||||
const zoomRef = useRef(1)
|
||||
const scrollRef = useRef(0)
|
||||
|
||||
// ── Audio decode ─────────────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
peaksRef.current = null
|
||||
dirtyRef.current = true
|
||||
if (!audioUrl) return
|
||||
let cancelled = false
|
||||
const actx = new AudioContext()
|
||||
fetch(audioUrl)
|
||||
.then(r => { if (cancelled) throw new Error('cancelled'); return r.arrayBuffer() })
|
||||
.then(buf => actx.decodeAudioData(buf))
|
||||
.then(audioBuf => {
|
||||
if (cancelled) return
|
||||
peaksRef.current = downsample(audioBuf.getChannelData(0), BUCKET_COUNT)
|
||||
dirtyRef.current = true
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => actx.close())
|
||||
return () => { cancelled = true; actx.close() }
|
||||
}, [audioUrl])
|
||||
|
||||
// ── Size canvas to CSS box ────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
const init = () => {
|
||||
canvas.width = canvas.offsetWidth || 800
|
||||
canvas.height = canvas.offsetHeight || CANVAS_HEIGHT
|
||||
dirtyRef.current = true
|
||||
}
|
||||
init()
|
||||
const ro = new ResizeObserver(init)
|
||||
ro.observe(canvas)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
// ── RAF draw loop ────────────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return
|
||||
|
||||
function loop() {
|
||||
const fraction = duration > 0 ? Math.min(1, currentTimeRef.current / duration) : 0
|
||||
const w = canvas!.width, h = canvas!.height
|
||||
const moved = Math.abs(fraction - lastFracRef.current) * w >= 0.5
|
||||
if (moved || dirtyRef.current) {
|
||||
dirtyRef.current = false
|
||||
lastFracRef.current = fraction
|
||||
const activeIdx = findActiveLine(linesRef.current, currentTimeRef.current)
|
||||
const wordLine = selectedLineIdxRef.current !== null ? (linesRef.current[selectedLineIdxRef.current] ?? null) : null
|
||||
drawFrame(ctx!, peaksRef.current, linesRef.current, w, h, fraction, zoomRef.current, scrollRef.current, duration, activeIdx, wordLine, dragPreviewRef.current)
|
||||
}
|
||||
rafRef.current = requestAnimationFrame(loop)
|
||||
}
|
||||
rafRef.current = requestAnimationFrame(loop)
|
||||
return () => { if (rafRef.current != null) cancelAnimationFrame(rafRef.current) }
|
||||
}, [currentTimeRef, duration])
|
||||
|
||||
// ── Wheel: Ctrl = zoom centred on cursor; plain = horizontal scroll ───────
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
|
||||
function onWheel(e: WheelEvent) {
|
||||
e.preventDefault()
|
||||
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
// Zoom centred on the cursor
|
||||
const rect = canvas!.getBoundingClientRect()
|
||||
const mouseXFrac = (e.clientX - rect.left) / rect.width
|
||||
const curZoom = zoomRef.current
|
||||
const curScroll = scrollRef.current
|
||||
const factor = e.deltaY > 0 ? 1 / 1.5 : 1.5
|
||||
const newZoom = Math.max(1, Math.min(MAX_ZOOM, curZoom * factor))
|
||||
const anchorBucket = curScroll * BUCKET_COUNT + mouseXFrac * (BUCKET_COUNT / curZoom)
|
||||
const newVisibleBuckets = BUCKET_COUNT / newZoom
|
||||
const newScroll = Math.max(0, Math.min(1 - 1 / newZoom, (anchorBucket - mouseXFrac * newVisibleBuckets) / BUCKET_COUNT))
|
||||
zoomRef.current = newZoom
|
||||
scrollRef.current = newScroll
|
||||
setZoom(newZoom)
|
||||
setScroll(newScroll)
|
||||
} else {
|
||||
if (zoomRef.current <= 1) return
|
||||
const delta = e.shiftKey || e.deltaX !== 0 ? (e.deltaX || e.deltaY) : e.deltaY
|
||||
const step = delta / ((canvasRef.current?.clientWidth ?? 800) * zoomRef.current)
|
||||
const newScroll = Math.max(0, Math.min(1 - 1 / zoomRef.current, scrollRef.current + step))
|
||||
scrollRef.current = newScroll
|
||||
setScroll(newScroll)
|
||||
}
|
||||
dirtyRef.current = true
|
||||
}
|
||||
|
||||
canvas.addEventListener('wheel', onWheel, { passive: false })
|
||||
return () => canvas.removeEventListener('wheel', onWheel)
|
||||
}, []) // stable — reads only refs
|
||||
|
||||
// ── selectedLineIdx change → force waveform redraw to show/hide word markers
|
||||
useEffect(() => { dirtyRef.current = true }, [selectedLineIdx])
|
||||
|
||||
// ── Pointer events: click-to-seek + drag-to-retime word markers ─────────
|
||||
// deps=[] — reads duration/callbacks through stable refs so listeners are
|
||||
// registered once and never torn down/re-added on every render.
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas) return
|
||||
|
||||
function getTimeAt(clientX: number): number {
|
||||
const dur = durationRef.current
|
||||
const rect = canvas!.getBoundingClientRect()
|
||||
const xFrac = (clientX - rect.left) / rect.width
|
||||
const bucket = scrollRef.current * BUCKET_COUNT + xFrac * (BUCKET_COUNT / zoomRef.current)
|
||||
return Math.max(0, Math.min(dur, (bucket / BUCKET_COUNT) * dur))
|
||||
}
|
||||
|
||||
function nearestWordIdx(clientX: number): number {
|
||||
const lineIdx = selectedLineIdxRef.current
|
||||
if (lineIdx === null) return -1
|
||||
const words = linesRef.current[lineIdx]?.words
|
||||
if (!words?.length) return -1
|
||||
const rect = canvas!.getBoundingClientRect()
|
||||
const dur = Math.max(durationRef.current, 0.001)
|
||||
const visibleBuckets = BUCKET_COUNT / zoomRef.current
|
||||
for (let wi = 0; wi < words.length; wi++) {
|
||||
const bucket = (words[wi].time / dur) * BUCKET_COUNT
|
||||
const x = ((bucket - scrollRef.current * BUCKET_COUNT) / visibleBuckets) * rect.width
|
||||
if (Math.abs((clientX - rect.left) - x) <= WORD_MARKER_HIT_PX) return wi
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (durationRef.current <= 0) return
|
||||
const wi = nearestWordIdx(e.clientX)
|
||||
if (wi >= 0) {
|
||||
dragStateRef.current = { active: true, wordIdx: wi, hasMoved: false }
|
||||
canvas!.setPointerCapture(e.pointerId)
|
||||
e.preventDefault()
|
||||
} else {
|
||||
dragStateRef.current = { active: false, wordIdx: -1, hasMoved: false }
|
||||
}
|
||||
}
|
||||
|
||||
function onPointerMove(e: PointerEvent) {
|
||||
const ds = dragStateRef.current
|
||||
if (ds?.active) {
|
||||
ds.hasMoved = true
|
||||
const lineIdx = selectedLineIdxRef.current!
|
||||
const line = linesRef.current[lineIdx]
|
||||
const cap = line.words[ds.wordIdx + 1]?.time ?? (linesRef.current[lineIdx + 1]?.time ?? durationRef.current)
|
||||
dragPreviewRef.current = { wordIdx: ds.wordIdx, time: Math.max(line.time, Math.min(cap - 0.01, getTimeAt(e.clientX))) }
|
||||
dirtyRef.current = true
|
||||
} else {
|
||||
const near = nearestWordIdx(e.clientX)
|
||||
canvas!.style.cursor = near >= 0 ? 'ew-resize' : (durationRef.current > 0 ? 'crosshair' : 'default')
|
||||
}
|
||||
}
|
||||
|
||||
function onPointerUp(e: PointerEvent) {
|
||||
const ds = dragStateRef.current
|
||||
dragStateRef.current = null
|
||||
if (!ds) return
|
||||
if (ds.active && ds.hasMoved) {
|
||||
const lineIdx = selectedLineIdxRef.current!
|
||||
const line = linesRef.current[lineIdx]
|
||||
const cap = line.words[ds.wordIdx + 1]?.time ?? (linesRef.current[lineIdx + 1]?.time ?? durationRef.current)
|
||||
const clamped = Math.max(line.time, Math.min(cap - 0.01, getTimeAt(e.clientX)))
|
||||
dragPreviewRef.current = null
|
||||
dirtyRef.current = true
|
||||
onWordTimeDragRef.current(ds.wordIdx, clamped)
|
||||
} else {
|
||||
if (durationRef.current > 0) onSeekRef.current(getTimeAt(e.clientX))
|
||||
}
|
||||
}
|
||||
|
||||
canvas.addEventListener('pointerdown', onPointerDown)
|
||||
canvas.addEventListener('pointermove', onPointerMove)
|
||||
canvas.addEventListener('pointerup', onPointerUp)
|
||||
return () => {
|
||||
canvas.removeEventListener('pointerdown', onPointerDown)
|
||||
canvas.removeEventListener('pointermove', onPointerMove)
|
||||
canvas.removeEventListener('pointerup', onPointerUp)
|
||||
}
|
||||
}, []) // stable — all dynamic values read through refs
|
||||
|
||||
// ── Zoom helpers ─────────────────────────────────────────────────────────
|
||||
function applyZoom(newZoom: number) {
|
||||
const clamped = Math.max(1, Math.min(MAX_ZOOM, newZoom))
|
||||
const newScroll = clamped === 1 ? 0 : Math.max(0, Math.min(1 - 1 / clamped, scrollRef.current))
|
||||
zoomRef.current = clamped
|
||||
scrollRef.current = newScroll
|
||||
setZoom(clamped)
|
||||
setScroll(newScroll)
|
||||
dirtyRef.current = true
|
||||
}
|
||||
|
||||
const btnStyle: Record<string, string | number> = {
|
||||
background: 'rgba(255,255,255,0.08)', color: '#94a3b8',
|
||||
border: 'none', borderRadius: 3, cursor: 'pointer',
|
||||
fontSize: 12, lineHeight: 1, padding: '1px 5px', fontFamily: 'system-ui, sans-serif',
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ position: 'relative' }}>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
title={zoom > 1 ? 'Click to seek · drag amber marker to retime · Ctrl+scroll to zoom · scroll to pan' : 'Click to seek · drag amber marker to retime · Ctrl+scroll to zoom'}
|
||||
style={{ display: 'block', width: '100%', height: CANVAS_HEIGHT, cursor: duration > 0 ? 'crosshair' : 'default', backgroundColor: UNPLAYED_BG }}
|
||||
/>
|
||||
|
||||
{/* Zoom controls — top-right overlay */}
|
||||
<div style={{ position: 'absolute', top: 4, right: 4, display: 'flex', alignItems: 'center', gap: 3 }}>
|
||||
<button style={btnStyle} onClick={() => applyZoom(zoomRef.current / 2)} title="Zoom out">−</button>
|
||||
<span style={{ fontSize: 10, color: '#64748b', fontFamily: 'system-ui, sans-serif', minWidth: 26, textAlign: 'center' }}>
|
||||
{zoom >= 2 ? `${Math.round(zoom)}×` : '1×'}
|
||||
</span>
|
||||
<button style={btnStyle} onClick={() => applyZoom(zoomRef.current * 2)} title="Zoom in">+</button>
|
||||
{zoom > 1 && (
|
||||
<button style={{ ...btnStyle, fontSize: 9 }} onClick={() => applyZoom(1)} title="Reset zoom">✕</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Horizontal scrollbar — only visible when zoomed in */}
|
||||
{zoom > 1 && (
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={1 - 1 / zoom}
|
||||
step={0.0001}
|
||||
value={scroll}
|
||||
onChange={(e: ReactChangeEvent<HTMLInputElement>) => {
|
||||
const v = parseFloat(e.target.value)
|
||||
scrollRef.current = v
|
||||
setScroll(v)
|
||||
dirtyRef.current = true
|
||||
}}
|
||||
style={{ display: 'block', width: '100%', height: 6, margin: 0, cursor: 'pointer' }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── TimingTable ──────────────────────────────────────────────────────────────
|
||||
|
||||
type EditingCell = { row: number; col: 'start' | 'text' } | null
|
||||
|
||||
interface TimingTableProps extends Pick<KaraokeEditorProps, 'lines' | 'currentTimeRef' | 'duration' | 'onSeek' | 'onLrcChange'> {
|
||||
expandedRow: number | null
|
||||
onExpandRow: (row: number | null) => void
|
||||
onWordTimeChange: (lineIdx: number, wordIdx: number, newTime: number) => void
|
||||
}
|
||||
|
||||
function TimingTable({
|
||||
lines, currentTimeRef, duration, onSeek, onLrcChange,
|
||||
expandedRow, onExpandRow, onWordTimeChange,
|
||||
}: TimingTableProps) {
|
||||
|
||||
// ── Inline editing ────────────────────────────────────────────────────────
|
||||
const [editing, setEditing] = useState<EditingCell>(null)
|
||||
const [draft, setDraft] = useState('')
|
||||
|
||||
function startEdit(row: number, col: 'start' | 'text', initialValue: string, e: ReactMouseEvent) {
|
||||
e.stopPropagation()
|
||||
setEditing({ row, col })
|
||||
setDraft(initialValue)
|
||||
}
|
||||
|
||||
function commitEdit() {
|
||||
if (!editing || !onLrcChange) { setEditing(null); return }
|
||||
const { row, col } = editing
|
||||
if (col === 'start') {
|
||||
const t = parseTs(draft)
|
||||
if (t === null) { setEditing(null); return }
|
||||
const newLines = lines.map((l, i) => i === row ? { ...l, time: t } : l).sort((a, b) => a.time - b.time)
|
||||
onLrcChange(reconstructLrc(newLines))
|
||||
} else {
|
||||
const newLines = lines.map((l, i) => i === row ? { ...l, text: draft.trim(), words: [] } : l)
|
||||
onLrcChange(reconstructLrc(newLines))
|
||||
}
|
||||
setEditing(null)
|
||||
}
|
||||
|
||||
function cancelEdit() { setEditing(null) }
|
||||
|
||||
// ── Word-level inline editing ─────────────────────────────────────────────
|
||||
const [wordEditing, setWordEditing] = useState<{ lineIdx: number; wordIdx: number } | null>(null)
|
||||
const [wordDraft, setWordDraft] = useState('')
|
||||
|
||||
function startWordEdit(lineIdx: number, wordIdx: number, e: ReactMouseEvent) {
|
||||
e.stopPropagation()
|
||||
setWordEditing({ lineIdx, wordIdx })
|
||||
setWordDraft(formatTs(lines[lineIdx].words[wordIdx].time))
|
||||
}
|
||||
|
||||
function commitWordEdit() {
|
||||
if (!wordEditing) { setWordEditing(null); return }
|
||||
const { lineIdx, wordIdx } = wordEditing
|
||||
const t = parseTs(wordDraft)
|
||||
if (t === null) { setWordEditing(null); return }
|
||||
const line = lines[lineIdx]
|
||||
const cap = line.words[wordIdx + 1]?.time ?? (lines[lineIdx + 1]?.time ?? duration)
|
||||
onWordTimeChange(lineIdx, wordIdx, Math.max(line.time, Math.min(cap - 0.01, t)))
|
||||
setWordEditing(null)
|
||||
}
|
||||
|
||||
function cancelWordEdit() { setWordEditing(null) }
|
||||
|
||||
function handleWordKeyDown(e: ReactKeyboardEvent<HTMLInputElement>) {
|
||||
if (e.key === 'Enter') { e.preventDefault(); commitWordEdit() }
|
||||
if (e.key === 'Escape') { e.preventDefault(); cancelWordEdit() }
|
||||
if (e.key === 'Tab' && wordEditing) {
|
||||
e.preventDefault()
|
||||
const { lineIdx, wordIdx } = wordEditing
|
||||
const line = lines[lineIdx]
|
||||
const t = parseTs(wordDraft)
|
||||
if (t !== null) {
|
||||
const cap = line.words[wordIdx + 1]?.time ?? (lines[lineIdx + 1]?.time ?? duration)
|
||||
onWordTimeChange(lineIdx, wordIdx, Math.max(line.time, Math.min(cap - 0.01, t)))
|
||||
}
|
||||
const nextIdx = e.shiftKey ? wordIdx - 1 : wordIdx + 1
|
||||
if (nextIdx >= 0 && nextIdx < line.words.length) {
|
||||
setWordEditing({ lineIdx, wordIdx: nextIdx })
|
||||
setWordDraft(formatTs(line.words[nextIdx].time))
|
||||
} else {
|
||||
setWordEditing(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleKeyDown(e: ReactKeyboardEvent<HTMLInputElement>) {
|
||||
if (e.key === 'Enter') { e.preventDefault(); commitEdit() }
|
||||
if (e.key === 'Escape') { e.preventDefault(); cancelEdit() }
|
||||
if (e.key === 'Tab' && editing) {
|
||||
e.preventDefault()
|
||||
commitEdit()
|
||||
const next = e.shiftKey
|
||||
? (editing.col === 'text' ? { row: editing.row, col: 'start' as const }
|
||||
: editing.row > 0 ? { row: editing.row - 1, col: 'text' as const } : null)
|
||||
: (editing.col === 'start' ? { row: editing.row, col: 'text' as const }
|
||||
: editing.row < lines.length - 1 ? { row: editing.row + 1, col: 'start' as const } : null)
|
||||
if (next) {
|
||||
const nextLine = lines[next.row]
|
||||
setEditing(next)
|
||||
setDraft(next.col === 'start' ? formatTs(nextLine.time) : nextLine.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Active-row highlight (RAF, no React re-renders) ───────────────────────
|
||||
const rowRefs = useRef<(HTMLTableRowElement | null)[]>([])
|
||||
const wordRowRefsMap = useRef<Record<string, HTMLTableRowElement | null>>({})
|
||||
const activeRef = useRef(-1)
|
||||
const activeWordRowRef = useRef<HTMLTableRowElement | null>(null)
|
||||
const rafRef = useRef<number | null>(null)
|
||||
const linesRef = useRef(lines)
|
||||
linesRef.current = lines
|
||||
|
||||
function highlightWordRow(el: HTMLTableRowElement | null) {
|
||||
if (activeWordRowRef.current && activeWordRowRef.current !== el) {
|
||||
activeWordRowRef.current.style.backgroundColor = 'transparent'
|
||||
}
|
||||
activeWordRowRef.current = el
|
||||
if (el) el.style.backgroundColor = 'rgba(251,191,36,0.12)'
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
rowRefs.current = new Array(lines.length).fill(null)
|
||||
activeRef.current = -1
|
||||
}, [lines.length])
|
||||
|
||||
useEffect(() => {
|
||||
function applyRow(idx: number, active: boolean) {
|
||||
const row = rowRefs.current[idx]
|
||||
if (!row) return
|
||||
row.style.backgroundColor = active ? ROW_ACTIVE_BG : 'transparent'
|
||||
const cells = row.children
|
||||
for (let c = 0; c < cells.length; c++) {
|
||||
const td = cells[c] as HTMLElement
|
||||
td.style.color = active ? (c === 0 ? ROW_DIM_FG : ROW_ACTIVE_FG) : (c === 0 ? ROW_NUM_FG : ROW_DIM_FG)
|
||||
}
|
||||
}
|
||||
function loop() {
|
||||
const newIdx = findActiveLine(linesRef.current, currentTimeRef.current)
|
||||
const oldIdx = activeRef.current
|
||||
if (newIdx !== oldIdx) {
|
||||
if (oldIdx >= 0) applyRow(oldIdx, false)
|
||||
if (newIdx >= 0) {
|
||||
applyRow(newIdx, true)
|
||||
rowRefs.current[newIdx]?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
|
||||
}
|
||||
activeRef.current = newIdx
|
||||
// Clear word-row highlight when the active line changes
|
||||
highlightWordRow(null)
|
||||
}
|
||||
rafRef.current = requestAnimationFrame(loop)
|
||||
}
|
||||
rafRef.current = requestAnimationFrame(loop)
|
||||
return () => { if (rafRef.current != null) cancelAnimationFrame(rafRef.current) }
|
||||
}, [currentTimeRef])
|
||||
|
||||
// ── Render ────────────────────────────────────────────────────────────────
|
||||
const hasSpeakers = lines.some(l => l.speaker)
|
||||
const canEdit = !!onLrcChange
|
||||
|
||||
const inputStyle: Record<string, string | number> = {
|
||||
width: '100%', boxSizing: 'border-box',
|
||||
background: 'rgba(96,165,250,0.12)', color: '#e2e8f0',
|
||||
border: '1px solid rgba(96,165,250,0.5)', borderRadius: 3,
|
||||
padding: '0 4px', fontSize: 11,
|
||||
fontFamily: '"Roboto Mono","Fira Code",monospace',
|
||||
outline: 'none', height: 20,
|
||||
}
|
||||
|
||||
const wordInputStyle: Record<string, string | number> = {
|
||||
width: '100%', boxSizing: 'border-box',
|
||||
background: 'rgba(251,191,36,0.08)', color: '#e2e8f0',
|
||||
border: '1px solid rgba(251,191,36,0.4)', borderRadius: 3,
|
||||
padding: '0 4px', fontSize: 11,
|
||||
fontFamily: '"Roboto Mono","Fira Code",monospace',
|
||||
outline: 'none', height: 20,
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ height: TABLE_HEIGHT, overflowY: 'auto', overflowX: 'hidden' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', tableLayout: 'fixed' }}>
|
||||
<colgroup>
|
||||
<col style={{ width: 36 }} />
|
||||
<col style={{ width: 78 }} />
|
||||
<col style={{ width: 72 }} />
|
||||
<col />
|
||||
{hasSpeakers && <col style={{ width: 80 }} />}
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr style={{ position: 'sticky', top: 0, zIndex: 1, backgroundColor: '#0c1523', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
|
||||
{(['#', 'Start', 'End', 'Text', ...(hasSpeakers ? ['Speaker'] : [])] as string[]).map(h => (
|
||||
<th key={h} style={{ padding: '3px 6px', textAlign: 'left', fontSize: 9, fontWeight: 600, color: '#334155', letterSpacing: '0.06em', textTransform: 'uppercase', fontFamily: 'system-ui, sans-serif', overflow: 'hidden' }}>{h}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{lines.map((line, i) => {
|
||||
const endTime = lines[i + 1]?.time ?? duration
|
||||
const editingStart = editing?.row === i && editing.col === 'start'
|
||||
const editingText = editing?.row === i && editing.col === 'text'
|
||||
return (
|
||||
<Fragment key={i}>
|
||||
<tr
|
||||
ref={(el: HTMLTableRowElement | null) => { rowRefs.current[i] = el }}
|
||||
onClick={() => onSeek(line.time)}
|
||||
style={{ cursor: 'pointer', borderBottom: '1px solid rgba(255,255,255,0.03)', backgroundColor: 'transparent' }}
|
||||
>
|
||||
<td
|
||||
style={{ padding: '3px 4px', textAlign: 'right', fontSize: 11, color: ROW_NUM_FG, fontFamily: 'system-ui, sans-serif', userSelect: 'none', cursor: line.words.length > 0 ? 'pointer' : 'default' }}
|
||||
onClick={line.words.length > 0 ? (e: ReactMouseEvent<HTMLTableCellElement>) => { e.stopPropagation(); onExpandRow(expandedRow === i ? null : i) } : undefined}
|
||||
title={line.words.length > 0 ? (expandedRow === i ? 'Collapse word timing' : 'Expand word timing') : undefined}
|
||||
>
|
||||
{line.words.length > 0 && <span style={{ fontSize: 8, color: '#64748b' }}>{expandedRow === i ? '▼ ' : '▶ '}</span>}
|
||||
{i + 1}
|
||||
</td>
|
||||
<td
|
||||
style={{ padding: editingStart ? '1px 4px' : '3px 6px', fontSize: 11, color: ROW_DIM_FG, fontFamily: '"Roboto Mono","Fira Code",monospace', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}
|
||||
title={canEdit ? 'Double-click to edit' : undefined}
|
||||
onDoubleClick={canEdit ? (e: ReactMouseEvent<HTMLTableCellElement>) => startEdit(i, 'start', formatTs(line.time), e) : undefined}
|
||||
>
|
||||
{editingStart ? (
|
||||
<input autoFocus style={inputStyle} value={draft}
|
||||
onChange={(e: ReactChangeEvent<HTMLInputElement>) => setDraft(e.target.value)}
|
||||
onBlur={commitEdit} onKeyDown={handleKeyDown}
|
||||
onClick={(e: ReactMouseEvent<HTMLInputElement>) => e.stopPropagation()} />
|
||||
) : formatTs(line.time)}
|
||||
</td>
|
||||
<td style={{ padding: '3px 6px', fontSize: 11, color: ROW_NUM_FG, fontFamily: '"Roboto Mono","Fira Code",monospace', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
|
||||
{formatTs(endTime)}
|
||||
</td>
|
||||
<td
|
||||
style={{ padding: editingText ? '1px 4px' : '3px 8px', fontSize: 12, color: ROW_DIM_FG, fontFamily: 'system-ui, sans-serif', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: editingText ? undefined : 'nowrap' }}
|
||||
title={canEdit ? 'Double-click to edit' + (line.words.length > 0 ? ' (word timing will be replaced with plain text)' : '') : undefined}
|
||||
onDoubleClick={canEdit ? (e: ReactMouseEvent<HTMLTableCellElement>) => startEdit(i, 'text', line.text, e) : undefined}
|
||||
>
|
||||
{editingText ? (
|
||||
<input autoFocus style={{ ...inputStyle, fontFamily: 'system-ui, sans-serif' }} value={draft}
|
||||
onChange={(e: ReactChangeEvent<HTMLInputElement>) => setDraft(e.target.value)}
|
||||
onBlur={commitEdit} onKeyDown={handleKeyDown}
|
||||
onClick={(e: ReactMouseEvent<HTMLInputElement>) => e.stopPropagation()} />
|
||||
) : line.text}
|
||||
</td>
|
||||
{hasSpeakers && (
|
||||
<td style={{ padding: '3px 6px', fontSize: 10, color: ROW_NUM_FG, fontFamily: 'system-ui, sans-serif', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{line.speaker ?? ''}
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
{expandedRow === i && line.words.length > 0 && line.words.map((word, j) => {
|
||||
const wEnd = line.words[j + 1]?.time ?? endTime
|
||||
const isWordEdit = wordEditing?.lineIdx === i && wordEditing?.wordIdx === j
|
||||
const wKey = `${i}-${j}`
|
||||
return (
|
||||
<tr
|
||||
key={`w-${j}`}
|
||||
ref={(el: HTMLTableRowElement | null) => { wordRowRefsMap.current[wKey] = el }}
|
||||
onClick={(e: ReactMouseEvent<HTMLTableRowElement>) => { e.stopPropagation(); onSeek(word.time); highlightWordRow(wordRowRefsMap.current[wKey] ?? null) }}
|
||||
style={{ cursor: 'pointer', borderBottom: '1px solid rgba(255,255,255,0.02)', backgroundColor: 'transparent' }}
|
||||
>
|
||||
<td style={{ padding: '2px 4px', textAlign: 'right', fontSize: 10, color: '#1e293b', fontFamily: 'system-ui, sans-serif', userSelect: 'none', borderLeft: '2px solid rgba(251,191,36,0.3)' }}>
|
||||
└
|
||||
</td>
|
||||
<td
|
||||
style={{ padding: isWordEdit ? '1px 4px' : '2px 6px', fontSize: 11, color: '#475569', fontFamily: '"Roboto Mono","Fira Code",monospace', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}
|
||||
title={canEdit ? 'Double-click to edit word start time' : undefined}
|
||||
onDoubleClick={canEdit ? (e: ReactMouseEvent<HTMLTableCellElement>) => startWordEdit(i, j, e) : undefined}
|
||||
>
|
||||
{isWordEdit ? (
|
||||
<input autoFocus style={wordInputStyle} value={wordDraft}
|
||||
onChange={(e: ReactChangeEvent<HTMLInputElement>) => setWordDraft(e.target.value)}
|
||||
onBlur={commitWordEdit} onKeyDown={handleWordKeyDown}
|
||||
onClick={(e: ReactMouseEvent<HTMLInputElement>) => e.stopPropagation()} />
|
||||
) : formatTs(word.time)}
|
||||
</td>
|
||||
<td style={{ padding: '2px 6px', fontSize: 11, color: '#334155', fontFamily: '"Roboto Mono","Fira Code",monospace', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
|
||||
{formatTs(wEnd)}
|
||||
</td>
|
||||
<td style={{ padding: '2px 8px', fontSize: 11, color: '#475569', fontFamily: 'system-ui, sans-serif', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{word.text}
|
||||
</td>
|
||||
{hasSpeakers && <td />}
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</Fragment>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── KaraokeEditor ────────────────────────────────────────────────────────────
|
||||
|
||||
export default function KaraokeEditor({
|
||||
lines, currentTimeRef, duration, audioUrl, onSeek, onLrcChange,
|
||||
}: KaraokeEditorProps) {
|
||||
|
||||
// Keep a stable ref for the keyboard shortcut handler
|
||||
const linesRef = useRef(lines)
|
||||
linesRef.current = lines
|
||||
|
||||
// ── Expanded word-timing row ──────────────────────────────────────────────
|
||||
const [expandedRow, setExpandedRow] = useState<number | null>(null)
|
||||
|
||||
function handleWordTimeChange(lineIdx: number, wordIdx: number, newTime: number) {
|
||||
const newLines = lines.map((l, i) => {
|
||||
if (i !== lineIdx) return l
|
||||
const newWords = l.words.map((w, j) => j === wordIdx ? { ...w, time: newTime } : w)
|
||||
return { ...l, words: newWords }
|
||||
})
|
||||
onLrcChange?.(reconstructLrc(newLines))
|
||||
}
|
||||
|
||||
function handleWordTimeDrag(wordIdx: number, newTime: number) {
|
||||
if (expandedRow === null) return
|
||||
handleWordTimeChange(expandedRow, wordIdx, newTime)
|
||||
}
|
||||
|
||||
// ── Arrow-key navigation: ← prev line · → next line ──────────────────────
|
||||
useEffect(() => {
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return
|
||||
const tag = (document.activeElement as HTMLElement | null)?.tagName
|
||||
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return
|
||||
e.preventDefault()
|
||||
const ls = linesRef.current
|
||||
const idx = findActiveLine(ls, currentTimeRef.current)
|
||||
if (e.key === 'ArrowLeft') {
|
||||
const prev = Math.max(0, idx > 0 ? idx - 1 : 0)
|
||||
if (ls[prev]) onSeek(ls[prev].time)
|
||||
} else {
|
||||
const next = idx + 1
|
||||
if (ls[next]) onSeek(ls[next].time)
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', onKeyDown)
|
||||
return () => document.removeEventListener('keydown', onKeyDown)
|
||||
}, [currentTimeRef, onSeek])
|
||||
|
||||
return (
|
||||
<div style={{ borderTop: '1px solid rgba(255,255,255,0.08)', backgroundColor: UNPLAYED_BG, userSelect: 'none' }}>
|
||||
|
||||
{/* Waveform header */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', padding: '4px 10px', borderBottom: '1px solid rgba(255,255,255,0.06)', backgroundColor: 'rgba(255,255,255,0.03)' }}>
|
||||
<span style={{ fontSize: 10, color: '#64748b', fontFamily: 'system-ui, sans-serif', letterSpacing: '0.05em', textTransform: 'uppercase' }}>Waveform</span>
|
||||
{!audioUrl
|
||||
? <span style={{ fontSize: 10, color: '#475569', marginLeft: 8, fontFamily: 'system-ui, sans-serif' }}>— not available in multi-stem mode</span>
|
||||
: <span style={{ fontSize: 10, color: '#334155', marginLeft: 8, fontFamily: 'system-ui, sans-serif' }}>Ctrl+scroll to zoom · scroll to pan · ←→ keys jump lines</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<WaveformCanvas currentTimeRef={currentTimeRef} duration={duration} audioUrl={audioUrl} onSeek={onSeek} lines={lines}
|
||||
selectedLineIdx={expandedRow} onWordTimeDrag={handleWordTimeDrag} />
|
||||
|
||||
{/* Lines header */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', padding: '4px 10px', borderTop: '1px solid rgba(255,255,255,0.06)', borderBottom: '1px solid rgba(255,255,255,0.06)', backgroundColor: 'rgba(255,255,255,0.03)' }}>
|
||||
<span style={{ fontSize: 10, color: '#64748b', fontFamily: 'system-ui, sans-serif', letterSpacing: '0.05em', textTransform: 'uppercase' }}>Lines</span>
|
||||
{onLrcChange && <span style={{ fontSize: 10, color: '#334155', marginLeft: 8, fontFamily: 'system-ui, sans-serif' }}>— double-click Start or Text to edit</span>}
|
||||
<span style={{ fontSize: 10, color: '#334155', marginLeft: 'auto', fontFamily: 'system-ui, sans-serif' }}>{lines.length}</span>
|
||||
</div>
|
||||
|
||||
<TimingTable lines={lines} currentTimeRef={currentTimeRef} duration={duration} onSeek={onSeek} onLrcChange={onLrcChange}
|
||||
expandedRow={expandedRow} onExpandRow={setExpandedRow} onWordTimeChange={handleWordTimeChange} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+2341
File diff suppressed because it is too large.
Load diff
+45
@@ -0,0 +1,45 @@
|
||||
import React from 'react'
|
||||
import { Download, FileAudio, FileMusic, FileText, File } from 'lucide-react'
|
||||
import { downloadUrl } from '../api/client'
|
||||
import type { JobFile } from '../types'
|
||||
|
||||
interface Props {
|
||||
jobId: string
|
||||
files: JobFile[]
|
||||
}
|
||||
|
||||
const FILE_ICONS: Record<string, React.ElementType> = {
|
||||
stem: FileAudio,
|
||||
instrumental: FileAudio,
|
||||
static: FileAudio,
|
||||
dynamic: FileAudio,
|
||||
lrc: FileText,
|
||||
elrc: FileText,
|
||||
midi: FileMusic,
|
||||
}
|
||||
|
||||
function FileIcon({ type }: { type?: string }) {
|
||||
const Icon = FILE_ICONS[type || ''] || File
|
||||
return <Icon className="w-4 h-4 text-slate-400" />
|
||||
}
|
||||
|
||||
export default function ResultFiles({ jobId, files }: Props) {
|
||||
if (!files.length) return null
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{files.map((f) => (
|
||||
<a
|
||||
key={f.name}
|
||||
href={downloadUrl(jobId, f.name)}
|
||||
download={f.name}
|
||||
className="flex items-center gap-3 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/50 border border-slate-200 dark:border-gray-700 hover:border-brand-400 dark:hover:border-brand-500 transition-colors group"
|
||||
>
|
||||
<FileIcon type={f.type} />
|
||||
<span className="flex-1 text-xs text-slate-700 dark:text-gray-300 truncate">{f.name}</span>
|
||||
<Download className="w-3.5 h-3.5 text-slate-400 group-hover:text-brand-500 transition-colors" />
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
|
||||
import { X, Sun, Moon, Monitor, Settings, ChevronRight } from 'lucide-react'
|
||||
import { useTheme } from '../context/ThemeContext'
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onOpenFullSettings?: () => void
|
||||
}
|
||||
|
||||
export default function SettingsPanel({ isOpen, onClose, onOpenFullSettings }: Props) {
|
||||
const { theme, setTheme } = useTheme()
|
||||
|
||||
const handleOpenFullSettings = () => {
|
||||
onClose()
|
||||
onOpenFullSettings?.()
|
||||
}
|
||||
|
||||
if (!isOpen) return null
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-start justify-center pt-16">
|
||||
<div className="absolute inset-0 bg-black/50" onClick={onClose} />
|
||||
<div className="relative w-full max-w-md mx-4 rounded-xl bg-white dark:bg-gray-900 shadow-2xl border border-slate-200 dark:border-gray-800">
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-slate-200 dark:border-gray-800">
|
||||
<h2 className="text-sm font-semibold text-slate-900 dark:text-white">Settings</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1 rounded text-slate-400 hover:text-slate-600 dark:text-gray-500 dark:hover:text-gray-300"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-4 space-y-4">
|
||||
{/* Theme */}
|
||||
<div>
|
||||
<label className="text-xs font-medium text-slate-500 dark:text-gray-400 uppercase tracking-wider block mb-2">
|
||||
Theme
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setTheme('light')}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-xs font-medium transition-colors ${
|
||||
theme === 'light'
|
||||
? 'bg-brand-50 dark:bg-brand-950/30 border-brand-400 text-brand-600 dark:text-brand-400'
|
||||
: 'bg-white dark:bg-gray-800 border-slate-200 dark:border-gray-700 text-slate-600 dark:text-gray-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Sun className="w-3.5 h-3.5" />
|
||||
Light
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTheme('dark')}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-xs font-medium transition-colors ${
|
||||
theme === 'dark'
|
||||
? 'bg-brand-50 dark:bg-brand-950/30 border-brand-400 text-brand-600 dark:text-brand-400'
|
||||
: 'bg-white dark:bg-gray-800 border-slate-200 dark:border-gray-700 text-slate-600 dark:text-gray-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Moon className="w-3.5 h-3.5" />
|
||||
Dark
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTheme('system')}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-xs font-medium transition-colors ${
|
||||
theme === 'system'
|
||||
? 'bg-brand-50 dark:bg-brand-950/30 border-brand-400 text-brand-600 dark:text-brand-400'
|
||||
: 'bg-white dark:bg-gray-800 border-slate-200 dark:border-gray-700 text-slate-600 dark:text-gray-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Monitor className="w-3.5 h-3.5" />
|
||||
System
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="border-t border-slate-200 dark:border-gray-800 pt-4">
|
||||
<button
|
||||
onClick={handleOpenFullSettings}
|
||||
className="w-full flex items-center justify-between p-3 rounded-lg bg-slate-50 dark:bg-gray-800 hover:bg-slate-100 dark:hover:bg-gray-750 transition-colors group"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Settings className="w-4 h-4 text-slate-500 dark:text-gray-400" />
|
||||
<span className="text-sm font-medium text-slate-700 dark:text-gray-300">
|
||||
Full Settings
|
||||
</span>
|
||||
</div>
|
||||
<ChevronRight className="w-4 h-4 text-slate-400 group-hover:text-slate-600 dark:group-hover:text-gray-300 transition-colors" />
|
||||
</button>
|
||||
<p className="mt-1.5 text-xs text-slate-400 dark:text-gray-500 px-1">
|
||||
Configure Subsonic integration, manage AI models, and more.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Executable
+528
@@ -0,0 +1,528 @@
|
||||
import React, { useState, useRef, useMemo } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
ChevronLeft, ChevronRight, Loader2, CheckCircle, XCircle,
|
||||
Clock, AlertCircle, X, Music2, Mic2, FileCode, Workflow,
|
||||
FolderOpen, Type, ChevronDown, ChevronUp, Radio, Search,
|
||||
Download, CheckCircle2, Trash2, Zap,
|
||||
} from 'lucide-react'
|
||||
import {
|
||||
listJobs, cancelJob,
|
||||
searchSubsonic, importSubsonicSong,
|
||||
listImports, deleteImport,
|
||||
listProjects, deleteProject,
|
||||
} from '../api/client'
|
||||
import type { Job, Project, SubsonicSong, ImportedFile } from '../types'
|
||||
import AutoPipelineDialog from './AutoPipelineDialog'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const JOB_COLORS: Record<string, string> = {
|
||||
separate: 'text-brand-500',
|
||||
transcribe: 'text-purple-500',
|
||||
'abc-convert': 'text-emerald-500',
|
||||
pipeline: 'text-rose-500',
|
||||
lrc_align: 'text-amber-500',
|
||||
mix: 'text-brand-500',
|
||||
}
|
||||
|
||||
const JOB_ICONS: Record<string, React.ElementType> = {
|
||||
separate: Music2,
|
||||
transcribe: Mic2,
|
||||
'abc-convert': FileCode,
|
||||
pipeline: Workflow,
|
||||
lrc_align: Type,
|
||||
mix: Music2,
|
||||
}
|
||||
|
||||
function StatusDot({ status }: { status: Job['status'] }) {
|
||||
switch (status) {
|
||||
case 'running': return <Loader2 className="w-3 h-3 text-brand-400 animate-spin shrink-0" />
|
||||
case 'queued': return <Clock className="w-3 h-3 text-amber-400 shrink-0" />
|
||||
case 'done': return <CheckCircle className="w-3 h-3 text-emerald-400 shrink-0" />
|
||||
case 'error': return <XCircle className="w-3 h-3 text-red-400 shrink-0" />
|
||||
case 'cancelled': return <AlertCircle className="w-3 h-3 text-gray-400 shrink-0" />
|
||||
}
|
||||
}
|
||||
|
||||
function timeSince(iso: string | null): string {
|
||||
if (!iso) return ''
|
||||
const ms = Date.now() - new Date(iso).getTime()
|
||||
const m = Math.floor(ms / 60000)
|
||||
if (m < 1) return 'just now'
|
||||
if (m < 60) return `${m}m ago`
|
||||
const h = Math.floor(m / 60)
|
||||
if (h < 24) return `${h}h ago`
|
||||
return `${Math.floor(h / 24)}d ago`
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Active job item (with cancel)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function ActiveJobItem({ job, onCancelled }: { job: Job; onCancelled: () => void }) {
|
||||
const [cancelling, setCancelling] = useState(false)
|
||||
const Icon = JOB_ICONS[job.job_type] ?? FolderOpen
|
||||
const colorCls = JOB_COLORS[job.job_type] ?? 'text-gray-400'
|
||||
|
||||
async function handleCancel(e: React.MouseEvent) {
|
||||
e.stopPropagation()
|
||||
setCancelling(true)
|
||||
try { await cancelJob(job.id) } catch { /* ignore */ }
|
||||
onCancelled()
|
||||
setCancelling(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/60 border border-slate-200 dark:border-gray-700/50">
|
||||
<Icon className={`w-3.5 h-3.5 shrink-0 ${colorCls}`} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">
|
||||
{job.job_type.replace('-', ' ').replace('_', ' ')}
|
||||
</p>
|
||||
{job.progress && (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-500 truncate leading-tight">{job.progress}</p>
|
||||
)}
|
||||
</div>
|
||||
<StatusDot status={job.status} />
|
||||
<button
|
||||
onClick={handleCancel}
|
||||
disabled={cancelling}
|
||||
title="Cancel"
|
||||
className="p-1 rounded text-slate-300 hover:text-red-400 dark:text-gray-600 dark:hover:text-red-400 transition-colors shrink-0"
|
||||
>
|
||||
{cancelling ? <Loader2 className="w-3 h-3 animate-spin" /> : <X className="w-3 h-3" />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Project item
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function ProjectItem({
|
||||
project,
|
||||
isOpen,
|
||||
onOpen,
|
||||
onDeleted,
|
||||
}: {
|
||||
project: Project
|
||||
isOpen: boolean
|
||||
onOpen: () => void
|
||||
onDeleted: () => void
|
||||
}) {
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
|
||||
async function handleDelete(e: React.MouseEvent) {
|
||||
e.stopPropagation()
|
||||
if (!window.confirm(`Delete "${project.name}"?\n\nThis will permanently remove the project and all its files.`)) return
|
||||
setDeleting(true)
|
||||
try { await deleteProject(project.id) } catch { /* ignore */ }
|
||||
finally { setDeleting(false) }
|
||||
onDeleted()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={onOpen}
|
||||
className={`group w-full flex items-center gap-2 px-3 py-2 rounded-lg border text-left transition-colors cursor-pointer ${
|
||||
isOpen
|
||||
? 'border-brand-400/50 bg-brand-50 dark:bg-brand-950/20 text-brand-700 dark:text-brand-300'
|
||||
: 'border-slate-200 dark:border-gray-700/60 hover:bg-slate-50 dark:hover:bg-gray-800/50 hover:border-brand-400/50'
|
||||
}`}
|
||||
>
|
||||
<Music2 className="w-3.5 h-3.5 shrink-0 text-brand-500" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">{project.name}</p>
|
||||
{project.tab_label && (
|
||||
<p className="text-[10px] text-brand-500 dark:text-brand-400 truncate leading-tight">{project.tab_label}</p>
|
||||
)}
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500">{timeSince(project.created_at)}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
disabled={deleting}
|
||||
title="Delete project"
|
||||
className="shrink-0 p-1 rounded text-slate-300 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 transition-colors opacity-0 group-hover:opacity-100"
|
||||
>
|
||||
{deleting ? <Loader2 className="w-3 h-3 animate-spin" /> : <Trash2 className="w-3 h-3" />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Subsonic import panel
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function formatDuration(secs: number): string {
|
||||
const m = Math.floor(secs / 60)
|
||||
const s = secs % 60
|
||||
return `${m}:${String(s).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
function SubsonicPanel() {
|
||||
const queryClient = useQueryClient()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState<SubsonicSong[]>([])
|
||||
const [searching, setSearching] = useState(false)
|
||||
const [searchErr, setSearchErr] = useState<string | null>(null)
|
||||
const [importing, setImporting] = useState<string | null>(null)
|
||||
const [importedIds, setImportedIds] = useState<Set<string>>(new Set())
|
||||
const [importErr, setImportErr] = useState<string | null>(null)
|
||||
const [deletingFile, setDeletingFile] = useState<string | null>(null)
|
||||
const [autoTarget, setAutoTarget] = useState<ImportedFile | null>(null)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const { data: importedFiles = [], refetch: refetchImports } = useQuery<ImportedFile[]>({
|
||||
queryKey: ['imports'],
|
||||
queryFn: listImports,
|
||||
enabled: open,
|
||||
refetchInterval: open ? 10000 : false,
|
||||
})
|
||||
|
||||
async function doSearch() {
|
||||
if (!query.trim()) return
|
||||
setSearching(true); setSearchErr(null); setResults([])
|
||||
try {
|
||||
const res = await searchSubsonic(query.trim())
|
||||
setResults(res)
|
||||
if (res.length === 0) setSearchErr('No results found.')
|
||||
} catch (e) {
|
||||
setSearchErr(String(e))
|
||||
} finally {
|
||||
setSearching(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function doImport(song: SubsonicSong) {
|
||||
setImporting(song.id); setImportErr(null)
|
||||
try {
|
||||
await importSubsonicSong(song)
|
||||
setImportedIds((prev) => new Set(prev).add(song.id))
|
||||
refetchImports()
|
||||
queryClient.invalidateQueries({ queryKey: ['imports'] })
|
||||
} catch (e) {
|
||||
setImportErr(String(e))
|
||||
} finally {
|
||||
setImporting(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function doDeleteImport(filename: string) {
|
||||
setDeletingFile(filename)
|
||||
try {
|
||||
await deleteImport(filename)
|
||||
refetchImports()
|
||||
queryClient.invalidateQueries({ queryKey: ['imports'] })
|
||||
} catch { /* ignore */ }
|
||||
finally { setDeletingFile(null) }
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-b border-slate-200 dark:border-gray-800">
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="w-full flex items-center gap-2 px-3 py-2.5 text-left hover:bg-slate-100 dark:hover:bg-gray-900/50 transition-colors"
|
||||
>
|
||||
<Radio className="w-3.5 h-3.5 text-sky-500 shrink-0" />
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-sky-500 flex-1">Subsonic Import</span>
|
||||
{open
|
||||
? <ChevronUp className="w-3 h-3 text-slate-400 shrink-0" />
|
||||
: <ChevronDown className="w-3 h-3 text-slate-400 shrink-0" />}
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="px-3 pb-3 space-y-2">
|
||||
{/* Search input */}
|
||||
<div className="flex gap-1.5">
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && doSearch()}
|
||||
placeholder="Search songs…"
|
||||
className="flex-1 rounded-md bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-2.5 py-1.5 text-xs text-slate-900 dark:text-gray-100 placeholder-slate-400 focus:border-sky-400 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
onClick={doSearch}
|
||||
disabled={searching || !query.trim()}
|
||||
className="rounded-md bg-sky-500 hover:bg-sky-400 disabled:bg-slate-200 dark:disabled:bg-gray-800 disabled:text-slate-400 px-2.5 py-1.5 text-xs font-medium text-white transition-colors shrink-0"
|
||||
>
|
||||
{searching ? <Loader2 className="w-3 h-3 animate-spin" /> : <Search className="w-3 h-3" />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Errors */}
|
||||
{searchErr && <p className="text-xs text-red-500 dark:text-red-400">{searchErr}</p>}
|
||||
{importErr && <p className="text-xs text-red-500 dark:text-red-400 break-all">{importErr}</p>}
|
||||
|
||||
{/* Search results */}
|
||||
{results.length > 0 && (
|
||||
<div className="space-y-1 max-h-52 overflow-y-auto pr-0.5">
|
||||
{results.map((song) => {
|
||||
const done = importedIds.has(song.id)
|
||||
const busy = importing === song.id
|
||||
return (
|
||||
<div
|
||||
key={song.id}
|
||||
className="flex items-start gap-2 rounded-lg border border-slate-200 dark:border-gray-700/60 bg-white dark:bg-gray-900/50 px-2.5 py-2"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate leading-tight">
|
||||
{song.title}
|
||||
</p>
|
||||
{song.artist && (
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500 truncate leading-tight">
|
||||
{song.artist}{song.album ? ` · ${song.album}` : ''}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-600 mt-0.5">
|
||||
{song.duration ? formatDuration(song.duration) : ''}{song.bitRate ? ` · ${song.bitRate} kbps` : ''}{song.suffix ? ` · ${song.suffix.toUpperCase()}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => doImport(song)}
|
||||
disabled={busy || done}
|
||||
title={done ? 'Imported' : 'Import'}
|
||||
className="shrink-0 p-1.5 rounded-md border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800 hover:border-sky-400 hover:text-sky-500 disabled:opacity-60 transition-colors"
|
||||
>
|
||||
{busy
|
||||
? <Loader2 className="w-3 h-3 animate-spin text-sky-400" />
|
||||
: done
|
||||
? <CheckCircle2 className="w-3 h-3 text-emerald-500" />
|
||||
: <Download className="w-3 h-3 text-slate-500 dark:text-gray-400" />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Imported files list */}
|
||||
{importedFiles.length > 0 && (
|
||||
<div>
|
||||
<p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 dark:text-gray-600 mb-1">Imported Files</p>
|
||||
<div className="space-y-1 max-h-40 overflow-y-auto">
|
||||
{importedFiles.map((f) => {
|
||||
const isDeleting = deletingFile === f.filename
|
||||
return (
|
||||
<div
|
||||
key={f.path}
|
||||
className="group flex items-center gap-2 rounded-lg border border-slate-200 dark:border-gray-700/60 bg-white dark:bg-gray-900/50 px-2.5 py-1.5"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">{f.filename}</p>
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500">{(f.size / 1024 / 1024).toFixed(1)} MB</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setAutoTarget(f)}
|
||||
title="Auto pipeline"
|
||||
className="shrink-0 p-1 rounded text-slate-300 dark:text-gray-600 hover:text-amber-500 dark:hover:text-amber-400 transition-colors opacity-0 group-hover:opacity-100"
|
||||
>
|
||||
<Zap className="w-3 h-3" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => doDeleteImport(f.filename)}
|
||||
disabled={isDeleting}
|
||||
title="Delete import"
|
||||
className="shrink-0 p-1 rounded text-slate-300 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 transition-colors opacity-0 group-hover:opacity-100"
|
||||
>
|
||||
{isDeleting
|
||||
? <Loader2 className="w-3 h-3 animate-spin" />
|
||||
: <Trash2 className="w-3 h-3" />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{autoTarget && (
|
||||
<AutoPipelineDialog
|
||||
target={{
|
||||
filePath: autoTarget.path,
|
||||
filename: autoTarget.filename,
|
||||
initialProjectName: autoTarget.artist && autoTarget.title
|
||||
? `${autoTarget.artist} - ${autoTarget.title}`
|
||||
: autoTarget.filename.replace(/\.[^/.]+$/, ''),
|
||||
}}
|
||||
onClose={() => setAutoTarget(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sidebar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean
|
||||
onToggle: () => void
|
||||
onOpenProject: (project: Project) => void
|
||||
onDeleteProject: (project: Project) => void
|
||||
openTabIds: string[] // IDs of project tabs currently open in the tab bar
|
||||
}
|
||||
|
||||
export default function Sidebar({ isOpen, onToggle, onOpenProject, onDeleteProject, openTabIds }: Props) {
|
||||
const queryClient = useQueryClient()
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
|
||||
const { data: jobs = [] } = useQuery({
|
||||
queryKey: ['jobs'],
|
||||
queryFn: listJobs,
|
||||
refetchInterval: 3000,
|
||||
})
|
||||
|
||||
const { data: projects = [] } = useQuery<Project[]>({
|
||||
queryKey: ['projects'],
|
||||
queryFn: listProjects,
|
||||
refetchInterval: 8000,
|
||||
})
|
||||
|
||||
// Filter projects based on search query
|
||||
const filteredProjects = useMemo(() => {
|
||||
if (!searchQuery.trim()) return projects
|
||||
const query = searchQuery.toLowerCase()
|
||||
return projects.filter(p =>
|
||||
p.name.toLowerCase().includes(query) ||
|
||||
p.tab_label.toLowerCase().includes(query)
|
||||
)
|
||||
}, [projects, searchQuery])
|
||||
|
||||
const activeJobs = jobs.filter((j) => j.status === 'running' || j.status === 'queued')
|
||||
|
||||
function invalidate() { queryClient.invalidateQueries({ queryKey: ['jobs'] }) }
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={`relative flex-shrink-0 flex flex-col border-r border-slate-200 dark:border-gray-800 bg-slate-50 dark:bg-gray-950 transition-all duration-200 ease-in-out ${
|
||||
isOpen ? 'sidebar-open' : 'sidebar-closed'
|
||||
}`}
|
||||
>
|
||||
{/* Toggle tab — always visible */}
|
||||
<button
|
||||
onClick={onToggle}
|
||||
title={isOpen ? 'Collapse sidebar' : 'Expand sidebar'}
|
||||
className={`absolute -right-3.5 top-6 z-10 flex items-center justify-center w-7 h-7 rounded-full bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 shadow-sm text-slate-400 hover:text-brand-500 dark:text-gray-500 dark:hover:text-brand-400 transition-colors`}
|
||||
>
|
||||
{isOpen ? <ChevronLeft className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
|
||||
</button>
|
||||
|
||||
{/* Collapsed indicator strip */}
|
||||
{!isOpen && (
|
||||
<div className="flex flex-col items-center gap-3 pt-16 px-2">
|
||||
{activeJobs.length > 0 && (
|
||||
<div className="relative">
|
||||
<Loader2 className="w-5 h-5 text-brand-400 animate-spin" />
|
||||
<span className="absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full bg-brand-500 text-white text-[9px] flex items-center justify-center font-bold">
|
||||
{activeJobs.length}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<Radio className="w-5 h-5 text-slate-400 dark:text-gray-600" />
|
||||
{projects.length > 0 && (
|
||||
<div className="relative">
|
||||
<FolderOpen className="w-5 h-5 text-slate-400 dark:text-gray-600" />
|
||||
<span className="absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full bg-slate-400 dark:bg-gray-600 text-white text-[9px] flex items-center justify-center font-bold">
|
||||
{projects.length}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Expanded content */}
|
||||
{isOpen && (
|
||||
<div className="flex flex-col flex-1 overflow-hidden">
|
||||
{/* Active jobs */}
|
||||
<div className="p-3 border-b border-slate-200 dark:border-gray-800">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-amber-500">
|
||||
In Progress
|
||||
</span>
|
||||
{activeJobs.length > 0 && (
|
||||
<span className="ml-auto text-xs bg-amber-500 text-white px-1.5 py-0.5 rounded-full font-bold">
|
||||
{activeJobs.length}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{activeJobs.length === 0 ? (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 italic text-center py-2">No active jobs</p>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
{activeJobs.map((job) => (
|
||||
<ActiveJobItem key={job.id} job={job} onCancelled={invalidate} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Subsonic import */}
|
||||
<SubsonicPanel />
|
||||
|
||||
{/* Projects */}
|
||||
<div className="flex-1 overflow-y-auto p-3 space-y-1.5">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-brand-500">Projects</span>
|
||||
{projects.length > 0 && (
|
||||
<span className="ml-auto text-xs text-slate-400 dark:text-gray-600">
|
||||
{filteredProjects.length}/{projects.length}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Search box for projects */}
|
||||
<div className="relative mb-2">
|
||||
<Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-slate-400" />
|
||||
<input
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder="Search projects..."
|
||||
className="w-full rounded-md bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 pl-7 pr-2 py-1.5 text-xs text-slate-900 dark:text-gray-100 placeholder-slate-400 focus:border-brand-400 focus:outline-none"
|
||||
/>
|
||||
{searchQuery && (
|
||||
<button
|
||||
onClick={() => setSearchQuery('')}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{filteredProjects.length === 0 ? (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 italic text-center py-4">
|
||||
{searchQuery ? 'No projects match your search.' : 'Completed separations appear here.'}
|
||||
</p>
|
||||
) : (
|
||||
filteredProjects.map((project) => (
|
||||
<ProjectItem
|
||||
key={project.id}
|
||||
project={project}
|
||||
isOpen={openTabIds.includes(project.id)}
|
||||
onOpen={() => onOpenProject(project)}
|
||||
onDeleted={() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] })
|
||||
onDeleteProject(project)
|
||||
}}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
Executable
+63
@@ -0,0 +1,63 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from 'react'
|
||||
|
||||
type Theme = 'light' | 'dark' | 'system'
|
||||
|
||||
interface ThemeContextType {
|
||||
theme: Theme
|
||||
resolved: 'light' | 'dark'
|
||||
setTheme: (t: Theme) => void
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextType | undefined>(undefined)
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
const [theme, setThemeState] = useState<Theme>(() => {
|
||||
if (typeof window === 'undefined') return 'system'
|
||||
return (localStorage.getItem('theme') as Theme) || 'system'
|
||||
})
|
||||
|
||||
const [resolved, setResolved] = useState<'light' | 'dark'>('dark')
|
||||
|
||||
useEffect(() => {
|
||||
const root = document.documentElement
|
||||
const media = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
|
||||
function apply() {
|
||||
let r: 'light' | 'dark'
|
||||
if (theme === 'system') {
|
||||
r = media.matches ? 'dark' : 'light'
|
||||
} else {
|
||||
r = theme
|
||||
}
|
||||
setResolved(r)
|
||||
if (r === 'dark') {
|
||||
root.classList.add('dark')
|
||||
} else {
|
||||
root.classList.remove('dark')
|
||||
}
|
||||
}
|
||||
|
||||
apply()
|
||||
localStorage.setItem('theme', theme)
|
||||
|
||||
const listener = () => apply()
|
||||
media.addEventListener('change', listener)
|
||||
return () => media.removeEventListener('change', listener)
|
||||
}, [theme])
|
||||
|
||||
function setTheme(t: Theme) {
|
||||
setThemeState(t)
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, resolved, setTheme }}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const ctx = useContext(ThemeContext)
|
||||
if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
|
||||
return ctx
|
||||
}
|
||||
Executable
+163
@@ -0,0 +1,163 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* ── Brand color palette (default: Blue) ─────────────────────────────────────
|
||||
Values are bare RGB channels so Tailwind's opacity modifier works:
|
||||
bg-brand-500/30 → rgb(var(--brand-500) / 0.3)
|
||||
──────────────────────────────────────────────────────────────────────────── */
|
||||
:root {
|
||||
--brand-50: 239 246 255;
|
||||
--brand-100: 219 234 254;
|
||||
--brand-200: 191 219 254;
|
||||
--brand-300: 147 197 253;
|
||||
--brand-400: 96 165 250;
|
||||
--brand-500: 59 130 246;
|
||||
--brand-600: 37 99 235;
|
||||
--brand-700: 29 78 216;
|
||||
--brand-800: 30 64 175;
|
||||
--brand-900: 30 58 138;
|
||||
--brand-950: 23 37 84;
|
||||
}
|
||||
|
||||
/* ── Violet ─────────────────────────────────────────────────────────────── */
|
||||
[data-accent="violet"] {
|
||||
--brand-50: 245 243 255;
|
||||
--brand-100: 237 233 254;
|
||||
--brand-200: 221 214 254;
|
||||
--brand-300: 196 181 253;
|
||||
--brand-400: 167 139 250;
|
||||
--brand-500: 139 92 246;
|
||||
--brand-600: 124 58 237;
|
||||
--brand-700: 109 40 217;
|
||||
--brand-800: 91 33 182;
|
||||
--brand-900: 76 29 149;
|
||||
--brand-950: 46 16 101;
|
||||
}
|
||||
|
||||
/* ── Rose ────────────────────────────────────────────────────────────────── */
|
||||
[data-accent="rose"] {
|
||||
--brand-50: 255 241 242;
|
||||
--brand-100: 255 228 230;
|
||||
--brand-200: 254 205 211;
|
||||
--brand-300: 253 164 175;
|
||||
--brand-400: 251 113 133;
|
||||
--brand-500: 244 63 94;
|
||||
--brand-600: 225 29 72;
|
||||
--brand-700: 190 18 60;
|
||||
--brand-800: 159 18 57;
|
||||
--brand-900: 136 19 55;
|
||||
--brand-950: 76 5 25;
|
||||
}
|
||||
|
||||
/* ── Emerald ─────────────────────────────────────────────────────────────── */
|
||||
[data-accent="emerald"] {
|
||||
--brand-50: 236 253 245;
|
||||
--brand-100: 209 250 229;
|
||||
--brand-200: 167 243 208;
|
||||
--brand-300: 110 231 183;
|
||||
--brand-400: 52 211 153;
|
||||
--brand-500: 16 185 129;
|
||||
--brand-600: 5 150 105;
|
||||
--brand-700: 4 120 87;
|
||||
--brand-800: 6 95 70;
|
||||
--brand-900: 6 78 59;
|
||||
--brand-950: 2 44 34;
|
||||
}
|
||||
|
||||
/* ── Amber ───────────────────────────────────────────────────────────────── */
|
||||
[data-accent="amber"] {
|
||||
--brand-50: 255 251 235;
|
||||
--brand-100: 254 243 199;
|
||||
--brand-200: 253 230 138;
|
||||
--brand-300: 252 211 77;
|
||||
--brand-400: 251 191 36;
|
||||
--brand-500: 245 158 11;
|
||||
--brand-600: 217 119 6;
|
||||
--brand-700: 180 83 9;
|
||||
--brand-800: 146 64 14;
|
||||
--brand-900: 120 53 15;
|
||||
--brand-950: 69 26 3;
|
||||
}
|
||||
|
||||
/* ── Cyan ────────────────────────────────────────────────────────────────── */
|
||||
[data-accent="cyan"] {
|
||||
--brand-50: 236 254 255;
|
||||
--brand-100: 207 250 254;
|
||||
--brand-200: 165 243 252;
|
||||
--brand-300: 103 232 249;
|
||||
--brand-400: 34 211 238;
|
||||
--brand-500: 6 182 212;
|
||||
--brand-600: 8 145 178;
|
||||
--brand-700: 14 116 144;
|
||||
--brand-800: 21 94 117;
|
||||
--brand-900: 22 78 99;
|
||||
--brand-950: 8 51 68;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
html {
|
||||
@apply h-full;
|
||||
}
|
||||
body {
|
||||
@apply h-full antialiased;
|
||||
}
|
||||
#root {
|
||||
@apply h-full;
|
||||
}
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.sidebar-open {
|
||||
@apply w-72;
|
||||
}
|
||||
.sidebar-closed {
|
||||
@apply w-14;
|
||||
}
|
||||
}
|
||||
|
||||
/* On small screens the sidebar overlays content instead of pushing it */
|
||||
@media (max-width: 639px) {
|
||||
.sidebar-open {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
z-index: 30;
|
||||
width: theme('spacing.72');
|
||||
}
|
||||
.sidebar-closed {
|
||||
width: theme('spacing.10');
|
||||
}
|
||||
}
|
||||
|
||||
/* Custom scrollbar */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
@apply bg-transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
@apply bg-slate-300 dark:bg-gray-600 rounded-full;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
@apply bg-slate-400 dark:bg-gray-500;
|
||||
}
|
||||
|
||||
/* Range input styling */
|
||||
input[type="range"] {
|
||||
@apply bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer;
|
||||
}
|
||||
|
||||
input[type="range"]::-webkit-slider-thumb {
|
||||
@apply appearance-none w-4 h-4 rounded-full bg-brand-500 cursor-pointer;
|
||||
}
|
||||
|
||||
input[type="range"]::-moz-range-thumb {
|
||||
@apply w-4 h-4 rounded-full bg-brand-500 cursor-pointer border-0;
|
||||
}
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import App from './App'
|
||||
import './index.css'
|
||||
import '@fontsource/archivo'
|
||||
import '@fontsource/eb-garamond'
|
||||
import '@fontsource/inter'
|
||||
import '@fontsource/libre-baskerville'
|
||||
import '@fontsource/oswald'
|
||||
import '@fontsource/poppins'
|
||||
import '@fontsource/roboto'
|
||||
import '@fontsource/work-sans'
|
||||
import '@fontsource/young-serif'
|
||||
|
||||
if ('serviceWorker' in navigator) {
|
||||
window.addEventListener('load', () => {
|
||||
navigator.serviceWorker.register('/sw.js').catch(() => {/* SW registration is best-effort */})
|
||||
})
|
||||
}
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 5000,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
Executable
+2312
File diff suppressed because it is too large.
Load diff
Executable
+501
@@ -0,0 +1,501 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { RefreshCw, Radio, Zap } from 'lucide-react'
|
||||
import FileUpload from '../components/FileUpload'
|
||||
import JobStatus from '../components/JobStatus'
|
||||
import ResultFiles from '../components/ResultFiles'
|
||||
import AutoPipelineDialog from '../components/AutoPipelineDialog'
|
||||
import {
|
||||
getSepModels, getSepFormats, getPresets, submitSeparate, extractLyrics,
|
||||
listImports, submitSeparateFromPath,
|
||||
} from '../api/client'
|
||||
import type { Job, ModelOption, PresetsResponse, DynamicLevels, ImportedFile } from '../types'
|
||||
|
||||
const SELECT_CLS = 'w-full rounded-lg bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-3 py-2 text-sm text-slate-900 dark:text-gray-100 focus:border-brand-500 focus:outline-none'
|
||||
const INPUT_CLS = 'w-full rounded-lg bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-3 py-2 text-sm text-slate-900 dark:text-gray-100 focus:border-brand-500 focus:outline-none'
|
||||
const SLIDER_CLS = 'w-full h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-600'
|
||||
|
||||
function groupModels(models: ModelOption[]) {
|
||||
const groups: Record<string, ModelOption[]> = {}
|
||||
for (const m of models) {
|
||||
const g = m.group ?? 'Other'
|
||||
if (!groups[g]) groups[g] = []
|
||||
groups[g].push(m)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
const DEFAULT_DYNAMIC_LEVELS: DynamicLevels = {
|
||||
vocals: 1.0,
|
||||
drums: 1.0,
|
||||
bass: 1.0,
|
||||
other: 1.0,
|
||||
}
|
||||
|
||||
interface Props {
|
||||
onSeparationComplete?: (projectId: string, tabLabel: string, projectName: string) => void
|
||||
onOpenSettings?: () => void
|
||||
}
|
||||
|
||||
export default function Separator({ onSeparationComplete, onOpenSettings }: Props) {
|
||||
const [inputMode, setInputMode] = useState<'upload' | 'imported'>('upload')
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
const [importedFile, setImportedFile] = useState<ImportedFile | null>(null)
|
||||
const [model, setModel] = useState('htdemucs')
|
||||
const [format, setFormat] = useState('mp3')
|
||||
const [presetType, setPresetType] = useState('stems_only')
|
||||
const [staticOption, setStaticOption] = useState('no_vocals')
|
||||
const [dynamicLevels, setDynamicLevels] = useState<DynamicLevels>(DEFAULT_DYNAMIC_LEVELS)
|
||||
const [projectName, setProjectName] = useState('')
|
||||
const [metadata, setMetadata] = useState<{artist?: string; title?: string}>({})
|
||||
const [jobId, setJobId] = useState<string | null>(null)
|
||||
const [result, setResult] = useState<Job | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [showAuto, setShowAuto] = useState(false)
|
||||
|
||||
const { data: models = [] } = useQuery({ queryKey: ['sep-models'], queryFn: getSepModels })
|
||||
const { data: formats = [] } = useQuery({ queryKey: ['sep-formats'], queryFn: getSepFormats })
|
||||
const { data: presets } = useQuery<PresetsResponse>({ queryKey: ['sep-presets'], queryFn: getPresets })
|
||||
const { data: imports = [], refetch: refetchImports } = useQuery<ImportedFile[]>({
|
||||
queryKey: ['imports'],
|
||||
queryFn: listImports,
|
||||
enabled: inputMode === 'imported',
|
||||
refetchInterval: inputMode === 'imported' ? 5000 : false,
|
||||
})
|
||||
|
||||
const grouped = groupModels(models)
|
||||
|
||||
// Read layout preferences saved in Settings → Model Settings
|
||||
const hiddenGroups = new Set<string>((() => {
|
||||
try { return JSON.parse(localStorage.getItem('se-model-hidden-groups') || '[]') as string[] }
|
||||
catch { return [] }
|
||||
})())
|
||||
const hiddenModels = new Set<string>((() => {
|
||||
try { return JSON.parse(localStorage.getItem('se-model-hidden-models') || '[]') as string[] }
|
||||
catch { return [] }
|
||||
})())
|
||||
const groupOrder: string[] = (() => {
|
||||
try { return JSON.parse(localStorage.getItem('se-model-group-order') || 'null') || [] }
|
||||
catch { return [] }
|
||||
})()
|
||||
const modelOrder: Record<string, string[]> = (() => {
|
||||
try { return JSON.parse(localStorage.getItem('se-model-model-order') || 'null') || {} }
|
||||
catch { return {} }
|
||||
})()
|
||||
|
||||
// Build visible + ordered groups (mirrors Settings ModelDownloader logic)
|
||||
const allGroupNames = Object.keys(grouped)
|
||||
const orderedGroupNames = [
|
||||
...groupOrder.filter(g => allGroupNames.includes(g)),
|
||||
...allGroupNames.filter(g => !groupOrder.includes(g)),
|
||||
]
|
||||
const visibleGrouped: Record<string, ModelOption[]> = {}
|
||||
for (const group of orderedGroupNames) {
|
||||
if (hiddenGroups.has(group)) continue
|
||||
const rawModels = grouped[group] || []
|
||||
const order = modelOrder[group] || rawModels.map(m => m.id)
|
||||
const ids = rawModels.map(m => m.id)
|
||||
const sorted = [
|
||||
...order.filter(id => ids.includes(id)).map(id => rawModels.find(m => m.id === id)!),
|
||||
...rawModels.filter(m => !order.includes(m.id)),
|
||||
]
|
||||
const visible = sorted.filter(m => !hiddenModels.has(m.id))
|
||||
if (visible.length > 0) visibleGrouped[group] = visible
|
||||
}
|
||||
|
||||
const rawGroup = models.find(m => m.id === model)?.group
|
||||
const selectedGroup = (rawGroup && visibleGrouped[rawGroup])
|
||||
? rawGroup
|
||||
: Object.keys(visibleGrouped)[0] ?? ''
|
||||
const isBSR = model.startsWith('bs_roformer_')
|
||||
|
||||
function handleGroupChange(group: string) {
|
||||
const first = visibleGrouped[group]?.[0]
|
||||
if (first) setModel(first.id)
|
||||
}
|
||||
|
||||
// Reset selected model when it becomes hidden/invisible
|
||||
useEffect(() => {
|
||||
if (!models.length) return
|
||||
const foundGroup = models.find(m => m.id === model)?.group
|
||||
const isVisible = foundGroup && visibleGrouped[foundGroup]?.some(m => m.id === model)
|
||||
if (!isVisible) {
|
||||
const firstGroup = Object.keys(visibleGrouped)[0]
|
||||
const firstModel = firstGroup ? visibleGrouped[firstGroup]?.[0] : undefined
|
||||
if (firstModel) setModel(firstModel.id)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [models])
|
||||
|
||||
// Fire callback when a separation job completes
|
||||
const firedRef = useRef<string | null>(null)
|
||||
useEffect(() => {
|
||||
if (
|
||||
result?.status === 'done' &&
|
||||
result.result?.project_id &&
|
||||
result.result?.tab_label &&
|
||||
onSeparationComplete &&
|
||||
firedRef.current !== result.id
|
||||
) {
|
||||
firedRef.current = result.id
|
||||
onSeparationComplete(
|
||||
result.result.project_id,
|
||||
result.result.tab_label,
|
||||
result.result.project_name ?? '',
|
||||
)
|
||||
}
|
||||
}, [result, onSeparationComplete])
|
||||
|
||||
// Extract metadata when file changes
|
||||
useEffect(() => {
|
||||
if (!file) {
|
||||
setMetadata({})
|
||||
setProjectName('')
|
||||
return
|
||||
}
|
||||
|
||||
// Try to extract metadata from the file
|
||||
extractLyrics(file).then(() => {
|
||||
// Use filename as fallback
|
||||
const filename = file.name.replace(/\.[^/.]+$/, '')
|
||||
setMetadata({ artist: '', title: filename })
|
||||
}).catch(() => {
|
||||
const filename = file.name.replace(/\.[^/.]+$/, '')
|
||||
setMetadata({ artist: '', title: filename })
|
||||
})
|
||||
}, [file])
|
||||
|
||||
// Auto-generate project name from metadata
|
||||
useEffect(() => {
|
||||
if (metadata.artist && metadata.title) {
|
||||
setProjectName(`${metadata.artist} - ${metadata.title}`)
|
||||
} else if (metadata.title) {
|
||||
setProjectName(metadata.title)
|
||||
} else if (file) {
|
||||
setProjectName(file.name.replace(/\.[^/.]+$/, ''))
|
||||
}
|
||||
}, [metadata, file])
|
||||
|
||||
async function submit() {
|
||||
if (inputMode === 'upload' && !file) return
|
||||
if (inputMode === 'imported' && !importedFile) return
|
||||
setError(null); setResult(null); setJobId(null); setLoading(true)
|
||||
try {
|
||||
const sepPowerPreset = localStorage.getItem('stemengine-sep-power') ?? 'standard'
|
||||
const opts = {
|
||||
presetType,
|
||||
projectName: projectName || undefined,
|
||||
staticOption: presetType === 'static' ? staticOption : undefined,
|
||||
dynamicLevels: presetType === 'dynamic' ? dynamicLevels : undefined,
|
||||
sepPowerPreset,
|
||||
}
|
||||
|
||||
let job_id: string
|
||||
if (inputMode === 'imported' && importedFile) {
|
||||
const res = await submitSeparateFromPath(importedFile.path, model, format, opts)
|
||||
job_id = res.job_id
|
||||
} else {
|
||||
const res = await submitSeparate(file!, model, format, opts)
|
||||
job_id = res.job_id
|
||||
}
|
||||
setJobId(job_id)
|
||||
} catch (e) {
|
||||
setError(String(e))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDynamicChange = (stem: keyof DynamicLevels, value: number) => {
|
||||
setDynamicLevels(prev => ({ ...prev, [stem]: value }))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-1">Stem Separator</h2>
|
||||
<p className="text-sm text-slate-500 dark:text-gray-400">
|
||||
Separate an audio track into individual stems using Demucs, BS-RoFormer, MelBand, or MDX-Net.
|
||||
Create presets like Instrumental, Static mixes, or Dynamic volume-adjusted mixes.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Input mode toggle */}
|
||||
<div className="flex rounded-lg border border-slate-200 dark:border-gray-700 overflow-hidden">
|
||||
<button
|
||||
onClick={() => setInputMode('upload')}
|
||||
className={`flex-1 py-2 text-xs font-medium transition-colors ${
|
||||
inputMode === 'upload'
|
||||
? 'bg-brand-600 text-white'
|
||||
: 'bg-white dark:bg-gray-900 text-slate-600 dark:text-gray-400 hover:bg-slate-50 dark:hover:bg-gray-800'
|
||||
}`}
|
||||
>
|
||||
Upload File
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setInputMode('imported'); refetchImports() }}
|
||||
className={`flex-1 py-2 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${
|
||||
inputMode === 'imported'
|
||||
? 'bg-sky-600 text-white'
|
||||
: 'bg-white dark:bg-gray-900 text-slate-600 dark:text-gray-400 hover:bg-slate-50 dark:hover:bg-gray-800'
|
||||
}`}
|
||||
>
|
||||
<Radio className="w-3 h-3" />
|
||||
Imported Files
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{inputMode === 'upload' && (
|
||||
<>
|
||||
<FileUpload
|
||||
label="Drop an audio file here, or click to select (MP3, FLAC, WAV, OGG…)"
|
||||
accept="audio/*"
|
||||
onFiles={([f]) => { setFile(f); setJobId(null); setResult(null) }}
|
||||
/>
|
||||
{file && (
|
||||
<div className="rounded-lg border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800/50 px-4 py-3">
|
||||
<p className="text-sm font-medium text-slate-700 dark:text-gray-300">
|
||||
Selected: {file.name}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{inputMode === 'imported' && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Select imported file</span>
|
||||
<button
|
||||
onClick={() => refetchImports()}
|
||||
title="Refresh"
|
||||
className="p-1 rounded text-slate-400 hover:text-brand-500 transition-colors"
|
||||
>
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{imports.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-slate-200 dark:border-gray-700 px-4 py-6 text-center">
|
||||
<Radio className="w-6 h-6 text-slate-300 dark:text-gray-600 mx-auto mb-2" />
|
||||
<p className="text-sm text-slate-400 dark:text-gray-600">No imported files yet.</p>
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 mt-1">Use the Subsonic panel in the sidebar to import songs.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1 max-h-48 overflow-y-auto rounded-lg border border-slate-200 dark:border-gray-700">
|
||||
{imports.map((f) => (
|
||||
<button
|
||||
key={f.path}
|
||||
onClick={() => {
|
||||
setImportedFile(f)
|
||||
setProjectName(f.filename.replace(/\.[^/.]+$/, ''))
|
||||
setJobId(null); setResult(null)
|
||||
}}
|
||||
className={`w-full flex items-start gap-2 px-3 py-2 text-left transition-colors ${
|
||||
importedFile?.path === f.path
|
||||
? 'bg-sky-50 dark:bg-sky-950/30 border-l-2 border-sky-500'
|
||||
: 'hover:bg-slate-50 dark:hover:bg-gray-800/50'
|
||||
}`}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">{f.filename}</p>
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500">
|
||||
{(f.size / 1024 / 1024).toFixed(1)} MB
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Model Family</span>
|
||||
<select value={selectedGroup} onChange={(e) => handleGroupChange(e.target.value)} className={SELECT_CLS}>
|
||||
{Object.keys(visibleGrouped).map((g) => (
|
||||
<option key={g} value={g}>{g}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Model</span>
|
||||
<select value={model} onChange={(e) => setModel(e.target.value)} className={SELECT_CLS}>
|
||||
{(visibleGrouped[selectedGroup] ?? []).map((m) => (
|
||||
<option key={m.id} value={m.id}>{m.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Output Format</span>
|
||||
<select value={format} onChange={(e) => setFormat(e.target.value)} className={SELECT_CLS}>
|
||||
{formats.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{isBSR && (
|
||||
<div className="rounded-lg border border-purple-300 dark:border-purple-800 bg-purple-50 dark:bg-purple-950/30 px-4 py-3 text-xs text-purple-700 dark:text-purple-300 space-y-1">
|
||||
<p className="font-semibold">BS-RoFormer selected</p>
|
||||
<p>State-of-the-art transformer model. Runs in-process — may take longer on CPU.</p>
|
||||
<ul className="list-disc list-inside mt-1 space-y-0.5 text-purple-600 dark:text-purple-400">
|
||||
<li><strong>4-stem</strong> — vocals · drums · bass · other</li>
|
||||
<li><strong>5-stem (guitar)</strong> — + guitar as separate stem</li>
|
||||
<li><strong>5-stem (piano)</strong> — + piano as separate stem</li>
|
||||
<li><strong>6-stem (full)</strong> — vocals · drums · bass · guitar · piano · other</li>
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project Name */}
|
||||
<div className="space-y-2">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Project Name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={projectName}
|
||||
onChange={(e) => setProjectName(e.target.value)}
|
||||
placeholder="Artist - Title"
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">
|
||||
Used for folder naming. Auto-generated from metadata if available.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Preset Type */}
|
||||
<div className="space-y-3">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Output Preset</span>
|
||||
<select value={presetType} onChange={(e) => setPresetType(e.target.value)} className={SELECT_CLS}>
|
||||
{presets?.preset_types.map((p) => (
|
||||
<option key={p.id} value={p.id}>{p.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">
|
||||
{presets?.preset_types.find(p => p.id === presetType)?.description}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Static Options */}
|
||||
{presetType === 'static' && (
|
||||
<div className="space-y-3 rounded-lg border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800/50 p-4">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Remove Elements</span>
|
||||
<select value={staticOption} onChange={(e) => setStaticOption(e.target.value)} className={SELECT_CLS}>
|
||||
{presets?.static_options.map((o) => (
|
||||
<option key={o.id} value={o.id}>{o.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">
|
||||
{presets?.static_options.find(o => o.id === staticOption)?.description}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Dynamic Options */}
|
||||
{presetType === 'dynamic' && (
|
||||
<div className="space-y-4 rounded-lg border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800/50 p-4">
|
||||
<p className="text-sm font-medium text-slate-700 dark:text-gray-300">Volume Levels</p>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">Adjust the volume of each stem (0 = mute, 1 = original, 2 = double)</p>
|
||||
|
||||
{Object.entries(dynamicLevels).map(([stem, value]) => (
|
||||
<div key={stem} className="space-y-1">
|
||||
<div className="flex justify-between items-center">
|
||||
<label className="text-sm capitalize text-slate-700 dark:text-gray-300">{stem}</label>
|
||||
<span className="text-sm text-slate-500 dark:text-gray-400">{Math.round(value * 100)}%</span>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="2"
|
||||
step="0.1"
|
||||
value={value}
|
||||
onChange={(e) => handleDynamicChange(stem as keyof DynamicLevels, parseFloat(e.target.value))}
|
||||
className={SLIDER_CLS}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Preset Preview */}
|
||||
{presetType !== 'stems_only' && (
|
||||
<div className="rounded-lg border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-950/30 px-4 py-3 text-sm text-blue-700 dark:text-blue-300">
|
||||
<p className="font-medium">Output Structure Preview:</p>
|
||||
<code className="block mt-2 text-xs whitespace-pre text-blue-600 dark:text-blue-400">
|
||||
{projectName || 'Project Name'}/
|
||||
{'\n'} Stems/ (always created)
|
||||
{presetType === 'instrumental' && "\n Instrumental/ (vocals removed)"}
|
||||
{presetType === 'static' && `\n Static/ (${presets?.static_options.find(o => o.id === staticOption)?.label})`}
|
||||
{presetType === 'dynamic' && "\n Dynamic/ (volume adjusted mix)"}
|
||||
</code>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <p className="text-sm text-red-500 dark:text-red-400">{error}</p>}
|
||||
|
||||
<button
|
||||
onClick={submit}
|
||||
disabled={(inputMode === 'upload' ? !file : !importedFile) || loading}
|
||||
className="w-full rounded-lg bg-brand-600 hover:bg-brand-500 disabled:bg-slate-200 disabled:text-slate-400 dark:disabled:bg-gray-800 dark:disabled:text-gray-500 px-4 py-2.5 text-sm font-semibold text-white disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
{loading ? 'Submitting…' : presetType === 'stems_only' ? 'Separate Stems' : `Separate & Create ${presets?.preset_types.find(p => p.id === presetType)?.label}`}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setShowAuto(true)}
|
||||
disabled={(inputMode === 'upload' ? !file : !importedFile)}
|
||||
className="w-full rounded-lg border border-amber-400 dark:border-amber-600 bg-amber-50 dark:bg-amber-950/30 hover:bg-amber-100 dark:hover:bg-amber-900/40 disabled:opacity-40 disabled:cursor-not-allowed px-4 py-2.5 text-sm font-semibold text-amber-700 dark:text-amber-400 transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
<Zap className="w-4 h-4" />
|
||||
Auto Pipeline
|
||||
</button>
|
||||
|
||||
{showAuto && (
|
||||
<AutoPipelineDialog
|
||||
target={{
|
||||
file: inputMode === 'upload' ? file ?? undefined : undefined,
|
||||
filePath: inputMode === 'imported' ? importedFile?.path : undefined,
|
||||
filename: inputMode === 'upload'
|
||||
? (file?.name ?? '')
|
||||
: (importedFile?.filename ?? ''),
|
||||
initialModel: model,
|
||||
initialFormat: format,
|
||||
initialProjectName: projectName || undefined,
|
||||
}}
|
||||
onClose={() => setShowAuto(false)}
|
||||
onComplete={(projectId, name) => {
|
||||
setShowAuto(false)
|
||||
onSeparationComplete?.(projectId, `Auto Pipeline`, name)
|
||||
}}
|
||||
onOpenSettings={onOpenSettings}
|
||||
/>
|
||||
)}
|
||||
|
||||
{jobId && <JobStatus jobId={jobId} onDone={setResult} />}
|
||||
{result && (
|
||||
<div className="space-y-4">
|
||||
{result.result?.project_name && (
|
||||
<div className="rounded-lg border border-green-200 dark:border-green-800 bg-green-50 dark:bg-green-950/30 px-4 py-3">
|
||||
<p className="text-sm font-medium text-green-800 dark:text-green-300">
|
||||
Project: {result.result.project_name}
|
||||
</p>
|
||||
<p className="text-xs text-green-600 dark:text-green-400 mt-1">
|
||||
Location: {result.result.project_path}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<ResultFiles jobId={result.id} files={result.files} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Executable
+2135
File diff suppressed because it is too large.
Load diff
Executable
+181
@@ -0,0 +1,181 @@
|
||||
export type JobStatus = 'queued' | 'running' | 'done' | 'error' | 'cancelled'
|
||||
|
||||
export interface JobFile {
|
||||
name: string
|
||||
path: string
|
||||
stage?: string // 'separation' | 'transcription' | 'abc' | 'elrc'
|
||||
type?: string // 'stem' | 'instrumental' | 'static' | 'dynamic' | 'lrc' | 'elrc' | 'source'
|
||||
stem?: string // stem name for stem files
|
||||
}
|
||||
|
||||
export interface Job {
|
||||
id: string
|
||||
job_type: 'separate' | 'transcribe' | 'abc-convert' | 'pipeline' | 'lrc_align' | 'mix' | 'lyric-transcribe'
|
||||
status: JobStatus
|
||||
progress: string
|
||||
error: string
|
||||
files: JobFile[]
|
||||
result?: {
|
||||
project_name?: string
|
||||
project_path?: string
|
||||
stems_dir?: string
|
||||
transcriptions_dir?: string
|
||||
model_label?: string
|
||||
format_label?: string
|
||||
tab_label?: string
|
||||
project_id?: string
|
||||
}
|
||||
created_at: string | null
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
export interface ModelOption {
|
||||
id: string
|
||||
label: string
|
||||
group?: string // 'Demucs' | 'BS-RoFormer' | 'MDX-Net' | 'MelBand'
|
||||
}
|
||||
|
||||
export interface PerInstrumentModel {
|
||||
id: string
|
||||
label: string
|
||||
instrument: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface ModeOption {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface FormatOption {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
// Preset types
|
||||
export interface PresetType {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface StaticOption {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface PresetsResponse {
|
||||
preset_types: PresetType[]
|
||||
static_options: StaticOption[]
|
||||
}
|
||||
|
||||
// Dynamic preset volume levels
|
||||
export interface DynamicLevels {
|
||||
vocals?: number
|
||||
drums?: number
|
||||
bass?: number
|
||||
other?: number
|
||||
guitar?: number
|
||||
piano?: number
|
||||
}
|
||||
|
||||
// LRC/Lyrics types
|
||||
export interface LyricsSource {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface LyricsData {
|
||||
source: string
|
||||
synced: boolean
|
||||
lyrics: string
|
||||
raw: string
|
||||
}
|
||||
|
||||
// Subsonic integration
|
||||
export interface SubsonicSong {
|
||||
id: string
|
||||
title: string
|
||||
artist: string
|
||||
album: string
|
||||
duration: number
|
||||
suffix: string
|
||||
size: number
|
||||
bitRate: number
|
||||
}
|
||||
|
||||
export interface SubsonicConfig {
|
||||
configured: boolean
|
||||
url?: string
|
||||
username?: string
|
||||
}
|
||||
|
||||
export interface ImportedFile {
|
||||
filename: string
|
||||
path: string
|
||||
size: number
|
||||
title?: string
|
||||
artist?: string
|
||||
}
|
||||
|
||||
// Model download types
|
||||
export interface ModelDownloadInfo {
|
||||
id: string
|
||||
label: string
|
||||
group: string
|
||||
description: string
|
||||
size_mb: number
|
||||
status: 'not_downloaded' | 'downloaded' | 'downloading' | 'paused' | 'error' | 'cancelled'
|
||||
progress_percent: number
|
||||
}
|
||||
|
||||
export interface ModelDownloadProgress {
|
||||
model_id: string
|
||||
status: string
|
||||
progress_percent: number
|
||||
bytes_downloaded: number
|
||||
total_bytes: number
|
||||
speed_mbps: number
|
||||
error_message?: string
|
||||
}
|
||||
|
||||
// Project management
|
||||
export interface Project {
|
||||
id: string
|
||||
name: string
|
||||
tab_label: string // display label for tab e.g. "Demucs v4_MP3 (256 kbps)"
|
||||
created_at: string | null
|
||||
sep_job_id: string
|
||||
trans_jobs: Record<string, string> // stem_name → job_id
|
||||
abc_jobs: Record<string, string> // stem_name → job_id
|
||||
lrc_jobs: Record<string, string> // stem_name → job_id
|
||||
mix_job_id: string | null
|
||||
}
|
||||
|
||||
export interface ProjectDetail {
|
||||
id: string
|
||||
name: string
|
||||
created_at: string | null
|
||||
sep_job_id: string
|
||||
trans_jobs: Record<string, Job> // stem_name → expanded Job
|
||||
abc_jobs: Record<string, Job> // stem_name → expanded Job
|
||||
lrc_jobs: Record<string, Job> // stem_name → expanded Job
|
||||
mix_job_id: string | null
|
||||
sep_job: Job
|
||||
mix_job: Job | null
|
||||
source_artist?: string
|
||||
source_title?: string
|
||||
}
|
||||
|
||||
// Lyrics Style options
|
||||
export interface LyricsStyleOptions {
|
||||
fontFamily: string
|
||||
fontSize: number
|
||||
textColor: string
|
||||
highlightColor: string
|
||||
backgroundColor: string
|
||||
wordHighlightColor: string
|
||||
lineSpacing: number
|
||||
textAlign: 'left' | 'center' | 'right'
|
||||
}
|
||||
Executable
+113
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Global audio playback registry.
|
||||
*
|
||||
* Only one audio player should be playing at a time. When a player starts,
|
||||
* it registers a stop callback here. Any previously registered callback is
|
||||
* called first, pausing the old player before the new one starts.
|
||||
*
|
||||
* Players also publish live state so the GlobalAudioBar can reflect playback
|
||||
* position, title and play/pause status across page navigation.
|
||||
*/
|
||||
|
||||
type StopFn = () => void
|
||||
|
||||
export interface PlaybackMeta {
|
||||
title: string
|
||||
isPlaying: boolean
|
||||
currentTime: number
|
||||
duration: number
|
||||
volume: number
|
||||
}
|
||||
|
||||
export interface PlaybackActions {
|
||||
toggle: () => void
|
||||
seek: (t: number) => void
|
||||
setVolume: (v: number) => void
|
||||
}
|
||||
|
||||
let _current: StopFn | null = null
|
||||
|
||||
// Mutable singleton — players overwrite toggle/seek/setVolume in-place each render,
|
||||
// so the bar always invokes the freshest closures without any ref gymnastics.
|
||||
const _actions: PlaybackActions = { toggle: () => {}, seek: () => {}, setVolume: () => {} }
|
||||
|
||||
let _meta: PlaybackMeta | null = null
|
||||
const _listeners = new Set<() => void>()
|
||||
|
||||
// ── Stop / unregister ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Call this when a player begins playback.
|
||||
* The previously active player (if any) will be stopped.
|
||||
*/
|
||||
export function registerPlayback(stop: StopFn): void {
|
||||
if (_current && _current !== stop) {
|
||||
_current()
|
||||
}
|
||||
_current = stop
|
||||
}
|
||||
|
||||
/**
|
||||
* Call this when a player unmounts or hard-resets so the registry no
|
||||
* longer holds a stale reference. Do NOT call on simple pause — let the
|
||||
* registry keep holding the player so the bar stays visible.
|
||||
*/
|
||||
export function unregisterPlayback(stop: StopFn): void {
|
||||
if (_current === stop) {
|
||||
_current = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop and dismiss the active player from anywhere (e.g. the global bar's ✕).
|
||||
* Calls the registered stop callback (which pauses audio and clears meta),
|
||||
* then removes the reference so the next player starts fresh.
|
||||
*/
|
||||
export function stopCurrent(): void {
|
||||
if (_current) {
|
||||
_current()
|
||||
_current = null
|
||||
}
|
||||
}
|
||||
|
||||
// ── Bar state ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Players call this whenever their state changes (play, pause, seek, RAF tick).
|
||||
* The mutable _actions singleton is updated in-place so the bar always has
|
||||
* fresh callbacks without needing extra refs.
|
||||
*/
|
||||
export function publishMeta(meta: PlaybackMeta, actions: PlaybackActions): void {
|
||||
_meta = meta
|
||||
_actions.toggle = actions.toggle
|
||||
_actions.seek = actions.seek
|
||||
_actions.setVolume = actions.setVolume
|
||||
_listeners.forEach(l => l())
|
||||
}
|
||||
|
||||
/**
|
||||
* Call this when the player is forcibly stopped (registry takeover) or unmounts.
|
||||
* Simple pause should NOT clear — the bar stays visible showing paused state.
|
||||
*/
|
||||
export function clearMeta(): void {
|
||||
if (_meta !== null) {
|
||||
_meta = null
|
||||
_listeners.forEach(l => l())
|
||||
}
|
||||
}
|
||||
|
||||
export function getMeta(): PlaybackMeta | null {
|
||||
return _meta
|
||||
}
|
||||
|
||||
export function getActions(): PlaybackActions {
|
||||
return _actions
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to bar state changes. Returns an unsubscribe function.
|
||||
*/
|
||||
export function subscribePlayback(listener: () => void): () => void {
|
||||
_listeners.add(listener)
|
||||
return () => _listeners.delete(listener)
|
||||
}
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Shared types and localStorage helpers for the Auto Pipeline feature.
|
||||
* Both Settings.tsx (configuration) and AutoPipelineDialog.tsx (execution) import from here.
|
||||
*/
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface AutoStepReprocess {
|
||||
type: 'reprocess'
|
||||
stem: string // e.g. 'other', 'vocals', 'drums'
|
||||
model: string // model id, e.g. 'mel_band_roformer_4stem'
|
||||
}
|
||||
|
||||
export interface AutoStepMidi {
|
||||
type: 'midi'
|
||||
mode: 'polyphonic' | 'melody'
|
||||
}
|
||||
|
||||
export interface AutoStepLyrics {
|
||||
type: 'lyrics'
|
||||
whisperModel: string // e.g. 'large-v2'
|
||||
diarize: boolean
|
||||
lsyncAlign: boolean // use lsync wav2vec2 CTC + pyphen for syllable-level timestamps
|
||||
twoPass: boolean // run a second VAD pass to fill transcription gaps > 2 s
|
||||
vocalStyle: string // 'general' | 'hiphop'
|
||||
explicit: boolean // disable Whisper's profanity filter via initial_prompt primer
|
||||
}
|
||||
|
||||
export interface AutoStepLyricsAlign {
|
||||
type: 'lyricsAlign'
|
||||
timingPrecision: 'word' | 'syllable' // word-level or syllable-level ELRC
|
||||
}
|
||||
|
||||
export type AutoStep = AutoStepReprocess | AutoStepMidi | AutoStepLyrics | AutoStepLyricsAlign
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Preset types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface AutoPreset {
|
||||
name: string
|
||||
model: string
|
||||
format: string
|
||||
steps: AutoStep[]
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// localStorage keys
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const LS_AUTO_MODEL = 'se-auto-model'
|
||||
export const LS_AUTO_FORMAT = 'se-auto-format'
|
||||
export const LS_AUTO_STEPS = 'se-auto-steps'
|
||||
export const LS_AUTO_PRESETS = 'se-auto-presets'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Readers / writers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function readAutoModel(): string { return localStorage.getItem(LS_AUTO_MODEL) ?? 'htdemucs' }
|
||||
export function readAutoFormat(): string { return localStorage.getItem(LS_AUTO_FORMAT) ?? 'mp3' }
|
||||
|
||||
export function readAutoSteps(): AutoStep[] {
|
||||
try { return JSON.parse(localStorage.getItem(LS_AUTO_STEPS) || '[]') as AutoStep[] }
|
||||
catch { return [] }
|
||||
}
|
||||
|
||||
export function writeAutoSteps(steps: AutoStep[]): void {
|
||||
localStorage.setItem(LS_AUTO_STEPS, JSON.stringify(steps))
|
||||
}
|
||||
|
||||
export function readAutoPresets(): AutoPreset[] {
|
||||
try { return JSON.parse(localStorage.getItem(LS_AUTO_PRESETS) || '[]') as AutoPreset[] }
|
||||
catch { return [] }
|
||||
}
|
||||
|
||||
export function writeAutoPresets(presets: AutoPreset[]): void {
|
||||
localStorage.setItem(LS_AUTO_PRESETS, JSON.stringify(presets))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Step display helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function stepLabel(step: AutoStep): string {
|
||||
switch (step.type) {
|
||||
case 'reprocess': return `Reprocess "${step.stem}" stem`
|
||||
case 'midi': return `MIDI Transcription (${step.mode})`
|
||||
case 'lyrics': return `AI Transcribe — WhisperX ${step.whisperModel}`
|
||||
case 'lyricsAlign': return `Lyrics Align — ${step.timingPrecision}-level`
|
||||
}
|
||||
}
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: [
|
||||
"./index.html",
|
||||
"./src/**/*.{js,ts,jsx,tsx}",
|
||||
],
|
||||
darkMode: 'class',
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
// Each shade references a CSS custom property holding bare RGB channels
|
||||
// so Tailwind's opacity modifier syntax (bg-brand-500/30) keeps working.
|
||||
brand: {
|
||||
50: 'rgb(var(--brand-50) / <alpha-value>)',
|
||||
100: 'rgb(var(--brand-100) / <alpha-value>)',
|
||||
200: 'rgb(var(--brand-200) / <alpha-value>)',
|
||||
300: 'rgb(var(--brand-300) / <alpha-value>)',
|
||||
400: 'rgb(var(--brand-400) / <alpha-value>)',
|
||||
500: 'rgb(var(--brand-500) / <alpha-value>)',
|
||||
600: 'rgb(var(--brand-600) / <alpha-value>)',
|
||||
700: 'rgb(var(--brand-700) / <alpha-value>)',
|
||||
800: 'rgb(var(--brand-800) / <alpha-value>)',
|
||||
900: 'rgb(var(--brand-900) / <alpha-value>)',
|
||||
950: 'rgb(var(--brand-950) / <alpha-value>)',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { resolve } from 'path'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
build: {
|
||||
outDir: '../backend/static',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': resolve(__dirname, './src'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:8000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
Generated
+117
@@ -17,6 +17,7 @@
|
||||
"@fontsource/roboto": "^5.0.0",
|
||||
"@fontsource/work-sans": "^5.0.0",
|
||||
"@fontsource/young-serif": "^5.0.0",
|
||||
"@olton/metroui": "^5.1.20",
|
||||
"@tanstack/react-query": "^5.0.0",
|
||||
"@tonejs/midi": "^2.0.28",
|
||||
"abcjs": "^6.6.2",
|
||||
@@ -849,6 +850,116 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/@olton/datetime": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@olton/datetime/-/datetime-3.3.0.tgz",
|
||||
"integrity": "sha512-YqGLhVp0iisuDjQZ77PQkRciEfFp92znIdwTq4jU86KQisYfzL0Z23MnT9CWDC7mDjxQOZczLh956eR1RsOVAg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@olton/dom": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@olton/dom/-/dom-1.5.1.tgz",
|
||||
"integrity": "sha512-vVXQYluo3id17GTol+0GI2RbD7HS9ajT6avHbnLXKE7ORjQ/NNfaRtvgJqWOnLGC0H+O09gVSm3g8HGOiNaRYQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"web-worker": "^1.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@olton/farbe": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@olton/farbe/-/farbe-1.0.11.tgz",
|
||||
"integrity": "sha512-gYpiDuKUIfONnc21a/q322RLGHGcwN0VABj+g3CoXwO4ysVxDVdAzfrwlOWbe4fFJwswr/HUUG0Ll8iJRo0eiw==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "paypal",
|
||||
"url": "serhii@pimenov.com.ua"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/metroui"
|
||||
},
|
||||
{
|
||||
"type": "subscription",
|
||||
"url": "https://korzh.com/metroui#licensing"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@olton/guardian": {
|
||||
"version": "0.7.3",
|
||||
"resolved": "https://registry.npmjs.org/@olton/guardian/-/guardian-0.7.3.tgz",
|
||||
"integrity": "sha512-ypl1ePJHjhz7Kl+Mo+N4E85bqgjIgdh070zmz22ZrVtv7lMXyvJ5yNJaz33UOvYKPylU9yQfi4MDomPuSfFQkg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@olton/hooks": {
|
||||
"version": "0.13.1",
|
||||
"resolved": "https://registry.npmjs.org/@olton/hooks/-/hooks-0.13.1.tgz",
|
||||
"integrity": "sha512-Mi59Dnmg9N7Yv0FsbrrPKf6GEvRbSv3bNca20whjCUQguQ7qUx4T54XX9KFAkJNqTVDQHbppZgV3pYjRsdb23w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@olton/html": {
|
||||
"version": "0.15.1",
|
||||
"resolved": "https://registry.npmjs.org/@olton/html/-/html-0.15.1.tgz",
|
||||
"integrity": "sha512-jdKda7+O/oOCJDOdIV9BAd5tk1qYuUUNYSVK0KAAY/fkycCjBG7QwStzNGmtaXz8bpIcL1giid+JdcSe4BaNUw==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "paypal",
|
||||
"url": "serhii@pimenov.com.ua"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/metroui"
|
||||
},
|
||||
{
|
||||
"type": "subscription",
|
||||
"url": "https://korzh.com/metroui#licensing"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@olton/metroui": {
|
||||
"version": "5.1.20",
|
||||
"resolved": "https://registry.npmjs.org/@olton/metroui/-/metroui-5.1.20.tgz",
|
||||
"integrity": "sha512-YV49RzUC3Uj4jqTSoADrmK/nHJ90TgJea50flmBKmDn34NxZtkrg3CAz9qy8726+I7ogdwWMBoxBfnqPfaTJYw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@olton/datetime": "^3.3.0",
|
||||
"@olton/dom": "^1.5.1",
|
||||
"@olton/farbe": "^1.0.11",
|
||||
"@olton/guardian": "^0.7.3",
|
||||
"@olton/hooks": "^0.13.1",
|
||||
"@olton/html": "^0.15.1",
|
||||
"@olton/model": "^0.18.1",
|
||||
"@olton/router": "^0.4.1",
|
||||
"@olton/string": "^0.10.2"
|
||||
},
|
||||
"funding": {
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/metroui"
|
||||
}
|
||||
},
|
||||
"node_modules/@olton/model": {
|
||||
"version": "0.18.1",
|
||||
"resolved": "https://registry.npmjs.org/@olton/model/-/model-0.18.1.tgz",
|
||||
"integrity": "sha512-UyvvUrINPC9W5mbf2sZXAbDaUKuRykQ7TCpfqfx2Qd8mPskMt5R65zzmYBtAoapeDfxtvnAYi9PYIwgIraKyZw==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/metroui"
|
||||
}
|
||||
},
|
||||
"node_modules/@olton/router": {
|
||||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@olton/router/-/router-0.4.1.tgz",
|
||||
"integrity": "sha512-9pCSomojBBM3kkqlofttpYchF+Qm2D73IYCQq2NBhiPkustnkXua9i4XCSVP3ptXpgvIOsc6+RnPR7AGB+5utA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@olton/string": {
|
||||
"version": "0.10.2",
|
||||
"resolved": "https://registry.npmjs.org/@olton/string/-/string-0.10.2.tgz",
|
||||
"integrity": "sha512-xuBuCOkgyJkEyVBSkjFPIYuAzZiCiGQuks/eWvwgF01A+QMXLv1w+OpR1M40ehCjvKVgz4eXWHqSBL7wfX+KiQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@rolldown/pluginutils": {
|
||||
"version": "1.0.0-beta.27",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
|
||||
@@ -2681,6 +2792,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/web-worker": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.5.0.tgz",
|
||||
"integrity": "sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@olton/metroui": "^5.1.20",
|
||||
"@fontsource/archivo": "^5.0.0",
|
||||
"@fontsource/eb-garamond": "^5.0.0",
|
||||
"@fontsource/inter": "^5.0.0",
|
||||
|
||||
+122
-100
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* App.tsx — StemEngine shell
|
||||
*
|
||||
* Phase 1 (MetroUI migration): outer shell uses MetroUI app-bar + CSS classes.
|
||||
* Inner pages (Separator, ProjectDetail, Settings, Sidebar) still use Tailwind;
|
||||
* they will be migrated in subsequent phases.
|
||||
*/
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Music2, Settings, Cpu } from 'lucide-react'
|
||||
import Separator from './pages/Separator'
|
||||
@@ -11,8 +18,8 @@ import type { Project } from './types'
|
||||
|
||||
interface ProjectTab {
|
||||
id: string
|
||||
label: string // e.g. "Demucs v4_MP3 (256 kbps)"
|
||||
name: string // e.g. "Artist - Title"
|
||||
label: string
|
||||
name: string
|
||||
}
|
||||
|
||||
interface GpuInfo {
|
||||
@@ -24,28 +31,24 @@ interface GpuInfo {
|
||||
}
|
||||
|
||||
function AppShell() {
|
||||
const [activeTabId, setActiveTabId] = useState<string>(
|
||||
const [activeTabId, setActiveTabId] = useState<string>(
|
||||
() => localStorage.getItem('stemengine-active-tab') ?? 'separate'
|
||||
)
|
||||
const [projectTabs, setProjectTabs] = useState<ProjectTab[]>([])
|
||||
const [sidebarOpen, setSidebarOpen] = useState(() => window.innerWidth >= 640)
|
||||
const [projectTabs, setProjectTabs] = useState<ProjectTab[]>([])
|
||||
const [sidebarOpen, setSidebarOpen] = useState(() => window.innerWidth >= 640)
|
||||
|
||||
// GPU state
|
||||
const [gpuInfo, setGpuInfo] = useState<GpuInfo | null>(null)
|
||||
const [gpuInfo, setGpuInfo] = useState<GpuInfo | null>(null)
|
||||
const [gpuResetting, setGpuResetting] = useState(false)
|
||||
|
||||
// Persist active tab so it survives a page refresh
|
||||
useEffect(() => {
|
||||
localStorage.setItem('stemengine-active-tab', activeTabId)
|
||||
}, [activeTabId])
|
||||
|
||||
// Apply saved font and accent color on mount
|
||||
useEffect(() => {
|
||||
applyFont(localStorage.getItem('stemengine-font') ?? 'system')
|
||||
applyAccent(localStorage.getItem('stemengine-accent') ?? 'blue')
|
||||
}, [])
|
||||
|
||||
// Load all projects from DB on mount → restore persistent tabs
|
||||
useEffect(() => {
|
||||
listProjects()
|
||||
.then((projects: Project[]) => {
|
||||
@@ -55,21 +58,17 @@ function AppShell() {
|
||||
name: p.name,
|
||||
}))
|
||||
setProjectTabs(tabs)
|
||||
// If the restored tab is a project that no longer exists, go home
|
||||
setActiveTabId((current) => {
|
||||
if (current === 'separate' || current === 'settings') return current
|
||||
return tabs.find((t) => t.id === current) ? current : 'separate'
|
||||
})
|
||||
})
|
||||
.catch(() => {/* ignore – server may not be ready yet */})
|
||||
.catch(() => {})
|
||||
}, [])
|
||||
|
||||
// Poll GPU info on mount + every 30 s
|
||||
useEffect(() => {
|
||||
async function fetchGpu() {
|
||||
try {
|
||||
setGpuInfo(await getGpuInfo())
|
||||
} catch { /* server not ready yet */ }
|
||||
try { setGpuInfo(await getGpuInfo()) } catch {}
|
||||
}
|
||||
fetchGpu()
|
||||
const id = setInterval(fetchGpu, 30_000)
|
||||
@@ -81,19 +80,15 @@ function AppShell() {
|
||||
try {
|
||||
await resetGpu()
|
||||
setGpuInfo(await getGpuInfo())
|
||||
} catch { /* ignore */ }
|
||||
} catch {}
|
||||
setGpuResetting(false)
|
||||
}
|
||||
|
||||
// Auto-reset when the GPU context is marked failed (e.g. after Whisper fallback)
|
||||
const gpuContextFailed = gpuInfo?.cuda_available === true && gpuInfo.cuda_ok === false
|
||||
useEffect(() => {
|
||||
if (gpuContextFailed && !gpuResetting) {
|
||||
handleGpuReset()
|
||||
}
|
||||
if (gpuContextFailed && !gpuResetting) handleGpuReset()
|
||||
}, [gpuContextFailed])
|
||||
|
||||
// Called by Separator when a separation job finishes
|
||||
const handleSeparationComplete = useCallback(
|
||||
(projectId: string, tabLabel: string, projectName: string) => {
|
||||
setProjectTabs((prev) => {
|
||||
@@ -105,114 +100,140 @@ function AppShell() {
|
||||
[]
|
||||
)
|
||||
|
||||
// Close (delete) a project tab
|
||||
async function handleCloseTab(projectId: string, projectName: string) {
|
||||
const label = projectTabs.find((t) => t.id === projectId)?.label || projectName
|
||||
if (!window.confirm(`Delete "${label}"?\n\nThis will permanently remove the project and all its files.`)) return
|
||||
|
||||
try {
|
||||
await deleteProject(projectId)
|
||||
} catch {
|
||||
// If delete fails, still remove from tabs (project may already be gone)
|
||||
}
|
||||
try { await deleteProject(projectId) } catch {}
|
||||
setProjectTabs((prev) => prev.filter((t) => t.id !== projectId))
|
||||
if (activeTabId === projectId) setActiveTabId('separate')
|
||||
}
|
||||
|
||||
// Called from sidebar when a project is deleted there
|
||||
function handleDeleteProjectFromSidebar(project: Project) {
|
||||
setProjectTabs((prev) => prev.filter((t) => t.id !== project.id))
|
||||
if (activeTabId === project.id) setActiveTabId('separate')
|
||||
}
|
||||
|
||||
// Open a project tab from sidebar click — adds it if not already open
|
||||
function handleOpenProject(project: Project) {
|
||||
setProjectTabs((prev) => {
|
||||
if (prev.find((t) => t.id === project.id)) return prev
|
||||
return [...prev, {
|
||||
id: project.id,
|
||||
label: project.tab_label || project.name,
|
||||
name: project.name,
|
||||
}]
|
||||
return [...prev, { id: project.id, label: project.tab_label || project.name, name: project.name }]
|
||||
})
|
||||
setActiveTabId(project.id)
|
||||
}
|
||||
|
||||
// Derive GPU button appearance
|
||||
const gpuError = gpuInfo ? (!gpuInfo.cuda_ok || !gpuInfo.cuda_available) : false
|
||||
const gpuTitle = gpuInfo
|
||||
const gpuError = gpuInfo ? (!gpuInfo.cuda_ok || !gpuInfo.cuda_available) : false
|
||||
const gpuTitle = gpuInfo
|
||||
? gpuInfo.cuda_available
|
||||
? `${gpuInfo.name ?? 'GPU'} · ${gpuInfo.free_mb} / ${gpuInfo.total_mb} MB free${!gpuInfo.cuda_ok ? ' · Context error — click to reset' : ''}`
|
||||
: 'CUDA unavailable — click to attempt reset'
|
||||
: 'GPU status unknown'
|
||||
|
||||
// ── Accent colour: map app accent id to MetroUI colour class ─────────────
|
||||
// Used for the active-settings button highlight via inline style.
|
||||
const accentHex = (() => {
|
||||
const raw = document.documentElement.dataset.accent ?? 'blue'
|
||||
const map: Record<string, string> = {
|
||||
blue: '#3b82f6', violet: '#8b5cf6', rose: '#f43f5e',
|
||||
emerald: '#10b981', amber: '#f59e0b', cyan: '#06b6d4',
|
||||
}
|
||||
return map[raw] ?? map.blue
|
||||
})()
|
||||
|
||||
// ── GPU status dot colour ─────────────────────────────────────────────────
|
||||
const gpuDotColor = !gpuInfo
|
||||
? 'transparent'
|
||||
: !gpuInfo.cuda_available ? '#64748b'
|
||||
: !gpuInfo.cuda_ok ? '#ef4444'
|
||||
: '#34d399'
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col overflow-hidden">
|
||||
{/* ── Header ── */}
|
||||
<header className="shrink-0 border-b border-slate-200 dark:border-gray-800 bg-white dark:bg-gray-950 z-20">
|
||||
<div className="h-1 bg-gradient-to-r from-brand-500 via-purple-500 to-rose-500" />
|
||||
<div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
|
||||
|
||||
<div className="px-4 py-2.5 flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => setActiveTabId('separate')}
|
||||
title="Home"
|
||||
className="flex items-center gap-2 flex-1 min-w-0 hover:opacity-80 transition-opacity text-left"
|
||||
>
|
||||
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-brand-500 to-brand-700 flex items-center justify-center shrink-0 shadow-md shadow-brand-500/30">
|
||||
<Music2 className="w-4 h-4 text-white" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span className="text-base font-bold text-slate-900 dark:text-white tracking-tight">StemEngine</span>
|
||||
<span className="text-xs text-slate-400 dark:text-gray-600 ml-2 hidden sm:inline">Audio processing toolkit</span>
|
||||
</div>
|
||||
</button>
|
||||
{/* ── AppBar ──────────────────────────────────────────────────────────── */}
|
||||
<header style={{ flexShrink: 0, position: 'relative', zIndex: 20 }}>
|
||||
{/* Accent gradient line */}
|
||||
<div style={{
|
||||
height: 3,
|
||||
background: `linear-gradient(90deg, rgb(var(--brand-500, 59 130 246)), #a855f7, #f43f5e)`,
|
||||
}} />
|
||||
|
||||
{/* GPU status button */}
|
||||
<button
|
||||
onClick={handleGpuReset}
|
||||
title={gpuTitle}
|
||||
className={`relative p-2 rounded-xl border transition-all ${
|
||||
gpuError
|
||||
? 'border-red-400 bg-red-50 dark:bg-red-950/30 text-red-500 dark:text-red-400 hover:border-red-500'
|
||||
: 'border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-900 text-slate-400 dark:text-gray-600 hover:text-brand-600 dark:hover:text-brand-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Cpu className={`w-4 h-4 ${gpuResetting ? 'animate-pulse' : ''}`} />
|
||||
{/* status dot */}
|
||||
{gpuInfo && (
|
||||
<span className={`absolute top-1 right-1 w-1.5 h-1.5 rounded-full ${
|
||||
!gpuInfo.cuda_available ? 'bg-slate-400 dark:bg-gray-600'
|
||||
: !gpuInfo.cuda_ok ? 'bg-red-500 animate-pulse'
|
||||
: 'bg-emerald-400'
|
||||
}`} />
|
||||
)}
|
||||
</button>
|
||||
<div className="app-bar">
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTabId('settings')}
|
||||
title="Settings"
|
||||
className={`p-2 rounded-xl border transition-all ${
|
||||
activeTabId === 'settings'
|
||||
? 'border-brand-500 bg-brand-50 dark:bg-brand-950/30 text-brand-600 dark:text-brand-400'
|
||||
: 'border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-900 text-slate-500 hover:text-brand-600 dark:text-gray-400 dark:hover:text-brand-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Settings className="w-4 h-4" />
|
||||
</button>
|
||||
{/* Brand */}
|
||||
<div className="app-bar-brand">
|
||||
<button
|
||||
onClick={() => setActiveTabId('separate')}
|
||||
title="Home"
|
||||
className="button flat"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 8px' }}
|
||||
>
|
||||
<div style={{
|
||||
width: 32, height: 32, borderRadius: 8, flexShrink: 0,
|
||||
background: `linear-gradient(135deg, rgb(var(--brand-500, 59 130 246)), rgb(var(--brand-700, 29 78 216)))`,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
<Music2 size={16} color="white" />
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1.2 }}>
|
||||
<span style={{ fontWeight: 700, fontSize: 15 }}>StemEngine</span>
|
||||
<span style={{ fontSize: 11, opacity: 0.45 }}>Audio processing toolkit</span>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Right-side icon buttons */}
|
||||
<div className="app-bar-item" style={{ display: 'flex', alignItems: 'center', gap: 4, marginLeft: 'auto' }}>
|
||||
|
||||
{/* GPU status */}
|
||||
<button
|
||||
onClick={handleGpuReset}
|
||||
title={gpuTitle}
|
||||
className="button cycle flat"
|
||||
style={{
|
||||
position: 'relative',
|
||||
color: gpuError ? '#ef4444' : undefined,
|
||||
}}
|
||||
>
|
||||
<Cpu size={16} style={{ animation: gpuResetting ? 'pulse 1s infinite' : undefined }} />
|
||||
{/* Status dot */}
|
||||
<span style={{
|
||||
position: 'absolute', top: 4, right: 4,
|
||||
width: 6, height: 6, borderRadius: '50%',
|
||||
background: gpuDotColor,
|
||||
transition: 'background 0.3s',
|
||||
}} />
|
||||
</button>
|
||||
|
||||
{/* Settings */}
|
||||
<button
|
||||
onClick={() => setActiveTabId('settings')}
|
||||
title="Settings"
|
||||
className="button cycle flat"
|
||||
style={{
|
||||
color: activeTabId === 'settings' ? accentHex : undefined,
|
||||
borderColor: activeTabId === 'settings' ? accentHex : undefined,
|
||||
}}
|
||||
>
|
||||
<Settings size={16} />
|
||||
</button>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* ── Body: sidebar + main ── */}
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{/* ── Body ────────────────────────────────────────────────────────────── */}
|
||||
<div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
|
||||
|
||||
{/* Backdrop — tapping it closes the sidebar on mobile */}
|
||||
{/* Mobile backdrop — tapping it closes the sidebar (hidden on sm+ where sidebar is in flow) */}
|
||||
{sidebarOpen && (
|
||||
<div
|
||||
className="sm:hidden fixed inset-0 z-20 bg-black/40"
|
||||
className="sm:hidden"
|
||||
style={{ position: 'fixed', inset: 0, zIndex: 20, background: 'rgba(0,0,0,0.4)' }}
|
||||
onClick={() => setSidebarOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Sidebar — Tailwind, migrated in Phase 2 */}
|
||||
<Sidebar
|
||||
isOpen={sidebarOpen}
|
||||
onToggle={() => setSidebarOpen((v) => !v)}
|
||||
@@ -221,15 +242,15 @@ function AppShell() {
|
||||
openTabIds={projectTabs.map((t) => t.id)}
|
||||
/>
|
||||
|
||||
<div className="flex-1 flex flex-col overflow-hidden bg-slate-100 dark:bg-gray-950">
|
||||
|
||||
{/* Page content */}
|
||||
<main className="flex-1 overflow-y-auto pb-12">
|
||||
{/* Main content area */}
|
||||
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
|
||||
<main style={{ flex: 1, overflowY: 'auto', paddingBottom: 48 }}>
|
||||
{activeTabId === 'settings' ? (
|
||||
// Settings page — Tailwind, migrated in Phase 5
|
||||
<SettingsPage />
|
||||
) : (
|
||||
<div className="max-w-3xl mx-auto px-2 sm:px-4 py-4 sm:py-6">
|
||||
<div className="rounded-2xl border border-slate-200 dark:border-gray-800 bg-white dark:bg-gray-900/60 p-3 sm:p-6 shadow-sm dark:shadow-xl">
|
||||
<div style={{ maxWidth: 768, margin: '0 auto', padding: '16px 16px' }}>
|
||||
<div style={{ border: '1px solid var(--border-color)', borderRadius: 16, background: 'var(--body-background, var(--background))', padding: 24, boxShadow: '0 1px 6px rgba(0,0,0,0.08)' }}>
|
||||
{activeTabId === 'separate' ? (
|
||||
<Separator
|
||||
onSeparationComplete={handleSeparationComplete}
|
||||
@@ -249,7 +270,7 @@ function AppShell() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<footer className="mt-6 text-center text-xs text-slate-400 dark:text-gray-700">
|
||||
<footer style={{ marginTop: 24, textAlign: 'center', fontSize: 11, opacity: 0.35 }}>
|
||||
StemEngine · Demucs · BS-RoFormer · Omnizart · wav2vec2
|
||||
</footer>
|
||||
</div>
|
||||
@@ -258,8 +279,9 @@ function AppShell() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Floating playback bar — persists across page navigation */}
|
||||
{/* Floating playback bar — GlobalAudioBar, migrated in Phase 6 */}
|
||||
<GlobalAudioBar />
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -91,10 +91,11 @@ async function pollUntilDone(jobId: string, signal?: AbortSignal): Promise<Job>
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function StepIcon({ step }: { step: AutoStep }) {
|
||||
if (step.type === 'reprocess') return <Music2 className="w-3.5 h-3.5 text-purple-500" />
|
||||
if (step.type === 'midi') return <Mic2 className="w-3.5 h-3.5 text-emerald-500" />
|
||||
if (step.type === 'lyricsAlign') return <BookmarkPlus className="w-3.5 h-3.5 text-teal-500" />
|
||||
return <AlignLeft className="w-3.5 h-3.5 text-sky-500" />
|
||||
const s = { width: 14, height: 14, flexShrink: 0 }
|
||||
if (step.type === 'reprocess') return <Music2 style={{ ...s, color: 'var(--color-violet, #a78bfa)' }} />
|
||||
if (step.type === 'midi') return <Mic2 style={{ ...s, color: 'var(--color-green)' }} />
|
||||
if (step.type === 'lyricsAlign') return <BookmarkPlus style={{ ...s, color: 'var(--color-teal, #2dd4bf)' }} />
|
||||
return <AlignLeft style={{ ...s, color: 'var(--color-blue, #38bdf8)' }} />
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -227,161 +228,178 @@ export default function AutoPipelineDialog({ target, onClose, onComplete, onOpen
|
||||
const finished = phase === 'done' || phase === 'error'
|
||||
const canRun = !!(target.file || target.filePath)
|
||||
|
||||
const brand = 'rgb(var(--brand-500, 59 130 246))'
|
||||
const amber = 'var(--color-amber)'
|
||||
|
||||
const stepColor = (status: StepStatus['status']) => {
|
||||
if (status === 'running') return brand
|
||||
if (status === 'done') return 'var(--color-green)'
|
||||
if (status === 'error') return 'var(--color-red)'
|
||||
return 'inherit'
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 right-4 z-50 w-96 rounded-2xl bg-white dark:bg-gray-900 border border-slate-200 dark:border-gray-700 shadow-2xl flex flex-col max-h-[85vh]">
|
||||
<div style={{
|
||||
position: 'fixed', bottom: 16, right: 16, zIndex: 50, width: 384,
|
||||
borderRadius: 16, border: '1px solid var(--border-color)',
|
||||
background: 'var(--body-background, var(--background))',
|
||||
boxShadow: '0 8px 32px rgba(0,0,0,0.24)',
|
||||
display: 'flex', flexDirection: 'column', maxHeight: '85vh',
|
||||
}}>
|
||||
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-3 px-5 py-4 border-b border-slate-200 dark:border-gray-800 shrink-0">
|
||||
<Zap className="w-5 h-5 text-amber-500 shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<h2 className="text-sm font-bold text-slate-900 dark:text-white">Auto Pipeline</h2>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-400 truncate">{target.filename}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={running ? cancel : onClose}
|
||||
className="p-1.5 rounded-lg text-slate-400 hover:text-slate-600 dark:hover:text-gray-200 transition-colors"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
{/* Header */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 20px', borderBottom: '1px solid var(--border-color)', flexShrink: 0 }}>
|
||||
<Zap style={{ width: 20, height: 20, color: amber, flexShrink: 0 }} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<h2 style={{ margin: 0, fontSize: 13, fontWeight: 700 }}>Auto Pipeline</h2>
|
||||
<p style={{ margin: 0, fontSize: 11, opacity: 0.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{target.filename}</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={running ? cancel : onClose}
|
||||
className="button cycle flat"
|
||||
style={{ padding: 6, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
>
|
||||
<X style={{ width: 16, height: 16 }} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="flex-1 overflow-y-auto p-5 space-y-4">
|
||||
{/* Body */}
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
|
||||
{/* Project name */}
|
||||
{!running && !finished && (
|
||||
<label className="space-y-1 block">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Project Name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={projName}
|
||||
onChange={e => setProjName(e.target.value)}
|
||||
placeholder="Artist - Title"
|
||||
className="w-full rounded-lg bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-3 py-2 text-sm text-slate-900 dark:text-gray-100 focus:border-brand-500 focus:outline-none"
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{/* Project name */}
|
||||
{!running && !finished && (
|
||||
<label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
<span style={{ fontSize: 10, fontWeight: 600, opacity: 0.5, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Project Name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={projName}
|
||||
onChange={e => setProjName(e.target.value)}
|
||||
placeholder="Artist - Title"
|
||||
style={{ width: '100%', borderRadius: 6, border: '1px solid var(--border-color)', padding: '7px 12px', fontSize: 13, background: 'transparent', boxSizing: 'border-box' }}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{/* Pipeline summary (shown before run) */}
|
||||
{!running && !finished && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Pipeline ({1 + steps.length} step{steps.length !== 0 ? 's' : ''})
|
||||
</span>
|
||||
{/* Pipeline summary */}
|
||||
{!running && !finished && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<span style={{ fontSize: 10, fontWeight: 600, opacity: 0.5, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
|
||||
Pipeline ({1 + steps.length} step{steps.length !== 0 ? 's' : ''})
|
||||
</span>
|
||||
{onOpenSettings && (
|
||||
<button
|
||||
onClick={onOpenSettings}
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 11, color: brand, background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}
|
||||
>
|
||||
<Settings style={{ width: 12, height: 12 }} />
|
||||
Edit in Settings
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Separation step */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 12px', borderRadius: 6, border: '1px solid var(--border-color)' }}>
|
||||
<Music2 style={{ width: 14, height: 14, color: brand, flexShrink: 0 }} />
|
||||
<span style={{ flex: 1, fontSize: 13 }}>Stem Separation</span>
|
||||
<span style={{ fontSize: 11, opacity: 0.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 128 }}>
|
||||
{model} · {format}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{steps.length === 0 && (
|
||||
<p style={{ margin: 0, fontSize: 11, opacity: 0.5, fontStyle: 'italic', padding: '0 4px' }}>
|
||||
No extra steps configured.{' '}
|
||||
{onOpenSettings && (
|
||||
<button
|
||||
onClick={onOpenSettings}
|
||||
className="flex items-center gap-1 text-xs text-brand-500 hover:text-brand-600 dark:text-brand-400 transition-colors"
|
||||
>
|
||||
<Settings className="w-3 h-3" />
|
||||
Edit in Settings
|
||||
<button onClick={onOpenSettings} style={{ color: brand, background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontSize: 11, textDecoration: 'underline' }}>
|
||||
Add steps in Settings →
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Separation step */}
|
||||
<div className="flex items-center gap-2.5 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/50 border border-slate-200 dark:border-gray-700">
|
||||
<Music2 className="w-3.5 h-3.5 text-brand-500 shrink-0" />
|
||||
<span className="text-sm text-slate-700 dark:text-gray-200 flex-1">Stem Separation</span>
|
||||
<span className="text-xs text-slate-400 dark:text-gray-500 truncate max-w-32">
|
||||
{model} · {format}
|
||||
{steps.map((step, i) => (
|
||||
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 12px', borderRadius: 6, border: '1px solid var(--border-color)' }}>
|
||||
<StepIcon step={step} />
|
||||
<span style={{ flex: 1, fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{stepLabel(step)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{steps.length === 0 && (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-500 italic px-1">
|
||||
No extra steps configured.{' '}
|
||||
{onOpenSettings && (
|
||||
<button onClick={onOpenSettings} className="text-brand-500 hover:underline">
|
||||
Add steps in Settings →
|
||||
</button>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{steps.map((step, i) => (
|
||||
<div key={i} className="flex items-center gap-2.5 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/50 border border-slate-200 dark:border-gray-700">
|
||||
<StepIcon step={step} />
|
||||
<span className="text-sm text-slate-700 dark:text-gray-200 flex-1 truncate">
|
||||
{stepLabel(step)}
|
||||
</span>
|
||||
{/* Live progress */}
|
||||
{stepStats.length > 0 && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
<span style={{ fontSize: 10, fontWeight: 600, opacity: 0.5, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Progress</span>
|
||||
{stepStats.map((s, i) => (
|
||||
<div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
|
||||
<div style={{ marginTop: 2, flexShrink: 0 }}>
|
||||
{s.status === 'running' && <Loader2 style={{ width: 16, height: 16, color: brand }} />}
|
||||
{s.status === 'done' && <CheckCircle2 style={{ width: 16, height: 16, color: 'var(--color-green)' }} />}
|
||||
{s.status === 'error' && <XCircle style={{ width: 16, height: 16, color: 'var(--color-red)' }} />}
|
||||
{s.status === 'pending' && <div style={{ width: 16, height: 16, borderRadius: '50%', border: '2px solid var(--border-color)' }} />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Live progress */}
|
||||
{stepStats.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<span className="text-xs font-semibold text-slate-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Progress
|
||||
</span>
|
||||
{stepStats.map((s, i) => (
|
||||
<div key={i} className="flex items-start gap-3">
|
||||
<div className="mt-0.5 shrink-0">
|
||||
{s.status === 'running' && <Loader2 className="w-4 h-4 text-brand-500 animate-spin" />}
|
||||
{s.status === 'done' && <CheckCircle2 className="w-4 h-4 text-emerald-500" />}
|
||||
{s.status === 'error' && <XCircle className="w-4 h-4 text-red-500" />}
|
||||
{s.status === 'pending' && <div className="w-4 h-4 rounded-full border-2 border-slate-300 dark:border-gray-600" />}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className={`text-sm font-medium ${
|
||||
s.status === 'running' ? 'text-brand-600 dark:text-brand-400'
|
||||
: s.status === 'done' ? 'text-emerald-700 dark:text-emerald-300'
|
||||
: s.status === 'error' ? 'text-red-600 dark:text-red-400'
|
||||
: 'text-slate-500 dark:text-gray-500'
|
||||
}`}>{s.label}</p>
|
||||
{s.detail && <p className="text-xs text-slate-400 dark:text-gray-500 truncate">{s.detail}</p>}
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ margin: 0, fontSize: 13, fontWeight: 500, color: stepColor(s.status) }}>{s.label}</p>
|
||||
{s.detail && <p style={{ margin: '2px 0 0', fontSize: 11, opacity: 0.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.detail}</p>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{errMsg && (
|
||||
<div className="rounded-lg bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-800 px-4 py-3 text-sm text-red-700 dark:text-red-300">
|
||||
{errMsg}
|
||||
</div>
|
||||
)}
|
||||
{errMsg && (
|
||||
<div style={{ borderRadius: 6, border: '1px solid var(--color-red)', padding: '10px 16px', fontSize: 13, color: 'var(--color-red)', opacity: 0.85 }}>
|
||||
{errMsg}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === 'done' && (
|
||||
<div className="rounded-lg bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-800 px-4 py-3 text-sm text-emerald-700 dark:text-emerald-300 font-medium">
|
||||
Pipeline complete!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{phase === 'done' && (
|
||||
<div style={{ borderRadius: 6, border: '1px solid var(--color-green)', padding: '10px 16px', fontSize: 13, fontWeight: 500, color: 'var(--color-green)', opacity: 0.9 }}>
|
||||
Pipeline complete!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="px-5 py-4 border-t border-slate-200 dark:border-gray-800 shrink-0 flex gap-3">
|
||||
{!finished && (
|
||||
<>
|
||||
<button
|
||||
onClick={running ? cancel : onClose}
|
||||
className="flex-1 rounded-lg border border-slate-300 dark:border-gray-600 px-4 py-2.5 text-sm font-medium text-slate-600 dark:text-gray-300 hover:bg-slate-50 dark:hover:bg-gray-800 transition-colors"
|
||||
>
|
||||
{running ? 'Cancel' : 'Dismiss'}
|
||||
</button>
|
||||
<button
|
||||
onClick={run}
|
||||
disabled={running || !canRun}
|
||||
className="flex-1 rounded-lg bg-amber-500 hover:bg-amber-400 disabled:bg-slate-200 disabled:text-slate-400 dark:disabled:bg-gray-800 dark:disabled:text-gray-500 px-4 py-2.5 text-sm font-bold text-white disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
{running
|
||||
? <><Loader2 className="w-4 h-4 animate-spin" />Running…</>
|
||||
: <><Zap className="w-4 h-4" />Run Pipeline</>}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{finished && (
|
||||
{/* Footer */}
|
||||
<div style={{ padding: '14px 20px', borderTop: '1px solid var(--border-color)', flexShrink: 0, display: 'flex', gap: 12 }}>
|
||||
{!finished && (
|
||||
<>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="flex-1 rounded-lg bg-brand-600 hover:bg-brand-500 px-4 py-2.5 text-sm font-bold text-white transition-colors"
|
||||
onClick={running ? cancel : onClose}
|
||||
style={{ flex: 1, borderRadius: 6, border: '1px solid var(--border-color)', padding: '9px 16px', fontSize: 13, fontWeight: 500, background: 'transparent', cursor: 'pointer' }}
|
||||
>
|
||||
Close
|
||||
{running ? 'Cancel' : 'Dismiss'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={run}
|
||||
disabled={running || !canRun}
|
||||
style={{
|
||||
flex: 1, borderRadius: 6, border: 'none', padding: '9px 16px', fontSize: 13, fontWeight: 700,
|
||||
background: running || !canRun ? 'var(--border-color)' : amber,
|
||||
color: running || !canRun ? 'inherit' : '#fff',
|
||||
cursor: running || !canRun ? 'not-allowed' : 'pointer',
|
||||
display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
|
||||
}}
|
||||
>
|
||||
{running
|
||||
? <><Loader2 style={{ width: 16, height: 16 }} />Running…</>
|
||||
: <><Zap style={{ width: 16, height: 16 }} />Run Pipeline</>}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{finished && (
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="button primary"
|
||||
style={{ flex: 1, padding: '9px 16px', fontSize: 13, fontWeight: 700 }}
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -226,22 +226,29 @@ export default function DynamicMixPlayer({ stems, title, onLevelChange }: Props)
|
||||
|
||||
const allLoaded = stems.every((s) => loaded[s.name] !== false)
|
||||
|
||||
const brand = 'rgb(var(--brand-500, 59 130 246))'
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
{/* Playback controls */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8 }}>
|
||||
<button
|
||||
onClick={togglePlay}
|
||||
disabled={!allLoaded}
|
||||
className="flex items-center justify-center w-9 h-9 rounded-full bg-brand-500 text-white hover:bg-brand-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shrink-0"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: 36, height: 36, borderRadius: '50%', flexShrink: 0,
|
||||
background: brand, color: '#fff', border: 'none', cursor: allLoaded ? 'pointer' : 'not-allowed',
|
||||
opacity: allLoaded ? 1 : 0.5, padding: 0,
|
||||
}}
|
||||
>
|
||||
{isPlaying ? (
|
||||
<svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
|
||||
<svg width="16" height="16" fill="currentColor" viewBox="0 0 24 24">
|
||||
<rect x="6" y="4" width="4" height="16" />
|
||||
<rect x="14" y="4" width="4" height="16" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
|
||||
<svg width="16" height="16" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
)}
|
||||
@@ -253,23 +260,24 @@ export default function DynamicMixPlayer({ stems, title, onLevelChange }: Props)
|
||||
step={0.1}
|
||||
value={currentTime}
|
||||
onChange={(e) => handleSeek(parseFloat(e.target.value))}
|
||||
className="flex-1 min-w-[80px] h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
style={{ flex: 1, minWidth: 80, cursor: 'pointer', accentColor: brand }}
|
||||
/>
|
||||
<span className="text-xs tabular-nums text-slate-500 dark:text-gray-400 shrink-0">
|
||||
<span style={{ fontSize: 11, fontVariantNumeric: 'tabular-nums', opacity: 0.6, flexShrink: 0 }}>
|
||||
{formatTime(currentTime)} / {formatTime(duration)}
|
||||
</span>
|
||||
|
||||
{/* Master volume */}
|
||||
<div className="flex items-center gap-1.5 pl-2 border-l border-slate-200 dark:border-gray-700 shrink-0">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, paddingLeft: 8, borderLeft: '1px solid var(--border-color)', flexShrink: 0 }}>
|
||||
<button
|
||||
onClick={toggleMute}
|
||||
className="p-1.5 rounded-md text-slate-500 dark:text-gray-400 hover:text-slate-700 dark:hover:text-gray-200 hover:bg-slate-100 dark:hover:bg-gray-800 transition-colors"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 6, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
title={isMuted ? 'Unmute' : 'Mute'}
|
||||
>
|
||||
{isMuted || masterVolume === 0 ? (
|
||||
<VolumeX className="w-4 h-4" />
|
||||
<VolumeX style={{ width: 16, height: 16 }} />
|
||||
) : (
|
||||
<Volume2 className="w-4 h-4" />
|
||||
<Volume2 style={{ width: 16, height: 16 }} />
|
||||
)}
|
||||
</button>
|
||||
<input
|
||||
@@ -279,38 +287,40 @@ export default function DynamicMixPlayer({ stems, title, onLevelChange }: Props)
|
||||
step={0.05}
|
||||
value={isMuted ? 0 : masterVolume}
|
||||
onChange={(e) => updateMasterVolume(parseFloat(e.target.value))}
|
||||
className="w-16 sm:w-20 h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
style={{ width: 72, cursor: 'pointer', accentColor: brand }}
|
||||
title="Master Volume"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stem level sliders */}
|
||||
<div className="space-y-2 pt-2 border-t border-slate-200 dark:border-gray-700">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, paddingTop: 8, borderTop: '1px solid var(--border-color)' }}>
|
||||
{stems.map((stem) => (
|
||||
<div key={stem.name} className="flex items-center gap-1.5">
|
||||
<span className="text-xs font-medium text-slate-600 dark:text-gray-400 w-12 sm:w-16 truncate capitalize">
|
||||
<div key={stem.name} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ fontSize: 11, fontWeight: 500, opacity: 0.7, width: 52, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', textTransform: 'capitalize', flexShrink: 0 }}>
|
||||
{stem.label}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => toggleStemMute(stem.name)}
|
||||
title={mutedStems[stem.name] ? 'Unmute' : 'Mute'}
|
||||
className={`w-6 h-6 text-xs font-bold rounded transition-colors flex-shrink-0 ${
|
||||
mutedStems[stem.name]
|
||||
? 'bg-red-500 text-white'
|
||||
: 'bg-slate-200 dark:bg-gray-700 text-slate-600 dark:text-gray-400 hover:bg-slate-300 dark:hover:bg-gray-600'
|
||||
}`}
|
||||
style={{
|
||||
width: 24, height: 24, fontSize: 11, fontWeight: 700, borderRadius: 4, flexShrink: 0,
|
||||
border: 'none', cursor: 'pointer', transition: 'background 0.15s',
|
||||
background: mutedStems[stem.name] ? 'var(--color-red)' : 'var(--border-color)',
|
||||
color: mutedStems[stem.name] ? '#fff' : 'inherit',
|
||||
}}
|
||||
>
|
||||
M
|
||||
</button>
|
||||
<button
|
||||
onClick={() => toggleStemSolo(stem.name)}
|
||||
title={soloedStems[stem.name] ? 'Unsolo' : 'Solo'}
|
||||
className={`w-6 h-6 text-xs font-bold rounded transition-colors flex-shrink-0 ${
|
||||
soloedStems[stem.name]
|
||||
? 'bg-yellow-400 text-black'
|
||||
: 'bg-slate-200 dark:bg-gray-700 text-slate-600 dark:text-gray-400 hover:bg-slate-300 dark:hover:bg-gray-600'
|
||||
}`}
|
||||
style={{
|
||||
width: 24, height: 24, fontSize: 11, fontWeight: 700, borderRadius: 4, flexShrink: 0,
|
||||
border: 'none', cursor: 'pointer', transition: 'background 0.15s',
|
||||
background: soloedStems[stem.name] ? 'var(--color-amber)' : 'var(--border-color)',
|
||||
color: soloedStems[stem.name] ? '#000' : 'inherit',
|
||||
}}
|
||||
>
|
||||
S
|
||||
</button>
|
||||
@@ -321,9 +331,9 @@ export default function DynamicMixPlayer({ stems, title, onLevelChange }: Props)
|
||||
step={0.1}
|
||||
value={gains[stem.name] ?? 1.0}
|
||||
onChange={(e) => updateGain(stem.name, parseFloat(e.target.value))}
|
||||
className="flex-1 h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
style={{ flex: 1, cursor: 'pointer', accentColor: brand }}
|
||||
/>
|
||||
<span className="text-xs tabular-nums text-slate-500 dark:text-gray-400 w-9 text-right">
|
||||
<span style={{ fontSize: 11, fontVariantNumeric: 'tabular-nums', opacity: 0.6, width: 36, textAlign: 'right', flexShrink: 0 }}>
|
||||
{Math.round((gains[stem.name] ?? 1.0) * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import React, { useCallback } from 'react'
|
||||
/**
|
||||
* FileUpload.tsx — Phase 3 MetroUI migration
|
||||
* Drag-and-drop / click-to-upload zone. Logic unchanged.
|
||||
*/
|
||||
import React, { useCallback, useState } from 'react'
|
||||
import { Upload } from 'lucide-react'
|
||||
|
||||
interface Props {
|
||||
@@ -8,9 +12,12 @@ interface Props {
|
||||
}
|
||||
|
||||
export default function FileUpload({ label = 'Drop files here', accept, onFiles }: Props) {
|
||||
const [dragOver, setDragOver] = useState(false)
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setDragOver(false)
|
||||
const files = Array.from(e.dataTransfer.files)
|
||||
if (files.length) onFiles(files)
|
||||
},
|
||||
@@ -26,15 +33,27 @@ export default function FileUpload({ label = 'Drop files here', accept, onFiles
|
||||
[onFiles]
|
||||
)
|
||||
|
||||
const accentColor = `rgb(var(--brand-500, 59 130 246))`
|
||||
|
||||
return (
|
||||
<label
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDragOver={(e) => { e.preventDefault(); setDragOver(true) }}
|
||||
onDragLeave={() => setDragOver(false)}
|
||||
onDrop={handleDrop}
|
||||
className="flex flex-col items-center justify-center gap-3 px-6 py-10 rounded-xl border-2 border-dashed border-slate-300 dark:border-gray-700 bg-slate-50 dark:bg-gray-900/50 hover:border-brand-400 dark:hover:border-brand-500 hover:bg-slate-100 dark:hover:bg-gray-800/50 transition-colors cursor-pointer"
|
||||
style={{
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center',
|
||||
justifyContent: 'center', gap: 12,
|
||||
padding: '28px 24px',
|
||||
borderRadius: 6,
|
||||
border: `2px dashed ${dragOver ? accentColor : 'var(--border-color)'}`,
|
||||
background: dragOver ? `rgba(var(--brand-500, 59 130 246), 0.05)` : 'var(--background)',
|
||||
cursor: 'pointer',
|
||||
transition: 'border-color 0.15s, background 0.15s',
|
||||
}}
|
||||
>
|
||||
<Upload className="w-8 h-8 text-slate-400 dark:text-gray-600" />
|
||||
<span className="text-sm text-slate-600 dark:text-gray-400 text-center">{label}</span>
|
||||
<input type="file" accept={accept} onChange={handleChange} className="hidden" />
|
||||
<Upload size={28} style={{ color: dragOver ? accentColor : undefined, opacity: dragOver ? 1 : 0.35, transition: 'opacity 0.15s, color 0.15s' }} />
|
||||
<span style={{ fontSize: 13, opacity: 0.55, textAlign: 'center', lineHeight: 1.4 }}>{label}</span>
|
||||
<input type="file" accept={accept} onChange={handleChange} style={{ display: 'none' }} />
|
||||
</label>
|
||||
)
|
||||
}
|
||||
@@ -28,29 +28,44 @@ export default function GlobalAudioBar() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-0 left-0 right-0 z-50 border-t border-slate-200 dark:border-gray-800 bg-white/95 dark:bg-gray-950/95 backdrop-blur-sm shadow-[0_-2px_8px_rgba(0,0,0,0.06)] dark:shadow-[0_-2px_8px_rgba(0,0,0,0.4)]">
|
||||
<div className="max-w-3xl mx-auto px-4 h-12 flex items-center gap-3">
|
||||
<div style={{
|
||||
position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 50,
|
||||
borderTop: '1px solid var(--border-color)',
|
||||
background: 'var(--body-background, var(--background))',
|
||||
backdropFilter: 'blur(8px)',
|
||||
boxShadow: '0 -2px 8px rgba(0,0,0,0.12)',
|
||||
}}>
|
||||
<div style={{
|
||||
maxWidth: 768, margin: '0 auto', padding: '0 16px',
|
||||
height: 48, display: 'flex', alignItems: 'center', gap: 12,
|
||||
}}>
|
||||
|
||||
{/* Play / Pause */}
|
||||
<button
|
||||
onClick={() => getActions().toggle()}
|
||||
className="flex items-center justify-center w-7 h-7 rounded-full bg-brand-500 text-white hover:bg-brand-600 transition-colors shrink-0"
|
||||
className="button cycle"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: 28, height: 28, borderRadius: '50%', flexShrink: 0,
|
||||
background: 'rgb(var(--brand-500, 59 130 246))', color: '#fff',
|
||||
border: 'none', cursor: 'pointer', padding: 0,
|
||||
}}
|
||||
title={isPlaying ? 'Pause' : 'Play'}
|
||||
>
|
||||
{isPlaying ? (
|
||||
<svg className="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
|
||||
<svg width="12" height="12" fill="currentColor" viewBox="0 0 24 24">
|
||||
<rect x="6" y="4" width="4" height="16" />
|
||||
<rect x="14" y="4" width="4" height="16" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
|
||||
<svg width="12" height="12" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Current time */}
|
||||
<span className="text-xs tabular-nums text-slate-400 dark:text-gray-500 shrink-0 w-8 text-right">
|
||||
<span style={{ fontSize: 11, fontVariantNumeric: 'tabular-nums', opacity: 0.5, flexShrink: 0, width: 32, textAlign: 'right' }}>
|
||||
{fmtTime(currentTime)}
|
||||
</span>
|
||||
|
||||
@@ -62,30 +77,31 @@ export default function GlobalAudioBar() {
|
||||
step={0.1}
|
||||
value={currentTime}
|
||||
onChange={e => getActions().seek(parseFloat(e.target.value))}
|
||||
className="flex-1 h-1.5 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500 min-w-0"
|
||||
style={{ flex: 1, minWidth: 0, cursor: 'pointer', accentColor: 'rgb(var(--brand-500, 59 130 246))' }}
|
||||
/>
|
||||
|
||||
{/* Duration */}
|
||||
<span className="text-xs tabular-nums text-slate-400 dark:text-gray-500 shrink-0 w-8">
|
||||
<span style={{ fontSize: 11, fontVariantNumeric: 'tabular-nums', opacity: 0.5, flexShrink: 0, width: 32 }}>
|
||||
{fmtTime(duration)}
|
||||
</span>
|
||||
|
||||
{/* Title */}
|
||||
<span
|
||||
className="text-xs font-medium text-slate-500 dark:text-gray-500 truncate shrink min-w-0 max-w-[120px] sm:max-w-[180px]"
|
||||
style={{ fontSize: 11, fontWeight: 500, opacity: 0.6, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flexShrink: 1, minWidth: 0, maxWidth: 180 }}
|
||||
title={title}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
|
||||
{/* Volume */}
|
||||
<div className="flex items-center gap-1 shrink-0 pl-2 border-l border-slate-200 dark:border-gray-700">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0, paddingLeft: 8, borderLeft: '1px solid var(--border-color)' }}>
|
||||
<button
|
||||
onClick={handleMuteToggle}
|
||||
className="p-1 rounded text-slate-400 dark:text-gray-500 hover:text-slate-600 dark:hover:text-gray-300 transition-colors"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
title={volume === 0 ? 'Unmute' : 'Mute'}
|
||||
>
|
||||
{volume === 0 ? <VolumeX className="w-3.5 h-3.5" /> : <Volume2 className="w-3.5 h-3.5" />}
|
||||
{volume === 0 ? <VolumeX style={{ width: 14, height: 14 }} /> : <Volume2 style={{ width: 14, height: 14 }} />}
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
@@ -94,7 +110,7 @@ export default function GlobalAudioBar() {
|
||||
step={0.05}
|
||||
value={volume}
|
||||
onChange={e => getActions().setVolume(parseFloat(e.target.value))}
|
||||
className="w-14 h-1.5 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-500"
|
||||
style={{ width: 56, cursor: 'pointer', accentColor: 'rgb(var(--brand-500, 59 130 246))' }}
|
||||
title="Volume"
|
||||
/>
|
||||
</div>
|
||||
@@ -102,10 +118,11 @@ export default function GlobalAudioBar() {
|
||||
{/* Dismiss */}
|
||||
<button
|
||||
onClick={stopCurrent}
|
||||
className="p-1 rounded text-slate-400 dark:text-gray-500 hover:text-slate-600 dark:hover:text-gray-300 transition-colors shrink-0 ml-1"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginLeft: 4 }}
|
||||
title="Stop and close"
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
<X style={{ width: 14, height: 14 }} />
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -43,10 +43,12 @@ export default function JobStatus({ jobId, onDone }: Props) {
|
||||
}
|
||||
}, [jobId, onDone])
|
||||
|
||||
const row = { display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-xs text-red-500">
|
||||
<XCircle className="w-4 h-4" />
|
||||
<div style={{ ...row, color: 'var(--color-red)' }}>
|
||||
<XCircle style={{ width: 16, height: 16, flexShrink: 0 }} />
|
||||
Error: {error}
|
||||
</div>
|
||||
)
|
||||
@@ -54,27 +56,42 @@ export default function JobStatus({ jobId, onDone }: Props) {
|
||||
|
||||
if (!job) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-xs text-slate-500">
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
<div style={{ ...row, opacity: 0.5 }}>
|
||||
<Loader2 style={{ width: 16, height: 16, flexShrink: 0 }} />
|
||||
Loading…
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const statusConfig: Record<string, { icon: React.ReactNode; text: string; color: string }> = {
|
||||
queued: { icon: <Loader2 className="w-4 h-4 animate-spin text-amber-500" />, text: 'Queued…', color: 'text-amber-600' },
|
||||
running: { icon: <Loader2 className="w-4 h-4 animate-spin text-brand-500" />, text: job.progress || 'Running…', color: 'text-brand-600' },
|
||||
done: { icon: <CheckCircle className="w-4 h-4 text-emerald-500" />, text: 'Complete', color: 'text-emerald-600' },
|
||||
error: { icon: <XCircle className="w-4 h-4 text-red-500" />, text: `Error: ${job.error || 'Failed'}`, color: 'text-red-600' },
|
||||
cancelled: { icon: <AlertCircle className="w-4 h-4 text-slate-400" />, text: 'Cancelled', color: 'text-slate-500' },
|
||||
const STATUS_COLOR: Record<string, string> = {
|
||||
queued: 'var(--color-amber)',
|
||||
running: 'rgb(var(--brand-500, 59 130 246))',
|
||||
done: 'var(--color-green)',
|
||||
error: 'var(--color-red)',
|
||||
cancelled: 'inherit',
|
||||
}
|
||||
|
||||
const config = statusConfig[job.status]
|
||||
const STATUS_TEXT: Record<string, string> = {
|
||||
queued: 'Queued…',
|
||||
running: job.progress || 'Running…',
|
||||
done: 'Complete',
|
||||
error: `Error: ${job.error || 'Failed'}`,
|
||||
cancelled: 'Cancelled',
|
||||
}
|
||||
|
||||
const color = STATUS_COLOR[job.status] ?? 'inherit'
|
||||
|
||||
return (
|
||||
<div className={`flex items-center gap-2 text-xs ${config.color}`}>
|
||||
{config.icon}
|
||||
<span className="truncate">{config.text}</span>
|
||||
<div style={{ ...row, color, opacity: job.status === 'cancelled' ? 0.5 : 1 }}>
|
||||
{(job.status === 'queued' || job.status === 'running') && (
|
||||
<Loader2 style={{ width: 16, height: 16, flexShrink: 0 }} />
|
||||
)}
|
||||
{job.status === 'done' && <CheckCircle style={{ width: 16, height: 16, flexShrink: 0 }} />}
|
||||
{job.status === 'error' && <XCircle style={{ width: 16, height: 16, flexShrink: 0 }} />}
|
||||
{job.status === 'cancelled' && <AlertCircle style={{ width: 16, height: 16, flexShrink: 0 }} />}
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{STATUS_TEXT[job.status] ?? job.status}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -20,24 +20,30 @@ const FILE_ICONS: Record<string, React.ElementType> = {
|
||||
|
||||
function FileIcon({ type }: { type?: string }) {
|
||||
const Icon = FILE_ICONS[type || ''] || File
|
||||
return <Icon className="w-4 h-4 text-slate-400" />
|
||||
return <Icon style={{ width: 16, height: 16, opacity: 0.5, flexShrink: 0 }} />
|
||||
}
|
||||
|
||||
export default function ResultFiles({ jobId, files }: Props) {
|
||||
if (!files.length) return null
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{files.map((f) => (
|
||||
<a
|
||||
key={f.name}
|
||||
href={downloadUrl(jobId, f.name)}
|
||||
download={f.name}
|
||||
className="flex items-center gap-3 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/50 border border-slate-200 dark:border-gray-700 hover:border-brand-400 dark:hover:border-brand-500 transition-colors group"
|
||||
className="button flat"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 12,
|
||||
padding: '6px 12px', borderRadius: 6,
|
||||
border: '1px solid var(--border-color)',
|
||||
textDecoration: 'none', fontSize: 12,
|
||||
}}
|
||||
>
|
||||
<FileIcon type={f.type} />
|
||||
<span className="flex-1 text-xs text-slate-700 dark:text-gray-300 truncate">{f.name}</span>
|
||||
<Download className="w-3.5 h-3.5 text-slate-400 group-hover:text-brand-500 transition-colors" />
|
||||
<span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.name}</span>
|
||||
<Download style={{ width: 14, height: 14, flexShrink: 0, opacity: 0.5 }} />
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import { X, Sun, Moon, Monitor, Settings, ChevronRight } from 'lucide-react'
|
||||
import { useTheme } from '../context/ThemeContext'
|
||||
|
||||
@@ -10,7 +9,7 @@ interface Props {
|
||||
|
||||
export default function SettingsPanel({ isOpen, onClose, onOpenFullSettings }: Props) {
|
||||
const { theme, setTheme } = useTheme()
|
||||
|
||||
|
||||
const handleOpenFullSettings = () => {
|
||||
onClose()
|
||||
onOpenFullSettings?.()
|
||||
@@ -18,78 +17,79 @@ export default function SettingsPanel({ isOpen, onClose, onOpenFullSettings }: P
|
||||
|
||||
if (!isOpen) return null
|
||||
|
||||
const THEMES = [
|
||||
{ id: 'light' as const, icon: Sun, label: 'Light' },
|
||||
{ id: 'dark' as const, icon: Moon, label: 'Dark' },
|
||||
{ id: 'system'as const, icon: Monitor, label: 'System' },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-start justify-center pt-16">
|
||||
<div className="absolute inset-0 bg-black/50" onClick={onClose} />
|
||||
<div className="relative w-full max-w-md mx-4 rounded-xl bg-white dark:bg-gray-900 shadow-2xl border border-slate-200 dark:border-gray-800">
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-slate-200 dark:border-gray-800">
|
||||
<h2 className="text-sm font-semibold text-slate-900 dark:text-white">Settings</h2>
|
||||
<div style={{ position: 'fixed', inset: 0, zIndex: 50, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', paddingTop: 64 }}>
|
||||
{/* Backdrop */}
|
||||
<div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)' }} onClick={onClose} />
|
||||
|
||||
{/* Panel */}
|
||||
<div style={{ position: 'relative', width: '100%', maxWidth: 420, margin: '0 16px', borderRadius: 12, border: '1px solid var(--border-color)', background: 'var(--body-background, var(--background))', boxShadow: '0 8px 32px rgba(0,0,0,0.2)' }}>
|
||||
|
||||
{/* Header */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 16px', borderBottom: '1px solid var(--border-color)' }}>
|
||||
<h2 style={{ margin: 0, fontSize: 13, fontWeight: 600 }}>Settings</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-1 rounded text-slate-400 hover:text-slate-600 dark:text-gray-500 dark:hover:text-gray-300"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
<X style={{ width: 16, height: 16 }} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-4 space-y-4">
|
||||
<div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
|
||||
{/* Theme */}
|
||||
<div>
|
||||
<label className="text-xs font-medium text-slate-500 dark:text-gray-400 uppercase tracking-wider block mb-2">
|
||||
<label style={{ display: 'block', marginBottom: 8, fontSize: 10, fontWeight: 600, opacity: 0.5, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
|
||||
Theme
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setTheme('light')}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-xs font-medium transition-colors ${
|
||||
theme === 'light'
|
||||
? 'bg-brand-50 dark:bg-brand-950/30 border-brand-400 text-brand-600 dark:text-brand-400'
|
||||
: 'bg-white dark:bg-gray-800 border-slate-200 dark:border-gray-700 text-slate-600 dark:text-gray-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Sun className="w-3.5 h-3.5" />
|
||||
Light
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTheme('dark')}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-xs font-medium transition-colors ${
|
||||
theme === 'dark'
|
||||
? 'bg-brand-50 dark:bg-brand-950/30 border-brand-400 text-brand-600 dark:text-brand-400'
|
||||
: 'bg-white dark:bg-gray-800 border-slate-200 dark:border-gray-700 text-slate-600 dark:text-gray-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Moon className="w-3.5 h-3.5" />
|
||||
Dark
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTheme('system')}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-xs font-medium transition-colors ${
|
||||
theme === 'system'
|
||||
? 'bg-brand-50 dark:bg-brand-950/30 border-brand-400 text-brand-600 dark:text-brand-400'
|
||||
: 'bg-white dark:bg-gray-800 border-slate-200 dark:border-gray-700 text-slate-600 dark:text-gray-400 hover:border-brand-400'
|
||||
}`}
|
||||
>
|
||||
<Monitor className="w-3.5 h-3.5" />
|
||||
System
|
||||
</button>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
{THEMES.map(({ id, icon: Icon, label }) => {
|
||||
const isActive = theme === id
|
||||
return (
|
||||
<button
|
||||
key={id}
|
||||
onClick={() => setTheme(id)}
|
||||
style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
padding: '6px 12px', borderRadius: 6, fontSize: 12, fontWeight: 500,
|
||||
border: `1px solid ${isActive ? 'rgb(var(--brand-500, 59 130 246))' : 'var(--border-color)'}`,
|
||||
background: isActive ? 'rgba(var(--brand-500, 59 130 246), 0.1)' : 'transparent',
|
||||
color: isActive ? 'rgb(var(--brand-500, 59 130 246))' : 'inherit',
|
||||
cursor: 'pointer', transition: 'border-color 0.15s, background 0.15s',
|
||||
}}
|
||||
>
|
||||
<Icon style={{ width: 14, height: 14 }} />
|
||||
{label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="border-t border-slate-200 dark:border-gray-800 pt-4">
|
||||
|
||||
{/* Full Settings link */}
|
||||
<div style={{ borderTop: '1px solid var(--border-color)', paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
<button
|
||||
onClick={handleOpenFullSettings}
|
||||
className="w-full flex items-center justify-between p-3 rounded-lg bg-slate-50 dark:bg-gray-800 hover:bg-slate-100 dark:hover:bg-gray-750 transition-colors group"
|
||||
style={{
|
||||
width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||
padding: 12, borderRadius: 8, border: '1px solid var(--border-color)',
|
||||
background: 'transparent', cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Settings className="w-4 h-4 text-slate-500 dark:text-gray-400" />
|
||||
<span className="text-sm font-medium text-slate-700 dark:text-gray-300">
|
||||
Full Settings
|
||||
</span>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<Settings style={{ width: 16, height: 16, opacity: 0.6, flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 13, fontWeight: 500 }}>Full Settings</span>
|
||||
</div>
|
||||
<ChevronRight className="w-4 h-4 text-slate-400 group-hover:text-slate-600 dark:group-hover:text-gray-300 transition-colors" />
|
||||
<ChevronRight style={{ width: 16, height: 16, opacity: 0.4 }} />
|
||||
</button>
|
||||
<p className="mt-1.5 text-xs text-slate-400 dark:text-gray-500 px-1">
|
||||
<p style={{ margin: 0, fontSize: 11, opacity: 0.5, padding: '0 4px' }}>
|
||||
Configure Subsonic integration, manage AI models, and more.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
+328
-144
@@ -1,3 +1,11 @@
|
||||
/**
|
||||
* Sidebar.tsx — Phase 2 MetroUI migration
|
||||
*
|
||||
* All business logic (state, queries, handlers) unchanged from Phase 1.
|
||||
* Tailwind classes replaced with MetroUI CSS + inline styles.
|
||||
* Accordion sections managed with React state (no data-role, avoids Metro JS
|
||||
* conflicts with React's virtual DOM).
|
||||
*/
|
||||
import React, { useState, useRef, useMemo } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
@@ -19,13 +27,13 @@ import AutoPipelineDialog from './AutoPipelineDialog'
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const JOB_COLORS: Record<string, string> = {
|
||||
separate: 'text-brand-500',
|
||||
transcribe: 'text-purple-500',
|
||||
'abc-convert': 'text-emerald-500',
|
||||
pipeline: 'text-rose-500',
|
||||
lrc_align: 'text-amber-500',
|
||||
mix: 'text-brand-500',
|
||||
const JOB_DOT_COLORS: Record<string, string> = {
|
||||
separate: 'var(--color-blue)',
|
||||
transcribe: 'var(--color-violet)',
|
||||
'abc-convert': 'var(--color-green)',
|
||||
pipeline: 'var(--color-red)',
|
||||
lrc_align: 'var(--color-amber)',
|
||||
mix: 'var(--color-blue)',
|
||||
}
|
||||
|
||||
const JOB_ICONS: Record<string, React.ElementType> = {
|
||||
@@ -37,13 +45,22 @@ const JOB_ICONS: Record<string, React.ElementType> = {
|
||||
mix: Music2,
|
||||
}
|
||||
|
||||
const STATUS_ICON_COLOR: Record<Job['status'], string> = {
|
||||
running: 'var(--color-blue)',
|
||||
queued: 'var(--color-amber)',
|
||||
done: 'var(--color-green)',
|
||||
error: 'var(--color-red)',
|
||||
cancelled: 'var(--color-gray)',
|
||||
}
|
||||
|
||||
function StatusDot({ status }: { status: Job['status'] }) {
|
||||
const color = STATUS_ICON_COLOR[status] ?? 'var(--color-gray)'
|
||||
switch (status) {
|
||||
case 'running': return <Loader2 className="w-3 h-3 text-brand-400 animate-spin shrink-0" />
|
||||
case 'queued': return <Clock className="w-3 h-3 text-amber-400 shrink-0" />
|
||||
case 'done': return <CheckCircle className="w-3 h-3 text-emerald-400 shrink-0" />
|
||||
case 'error': return <XCircle className="w-3 h-3 text-red-400 shrink-0" />
|
||||
case 'cancelled': return <AlertCircle className="w-3 h-3 text-gray-400 shrink-0" />
|
||||
case 'running': return <Loader2 size={12} style={{ color, flexShrink: 0, animation: 'spin 1s linear infinite' }} />
|
||||
case 'queued': return <Clock size={12} style={{ color, flexShrink: 0 }} />
|
||||
case 'done': return <CheckCircle size={12} style={{ color, flexShrink: 0 }} />
|
||||
case 'error': return <XCircle size={12} style={{ color, flexShrink: 0 }} />
|
||||
case 'cancelled': return <AlertCircle size={12} style={{ color, flexShrink: 0 }} />
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +75,17 @@ function timeSince(iso: string | null): string {
|
||||
return `${Math.floor(h / 24)}d ago`
|
||||
}
|
||||
|
||||
// Shared section-header style (accordion trigger row)
|
||||
const sectionHeaderStyle: React.CSSProperties = {
|
||||
display: 'flex', alignItems: 'center', gap: 6,
|
||||
padding: '6px 10px',
|
||||
cursor: 'pointer', userSelect: 'none',
|
||||
borderBottom: '1px solid var(--border-color)',
|
||||
fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
|
||||
width: '100%', background: 'none', border: 'none', textAlign: 'left',
|
||||
color: 'var(--label-color)',
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Active job item (with cancel)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -65,7 +93,7 @@ function timeSince(iso: string | null): string {
|
||||
function ActiveJobItem({ job, onCancelled }: { job: Job; onCancelled: () => void }) {
|
||||
const [cancelling, setCancelling] = useState(false)
|
||||
const Icon = JOB_ICONS[job.job_type] ?? FolderOpen
|
||||
const colorCls = JOB_COLORS[job.job_type] ?? 'text-gray-400'
|
||||
const dotColor = JOB_DOT_COLORS[job.job_type] ?? 'var(--color-gray)'
|
||||
|
||||
async function handleCancel(e: React.MouseEvent) {
|
||||
e.stopPropagation()
|
||||
@@ -76,14 +104,22 @@ function ActiveJobItem({ job, onCancelled }: { job: Job; onCancelled: () => void
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-slate-50 dark:bg-gray-800/60 border border-slate-200 dark:border-gray-700/50">
|
||||
<Icon className={`w-3.5 h-3.5 shrink-0 ${colorCls}`} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 8,
|
||||
padding: '6px 10px',
|
||||
borderRadius: 6, marginBottom: 4,
|
||||
background: 'var(--background)',
|
||||
border: '1px solid var(--border-color)',
|
||||
}}>
|
||||
<Icon size={13} style={{ color: dotColor, flexShrink: 0 }} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{job.job_type.replace('-', ' ').replace('_', ' ')}
|
||||
</p>
|
||||
</div>
|
||||
{job.progress && (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-500 truncate leading-tight">{job.progress}</p>
|
||||
<div style={{ fontSize: 10, opacity: 0.55, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{job.progress}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<StatusDot status={job.status} />
|
||||
@@ -91,19 +127,22 @@ function ActiveJobItem({ job, onCancelled }: { job: Job; onCancelled: () => void
|
||||
onClick={handleCancel}
|
||||
disabled={cancelling}
|
||||
title="Cancel"
|
||||
className="p-1 rounded text-slate-300 hover:text-red-400 dark:text-gray-600 dark:hover:text-red-400 transition-colors shrink-0"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 3, flexShrink: 0 }}
|
||||
>
|
||||
{cancelling ? <Loader2 className="w-3 h-3 animate-spin" /> : <X className="w-3 h-3" />}
|
||||
{cancelling
|
||||
? <Loader2 size={11} style={{ animation: 'spin 1s linear infinite' }} />
|
||||
: <X size={11} />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Project item
|
||||
// Project tile
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function ProjectItem({
|
||||
function ProjectTile({
|
||||
project,
|
||||
isOpen,
|
||||
onOpen,
|
||||
@@ -115,6 +154,7 @@ function ProjectItem({
|
||||
onDeleted: () => void
|
||||
}) {
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [hovered, setHovered] = useState(false)
|
||||
|
||||
async function handleDelete(e: React.MouseEvent) {
|
||||
e.stopPropagation()
|
||||
@@ -125,30 +165,50 @@ function ProjectItem({
|
||||
onDeleted()
|
||||
}
|
||||
|
||||
const accentColor = `rgb(var(--brand-500, 59 130 246))`
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={onOpen}
|
||||
className={`group w-full flex items-center gap-2 px-3 py-2 rounded-lg border text-left transition-colors cursor-pointer ${
|
||||
isOpen
|
||||
? 'border-brand-400/50 bg-brand-50 dark:bg-brand-950/20 text-brand-700 dark:text-brand-300'
|
||||
: 'border-slate-200 dark:border-gray-700/60 hover:bg-slate-50 dark:hover:bg-gray-800/50 hover:border-brand-400/50'
|
||||
}`}
|
||||
onMouseEnter={() => setHovered(true)}
|
||||
onMouseLeave={() => setHovered(false)}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 8,
|
||||
padding: '7px 10px',
|
||||
borderRadius: 6, marginBottom: 3, cursor: 'pointer',
|
||||
border: `1px solid ${isOpen ? accentColor : 'var(--border-color)'}`,
|
||||
background: isOpen
|
||||
? `rgba(var(--brand-500, 59 130 246), 0.08)`
|
||||
: hovered ? 'var(--background)' : 'transparent',
|
||||
transition: 'background 0.15s, border-color 0.15s',
|
||||
}}
|
||||
>
|
||||
<Music2 className="w-3.5 h-3.5 shrink-0 text-brand-500" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">{project.name}</p>
|
||||
<Music2 size={13} style={{ color: accentColor, flexShrink: 0 }} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{
|
||||
fontSize: 12, fontWeight: 500,
|
||||
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
|
||||
color: isOpen ? accentColor : undefined,
|
||||
}}>
|
||||
{project.name}
|
||||
</div>
|
||||
{project.tab_label && (
|
||||
<p className="text-[10px] text-brand-500 dark:text-brand-400 truncate leading-tight">{project.tab_label}</p>
|
||||
<div style={{ fontSize: 10, color: accentColor, opacity: 0.8, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{project.tab_label}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500">{timeSince(project.created_at)}</p>
|
||||
<div style={{ fontSize: 10, opacity: 0.45 }}>{timeSince(project.created_at)}</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
disabled={deleting}
|
||||
title="Delete project"
|
||||
className="shrink-0 p-1 rounded text-slate-300 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 transition-colors opacity-0 group-hover:opacity-100"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 3, flexShrink: 0, opacity: hovered ? 1 : 0, transition: 'opacity 0.15s' }}
|
||||
>
|
||||
{deleting ? <Loader2 className="w-3 h-3 animate-spin" /> : <Trash2 className="w-3 h-3" />}
|
||||
{deleting
|
||||
? <Loader2 size={11} style={{ animation: 'spin 1s linear infinite' }} />
|
||||
: <Trash2 size={11} />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
@@ -223,79 +283,98 @@ function SubsonicPanel() {
|
||||
finally { setDeletingFile(null) }
|
||||
}
|
||||
|
||||
const skyColor = 'var(--color-blue, #0ea5e9)'
|
||||
|
||||
return (
|
||||
<div className="border-b border-slate-200 dark:border-gray-800">
|
||||
<div style={{ borderBottom: '1px solid var(--border-color)' }}>
|
||||
{/* Accordion header */}
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="w-full flex items-center gap-2 px-3 py-2.5 text-left hover:bg-slate-100 dark:hover:bg-gray-900/50 transition-colors"
|
||||
style={{ ...sectionHeaderStyle, color: skyColor }}
|
||||
>
|
||||
<Radio className="w-3.5 h-3.5 text-sky-500 shrink-0" />
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-sky-500 flex-1">Subsonic Import</span>
|
||||
<Radio size={13} style={{ color: skyColor, flexShrink: 0 }} />
|
||||
<span style={{ flex: 1 }}>Subsonic Import</span>
|
||||
{open
|
||||
? <ChevronUp className="w-3 h-3 text-slate-400 shrink-0" />
|
||||
: <ChevronDown className="w-3 h-3 text-slate-400 shrink-0" />}
|
||||
? <ChevronUp size={11} style={{ opacity: 0.5 }} />
|
||||
: <ChevronDown size={11} style={{ opacity: 0.5 }} />}
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="px-3 pb-3 space-y-2">
|
||||
{/* Search input */}
|
||||
<div className="flex gap-1.5">
|
||||
<div style={{ padding: '8px 10px 10px' }}>
|
||||
{/* Search row */}
|
||||
<div style={{ display: 'flex', gap: 6, marginBottom: 6 }}>
|
||||
<input
|
||||
ref={inputRef}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && doSearch()}
|
||||
placeholder="Search songs…"
|
||||
className="flex-1 rounded-md bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-2.5 py-1.5 text-xs text-slate-900 dark:text-gray-100 placeholder-slate-400 focus:border-sky-400 focus:outline-none"
|
||||
style={{
|
||||
flex: 1, padding: '5px 8px', fontSize: 12, borderRadius: 4,
|
||||
border: '1px solid var(--border-color)',
|
||||
background: 'var(--input-background, var(--background))',
|
||||
color: 'inherit', outline: 'none',
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
onClick={doSearch}
|
||||
disabled={searching || !query.trim()}
|
||||
className="rounded-md bg-sky-500 hover:bg-sky-400 disabled:bg-slate-200 dark:disabled:bg-gray-800 disabled:text-slate-400 px-2.5 py-1.5 text-xs font-medium text-white transition-colors shrink-0"
|
||||
className="button"
|
||||
style={{ background: skyColor, color: '#fff', padding: '5px 10px', borderRadius: 4, border: 'none', flexShrink: 0 }}
|
||||
>
|
||||
{searching ? <Loader2 className="w-3 h-3 animate-spin" /> : <Search className="w-3 h-3" />}
|
||||
{searching
|
||||
? <Loader2 size={11} style={{ animation: 'spin 1s linear infinite' }} />
|
||||
: <Search size={11} />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Errors */}
|
||||
{searchErr && <p className="text-xs text-red-500 dark:text-red-400">{searchErr}</p>}
|
||||
{importErr && <p className="text-xs text-red-500 dark:text-red-400 break-all">{importErr}</p>}
|
||||
{/* Error messages */}
|
||||
{searchErr && <p style={{ fontSize: 11, color: 'var(--color-red)', marginBottom: 4 }}>{searchErr}</p>}
|
||||
{importErr && <p style={{ fontSize: 11, color: 'var(--color-red)', marginBottom: 4, wordBreak: 'break-all' }}>{importErr}</p>}
|
||||
|
||||
{/* Search results */}
|
||||
{results.length > 0 && (
|
||||
<div className="space-y-1 max-h-52 overflow-y-auto pr-0.5">
|
||||
<div style={{ maxHeight: 200, overflowY: 'auto', marginBottom: 6 }}>
|
||||
{results.map((song) => {
|
||||
const done = importedIds.has(song.id)
|
||||
const busy = importing === song.id
|
||||
return (
|
||||
<div
|
||||
key={song.id}
|
||||
className="flex items-start gap-2 rounded-lg border border-slate-200 dark:border-gray-700/60 bg-white dark:bg-gray-900/50 px-2.5 py-2"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'flex-start', gap: 8,
|
||||
padding: '7px 8px', marginBottom: 3, borderRadius: 5,
|
||||
border: '1px solid var(--border-color)',
|
||||
background: 'var(--background)',
|
||||
}}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate leading-tight">
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{song.title}
|
||||
</p>
|
||||
</div>
|
||||
{song.artist && (
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500 truncate leading-tight">
|
||||
<div style={{ fontSize: 10, opacity: 0.55, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{song.artist}{song.album ? ` · ${song.album}` : ''}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-600 mt-0.5">
|
||||
{song.duration ? formatDuration(song.duration) : ''}{song.bitRate ? ` · ${song.bitRate} kbps` : ''}{song.suffix ? ` · ${song.suffix.toUpperCase()}` : ''}
|
||||
</p>
|
||||
<div style={{ fontSize: 10, opacity: 0.4 }}>
|
||||
{song.duration ? formatDuration(song.duration) : ''}
|
||||
{song.bitRate ? ` · ${song.bitRate} kbps` : ''}
|
||||
{song.suffix ? ` · ${song.suffix.toUpperCase()}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => doImport(song)}
|
||||
disabled={busy || done}
|
||||
title={done ? 'Imported' : 'Import'}
|
||||
className="shrink-0 p-1.5 rounded-md border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800 hover:border-sky-400 hover:text-sky-500 disabled:opacity-60 transition-colors"
|
||||
className="button cycle flat"
|
||||
style={{ flexShrink: 0, padding: 5 }}
|
||||
>
|
||||
{busy
|
||||
? <Loader2 className="w-3 h-3 animate-spin text-sky-400" />
|
||||
? <Loader2 size={11} style={{ color: skyColor, animation: 'spin 1s linear infinite' }} />
|
||||
: done
|
||||
? <CheckCircle2 className="w-3 h-3 text-emerald-500" />
|
||||
: <Download className="w-3 h-3 text-slate-500 dark:text-gray-400" />}
|
||||
? <CheckCircle2 size={11} style={{ color: 'var(--color-green)' }} />
|
||||
: <Download size={11} />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
@@ -303,40 +382,26 @@ function SubsonicPanel() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Imported files list */}
|
||||
{/* Imported files */}
|
||||
{importedFiles.length > 0 && (
|
||||
<div>
|
||||
<p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 dark:text-gray-600 mb-1">Imported Files</p>
|
||||
<div className="space-y-1 max-h-40 overflow-y-auto">
|
||||
<div style={{
|
||||
fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
|
||||
opacity: 0.45, marginBottom: 4,
|
||||
}}>
|
||||
Imported Files
|
||||
</div>
|
||||
<div style={{ maxHeight: 160, overflowY: 'auto' }}>
|
||||
{importedFiles.map((f) => {
|
||||
const isDeleting = deletingFile === f.filename
|
||||
return (
|
||||
<div
|
||||
<ImportedFileRow
|
||||
key={f.path}
|
||||
className="group flex items-center gap-2 rounded-lg border border-slate-200 dark:border-gray-700/60 bg-white dark:bg-gray-900/50 px-2.5 py-1.5"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">{f.filename}</p>
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500">{(f.size / 1024 / 1024).toFixed(1)} MB</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setAutoTarget(f)}
|
||||
title="Auto pipeline"
|
||||
className="shrink-0 p-1 rounded text-slate-300 dark:text-gray-600 hover:text-amber-500 dark:hover:text-amber-400 transition-colors opacity-0 group-hover:opacity-100"
|
||||
>
|
||||
<Zap className="w-3 h-3" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => doDeleteImport(f.filename)}
|
||||
disabled={isDeleting}
|
||||
title="Delete import"
|
||||
className="shrink-0 p-1 rounded text-slate-300 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 transition-colors opacity-0 group-hover:opacity-100"
|
||||
>
|
||||
{isDeleting
|
||||
? <Loader2 className="w-3 h-3 animate-spin" />
|
||||
: <Trash2 className="w-3 h-3" />}
|
||||
</button>
|
||||
</div>
|
||||
file={f}
|
||||
isDeleting={isDeleting}
|
||||
onDelete={() => doDeleteImport(f.filename)}
|
||||
onAutoPipeline={() => setAutoTarget(f)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
@@ -361,6 +426,55 @@ function SubsonicPanel() {
|
||||
)
|
||||
}
|
||||
|
||||
function ImportedFileRow({
|
||||
file, isDeleting, onDelete, onAutoPipeline,
|
||||
}: {
|
||||
file: ImportedFile
|
||||
isDeleting: boolean
|
||||
onDelete: () => void
|
||||
onAutoPipeline: () => void
|
||||
}) {
|
||||
const [hovered, setHovered] = useState(false)
|
||||
return (
|
||||
<div
|
||||
onMouseEnter={() => setHovered(true)}
|
||||
onMouseLeave={() => setHovered(false)}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6,
|
||||
padding: '5px 8px', marginBottom: 3, borderRadius: 5,
|
||||
border: '1px solid var(--border-color)',
|
||||
background: 'var(--background)',
|
||||
}}
|
||||
>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{file.filename}
|
||||
</div>
|
||||
<div style={{ fontSize: 10, opacity: 0.45 }}>{(file.size / 1024 / 1024).toFixed(1)} MB</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={onAutoPipeline}
|
||||
title="Auto pipeline"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 3, flexShrink: 0, opacity: hovered ? 1 : 0, transition: 'opacity 0.15s', color: 'var(--color-amber)' }}
|
||||
>
|
||||
<Zap size={11} />
|
||||
</button>
|
||||
<button
|
||||
onClick={onDelete}
|
||||
disabled={isDeleting}
|
||||
title="Delete import"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 3, flexShrink: 0, opacity: hovered ? 1 : 0, transition: 'opacity 0.15s', color: 'var(--color-red)' }}
|
||||
>
|
||||
{isDeleting
|
||||
? <Loader2 size={11} style={{ animation: 'spin 1s linear infinite' }} />
|
||||
: <Trash2 size={11} />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sidebar
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -376,6 +490,7 @@ interface Props {
|
||||
export default function Sidebar({ isOpen, onToggle, onOpenProject, onDeleteProject, openTabIds }: Props) {
|
||||
const queryClient = useQueryClient()
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [jobsOpen, setJobsOpen] = useState(true)
|
||||
|
||||
const { data: jobs = [] } = useQuery({
|
||||
queryKey: ['jobs'],
|
||||
@@ -389,13 +504,12 @@ export default function Sidebar({ isOpen, onToggle, onOpenProject, onDeleteProje
|
||||
refetchInterval: 8000,
|
||||
})
|
||||
|
||||
// Filter projects based on search query
|
||||
const filteredProjects = useMemo(() => {
|
||||
if (!searchQuery.trim()) return projects
|
||||
const query = searchQuery.toLowerCase()
|
||||
return projects.filter(p =>
|
||||
p.name.toLowerCase().includes(query) ||
|
||||
p.tab_label.toLowerCase().includes(query)
|
||||
const q = searchQuery.toLowerCase()
|
||||
return projects.filter(p =>
|
||||
p.name.toLowerCase().includes(q) ||
|
||||
p.tab_label.toLowerCase().includes(q)
|
||||
)
|
||||
}, [projects, searchQuery])
|
||||
|
||||
@@ -403,37 +517,73 @@ export default function Sidebar({ isOpen, onToggle, onOpenProject, onDeleteProje
|
||||
|
||||
function invalidate() { queryClient.invalidateQueries({ queryKey: ['jobs'] }) }
|
||||
|
||||
const accentColor = `rgb(var(--brand-500, 59 130 246))`
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={`relative flex-shrink-0 flex flex-col border-r border-slate-200 dark:border-gray-800 bg-slate-50 dark:bg-gray-950 transition-all duration-200 ease-in-out ${
|
||||
isOpen ? 'sidebar-open' : 'sidebar-closed'
|
||||
}`}
|
||||
className={isOpen ? 'sidebar-open' : 'sidebar-closed'}
|
||||
style={{
|
||||
position: 'relative',
|
||||
flexShrink: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
borderRight: '1px solid var(--border-color)',
|
||||
background: 'var(--sidebar-background, var(--body-background))',
|
||||
transition: 'width 0.2s ease-in-out',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{/* Toggle tab — always visible */}
|
||||
<button
|
||||
onClick={onToggle}
|
||||
title={isOpen ? 'Collapse sidebar' : 'Expand sidebar'}
|
||||
className={`absolute -right-3.5 top-6 z-10 flex items-center justify-center w-7 h-7 rounded-full bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 shadow-sm text-slate-400 hover:text-brand-500 dark:text-gray-500 dark:hover:text-brand-400 transition-colors`}
|
||||
className="button cycle flat"
|
||||
style={{
|
||||
position: 'absolute', right: -14, top: 24, zIndex: 10,
|
||||
width: 28, height: 28, borderRadius: '50%',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
padding: 0,
|
||||
background: 'var(--body-background)',
|
||||
border: '1px solid var(--border-color)',
|
||||
boxShadow: '0 1px 3px rgba(0,0,0,0.12)',
|
||||
}}
|
||||
>
|
||||
{isOpen ? <ChevronLeft className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
|
||||
{isOpen
|
||||
? <ChevronLeft size={14} />
|
||||
: <ChevronRight size={14} />}
|
||||
</button>
|
||||
|
||||
{/* Collapsed indicator strip */}
|
||||
{/* ── Collapsed indicator strip ──────────────────────────────────────── */}
|
||||
{!isOpen && (
|
||||
<div className="flex flex-col items-center gap-3 pt-16 px-2">
|
||||
<div style={{
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center',
|
||||
gap: 12, paddingTop: 64, paddingLeft: 8, paddingRight: 8,
|
||||
}}>
|
||||
{activeJobs.length > 0 && (
|
||||
<div className="relative">
|
||||
<Loader2 className="w-5 h-5 text-brand-400 animate-spin" />
|
||||
<span className="absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full bg-brand-500 text-white text-[9px] flex items-center justify-center font-bold">
|
||||
<div style={{ position: 'relative' }}>
|
||||
<Loader2 size={18} style={{ color: accentColor, animation: 'spin 1s linear infinite' }} />
|
||||
<span style={{
|
||||
position: 'absolute', top: -4, right: -4,
|
||||
width: 14, height: 14, borderRadius: '50%',
|
||||
background: accentColor, color: '#fff',
|
||||
fontSize: 9, fontWeight: 700,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
{activeJobs.length}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<Radio className="w-5 h-5 text-slate-400 dark:text-gray-600" />
|
||||
<Radio size={18} style={{ opacity: 0.35 }} />
|
||||
{projects.length > 0 && (
|
||||
<div className="relative">
|
||||
<FolderOpen className="w-5 h-5 text-slate-400 dark:text-gray-600" />
|
||||
<span className="absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full bg-slate-400 dark:bg-gray-600 text-white text-[9px] flex items-center justify-center font-bold">
|
||||
<div style={{ position: 'relative' }}>
|
||||
<FolderOpen size={18} style={{ opacity: 0.35 }} />
|
||||
<span style={{
|
||||
position: 'absolute', top: -4, right: -4,
|
||||
width: 14, height: 14, borderRadius: '50%',
|
||||
background: 'var(--color-gray, #64748b)', color: '#fff',
|
||||
fontSize: 9, fontWeight: 700,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
}}>
|
||||
{projects.length}
|
||||
</span>
|
||||
</div>
|
||||
@@ -441,74 +591,108 @@ export default function Sidebar({ isOpen, onToggle, onOpenProject, onDeleteProje
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Expanded content */}
|
||||
{/* ── Expanded content ───────────────────────────────────────────────── */}
|
||||
{isOpen && (
|
||||
<div className="flex flex-col flex-1 overflow-hidden">
|
||||
{/* Active jobs */}
|
||||
<div className="p-3 border-b border-slate-200 dark:border-gray-800">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-amber-500">
|
||||
In Progress
|
||||
</span>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', flex: 1, overflow: 'hidden' }}>
|
||||
|
||||
{/* Active jobs accordion */}
|
||||
<div style={{ borderBottom: '1px solid var(--border-color)' }}>
|
||||
<button
|
||||
onClick={() => setJobsOpen((v) => !v)}
|
||||
style={{ ...sectionHeaderStyle, color: 'var(--color-amber, #f59e0b)', borderBottom: 'none' }}
|
||||
>
|
||||
<span style={{ flex: 1 }}>In Progress</span>
|
||||
{activeJobs.length > 0 && (
|
||||
<span className="ml-auto text-xs bg-amber-500 text-white px-1.5 py-0.5 rounded-full font-bold">
|
||||
<span style={{
|
||||
background: 'var(--color-amber, #f59e0b)', color: '#fff',
|
||||
fontSize: 10, fontWeight: 700, borderRadius: 10,
|
||||
padding: '1px 6px',
|
||||
}}>
|
||||
{activeJobs.length}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{jobsOpen
|
||||
? <ChevronUp size={11} style={{ opacity: 0.5, marginLeft: 4 }} />
|
||||
: <ChevronDown size={11} style={{ opacity: 0.5, marginLeft: 4 }} />}
|
||||
</button>
|
||||
|
||||
{activeJobs.length === 0 ? (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 italic text-center py-2">No active jobs</p>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
{activeJobs.map((job) => (
|
||||
<ActiveJobItem key={job.id} job={job} onCancelled={invalidate} />
|
||||
))}
|
||||
{jobsOpen && (
|
||||
<div style={{ padding: '4px 8px 8px' }}>
|
||||
{activeJobs.length === 0 ? (
|
||||
<p style={{ fontSize: 11, opacity: 0.4, fontStyle: 'italic', textAlign: 'center', padding: '6px 0' }}>
|
||||
No active jobs
|
||||
</p>
|
||||
) : (
|
||||
activeJobs.map((job) => (
|
||||
<ActiveJobItem key={job.id} job={job} onCancelled={invalidate} />
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Subsonic import */}
|
||||
{/* Subsonic import accordion */}
|
||||
<SubsonicPanel />
|
||||
|
||||
{/* Projects */}
|
||||
<div className="flex-1 overflow-y-auto p-3 space-y-1.5">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-brand-500">Projects</span>
|
||||
{/* Projects list */}
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: '8px 8px 8px' }}>
|
||||
{/* Section header */}
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6,
|
||||
marginBottom: 6, paddingLeft: 2,
|
||||
}}>
|
||||
<span style={{
|
||||
fontSize: 11, fontWeight: 700, letterSpacing: '0.08em',
|
||||
textTransform: 'uppercase', color: accentColor,
|
||||
}}>
|
||||
Projects
|
||||
</span>
|
||||
{projects.length > 0 && (
|
||||
<span className="ml-auto text-xs text-slate-400 dark:text-gray-600">
|
||||
<span style={{ marginLeft: 'auto', fontSize: 10, opacity: 0.45 }}>
|
||||
{filteredProjects.length}/{projects.length}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Search box for projects */}
|
||||
<div className="relative mb-2">
|
||||
<Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-slate-400" />
|
||||
{/* Search input */}
|
||||
<div style={{ position: 'relative', marginBottom: 8 }}>
|
||||
<Search size={11} style={{
|
||||
position: 'absolute', left: 8, top: '50%', transform: 'translateY(-50%)',
|
||||
opacity: 0.4, pointerEvents: 'none',
|
||||
}} />
|
||||
<input
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder="Search projects..."
|
||||
className="w-full rounded-md bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 pl-7 pr-2 py-1.5 text-xs text-slate-900 dark:text-gray-100 placeholder-slate-400 focus:border-brand-400 focus:outline-none"
|
||||
placeholder="Search projects…"
|
||||
style={{
|
||||
width: '100%', padding: '5px 28px 5px 26px', fontSize: 12, borderRadius: 5,
|
||||
border: '1px solid var(--border-color)',
|
||||
background: 'var(--input-background, var(--background))',
|
||||
color: 'inherit', outline: 'none', boxSizing: 'border-box',
|
||||
}}
|
||||
/>
|
||||
{searchQuery && (
|
||||
<button
|
||||
onClick={() => setSearchQuery('')}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
|
||||
style={{
|
||||
position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)',
|
||||
background: 'none', border: 'none', cursor: 'pointer', opacity: 0.45, padding: 2,
|
||||
}}
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
<X size={10} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Project items */}
|
||||
{filteredProjects.length === 0 ? (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 italic text-center py-4">
|
||||
{searchQuery ? 'No projects match your search.' : 'Completed separations appear here.'}
|
||||
<p style={{ fontSize: 11, opacity: 0.4, fontStyle: 'italic', textAlign: 'center', padding: '12px 0' }}>
|
||||
{searchQuery ? 'No projects match.' : 'Completed separations appear here.'}
|
||||
</p>
|
||||
) : (
|
||||
filteredProjects.map((project) => (
|
||||
<ProjectItem
|
||||
<ProjectTile
|
||||
key={project.id}
|
||||
project={project}
|
||||
isOpen={openTabIds.includes(project.id)}
|
||||
|
||||
@@ -30,11 +30,26 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
r = theme
|
||||
}
|
||||
setResolved(r)
|
||||
// Tailwind dark mode (for components not yet migrated to MetroUI)
|
||||
if (r === 'dark') {
|
||||
root.classList.add('dark')
|
||||
} else {
|
||||
root.classList.remove('dark')
|
||||
}
|
||||
// MetroUI dark mode
|
||||
root.setAttribute('data-theme', r)
|
||||
// Explicit CSS custom properties — guaranteed regardless of MetroUI var availability
|
||||
const dark = r === 'dark'
|
||||
root.style.setProperty('--body-background', dark ? '#0f172a' : '#ffffff')
|
||||
root.style.setProperty('--background', dark ? '#1e293b' : '#f8fafc')
|
||||
root.style.setProperty('--border-color', dark ? '#334155' : '#e2e8f0')
|
||||
root.style.setProperty('--sidebar-background', dark ? '#0f172a' : '#f1f5f9')
|
||||
root.style.setProperty('--color-green', '#22c55e')
|
||||
root.style.setProperty('--color-red', '#ef4444')
|
||||
root.style.setProperty('--color-amber', '#f59e0b')
|
||||
root.style.setProperty('--color-blue', '#0ea5e9')
|
||||
root.style.setProperty('--color-violet', '#8b5cf6')
|
||||
root.style.setProperty('--color-teal', '#14b8a6')
|
||||
}
|
||||
|
||||
apply()
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
/*
|
||||
* index.css — StemEngine global styles
|
||||
*
|
||||
* Phase 1 (MetroUI migration): Tailwind stays active for inner pages
|
||||
* (Separator, ProjectDetail, Settings, Sidebar). MetroUI is loaded in
|
||||
* main.tsx after this file. Both systems coexist during the migration;
|
||||
* @tailwind directives are removed in Phase 6 once all components are migrated.
|
||||
*/
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@@ -3,6 +3,9 @@ import ReactDOM from 'react-dom/client'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import App from './App'
|
||||
import './index.css'
|
||||
// MetroUI — Phase 1 shell redesign
|
||||
import '@olton/metroui/lib/metro.css'
|
||||
import '@olton/metroui/lib/icons.css'
|
||||
import '@fontsource/archivo'
|
||||
import '@fontsource/eb-garamond'
|
||||
import '@fontsource/inter'
|
||||
|
||||
@@ -34,13 +34,13 @@ const STATIC_OPTIONS = [
|
||||
|
||||
|
||||
// Color classes for each stem type
|
||||
const STEM_COLORS: Record<string, string> = {
|
||||
vocals: 'bg-sky-50 dark:bg-sky-950/40 border-sky-300/50 text-sky-700 dark:text-sky-300 hover:border-sky-400',
|
||||
drums: 'bg-orange-50 dark:bg-orange-950/40 border-orange-300/50 text-orange-700 dark:text-orange-300 hover:border-orange-400',
|
||||
bass: 'bg-purple-50 dark:bg-purple-950/40 border-purple-300/50 text-purple-700 dark:text-purple-300 hover:border-purple-400',
|
||||
other: 'bg-slate-50 dark:bg-gray-800 border-slate-200 dark:border-gray-700 text-slate-600 dark:text-gray-300 hover:border-slate-400',
|
||||
guitar: 'bg-emerald-50 dark:bg-emerald-950/40 border-emerald-300/50 text-emerald-700 dark:text-emerald-300 hover:border-emerald-400',
|
||||
piano: 'bg-rose-50 dark:bg-rose-950/40 border-rose-300/50 text-rose-700 dark:text-rose-300 hover:border-rose-400',
|
||||
const STEM_COLORS: Record<string, { bg: string; border: string; color: string }> = {
|
||||
vocals: { bg: 'rgba(14, 165, 233, 0.09)', border: 'rgba(14, 165, 233, 0.35)', color: '#0ea5e9' },
|
||||
drums: { bg: 'rgba(249, 115, 22, 0.09)', border: 'rgba(249, 115, 22, 0.35)', color: '#f97316' },
|
||||
bass: { bg: 'rgba(168, 85, 247, 0.09)', border: 'rgba(168, 85, 247, 0.35)', color: '#a855f7' },
|
||||
other: { bg: 'var(--background)', border: 'var(--border-color)', color: 'inherit' },
|
||||
guitar: { bg: 'rgba(16, 185, 129, 0.09)', border: 'rgba(16, 185, 129, 0.35)', color: '#10b981' },
|
||||
piano: { bg: 'rgba(244, 63, 94, 0.09)', border: 'rgba(244, 63, 94, 0.35)', color: '#f43f5e' },
|
||||
}
|
||||
|
||||
function isActive(job: Job | null | undefined) {
|
||||
@@ -49,22 +49,27 @@ function isActive(job: Job | null | undefined) {
|
||||
|
||||
function JobBadge({ job }: { job: Job | null }) {
|
||||
if (!job) return null
|
||||
const styles: Record<string, string> = {
|
||||
done: 'bg-emerald-50 dark:bg-emerald-950/30 text-emerald-600 dark:text-emerald-400 border-emerald-300/50',
|
||||
running: 'bg-brand-50 dark:bg-brand-950/30 text-brand-600 dark:text-brand-400 border-brand-300/50',
|
||||
queued: 'bg-amber-50 dark:bg-amber-950/30 text-amber-600 dark:text-amber-400 border-amber-300/50',
|
||||
error: 'bg-red-50 dark:bg-red-950/30 text-red-600 dark:text-red-400 border-red-300/50',
|
||||
cancelled: 'bg-slate-50 dark:bg-gray-900 text-slate-500 dark:text-gray-500 border-slate-200 dark:border-gray-700',
|
||||
const colors: Record<string, { bg: string; color: string; border: string }> = {
|
||||
done: { bg: 'rgba(16, 185, 129, 0.1)', color: 'var(--color-green, #10b981)', border: 'rgba(16, 185, 129, 0.35)' },
|
||||
running: { bg: 'rgba(59, 130, 246, 0.1)', color: 'rgb(var(--brand-500,59 130 246))', border: 'rgba(59,130,246,0.35)' },
|
||||
queued: { bg: 'rgba(245, 158, 11, 0.1)', color: 'var(--color-amber, #f59e0b)', border: 'rgba(245, 158, 11, 0.35)' },
|
||||
error: { bg: 'rgba(239, 68, 68, 0.1)', color: 'var(--color-red, #ef4444)', border: 'rgba(239, 68, 68, 0.35)' },
|
||||
cancelled: { bg: 'var(--background)', color: 'var(--label-color)', border: 'var(--border-color)' },
|
||||
}
|
||||
const icons: Record<string, React.ReactNode> = {
|
||||
done: <CheckCircle className="w-3 h-3" />,
|
||||
running: <Loader2 className="w-3 h-3 animate-spin" />,
|
||||
queued: <Clock className="w-3 h-3" />,
|
||||
error: <XCircle className="w-3 h-3" />,
|
||||
cancelled: <AlertCircle className="w-3 h-3" />,
|
||||
done: <CheckCircle size={11} />,
|
||||
running: <Loader2 size={11} style={{ animation: 'spin 1s linear infinite' }} />,
|
||||
queued: <Clock size={11} />,
|
||||
error: <XCircle size={11} />,
|
||||
cancelled: <AlertCircle size={11} />,
|
||||
}
|
||||
const c = colors[job.status] ?? colors.cancelled
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full border font-medium ${styles[job.status] ?? ''}`}>
|
||||
<span style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 4,
|
||||
fontSize: 11, padding: '2px 8px', borderRadius: 12,
|
||||
border: `1px solid ${c.border}`, background: c.bg, color: c.color, fontWeight: 500,
|
||||
}}>
|
||||
{icons[job.status]}
|
||||
{job.status}
|
||||
</span>
|
||||
@@ -76,9 +81,10 @@ function DownloadButton({ file, jobId }: { file: JobFile; jobId: string }) {
|
||||
<a
|
||||
href={downloadUrl(jobId, file.name)}
|
||||
download={file.name}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg bg-slate-100 dark:bg-gray-800 border border-slate-200 dark:border-gray-700 px-2.5 py-1.5 text-xs font-medium text-slate-700 dark:text-gray-300 hover:border-brand-400 hover:text-brand-600 dark:hover:text-brand-400 transition-colors"
|
||||
className="button flat"
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12 }}
|
||||
>
|
||||
<Download className="w-3 h-3" />
|
||||
<Download size={12} />
|
||||
{file.name}
|
||||
</a>
|
||||
)
|
||||
@@ -670,17 +676,23 @@ function MidiGroupPlayer({ stems }: { stems: MidiGroupStem[] }) {
|
||||
|
||||
// Color-coded stem download chip — shows just the part name, not the full filename
|
||||
function StemChipButton({ file, jobId }: { file: JobFile; jobId: string }) {
|
||||
const stemKey = (file.stem ?? file.name).toLowerCase().split('.')[0]
|
||||
const label = stemKey.charAt(0).toUpperCase() + stemKey.slice(1)
|
||||
const colorCls = STEM_COLORS[stemKey] ?? STEM_COLORS.other
|
||||
const stemKey = (file.stem ?? file.name).toLowerCase().split('.')[0]
|
||||
const label = stemKey.charAt(0).toUpperCase() + stemKey.slice(1)
|
||||
const c = STEM_COLORS[stemKey] ?? STEM_COLORS.other
|
||||
return (
|
||||
<a
|
||||
href={downloadUrl(jobId, file.name)}
|
||||
download={file.name}
|
||||
title={file.name}
|
||||
className={`inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-semibold transition-colors ${colorCls}`}
|
||||
style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
borderRadius: 5, border: `1px solid ${c.border}`,
|
||||
background: c.bg, color: c.color,
|
||||
padding: '5px 12px', fontSize: 12, fontWeight: 600,
|
||||
textDecoration: 'none',
|
||||
}}
|
||||
>
|
||||
<Download className="w-3 h-3" />
|
||||
<Download size={12} />
|
||||
{label}
|
||||
</a>
|
||||
)
|
||||
@@ -719,61 +731,65 @@ function StemReprocessButton({
|
||||
}
|
||||
}
|
||||
|
||||
const accentColor = `rgb(var(--brand-500, 59 130 246))`
|
||||
return (
|
||||
<div className="relative">
|
||||
<div style={{ position: 'relative' }}>
|
||||
<button
|
||||
onClick={() => setShowMenu(v => !v)}
|
||||
disabled={busy}
|
||||
className="flex items-center gap-1 rounded-lg bg-slate-100 dark:bg-gray-800 border border-slate-200 dark:border-gray-700 px-2 py-1 text-[10px] font-medium text-slate-600 dark:text-gray-400 hover:border-brand-400 hover:text-brand-600 transition-colors"
|
||||
className="button flat"
|
||||
title="Reprocess with different model"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, padding: '4px 8px' }}
|
||||
>
|
||||
{busy ? <Loader2 className="w-3 h-3 animate-spin" /> : <Wand2 className="w-3 h-3" />}
|
||||
{busy ? <Loader2 size={11} style={{ animation: 'spin 1s linear infinite' }} /> : <Wand2 size={11} />}
|
||||
Reprocess
|
||||
</button>
|
||||
|
||||
{showMenu && (
|
||||
<div className="absolute right-0 top-full mt-1 z-20 w-64 rounded-lg border border-slate-200 dark:border-gray-700 bg-white dark:bg-gray-900 shadow-lg">
|
||||
<div className="p-2 space-y-2">
|
||||
{/* Family tabs */}
|
||||
<p className="text-[10px] font-medium text-slate-500 dark:text-gray-500 uppercase tracking-wider">
|
||||
<div style={{
|
||||
position: 'absolute', right: 0, top: '100%', marginTop: 4, zIndex: 20,
|
||||
width: 240, borderRadius: 6, border: '1px solid var(--border-color)',
|
||||
background: 'var(--body-background)', boxShadow: '0 4px 16px rgba(0,0,0,0.2)',
|
||||
}}>
|
||||
<div style={{ padding: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
<p style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', opacity: 0.5, margin: 0 }}>
|
||||
Model Family
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
|
||||
{groups.map(g => (
|
||||
<button
|
||||
key={g}
|
||||
onClick={() => setSelectedGroup(g)}
|
||||
className={`px-2 py-0.5 rounded text-[10px] font-medium transition-colors ${
|
||||
activeGroup === g
|
||||
? 'bg-brand-500 text-white'
|
||||
: 'bg-slate-100 dark:bg-gray-800 text-slate-600 dark:text-gray-400 hover:bg-slate-200 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
style={{
|
||||
padding: '2px 8px', borderRadius: 4, fontSize: 10, fontWeight: 600, border: 'none', cursor: 'pointer',
|
||||
background: activeGroup === g ? accentColor : 'var(--background)',
|
||||
color: activeGroup === g ? '#fff' : 'inherit',
|
||||
}}
|
||||
>
|
||||
{g}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Model list for selected family */}
|
||||
<p className="text-[10px] font-medium text-slate-500 dark:text-gray-500 uppercase tracking-wider">
|
||||
<p style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', opacity: 0.5, margin: 0 }}>
|
||||
Model
|
||||
</p>
|
||||
<div className="space-y-0.5 max-h-40 overflow-y-auto">
|
||||
<div style={{ maxHeight: 160, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
{filteredModels.map((model) => (
|
||||
<button
|
||||
key={model.id}
|
||||
onClick={() => handleReprocess(model.id)}
|
||||
className="w-full text-left px-2 py-1.5 rounded text-xs text-slate-700 dark:text-gray-300 hover:bg-slate-100 dark:hover:bg-gray-800 transition-colors font-medium"
|
||||
className="button flat"
|
||||
style={{ textAlign: 'left', fontSize: 12, padding: '5px 8px' }}
|
||||
>
|
||||
{model.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => setShowMenu(false)}
|
||||
className="w-full py-1.5 text-[10px] text-slate-500 hover:text-slate-700 dark:text-gray-500 dark:hover:text-gray-300 border-t border-slate-200 dark:border-gray-700"
|
||||
className="button flat"
|
||||
style={{ width: '100%', fontSize: 11, padding: '6px 0', borderTop: '1px solid var(--border-color)', borderRadius: 0 }}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
@@ -819,7 +835,7 @@ function StemRenameButton({
|
||||
|
||||
if (isEditing) {
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
<input
|
||||
type="text"
|
||||
value={newName}
|
||||
@@ -828,21 +844,28 @@ function StemRenameButton({
|
||||
if (e.key === 'Enter') handleSubmit()
|
||||
if (e.key === 'Escape') setIsEditing(false)
|
||||
}}
|
||||
className="w-24 rounded border border-slate-300 dark:border-gray-600 px-1.5 py-0.5 text-xs bg-white dark:bg-gray-900 text-slate-900 dark:text-gray-100"
|
||||
style={{
|
||||
width: 96, padding: '3px 7px', fontSize: 12, borderRadius: 4,
|
||||
border: '1px solid var(--border-color)',
|
||||
background: 'var(--input-background, var(--background))',
|
||||
color: 'inherit', outline: 'none',
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={busy}
|
||||
className="p-0.5 rounded text-emerald-500 hover:text-emerald-600"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 3, color: 'var(--color-green, #10b981)' }}
|
||||
>
|
||||
{busy ? <Loader2 className="w-3 h-3 animate-spin" /> : <Check className="w-3 h-3" />}
|
||||
{busy ? <Loader2 size={11} style={{ animation: 'spin 1s linear infinite' }} /> : <Check size={11} />}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setIsEditing(false)}
|
||||
className="p-0.5 rounded text-slate-400 hover:text-slate-600"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 3 }}
|
||||
>
|
||||
<XIcon className="w-3 h-3" />
|
||||
<XIcon size={11} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
@@ -851,10 +874,11 @@ function StemRenameButton({
|
||||
return (
|
||||
<button
|
||||
onClick={() => setIsEditing(true)}
|
||||
className="p-1 rounded text-slate-400 hover:text-brand-500 transition-colors"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 4 }}
|
||||
title="Rename stem"
|
||||
>
|
||||
<Edit2 className="w-3 h-3" />
|
||||
<Edit2 size={12} />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -873,40 +897,48 @@ function StemsSection({
|
||||
const stems = sepJob.files.filter((f) => f.type === 'stem')
|
||||
const [open, setOpen] = useState(true)
|
||||
|
||||
const accentColor = `rgb(var(--brand-500, 59 130 246))`
|
||||
return (
|
||||
<section>
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="w-full flex items-center justify-between mb-3 text-left group"
|
||||
>
|
||||
<h3 className="text-sm font-semibold text-slate-700 dark:text-gray-200 flex items-center gap-2 group-hover:text-brand-500 transition-colors">
|
||||
<Music2 className="w-4 h-4 text-brand-500" /> Stems
|
||||
</h3>
|
||||
{open ? <ChevronUp className="w-3.5 h-3.5 text-slate-400" /> : <ChevronDown className="w-3.5 h-3.5 text-slate-400" />}
|
||||
</button>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'none', border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 600, color: accentColor }}
|
||||
>
|
||||
<Music2 size={15} style={{ color: accentColor }} /> Stems
|
||||
</button>
|
||||
<button onClick={() => setOpen((v) => !v)} className="button cycle flat" style={{ padding: 3 }}>
|
||||
{open ? <ChevronUp size={13} /> : <ChevronDown size={13} />}
|
||||
</button>
|
||||
</div>
|
||||
{open && (stems.length === 0 ? (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 italic">No stem files found.</p>
|
||||
<p style={{ fontSize: 12, opacity: 0.45, fontStyle: 'italic' }}>No stem files found.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
{stems.map((f) => (
|
||||
<div
|
||||
key={f.name}
|
||||
className="flex items-center gap-2 p-2 rounded-lg border border-slate-200 dark:border-gray-700 bg-slate-50/50 dark:bg-gray-800/30"
|
||||
>
|
||||
<StemChipButton file={f} jobId={sepJob.id} />
|
||||
<div className="flex-1" />
|
||||
<StemRenameButton
|
||||
projectId={project.id}
|
||||
stemName={f.stem ?? f.name}
|
||||
currentLabel={f.stem ?? f.name}
|
||||
onRename={onAction}
|
||||
/>
|
||||
<StemReprocessButton
|
||||
projectId={project.id}
|
||||
stemName={f.stem ?? f.name}
|
||||
onReprocess={onAction}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
key={f.name}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 8,
|
||||
padding: '6px 8px', borderRadius: 6,
|
||||
border: '1px solid var(--border-color)',
|
||||
background: 'var(--background)',
|
||||
}}
|
||||
>
|
||||
<StemChipButton file={f} jobId={sepJob.id} />
|
||||
<div style={{ flex: 1 }} />
|
||||
<StemRenameButton
|
||||
projectId={project.id}
|
||||
stemName={f.stem ?? f.name}
|
||||
currentLabel={f.stem ?? f.name}
|
||||
onRename={onAction}
|
||||
/>
|
||||
<StemReprocessButton
|
||||
projectId={project.id}
|
||||
stemName={f.stem ?? f.name}
|
||||
onReprocess={onAction}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
@@ -965,30 +997,34 @@ function MixesSection({
|
||||
const currentMixType = mixFiles[0]?.type // 'static' | 'dynamic'
|
||||
const [open, setOpen] = useState(true)
|
||||
|
||||
const accentColor = `rgb(var(--brand-500, 59 130 246))`
|
||||
return (
|
||||
<section>
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="w-full flex items-center justify-between mb-3 text-left group"
|
||||
>
|
||||
<h3 className="text-sm font-semibold text-slate-700 dark:text-gray-200 flex items-center gap-2 group-hover:text-brand-500 transition-colors">
|
||||
<Music2 className="w-4 h-4 text-brand-500" /> Mixes
|
||||
</h3>
|
||||
{open ? <ChevronUp className="w-3.5 h-3.5 text-slate-400" /> : <ChevronDown className="w-3.5 h-3.5 text-slate-400" />}
|
||||
</button>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'none', border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 600, color: accentColor }}
|
||||
>
|
||||
<Music2 size={15} style={{ color: accentColor }} /> Mixes
|
||||
</button>
|
||||
<button onClick={() => setOpen((v) => !v)} className="button cycle flat" style={{ padding: 3 }}>
|
||||
{open ? <ChevronUp size={13} /> : <ChevronDown size={13} />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{open && (<>
|
||||
{/* Sub-tabs */}
|
||||
<div className="flex gap-1 mb-4">
|
||||
<div style={{ display: 'flex', gap: 4, marginBottom: 14 }}>
|
||||
{(['static', 'dynamic'] as const).map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
onClick={() => setMixTab(t)}
|
||||
className={`px-3 py-1 rounded-lg text-xs font-medium capitalize transition-colors ${
|
||||
mixTab === t
|
||||
? 'bg-brand-500 text-white'
|
||||
: 'bg-slate-100 dark:bg-gray-800 text-slate-600 dark:text-gray-400 hover:bg-slate-200 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
style={{
|
||||
padding: '4px 12px', borderRadius: 4, fontSize: 12, fontWeight: 600,
|
||||
border: 'none', cursor: 'pointer', textTransform: 'capitalize',
|
||||
background: mixTab === t ? accentColor : 'var(--background)',
|
||||
color: mixTab === t ? '#fff' : 'inherit',
|
||||
}}
|
||||
>
|
||||
{t}
|
||||
</button>
|
||||
@@ -996,30 +1032,31 @@ function MixesSection({
|
||||
</div>
|
||||
|
||||
{mixTab === 'static' ? (
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="text-xs font-medium text-slate-600 dark:text-gray-400 block mb-1">Remove</label>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
<label>
|
||||
<span style={{ display: 'block', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', opacity: 0.5, marginBottom: 5 }}>Remove</span>
|
||||
<select
|
||||
value={staticOption}
|
||||
onChange={(e) => setStaticOption(e.target.value)}
|
||||
className="rounded-lg bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-3 py-1.5 text-xs text-slate-900 dark:text-gray-100 focus:outline-none focus:border-brand-400"
|
||||
style={{ padding: '6px 10px', fontSize: 12, borderRadius: 4, border: '1px solid var(--border-color)', background: 'var(--input-background, var(--background))', color: 'inherit', outline: 'none' }}
|
||||
>
|
||||
{STATIC_OPTIONS.map((o) => (
|
||||
<option key={o.id} value={o.id}>{o.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</label>
|
||||
<button
|
||||
onClick={handleGenerate}
|
||||
disabled={busy || !!isActive(mixJob)}
|
||||
className="flex items-center gap-1.5 rounded-lg bg-brand-500/10 border border-brand-400/30 px-3 py-1.5 text-xs font-medium text-brand-600 dark:text-brand-400 hover:bg-brand-500/20 transition-colors disabled:opacity-50"
|
||||
className="button"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, padding: '6px 14px', width: 'fit-content', opacity: (busy || !!isActive(mixJob)) ? 0.5 : 1 }}
|
||||
>
|
||||
{busy ? <Loader2 className="w-3 h-3 animate-spin" /> : null}
|
||||
{busy ? <Loader2 size={12} style={{ animation: 'spin 1s linear infinite' }} /> : null}
|
||||
Generate
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
<DynamicMixPlayer
|
||||
stems={stemEntries}
|
||||
title={project.name}
|
||||
@@ -1028,37 +1065,38 @@ function MixesSection({
|
||||
<button
|
||||
onClick={handleGenerate}
|
||||
disabled={busy || !!isActive(mixJob)}
|
||||
className="flex items-center gap-1.5 rounded-lg bg-brand-500/10 border border-brand-400/30 px-3 py-1.5 text-xs font-medium text-brand-600 dark:text-brand-400 hover:bg-brand-500/20 transition-colors disabled:opacity-50"
|
||||
className="button"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, padding: '6px 14px', width: 'fit-content', opacity: (busy || !!isActive(mixJob)) ? 0.5 : 1 }}
|
||||
>
|
||||
{busy ? <Loader2 className="w-3 h-3 animate-spin" /> : null}
|
||||
{busy ? <Loader2 size={12} style={{ animation: 'spin 1s linear infinite' }} /> : null}
|
||||
Export Mix
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{err && <p className="mt-2 text-xs text-red-500 dark:text-red-400">{err}</p>}
|
||||
{err && <p style={{ fontSize: 12, color: 'var(--color-red, #ef4444)', marginTop: 6 }}>{err}</p>}
|
||||
|
||||
{/* Current mix job */}
|
||||
{mixJob && (
|
||||
<div className="mt-3 rounded-xl bg-slate-50 dark:bg-gray-900 border border-slate-200 dark:border-gray-800 p-3 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400">
|
||||
<div style={{ marginTop: 12, borderRadius: 6, border: '1px solid var(--border-color)', background: 'var(--background)', padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<span style={{ fontSize: 12, opacity: 0.55 }}>
|
||||
{currentMixType === 'dynamic' ? 'Dynamic' : 'Static'} mix
|
||||
</span>
|
||||
<JobBadge job={mixJob} />
|
||||
</div>
|
||||
{isActive(mixJob) && (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-500 truncate">{mixJob.progress}</p>
|
||||
<p style={{ fontSize: 12, opacity: 0.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{mixJob.progress}</p>
|
||||
)}
|
||||
{mixJob.status === 'done' && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
|
||||
{mixJob.files.map((f) => (
|
||||
<DownloadButton key={f.name} file={f} jobId={mixJob.id} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{mixJob.status === 'error' && (
|
||||
<p className="text-xs text-red-400 break-all">{mixJob.error}</p>
|
||||
<p style={{ fontSize: 11, color: 'var(--color-red, #ef4444)', wordBreak: 'break-all' }}>{mixJob.error}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -1171,35 +1209,37 @@ function MidiSection({
|
||||
|
||||
const [open, setOpen] = useState(true)
|
||||
|
||||
const violetColor = 'var(--color-violet, #a855f7)'
|
||||
return (
|
||||
<section>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="flex items-center gap-2 text-sm font-semibold text-slate-700 dark:text-gray-200 hover:text-brand-500 transition-colors"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'none', border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 600, color: violetColor }}
|
||||
>
|
||||
<Mic2 className="w-4 h-4 text-purple-500" /> MIDI
|
||||
<Mic2 size={15} style={{ color: violetColor }} /> MIDI
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
{open && stems.length > 1 && (
|
||||
<button
|
||||
onClick={handleTranscribeAll}
|
||||
disabled={bulkBusy || anyActive}
|
||||
className="flex items-center gap-1.5 rounded-lg bg-purple-500/10 border border-purple-400/30 px-3 py-1 text-xs font-medium text-purple-600 dark:text-purple-400 hover:bg-purple-500/20 transition-colors disabled:opacity-50"
|
||||
className="button flat"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, padding: '4px 10px', color: violetColor, opacity: (bulkBusy || anyActive) ? 0.5 : 1 }}
|
||||
>
|
||||
{bulkBusy ? <Loader2 className="w-3 h-3 animate-spin" /> : <ListMusic className="w-3 h-3" />}
|
||||
{bulkBusy ? <Loader2 size={11} style={{ animation: 'spin 1s linear infinite' }} /> : <ListMusic size={11} />}
|
||||
Transcribe All
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => setOpen((v) => !v)} className="text-slate-400 hover:text-slate-600 dark:hover:text-gray-300 transition-colors">
|
||||
{open ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
|
||||
<button onClick={() => setOpen((v) => !v)} className="button cycle flat" style={{ padding: 3 }}>
|
||||
{open ? <ChevronUp size={13} /> : <ChevronDown size={13} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{open && (<>
|
||||
{bulkErr && <p className="mb-2 text-xs text-red-500 dark:text-red-400">{bulkErr}</p>}
|
||||
{bulkErr && <p style={{ fontSize: 12, color: 'var(--color-red, #ef4444)', marginBottom: 6 }}>{bulkErr}</p>}
|
||||
{stems.length === 0 ? (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 italic">No stems available.</p>
|
||||
<p style={{ fontSize: 12, opacity: 0.45, fontStyle: 'italic' }}>No stems available.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{stems.map((stem) => {
|
||||
@@ -1364,35 +1404,37 @@ function AbcSection({
|
||||
|
||||
const [open, setOpen] = useState(true)
|
||||
|
||||
const greenColor = 'var(--color-green, #10b981)'
|
||||
return (
|
||||
<section>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="flex items-center gap-2 text-sm font-semibold text-slate-700 dark:text-gray-200 hover:text-brand-500 transition-colors"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'none', border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 600, color: greenColor }}
|
||||
>
|
||||
<FileCode className="w-4 h-4 text-emerald-500" /> ABC Notation
|
||||
<FileCode size={15} style={{ color: greenColor }} /> ABC Notation
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
{open && convertableStems.length > 1 && (
|
||||
<button
|
||||
onClick={handleConvertAll}
|
||||
disabled={bulkBusy || anyActive}
|
||||
className="flex items-center gap-1.5 rounded-lg bg-emerald-500/10 border border-emerald-400/30 px-3 py-1 text-xs font-medium text-emerald-600 dark:text-emerald-400 hover:bg-emerald-500/20 transition-colors disabled:opacity-50"
|
||||
className="button flat"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, padding: '4px 10px', color: greenColor, opacity: (bulkBusy || anyActive) ? 0.5 : 1 }}
|
||||
>
|
||||
{bulkBusy ? <Loader2 className="w-3 h-3 animate-spin" /> : <ListMusic className="w-3 h-3" />}
|
||||
{bulkBusy ? <Loader2 size={11} style={{ animation: 'spin 1s linear infinite' }} /> : <ListMusic size={11} />}
|
||||
Convert All
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => setOpen((v) => !v)} className="text-slate-400 hover:text-slate-600 dark:hover:text-gray-300 transition-colors">
|
||||
{open ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
|
||||
<button onClick={() => setOpen((v) => !v)} className="button cycle flat" style={{ padding: 3 }}>
|
||||
{open ? <ChevronUp size={13} /> : <ChevronDown size={13} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{open && (<>
|
||||
{bulkErr && <p className="mb-2 text-xs text-red-500 dark:text-red-400">{bulkErr}</p>}
|
||||
{bulkErr && <p style={{ fontSize: 12, color: 'var(--color-red, #ef4444)', marginBottom: 6 }}>{bulkErr}</p>}
|
||||
{stems.length === 0 ? (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 italic">No stems available.</p>
|
||||
<p style={{ fontSize: 12, opacity: 0.45, fontStyle: 'italic' }}>No stems available.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{stems.map((stem) => {
|
||||
@@ -2150,19 +2192,22 @@ function LyricsSection({
|
||||
|
||||
const [open, setOpen] = useState(true)
|
||||
|
||||
const skyColor = 'var(--color-blue, #0ea5e9)'
|
||||
return (
|
||||
<section>
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="w-full flex items-center justify-between mb-3 text-left group"
|
||||
>
|
||||
<h3 className="text-sm font-semibold text-slate-700 dark:text-gray-200 flex items-center gap-2 group-hover:text-brand-500 transition-colors">
|
||||
<FileText className="w-4 h-4 text-sky-500" /> Lyrics Sync
|
||||
</h3>
|
||||
{open ? <ChevronUp className="w-3.5 h-3.5 text-slate-400" /> : <ChevronDown className="w-3.5 h-3.5 text-slate-400" />}
|
||||
</button>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'none', border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 600, color: skyColor }}
|
||||
>
|
||||
<FileText size={15} style={{ color: skyColor }} /> Lyrics Sync
|
||||
</button>
|
||||
<button onClick={() => setOpen((v) => !v)} className="button cycle flat" style={{ padding: 3 }}>
|
||||
{open ? <ChevronUp size={13} /> : <ChevronDown size={13} />}
|
||||
</button>
|
||||
</div>
|
||||
{open && (vocalStems.length === 0 ? (
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 italic">No vocals stem available.</p>
|
||||
<p style={{ fontSize: 12, opacity: 0.45, fontStyle: 'italic' }}>No vocals stem available.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{vocalStems.map((stem) => {
|
||||
@@ -2227,27 +2272,27 @@ export default function ProjectDetail({ id, onDelete }: Props) {
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-brand-400" />
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '48px 0' }}>
|
||||
<Loader2 size={24} style={{ animation: 'spin 1s linear infinite', color: `rgb(var(--brand-500, 59 130 246))` }} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error || !project) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-red-500">Failed to load project.</p>
|
||||
</div>
|
||||
<p style={{ fontSize: 13, color: 'var(--color-red, #ef4444)' }}>Failed to load project.</p>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
|
||||
{/* Header */}
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h2 className="text-base font-bold text-slate-900 dark:text-white leading-tight truncate">{project.name}</h2>
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 mt-0.5">
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 20 }}>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<h2 style={{ fontSize: 15, fontWeight: 700, margin: '0 0 2px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{project.name}
|
||||
</h2>
|
||||
<p style={{ fontSize: 11, opacity: 0.45, margin: 0 }}>
|
||||
{project.created_at ? new Date(project.created_at).toLocaleDateString() : ''}
|
||||
</p>
|
||||
</div>
|
||||
@@ -2255,19 +2300,23 @@ export default function ProjectDetail({ id, onDelete }: Props) {
|
||||
<button
|
||||
onClick={onDelete}
|
||||
title="Delete project"
|
||||
className="shrink-0 p-1.5 rounded-lg text-slate-300 dark:text-gray-600 hover:text-red-500 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/30 transition-colors"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 6, flexShrink: 0, color: 'var(--color-red, #ef4444)' }}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
<Trash2 size={15} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="divide-y divide-slate-100 dark:divide-gray-800 space-y-6">
|
||||
{/* Sections */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
|
||||
{/* 1 — Stems */}
|
||||
<StemsSection project={project} sepJob={project.sep_job} onAction={invalidate} />
|
||||
<div style={{ padding: '16px 0', borderTop: '1px solid var(--border-color)' }}>
|
||||
<StemsSection project={project} sepJob={project.sep_job} onAction={invalidate} />
|
||||
</div>
|
||||
|
||||
{/* 2 — Mixes */}
|
||||
<div className="pt-6">
|
||||
<div style={{ padding: '16px 0', borderTop: '1px solid var(--border-color)' }}>
|
||||
<MixesSection
|
||||
project={project}
|
||||
sepJob={project.sep_job}
|
||||
@@ -2277,7 +2326,7 @@ export default function ProjectDetail({ id, onDelete }: Props) {
|
||||
</div>
|
||||
|
||||
{/* 3 — MIDI */}
|
||||
<div className="pt-6">
|
||||
<div style={{ padding: '16px 0', borderTop: '1px solid var(--border-color)' }}>
|
||||
<MidiSection
|
||||
project={project}
|
||||
sepJob={project.sep_job}
|
||||
@@ -2287,7 +2336,7 @@ export default function ProjectDetail({ id, onDelete }: Props) {
|
||||
</div>
|
||||
|
||||
{/* 4 — ABC */}
|
||||
<div className="pt-6">
|
||||
<div style={{ padding: '16px 0', borderTop: '1px solid var(--border-color)' }}>
|
||||
<AbcSection
|
||||
project={project}
|
||||
sepJob={project.sep_job}
|
||||
@@ -2298,7 +2347,7 @@ export default function ProjectDetail({ id, onDelete }: Props) {
|
||||
</div>
|
||||
|
||||
{/* 5 — Lyrics Sync */}
|
||||
<div className="pt-6">
|
||||
<div style={{ padding: '16px 0', borderTop: '1px solid var(--border-color)' }}>
|
||||
<LyricsSection
|
||||
project={project}
|
||||
sepJob={project.sep_job}
|
||||
|
||||
+229
-120
@@ -1,4 +1,11 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
/**
|
||||
* Separator.tsx — Phase 3 MetroUI migration
|
||||
*
|
||||
* All business logic (state, queries, handlers, effects) unchanged.
|
||||
* Tailwind classes replaced with MetroUI CSS + inline styles.
|
||||
* Sub-components JobStatus, ResultFiles are not yet migrated (Phase 4+).
|
||||
*/
|
||||
import { useState, useEffect, useRef, type CSSProperties } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { RefreshCw, Radio, Zap } from 'lucide-react'
|
||||
import FileUpload from '../components/FileUpload'
|
||||
@@ -11,9 +18,27 @@ import {
|
||||
} from '../api/client'
|
||||
import type { Job, ModelOption, PresetsResponse, DynamicLevels, ImportedFile } from '../types'
|
||||
|
||||
const SELECT_CLS = 'w-full rounded-lg bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-3 py-2 text-sm text-slate-900 dark:text-gray-100 focus:border-brand-500 focus:outline-none'
|
||||
const INPUT_CLS = 'w-full rounded-lg bg-white dark:bg-gray-900 border border-slate-300 dark:border-gray-700 px-3 py-2 text-sm text-slate-900 dark:text-gray-100 focus:border-brand-500 focus:outline-none'
|
||||
const SLIDER_CLS = 'w-full h-2 bg-slate-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-brand-600'
|
||||
// ── Shared style helpers ────────────────────────────────────────────────────
|
||||
|
||||
const fieldLabel: CSSProperties = {
|
||||
display: 'block', fontSize: 11, fontWeight: 700,
|
||||
letterSpacing: '0.08em', textTransform: 'uppercase',
|
||||
opacity: 0.5, marginBottom: 5,
|
||||
}
|
||||
|
||||
const ctrl: CSSProperties = {
|
||||
width: '100%', padding: '6px 10px', fontSize: 13, borderRadius: 4,
|
||||
border: '1px solid var(--border-color)',
|
||||
background: 'var(--input-background, var(--background))',
|
||||
color: 'inherit', outline: 'none', boxSizing: 'border-box',
|
||||
}
|
||||
|
||||
const card: CSSProperties = {
|
||||
borderRadius: 6, border: '1px solid var(--border-color)',
|
||||
background: 'var(--background)', padding: '12px 14px',
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function groupModels(models: ModelOption[]) {
|
||||
const groups: Record<string, ModelOption[]> = {}
|
||||
@@ -66,7 +91,6 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
|
||||
const grouped = groupModels(models)
|
||||
|
||||
// Read layout preferences saved in Settings → Model Settings
|
||||
const hiddenGroups = new Set<string>((() => {
|
||||
try { return JSON.parse(localStorage.getItem('se-model-hidden-groups') || '[]') as string[] }
|
||||
catch { return [] }
|
||||
@@ -84,7 +108,6 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
catch { return {} }
|
||||
})()
|
||||
|
||||
// Build visible + ordered groups (mirrors Settings ModelDownloader logic)
|
||||
const allGroupNames = Object.keys(grouped)
|
||||
const orderedGroupNames = [
|
||||
...groupOrder.filter(g => allGroupNames.includes(g)),
|
||||
@@ -115,7 +138,6 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
if (first) setModel(first.id)
|
||||
}
|
||||
|
||||
// Reset selected model when it becomes hidden/invisible
|
||||
useEffect(() => {
|
||||
if (!models.length) return
|
||||
const foundGroup = models.find(m => m.id === model)?.group
|
||||
@@ -128,7 +150,6 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [models])
|
||||
|
||||
// Fire callback when a separation job completes
|
||||
const firedRef = useRef<string | null>(null)
|
||||
useEffect(() => {
|
||||
if (
|
||||
@@ -147,17 +168,13 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
}
|
||||
}, [result, onSeparationComplete])
|
||||
|
||||
// Extract metadata when file changes
|
||||
useEffect(() => {
|
||||
if (!file) {
|
||||
setMetadata({})
|
||||
setProjectName('')
|
||||
return
|
||||
}
|
||||
|
||||
// Try to extract metadata from the file
|
||||
extractLyrics(file).then(() => {
|
||||
// Use filename as fallback
|
||||
const filename = file.name.replace(/\.[^/.]+$/, '')
|
||||
setMetadata({ artist: '', title: filename })
|
||||
}).catch(() => {
|
||||
@@ -166,7 +183,6 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
})
|
||||
}, [file])
|
||||
|
||||
// Auto-generate project name from metadata
|
||||
useEffect(() => {
|
||||
if (metadata.artist && metadata.title) {
|
||||
setProjectName(`${metadata.artist} - ${metadata.title}`)
|
||||
@@ -190,7 +206,6 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
dynamicLevels: presetType === 'dynamic' ? dynamicLevels : undefined,
|
||||
sepPowerPreset,
|
||||
}
|
||||
|
||||
let job_id: string
|
||||
if (inputMode === 'imported' && importedFile) {
|
||||
const res = await submitSeparateFromPath(importedFile.path, model, format, opts)
|
||||
@@ -211,41 +226,51 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
setDynamicLevels(prev => ({ ...prev, [stem]: value }))
|
||||
}
|
||||
|
||||
const accentColor = `rgb(var(--brand-500, 59 130 246))`
|
||||
const hasInput = inputMode === 'upload' ? !!file : !!importedFile
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
|
||||
|
||||
{/* ── Page header ──────────────────────────────────────────────────────── */}
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-1">Stem Separator</h2>
|
||||
<p className="text-sm text-slate-500 dark:text-gray-400">
|
||||
<h2 style={{ fontSize: 20, fontWeight: 600, margin: '0 0 4px' }}>Stem Separator</h2>
|
||||
<p style={{ fontSize: 13, opacity: 0.55, margin: 0, lineHeight: 1.5 }}>
|
||||
Separate an audio track into individual stems using Demucs, BS-RoFormer, MelBand, or MDX-Net.
|
||||
Create presets like Instrumental, Static mixes, or Dynamic volume-adjusted mixes.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Input mode toggle */}
|
||||
<div className="flex rounded-lg border border-slate-200 dark:border-gray-700 overflow-hidden">
|
||||
{/* ── Input mode toggle ─────────────────────────────────────────────────── */}
|
||||
<div style={{ display: 'flex', borderRadius: 5, overflow: 'hidden', border: '1px solid var(--border-color)' }}>
|
||||
<button
|
||||
onClick={() => setInputMode('upload')}
|
||||
className={`flex-1 py-2 text-xs font-medium transition-colors ${
|
||||
inputMode === 'upload'
|
||||
? 'bg-brand-600 text-white'
|
||||
: 'bg-white dark:bg-gray-900 text-slate-600 dark:text-gray-400 hover:bg-slate-50 dark:hover:bg-gray-800'
|
||||
}`}
|
||||
style={{
|
||||
flex: 1, padding: '7px 12px', fontSize: 12, fontWeight: 600,
|
||||
border: 'none', cursor: 'pointer', transition: 'background 0.15s, color 0.15s',
|
||||
background: inputMode === 'upload' ? accentColor : 'transparent',
|
||||
color: inputMode === 'upload' ? '#fff' : 'inherit',
|
||||
}}
|
||||
>
|
||||
Upload File
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setInputMode('imported'); refetchImports() }}
|
||||
className={`flex-1 py-2 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${
|
||||
inputMode === 'imported'
|
||||
? 'bg-sky-600 text-white'
|
||||
: 'bg-white dark:bg-gray-900 text-slate-600 dark:text-gray-400 hover:bg-slate-50 dark:hover:bg-gray-800'
|
||||
}`}
|
||||
style={{
|
||||
flex: 1, padding: '7px 12px', fontSize: 12, fontWeight: 600,
|
||||
border: 'none', borderLeft: '1px solid var(--border-color)', cursor: 'pointer',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
|
||||
transition: 'background 0.15s, color 0.15s',
|
||||
background: inputMode === 'imported' ? 'var(--color-blue, #0ea5e9)' : 'transparent',
|
||||
color: inputMode === 'imported' ? '#fff' : 'inherit',
|
||||
}}
|
||||
>
|
||||
<Radio className="w-3 h-3" />
|
||||
<Radio size={12} />
|
||||
Imported Files
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* ── Upload mode ───────────────────────────────────────────────────────── */}
|
||||
{inputMode === 'upload' && (
|
||||
<>
|
||||
<FileUpload
|
||||
@@ -254,95 +279,106 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
onFiles={([f]) => { setFile(f); setJobId(null); setResult(null) }}
|
||||
/>
|
||||
{file && (
|
||||
<div className="rounded-lg border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800/50 px-4 py-3">
|
||||
<p className="text-sm font-medium text-slate-700 dark:text-gray-300">
|
||||
Selected: {file.name}
|
||||
</p>
|
||||
<div style={{ ...card, borderColor: `rgba(var(--brand-500, 59 130 246), 0.35)` }}>
|
||||
<span style={{ fontSize: 13, fontWeight: 500 }}>Selected: </span>
|
||||
<span style={{ fontSize: 13, opacity: 0.7 }}>{file.name}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* ── Imported mode ─────────────────────────────────────────────────────── */}
|
||||
{inputMode === 'imported' && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Select imported file</span>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', opacity: 0.5 }}>
|
||||
Select imported file
|
||||
</span>
|
||||
<button
|
||||
onClick={() => refetchImports()}
|
||||
title="Refresh"
|
||||
className="p-1 rounded text-slate-400 hover:text-brand-500 transition-colors"
|
||||
className="button cycle flat"
|
||||
style={{ padding: 4, marginLeft: 'auto' }}
|
||||
>
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
<RefreshCw size={13} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{imports.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-slate-200 dark:border-gray-700 px-4 py-6 text-center">
|
||||
<Radio className="w-6 h-6 text-slate-300 dark:text-gray-600 mx-auto mb-2" />
|
||||
<p className="text-sm text-slate-400 dark:text-gray-600">No imported files yet.</p>
|
||||
<p className="text-xs text-slate-400 dark:text-gray-600 mt-1">Use the Subsonic panel in the sidebar to import songs.</p>
|
||||
<div style={{
|
||||
borderRadius: 6, border: '2px dashed var(--border-color)',
|
||||
padding: '24px 16px', textAlign: 'center',
|
||||
}}>
|
||||
<Radio size={22} style={{ opacity: 0.25, margin: '0 auto 8px', display: 'block' }} />
|
||||
<p style={{ fontSize: 13, opacity: 0.45, margin: '0 0 4px' }}>No imported files yet.</p>
|
||||
<p style={{ fontSize: 11, opacity: 0.35, margin: 0 }}>
|
||||
Use the Subsonic panel in the sidebar to import songs.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1 max-h-48 overflow-y-auto rounded-lg border border-slate-200 dark:border-gray-700">
|
||||
<div style={{
|
||||
maxHeight: 192, overflowY: 'auto',
|
||||
borderRadius: 6, border: '1px solid var(--border-color)',
|
||||
}}>
|
||||
{imports.map((f) => (
|
||||
<button
|
||||
<ImportedFileButton
|
||||
key={f.path}
|
||||
onClick={() => {
|
||||
file={f}
|
||||
selected={importedFile?.path === f.path}
|
||||
onSelect={() => {
|
||||
setImportedFile(f)
|
||||
setProjectName(f.filename.replace(/\.[^/.]+$/, ''))
|
||||
setJobId(null); setResult(null)
|
||||
}}
|
||||
className={`w-full flex items-start gap-2 px-3 py-2 text-left transition-colors ${
|
||||
importedFile?.path === f.path
|
||||
? 'bg-sky-50 dark:bg-sky-950/30 border-l-2 border-sky-500'
|
||||
: 'hover:bg-slate-50 dark:hover:bg-gray-800/50'
|
||||
}`}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs font-medium text-slate-700 dark:text-gray-200 truncate">{f.filename}</p>
|
||||
<p className="text-[10px] text-slate-400 dark:text-gray-500">
|
||||
{(f.size / 1024 / 1024).toFixed(1)} MB
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Model Family</span>
|
||||
<select value={selectedGroup} onChange={(e) => handleGroupChange(e.target.value)} className={SELECT_CLS}>
|
||||
{/* ── Model + Format selectors ─────────────────────────────────────────── */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
|
||||
<label>
|
||||
<span style={fieldLabel}>Model Family</span>
|
||||
<select value={selectedGroup} onChange={(e) => handleGroupChange(e.target.value)} style={ctrl}>
|
||||
{Object.keys(visibleGrouped).map((g) => (
|
||||
<option key={g} value={g}>{g}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Model</span>
|
||||
<select value={model} onChange={(e) => setModel(e.target.value)} className={SELECT_CLS}>
|
||||
<label>
|
||||
<span style={fieldLabel}>Model</span>
|
||||
<select value={model} onChange={(e) => setModel(e.target.value)} style={ctrl}>
|
||||
{(visibleGrouped[selectedGroup] ?? []).map((m) => (
|
||||
<option key={m.id} value={m.id}>{m.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Output Format</span>
|
||||
<select value={format} onChange={(e) => setFormat(e.target.value)} className={SELECT_CLS}>
|
||||
<label>
|
||||
<span style={fieldLabel}>Output Format</span>
|
||||
<select value={format} onChange={(e) => setFormat(e.target.value)} style={ctrl}>
|
||||
{formats.map((f) => <option key={f.id} value={f.id}>{f.label}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* ── BS-RoFormer info ─────────────────────────────────────────────────── */}
|
||||
{isBSR && (
|
||||
<div className="rounded-lg border border-purple-300 dark:border-purple-800 bg-purple-50 dark:bg-purple-950/30 px-4 py-3 text-xs text-purple-700 dark:text-purple-300 space-y-1">
|
||||
<p className="font-semibold">BS-RoFormer selected</p>
|
||||
<p>State-of-the-art transformer model. Runs in-process — may take longer on CPU.</p>
|
||||
<ul className="list-disc list-inside mt-1 space-y-0.5 text-purple-600 dark:text-purple-400">
|
||||
<div style={{
|
||||
borderRadius: 6,
|
||||
border: '1px solid rgba(139, 92, 246, 0.45)',
|
||||
background: 'rgba(139, 92, 246, 0.07)',
|
||||
padding: '10px 14px', fontSize: 12,
|
||||
color: 'var(--color-violet, #8b5cf6)',
|
||||
}}>
|
||||
<p style={{ fontWeight: 700, margin: '0 0 4px' }}>BS-RoFormer selected</p>
|
||||
<p style={{ opacity: 0.8, margin: '0 0 6px' }}>
|
||||
State-of-the-art transformer model. Runs in-process — may take longer on CPU.
|
||||
</p>
|
||||
<ul style={{ margin: 0, paddingLeft: 18, opacity: 0.75, lineHeight: 1.7 }}>
|
||||
<li><strong>4-stem</strong> — vocals · drums · bass · other</li>
|
||||
<li><strong>5-stem (guitar)</strong> — + guitar as separate stem</li>
|
||||
<li><strong>5-stem (piano)</strong> — + piano as separate stem</li>
|
||||
@@ -351,66 +387,67 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project Name */}
|
||||
<div className="space-y-2">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Project Name</span>
|
||||
{/* ── Project name ─────────────────────────────────────────────────────── */}
|
||||
<div>
|
||||
<label>
|
||||
<span style={fieldLabel}>Project Name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={projectName}
|
||||
onChange={(e) => setProjectName(e.target.value)}
|
||||
placeholder="Artist - Title"
|
||||
className={INPUT_CLS}
|
||||
style={ctrl}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">
|
||||
<p style={{ fontSize: 11, opacity: 0.45, margin: '5px 0 0' }}>
|
||||
Used for folder naming. Auto-generated from metadata if available.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Preset Type */}
|
||||
<div className="space-y-3">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Output Preset</span>
|
||||
<select value={presetType} onChange={(e) => setPresetType(e.target.value)} className={SELECT_CLS}>
|
||||
{/* ── Output preset ────────────────────────────────────────────────────── */}
|
||||
<div>
|
||||
<label>
|
||||
<span style={fieldLabel}>Output Preset</span>
|
||||
<select value={presetType} onChange={(e) => setPresetType(e.target.value)} style={ctrl}>
|
||||
{presets?.preset_types.map((p) => (
|
||||
<option key={p.id} value={p.id}>{p.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">
|
||||
<p style={{ fontSize: 12, opacity: 0.5, margin: '6px 0 0', lineHeight: 1.4 }}>
|
||||
{presets?.preset_types.find(p => p.id === presetType)?.description}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Static Options */}
|
||||
{/* ── Static options ───────────────────────────────────────────────────── */}
|
||||
{presetType === 'static' && (
|
||||
<div className="space-y-3 rounded-lg border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800/50 p-4">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs text-slate-500 dark:text-gray-400 uppercase tracking-wider">Remove Elements</span>
|
||||
<select value={staticOption} onChange={(e) => setStaticOption(e.target.value)} className={SELECT_CLS}>
|
||||
<div style={card}>
|
||||
<label>
|
||||
<span style={fieldLabel}>Remove Elements</span>
|
||||
<select value={staticOption} onChange={(e) => setStaticOption(e.target.value)} style={ctrl}>
|
||||
{presets?.static_options.map((o) => (
|
||||
<option key={o.id} value={o.id}>{o.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">
|
||||
<p style={{ fontSize: 12, opacity: 0.5, margin: '6px 0 0', lineHeight: 1.4 }}>
|
||||
{presets?.static_options.find(o => o.id === staticOption)?.description}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Dynamic Options */}
|
||||
{/* ── Dynamic options ──────────────────────────────────────────────────── */}
|
||||
{presetType === 'dynamic' && (
|
||||
<div className="space-y-4 rounded-lg border border-slate-200 dark:border-gray-700 bg-slate-50 dark:bg-gray-800/50 p-4">
|
||||
<p className="text-sm font-medium text-slate-700 dark:text-gray-300">Volume Levels</p>
|
||||
<p className="text-xs text-slate-500 dark:text-gray-500">Adjust the volume of each stem (0 = mute, 1 = original, 2 = double)</p>
|
||||
|
||||
<div style={card}>
|
||||
<p style={{ fontSize: 13, fontWeight: 600, margin: '0 0 4px' }}>Volume Levels</p>
|
||||
<p style={{ fontSize: 12, opacity: 0.5, margin: '0 0 14px' }}>
|
||||
Adjust the volume of each stem (0 = mute, 1 = original, 2 = double)
|
||||
</p>
|
||||
{Object.entries(dynamicLevels).map(([stem, value]) => (
|
||||
<div key={stem} className="space-y-1">
|
||||
<div className="flex justify-between items-center">
|
||||
<label className="text-sm capitalize text-slate-700 dark:text-gray-300">{stem}</label>
|
||||
<span className="text-sm text-slate-500 dark:text-gray-400">{Math.round(value * 100)}%</span>
|
||||
<div key={stem} style={{ marginBottom: 12 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
|
||||
<label style={{ fontSize: 13, textTransform: 'capitalize' }}>{stem}</label>
|
||||
<span style={{ fontSize: 13, opacity: 0.55 }}>{Math.round(value * 100)}%</span>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
@@ -419,46 +456,73 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
step="0.1"
|
||||
value={value}
|
||||
onChange={(e) => handleDynamicChange(stem as keyof DynamicLevels, parseFloat(e.target.value))}
|
||||
className={SLIDER_CLS}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Preset Preview */}
|
||||
{/* ── Preset output preview ────────────────────────────────────────────── */}
|
||||
{presetType !== 'stems_only' && (
|
||||
<div className="rounded-lg border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-950/30 px-4 py-3 text-sm text-blue-700 dark:text-blue-300">
|
||||
<p className="font-medium">Output Structure Preview:</p>
|
||||
<code className="block mt-2 text-xs whitespace-pre text-blue-600 dark:text-blue-400">
|
||||
{projectName || 'Project Name'}/
|
||||
{'\n'} Stems/ (always created)
|
||||
{presetType === 'instrumental' && "\n Instrumental/ (vocals removed)"}
|
||||
<div style={{
|
||||
borderRadius: 6,
|
||||
border: `1px solid rgba(var(--brand-500, 59 130 246), 0.35)`,
|
||||
background: `rgba(var(--brand-500, 59 130 246), 0.06)`,
|
||||
padding: '10px 14px', fontSize: 13,
|
||||
}}>
|
||||
<p style={{ fontWeight: 600, margin: '0 0 6px', color: accentColor }}>Output Structure Preview:</p>
|
||||
<code style={{
|
||||
display: 'block', fontSize: 11, whiteSpace: 'pre',
|
||||
color: accentColor, opacity: 0.85, fontFamily: 'monospace', lineHeight: 1.7,
|
||||
}}>
|
||||
{projectName || 'Project Name'}/{'\n'}
|
||||
{' Stems/ (always created)'}
|
||||
{presetType === 'instrumental' && '\n Instrumental/ (vocals removed)'}
|
||||
{presetType === 'static' && `\n Static/ (${presets?.static_options.find(o => o.id === staticOption)?.label})`}
|
||||
{presetType === 'dynamic' && "\n Dynamic/ (volume adjusted mix)"}
|
||||
{presetType === 'dynamic' && '\n Dynamic/ (volume adjusted mix)'}
|
||||
</code>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <p className="text-sm text-red-500 dark:text-red-400">{error}</p>}
|
||||
{/* ── Error message ────────────────────────────────────────────────────── */}
|
||||
{error && (
|
||||
<p style={{ fontSize: 13, color: 'var(--color-red, #ef4444)', margin: 0 }}>{error}</p>
|
||||
)}
|
||||
|
||||
{/* ── Submit button ────────────────────────────────────────────────────── */}
|
||||
<button
|
||||
onClick={submit}
|
||||
disabled={(inputMode === 'upload' ? !file : !importedFile) || loading}
|
||||
className="w-full rounded-lg bg-brand-600 hover:bg-brand-500 disabled:bg-slate-200 disabled:text-slate-400 dark:disabled:bg-gray-800 dark:disabled:text-gray-500 px-4 py-2.5 text-sm font-semibold text-white disabled:cursor-not-allowed transition-colors"
|
||||
disabled={!hasInput || loading}
|
||||
className="button primary"
|
||||
style={{ width: '100%', padding: '10px 16px', fontSize: 14, fontWeight: 600 }}
|
||||
>
|
||||
{loading ? 'Submitting…' : presetType === 'stems_only' ? 'Separate Stems' : `Separate & Create ${presets?.preset_types.find(p => p.id === presetType)?.label}`}
|
||||
{loading
|
||||
? 'Submitting…'
|
||||
: presetType === 'stems_only'
|
||||
? 'Separate Stems'
|
||||
: `Separate & Create ${presets?.preset_types.find(p => p.id === presetType)?.label}`}
|
||||
</button>
|
||||
|
||||
{/* ── Auto pipeline button ─────────────────────────────────────────────── */}
|
||||
<button
|
||||
onClick={() => setShowAuto(true)}
|
||||
disabled={(inputMode === 'upload' ? !file : !importedFile)}
|
||||
className="w-full rounded-lg border border-amber-400 dark:border-amber-600 bg-amber-50 dark:bg-amber-950/30 hover:bg-amber-100 dark:hover:bg-amber-900/40 disabled:opacity-40 disabled:cursor-not-allowed px-4 py-2.5 text-sm font-semibold text-amber-700 dark:text-amber-400 transition-colors flex items-center justify-center gap-2"
|
||||
disabled={!hasInput}
|
||||
style={{
|
||||
width: '100%', padding: '9px 16px', fontSize: 13, fontWeight: 600,
|
||||
borderRadius: 4, cursor: hasInput ? 'pointer' : 'not-allowed',
|
||||
border: '1px solid var(--color-amber, #f59e0b)',
|
||||
background: 'rgba(245, 158, 11, 0.07)',
|
||||
color: 'var(--color-amber, #f59e0b)',
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
|
||||
opacity: hasInput ? 1 : 0.4, transition: 'opacity 0.15s',
|
||||
}}
|
||||
>
|
||||
<Zap className="w-4 h-4" />
|
||||
<Zap size={15} />
|
||||
Auto Pipeline
|
||||
</button>
|
||||
|
||||
{/* ── Dialogs / job status / results ───────────────────────────────────── */}
|
||||
{showAuto && (
|
||||
<AutoPipelineDialog
|
||||
target={{
|
||||
@@ -481,14 +545,18 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
)}
|
||||
|
||||
{jobId && <JobStatus jobId={jobId} onDone={setResult} />}
|
||||
|
||||
{result && (
|
||||
<div className="space-y-4">
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
{result.result?.project_name && (
|
||||
<div className="rounded-lg border border-green-200 dark:border-green-800 bg-green-50 dark:bg-green-950/30 px-4 py-3">
|
||||
<p className="text-sm font-medium text-green-800 dark:text-green-300">
|
||||
<div style={{
|
||||
borderRadius: 6, border: '1px solid rgba(16, 185, 129, 0.4)',
|
||||
background: 'rgba(16, 185, 129, 0.07)', padding: '10px 14px',
|
||||
}}>
|
||||
<p style={{ fontSize: 13, fontWeight: 600, color: 'var(--color-green, #10b981)', margin: '0 0 3px' }}>
|
||||
Project: {result.result.project_name}
|
||||
</p>
|
||||
<p className="text-xs text-green-600 dark:text-green-400 mt-1">
|
||||
<p style={{ fontSize: 11, color: 'var(--color-green, #10b981)', opacity: 0.7, margin: 0 }}>
|
||||
Location: {result.result.project_path}
|
||||
</p>
|
||||
</div>
|
||||
@@ -496,6 +564,47 @@ export default function Separator({ onSeparationComplete, onOpenSettings }: Prop
|
||||
<ResultFiles jobId={result.id} files={result.files} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Imported file selector row ───────────────────────────────────────────────
|
||||
|
||||
function ImportedFileButton({
|
||||
file, selected, onSelect,
|
||||
}: {
|
||||
file: ImportedFile
|
||||
selected: boolean
|
||||
onSelect: () => void
|
||||
}) {
|
||||
const [hovered, setHovered] = useState(false)
|
||||
const accentColor = `rgb(var(--brand-500, 59 130 246))`
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={onSelect}
|
||||
onMouseEnter={() => setHovered(true)}
|
||||
onMouseLeave={() => setHovered(false)}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'flex-start', gap: 10,
|
||||
width: '100%', padding: '8px 12px', textAlign: 'left',
|
||||
border: 'none', borderLeft: `3px solid ${selected ? accentColor : 'transparent'}`,
|
||||
background: selected
|
||||
? `rgba(var(--brand-500, 59 130 246), 0.08)`
|
||||
: hovered ? 'var(--background)' : 'transparent',
|
||||
cursor: 'pointer', transition: 'background 0.12s, border-color 0.12s',
|
||||
}}
|
||||
>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ fontSize: 12, fontWeight: 500, margin: '0 0 2px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{file.filename}
|
||||
</p>
|
||||
<p style={{ fontSize: 10, opacity: 0.45, margin: 0 }}>
|
||||
{(file.size / 1024 / 1024).toFixed(1)} MB
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
+495
-612
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user