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
This commit is contained in:
2026-04-17 13:06:36 +01:00
parent 19a6b83cb2
commit 69d768e803
4 changed files with 239 additions and 0 deletions

View File

@@ -0,0 +1,129 @@
<script>
// Renders the toast stack in the bottom-right of the viewport. Mount once
// at the app root (in +layout.svelte). Reads from the global toasts store.
//
// Severity colour mapping uses the brand palette via CSS variables already
// defined in app.css — no inline literals.
//
// Honours prefers-reduced-motion via the existing :root[data-reduce-motion]
// attribute that preferences.svelte.js sets.
import { toasts } from '$lib/stores/toasts.svelte.js';
import { X } from 'lucide-svelte';
function severityClass(severity) {
switch (severity) {
case 'success': return 'toast-success';
case 'info': return 'toast-info';
case 'warn': return 'toast-warn';
case 'error': return 'toast-error';
default: return 'toast-info';
}
}
</script>
<div class="toast-viewport" aria-live="polite" aria-atomic="false">
{#each toasts.items as toast (toast.id)}
<div
class="toast {severityClass(toast.severity)}"
role={toast.severity === 'error' ? 'alert' : 'status'}
>
<div class="toast-body">
<div class="toast-title">{toast.title}</div>
{#if toast.body}
<div class="toast-msg">{toast.body}</div>
{/if}
</div>
<button
class="toast-close"
aria-label="Dismiss"
onclick={() => toasts.dismiss(toast.id)}
type="button"
>
<X size={14} aria-hidden="true" />
</button>
</div>
{/each}
</div>
<style>
.toast-viewport {
position: fixed;
bottom: 1rem;
right: 1rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
z-index: 9999;
max-width: min(28rem, calc(100vw - 2rem));
pointer-events: none;
}
.toast {
pointer-events: auto;
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 0.875rem 1rem;
border-radius: 0.5rem;
background: var(--surface, #1a1a1a);
color: var(--text, #fff);
border-left: 3px solid var(--moss, #4a7a4a);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
/* Slide in from right; honours reduce-motion via the existing class
that preferences.svelte.js applies to <html>. */
animation: toast-slide-in 200ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
:global(html.reduce-motion) .toast { animation: none; }
@keyframes toast-slide-in {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
.toast-info { border-left-color: var(--moss, #4a7a4a); }
.toast-success { border-left-color: var(--moss, #4a7a4a); }
.toast-warn { border-left-color: var(--signal, #d4a017); }
.toast-error { border-left-color: var(--ember, #c87144); }
.toast-body {
flex: 1;
min-width: 0;
}
.toast-title {
font-weight: 600;
font-size: 0.9375rem;
line-height: 1.4;
word-wrap: break-word;
}
.toast-msg {
margin-top: 0.25rem;
font-size: 0.875rem;
line-height: 1.5;
color: var(--text-muted, rgba(255, 255, 255, 0.7));
word-wrap: break-word;
}
.toast-close {
flex-shrink: 0;
background: transparent;
border: none;
color: var(--text-muted, rgba(255, 255, 255, 0.6));
cursor: pointer;
padding: 0.25rem;
border-radius: 0.25rem;
display: flex;
align-items: center;
justify-content: center;
transition: background 100ms, color 100ms;
}
.toast-close:hover {
background: rgba(255, 255, 255, 0.08);
color: var(--text, #fff);
}
.toast-close:focus-visible {
outline: 2px solid var(--ember, #c87144);
outline-offset: 2px;
}
</style>

View File

@@ -2,6 +2,7 @@
import { onMount, onDestroy } from "svelte";
import { Channel, invoke } from "@tauri-apps/api/core";
import { page, settings, templates, profiles, addToHistory, addTask, tasks } from "$lib/stores/page.svelte.js";
import { toasts } from "$lib/stores/toasts.svelte.js";
import Card from "$lib/components/Card.svelte";
import ModelDownloader from "$lib/components/ModelDownloader.svelte";
import { exportTranscript } from "$lib/utils/export.js";
@@ -342,6 +343,10 @@
timerInterval = setInterval(updateTimer, 1000);
} catch (err) {
error = typeof err === "string" ? err : err?.message || "Microphone error";
// Surface the failure as a sticky error toast so it does not get
// swallowed if the inline `error` panel is not visible.
// (Day 3 of the upgrade plan)
toasts.error("Could not start recording", error);
page.status = "Error";
page.statusColor = "#e87171";
cleanup();

View File

@@ -0,0 +1,83 @@
// Minimal toast store. Roll-our-own (no svelte-french-toast etc) so Kon
// stays lean. Toasts auto-dismiss after `duration` ms unless duration is 0
// (sticky) or unless the user clicks the close button.
//
// Severity → colour:
// info → moss (informational, default 4s)
// success → moss (operation succeeded, default 3s)
// warn → signal (degraded but not failed, default 6s)
// error → ember (operation failed, sticky until dismissed)
//
// Usage from a component:
// import { toasts } from '$lib/stores/toasts.svelte.js';
// toasts.error('Could not start recording', 'Selected microphone disappeared.');
// toasts.success('Saved');
let nextId = 1;
function defaultDuration(severity) {
switch (severity) {
case 'success': return 3000;
case 'info': return 4000;
case 'warn': return 6000;
case 'error': return 0; // sticky
default: return 4000;
}
}
function createToastsStore() {
// $state requires a class field or top-level let in Svelte 5; we expose
// `items` via a getter on the singleton.
let items = $state([]);
function show(severity, title, body) {
const id = nextId++;
const duration = defaultDuration(severity);
const toast = { id, severity, title, body: body ?? '', duration };
items.push(toast);
if (duration > 0) {
setTimeout(() => dismiss(id), duration);
}
return id;
}
function dismiss(id) {
const ix = items.findIndex(t => t.id === id);
if (ix >= 0) items.splice(ix, 1);
}
function dismissAll() {
items.length = 0;
}
return {
get items() { return items; },
info: (title, body) => show('info', title, body),
success: (title, body) => show('success', title, body),
warn: (title, body) => show('warn', title, body),
error: (title, body) => show('error', title, body),
dismiss,
dismissAll,
};
}
export const toasts = createToastsStore();
// Helper: wrap a Tauri invoke and toast on failure. Returns the result on
// success, throws on failure (so callers that need to handle the error
// can still try/catch).
//
// import { invoke } from '@tauri-apps/api/core';
// import { invokeWithToast } from '$lib/stores/toasts.svelte.js';
// const result = await invokeWithToast('start_native_capture', { deviceName });
//
// Optional `errorTitle` overrides the default ("Action failed").
export async function invokeWithToast(invokeFn, command, args, errorTitle) {
try {
return await invokeFn(command, args);
} catch (err) {
const msg = typeof err === 'string' ? err : (err?.message ?? String(err));
toasts.error(errorTitle ?? 'Action failed', msg);
throw err;
}
}

View File

@@ -5,14 +5,17 @@
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
@@ -49,6 +52,10 @@
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) {
@@ -73,6 +80,7 @@
}
async function registerGlobalHotkey(hotkey) {
if (!tauriRuntimeAvailable) return;
if (hotkeyBackend === "unknown") return; // not yet initialised
try {
@@ -106,6 +114,7 @@
// 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";
@@ -161,6 +170,11 @@
handleResize();
window.addEventListener("resize", handleResize);
if (!tauriRuntimeAvailable) {
hotkeyBackend = "unavailable";
return;
}
// Detect and initialise the correct hotkey backend
await initHotkeyBackend();
@@ -177,6 +191,9 @@
onDestroy(() => {
window.removeEventListener("resize", handleResize);
if (!tauriRuntimeAvailable) {
return;
}
if (hotkeyBackend === "evdev") {
invoke("stop_evdev_hotkey").catch(() => {});
} else if (hotkeyBackend === "tauri" && registeredHotkey) {
@@ -220,3 +237,8 @@
</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 />