Files
Lumotia/src/routes/+layout.svelte
Jake 69d768e803 ui: Day 3 — global toast system + first error-toast wiring on DictationPage
THE PROBLEM (Codex review + architecture-review.md §1, §14):
Multiple critical paths discard errors silently — `let _ = insert_transcript(...)`,
`.catch(() => {})`, inline `error = ...` state that not every page surfaces. ND
users in particular need explicit feedback when something fails; silent
failure is worse than no feature.

SHIPPED:

src/lib/stores/toasts.svelte.js (new):
- Minimal in-house toast store (~80 lines, no svelte-french-toast dep)
- Severity → palette: info/success → moss, warn → signal, error → ember
- Auto-dismiss durations per severity (success 3s, info 4s, warn 6s,
  error sticky)
- `invokeWithToast(invoke, command, args, errorTitle?)` helper wraps a
  Tauri invoke and toasts on failure while still throwing for callers
  that need to handle the error themselves

src/lib/components/ToastViewport.svelte (new):
- Reads from the toasts store
- Bottom-right stack, max-width clamp on small screens
- aria-live=polite + role=alert on error toasts (screen-reader friendly)
- Slide-in animation honours `html.reduce-motion` for the existing
  preferences toggle
- Severity left-border in brand colours via existing CSS variables

src/routes/+layout.svelte:
- Mounts <ToastViewport /> once at the app root so toasts work from any
  page or window

src/lib/pages/DictationPage.svelte:
- First error-toast wiring: failures starting recording now show a
  sticky toast in addition to the inline `error` panel
- Replaces a previously easy-to-miss failure-mode

NEXT (Day 4 batch):
- Wire toasts into FilesPage, HistoryPage, SettingsPage, ModelDownloader
  (all currently swallow errors)
- Add `add_transcript`, `list_transcripts`, `update_transcript` (closes the
  long-standing TODO Codex flagged), `delete_transcript` Tauri commands
  wrapping the existing storage layer
- Switch addToHistory to dual-write (localStorage + SQLite) so the
  canonical store catches up with the actual transcript flow
- FTS5 transcripts_fts virtual table + search command
- Wrap multi-row writes (decompose_and_store) in DB transactions
2026-04-17 13:06:36 +01:00

245 lines
7.7 KiB
Svelte

<script>
import "../app.css";
import { onMount, onDestroy } from "svelte";
import { invoke } from "@tauri-apps/api/core";
import Sidebar from "$lib/Sidebar.svelte";
import TaskSidebar from "$lib/components/TaskSidebar.svelte";
import Titlebar from "$lib/components/Titlebar.svelte";
import ToastViewport from "$lib/components/ToastViewport.svelte";
import { page, settings, saveSettings } from "$lib/stores/page.svelte.js";
import { getPreferences, updatePreferences } from "$lib/stores/preferences.svelte.js";
import { hasTauriRuntime } from "$lib/utils/runtime.js";
import { page as sveltePage } from "$app/stores";
let { children } = $props();
const prefs = getPreferences();
const tauriRuntimeAvailable = hasTauriRuntime();
// Detect secondary windows (float, viewer) — they use +layout@.svelte
// but as a fallback, hide chrome if the URL matches
let isSecondaryWindow = $derived(
$sveltePage.url.pathname.startsWith("/float") ||
$sveltePage.url.pathname.startsWith("/viewer")
);
// Recording indicator dot (follows mouse)
let mouseX = $state(0);
let mouseY = $state(0);
function handleMouseMove(e) {
mouseX = e.clientX;
mouseY = e.clientY;
}
// Theme — migrate from old class-based to new data-attribute system
// The preferences store handles DOM application via data-theme attribute
$effect(() => {
// Sync legacy settings.theme → preferences store
const legacyTheme = settings.theme;
const mapped = legacyTheme === "Light" ? "light" : legacyTheme === "Dark" ? "dark" : "system";
if (prefs.theme !== mapped) {
updatePreferences({ theme: mapped });
}
});
// Global hotkey registration — dual backend
// Wayland: evdev via kon-hotkey crate (works without display server)
// X11/macOS/Windows: tauri-plugin-global-shortcut (native)
let registeredHotkey = null;
let hotkeyBackend = $state("unknown"); // "evdev" | "tauri" | "unavailable"
async function initHotkeyBackend() {
if (!tauriRuntimeAvailable) {
hotkeyBackend = "unavailable";
return;
}
try {
const isWayland = await invoke("is_wayland_session");
if (isWayland) {
// Try evdev backend first (Wayland-compatible)
try {
await invoke("check_hotkey_access");
hotkeyBackend = "evdev";
console.log("Hotkey backend: evdev (Wayland)");
} catch (err) {
console.warn("evdev hotkey access denied:", err);
console.warn("Add your user to the 'input' group for global hotkeys on Wayland");
hotkeyBackend = "unavailable";
}
} else {
hotkeyBackend = "tauri";
console.log("Hotkey backend: tauri-plugin-global-shortcut (X11)");
}
} catch {
// Fallback to tauri plugin if detection fails
hotkeyBackend = "tauri";
}
}
async function registerGlobalHotkey(hotkey) {
if (!tauriRuntimeAvailable) return;
if (hotkeyBackend === "unknown") return; // not yet initialised
try {
if (hotkeyBackend === "evdev") {
// evdev backend: start or update the Rust-side listener
if (registeredHotkey) {
await invoke("update_evdev_hotkey", { hotkey });
} else {
await invoke("start_evdev_hotkey", { hotkey });
}
registeredHotkey = hotkey;
} else if (hotkeyBackend === "tauri") {
// Tauri plugin backend (X11/macOS/Windows)
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("kon:toggle-recording"));
});
});
registeredHotkey = hotkey;
}
} catch (err) {
console.error("Hotkey registration failed:", err);
}
}
// Listen for evdev hotkey events from the Rust backend
let unlistenEvdev = null;
async function setupEvdevListener() {
if (!tauriRuntimeAvailable) return;
const { listen } = await import("@tauri-apps/api/event");
unlistenEvdev = await listen("kon:hotkey-pressed", () => {
if (page.current !== "dictation") page.current = "dictation";
requestAnimationFrame(() => {
window.dispatchEvent(new CustomEvent("kon:toggle-recording"));
});
});
}
$effect(() => {
if (hotkeyBackend === "evdev" && !unlistenEvdev) {
setupEvdevListener();
}
});
$effect(() => {
if (hotkeyBackend !== "unknown") {
registerGlobalHotkey(settings.globalHotkey);
}
});
// Apply font size setting as CSS variable (legacy — kept for backwards compat)
$effect(() => {
document.documentElement.style.setProperty("--font-size-transcript", `${settings.fontSize}px`);
});
// Check whether the keydown originates from a text input (avoid triggering while typing)
function isInputFocused(e) {
const tag = e.target?.tagName;
return tag === "INPUT" || tag === "TEXTAREA" || e.target?.isContentEditable;
}
function handleKeydown(e) {
if (e.key === "Escape" && page.taskSidebarOpen) {
page.taskSidebarOpen = false;
return;
}
if (e.key === "[" && !isInputFocused(e)) {
settings.sidebarCollapsed = !settings.sidebarCollapsed;
saveSettings();
}
}
function handleResize() {
if (window.innerWidth < 900 && !settings.sidebarCollapsed) {
settings.sidebarCollapsed = true;
saveSettings();
}
}
onMount(async () => {
// Auto-collapse if window is already narrow on first load
handleResize();
window.addEventListener("resize", handleResize);
if (!tauriRuntimeAvailable) {
hotkeyBackend = "unavailable";
return;
}
// Detect and initialise the correct hotkey backend
await initHotkeyBackend();
try {
const whisper = await invoke("list_models");
const parakeet = await invoke("list_parakeet_models");
if (whisper.length === 0 && parakeet.length === 0) {
page.current = "first-run";
}
} catch {
// If commands fail, skip first-run check
}
});
onDestroy(() => {
window.removeEventListener("resize", handleResize);
if (!tauriRuntimeAvailable) {
return;
}
if (hotkeyBackend === "evdev") {
invoke("stop_evdev_hotkey").catch(() => {});
} else if (hotkeyBackend === "tauri" && registeredHotkey) {
import("@tauri-apps/plugin-global-shortcut")
.then((mod) => mod.unregister(registeredHotkey))
.catch(() => {});
}
if (unlistenEvdev) {
unlistenEvdev();
}
});
</script>
<svelte:window onmousemove={handleMouseMove} onkeydown={handleKeydown} />
{#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}
{#if isSecondaryWindow}
<!-- Secondary windows (float, viewer) render children only — no shell chrome -->
{@render children()}
{:else}
<div class="flex flex-col h-screen w-screen overflow-hidden grain">
<Titlebar />
<div class="flex flex-1 min-h-0 relative">
{#if page.current !== "first-run"}
<Sidebar />
{/if}
<div class="flex-1 overflow-hidden bg-bg">
{@render children()}
</div>
{#if page.taskSidebarOpen && page.current !== "first-run"}
<div class="w-[280px] min-w-[280px] shadow-xl">
<TaskSidebar />
</div>
{/if}
</div>
</div>
{/if}
<!-- Global toast viewport. Mounted once at the app root so any component
can call toasts.error(...), toasts.success(...) etc and have it render
in the bottom-right of the viewport. (Day 3 of the upgrade plan) -->
<ToastViewport />