import { convertFileSrc } from "@tauri-apps/api/core"; type RecordingState = | "WaitingForGame" | "Buffering" | "RecordingSession" | "Clipping" | "Processing" | "StorageLow"; type ClipSource = "Auto Event" | "Manual Hotkey" | "Bookmark" | "Imported"; 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; }; 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 GsiConfigDto = { game_id: string; path: string; }; type AudioDeviceDto = { name: string; kind: "input" | "system_loopback"; }; 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[]; autoEvents: AutoEvent[]; hotkeyClipLast60s: string; hotkeyClipLast30s: string; hotkeyToggleRecording: string; hotkeyScreenshot: string; }; 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: [], 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", }; const root = document.querySelector("#app"); if (!root) { throw new Error("Missing #app root"); } const appRoot = root; function render() { 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 renderRecordingBar() { const statusText = state.captureActive ? "Recording to disk" : state.sessionRecording ? "Recording session" : `${state.recordingState} ${state.replayBufferSeconds}s`; return `

Detected game

${state.detectedGame}

${statusText}
`; } 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
`}
${renderClipDetails(selectedClip)}
`; } 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() { return `

Replay buffer

${state.replayBufferSeconds} seconds

Capture

720p30 Performance

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"}

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

`; } function renderSettingsView() { return `

Privacy

Local-first

Storage

50 GB cap

Old temporary buffer segments are removed automatically; saved clips are kept.

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='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(); }); // 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", clientX: number) => { 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", e.clientX); }); handleEnd.addEventListener("mousedown", (e) => { e.stopPropagation(); startDrag("end", e.clientX); }); 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; } 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 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)); 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)}`); } } 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 ?? ""; 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();