Files
bytesize/src/lib/Main.svelte
T
lashman 2cd836b09e quality pass 2: cached encoders, cancel in gif retry, overlay CSS split
- debug logging in picker changed to tracing::debug
- show_overlay uses visible_window_bounds helper
- encode_gif retry loop checks cancel flag between attempts
- list_encoders cached via OnceLock (ffmpeg -encoders runs once)
- remove unnecessary GifBudgetMode clone (is Copy)
- config test uses unique temp dir per process
- click highlights use 2px border instead of solid fill
- audio capture_loop polls at 5ms instead of 1ms
- overlay window loads minimal overlay.css instead of full app.css
- remove non-spec 960x540 preset
- Settings dirty detection uses field-by-field comparison
- Overlay startDragging catches errors
- pauseRec only emits recording-state on success
- Picker listener cleanup guards against unmount race
- add sync notes for previewDims and sr-only trim inputs
2026-05-30 00:01:56 +03:00

1632 lines
50 KiB
Svelte

<script lang="ts">
import { onMount } from "svelte"
import { api, convertFileSrc, 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"
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 useFrame: boolean = $state(false)
let previewTimer: number | null = null
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"],
[800, 800, "1:1"],
[540, 960, "9:16"],
]
// Derived
let trimmedDuration = $derived(Math.max(0.1, trimEnd - trimStart))
// NOTE: This logic mirrors gif_params() in encode.rs. Keep in sync.
let previewDims = $derived.by(() => {
if (!clip) return ""
if (format === "gif") {
const colorFactor = Math.sqrt(gifColors / 256)
const bpf = 0.2 * colorFactor
const requestedFps = fps
const aspect = clip.height === 0 ? 16 / 9 : clip.width / clip.height
if (gifBudgetMode === "resolution") {
const maxW = Math.min(clip.width, 1280)
const w = Math.max(120, maxW)
const h = Math.round(w / aspect)
const pixelsPerFrame = w * h
const bytesPerFrame = pixelsPerFrame * bpf
const maxFrames = Math.max(1, Math.floor((targetMB * 1_048_576) / bytesPerFrame))
const minFps = Math.max(1, Math.round(maxFrames / trimmedDuration))
const effectiveFps = Math.max(1, Math.min(requestedFps, minFps))
const w2 = w & ~1
const h2 = Math.round(w2 / aspect) & ~1
return `${w2}x${h2} @ ${effectiveFps}fps`
} else if (gifBudgetMode === "framerate") {
const frames = Math.max(1, requestedFps * trimmedDuration)
const budget = (targetMB * 1_048_576) / (frames * bpf)
const w = Math.sqrt(budget * aspect)
const w2 = Math.min(clip.width, Math.max(120, Math.round(w))) & ~1
const h2 = Math.round(w2 / aspect) & ~1
return `${w2}x${h2}`
} else {
const framesAtFull = Math.max(1, requestedFps * trimmedDuration)
const budgetAtFull = (targetMB * 1_048_576) / (framesAtFull * bpf)
const wAtFull = Math.sqrt(budgetAtFull * aspect)
const scale = wAtFull < clip.width ? Math.sqrt(wAtFull / clip.width) : 1
const w2 = Math.max(60, Math.round(clip.width * scale)) & ~1
const h2 = Math.round(w2 / aspect) & ~1
const effectiveFps = Math.max(1, Math.min(requestedFps, Math.round(requestedFps * scale)))
return `${w2}x${h2} @ ${effectiveFps}fps`
}
}
return `${clip.width}x${clip.height}`
})
onMount(() => {
let unlistenHotkey: (() => void) | null = null
let unlistenProgress: (() => void) | null = null
let unlistenAudio: (() => void) | null = null
let unlistenOverlayClosed: (() => void) | null = null
void (async () => {
unlistenOverlayClosed = await listen("overlay-closed", () => {
useFrame = false
})
config = await api.getConfig()
format = config.export.default_format
fps = config.capture.default_fps
keepAudio = config.capture.capture_audio
gifDither = config.export.gif_dither
unlistenHotkey = await 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()
}
})
unlistenProgress = await api.onEncodeProgress((p) => {
encodeProgress = { pass: p.pass, total: p.total_passes, pct: p.percent }
})
unlistenAudio = await api.onAudioFailed((msg) => {
audioWarning = msg || "audio capture failed - audio will not be recorded"
})
})()
return () => {
unlistenHotkey?.()
unlistenProgress?.()
unlistenAudio?.()
unlistenOverlayClosed?.()
}
})
// ---- Actions ----
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, fps })
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(minMB(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() }
catch (e) { errMsg = String(e) }
void emit("recording-state", { phase: "recording", fps })
}
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) { thumbnails = cached; deletedFrames = new Set(); return }
loadingThumbs = true
try {
const thumbs = await api.extractThumbnails(fps)
thumbCache.set(cacheKey, thumbs)
if (thumbCache.size > 5) {
const firstKey = thumbCache.keys().next().value
if (firstKey) thumbCache.delete(firstKey)
}
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()
if (previewTimer !== null) { clearTimeout(previewTimer); previewTimer = null }
elapsed = 0; phase = "idle"
}
async function cancelExport() {
try { await api.cancelExport() } catch {}
phase = "editing"
encodeProgress = null
}
function confirmDiscard() {
showDiscardConfirm = true
}
function cancelDiscard() {
showDiscardConfirm = false
}
function doDiscard() {
showDiscardConfirm = false
startOver()
}
function tick() { elapsedTimer = window.setInterval(() => { elapsed += 0.1 }, 100) }
function clearTick() { if (elapsedTimer !== null) { clearInterval(elapsedTimer); elapsedTimer = null } }
function minMB(s: number): number { return Math.max(0.1, Math.max(50_000, s * 50_000) / 1_048_576) }
function maxMB(s: number): number { return Math.min(200, Math.max(10, s * 5)) }
// Trim drag
let trackEl: HTMLDivElement | null = $state(null)
let dragging: 'start' | 'end' | null = $state(null)
let trimPreviewPath: string | null = $state(null)
let trimPreviewBust: number = $state(0)
let lastTrimPreview = 0
function pointerToSecs(e: PointerEvent): number {
if (!trackEl || !clip) return 0
const rect = trackEl.getBoundingClientRect()
const x = e.clientX - rect.left
const ratio = Math.max(0, Math.min(1, x / rect.width))
return ratio * clip.duration_secs
}
async function updateTrimPreview(secs: number) {
const now = Date.now()
if (now - lastTrimPreview < 100) return // 10Hz max
lastTrimPreview = now
try {
trimPreviewPath = await api.renderRawPreview(secs)
trimPreviewBust = Date.now()
} catch {}
}
function startDrag(which: 'start' | 'end', e: PointerEvent) {
dragging = which
const el = e.currentTarget as HTMLElement
el.setPointerCapture(e.pointerId)
// Show raw frame at current trim position
void updateTrimPreview(which === 'start' ? trimStart : trimEnd)
}
function onDrag(e: PointerEvent) {
if (!dragging || !clip) return
const secs = pointerToSecs(e)
if (dragging === 'start') {
trimStart = Math.min(secs, trimEnd - 0.1)
} else {
trimEnd = Math.max(secs, trimStart + 0.1)
}
// Update raw preview as user drags
void updateTrimPreview(secs)
}
function endDrag(e: PointerEvent) {
const el = e.currentTarget as HTMLElement
el.releasePointerCapture(e.pointerId)
dragging = null
// Switch back to compressed preview
trimPreviewPath = null
void refreshPreview()
}
function onTrackClick(e: PointerEvent) {
if (!clip || !trackEl) return
const secs = pointerToSecs(e)
const distToStart = Math.abs(secs - trimStart)
const distToEnd = Math.abs(secs - trimEnd)
if (distToStart < distToEnd) {
trimStart = Math.min(secs, trimEnd - 0.1)
} else {
trimEnd = Math.max(secs, trimStart + 0.1)
}
}
// Reactivity
$effect(() => {
if (phase === "editing" && format === "gif") void loadThumbnails()
else if (format !== "gif") thumbnails = []
})
$effect(() => {
if (phase === "editing" && format) {
const timer = window.setTimeout(() => { void refreshPreview() }, 300)
return () => { clearTimeout(timer) }
}
})
$effect(() => {
if (phase === "editing" && !pathOverridden && format) {
void api.defaultOutputPath(format).then(p => { if (!pathOverridden) outputPath = p })
}
})
// 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" : ""
)
let phaseColor = $derived(
phase === "recording" ? "var(--recording)" :
phase === "paused" ? "var(--warn)" :
phase === "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" title="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
api.setOverlayAspect(aspectLock)
emit("overlay-set-ratio", { ratio: aspectLock })
api.setOverlaySize(w, h)
}}>{label}</button>
{/each}
{#if aspectLock !== null}
<button class="chip unlock" onclick={() => {
aspectLock = null
api.setOverlayAspect(null)
emit("overlay-set-ratio", { ratio: null })
}}>Unlock</button>
{/if}
</div>
{/if}
<div class="idle-fps">
<span class="switch-label">Capture FPS</span>
<select bind:value={fps}>
{#each [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>
{audioWarning}
</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 -->
{#if (dragging && trimPreviewPath ? trimPreviewPath : previewPath)}
<div class="preview-box">
<img src={convertFileSrc(dragging && trimPreviewPath ? trimPreviewPath : previewPath) + "?t=" + (dragging && trimPreviewPath ? trimPreviewBust : previewCacheBust)} alt="preview frame" class="preview-img"/>
{#if previewLoading && !dragging}<div class="preview-loading">rendering</div>{/if}
{#if dragging}<div class="preview-loading">original</div>{/if}
</div>
{:else}
<div class="preview-box empty">
<span class="preview-placeholder">preview</span>
</div>
{/if}
<!-- Trim timeline -->
<div class="trim-block">
<div class="trim-labels">
<span class="mono">{trimStart.toFixed(2)}s</span>
<span class="trim-kept">{trimmedDuration.toFixed(2)}s kept</span>
<span class="mono">{trimEnd.toFixed(2)}s</span>
</div>
<div
class="trim-track"
bind:this={trackEl}
onpointerdown={onTrackClick}
role="none"
>
<div class="trim-range" style="left:{(trimStart/clip.duration_secs)*100}%; right:{(1-trimEnd/clip.duration_secs)*100}%"></div>
<div
class="trim-handle trim-start"
style="left:{(trimStart/clip.duration_secs)*100}%"
role="slider"
aria-label="trim start"
aria-valuemin={0}
aria-valuemax={trimEnd - 0.1}
aria-valuenow={trimStart}
tabindex="0"
onpointerdown={(e) => startDrag('start', e)}
onpointermove={onDrag}
onpointerup={endDrag}
onkeydown={(e) => {
if (!clip) return
const step = e.shiftKey ? 0.5 : 0.05
if (e.key === 'ArrowLeft') { trimStart = Math.max(0, trimStart - step); e.preventDefault() }
else if (e.key === 'ArrowRight') { trimStart = Math.min(trimEnd - 0.1, trimStart + step); e.preventDefault() }
}}
></div>
<div
class="trim-handle trim-end"
style="left:{(trimEnd/clip.duration_secs)*100}%"
role="slider"
aria-label="trim end"
aria-valuemin={trimStart + 0.1}
aria-valuemax={clip.duration_secs}
aria-valuenow={trimEnd}
tabindex="0"
onpointerdown={(e) => startDrag('end', e)}
onpointermove={onDrag}
onpointerup={endDrag}
onkeydown={(e) => {
if (!clip) return
const step = e.shiftKey ? 0.5 : 0.05
if (e.key === 'ArrowLeft') { trimEnd = Math.max(trimStart + 0.1, trimEnd - step); e.preventDefault() }
else if (e.key === 'ArrowRight') { trimEnd = Math.min(clip.duration_secs, trimEnd + step); e.preventDefault() }
}}
></div>
</div>
<!-- Screen reader alternative: these range inputs mirror the drag handle positions. -->
<input type="range" min="0" max={clip.duration_secs} step="0.05" value={trimStart}
oninput={(e) => { const v = parseFloat((e.currentTarget as HTMLInputElement).value); trimStart = Math.min(v, trimEnd - 0.1) }}
class="sr-only" aria-label="trim start seconds" />
<input type="range" min="0" max={clip.duration_secs} step="0.05" value={trimEnd}
oninput={(e) => { const v = parseFloat((e.currentTarget as HTMLInputElement).value); trimEnd = Math.max(v, trimStart + 0.1) }}
class="sr-only" aria-label="trim end seconds" />
</div>
<!-- GIF frames -->
{#if format === "gif" && (thumbnails.length > 0 || loadingThumbs)}
<div class="frames-block">
<div class="frames-head">
<span class="section-title">Frames</span>
{#if deletedFrames.size > 0}
<button class="text-btn" onclick={clearDeleted}>Clear ({deletedFrames.size})</button>
{/if}
</div>
{#if loadingThumbs}
<p class="frames-hint">extracting...</p>
{:else}
<div class="frames-strip">
{#each thumbnails as path, idx}
<button
class="frame-thumb"
class:del={deletedFrames.has(idx)}
onclick={() => toggleThumb(idx)}
aria-pressed={deletedFrames.has(idx)}
aria-label="frame {idx+1} - {deletedFrames.has(idx) ? 'deleted, click to restore' : 'click to delete'}"
title={deletedFrames.has(idx) ? "restore" : "delete"}
>
<img src={convertFileSrc(path)} alt="" loading="lazy" />
<span class="frame-idx">{idx+1}</span>
</button>
{/each}
</div>
{/if}
</div>
{/if}
</div>
<!-- Right: controls -->
<div class="edit-right">
<!-- Target size -->
<div class="control-group">
<div class="control-head">
<span class="section-title">Target size</span>
<span class="mono size-readout">{targetMB.toFixed(1)} MB</span>
</div>
<input
type="range"
class="styled-range"
min={minMB(clip.duration_secs)}
max={maxMB(clip.duration_secs)}
step="0.1"
bind:value={targetMB}
onchange={refreshPreview}
/>
<p class="estimate">{previewDims} &middot; {fps}fps &middot; {trimmedDuration.toFixed(1)}s</p>
</div>
{#if format === "gif"}
<div class="control-group">
<span class="section-title">Budget priority</span>
<div class="fmt-bar">
{#each (["resolution", "framerate", "balanced"] as const) as m}
<button
class="fmt-chip"
class:active={gifBudgetMode === m}
onclick={() => { gifBudgetMode = m }}
>{m === "resolution" ? "Resolution" : m === "framerate" ? "Framerate" : "Balanced"}</button>
{/each}
</div>
<p class="estimate">
{gifBudgetMode === "resolution" ? "Keeps resolution high, may reduce FPS" :
gifBudgetMode === "framerate" ? "Keeps FPS high, may reduce resolution" :
"Balances resolution and FPS"}
</p>
</div>
<div class="control-group">
<span class="section-title">Colors</span>
<div class="control-head">
<input
type="range"
class="styled-range"
min={2}
max={256}
step={1}
bind:value={gifColors}
onchange={refreshPreview}
/>
<span class="mono" style="min-width:32px;text-align:right">{gifColors}</span>
</div>
<p class="estimate">{gifColors <= 32 ? "Low - small file, posterized" : gifColors <= 128 ? "Medium - balanced" : "High - full color"}</p>
</div>
<div class="control-group">
<span class="section-title">Dithering</span>
<div class="fmt-bar">
{#each (["floyd_steinberg", "bayer", "none"] as const) as d}
<button
class="fmt-chip"
class:active={gifDither === d}
onclick={() => { gifDither = d; refreshPreview() }}
>{d === "floyd_steinberg" ? "Floyd-Steinberg" : d === "bayer" ? "Bayer" : "None"}</button>
{/each}
</div>
<p class="estimate">{gifDither === "floyd_steinberg" ? "Smooth gradients, slightly larger" : gifDither === "bayer" ? "Patterned, smaller file" : "No dithering, smallest file"}</p>
</div>
{/if}
<!-- FPS + Audio -->
<div class="control-row">
<label class="control">
<span class="control-label">FPS</span>
<select bind:value={fps} onchange={refreshPreview}>
{#each [15, 24, 30, 60] as f}<option value={f}>{f}</option>{/each}
</select>
</label>
{#if format !== "gif"}
<label class="check-control">
<input type="checkbox" bind:checked={keepAudio} />
<span>Keep audio</span>
</label>
{/if}
</div>
<!-- Crop -->
<div class="control-group">
<div class="control-head">
<span class="section-title">Crop</span>
<label class="check-control compact">
<input type="checkbox" bind:checked={cropEnabled} />
<span>Enable</span>
</label>
</div>
{#if cropEnabled}
<div class="crop-grid">
<label class="crop-field">
<span>X</span>
<input type="number" min="0" max={clip?.width ?? 9999} bind:value={cropX} />
</label>
<label class="crop-field">
<span>Y</span>
<input type="number" min="0" max={clip?.height ?? 9999} bind:value={cropY} />
</label>
<label class="crop-field">
<span>W</span>
<input type="number" min="1" max={clip?.width ?? 9999} bind:value={cropW} />
</label>
<label class="crop-field">
<span>H</span>
<input type="number" min="1" max={clip?.height ?? 9999} bind:value={cropH} />
</label>
</div>
{/if}
</div>
<!-- Output path -->
<div class="control-group">
<span class="section-title">Output</span>
<div class="path-row">
<input type="text" class="path-input" bind:value={outputPath} oninput={() => pathOverridden = true} aria-label="output file path" />
<button class="btn-ghost" onclick={browseOutput}>Browse</button>
</div>
</div>
<!-- Actions -->
<div class="edit-actions">
<button class="btn-primary" onclick={doExport}>Export</button>
<button class="btn-ghost" onclick={confirmDiscard}>Discard</button>
</div>
</div>
</div>
<!-- EXPORTING -->
{:else if phase === "exporting"}
<div class="exporting">
{#if encodeProgress}
<div class="enc-meta">
<span>Pass {encodeProgress.pass}/{encodeProgress.total}</span>
<span class="mono">{encodeProgress.pct.toFixed(0)}%</span>
</div>
<div class="enc-track">
<div class="enc-fill" style="width:{encodeProgress.pct}%"></div>
</div>
{:else}
<div class="enc-meta"><span>Preparing</span></div>
<div class="enc-track"><div class="enc-fill" style="width:0%"></div></div>
{/if}
<p class="enc-hint">ffmpeg is encoding your clip</p>
<button class="btn-ghost" onclick={cancelExport}>Cancel</button>
</div>
<!-- DONE -->
{:else if phase === "done" && exportResult}
<div class="done">
<div class="done-mark">
<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>
</div>
<h2 class="done-title">Exported</h2>
<p class="done-size mono">{formatBytes(exportResult.size_bytes)}</p>
<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={() => exportResult && 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); }
/* ---- 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-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, .edit-right {
background: var(--bg);
display: flex;
flex-direction: column;
gap: 1px;
overflow: auto;
min-height: 0;
}
.edit-left { padding: 20px; gap: 20px; }
.edit-right { padding: 20px; gap: 20px; border-left: 1px solid var(--border); }
@media (max-width: 720px) {
.edit { grid-template-columns: 1fr; }
.edit-right { border-left: none; border-top: 1px solid var(--border); }
}
/* 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); }
/* Preview */
.preview-box {
position: relative;
border-radius: var(--r-sm);
overflow: hidden;
background: var(--bg-2);
border: 1px solid var(--border);
display: grid;
place-items: center;
aspect-ratio: 16 / 9;
}
.preview-box.empty { aspect-ratio: 16 / 9; }
.preview-img {
width: 100%;
height: 100%;
object-fit: contain;
display: block;
}
.preview-placeholder {
font-size: 11px;
color: var(--text-4);
text-transform: uppercase;
letter-spacing: 0.08em;
}
.preview-loading {
position: absolute; inset: 0;
background: rgba(0,0,0,0.5);
display: grid; place-items: center;
font-size: 11px;
color: var(--text-3);
text-transform: uppercase;
letter-spacing: 0.06em;
}
/* Trim */
.trim-block { display: flex; flex-direction: column; gap: 8px; }
.trim-track {
position: relative;
height: 4px;
background: var(--bg-3);
border-radius: 2px;
cursor: pointer;
}
.trim-range {
position: absolute; top: 0; bottom: 0;
background: var(--accent);
border-radius: 2px;
pointer-events: none;
}
.trim-handle {
position: absolute; top: 50%; transform: translate(-50%, -50%);
width: 12px; height: 22px;
background: var(--accent);
border-radius: var(--r-sm);
cursor: ew-resize;
z-index: 1;
touch-action: none;
}
.trim-handle:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--accent-glow); }
.trim-labels {
display: flex;
justify-content: space-between;
font-size: 11px;
color: var(--text-3);
font-family: var(--mono);
}
.trim-kept { color: var(--accent); }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
/* Frames */
.frames-block { display: flex; flex-direction: column; gap: 8px; }
.frames-head { display: flex; justify-content: space-between; align-items: center; }
.frames-hint { margin: 0; font-size: 11px; color: var(--text-3); }
.frames-strip {
display: flex;
gap: 4px;
overflow-x: auto;
padding-bottom: 4px;
}
.frames-strip::-webkit-scrollbar { height: 3px; }
.frames-strip::-webkit-scrollbar-thumb { background: var(--border-2); border-radius: 2px; }
.frame-thumb {
flex: 0 0 auto;
position: relative;
padding: 0;
border: 1px solid transparent;
border-radius: var(--r-sm);
background: transparent;
cursor: pointer;
overflow: hidden;
transition: border-color 80ms;
}
.frame-thumb img { display: block; width: 64px; height: auto; border-radius: 2px; }
.frame-thumb:hover { border-color: var(--accent); }
.frame-thumb.del img { opacity: 0.2; filter: grayscale(1); }
.frame-thumb.del { border-color: var(--err); }
.frame-idx {
position: absolute; bottom: 2px; right: 3px;
font-family: var(--mono); font-size: 9px;
color: var(--text-3);
background: rgba(0,0,0,0.6);
padding: 0 3px;
border-radius: 2px;
}
/* Right panel controls */
.control-group { display: flex; flex-direction: column; gap: 8px; }
.control-head {
display: flex;
justify-content: space-between;
align-items: center;
}
.section-title {
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.1em;
color: var(--text-3);
}
.size-readout { font-size: 14px; color: var(--text); }
.styled-range {
-webkit-appearance: none;
width: 100%;
height: 3px;
background: var(--bg-3);
border-radius: 2px;
outline: none;
cursor: pointer;
}
.styled-range::-webkit-slider-thumb {
-webkit-appearance: none;
width: 14px; height: 14px;
border-radius: 50%;
background: var(--accent);
border: 2px solid var(--bg);
cursor: pointer;
transition: transform 80ms;
}
.styled-range::-webkit-slider-thumb:hover { transform: scale(1.2); }
.estimate {
margin: 0;
font-size: 11px;
color: var(--text-3);
font-family: var(--mono);
}
.control-row {
display: flex;
gap: 16px;
align-items: flex-end;
}
.control { display: flex; flex-direction: column; gap: 6px; }
.control-label {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--text-3);
}
select {
padding: 7px 10px;
background: var(--bg-2);
border: 1px solid var(--border);
color: var(--text);
border-radius: var(--r-sm);
font-family: var(--mono);
font-size: 12px;
cursor: pointer;
outline: none;
}
select:focus { border-color: var(--accent); }
.check-control {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: var(--text-2);
cursor: pointer;
}
.check-control.compact { font-size: 11px; }
.check-control input[type="checkbox"] {
width: 14px; height: 14px;
accent-color: var(--accent);
cursor: pointer;
}
/* Crop */
.crop-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
}
.crop-field {
display: flex;
flex-direction: column;
gap: 4px;
}
.crop-field span {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--text-3);
}
.crop-field input {
padding: 6px 8px;
background: var(--bg-2);
border: 1px solid var(--border);
color: var(--text);
border-radius: var(--r-sm);
font-family: var(--mono);
font-size: 12px;
outline: none;
width: 100%;
}
.crop-field input:focus { border-color: var(--accent); }
/* Path */
.path-row { display: flex; gap: 6px; }
.path-input {
flex: 1;
padding: 7px 10px;
background: var(--bg-2);
border: 1px solid var(--border);
color: var(--text);
border-radius: var(--r-sm);
font-family: var(--mono);
font-size: 11px;
outline: none;
}
.path-input:focus { border-color: var(--accent); }
.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); }
.edit-actions {
display: flex;
gap: 10px;
margin-top: auto;
padding-top: 8px;
}
.text-btn {
background: none;
border: none;
color: var(--accent);
cursor: pointer;
font-size: 11px;
font-family: var(--sans);
padding: 0;
transition: color 80ms;
}
.text-btn:hover { color: var(--accent-hover); }
/* ---- 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;
}
.enc-fill {
height: 100%;
background: var(--accent);
border-radius: 2px;
transition: width 0.4s ease;
}
.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-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;
}
.confirm-card {
background: var(--bg-2);
border: 1px solid var(--border);
border-radius: var(--r-md);
padding: 24px;
min-width: 280px;
text-align: center;
}
.confirm-card p { margin: 0 0 16px; font-size: 14px; color: var(--text); }
.confirm-actions { display: flex; gap: 10px; justify-content: center; }
</style>