Files
bytesize/src/lib/Main.svelte
T

1297 lines
40 KiB
Svelte

<script lang="ts">
import { onDestroy, onMount } from "svelte"
import { api, formatBytes, type Config, type Format, type GifBudgetMode, type GifDither, type RecordedClip, type ExportResult, type CaptureRect } from "./api"
import { save } from "@tauri-apps/plugin-dialog"
import { emit, listen } from "@tauri-apps/api/event"
import TrimPanel from "./TrimPanel.svelte"
import Preview from "./Preview.svelte"
import FramesStrip from "./FramesStrip.svelte"
import ExportSidebar from "./ExportSidebar.svelte"
import { resetTrimPreview } from "./trimPreviewState.svelte"
import { minTargetMB } from "./exportSizing"
type Phase = "idle" | "recording" | "paused" | "editing" | "exporting" | "done"
let { onSettings }: { onSettings: () => void } = $props()
let phase: Phase = $state("idle")
let config: Config | null = $state(null)
let clip: RecordedClip | null = $state(null)
let elapsed: number = $state(0)
let elapsedTimer: number | null = null
// Export config
let format: Format = $state("gif")
let keepAudio: boolean = $state(false)
let fps: number = $state(30)
let targetMB: number = $state(8)
let trimStart: number = $state(0)
let trimEnd: number = $state(0)
let outputPath: string = $state("")
let pathOverridden: boolean = $state(false)
let gifBudgetMode: GifBudgetMode = $state("balanced")
let gifDither: GifDither = $state("floyd_steinberg")
let gifColors: number = $state(256)
// Post-record crop
let cropEnabled: boolean = $state(false)
let cropX: number = $state(0)
let cropY: number = $state(0)
let cropW: number = $state(0)
let cropH: number = $state(0)
// Thumbnails
let thumbnails: string[] = $state([])
let deletedFrames: Set<number> = $state(new Set())
let loadingThumbs: boolean = $state(false)
// Preview
let previewPath: string | null = $state(null)
let previewLoading: boolean = $state(false)
let previewCacheBust: number = $state(0)
// State
let exportResult: ExportResult | null = $state(null)
let errMsg: string | null = $state(null)
let encodeProgress: { pass: number; total: number; pct: number } | null = $state(null)
let audioWarning: string | null = $state(null)
let retryingAudio: boolean = $state(false)
let useFrame: boolean = $state(false)
let thumbCache: Map<string, string[]> = $state(new Map())
let showDiscardConfirm: boolean = $state(false)
let aspectLock: number | null = $state(null)
const PRESETS: [number, number, string][] = [
[1280, 720, "720p"],
[1920, 1080, "1080p"],
[960, 540, "16:9"],
[800, 800, "1:1"],
[540, 960, "9:16"],
]
// Derived
let trimmedDuration = $derived(Math.max(0.1, trimEnd - trimStart))
// GIF size/dimensions estimate - computed by the Rust backend so the
// math stays in lockstep with encode.rs::gif_params. We fetch a table of
// estimates across a target-bytes grid once per parameter set (fps, dims,
// duration, mode, colors) and interpolate on slider drag locally to avoid
// one IPC per debounce tick.
let gifEstimate: { width: number; fps: number; height: number; dims_label: string } | null = $state(null)
let gifEstimateTimer: number | null = null
let gifTable: { key: string; points: { target_bytes: number; width: number; fps: number; height: number }[] } | null = $state(null)
async function refreshGifTable() {
if (!clip || format !== "gif") { gifTable = null; return }
const key = `${fps}|${gifBudgetMode}|${gifColors}|${clip.width}x${clip.height}|${trimmedDuration}`
try {
const table = await api.estimateGifParamsTable({
format: "gif",
fps,
gif_budget_mode: gifBudgetMode,
gif_dither: gifDither,
gif_colors: gifColors,
clip_width: clip.width,
clip_height: clip.height,
duration_secs: trimmedDuration,
})
gifTable = { key, points: table.points }
} catch {
gifTable = null
}
}
// Interpolate the cached table for the current target_bytes. GIF width/fps
// are step functions of budget, so we find the bracketing grid points and
// pick the lower one (slightly conservative on dims).
function interpolateTable(): { width: number; fps: number; height: number; dims_label: string } | null {
if (!gifTable || gifTable.points.length === 0) return null
const target = Math.round(targetMB * 1_048_576)
const pts = gifTable.points
let chosen = pts[0]
for (const p of pts) {
if (p.target_bytes <= target) chosen = p
else break
}
const { width, fps, height } = chosen
return { width, fps, height, dims_label: `${width}x${height} @ ${fps}fps` }
}
// Debounced: re-fetch the table when any non-target parameter changes;
// re-interpolate when targetMB changes (local, no IPC).
$effect(() => {
void phase; void clip; void format
if (phase !== "editing" || !clip || format !== "gif") { gifTable = null; gifEstimate = null; return }
const key = `${fps}|${gifBudgetMode}|${gifColors}|${clip.width}x${clip.height}|${trimmedDuration}`
if (!gifTable || gifTable.key !== key) {
if (gifEstimateTimer !== null) clearTimeout(gifEstimateTimer)
gifEstimateTimer = window.setTimeout(() => { void refreshGifTable() }, 150)
}
return () => {
if (gifEstimateTimer !== null) { clearTimeout(gifEstimateTimer); gifEstimateTimer = null }
}
})
// Local interpolation on targetMB changes - no IPC.
$effect(() => {
void targetMB
if (phase !== "editing" || !clip || format !== "gif") { gifEstimate = null; return }
gifEstimate = interpolateTable()
})
let previewDims = $derived.by(() => {
if (!clip) return ""
if (format === "gif") {
return gifEstimate ? gifEstimate.dims_label : "computing..."
}
return `${clip.width}x${clip.height}`
})
onMount(() => {
const unlisten: (() => void)[] = []
// Registered one at a time rather than through a single Promise.all: one
// rejected registration used to lose the whole batch, which left every
// listener live and none of them removable - hotkeys included.
const keep = (p: Promise<() => void>) => {
void p.then(fn => unlisten.push(fn))
.catch(e => console.warn("could not register a listener:", e))
}
keep(listen("overlay-closed", () => { useFrame = false }))
keep(api.onHotkey((kind) => {
if (kind === "start" && phase === "idle") void startRec()
else if (kind === "pause") {
if (phase === "recording") void pauseRec()
else if (phase === "paused") void resumeRec()
} else if (kind === "stop") {
if (phase === "recording" || phase === "paused") void stopRec()
}
}))
keep(api.onEncodeProgress((p) => {
encodeProgress = { pass: p.pass, total: p.total_passes, pct: p.percent }
}))
keep(api.onAudioFailed((msg) => {
audioWarning = msg || "audio capture failed - audio will not be recorded"
}))
keep(listen("audio-recovered", () => { audioWarning = null }))
void (async () => {
try {
config = await api.getConfig()
format = config.export.default_format
fps = config.capture.default_fps
keepAudio = config.capture.capture_audio
gifDither = config.export.gif_dither
} catch (e) {
console.warn("failed to load config:", e)
}
})()
return () => { unlisten.forEach(fn => fn()) }
})
// ---- Actions ----
// Several template handlers fire a command without awaiting it; an unhandled
// rejection there would disappear without a trace.
function toastOnFail(p: Promise<unknown>) {
void p.catch((e) => { errMsg = String(e) })
}
async function toggleFrame() {
useFrame = !useFrame
try {
await (useFrame ? api.showOverlay() : api.hideOverlay())
} catch (e) { errMsg = String(e); useFrame = false }
}
async function startRec() {
errMsg = null; audioWarning = null; elapsed = 0
let crop: CaptureRect | null = null
if (useFrame) {
try { crop = await api.getOverlayRect() } catch (e) { errMsg = String(e); return }
}
try {
await api.startCapture({ crop })
phase = "recording"
tick()
void emit("recording-state", { phase: "recording", fps })
} catch (e) { errMsg = String(e) }
}
async function stopRec() {
void emit("recording-state", { phase: "idle", fps })
try {
const c = await api.stopCapture()
clearTick()
clip = c
phase = "editing"
trimStart = 0
trimEnd = c.duration_secs
cropEnabled = false
cropX = 0
cropY = 0
cropW = c.width
cropH = c.height
pathOverridden = false
outputPath = await api.defaultOutputPath(format)
const sensible = Math.min(50, Math.max(minTargetMB(c.duration_secs), Math.round(c.duration_secs * 0.5)))
targetMB = sensible
} catch (e) { errMsg = String(e); phase = "idle"; clearTick() }
}
async function pauseRec() {
try {
await api.pauseCapture()
clearTick()
phase = "paused"
void emit("recording-state", { phase: "paused", fps })
} catch (e) {
errMsg = String(e)
}
}
async function resumeRec() {
try {
await api.resumeCapture()
phase = "recording"
tick()
void emit("recording-state", { phase: "recording", fps })
} catch (e) { errMsg = String(e) }
}
async function retryAudio() {
if (retryingAudio) return
retryingAudio = true
try {
await api.restartAudioCapture()
// On success, the audio-recovered listener clears audioWarning.
// On failure, onAudioFailed re-fires with the new error message.
} catch (e) { errMsg = String(e) }
finally { retryingAudio = false }
}
async function browseOutput() {
const ext = format === "gif" ? "gif" : format === "webm" ? "webm" : "mp4"
const picked = await save({ defaultPath: outputPath, filters: [{ name: format.toUpperCase(), extensions: [ext] }] })
if (picked) { outputPath = picked; pathOverridden = true }
}
async function refreshPreview() {
if (!clip) return
previewLoading = true
try {
previewPath = await api.renderPreview(format, fps, Math.round(targetMB * 1_048_576), format === "gif" ? gifBudgetMode : undefined, format === "gif" ? gifDither : undefined, format === "gif" ? gifColors : undefined)
previewCacheBust = Date.now()
} catch (e) { previewPath = null; console.warn("preview render failed:", e) }
finally { previewLoading = false }
}
async function loadThumbnails() {
if (format !== "gif") { thumbnails = []; return }
const cacheKey = `${format}-${fps}`
const cached = thumbCache.get(cacheKey)
if (cached) {
// Promote to most-recently-used so eviction is LRU, not FIFO.
// Map iteration is insertion-order; delete + re-set moves the key to the end.
thumbCache.delete(cacheKey)
thumbCache.set(cacheKey, cached)
thumbnails = cached
deletedFrames = new Set()
return
}
loadingThumbs = true
try {
const thumbs = await api.extractThumbnails(fps)
thumbCache.set(cacheKey, thumbs)
if (thumbCache.size > 5) {
const oldestKey = thumbCache.keys().next().value
if (oldestKey) thumbCache.delete(oldestKey)
}
thumbnails = thumbs
deletedFrames = new Set()
} catch (e) { errMsg = String(e) }
finally { loadingThumbs = false }
}
function toggleThumb(idx: number) {
const n = new Set(deletedFrames)
n.has(idx) ? n.delete(idx) : n.add(idx)
deletedFrames = n
}
function clearDeleted() { deletedFrames = new Set() }
async function doExport() {
if (!clip) return
errMsg = null; encodeProgress = null; phase = "exporting"
try {
const tsStart = trimStart > 0.05 ? trimStart : null
const tsEnd = trimEnd < clip.duration_secs - 0.05 ? trimEnd : null
const crop = cropEnabled ? { x: Math.round(cropX), y: Math.round(cropY), width: Math.round(cropW), height: Math.round(cropH) } satisfies CaptureRect : null
const result = await api.export({
format, target_bytes: Math.round(targetMB * 1_048_576), fps,
keep_audio: keepAudio && format !== "gif",
deleted_frame_indices: format === "gif" ? Array.from(deletedFrames) : [],
trim_start_secs: tsStart, trim_end_secs: tsEnd,
output_path: outputPath.trim() || null,
crop,
gif_budget_mode: format === "gif" ? gifBudgetMode : undefined,
gif_dither: format === "gif" ? gifDither : undefined,
gif_colors: format === "gif" ? gifColors : undefined,
})
exportResult = result; phase = "done"
} catch (e) { errMsg = String(e); phase = "editing" }
}
function startOver() {
clip = null; exportResult = null; errMsg = null; encodeProgress = null
thumbnails = []; deletedFrames = new Set()
thumbCache = new Map()
previewPath = null; resetTrimPreview()
elapsed = 0; phase = "idle"
if (config) {
format = config.export.default_format
fps = config.capture.default_fps
gifDither = config.export.gif_dither
gifBudgetMode = "balanced"
gifColors = 256
}
}
async function cancelExport() {
try { await api.cancelExport() } catch {}
phase = "editing"
encodeProgress = null
}
function confirmDiscard() {
showDiscardConfirm = true
}
function cancelDiscard() {
showDiscardConfirm = false
}
async function doDiscard() {
try { await api.discardClip() }
catch (error) { errMsg = String(error); return }
showDiscardConfirm = false
startOver()
}
function tick() { elapsedTimer = window.setInterval(() => { elapsed += 0.1 }, 100) }
function clearTick() { if (elapsedTimer !== null) { clearInterval(elapsedTimer); elapsedTimer = null } }
onDestroy(clearTick)
// The settings view replaces Main, which would strand a running capture or
// encode with no UI left to stop it, so the button stays locked while one is
// live.
const BUSY_PHASES: Phase[] = ["recording", "paused", "exporting"]
let settingsLocked = $derived(BUSY_PHASES.includes(phase))
// Reactivity
$effect(() => {
if (phase === "editing" && format === "gif") void loadThumbnails()
else if (format !== "gif") thumbnails = []
})
// Single owner of preview rendering. Touches every input that affects the
// preview so one debounced render fires per change-burst - previously the
// debounced effect here and TrimPanel's synchronous onAfterChange could
// both trigger a render for the same change.
//
// Trim and crop are deliberately not inputs: render_preview samples the middle
// of the whole clip and ignores both, so depending on them bought an extra
// ffmpeg run per drag that could not change a pixel.
$effect(() => {
void phase; void format; void fps; void targetMB
void gifBudgetMode; void gifDither; void gifColors
if (phase === "editing" && format) {
const timer = window.setTimeout(() => { void refreshPreview() }, 300)
return () => { clearTimeout(timer) }
}
})
$effect(() => {
const f = format
if (phase !== "editing" || pathOverridden || !f) return
void api.defaultOutputPath(f).then(p => { if (!pathOverridden) outputPath = p })
.catch(e => console.warn("could not resolve the default output path:", e))
})
// Auto-dismiss error toast
$effect(() => {
if (errMsg) {
const timer = setTimeout(() => { errMsg = null }, 8000)
return () => clearTimeout(timer)
}
})
// Phase label
let phaseLabel = $derived(
phase === "idle" ? "READY" :
phase === "recording"? "RECORDING" :
phase === "paused" ? "PAUSED" :
phase === "editing" ? "CLIP READY" :
phase === "exporting"? "ENCODING" :
phase === "done" ? "DONE" : ""
)
// Overall encode percent across all passes/attempts. The encoder reports
// per-pass percent (0-100 within one pass); with GIF retrying up to ~12
// times the headline number otherwise jumps back to single digits each
// attempt. Spread each pass's percent across its share of the whole.
let encodeOverall = $derived.by(() => {
if (!encodeProgress) return 0
const { pass, total, pct } = encodeProgress
if (total <= 0) return pct
return ((pass - 1) / total) * 100 + (pct / total)
})
// GIF retry loop calls each pass an "attempt"; two-pass video keeps "pass".
let encodeUnit = $derived(format === "gif" ? "attempt" : "pass")
let phaseColor: string = $derived.by(() => {
const p: string = phase
return p === "recording" ? "var(--recording)" :
p === "paused" ? "var(--warn)" :
p === "done" ? "var(--accent)" :
"var(--text-3)"
})
</script>
<div class="app">
<!-- Top bar -->
<header class="topbar">
<div class="topbar-left">
<span class="brand">BYTESIZE</span>
</div>
<div class="topbar-center">
<span class="phase" style="color:{phaseColor}">
<span class="phase-dot" class:pulse={phase === "recording"} style="background:{phaseColor}"></span>
{phaseLabel}
</span>
{#if clip && (phase === "editing" || phase === "exporting" || phase === "done")}
<span class="top-meta">{clip.width}x{clip.height} &middot; {clip.duration_secs.toFixed(2)}s</span>
{/if}
{#if phase === "recording" || phase === "paused"}
<span class="top-meta mono">{elapsed.toFixed(1)}s</span>
{/if}
</div>
<div class="topbar-right">
<button class="icon-btn" onclick={onSettings} aria-label="settings" disabled={settingsLocked}
title={settingsLocked ? "stop the current recording or export first" : "settings"}>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<circle cx="8" cy="8" r="2"/>
<path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.3 3.3l1.4 1.4M11.3 11.3l1.4 1.4M3.3 12.7l1.4-1.4M11.3 4.7l1.4-1.4"/>
</svg>
</button>
</div>
</header>
<!-- Content -->
<main class="main">
<!-- IDLE -->
{#if phase === "idle"}
<div class="idle">
<button class="rec-btn" onclick={startRec} aria-label="start recording">
<svg width="32" height="32" viewBox="0 0 32 32" fill="currentColor">
<circle cx="16" cy="16" r="12"/>
</svg>
</button>
<p class="idle-hint">
{#if useFrame}
Drag the frame to position your capture region
{:else}
Captures the full primary monitor
{/if}
</p>
<div class="idle-options">
<label class="switch-row">
<span class="switch-label">Use capture frame</span>
<button
class="switch"
class:on={useFrame}
onclick={toggleFrame}
role="switch"
aria-checked={useFrame}
aria-label="use capture frame"
>
<span class="switch-knob"></span>
</button>
</label>
{#if useFrame}
<div class="preset-row">
{#each PRESETS as [w, h, label]}
<button class="chip" onclick={() => {
aspectLock = w / h
toastOnFail(api.setOverlayAspect(aspectLock))
emit("overlay-set-ratio", { ratio: aspectLock })
toastOnFail(api.setOverlaySize(w, h))
}}>{label}</button>
{/each}
{#if aspectLock !== null}
<button class="chip unlock" onclick={() => {
aspectLock = null
toastOnFail(api.setOverlayAspect(null))
emit("overlay-set-ratio", { ratio: null })
}}>Unlock</button>
{/if}
</div>
{/if}
<div class="idle-fps">
<span class="switch-label">Export FPS</span>
<select bind:value={fps}>
{#each [1, 2, 5, 10, 15, 24, 30, 60] as f}<option value={f}>{f}</option>{/each}
</select>
</div>
</div>
</div>
<!-- RECORDING / PAUSED -->
{:else if phase === "recording" || phase === "paused"}
<div class="recording">
<div class="timer">
<span class="timer-digits mono">{elapsed.toFixed(1)}</span>
<span class="timer-unit">seconds</span>
</div>
{#if audioWarning}
<div class="audio-warn" role="alert">
<svg width="12" height="12" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round">
<path d="M7 1L13 12H1L7 1z"/><line x1="7" y1="5" x2="7" y2="8"/><circle cx="7" cy="10.5" r="0.5" fill="currentColor"/>
</svg>
<span>{audioWarning}</span>
<button class="audio-retry" onclick={retryAudio} disabled={retryingAudio}>
{retryingAudio ? "Retrying" : "Retry"}
</button>
</div>
{:else if config?.capture.capture_audio}
<div class="audio-ok">
<span class="audio-dot" class:active={phase === "recording"}></span>
<span>audio</span>
</div>
{/if}
<div class="rec-controls">
<button class="btn-stop" onclick={stopRec}>
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor"><rect x="1" y="1" width="10" height="10" rx="1"/></svg>
Stop
</button>
{#if phase === "recording"}
<button class="btn-ctrl" onclick={pauseRec}>Pause</button>
{:else}
<button class="btn-ctrl accent" onclick={resumeRec}>Resume</button>
{/if}
</div>
</div>
<!-- EDITING -->
{:else if phase === "editing" && clip}
<div class="edit">
<!-- Left: preview + timeline -->
<div class="edit-left">
<!-- Format selector -->
<div class="fmt-bar">
{#each (["gif","webm","mp4"] as const) as f}
<button
class="fmt-chip"
class:active={format === f}
onclick={() => { format = f }}
aria-pressed={format === f}
>{f.toUpperCase()}</button>
{/each}
</div>
<!-- Preview -->
<Preview
{previewPath}
{previewLoading}
{previewCacheBust}
/>
<!-- Trim timeline. Preview re-render is driven by the debounced
$effect that watches trimStart/trimEnd, so no onAfterChange. -->
<TrimPanel
{clip}
bind:trimStart
bind:trimEnd
/>
<!-- GIF frames -->
{#if format === "gif" && (thumbnails.length > 0 || loadingThumbs)}
<FramesStrip
{thumbnails}
{deletedFrames}
loading={loadingThumbs}
onToggle={toggleThumb}
onClear={clearDeleted}
/>
{/if}
</div>
<!-- Right: controls -->
<ExportSidebar
{clip}
{format}
bind:targetMB
bind:fps
bind:keepAudio
bind:gifBudgetMode
bind:gifDither
bind:gifColors
bind:cropEnabled
bind:cropX
bind:cropY
bind:cropW
bind:cropH
bind:outputPath
{previewDims}
{trimmedDuration}
onPreview={refreshPreview}
onPathInput={() => pathOverridden = true}
onBrowse={browseOutput}
onExport={doExport}
onDiscard={confirmDiscard}
/>
</div>
<!-- EXPORTING -->
{:else if phase === "exporting"}
<div class="exporting">
{#if encodeProgress}
<div class="enc-meta">
<span class="text-cap">{encodeUnit} {encodeProgress.pass}/{encodeProgress.total}</span>
<span class="mono">{encodeOverall.toFixed(0)}%</span>
</div>
<div class="enc-track" class:multi={encodeProgress.total > 3}>
{#each Array(encodeProgress.total) as _, i}
<div class="enc-segment">
<div
class="enc-fill"
style="width:{i + 1 < encodeProgress.pass ? 100 : i + 1 === encodeProgress.pass ? encodeProgress.pct : 0}%"
></div>
</div>
{/each}
</div>
{:else}
<div class="enc-meta"><span>Preparing</span></div>
<div class="enc-track"><div class="enc-segment"><div class="enc-fill" style="width:0%"></div></div></div>
{/if}
<p class="enc-hint">ffmpeg is encoding your clip{format === "gif" ? " (retrying to hit target size)" : ""}</p>
<button class="btn-ghost" onclick={cancelExport}>Cancel</button>
</div>
<!-- DONE -->
{:else if phase === "done" && exportResult}
<div class="done">
<div class="done-mark" class:warn={!exportResult.met_target}>
{#if exportResult.met_target}
<svg width="28" height="28" viewBox="0 0 28 28" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="14" cy="14" r="11"/><polyline points="9,14 13,18 19,11"/>
</svg>
{:else}
<svg width="28" height="28" viewBox="0 0 28 28" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="14" cy="14" r="11"/><line x1="14" y1="8" x2="14" y2="15"/><circle cx="14" cy="19" r="0.5" fill="currentColor"/>
</svg>
{/if}
</div>
<h2 class="done-title">
{exportResult.met_target ? "Exported" : "Exported (over budget)"}
</h2>
<p class="done-size mono">{formatBytes(exportResult.size_bytes)}</p>
{#if !exportResult.met_target}
<p class="done-caveat">
target {formatBytes(exportResult.target_bytes)} - could not shrink further without wrecking quality
</p>
{/if}
<p class="done-path mono">{exportResult.output_path}</p>
<div class="done-actions">
<button class="btn-primary" onclick={startOver}>Record another</button>
<button class="btn-ghost" onclick={() => {
if (exportResult) toastOnFail(api.revealInExplorer(exportResult.output_path))
}}>
Show in explorer
</button>
</div>
</div>
{/if}
{#if showDiscardConfirm}
<div class="confirm-overlay">
<div class="confirm-card">
<p>Discard this recording?</p>
<div class="confirm-actions">
<button class="btn-ghost" onclick={cancelDiscard}>Keep it</button>
<button class="btn-stop" onclick={doDiscard}>Discard</button>
</div>
</div>
</div>
{/if}
</main>
<!-- Error toast -->
{#if errMsg}
<div class="err-toast" role="alert">
<svg width="12" height="12" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round">
<circle cx="7" cy="7" r="6"/><line x1="7" y1="4" x2="7" y2="7.5"/><circle cx="7" cy="10" r="0.5" fill="currentColor"/>
</svg>
{errMsg}
<button class="err-dismiss" onclick={() => errMsg = null} aria-label="dismiss error">
<svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round">
<line x1="2" y1="2" x2="8" y2="8"/>
<line x1="8" y1="2" x2="2" y2="8"/>
</svg>
</button>
</div>
{/if}
</div>
<style>
.app {
display: flex;
flex-direction: column;
min-height: 100vh;
background: var(--bg);
}
/* ---- Top bar ---- */
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
height: 44px;
padding: 0 16px;
border-bottom: 1px solid var(--border);
background: var(--bg-2);
flex-shrink: 0;
}
.topbar-left, .topbar-right { display: flex; align-items: center; gap: 8px; }
.topbar-center { display: flex; align-items: center; gap: 12px; }
.brand {
font-family: var(--mono);
font-size: 11px;
font-weight: 500;
letter-spacing: 0.1em;
color: var(--text-3);
}
.phase {
display: flex;
align-items: center;
gap: 6px;
font-family: var(--mono);
font-size: 11px;
font-weight: 500;
letter-spacing: 0.04em;
}
.phase-dot {
width: 5px; height: 5px;
border-radius: 50%;
background: var(--text-3);
flex-shrink: 0;
}
.phase-dot.pulse { animation: recpulse 1.2s ease-in-out infinite; }
@keyframes recpulse { 0%,100%{opacity:1} 50%{opacity:0.25} }
.top-meta {
font-size: 11px;
color: var(--text-3);
letter-spacing: 0.02em;
}
.icon-btn {
display: grid; place-items: center;
width: 28px; height: 28px;
background: transparent;
border: 1px solid var(--border);
color: var(--text-3);
border-radius: var(--r-sm);
cursor: pointer;
transition: color 80ms, border-color 80ms, background 80ms;
}
.icon-btn:hover { color: var(--text); border-color: var(--border-2); background: var(--bg-3); }
.icon-btn:disabled { opacity: 0.35; cursor: not-allowed; }
.icon-btn:disabled:hover { color: var(--text-3); border-color: var(--border); background: transparent; }
/* ---- Main ---- */
.main {
flex: 1;
display: flex;
flex-direction: column;
overflow: auto;
position: relative;
}
/* ---- Idle ---- */
.idle {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 32px;
padding: 40px 24px;
}
.rec-btn {
width: 88px; height: 88px;
border-radius: var(--r-md);
background: var(--bg-3);
border: 1px solid var(--border-2);
color: var(--text-3);
cursor: pointer;
display: grid; place-items: center;
transition: all 80ms;
}
.rec-btn:hover {
background: var(--bg-4);
border-color: var(--accent);
color: var(--accent);
transform: scale(1.04);
}
.rec-btn:active { transform: scale(0.97); }
.idle-hint {
margin: 0;
font-size: 12px;
color: var(--text-3);
text-align: center;
}
.idle-options {
display: flex;
flex-direction: column;
gap: 12px;
width: 100%;
max-width: 280px;
}
.switch-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 14px;
background: var(--bg-2);
border: 1px solid var(--border);
border-radius: var(--r-sm);
cursor: default;
}
.switch-label { font-size: 12px; color: var(--text-2); }
.switch {
width: 36px; height: 20px;
border-radius: 10px;
background: var(--bg-4);
border: 1px solid var(--border-2);
cursor: pointer;
position: relative;
transition: background 80ms, border-color 80ms;
flex-shrink: 0;
}
.switch.on { background: var(--accent); border-color: var(--accent); }
.switch-knob {
position: absolute;
top: 2px; left: 2px;
width: 14px; height: 14px;
border-radius: 50%;
background: var(--text-3);
transition: transform 80ms, background 80ms;
}
.switch.on .switch-knob { transform: translateX(16px); background: var(--accent-text); }
.idle-fps {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 14px;
background: var(--bg-2);
border: 1px solid var(--border);
border-radius: var(--r-sm);
}
.preset-row {
display: flex;
gap: 6px;
justify-content: center;
flex-wrap: wrap;
}
.chip {
padding: 5px 12px;
background: var(--bg-2);
border: 1px solid var(--border);
color: var(--text-2);
border-radius: var(--r-sm);
font-family: var(--mono);
font-size: 11px;
cursor: pointer;
transition: border-color 80ms, color 80ms;
}
.chip:hover { border-color: var(--accent); color: var(--accent); }
.chip.unlock {
border-color: var(--warn);
color: var(--warn);
}
.chip.unlock:hover {
background: var(--warn);
color: var(--bg);
}
/* ---- Recording ---- */
.recording {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 24px;
padding: 40px 24px;
}
.timer {
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
}
.timer-digits {
font-size: 80px;
font-weight: 400;
color: var(--recording);
letter-spacing: -0.03em;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.timer-unit {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.12em;
color: var(--text-3);
}
.audio-warn {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 14px;
background: var(--err-dim);
border: 1px solid var(--err-border);
border-radius: var(--r-sm);
font-size: 12px;
color: var(--err);
}
.audio-warn > span { flex: 1; }
.audio-retry {
background: transparent;
border: 1px solid var(--err-border);
color: var(--err);
padding: 3px 10px;
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 11px;
font-weight: 500;
cursor: pointer;
transition: background 80ms, border-color 80ms;
}
.audio-retry:hover:not(:disabled) { background: var(--err); color: #fff; }
.audio-retry:disabled { opacity: 0.5; cursor: not-allowed; }
.audio-ok {
display: flex;
align-items: center;
gap: 8px;
font-size: 11px;
color: var(--text-3);
text-transform: uppercase;
letter-spacing: 0.06em;
}
.audio-dot {
width: 5px; height: 5px;
border-radius: 50%;
background: var(--text-3);
transition: background 80ms;
}
.audio-dot.active { background: var(--recording); animation: recpulse 1.2s ease-in-out infinite; }
.rec-controls {
display: flex;
gap: 10px;
margin-top: 8px;
}
.btn-stop {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 22px;
background: var(--stop);
border: none;
color: #fff;
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: background 80ms;
}
.btn-stop:hover { background: var(--stop-hover); }
.btn-ctrl {
padding: 10px 22px;
background: var(--bg-3);
border: 1px solid var(--border-2);
color: var(--text);
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: background 80ms, border-color 80ms;
}
.btn-ctrl:hover { background: var(--bg-4); border-color: var(--border-3); }
.btn-ctrl.accent { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
.btn-ctrl.accent:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
/* ---- Edit ---- */
.edit {
flex: 1;
display: grid;
grid-template-columns: minmax(300px, 1.4fr) minmax(250px, 1fr);
gap: 1px;
background: var(--border);
min-height: 0;
}
.edit-left {
background: var(--bg);
display: flex;
flex-direction: column;
gap: 1px;
overflow: auto;
min-height: 0;
}
.edit-left { padding: 20px; gap: 20px; }
@media (max-width: 720px) {
.edit { grid-template-columns: 1fr; }
}
/* Format bar */
.fmt-bar {
display: flex;
gap: 2px;
padding: 3px;
background: var(--bg-2);
border: 1px solid var(--border);
border-radius: var(--r-sm);
width: fit-content;
}
.fmt-chip {
padding: 5px 14px;
background: transparent;
border: 1px solid transparent;
color: var(--text-3);
border-radius: var(--r-sm);
font-family: var(--mono);
font-size: 11px;
font-weight: 500;
letter-spacing: 0.04em;
cursor: pointer;
transition: all 80ms;
}
.fmt-chip:hover { color: var(--text-2); }
.fmt-chip.active { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
.btn-primary {
padding: 10px 24px;
background: var(--accent);
border: none;
color: var(--accent-text);
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: background 80ms;
white-space: nowrap;
}
.btn-primary:hover { background: var(--accent-hover); }
.btn-ghost {
padding: 10px 18px;
background: transparent;
border: 1px solid var(--border-2);
color: var(--text-3);
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 13px;
cursor: pointer;
transition: border-color 80ms, color 80ms;
white-space: nowrap;
}
.btn-ghost:hover { border-color: var(--border-3); color: var(--text); }
/* ---- Exporting ---- */
.exporting {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 16px;
padding: 40px 24px;
max-width: 400px;
margin: 0 auto;
width: 100%;
}
.enc-meta {
display: flex;
justify-content: space-between;
width: 100%;
font-size: 12px;
color: var(--text-2);
}
.enc-track {
width: 100%;
height: 3px;
background: var(--bg-3);
border-radius: 2px;
overflow: hidden;
display: flex;
gap: 2px;
}
/* GIF retry renders many thin segments; tighten the gap so they don't read as
a dotted line at 10+ attempts. */
.enc-track.multi { gap: 1px; }
.enc-segment { flex: 1; background: var(--bg-3); overflow: hidden; }
.enc-fill {
height: 100%;
background: var(--accent);
border-radius: 2px;
transition: width 0.4s ease;
}
.text-cap { text-transform: capitalize; }
.enc-hint {
margin: 0;
font-size: 11px;
color: var(--text-3);
}
/* ---- Done ---- */
.done {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 14px;
padding: 40px 24px;
}
.done-mark {
color: var(--accent);
}
.done-mark.warn {
color: var(--warn);
}
.done-caveat {
margin: 0;
font-size: 11px;
color: var(--warn);
text-align: center;
max-width: 320px;
line-height: 1.5;
}
.done-title {
margin: 0;
font-size: 18px;
font-weight: 600;
color: var(--text);
letter-spacing: -0.01em;
}
.done-size {
margin: 0;
font-size: 22px;
font-family: var(--mono);
color: var(--accent);
font-variant-numeric: tabular-nums;
}
.done-path {
margin: 0;
font-size: 11px;
color: var(--text-3);
word-break: break-all;
text-align: center;
max-width: 420px;
font-family: var(--mono);
}
.done-actions {
display: flex;
gap: 10px;
margin-top: 8px;
}
/* ---- Error toast ---- */
.err-toast {
position: fixed;
bottom: 16px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 8px;
padding: 10px 18px;
background: var(--err-dim);
border: 1px solid var(--err-border);
border-radius: var(--r-sm);
font-size: 12px;
color: var(--err);
z-index: 100;
animation: slideup 150ms ease-out;
}
@keyframes slideup {
from { opacity: 0; transform: translateX(-50%) translateY(8px); }
to { opacity: 1; transform: translateX(-50%) translateY(0); }
}
.err-dismiss {
background: none;
border: none;
color: var(--err);
cursor: pointer;
padding: 0;
display: grid;
place-items: center;
margin-left: 4px;
opacity: 0.6;
transition: opacity 80ms;
}
.err-dismiss:hover { opacity: 1; }
.mono { font-family: var(--mono); }
/* ---- Confirm overlay ---- */
.confirm-overlay {
position: fixed; inset: 0;
background: rgba(0,0,0,0.5);
display: grid; place-items: center;
z-index: 50;
animation: fadein 120ms ease-out;
}
.confirm-card {
background: var(--bg-2);
border: 1px solid var(--border);
border-radius: var(--r-md);
padding: 24px;
min-width: 280px;
text-align: center;
animation: cardin 140ms ease-out;
}
@keyframes fadein { from { opacity: 0; } to { opacity: 1; } }
@keyframes cardin { from { opacity: 0; transform: translateY(6px) scale(0.98); } to { opacity: 1; transform: translateY(0) scale(1); } }
.confirm-card p { margin: 0 0 16px; font-size: 14px; color: var(--text); }
.confirm-actions { display: flex; gap: 10px; justify-content: center; }
</style>