import { convertFileSrc } from "@tauri-apps/api/core"; type RecordingState = | "WaitingForGame" | "Buffering" | "RecordingSession" | "Clipping" | "Processing" | "StorageLow"; type ClipSource = "Auto Event" | "Manual Hotkey" | "Bookmark" | "Imported" | "Screenshot"; type UploadState = "Local only" | "Uploaded" | "Failed" | "Queued"; type UploadProvider = "catbox" | "litterbox" | "custom_http" | "lustful"; type Clip = { id: string; title: string; game: string; event: string; source: ClipSource; duration: string; createdAt: string; uploadState: UploadState; path: string; thumbnailPath: string | null; videoUrl: string | null; thumbnailUrl: string | null; tags: string[]; colorClass: string; }; type AutoEvent = { id: string; gameId: string; eventType: string; game: string; event: string; enabled: boolean; }; type AutoClipEventDto = { game_id: string; event_type: string; enabled: boolean; }; type DesktopStatus = { recording_state: RecordingState; detected_game: string | null; replay_buffer_seconds: number; system_audio_enabled: boolean; mic_enabled: boolean; mic_device: string | null; auto_record_enabled: boolean; upload_enabled: boolean; upload_provider: UploadProvider; catbox_userhash: string | null; litterbox_expiry_hours: number; custom_upload_endpoint: string | null; custom_upload_response_url_path: string; custom_upload_headers: string[]; session_recording: boolean; capture_active: boolean; capture_backend: string | null; capture_path: string | null; clip_count: number; library_root: string; ffmpeg_available: boolean; ffmpeg_path: string | null; system_audio_available: boolean; desktop_duplication_available: boolean; auto_clip_enabled_events: AutoClipEventDto[]; hotkey_clip_last_60s: string; hotkey_clip_last_30s: string; hotkey_toggle_session_recording: string; hotkey_screenshot: string; free_disk_gb: number; capture_fps: number; capture_bitrate_kbps: number; capture_resolution: string; storage_limit_gb: number; excluded_window_titles: string[]; separate_audio_tracks: boolean; game_quality_overrides: GameQualityOverrideDto[]; effective_quality_applied: boolean; app_version: string; onboarding_complete: boolean; }; type ClipDto = { id: string; title: string; game: string; event: string; source: ClipSource; duration: string; created_at: string; upload_state: UploadState; path: string; thumbnail_path: string | null; tags: string[]; color_class: string; }; type UploadHistoryEntry = { id: number; clip_id: string; provider: string; status: string; url: string | null; error: string | null; attempted_at: string; }; type GsiConfigDto = { game_id: string; path: string; }; type AudioDeviceDto = { name: string; kind: "input" | "system_loopback"; }; type UpdateInfo = { checked: boolean; updateAvailable: boolean; latestVersion: string; installerFile: string; downloadUrl: string; message: string; applying: boolean; }; type GameQualityOverrideDto = { game_id: string; name: string; width: number; height: number; fps: number; bitrate_kbps: number; }; type AppState = { activeView: "Library" | "Recording" | "Auto Clip" | "Uploads" | "Settings"; recordingState: RecordingState; detectedGame: string; replayBufferSeconds: number; systemAudioEnabled: boolean; sessionRecording: boolean; captureActive: boolean; captureBackend: string | null; capturePath: string | null; ffmpegAvailable: boolean; ffmpegPath: string | null; systemAudioAvailable: boolean; desktopDuplicationAvailable: boolean; micEnabled: boolean; micDevice: string; audioDevices: AudioDeviceDto[]; autoRecordEnabled: boolean; autoUpload: boolean; uploadProvider: UploadProvider; catboxUserhash: string; litterboxExpiryHours: 1 | 12 | 24 | 72; customUploadEndpoint: string; customUploadResponsePath: string; customUploadHeaders: string; gsiConfigStatus: string; libraryFilter: "all" | "kills" | "wins" | "uploaded" | "failed"; libraryQuery: string; libraryViewMode: "grid" | "list"; notice: string; selectedClipId: string; clips: Clip[]; screenshots: string[]; uploadHistory: UploadHistoryEntry[]; autoEvents: AutoEvent[]; hotkeyClipLast60s: string; hotkeyClipLast30s: string; hotkeyToggleRecording: string; hotkeyScreenshot: string; freeDiskGb: number; captureFps: number; captureBitrateKbps: number; captureResolution: string; storageLimitGb: number; excludedWindowTitles: string[]; excludedWindowText: string; separateAudioTracks: boolean; appVersion: string; onboardingComplete: boolean; onboardingStep: number; gameQualityOverrides: GameQualityOverrideDto[]; effectiveQualityApplied: boolean; update: UpdateInfo; }; type TauriGlobal = { core?: { invoke?: (command: string, args?: Record) => Promise; }; }; declare global { interface Window { __TAURI__?: TauriGlobal; __TAURI_INTERNALS__?: unknown; } } let tauriInvoke: ((command: string, args?: Record) => Promise) | null = null; const state: AppState = { activeView: "Library", recordingState: "WaitingForGame", detectedGame: "Waiting for game", replayBufferSeconds: 60, systemAudioEnabled: true, sessionRecording: false, captureActive: false, captureBackend: null, capturePath: null, ffmpegAvailable: false, ffmpegPath: null, systemAudioAvailable: false, desktopDuplicationAvailable: false, micEnabled: false, micDevice: "", audioDevices: [], autoRecordEnabled: false, autoUpload: false, uploadProvider: "catbox", catboxUserhash: "", litterboxExpiryHours: 24, customUploadEndpoint: "", customUploadResponsePath: "url", customUploadHeaders: "", gsiConfigStatus: "", libraryFilter: "all", libraryQuery: "", libraryViewMode: "grid", notice: "", selectedClipId: "", clips: [], screenshots: [], uploadHistory: [], autoEvents: [ { id: "cs2-kill", gameId: "counter-strike-2", eventType: "kill", game: "Counter-Strike 2", event: "Kill", enabled: true }, { id: "cs2-death", gameId: "counter-strike-2", eventType: "death", game: "Counter-Strike 2", event: "Death", enabled: true }, { id: "cs2-round", gameId: "counter-strike-2", eventType: "round_win", game: "Counter-Strike 2", event: "Round win", enabled: true }, { id: "cs2-multi", gameId: "counter-strike-2", eventType: "multi_kill", game: "Counter-Strike 2", event: "Multi-kill", enabled: true }, { id: "cs2-bomb-planted", gameId: "counter-strike-2", eventType: "bomb_planted", game: "Counter-Strike 2", event: "Bomb planted", enabled: true }, { id: "cs2-bomb-defused", gameId: "counter-strike-2", eventType: "bomb_defused", game: "Counter-Strike 2", event: "Bomb defused", enabled: true }, { id: "cs2-bomb-exploded", gameId: "counter-strike-2", eventType: "bomb_exploded", game: "Counter-Strike 2", event: "Bomb exploded", enabled: true }, { id: "cs2-mvp", gameId: "counter-strike-2", eventType: "mvp", game: "Counter-Strike 2", event: "MVP", enabled: true }, { id: "lol-kill", gameId: "league-of-legends", eventType: "kill", game: "League of Legends", event: "Champion kill", enabled: true }, { id: "lol-death", gameId: "league-of-legends", eventType: "death", game: "League of Legends", event: "Death", enabled: true }, { id: "lol-assist", gameId: "league-of-legends", eventType: "assist", game: "League of Legends", event: "Assist", enabled: true }, { id: "lol-objective", gameId: "league-of-legends", eventType: "objective", game: "League of Legends", event: "Objective", enabled: true }, { id: "dota-kill", gameId: "dota-2", eventType: "kill", game: "Dota 2", event: "Kill", enabled: true }, { id: "dota-death", gameId: "dota-2", eventType: "death", game: "Dota 2", event: "Death", enabled: true }, { id: "dota-assist", gameId: "dota-2", eventType: "assist", game: "Dota 2", event: "Assist", enabled: true }, { id: "dota-objective", gameId: "dota-2", eventType: "objective", game: "Dota 2", event: "Roshan/objective", enabled: true }, { id: "dota-multi", gameId: "dota-2", eventType: "multi_kill", game: "Dota 2", event: "Multi-kill", enabled: true }, { id: "dota-mvp", gameId: "dota-2", eventType: "mvp", game: "Dota 2", event: "MVP", enabled: true }, ], hotkeyClipLast60s: "F8", hotkeyClipLast30s: "Shift+F8", hotkeyToggleRecording: "Alt+F7", hotkeyScreenshot: "F9", freeDiskGb: 0, captureFps: 30, captureBitrateKbps: 6000, captureResolution: "1280x720", storageLimitGb: 50, excludedWindowTitles: [], excludedWindowText: "", separateAudioTracks: false, appVersion: "0.1.0", onboardingComplete: true, onboardingStep: 0, gameQualityOverrides: [], effectiveQualityApplied: false, update: { checked: false, updateAvailable: false, latestVersion: "", installerFile: "", downloadUrl: "", message: "Updates have not been checked yet.", applying: false, }, }; const root = document.querySelector("#app"); if (!root) { throw new Error("Missing #app root"); } const appRoot = root; function render() { if (!state.onboardingComplete) { appRoot.innerHTML = renderOnboardingWizard(); bindEvents(); return; } const selectedClip = state.clips.find((clip) => clip.id === state.selectedClipId) ?? state.clips[0]; appRoot.innerHTML = `
${renderRecordingBar()} ${state.notice ? `
${escapeHtml(state.notice)}
` : ""} ${renderActiveView(selectedClip)}
`; bindEvents(); } function renderOnboardingWizard() { const step = state.onboardingStep; const steps = ["Privacy", "Capture source", "Storage", "Hotkeys"]; const stepBody = (() => { switch (step) { case 0: return `

What should ClipForge record?

You can change any of these later in Settings. Audio is mixed into your clips; enable separate tracks to keep system and mic audio in distinct tracks.

`; case 1: return `

When should recording start?

Auto-clipping keeps a rolling buffer and saves highlights when supported games detect events. Continuous recording saves the full session.

`; case 2: return `

How much disk space is ClipForge allowed to use?

The rolling buffer shrinks automatically to fit this limit. Finished clips are saved to your library and are never pruned.

`; case 3: return `

You're almost set

These hotkeys are active while the app is running. You can customize them anytime in Settings.

  • Save last ${state.replayBufferSeconds}s clip${escapeHtml(state.hotkeyClipLast60s)}
  • Save last 30s clip${escapeHtml(state.hotkeyClipLast30s)}
  • Toggle recording${escapeHtml(state.hotkeyToggleRecording)}
  • Take screenshot${escapeHtml(state.hotkeyScreenshot)}
`; default: return ""; } })(); return `
CF

Welcome to ClipForge

Set up capture in a few quick steps.

    ${steps .map( (name, index) => `
  1. ${name}
  2. `, ) .join("")}
${stepBody}
${step === 0 ? `` : ``} ${step < steps.length - 1 ? `` : ``}
`; } function renderRecordingBar() { const lowDisk = state.freeDiskGb < 2 && state.freeDiskGb > 0; const statusText = lowDisk ? `Low disk (${state.freeDiskGb.toFixed(1)} GB free)` : state.captureActive ? "Recording to disk" : state.sessionRecording ? "Recording session" : `${state.recordingState} ${state.replayBufferSeconds}s`; return `

Detected game

${state.detectedGame}

${statusText}
${lowDisk ? "" : ``} ${lowDisk ? "" : ``}
`; } function renderActiveView(selectedClip: Clip | undefined) { switch (state.activeView) { case "Recording": return renderRecordingView(); case "Auto Clip": return renderAutoClipView(); case "Uploads": return renderUploadsView(); case "Settings": return renderSettingsView(); case "Library": default: return renderLibraryView(selectedClip); } } function renderLibraryView(selectedClip: Clip | undefined) { const clips = filteredClips(); return `

Local library

Recent Clips

${[ ["all", "All"], ["kills", "Kills"], ["wins", "Wins"], ["uploaded", "Uploaded"], ["failed", "Failed"], ] .map( ([filter, label]) => ``, ) .join("")}
${clips.length > 0 ? clips.map(renderClipCard).join("") : `
No matching clips
`}

Screenshots

Recent Screenshots

${state.screenshots.length > 0 ? state.screenshots.map(renderScreenshotCard).join("") : `
No screenshots
`}
${renderClipDetails(selectedClip)}
`; } function renderScreenshotCard(path: string) { const filename = path.split(/[/\\]/).pop() ?? path; const url = convertFileSrc(path); return `
${escapeHtml(filename)}

${escapeHtml(filename)}

${escapeHtml(path)}

`; } function clipFromDto(dto: ClipDto): Clip { return { id: dto.id, title: dto.title, game: dto.game, event: dto.event, source: dto.source, duration: dto.duration, createdAt: dto.created_at, uploadState: dto.upload_state, path: dto.path, thumbnailPath: dto.thumbnail_path, videoUrl: dto.path ? convertFileSrc(dto.path) : null, thumbnailUrl: dto.thumbnail_path ? convertFileSrc(dto.thumbnail_path) : null, tags: dto.tags, colorClass: dto.color_class, }; } function renderClipCard(clip: Clip) { return `
${clip.thumbnailUrl ? `` : escapeHtml(clip.event)}

${escapeHtml(clip.title)}

${escapeHtml(clip.game)} · ${escapeHtml(clip.source)} · ${escapeHtml(clip.duration)}

`; } function renderClipDetails(clip: Clip | undefined) { if (!clip) { return ` `; } const durationSeconds = parseTimestamp(clip.duration); const durationDisplay = formatDuration(durationSeconds); return ` `; } function renderRecordingView() { const override = state.gameQualityOverrides.find((candidate) => candidate.game_id === state.detectedGame) ?? null; const baseResolution = state.captureResolution || "1280x720"; const overrideResolution = override ? `${override.width}x${override.height}` : baseResolution; const presetOptions = ["1280x720", "1920x1080", "2560x1440", "3840x2160"]; const resolutionOptions = presetOptions.includes(overrideResolution) ? presetOptions : [overrideResolution, ...presetOptions]; const fpsOptions = [30, 60, 120]; const overrideFps = override?.fps ?? state.captureFps; const overrideBitrate = override?.bitrate_kbps ?? state.captureBitrateKbps; return `

Replay buffer

${state.replayBufferSeconds} seconds

Capture

${escapeHtml(state.captureResolution)} @ ${state.captureFps} fps

${state.effectiveQualityApplied ? `A quality override is active for ${escapeHtml(state.detectedGame)}.` : "Using the global quality settings."}

Lightweight desktop capture uses bundled FFmpeg when system FFmpeg is missing.

${state.desktopDuplicationAvailable ? "Desktop Duplication capture available" : "Using GDI capture fallback"}

${state.captureBackend ? `Active backend: ${state.captureBackend}` : "Active backend: idle"}

${state.ffmpegAvailable ? "FFmpeg ready" : "FFmpeg missing"}${state.ffmpegPath ? ` · ${state.ffmpegPath}` : ""}

${state.capturePath ? `Writing ${state.capturePath}` : "No active capture file"}

${state.freeDiskGb > 0 ? `${state.freeDiskGb.toFixed(1)} GB free on recording drive` : "Disk space unknown"}

Quality override

Per-game capture settings

${state.detectedGame === "Waiting for game" ? `

Start a supported game and you can give it its own resolution, FPS, and bitrate here.

` : `

Override quality for ${escapeHtml(state.detectedGame)}${override ? ` (currently ${override.width}x${override.height} @ ${override.fps} fps)` : ""}.

`}

Audio

${state.systemAudioAvailable ? "System audio ready" : "System audio unavailable"}

${state.systemAudioAvailable ? "Native WASAPI or FFmpeg audio capture is available." : "No system loopback device is available; video recording still works."}

`; } function renderAutoClipView() { return `

Game events

Auto Clip Rules

Local APIs only
${state.autoEvents .map( (event) => ` `, ) .join("")}
${state.gsiConfigStatus ? `

${state.gsiConfigStatus}

` : ""}
`; } function renderUploadsView() { const providers: Array<{ id: UploadProvider; title: string; body: string }> = [ { id: "catbox", title: "Catbox", body: "Anonymous or userhash-backed permanent uploads." }, { id: "litterbox", title: "Litterbox", body: "Temporary uploads with a selectable expiry." }, { id: "custom_http", title: "Custom HTTP", body: "POST multipart clip files to your own endpoint." }, { id: "lustful", title: "Lustful", body: "Blocked until API details are confirmed." }, ]; return `
${providers.map((provider) => `

Provider

${provider.title}

${provider.body}

`).join("")}

Automation

Upload Rules

Catbox

Userhash

Litterbox

Expiry

Custom HTTP

Endpoint

Upload history

Recent Uploads

${state.uploadHistory.length > 0 ? `
${state.uploadHistory.map(renderUploadHistoryRow).join("")}
` : `

No upload attempts recorded yet.

`}
`; } function renderUploadHistoryRow(entry: UploadHistoryEntry) { const failed = entry.status === "failed"; const uploaded = entry.status === "uploaded"; return `
${escapeHtml(entry.provider)} ${escapeHtml(entry.clip_id)} ${escapeHtml(entry.status)} ${entry.url ? `${escapeHtml(entry.url)}` : ""} ${entry.error ? `

${escapeHtml(entry.error)}

` : ""}

${escapeHtml(entry.attempted_at)}

${failed ? `` : ""}
`; } function renderSettingsView() { const resolutionPresets = ["1280x720", "1920x1080", "2560x1440", "3840x2160"]; const resolutionOptions = resolutionPresets.includes(state.captureResolution) ? resolutionPresets : [state.captureResolution, ...resolutionPresets]; const fpsPresets = [30, 60, 120, 144]; const fpsOptions = fpsPresets.includes(state.captureFps) ? fpsPresets : [state.captureFps, ...fpsPresets]; return `

Privacy

Local-first

Capture

Quality & rights

Current: ${escapeHtml(state.captureResolution)} @ ${state.captureFps} fps (${state.captureBitrateKbps.toLocaleString()} kbps). New settings apply the next time capture starts.

Storage

${state.storageLimitGb} GB buffer cap

Old temporary buffer segments are removed automatically once the buffer reaches the cap; saved clips are kept.

About & support

ClipForge ${escapeHtml(state.appVersion)}

${escapeHtml(state.update.message)}

${state.update.updateAvailable ? ` ` : ` `}

Hotkeys

Customizable

Format: [Modifier+]Key (e.g. Ctrl+Shift+F1, Alt+F7, F8). Modifiers: Ctrl, Shift, Alt, Meta.

`; } function bindEvents() { appRoot.querySelectorAll("[data-view]").forEach((button) => { button.addEventListener("click", () => { state.activeView = button.dataset.view as AppState["activeView"]; render(); }); }); appRoot.querySelectorAll("[data-clip-id]").forEach((card) => { card.addEventListener("click", () => { state.selectedClipId = card.dataset.clipId ?? state.selectedClipId; render(); }); }); appRoot.querySelectorAll("[data-view-mode]").forEach((button) => { button.addEventListener("click", () => { state.libraryViewMode = button.dataset.viewMode === "list" ? "list" : "grid"; render(); }); }); appRoot.querySelectorAll("[data-library-filter]").forEach((button) => { button.addEventListener("click", () => { state.libraryFilter = (button.dataset.libraryFilter as AppState["libraryFilter"]) ?? "all"; render(); }); }); appRoot.querySelector("[data-action='library-search']")?.addEventListener("input", (event) => { state.libraryQuery = (event.target as HTMLInputElement).value; render(); }); appRoot.querySelector("[data-action='clip']")?.addEventListener("click", () => { void saveClip(); }); appRoot.querySelector("[data-action='screenshot']")?.addEventListener("click", () => { void takeScreenshot(); }); appRoot.querySelector("[data-action='toggle-record']")?.addEventListener("click", () => { void toggleRecording(); }); appRoot.querySelector("[data-action='process']")?.addEventListener("click", () => { void trimSelectedClip(); }); appRoot.querySelector("[data-action='save-metadata']")?.addEventListener("click", () => { void saveSelectedClipMetadata(); }); appRoot.querySelector("[data-action='reveal']")?.addEventListener("click", () => { void revealSelectedClip(); }); appRoot.querySelector("[data-action='upload']")?.addEventListener("click", () => { void uploadSelectedClip(); }); appRoot.querySelector("[data-action='export-copy']")?.addEventListener("click", () => { void exportSelectedClip(); }); appRoot.querySelector("[data-action='write-gsi-configs']")?.addEventListener("click", () => { void writeGsiConfigs(); }); appRoot.querySelector("[data-action='delete']")?.addEventListener("click", () => { void deleteSelectedClip(); }); appRoot.querySelector("[data-action='buffer-length']")?.addEventListener("input", (event) => { state.replayBufferSeconds = Number((event.target as HTMLInputElement).value); render(); }); appRoot.querySelector("[data-action='buffer-length']")?.addEventListener("change", (event) => { void saveReplayBufferSetting(Number((event.target as HTMLInputElement).value)); }); appRoot.querySelector("[data-action='toggle-mic']")?.addEventListener("change", (event) => { state.micEnabled = (event.target as HTMLInputElement).checked; render(); void saveMicSetting(state.micEnabled); }); appRoot.querySelector("[data-action='toggle-system-audio']")?.addEventListener("change", (event) => { state.systemAudioEnabled = (event.target as HTMLInputElement).checked; render(); void saveSystemAudioSetting(state.systemAudioEnabled); }); appRoot.querySelector("[data-action='mic-device']")?.addEventListener("change", (event) => { state.micDevice = (event.target as HTMLSelectElement).value; void saveMicDevice(state.micDevice); }); appRoot.querySelector("[data-action='toggle-auto-upload']")?.addEventListener("change", (event) => { state.autoUpload = (event.target as HTMLInputElement).checked; render(); void saveUploadSettings(); }); appRoot.querySelector("[data-action='toggle-auto-record']")?.addEventListener("change", (event) => { state.autoRecordEnabled = (event.target as HTMLInputElement).checked; render(); void saveAutoRecordSetting(state.autoRecordEnabled); }); appRoot.querySelectorAll("[data-upload-provider]").forEach((button) => { button.addEventListener("click", () => { state.uploadProvider = button.dataset.uploadProvider as UploadProvider; render(); void saveUploadSettings(); }); }); appRoot.querySelector("[data-action='catbox-userhash']")?.addEventListener("change", (event) => { state.catboxUserhash = (event.target as HTMLInputElement).value; void saveUploadSettings(); }); appRoot.querySelector("[data-action='litterbox-expiry']")?.addEventListener("change", (event) => { state.litterboxExpiryHours = Number((event.target as HTMLSelectElement).value) as AppState["litterboxExpiryHours"]; void saveUploadSettings(); }); appRoot.querySelector("[data-action='custom-upload-endpoint']")?.addEventListener("input", (event) => { state.customUploadEndpoint = (event.target as HTMLInputElement).value; }); appRoot.querySelector("[data-action='custom-upload-endpoint']")?.addEventListener("change", () => { void saveUploadSettings(); }); appRoot.querySelector("[data-action='custom-upload-response-path']")?.addEventListener("input", (event) => { state.customUploadResponsePath = (event.target as HTMLInputElement).value; }); appRoot.querySelector("[data-action='custom-upload-response-path']")?.addEventListener("change", () => { void saveUploadSettings(); }); appRoot.querySelector("[data-action='custom-upload-headers']")?.addEventListener("input", (event) => { state.customUploadHeaders = (event.target as HTMLTextAreaElement).value; }); appRoot.querySelector("[data-action='custom-upload-headers']")?.addEventListener("change", () => { void saveUploadSettings(); }); appRoot.querySelectorAll("[data-event-id]").forEach((input) => { input.addEventListener("change", () => { const eventRule = state.autoEvents.find((event) => event.id === input.dataset.eventId); if (eventRule) { eventRule.enabled = input.checked; void saveAutoClipEventSetting(eventRule); } }); }); appRoot.querySelector("[data-action='hotkey-clip-60s']")?.addEventListener("change", (event) => { state.hotkeyClipLast60s = (event.target as HTMLInputElement).value; }); appRoot.querySelector("[data-action='hotkey-clip-30s']")?.addEventListener("change", (event) => { state.hotkeyClipLast30s = (event.target as HTMLInputElement).value; }); appRoot.querySelector("[data-action='hotkey-toggle-recording']")?.addEventListener("change", (event) => { state.hotkeyToggleRecording = (event.target as HTMLInputElement).value; }); appRoot.querySelector("[data-action='hotkey-screenshot']")?.addEventListener("change", (event) => { state.hotkeyScreenshot = (event.target as HTMLInputElement).value; }); appRoot.querySelector("[data-action='save-hotkeys']")?.addEventListener("click", () => { void saveHotkeys(); }); appRoot.querySelector("[data-action='capture-resolution']")?.addEventListener("change", (event) => { state.captureResolution = (event.target as HTMLSelectElement).value; }); appRoot.querySelector("[data-action='capture-fps']")?.addEventListener("change", (event) => { state.captureFps = Number((event.target as HTMLSelectElement).value); }); appRoot.querySelector("[data-action='capture-bitrate']")?.addEventListener("input", (event) => { state.captureBitrateKbps = Number((event.target as HTMLInputElement).value); }); appRoot.querySelector("[data-action='capture-storage-gb']")?.addEventListener("input", (event) => { state.storageLimitGb = Number((event.target as HTMLInputElement).value); }); appRoot.querySelector("[data-action='excluded-windows']")?.addEventListener("input", (event) => { state.excludedWindowText = (event.target as HTMLTextAreaElement).value; }); appRoot.querySelector("[data-action='toggle-separate-audio']")?.addEventListener("change", (event) => { state.separateAudioTracks = (event.target as HTMLInputElement).checked; }); appRoot.querySelector("[data-action='save-capture-settings']")?.addEventListener("click", () => { void saveCaptureSettings(); }); appRoot.querySelector("[data-action='check-updates']")?.addEventListener("click", () => { void checkForUpdates(); }); appRoot.querySelector("[data-action='save-override']")?.addEventListener("click", () => { void saveGameQualityOverride(); }); appRoot.querySelector("[data-action='clear-override']")?.addEventListener("click", () => { void clearGameQualityOverride(); }); appRoot.querySelector("[data-action='onboarding-next']")?.addEventListener("click", () => { state.onboardingStep = Math.min(state.onboardingStep + 1, 3); render(); }); appRoot.querySelector("[data-action='onboarding-back']")?.addEventListener("click", () => { state.onboardingStep = Math.max(state.onboardingStep - 1, 0); render(); }); appRoot.querySelector("[data-action='onboarding-finish']")?.addEventListener("click", () => { void finishOnboarding(); }); appRoot.querySelector("[data-action='onboarding-skip']")?.addEventListener("click", () => { void skipOnboarding(); }); appRoot.querySelector("[data-action='download-update']")?.addEventListener("click", () => { void downloadUpdate(); }); appRoot.querySelector("[data-action='reveal-crash-logs']")?.addEventListener("click", () => { void revealCrashLogs(); }); appRoot.querySelectorAll("[data-action='reveal-screenshot']").forEach((button) => { button.addEventListener("click", () => { const path = button.dataset.screenshotPath; if (path) { void revealScreenshot(path); } }); }); appRoot.querySelector("[data-action='refresh-upload-history']")?.addEventListener("click", () => { void refreshUploadHistory().then(() => render()); }); appRoot.querySelectorAll("[data-action='retry-upload']").forEach((button) => { button.addEventListener("click", () => { const clipId = button.dataset.clipId; if (clipId) { const entry = state.uploadHistory.find((e) => e.clip_id === clipId); if (entry) { void retryUpload(entry); } } }); }); // Timeline drag handlers const timelineTrack = appRoot.querySelector("[data-action='timeline-track']"); const handleStart = appRoot.querySelector("#timeline-handle-start"); const handleEnd = appRoot.querySelector("#timeline-handle-end"); if (timelineTrack && handleStart && handleEnd) { let draggingHandle: "start" | "end" | null = null; const clip = state.clips.find((c) => c.id === state.selectedClipId); const clipDuration = clip ? parseTimestamp(clip.duration) : 0; const updateHandlePositions = () => { const startInput = appRoot.querySelector("[data-action='trim-start']"); const endInput = appRoot.querySelector("[data-action='trim-end']"); const startLabel = appRoot.querySelector("#timeline-label-start"); const endLabel = appRoot.querySelector("#timeline-label-end"); const fill = appRoot.querySelector("#timeline-fill"); if (startInput && endInput && clipDuration > 0) { const startPercent = (parseTimestamp(startInput.value) / clipDuration) * 100; const endPercent = (parseTimestamp(endInput.value) / clipDuration) * 100; handleStart.style.left = `${Math.max(0, Math.min(100, startPercent))}%`; handleEnd.style.left = `${Math.max(0, Math.min(100, endPercent))}%`; if (fill) { fill.style.left = `${startPercent}%`; fill.style.width = `${Math.max(0, endPercent - startPercent)}%`; } if (startLabel) startLabel.textContent = formatDuration(parseTimestamp(startInput.value)); if (endLabel) endLabel.textContent = formatDuration(parseTimestamp(endInput.value)); } }; const startDrag = (handle: "start" | "end") => { draggingHandle = handle; document.body.style.cursor = "ew-resize"; document.body.style.userSelect = "none"; }; const onMouseMove = (e: MouseEvent) => { if (!draggingHandle || clipDuration <= 0) return; const rect = timelineTrack.getBoundingClientRect(); const percent = Math.max(0, Math.min(100, ((e.clientX - rect.left) / rect.width) * 100)); const seconds = (percent / 100) * clipDuration; const startInput = appRoot.querySelector("[data-action='trim-start']"); const endInput = appRoot.querySelector("[data-action='trim-end']"); if (draggingHandle === "start" && startInput && endInput) { const newStart = Math.min(seconds, parseTimestamp(endInput.value) - 1); startInput.value = formatDuration(Math.max(0, newStart)); } else if (draggingHandle === "end" && startInput && endInput) { const newEnd = Math.max(seconds, parseTimestamp(startInput.value) + 1); endInput.value = formatDuration(Math.min(clipDuration, newEnd)); } updateHandlePositions(); }; const onMouseUp = () => { if (draggingHandle) { draggingHandle = null; document.body.style.cursor = ""; document.body.style.userSelect = ""; } }; handleStart.addEventListener("mousedown", (e) => { e.stopPropagation(); startDrag("start"); }); handleEnd.addEventListener("mousedown", (e) => { e.stopPropagation(); startDrag("end"); }); timelineTrack.addEventListener("mousedown", (e) => { const rect = timelineTrack.getBoundingClientRect(); const percent = ((e.clientX - rect.left) / rect.width) * 100; const seconds = (percent / 100) * clipDuration; const startInput = appRoot.querySelector("[data-action='trim-start']"); const endInput = appRoot.querySelector("[data-action='trim-end']"); if (startInput && endInput) { const startVal = parseTimestamp(startInput.value); const endVal = parseTimestamp(endInput.value); const midPoint = (startVal + endVal) / 2; if (seconds < midPoint) { startInput.value = formatDuration(Math.max(0, seconds)); } else { endInput.value = formatDuration(Math.min(clipDuration, seconds)); } updateHandlePositions(); } }); document.addEventListener("mousemove", onMouseMove); document.addEventListener("mouseup", onMouseUp); // Keyboard support for handles [handleStart, handleEnd].forEach((handle, idx) => { handle.addEventListener("keydown", (e) => { const startInput = appRoot.querySelector("[data-action='trim-start']"); const endInput = appRoot.querySelector("[data-action='trim-end']"); if (!startInput || !endInput) return; const step = 5; // 5 seconds let changed = false; if (e.key === "ArrowRight") { if (idx === 0) { // start handle const newVal = Math.min(parseTimestamp(startInput.value) + step, parseTimestamp(endInput.value) - 1); startInput.value = formatDuration(newVal); changed = true; } else { // end handle const newVal = Math.min(parseTimestamp(endInput.value) + step, clipDuration); endInput.value = formatDuration(newVal); changed = true; } } else if (e.key === "ArrowLeft") { if (idx === 0) { // start handle const newVal = Math.max(parseTimestamp(startInput.value) - step, 0); startInput.value = formatDuration(newVal); changed = true; } else { // end handle const newVal = Math.max(parseTimestamp(endInput.value) - step, parseTimestamp(startInput.value) + 1); endInput.value = formatDuration(newVal); changed = true; } } if (changed) { e.preventDefault(); updateHandlePositions(); } }); }); // Sync input changes to timeline const startInput = appRoot.querySelector("[data-action='trim-start']"); const endInput = appRoot.querySelector("[data-action='trim-end']"); if (startInput) startInput.addEventListener("input", updateHandlePositions); if (endInput) endInput.addEventListener("input", updateHandlePositions); // Initial update updateHandlePositions(); } } async function saveClip() { state.recordingState = "Clipping"; render(); if (tauriInvoke) { try { const dto = await tauriInvoke("save_manual_clip", { seconds: state.replayBufferSeconds }); const clip = clipFromDto(dto); state.clips.unshift(clip); state.selectedClipId = clip.id; state.activeView = "Library"; state.recordingState = "Processing"; await refreshClips(); showNotice("Clip saved"); render(); return; } catch (error) { console.error("Could not save desktop clip", error); showNotice(`Could not save clip: ${String(error)}`); } } state.clips.unshift({ id: `manual-${Date.now()}`, title: "Manual clip", game: state.detectedGame, event: "Manual", source: "Manual Hotkey", duration: "1:00", createdAt: "Just now", uploadState: "Local only", path: "", thumbnailPath: null, videoUrl: null, thumbnailUrl: null, tags: ["manual"], colorClass: "manual", }); state.selectedClipId = state.clips[0].id; state.activeView = "Library"; render(); } async function toggleRecording() { if (tauriInvoke) { try { const status = await tauriInvoke(state.captureActive ? "stop_capture" : "start_capture"); applyDesktopStatus(status); await refreshClips(); showNotice(state.captureActive ? "Recording started" : "Recording stopped"); render(); return; } catch (error) { console.error("Could not toggle desktop recording", error); showNotice(`Could not toggle recording: ${String(error)}`); } } state.sessionRecording = !state.sessionRecording; state.recordingState = state.sessionRecording ? "RecordingSession" : "Buffering"; render(); } function applyDesktopStatus(status: DesktopStatus) { state.recordingState = status.recording_state; state.detectedGame = status.detected_game ?? "Waiting for game"; state.replayBufferSeconds = status.replay_buffer_seconds; state.systemAudioEnabled = status.system_audio_enabled; state.micEnabled = status.mic_enabled; state.micDevice = status.mic_device ?? ""; state.autoRecordEnabled = status.auto_record_enabled; state.autoUpload = status.upload_enabled; state.uploadProvider = status.upload_provider; state.catboxUserhash = status.catbox_userhash ?? ""; state.litterboxExpiryHours = validLitterboxExpiry(status.litterbox_expiry_hours); state.customUploadEndpoint = status.custom_upload_endpoint ?? ""; state.customUploadResponsePath = status.custom_upload_response_url_path; state.customUploadHeaders = status.custom_upload_headers.join("\n"); state.sessionRecording = status.session_recording; state.captureActive = status.capture_active; state.captureBackend = status.capture_backend; state.capturePath = status.capture_path; state.ffmpegAvailable = status.ffmpeg_available; state.ffmpegPath = status.ffmpeg_path; state.systemAudioAvailable = status.system_audio_available; state.desktopDuplicationAvailable = status.desktop_duplication_available; for (const event of state.autoEvents) { const enabled = status.auto_clip_enabled_events.find( (candidate) => candidate.game_id === event.gameId && candidate.event_type === event.eventType, ); if (enabled) { event.enabled = enabled.enabled; } } state.hotkeyClipLast60s = status.hotkey_clip_last_60s; state.hotkeyClipLast30s = status.hotkey_clip_last_30s; state.hotkeyToggleRecording = status.hotkey_toggle_session_recording; state.hotkeyScreenshot = status.hotkey_screenshot; state.freeDiskGb = status.free_disk_gb; state.captureFps = status.capture_fps; state.captureBitrateKbps = status.capture_bitrate_kbps; state.captureResolution = status.capture_resolution; state.storageLimitGb = status.storage_limit_gb; state.excludedWindowTitles = status.excluded_window_titles ?? []; state.excludedWindowText = (status.excluded_window_titles ?? []).join(", "); state.separateAudioTracks = status.separate_audio_tracks ?? false; state.appVersion = status.app_version ?? state.appVersion; state.gameQualityOverrides = status.game_quality_overrides ?? []; state.effectiveQualityApplied = status.effective_quality_applied ?? false; if (typeof status.onboarding_complete === "boolean") { state.onboardingComplete = status.onboarding_complete; } } async function trimSelectedClip() { if (!tauriInvoke) { return; } const clip = state.clips.find((candidate) => candidate.id === state.selectedClipId); if (!clip) { return; } const startInput = appRoot.querySelector("[data-action='trim-start']"); const endInput = appRoot.querySelector("[data-action='trim-end']"); const startSeconds = parseTimestamp(startInput?.value ?? "0"); const endSeconds = parseTimestamp(endInput?.value ?? clip.duration); try { const dto = await tauriInvoke("trim_clip", { clipId: clip.id, startSeconds, endSeconds, }); const trimmed = clipFromDto(dto); state.clips.unshift(trimmed); state.selectedClipId = trimmed.id; await refreshClips(); showNotice("Trimmed clip created"); render(); } catch (error) { console.error("Could not trim clip", error); showNotice(`Could not trim clip: ${String(error)}`); } } async function saveSelectedClipMetadata() { if (!tauriInvoke || !state.selectedClipId) { return; } const title = appRoot.querySelector("[data-action='clip-title']")?.value ?? ""; const tags = (appRoot.querySelector("[data-action='clip-tags']")?.value ?? "") .split(",") .map((tag) => tag.trim()) .filter((tag) => tag.length > 0); try { const dto = await tauriInvoke("update_clip_metadata", { clipId: state.selectedClipId, title, tags, }); const updated = clipFromDto(dto); state.clips = state.clips.map((clip) => (clip.id === updated.id ? updated : clip)); showNotice("Clip info saved"); render(); } catch (error) { console.error("Could not save clip info", error); showNotice(`Could not save clip info: ${String(error)}`); } } async function revealSelectedClip() { if (!tauriInvoke || !state.selectedClipId) { return; } try { await tauriInvoke("reveal_clip", { clipId: state.selectedClipId }); } catch (error) { console.error("Could not reveal clip", error); showNotice(`Could not reveal clip: ${String(error)}`); } } async function revealScreenshot(path: string) { try { await window.__TAURI__?.core?.invoke?.("reveal_screenshot", { path }); } catch (error) { console.error("Could not reveal screenshot", error); showNotice(`Could not reveal screenshot: ${String(error)}`); } } async function revealCrashLogs() { try { await window.__TAURI__?.core?.invoke?.("reveal_crash_logs"); } catch (error) { console.error("Could not reveal crash logs", error); showNotice(`Could not reveal crash logs: ${String(error)}`); } } async function uploadSelectedClip() { if (!tauriInvoke || !state.selectedClipId) { return; } try { const dto = await tauriInvoke("upload_clip", { clipId: state.selectedClipId, provider: state.uploadProvider, customEndpoint: state.customUploadEndpoint, customResponseUrlPath: state.customUploadResponsePath, }); const updated = clipFromDto(dto); state.clips = state.clips.map((clip) => (clip.id === updated.id ? updated : clip)); await refreshUploadHistory(); showNotice("Clip uploaded"); render(); } catch (error) { console.error("Could not queue upload", error); showNotice(`Could not upload clip: ${String(error)}`); } } async function exportSelectedClip() { if (!tauriInvoke || !state.selectedClipId) { return; } try { const path = await tauriInvoke("export_clip_copy", { clipId: state.selectedClipId }); showNotice(`Exported to ${path}`); render(); } catch (error) { console.error("Could not export clip", error); showNotice(`Could not export clip: ${String(error)}`); } } async function writeGsiConfigs() { if (!tauriInvoke) { return; } try { const configs = await tauriInvoke("write_gsi_configs"); state.gsiConfigStatus = configs.map((config) => `${config.game_id}: ${config.path}`).join(" · "); showNotice("GSI configs written"); render(); } catch (error) { state.gsiConfigStatus = `Could not write GSI configs: ${String(error)}`; render(); } } async function deleteSelectedClip() { if (!tauriInvoke || !state.selectedClipId) { return; } try { const clips = await tauriInvoke("delete_clip", { clipId: state.selectedClipId }); state.clips = clips.map(clipFromDto); state.selectedClipId = state.clips[0]?.id ?? ""; showNotice("Clip deleted"); render(); } catch (error) { console.error("Could not delete clip", error); showNotice(`Could not delete clip: ${String(error)}`); } } async function refreshClips() { if (!tauriInvoke) { return; } const clips = await tauriInvoke("list_clips"); state.clips = clips.map(clipFromDto); if (!state.clips.some((clip) => clip.id === state.selectedClipId)) { state.selectedClipId = state.clips[0]?.id ?? ""; } } async function saveReplayBufferSetting(seconds: number) { if (!tauriInvoke) { return; } try { const status = await tauriInvoke("set_replay_buffer", { seconds }); applyDesktopStatus(status); render(); } catch (error) { console.warn("Could not save replay buffer setting", error); } } async function saveMicSetting(enabled: boolean) { if (!tauriInvoke) { return; } try { const status = await tauriInvoke("set_mic_enabled", { enabled }); applyDesktopStatus(status); render(); } catch (error) { console.warn("Could not save mic setting", error); } } async function saveSystemAudioSetting(enabled: boolean) { if (!tauriInvoke) { return; } try { const status = await tauriInvoke("set_system_audio_enabled", { enabled }); applyDesktopStatus(status); render(); } catch (error) { console.warn("Could not save system audio setting", error); } } async function saveMicDevice(device: string) { if (!tauriInvoke) { return; } try { const status = await tauriInvoke("set_mic_device", { device: device || null }); applyDesktopStatus(status); render(); } catch (error) { console.warn("Could not save mic device", error); } } async function saveAutoRecordSetting(enabled: boolean) { if (!tauriInvoke) { return; } try { const status = await tauriInvoke("set_auto_record_enabled", { enabled }); applyDesktopStatus(status); render(); } catch (error) { console.warn("Could not save auto-record setting", error); } } async function refreshStatus() { if (!tauriInvoke) { return; } try { const status = await tauriInvoke("refresh_detected_game"); applyDesktopStatus(status); render(); } catch (error) { console.warn("Could not refresh detected game", error); } } async function refreshAudioDevices() { if (!tauriInvoke) { return; } try { state.audioDevices = await tauriInvoke("list_audio_devices"); render(); } catch (error) { console.warn("Could not load audio devices", error); } } async function pollAutoClips() { if (!tauriInvoke || !state.captureActive) { return; } try { const clips = await tauriInvoke("poll_auto_clip_events"); if (clips.length === 0) { return; } const created = clips.map(clipFromDto); state.clips = [...created, ...state.clips.filter((clip) => !created.some((fresh) => fresh.id === clip.id))]; state.selectedClipId = created[0].id; state.activeView = "Library"; render(); } catch (error) { console.warn("Could not poll auto clips", error); } } async function saveUploadSettings() { if (!tauriInvoke) { return; } try { const status = await tauriInvoke("set_upload_settings", { autoUploadEnabled: state.autoUpload, provider: state.uploadProvider, catboxUserhash: state.catboxUserhash || null, litterboxExpiryHours: state.litterboxExpiryHours, customEndpoint: state.customUploadEndpoint || null, customResponseUrlPath: state.customUploadResponsePath, customHeaders: state.customUploadHeaders .split("\n") .map((line) => line.trim()) .filter((line) => line.length > 0), }); applyDesktopStatus(status); showNotice("Upload settings saved"); render(); } catch (error) { console.warn("Could not save upload settings", error); showNotice(`Could not save upload settings: ${String(error)}`); } } async function saveAutoClipEventSetting(eventRule: AutoEvent) { if (!tauriInvoke) { return; } try { const status = await tauriInvoke("set_auto_clip_event_enabled", { gameId: eventRule.gameId, eventType: eventRule.eventType, enabled: eventRule.enabled, }); applyDesktopStatus(status); showNotice("Auto-clip rule saved"); render(); } catch (error) { console.warn("Could not save auto-clip rule", error); showNotice(`Could not save auto-clip rule: ${String(error)}`); } } async function saveHotkeys() { if (!tauriInvoke) { return; } try { const status = await tauriInvoke("set_hotkeys", { clip_last_60s: state.hotkeyClipLast60s, clip_last_30s: state.hotkeyClipLast30s, toggle_session_recording: state.hotkeyToggleRecording, screenshot: state.hotkeyScreenshot, }); applyDesktopStatus(status); showNotice("Hotkeys saved"); render(); } catch (error) { console.warn("Could not save hotkeys", error); showNotice(`Could not save hotkeys: ${String(error)}`); } } async function saveCaptureSettings() { if (!tauriInvoke) { return; } const [width, height] = parseResolution(state.captureResolution); const excludedWindowTitles = state.excludedWindowText .split(",") .map((title) => title.trim()) .filter((title) => title.length > 0); try { const status = await tauriInvoke("set_capture_settings", { width, height, fps: state.captureFps, bitrateKbps: state.captureBitrateKbps, storageLimitGb: state.storageLimitGb, excludedWindowTitles, separateAudioTracks: state.separateAudioTracks, }); applyDesktopStatus(status); showNotice("Capture settings saved. They will apply the next time capture starts."); render(); } catch (error) { console.warn("Could not save capture settings", error); showNotice(`Could not save capture settings: ${String(error)}`); } } function parseResolution(value: string): [number, number] { const [width, height] = value.split("x").map((part) => Number(part)); return [ Number.isFinite(width) ? width : 1280, Number.isFinite(height) ? height : 720, ]; } async function saveGameQualityOverride() { if (!tauriInvoke) { return; } if (state.detectedGame === "Waiting for game") { return; } const preset = appRoot.querySelector("[data-action='override-preset']")?.value ?? "1280x720"; const fps = Number(appRoot.querySelector("[data-action='override-fps']")?.value ?? 30); const bitrate = Number(appRoot.querySelector("[data-action='override-bitrate']")?.value ?? 6000); const [width, height] = parseResolution(preset); try { const status = await tauriInvoke("set_game_quality_override", { gameId: state.detectedGame, name: `${preset} ${fps}fps`, width, height, fps, bitrateKbps: bitrate, }); applyDesktopStatus(status); showNotice(`Quality override saved for ${state.detectedGame}.`); render(); } catch (error) { console.warn("Could not save quality override", error); showNotice(`Could not save quality override: ${String(error)}`); } } async function clearGameQualityOverride() { if (!tauriInvoke) { return; } if (state.detectedGame === "Waiting for game") { return; } try { const status = await tauriInvoke("clear_game_quality_override", { gameId: state.detectedGame, }); applyDesktopStatus(status); showNotice(`Quality override cleared for ${state.detectedGame}.`); render(); } catch (error) { console.warn("Could not clear quality override", error); showNotice(`Could not clear quality override: ${String(error)}`); } } async function finishOnboarding() { if (!tauriInvoke) { state.onboardingComplete = true; render(); return; } const systemAudio = document .querySelector("[data-action='onboard-system-audio']")?.checked ?? state.systemAudioEnabled; const mic = document .querySelector("[data-action='onboard-mic']")?.checked ?? state.micEnabled; const separate = document .querySelector("[data-action='onboard-separate-tracks']")?.checked ?? state.separateAudioTracks; const autoRecord = document .querySelector("[data-action='onboard-auto-record']")?.checked ?? state.autoRecordEnabled; const buffer = Number( document.querySelector("[data-action='onboard-buffer']")?.value ?? state.replayBufferSeconds, ); const storage = Number( document.querySelector("[data-action='onboard-storage']")?.value ?? state.storageLimitGb, ); try { const status = await tauriInvoke("finish_onboarding", { systemAudioEnabled: systemAudio, micEnabled: mic, separateAudioTracks: separate, autoRecordEnabled: autoRecord, replayBufferSeconds: buffer, storageLimitGb: storage, }); applyDesktopStatus(status); state.onboardingStep = 0; render(); } catch (error) { console.warn("Could not finish onboarding", error); showNotice(`Could not finish setup: ${String(error)}`); } } async function skipOnboarding() { if (!tauriInvoke) { state.onboardingComplete = true; render(); return; } try { const status = await tauriInvoke("finish_onboarding", {}); applyDesktopStatus(status); state.onboardingStep = 0; render(); } catch (error) { console.warn("Could not skip onboarding", error); showNotice(`Could not skip setup: ${String(error)}`); } } async function checkForUpdates() { if (!tauriInvoke) { return; } state.update.applying = true; state.update.message = "Checking for updates…"; render(); try { const info = await tauriInvoke<{ update_available: boolean; latest_version: string; installer_file: string | null; download_url: string | null; message: string; }>("check_for_updates"); state.update.checked = true; state.update.updateAvailable = info.update_available; state.update.latestVersion = info.latest_version; state.update.installerFile = info.installer_file ?? ""; state.update.downloadUrl = info.download_url ?? ""; state.update.message = info.message; } catch (error) { console.warn("Could not check for updates", error); state.update.message = `Could not check for updates: ${String(error)}`; } state.update.applying = false; render(); } async function downloadUpdate() { if (!tauriInvoke || !state.update.downloadUrl || !state.update.installerFile) { return; } state.update.applying = true; state.update.message = "Downloading update…"; render(); try { const message = await tauriInvoke("download_and_apply_update", { downloadUrl: state.update.downloadUrl, installerFile: state.update.installerFile, }); showNotice(message); } catch (error) { console.warn("Could not download the update", error); state.update.applying = false; state.update.message = `Could not download the update: ${String(error)}`; render(); } } async function takeScreenshot() { if (!tauriInvoke) { return; } state.recordingState = "Processing"; render(); try { await tauriInvoke("take_screenshot"); await refreshScreenshots(); showNotice("Screenshot saved"); render(); } catch (error) { console.error("Could not take screenshot", error); showNotice(`Could not take screenshot: ${String(error)}`); render(); } } async function listScreenshots() { if (!tauriInvoke) { return []; } try { return await tauriInvoke("list_screenshots"); } catch (error) { console.warn("Could not list screenshots", error); return []; } } async function refreshScreenshots() { const screenshots = await listScreenshots(); state.screenshots = screenshots; } async function refreshUploadHistory() { if (!tauriInvoke) return; try { state.uploadHistory = await tauriInvoke("list_upload_history"); } catch (error) { console.warn("Could not load upload history", error); } } async function retryUpload(entry: UploadHistoryEntry) { if (!tauriInvoke) return; const clip = state.clips.find((c) => c.id === entry.clip_id); if (!clip) { showNotice(`Clip ${entry.clip_id} not found in library`); return; } state.selectedClipId = clip.id; state.activeView = "Library"; render(); await uploadSelectedClip(); } function filteredClips() { const query = state.libraryQuery.trim().toLowerCase(); return state.clips.filter((clip) => { const matchesFilter = state.libraryFilter === "all" || (state.libraryFilter === "kills" && clip.event.toLowerCase().includes("kill")) || (state.libraryFilter === "wins" && clip.event.toLowerCase().includes("win")) || (state.libraryFilter === "uploaded" && clip.uploadState === "Uploaded") || (state.libraryFilter === "failed" && clip.uploadState === "Failed"); if (!matchesFilter) { return false; } if (!query) { return true; } return [clip.title, clip.game, clip.event, clip.source, clip.uploadState, clip.path, ...clip.tags] .join(" ") .toLowerCase() .includes(query); }); } function validLitterboxExpiry(value: number): AppState["litterboxExpiryHours"] { return value === 1 || value === 12 || value === 24 || value === 72 ? value : 24; } function showNotice(message: string) { state.notice = message; window.setTimeout(() => { if (state.notice === message) { state.notice = ""; render(); } }, 5_000); } function parseTimestamp(value: string) { const parts = value.trim().split(":").map(Number); if (parts.some((part) => Number.isNaN(part))) { return 0; } if (parts.length === 1) { return parts[0]; } if (parts.length === 2) { return parts[0] * 60 + parts[1]; } return parts[0] * 3600 + parts[1] * 60 + parts[2]; } function formatDuration(seconds: number): string { const hrs = Math.floor(seconds / 3600); const mins = Math.floor((seconds % 3600) / 60); const secs = Math.floor(seconds % 60); if (hrs > 0) { return `${hrs}:${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`; } return `${mins}:${secs.toString().padStart(2, "0")}`; } function escapeHtml(value: string) { return value .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """); } async function loadDesktopBridge() { const hasTauri = "__TAURI_INTERNALS__" in window; if (!hasTauri) { return; } try { tauriInvoke = window.__TAURI__?.core?.invoke ?? null; if (!tauriInvoke) { return; } const invoke = tauriInvoke; const status = await invoke("get_status"); applyDesktopStatus(status); const clips = await invoke("list_clips"); state.clips = clips.map(clipFromDto); state.selectedClipId = state.clips[0]?.id ?? ""; await refreshScreenshots(); await refreshUploadHistory(); render(); await refreshAudioDevices(); window.setInterval(() => { void refreshStatus(); }, 3_000); window.setInterval(() => { void pollAutoClips(); }, 2_000); } catch (error) { console.warn("Tauri bridge unavailable", error); } } render(); void loadDesktopBridge();