feat(kon): scaffold hybrid modular workspace

- Cargo workspace with 6 domain crates: core, audio, transcription, ai-formatting, storage, cloud-providers
- Minimal Tauri shell (lib.rs + main.rs) with plugin registration
- Svelte 5 frontend copied from Ramble v0.2
- All crates compile as empty stubs
- App identifier: uk.co.corbel.kon

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
jake
2026-03-16 20:21:38 +00:00
commit 9926a42b7a
80 changed files with 13328 additions and 0 deletions

5
src/routes/+layout.js Normal file
View File

@@ -0,0 +1,5 @@
// Tauri doesn't have a Node.js server to do proper SSR
// so we use adapter-static with a fallback to index.html to put the site in SPA mode
// See: https://svelte.dev/docs/kit/single-page-apps
// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info
export const ssr = false;

98
src/routes/+layout.svelte Normal file
View File

@@ -0,0 +1,98 @@
<script>
import "../app.css";
import { onDestroy } from "svelte";
import Sidebar from "$lib/Sidebar.svelte";
import TaskSidebar from "$lib/components/TaskSidebar.svelte";
import Titlebar from "$lib/components/Titlebar.svelte";
import { page, settings } from "$lib/stores/page.svelte.js";
let { children } = $props();
// Recording indicator dot (follows mouse)
let mouseX = $state(0);
let mouseY = $state(0);
function handleMouseMove(e) {
mouseX = e.clientX;
mouseY = e.clientY;
}
// Theme application
$effect(() => {
const theme = settings.theme;
if (theme === "Light") {
document.documentElement.classList.add("light");
return;
}
if (theme === "Dark") {
document.documentElement.classList.remove("light");
return;
}
// System mode
const mq = window.matchMedia("(prefers-color-scheme: light)");
const apply = () => document.documentElement.classList.toggle("light", mq.matches);
apply();
mq.addEventListener("change", apply);
return () => mq.removeEventListener("change", apply);
});
// Global hotkey registration
let registeredHotkey = null;
async function registerGlobalHotkey(hotkey) {
try {
const mod = await import("@tauri-apps/plugin-global-shortcut");
if (registeredHotkey) {
await mod.unregister(registeredHotkey).catch(() => {});
}
await mod.register(hotkey, () => {
if (page.current !== "dictation") page.current = "dictation";
requestAnimationFrame(() => {
window.dispatchEvent(new CustomEvent("ramble:toggle-recording"));
});
});
registeredHotkey = hotkey;
} catch (err) {
console.error("Hotkey registration failed:", err);
}
}
$effect(() => {
registerGlobalHotkey(settings.globalHotkey);
});
// Apply font size setting as CSS variable
$effect(() => {
document.documentElement.style.setProperty("--font-size-transcript", `${settings.fontSize}px`);
});
onDestroy(() => {
if (registeredHotkey) {
import("@tauri-apps/plugin-global-shortcut")
.then((mod) => mod.unregister(registeredHotkey))
.catch(() => {});
}
});
</script>
<svelte:window onmousemove={handleMouseMove} />
{#if page.recording}
<div
class="fixed w-3 h-3 rounded-full bg-danger animate-pulse-soft pointer-events-none"
style="left: {mouseX + 18}px; top: {mouseY + 18}px; z-index: 100;"
></div>
{/if}
<div class="flex flex-col h-screen w-screen overflow-hidden grain">
<Titlebar />
<div class="flex flex-1 min-h-0">
<Sidebar />
<div class="flex-1 overflow-hidden bg-bg">
{@render children()}
</div>
{#if page.taskSidebarOpen}
<TaskSidebar />
{/if}
</div>
</div>

29
src/routes/+page.svelte Normal file
View File

@@ -0,0 +1,29 @@
<script>
import { page } from "$lib/stores/page.svelte.js";
import DictationPage from "$lib/pages/DictationPage.svelte";
import FilesPage from "$lib/pages/FilesPage.svelte";
import TasksPage from "$lib/pages/TasksPage.svelte";
import HistoryPage from "$lib/pages/HistoryPage.svelte";
import SettingsPage from "$lib/pages/SettingsPage.svelte";
// Redirect legacy "profiles" page to settings
$effect(() => {
if (page.current === "profiles") page.current = "settings";
});
</script>
<div class="h-full overflow-hidden">
{#key page.current}
{#if page.current === "dictation"}
<DictationPage />
{:else if page.current === "files"}
<FilesPage />
{:else if page.current === "tasks"}
<TasksPage />
{:else if page.current === "history"}
<HistoryPage />
{:else if page.current === "settings"}
<SettingsPage />
{/if}
{/key}
</div>

View File

@@ -0,0 +1,71 @@
<script>
import "../../app.css";
import { onMount, onDestroy } from "svelte";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { settings } from "$lib/stores/page.svelte.js";
let { children } = $props();
let glowing = $state(false);
let unlistenFocus = null;
let quickAddEl = $state(null);
// Theme application (float window has its own DOM)
$effect(() => {
const theme = settings.theme;
if (theme === "Light") {
document.documentElement.classList.add("light");
return;
}
if (theme === "Dark") {
document.documentElement.classList.remove("light");
return;
}
// System mode
const mq = window.matchMedia("(prefers-color-scheme: light)");
const apply = () => document.documentElement.classList.toggle("light", mq.matches);
apply();
mq.addEventListener("change", apply);
return () => mq.removeEventListener("change", apply);
});
// Listen for settings changes from main window
if (typeof window !== "undefined") {
window.addEventListener("storage", (e) => {
if (e.key === "ramble_settings" && e.newValue) {
try {
Object.assign(settings, JSON.parse(e.newValue));
} catch {}
}
});
}
onMount(async () => {
try {
unlistenFocus = await listen("task-window-focus", () => {
glowing = true;
setTimeout(() => { glowing = false; }, 700);
// Auto-focus quick-add input
const input = document.querySelector("[data-quick-add]");
if (input) input.focus();
});
} catch {}
});
onDestroy(() => {
if (unlistenFocus) unlistenFocus();
});
// Escape to close
function handleKeydown(e) {
if (e.key === "Escape") {
getCurrentWindow().close();
}
}
</script>
<svelte:window onkeydown={handleKeydown} />
<div class="h-screen w-screen overflow-hidden grain rounded-lg border border-border shadow-xl animate-float-enter {glowing ? 'animate-glow-pulse' : ''}">
{@render children()}
</div>

View File

@@ -0,0 +1,460 @@
<script>
import { getCurrentWindow } from "@tauri-apps/api/window";
import {
tasks, addTask, completeTask, uncompleteTask, deleteTask,
taskLists, addTaskList, renameTaskList, deleteTaskList, moveTaskList, sortTaskLists,
moveTaskToList, moveTaskListToProfile, profiles,
} from "$lib/stores/page.svelte.js";
let quickInput = $state("");
let pinned = $state(true);
let activeListId = $state("all");
let showCompleted = $state(false);
let newListName = $state("");
let showNewList = $state(false);
let contextMenuListId = $state(null);
let editingListId = $state(null);
let editingName = $state("");
let showSortMenu = $state(false);
let draggingTaskId = $state(null);
let dropHighlightId = $state(null);
// Filtered tasks for active list
let tasksForActiveList = $derived.by(() => {
const active = tasks.filter((t) => !t.done);
if (activeListId === "all") return active;
if (activeListId === "inbox") return active.filter((t) => !t.listId);
return active.filter((t) => t.listId === activeListId);
});
let completedForActiveList = $derived.by(() => {
const done = tasks.filter((t) => t.done);
if (activeListId === "all") return done.slice(0, 10);
if (activeListId === "inbox") return done.filter((t) => !t.listId).slice(0, 10);
return done.filter((t) => t.listId === activeListId).slice(0, 10);
});
function countForList(listId) {
if (listId === "all") return tasks.filter((t) => !t.done).length;
if (listId === "inbox") return tasks.filter((t) => !t.done && !t.listId).length;
return tasks.filter((t) => !t.done && t.listId === listId).length;
}
let activeListName = $derived(
taskLists.find((l) => l.id === activeListId)?.name || "Tasks"
);
// Split lists into built-in and custom for section divider
let builtInLists = $derived(taskLists.filter((l) => l.builtIn));
let customLists = $derived(taskLists.filter((l) => !l.builtIn));
function handleQuickAdd(e) {
if (e.key === "Enter" && quickInput.trim()) {
const listId = (activeListId === "all" || activeListId === "inbox") ? null : activeListId;
addTask({ text: quickInput.trim(), bucket: "inbox", listId });
quickInput = "";
}
}
function handleDragStart(e) {
if (e.button !== 0) return;
if (e.target.closest("button")) return;
if (e.target.closest("input")) return;
getCurrentWindow().startDragging();
}
async function togglePin() {
pinned = !pinned;
await getCurrentWindow().setAlwaysOnTop(pinned);
}
function closeWindow() {
getCurrentWindow().close();
}
// List management
function handleCreateList(e) {
if (e.key === "Enter" && newListName.trim()) {
addTaskList(newListName.trim());
newListName = "";
showNewList = false;
}
if (e.key === "Escape") {
showNewList = false;
newListName = "";
}
}
function startRenaming(list) {
editingListId = list.id;
editingName = list.name;
contextMenuListId = null;
}
function finishRenaming() {
if (editingListId && editingName.trim()) {
renameTaskList(editingListId, editingName.trim());
}
editingListId = null;
editingName = "";
}
function handleRenameKey(e) {
if (e.key === "Enter") finishRenaming();
if (e.key === "Escape") { editingListId = null; editingName = ""; }
}
function handleDeleteList(id) {
if (activeListId === id) activeListId = "all";
deleteTaskList(id);
contextMenuListId = null;
}
function toggleContextMenu(e, listId) {
e.preventDefault();
e.stopPropagation();
contextMenuListId = contextMenuListId === listId ? null : listId;
}
// Drag-and-drop: tasks between lists
function handleTaskDragStart(e, taskId) {
draggingTaskId = taskId;
e.dataTransfer.setData("text/plain", taskId);
e.dataTransfer.effectAllowed = "move";
}
function handleTaskDragEnd() {
draggingTaskId = null;
dropHighlightId = null;
}
function handleListDragOver(e) {
e.preventDefault();
e.dataTransfer.dropEffect = "move";
}
function handleListDragEnter(e, listId) {
e.preventDefault();
dropHighlightId = listId;
}
function handleListDragLeave(e, listId) {
if (dropHighlightId === listId) dropHighlightId = null;
}
function handleListDrop(e, listId) {
e.preventDefault();
dropHighlightId = null;
const taskId = e.dataTransfer.getData("text/plain");
if (taskId) {
moveTaskToList(taskId, listId);
}
}
// Close context menu on outside click
function handleWindowClick() {
if (contextMenuListId) contextMenuListId = null;
if (showSortMenu) showSortMenu = false;
}
</script>
<svelte:window onclick={handleWindowClick} />
<div class="flex flex-col h-full bg-bg">
<!-- Drag handle with title -->
<div
class="flex items-center h-[36px] bg-bg-elevated select-none px-3"
onmousedown={handleDragStart}
data-tauri-drag-region
>
<span class="text-[12px] font-medium text-text-secondary tracking-wide" data-tauri-drag-region>
Ramble - To-do
</span>
<div class="flex-1" data-tauri-drag-region></div>
<!-- Pin button -->
<button
class="w-7 h-7 flex items-center justify-center rounded-md
{pinned ? 'bg-accent/15 text-accent' : 'text-text-tertiary hover:bg-hover hover:text-text-secondary'}"
onclick={togglePin}
title={pinned ? "Pinned on top (click to unpin)" : "Pin on top"}
>
{#if pinned}
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
<path d="M16 12V4h1V2H7v2h1v8l-2 2v2h5.2v6h1.6v-6H18v-2l-2-2Z" />
</svg>
{:else}
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M16 12V4h1V2H7v2h1v8l-2 2v2h5.2v6h1.6v-6H18v-2l-2-2Z" />
</svg>
{/if}
</button>
<!-- Close button -->
<button
class="w-7 h-7 flex items-center justify-center text-text-tertiary hover:text-danger rounded-md hover:bg-hover ml-1"
onclick={closeWindow}
aria-label="Close"
>
<svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
<path d="M18 6L6 18M6 6l12 12" stroke-linecap="round" />
</svg>
</button>
</div>
<!-- Single-column content -->
<div class="flex flex-col flex-1 min-h-0">
<!-- List selector pills -->
<div class="flex items-center gap-1 px-3 py-2 border-b border-border-subtle overflow-x-auto">
{#each builtInLists as list (list.id)}
<button
class="flex items-center gap-1 px-2.5 py-1 rounded-lg text-[11px] whitespace-nowrap flex-shrink-0
{activeListId === list.id
? 'bg-nav-active text-text font-medium'
: 'text-text-secondary hover:bg-hover hover:text-text'}
{dropHighlightId === list.id ? 'ring-1 ring-accent scale-105' : ''}"
onclick={() => { activeListId = list.id; contextMenuListId = null; }}
ondragover={handleListDragOver}
ondragenter={(e) => handleListDragEnter(e, list.id)}
ondragleave={(e) => handleListDragLeave(e, list.id)}
ondrop={(e) => handleListDrop(e, list.id)}
>
{list.name}
{#if countForList(list.id) > 0}
<span class="text-[9px] px-1 rounded-full bg-bg-elevated text-text-tertiary">
{countForList(list.id)}
</span>
{/if}
</button>
{/each}
<!-- Divider between built-in and custom lists -->
{#if customLists.length > 0}
<span class="w-px h-4 bg-border-subtle flex-shrink-0"></span>
{/if}
{#each customLists as list (list.id)}
{#if editingListId === list.id}
<input
type="text"
class="bg-bg-input border border-accent rounded px-2 py-0.5 text-[11px] text-text
focus:outline-none w-[100px]"
bind:value={editingName}
onkeydown={handleRenameKey}
onblur={finishRenaming}
data-no-transition
autofocus
/>
{:else}
<div class="relative flex-shrink-0">
<button
class="flex items-center gap-1 px-2.5 py-1 rounded-lg text-[11px] whitespace-nowrap
{activeListId === list.id
? 'bg-nav-active text-text font-medium'
: 'text-text-secondary hover:bg-hover hover:text-text'}
{dropHighlightId === list.id ? 'ring-1 ring-accent scale-105' : ''}"
onclick={() => { activeListId = list.id; contextMenuListId = null; }}
ondblclick={() => startRenaming(list)}
oncontextmenu={(e) => toggleContextMenu(e, list.id)}
ondragover={handleListDragOver}
ondragenter={(e) => handleListDragEnter(e, list.id)}
ondragleave={(e) => handleListDragLeave(e, list.id)}
ondrop={(e) => handleListDrop(e, list.id)}
>
{#if list.profileId}
<svg class="w-2.5 h-2.5 text-text-tertiary" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 12a5 5 0 1 0 0-10 5 5 0 0 0 0 10Zm0 2c-5.33 0-8 2.67-8 4v2h16v-2c0-1.33-2.67-4-8-4Z" />
</svg>
{/if}
{list.name}
{#if countForList(list.id) > 0}
<span class="text-[9px] px-1 rounded-full bg-bg-elevated text-text-tertiary">
{countForList(list.id)}
</span>
{/if}
</button>
<!-- Context menu -->
{#if contextMenuListId === list.id}
<div class="absolute left-0 top-full mt-1 bg-bg-card border border-border rounded-lg shadow-lg py-1 z-20 animate-fade-in min-w-[120px]"
onclick={(e) => e.stopPropagation()}>
<button
class="w-full text-left px-3 py-1 text-[10px] text-text-secondary hover:bg-hover hover:text-text"
onclick={() => startRenaming(list)}
>Rename</button>
<button
class="w-full text-left px-3 py-1 text-[10px] text-text-secondary hover:bg-hover hover:text-text"
onclick={() => { moveTaskList(list.id, -1); contextMenuListId = null; }}
>Move left</button>
<button
class="w-full text-left px-3 py-1 text-[10px] text-text-secondary hover:bg-hover hover:text-text"
onclick={() => { moveTaskList(list.id, 1); contextMenuListId = null; }}
>Move right</button>
{#if profiles.length > 0}
<div class="my-1 h-px bg-border-subtle"></div>
<p class="px-3 py-0.5 text-[9px] text-text-tertiary uppercase tracking-wider">Move to profile</p>
{#each profiles as profile}
<button
class="w-full text-left px-3 py-1 text-[10px] hover:bg-hover
{list.profileId === profile.name ? 'text-accent' : 'text-text-secondary hover:text-text'}"
onclick={() => { moveTaskListToProfile(list.id, profile.name); contextMenuListId = null; }}
>{profile.name}</button>
{/each}
<button
class="w-full text-left px-3 py-1 text-[10px] text-text-secondary hover:bg-hover hover:text-text"
onclick={() => { moveTaskListToProfile(list.id, null); contextMenuListId = null; }}
>None (unlink)</button>
{/if}
<div class="my-1 h-px bg-border-subtle"></div>
<button
class="w-full text-left px-3 py-1 text-[10px] text-danger hover:bg-hover"
onclick={() => handleDeleteList(list.id)}
>Delete</button>
</div>
{/if}
</div>
{/if}
{/each}
<!-- New list button -->
{#if showNewList}
<input
type="text"
class="bg-bg-input border border-border rounded px-2 py-0.5 text-[10px] text-text
placeholder:text-text-tertiary focus:outline-none focus:border-accent w-[100px] flex-shrink-0"
placeholder="List name..."
bind:value={newListName}
onkeydown={handleCreateList}
onblur={() => { showNewList = false; newListName = ""; }}
data-no-transition
autofocus
/>
{:else}
<button
class="px-2 py-1 rounded-lg text-[11px] text-accent hover:bg-accent/10 whitespace-nowrap flex-shrink-0"
onclick={(e) => { e.stopPropagation(); showNewList = true; }}
>+</button>
{/if}
<!-- Sort -->
<div class="relative flex-shrink-0 ml-auto">
<button
class="px-1.5 py-1 rounded text-[10px] text-text-tertiary hover:text-text-secondary"
onclick={(e) => { e.stopPropagation(); showSortMenu = !showSortMenu; }}
>
<svg class="w-3 h-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M3 6h18M3 12h12M3 18h6" stroke-linecap="round" />
</svg>
</button>
{#if showSortMenu}
<div class="absolute right-0 top-full mt-1 bg-bg-card border border-border rounded-lg shadow-lg py-1 z-20 animate-fade-in min-w-[110px]"
onclick={(e) => e.stopPropagation()}>
<button
class="w-full text-left px-3 py-1 text-[10px] text-text-secondary hover:bg-hover hover:text-text"
onclick={() => { sortTaskLists("alpha"); showSortMenu = false; }}
>Alphabetical</button>
<button
class="w-full text-left px-3 py-1 text-[10px] text-text-secondary hover:bg-hover hover:text-text"
onclick={() => { sortTaskLists("date"); showSortMenu = false; }}
>By date created</button>
</div>
{/if}
</div>
</div>
<!-- Quick add (top — capture first) -->
<div class="px-3 py-2 border-b border-border-subtle">
<input
type="text"
class="w-full bg-bg-input border border-border rounded-lg px-3 py-2 text-[12px] text-text
placeholder:text-text-tertiary focus:outline-none focus:border-accent"
placeholder="Add task to {activeListName}..."
bind:value={quickInput}
onkeydown={handleQuickAdd}
data-no-transition
data-quick-add
/>
</div>
<!-- Tasks -->
<div class="flex-1 overflow-y-auto px-3 py-2 min-h-0">
{#if tasksForActiveList.length === 0}
<div class="flex flex-col items-center justify-center h-full opacity-60">
<p class="text-[11px] text-text-tertiary text-center">No active tasks</p>
<p class="text-[10px] text-text-tertiary mt-1">Type above or drag tasks here</p>
</div>
{:else}
<div class="flex flex-col gap-0.5">
{#each tasksForActiveList as task (task.id)}
<div
class="group flex items-start gap-2.5 px-2 py-2 rounded-lg hover:bg-hover cursor-grab active:cursor-grabbing
{draggingTaskId === task.id ? 'opacity-40' : ''}"
draggable="true"
ondragstart={(e) => handleTaskDragStart(e, task.id)}
ondragend={handleTaskDragEnd}
>
<button
class="mt-0.5 w-[18px] h-[18px] rounded-md border-2 border-border-subtle hover:border-accent flex-shrink-0
flex items-center justify-center"
onclick={() => completeTask(task.id)}
aria-label="Complete"
></button>
<div class="flex-1 min-w-0">
<p class="text-[12px] text-text leading-[1.4]">{task.text}</p>
{#if task.createdAt}
<p class="text-[10px] text-text-tertiary mt-0.5">
{new Date(task.createdAt).toLocaleDateString("en-GB", { day: "numeric", month: "short" })}
</p>
{/if}
</div>
<button
class="mt-0.5 text-text-tertiary hover:text-danger opacity-0 group-hover:opacity-100"
onclick={() => deleteTask(task.id)}
aria-label="Delete"
>
<svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 6L6 18M6 6l12 12" stroke-linecap="round" />
</svg>
</button>
</div>
{/each}
</div>
{/if}
<!-- Completed -->
{#if completedForActiveList.length > 0}
<div class="mt-3">
<button
class="flex items-center gap-1.5 text-[10px] text-text-tertiary hover:text-text-secondary mb-1.5"
onclick={() => showCompleted = !showCompleted}
>
<svg class="w-2.5 h-2.5 transition-transform {showCompleted ? 'rotate-90' : ''}" viewBox="0 0 24 24" fill="currentColor">
<path d="M8 5l8 7-8 7z" />
</svg>
Done ({completedForActiveList.length})
</button>
{#if showCompleted}
<div class="flex flex-col gap-0.5 animate-fade-in">
{#each completedForActiveList as task (task.id)}
<div class="group flex items-start gap-2.5 px-2 py-1.5 rounded-lg opacity-50 hover:opacity-70">
<button
class="mt-0.5 w-[18px] h-[18px] rounded-md border-2 border-accent bg-accent/20 flex-shrink-0
flex items-center justify-center animate-scale-pop"
onclick={() => uncompleteTask(task.id)}
aria-label="Uncomplete"
>
<svg class="w-3 h-3 text-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
<path d="M5 12l5 5L20 7" stroke-linecap="round" stroke-linejoin="round" />
</svg>
</button>
<p class="text-[12px] text-text-secondary line-through flex-1">{task.text}</p>
</div>
{/each}
</div>
{/if}
</div>
{/if}
</div>
</div>
</div>

View File

@@ -0,0 +1,48 @@
<script>
import "../../app.css";
import { onMount, onDestroy } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { settings } from "$lib/stores/page.svelte.js";
let { children } = $props();
// Theme application (viewer window has its own DOM)
$effect(() => {
const theme = settings.theme;
if (theme === "Light") {
document.documentElement.classList.add("light");
return;
}
if (theme === "Dark") {
document.documentElement.classList.remove("light");
return;
}
const mq = window.matchMedia("(prefers-color-scheme: light)");
const apply = () => document.documentElement.classList.toggle("light", mq.matches);
apply();
mq.addEventListener("change", apply);
return () => mq.removeEventListener("change", apply);
});
// Sync settings from main window
if (typeof window !== "undefined") {
window.addEventListener("storage", (e) => {
if (e.key === "ramble_settings" && e.newValue) {
try { Object.assign(settings, JSON.parse(e.newValue)); } catch {}
}
});
}
// Escape to close
function handleKeydown(e) {
if (e.key === "Escape") {
getCurrentWindow().close();
}
}
</script>
<svelte:window onkeydown={handleKeydown} />
<div class="h-screen w-screen overflow-hidden grain rounded-lg border border-border shadow-xl animate-float-enter">
{@render children()}
</div>

View File

@@ -0,0 +1,452 @@
<script>
import { onMount, onDestroy } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { convertFileSrc } from "@tauri-apps/api/core";
import { formatTime, formatDuration } from "$lib/utils/time.js";
import { PLAYBACK_SPEEDS } from "$lib/utils/constants.js";
let item = $state(null);
let audioEl = $state(null);
let playing = $state(false);
let currentTime = $state(0);
let duration = $state(0);
let playbackRate = $state(1);
let searchQuery = $state("");
let activeSegmentIdx = $state(-1);
let editingIdx = $state(-1);
let editingText = $state("");
let showTimestamps = $state(true);
let showStarredOnly = $state(false);
let animFrameId = null;
let segmentRefs = [];
// Load item data from localStorage (set by HistoryPage before opening this window)
onMount(() => {
try {
const raw = localStorage.getItem("ramble_viewer_item");
if (raw) {
item = JSON.parse(raw);
if (item.audioPath) {
const src = convertFileSrc(item.audioPath);
const audio = new Audio(src);
audio.onloadedmetadata = () => { duration = audio.duration; };
audio.onended = () => { playing = false; cancelAnimationFrame(animFrameId); };
audio.onerror = () => { playing = false; };
audioEl = audio;
}
}
} catch {}
// Listen for new items via storage events
window.addEventListener("storage", handleStorageChange);
});
onDestroy(() => {
if (audioEl) audioEl.pause();
cancelAnimationFrame(animFrameId);
window.removeEventListener("storage", handleStorageChange);
});
function handleStorageChange(e) {
if (e.key === "ramble_viewer_item" && e.newValue) {
try {
if (audioEl) { audioEl.pause(); }
cancelAnimationFrame(animFrameId);
playing = false;
currentTime = 0;
item = JSON.parse(e.newValue);
if (item.audioPath) {
const src = convertFileSrc(item.audioPath);
const audio = new Audio(src);
audio.onloadedmetadata = () => { duration = audio.duration; };
audio.onended = () => { playing = false; cancelAnimationFrame(animFrameId); };
audioEl = audio;
}
} catch {}
}
}
function togglePlay() {
if (!audioEl) return;
if (playing) {
audioEl.pause();
playing = false;
cancelAnimationFrame(animFrameId);
} else {
audioEl.play();
playing = true;
tickTime();
}
}
function tickTime() {
if (audioEl) {
currentTime = audioEl.currentTime;
updateActiveSegment();
if (!audioEl.paused) {
animFrameId = requestAnimationFrame(tickTime);
}
}
}
function updateActiveSegment() {
if (!item?.segments) return;
const t = currentTime;
for (let i = 0; i < item.segments.length; i++) {
const seg = item.segments[i];
if (t >= seg.start && t < seg.end) {
if (activeSegmentIdx !== i) {
activeSegmentIdx = i;
// Auto-scroll to active segment
if (segmentRefs[i]) {
segmentRefs[i].scrollIntoView({ behavior: "smooth", block: "center" });
}
}
return;
}
}
}
function seekTo(e) {
const val = parseFloat(e.target.value);
if (audioEl) {
audioEl.currentTime = val;
currentTime = val;
updateActiveSegment();
}
}
function seekToTime(time) {
if (audioEl) {
audioEl.currentTime = time;
currentTime = time;
if (!playing) {
audioEl.play();
playing = true;
tickTime();
}
updateActiveSegment();
}
}
function setSpeed(speed) {
playbackRate = speed;
if (audioEl) audioEl.playbackRate = speed;
}
// Search: find matching segments
let matchingSegments = $derived.by(() => {
if (!searchQuery.trim() || !item?.segments) return new Set();
const q = searchQuery.toLowerCase();
const matches = new Set();
item.segments.forEach((seg, i) => {
if (seg.text.toLowerCase().includes(q)) matches.add(i);
});
return matches;
});
let matchCount = $derived.by(() => matchingSegments.size);
// Highlight search matches in text
function highlightText(text) {
if (!searchQuery.trim()) return text;
const q = searchQuery.trim();
const regex = new RegExp(`(${q.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`, "gi");
return text.replace(regex, '<mark class="bg-accent/25 text-text rounded px-0.5">$1</mark>');
}
// Segment editing
function startEditing(idx) {
editingIdx = idx;
editingText = item.segments[idx].text;
}
function finishEditing() {
if (editingIdx >= 0 && item?.segments) {
item.segments[editingIdx].text = editingText.trim();
// Update full text
item.text = item.segments.map((s) => s.text).join(" ").trim();
saveItemToHistory();
}
editingIdx = -1;
editingText = "";
}
function deleteSegment(idx) {
if (item?.segments) {
item.segments.splice(idx, 1);
item.text = item.segments.map((s) => s.text).join(" ").trim();
saveItemToHistory();
if (editingIdx === idx) { editingIdx = -1; }
}
}
function toggleStar(idx) {
if (item?.segments) {
item.segments[idx].starred = !item.segments[idx].starred;
saveItemToHistory();
}
}
function copySegment(idx) {
if (item?.segments?.[idx]) {
navigator.clipboard.writeText(item.segments[idx].text.trim()).catch(() => {});
}
}
function saveItemToHistory() {
// Persist edits back to localStorage history
try {
const raw = localStorage.getItem("ramble_history");
if (raw) {
const hist = JSON.parse(raw);
const idx = hist.findIndex((h) => h.id === item.id);
if (idx >= 0) {
hist[idx] = { ...hist[idx], segments: item.segments, text: item.text };
localStorage.setItem("ramble_history", JSON.stringify(hist));
}
}
// Also update the viewer item cache
localStorage.setItem("ramble_viewer_item", JSON.stringify(item));
} catch {}
}
// Filtered segments (starred filter + search)
let visibleSegments = $derived.by(() => {
if (!item?.segments) return [];
let segs = item.segments.map((seg, i) => ({ ...seg, _idx: i }));
if (showStarredOnly) {
segs = segs.filter((s) => s.starred);
}
return segs;
});
// Window drag
function handleDragStart(e) {
if (e.button !== 0) return;
if (e.target.closest("button")) return;
if (e.target.closest("input")) return;
getCurrentWindow().startDragging();
}
function closeWindow() {
getCurrentWindow().close();
}
</script>
<div class="flex flex-col h-full bg-bg">
<!-- Drag handle -->
<div
class="flex items-center h-[36px] bg-bg-elevated select-none px-3"
onmousedown={handleDragStart}
data-tauri-drag-region
>
<span class="text-[12px] font-medium text-text-secondary tracking-wide" data-tauri-drag-region>
Ramble - Viewer
</span>
<div class="flex-1" data-tauri-drag-region></div>
<button
class="w-7 h-7 flex items-center justify-center text-text-tertiary hover:text-danger rounded-md hover:bg-hover"
onclick={closeWindow}
aria-label="Close"
>
<svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
<path d="M18 6L6 18M6 6l12 12" stroke-linecap="round" />
</svg>
</button>
</div>
{#if item}
<!-- Item info -->
<div class="px-5 pt-3 pb-2">
<p class="text-[13px] text-text font-medium">
{item.title || "Transcript"}
</p>
<p class="text-[10px] text-text-tertiary mt-0.5">
{item.date}{#if item.duration} · {formatDuration(item.duration)}{/if} · {item.source}
</p>
</div>
<!-- Media controls -->
{#if audioEl}
<div class="flex items-center gap-3 px-5 py-2 border-b border-border-subtle">
<!-- Play/Pause -->
<button
class="w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0
{playing ? 'bg-accent text-white' : 'bg-accent/15 text-accent hover:bg-accent/25'}"
onclick={togglePlay}
aria-label={playing ? "Pause" : "Play"}
>
{#if playing}
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
<rect x="6" y="4" width="4" height="16" rx="1" />
<rect x="14" y="4" width="4" height="16" rx="1" />
</svg>
{:else}
<svg class="w-4 h-4 ml-0.5" viewBox="0 0 24 24" fill="currentColor">
<path d="M8 5v14l11-7z" />
</svg>
{/if}
</button>
<!-- Time -->
<span class="text-[11px] text-text-tertiary tabular-nums min-w-[70px]">
{formatTime(currentTime)} / {formatTime(duration)}
</span>
<!-- Seek bar -->
<input
type="range"
min="0"
max={duration || 0}
step="0.1"
value={currentTime}
oninput={seekTo}
class="flex-1 accent-accent h-1"
data-no-transition
/>
<!-- Speed pills -->
<div class="flex gap-0.5 flex-shrink-0">
{#each PLAYBACK_SPEEDS as speed}
<button
class="text-[9px] px-1.5 py-0.5 rounded-full
{playbackRate === speed
? 'bg-accent/15 text-accent font-medium'
: 'text-text-tertiary hover:text-text-secondary'}"
onclick={() => setSpeed(speed)}
>{speed}x</button>
{/each}
</div>
</div>
{/if}
<!-- Search bar + view controls -->
<div class="flex items-center gap-2 px-5 py-2 border-b border-border-subtle">
<div class="flex items-center gap-2 bg-bg-input border border-border rounded-lg px-3 py-1.5 focus-within:border-accent flex-1">
<svg class="w-3.5 h-3.5 text-text-tertiary flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="11" cy="11" r="8" />
<path d="M21 21l-4.35-4.35" stroke-linecap="round" />
</svg>
<input
type="text"
class="flex-1 bg-transparent text-[12px] text-text placeholder:text-text-tertiary focus:outline-none"
placeholder="Search transcript..."
bind:value={searchQuery}
data-no-transition
/>
{#if searchQuery}
<span class="text-[10px] text-text-tertiary">{matchCount} matches</span>
<button class="text-[10px] text-text-tertiary hover:text-text" onclick={() => searchQuery = ""}>Clear</button>
{/if}
</div>
<!-- Compact mode toggle -->
<button
class="text-[10px] px-2 py-1 rounded-lg flex-shrink-0
{showTimestamps ? 'text-text-tertiary hover:text-text-secondary' : 'text-accent bg-accent/10'}"
onclick={() => showTimestamps = !showTimestamps}
title={showTimestamps ? "Hide timestamps (compact)" : "Show timestamps"}
>Compact</button>
<!-- Starred filter -->
<button
class="text-[10px] px-2 py-1 rounded-lg flex-shrink-0
{showStarredOnly ? 'text-accent bg-accent/10' : 'text-text-tertiary hover:text-text-secondary'}"
onclick={() => showStarredOnly = !showStarredOnly}
title={showStarredOnly ? "Show all segments" : "Show starred only"}
>Starred</button>
</div>
<!-- Transcript segments -->
<div class="flex-1 overflow-y-auto px-5 py-3 min-h-0">
{#if item.segments && item.segments.length > 0}
<div class="flex flex-col gap-1">
{#each visibleSegments as seg (seg._idx)}
<div
bind:this={segmentRefs[seg._idx]}
class="group flex gap-3 px-3 py-2 rounded-lg cursor-pointer transition-colors
{activeSegmentIdx === seg._idx
? 'bg-accent/10 border-l-2 border-accent'
: matchingSegments.has(seg._idx)
? 'bg-warning/5 border-l-2 border-warning/40'
: 'border-l-2 border-transparent hover:bg-hover'}"
onclick={() => seekToTime(seg.start)}
ondblclick={() => startEditing(seg._idx)}
role="button"
tabindex="0"
onkeydown={(e) => { if (e.key === "Enter" && editingIdx !== seg._idx) seekToTime(seg.start); }}
>
<!-- Star -->
<button
class="mt-0.5 flex-shrink-0 {seg.starred ? 'text-accent' : 'text-text-tertiary opacity-0 group-hover:opacity-100'}"
onclick={(e) => { e.stopPropagation(); toggleStar(seg._idx); }}
aria-label={seg.starred ? "Unstar" : "Star"}
>
<svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill={seg.starred ? "currentColor" : "none"} stroke="currentColor" stroke-width="2">
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
</svg>
</button>
<!-- Timestamp -->
{#if showTimestamps}
<span class="text-[10px] text-text-tertiary tabular-nums flex-shrink-0 mt-0.5 min-w-[36px]">
{formatTime(seg.start)}
</span>
{/if}
<!-- Text (editable or display) -->
{#if editingIdx === seg._idx}
<textarea
class="flex-1 bg-bg-input border border-accent rounded-lg px-2 py-1 text-[13px] text-text
leading-relaxed resize-none focus:outline-none min-h-[40px]"
bind:value={editingText}
onkeydown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); finishEditing(); } if (e.key === "Escape") { editingIdx = -1; } }}
onblur={finishEditing}
onclick={(e) => e.stopPropagation()}
data-no-transition
autofocus
></textarea>
{:else}
<p class="text-[13px] text-text leading-relaxed flex-1">
{#if searchQuery.trim()}
{@html highlightText(seg.text.trim())}
{:else}
{seg.text.trim()}
{/if}
</p>
{/if}
<!-- Actions (hover reveal) -->
<div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 flex-shrink-0">
<button
class="text-text-tertiary hover:text-accent"
onclick={(e) => { e.stopPropagation(); copySegment(seg._idx); }}
title="Copy segment"
>
<svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="9" y="9" width="13" height="13" rx="2" /><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
</button>
<button
class="text-text-tertiary hover:text-danger"
onclick={(e) => { e.stopPropagation(); deleteSegment(seg._idx); }}
title="Delete segment"
>
<svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 6L6 18M6 6l12 12" stroke-linecap="round" />
</svg>
</button>
</div>
</div>
{/each}
</div>
{:else}
<!-- No segments — show full text -->
<p class="text-[13px] text-text leading-relaxed whitespace-pre-wrap">{item.text}</p>
{/if}
</div>
{:else}
<div class="flex-1 flex items-center justify-center">
<p class="text-[13px] text-text-tertiary">No transcript loaded</p>
</div>
{/if}
</div>