feat(focus-timer): Phase 1 — visual countdown ring + just-start timer

Closes the Core MVP gap in docs/brief/feature-set.md ("visual time
representation") and wires the dangling kon:start-timer emit that
MicroSteps.svelte has been firing into the void since the stub was
written. Implements phase 1 of the 2026-04-23 feature-complete
roadmap.

New:
- src/lib/stores/focusTimer.svelte.ts — singleton timer store with
  localStorage persistence so a timer started in Dictation survives
  page nav, window close, and reopen. Gentle WebAudio chime at
  completion (no bundled asset). 250 ms tick. Completion flash for
  3 s before auto-clear.
- src/lib/components/FocusTimer.svelte — floating top-right overlay
  with SVG progress ring (shrinking colour: accent -> warning in
  the final 15% -> success on completion). Cancel + "+1 min" on
  hover. Renders nothing when idle.

Wired in +layout.svelte next to ToastViewport.

Two triggers now in the app:
- MicroSteps row 2-min button (pre-existing emit, previously no
  listener)
- WipTaskList row 5-min button (new; the brief's "just-start"
  from the Now column)

Respects prefers-reduced-motion via the existing
[data-reduce-motion] attribute.

Out of scope, carried to later phases: rhythmic voice anchoring
(Phase 6), custom-duration picker, multi-timer UI, native OS
notification (deferred to Phase 6 with the full nudge pipeline).
This commit is contained in:
2026-04-24 11:50:45 +01:00
parent df6b19834d
commit 0c34a29367
4 changed files with 525 additions and 1 deletions

View File

@@ -0,0 +1,270 @@
<script lang="ts">
// Floating focus-timer overlay. Renders nothing when no timer is
// active. When a timer is running, pins a compact SVG progress ring
// to the top-right of the viewport with the remaining mm:ss in the
// centre. Completion plays a gentle chime, flashes a success ring
// for 3 s, then disappears. Cancel button appears on hover.
//
// Mounted once in +layout.svelte. Listens for `kon:start-timer`
// events from anywhere in the app (e.g. MicroSteps) and delegates
// to the focus-timer store.
//
// Design tokens used: --color-accent (mid-progress),
// --color-warning (final 15%), --color-success (flourish),
// --color-border (unfilled ring track). No literals, so the ring
// follows the sensory-zone theme switcher in Settings.
import { onMount, onDestroy } from "svelte";
import { X, Plus } from "lucide-svelte";
import { focusTimer } from "$lib/stores/focusTimer.svelte.js";
const RING_SIZE = 64;
const RING_STROKE = 5;
const RING_RADIUS = (RING_SIZE - RING_STROKE) / 2;
const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS;
// Progress ring fills as time elapses. Stroke-dashoffset goes from
// circumference (empty) to 0 (full) — we want it the other way,
// because the UX is a shrinking-time disc: more elapsed = less
// ring visible. Render the remaining arc: dashoffset = circumference * progress.
let dashOffset = $derived(RING_CIRCUMFERENCE * focusTimer.progress);
function formatRemaining(ms: number): string {
const total = Math.ceil(ms / 1000);
const mins = Math.floor(total / 60);
const secs = total % 60;
return `${mins}:${secs.toString().padStart(2, "0")}`;
}
// Colour shifts over the last 15% of the timer to cue "nearly done"
// without resorting to red (which the brief flags as anxiogenic for
// the target audience).
let ringColor = $derived.by(() => {
if (focusTimer.showingCompletionFlash) return "var(--color-success)";
if (focusTimer.progress >= 0.85) return "var(--color-warning)";
return "var(--color-accent)";
});
// Event handler: start a timer when any component fires `kon:start-timer`.
// Payload shape from MicroSteps.svelte and task row buttons:
// { taskId?: string, seconds: number, label?: string }
function handleStartEvent(evt: Event) {
const detail = (evt as CustomEvent).detail ?? {};
const seconds = Number(detail.seconds);
if (!Number.isFinite(seconds) || seconds <= 0) return;
focusTimer.start(seconds, {
taskId: detail.taskId ?? null,
label: detail.label ?? null,
});
}
onMount(() => {
window.addEventListener("kon:start-timer", handleStartEvent);
// Rehydrate any in-flight timer that survived a window close.
focusTimer.rehydrate();
});
onDestroy(() => {
window.removeEventListener("kon:start-timer", handleStartEvent);
});
function handleCancel() {
focusTimer.cancel();
}
function handleExtend() {
focusTimer.extend(60);
}
function handleDismissFlash() {
focusTimer.dismissCompletionFlash();
}
</script>
{#if focusTimer.active || focusTimer.showingCompletionFlash}
<div
class="focus-timer"
class:completed={focusTimer.showingCompletionFlash}
role="status"
aria-live="polite"
aria-label={focusTimer.label ?? "Focus timer"}
>
<div class="ring-wrap">
<svg
width={RING_SIZE}
height={RING_SIZE}
viewBox={`0 0 ${RING_SIZE} ${RING_SIZE}`}
aria-hidden="true"
>
<!-- Track -->
<circle
cx={RING_SIZE / 2}
cy={RING_SIZE / 2}
r={RING_RADIUS}
fill="none"
stroke="var(--color-border)"
stroke-width={RING_STROKE}
/>
<!-- Progress (shrinking slice — full ring at start, none at end) -->
<circle
cx={RING_SIZE / 2}
cy={RING_SIZE / 2}
r={RING_RADIUS}
fill="none"
stroke={ringColor}
stroke-width={RING_STROKE}
stroke-linecap="round"
stroke-dasharray={RING_CIRCUMFERENCE}
stroke-dashoffset={dashOffset}
transform={`rotate(-90 ${RING_SIZE / 2} ${RING_SIZE / 2})`}
style="transition: stroke-dashoffset 250ms linear, stroke 400ms ease"
/>
</svg>
<div class="time" aria-hidden={focusTimer.showingCompletionFlash}>
{#if focusTimer.showingCompletionFlash}
<span class="done">done</span>
{:else}
{formatRemaining(focusTimer.remainingMs)}
{/if}
</div>
</div>
<div class="controls">
{#if focusTimer.showingCompletionFlash}
<button
class="icon-btn"
onclick={handleDismissFlash}
aria-label="Dismiss completion"
title="Dismiss"
>
<X size={14} aria-hidden="true" />
</button>
{:else}
<button
class="icon-btn"
onclick={handleExtend}
aria-label="Add one minute"
title="+1 min"
>
<Plus size={14} aria-hidden="true" />
</button>
<button
class="icon-btn"
onclick={handleCancel}
aria-label="Cancel timer"
title="Cancel"
>
<X size={14} aria-hidden="true" />
</button>
{/if}
</div>
{#if focusTimer.label}
<div class="label" aria-hidden="true">{focusTimer.label}</div>
{/if}
</div>
{/if}
<style>
.focus-timer {
position: fixed;
top: 52px;
right: 16px;
z-index: 40;
display: flex;
align-items: center;
gap: 8px;
padding: 6px 10px 6px 6px;
background: var(--color-bg-elevated);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
font-family: var(--font-family-body);
font-variant-numeric: tabular-nums;
transition: opacity 200ms ease, transform 200ms ease;
}
.focus-timer.completed {
border-color: var(--color-success);
}
.ring-wrap {
position: relative;
width: 64px;
height: 64px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.time {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
font-weight: 500;
color: var(--color-text);
}
.time .done {
font-size: 11px;
color: var(--color-success);
font-family: var(--font-family-display);
letter-spacing: 0.02em;
}
.controls {
display: flex;
flex-direction: column;
gap: 4px;
opacity: 0;
transition: opacity 180ms ease;
}
.focus-timer:hover .controls,
.focus-timer:focus-within .controls,
.focus-timer.completed .controls {
opacity: 1;
}
.icon-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
padding: 0;
border: 0;
border-radius: var(--radius-sm);
background: transparent;
color: var(--color-text-secondary);
cursor: pointer;
transition: background 150ms ease, color 150ms ease;
}
.icon-btn:hover {
background: var(--color-hover);
color: var(--color-text);
}
.icon-btn:focus-visible {
outline: 2px solid var(--color-accent);
outline-offset: 1px;
}
.label {
max-width: 140px;
font-size: 12px;
color: var(--color-text-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
:global([data-reduce-motion="true"]) .focus-timer circle {
transition: none !important;
}
</style>

View File

@@ -1,7 +1,13 @@
<script lang="ts">
import { tasks, addTask, completeTask, uncompleteTask, deleteTask } from '$lib/stores/page.svelte.js';
import MicroSteps from '$lib/components/MicroSteps.svelte';
import { ChevronDown, ChevronRight } from 'lucide-svelte';
import { ChevronDown, ChevronRight, Timer } from 'lucide-svelte';
function startFocusTimer(task: { id: string; text: string }) {
window.dispatchEvent(new CustomEvent('kon:start-timer', {
detail: { taskId: task.id, seconds: 300, label: task.text }
}));
}
let { wipLimit = 3 } = $props();
@@ -68,6 +74,16 @@
aria-label="Complete task"
></button>
<span class="text-[13px] text-text flex-1 min-w-0 truncate">{task.text}</span>
<!-- 5-min focus timer — the "just-start" button from the brief -->
<button
class="opacity-0 group-hover:opacity-100 text-text-tertiary hover:text-accent"
onclick={() => startFocusTimer(task)}
aria-label="Start 5-minute focus timer for this task"
title="Start 5-minute focus timer"
style="transition: opacity var(--duration-ui)"
>
<Timer size={12} aria-hidden="true" />
</button>
<!-- Expand/collapse micro-steps toggle -->
<button
class="opacity-0 group-hover:opacity-100 text-text-tertiary hover:text-accent"

View File

@@ -0,0 +1,230 @@
// Focus timer store. Single active timer at a time — the "just-start"
// 2/5/10/15-minute countdown paired with micro-steps. Exposes:
// - focusTimer.active: whether a timer is currently running
// - focusTimer.progress: 0..1 fraction of elapsed time
// - focusTimer.remainingMs: milliseconds until completion
// - focusTimer.label / focusTimer.taskId: what this timer is for
// - start(seconds, opts) / cancel() / extend(seconds)
//
// Survives window close + reopen via localStorage, because a timer
// that loses its clock when the user alt-tabs is a timer that nobody
// trusts. On rehydrate after expiry, fires completion then clears —
// so closing the window mid-timer still gets you the "done" signal
// on next launch.
const STORAGE_KEY = "kon.focusTimer.v1";
const TICK_INTERVAL_MS = 250;
export type FocusTimerPersisted = {
startedAt: number;
durationMs: number;
taskId: string | null;
label: string | null;
};
function readPersisted(): FocusTimerPersisted | null {
if (typeof window === "undefined") return null;
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw);
if (
typeof parsed?.startedAt !== "number" ||
typeof parsed?.durationMs !== "number"
) return null;
return {
startedAt: parsed.startedAt,
durationMs: parsed.durationMs,
taskId: parsed.taskId ?? null,
label: parsed.label ?? null,
};
} catch {
return null;
}
}
function writePersisted(state: FocusTimerPersisted | null): void {
if (typeof window === "undefined") return;
try {
if (state === null) window.localStorage.removeItem(STORAGE_KEY);
else window.localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
} catch { /* storage may be disabled; non-fatal */ }
}
function createFocusTimerStore() {
let startedAt = $state<number | null>(null);
let durationMs = $state<number>(0);
let taskId = $state<string | null>(null);
let label = $state<string | null>(null);
let now = $state<number>(Date.now());
let completionFlashUntil = $state<number>(0);
let interval: ReturnType<typeof setInterval> | null = null;
const active = $derived(startedAt !== null);
const elapsedMs = $derived(startedAt === null ? 0 : Math.max(0, now - startedAt));
const remainingMs = $derived(Math.max(0, durationMs - elapsedMs));
const progress = $derived(durationMs === 0 ? 0 : Math.min(1, elapsedMs / durationMs));
const finished = $derived(active && remainingMs === 0);
const showingCompletionFlash = $derived(now < completionFlashUntil);
// Internal completion + flash bookkeeping. We track whether we have
// already fired the completion chime for the current timer so a
// second tick does not re-fire it. Reset whenever a new timer starts.
let completionFired = false;
function tick() {
now = Date.now();
// Fire completion once, the first tick after we cross remaining=0.
if (startedAt !== null && !completionFired && now - startedAt >= durationMs) {
completionFired = true;
completionFlashUntil = now + 3000;
fireCompletion();
}
// After the 3 s flash window, clear everything and stop ticking.
if (completionFlashUntil > 0 && now >= completionFlashUntil) {
clear();
}
}
function startTick() {
if (interval !== null) return;
interval = setInterval(tick, TICK_INTERVAL_MS);
}
function stopTick() {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
}
function clear() {
startedAt = null;
durationMs = 0;
taskId = null;
label = null;
completionFlashUntil = 0;
completionFired = false;
writePersisted(null);
stopTick();
}
function start(seconds: number, opts?: { taskId?: string | null; label?: string | null }): void {
if (!Number.isFinite(seconds) || seconds <= 0) return;
now = Date.now();
startedAt = now;
durationMs = Math.floor(seconds * 1000);
taskId = opts?.taskId ?? null;
label = opts?.label ?? null;
completionFlashUntil = 0;
completionFired = false;
writePersisted({ startedAt, durationMs, taskId, label });
startTick();
}
function cancel(): void {
clear();
}
function extend(seconds: number): void {
if (startedAt === null) return;
if (!Number.isFinite(seconds) || seconds <= 0) return;
durationMs += Math.floor(seconds * 1000);
writePersisted({ startedAt, durationMs, taskId, label });
}
function dismissCompletionFlash(): void {
completionFlashUntil = 0;
clear();
}
function fireCompletion(): void {
if (typeof window === "undefined") return;
// Gentle chime — WebAudio so we do not ship a bundled asset.
// A 440 Hz fall into 330 Hz over 220 ms, low volume, no sustain.
try {
type AudioCtx = typeof AudioContext;
const win = window as unknown as { AudioContext?: AudioCtx; webkitAudioContext?: AudioCtx };
const Ctx = win.AudioContext ?? win.webkitAudioContext;
if (!Ctx) return;
const ctx = new Ctx();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.type = "sine";
osc.frequency.setValueAtTime(440, ctx.currentTime);
osc.frequency.exponentialRampToValueAtTime(330, ctx.currentTime + 0.22);
gain.gain.setValueAtTime(0.0001, ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.15, ctx.currentTime + 0.02);
gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.28);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start();
osc.stop(ctx.currentTime + 0.3);
osc.onended = () => ctx.close().catch(() => {});
} catch { /* audio is a nicety; never fatal */ }
window.dispatchEvent(new CustomEvent("kon:focus-timer-complete", {
detail: { taskId, label },
}));
}
// Rehydrate on first touch. If the persisted timer has already
// expired, fire completion then clear so the user still gets the
// "done" signal they missed while the window was closed.
function rehydrate(): void {
const persisted = readPersisted();
if (!persisted) return;
const age = Date.now() - persisted.startedAt;
if (age >= persisted.durationMs) {
// Already expired while the window was closed. Fire a completion
// event so downstream listeners (nudges, UI flourishes) can react.
taskId = persisted.taskId;
label = persisted.label;
durationMs = persisted.durationMs;
startedAt = persisted.startedAt;
now = persisted.startedAt + persisted.durationMs;
// Flash briefly so the user knows it happened.
completionFlashUntil = Date.now() + 3000;
completionFired = true;
fireCompletion();
startTick();
return;
}
startedAt = persisted.startedAt;
durationMs = persisted.durationMs;
taskId = persisted.taskId;
label = persisted.label;
now = Date.now();
startTick();
}
// Exposed as frozen object. Getters so derivations stay reactive.
return {
get active() { return active; },
get progress() { return progress; },
get elapsedMs() { return elapsedMs; },
get remainingMs() { return remainingMs; },
get durationMs() { return durationMs; },
get taskId() { return taskId; },
get label() { return label; },
get showingCompletionFlash() { return showingCompletionFlash; },
start,
cancel,
extend,
rehydrate,
dismissCompletionFlash,
};
}
export const focusTimer = createFocusTimerStore();
// Preset durations surfaced in the UI. 2 / 5 / 10 / 15 minutes match
// the brief's guidance for the "just-start" timer and cover common
// Pomodoro / shorter-focus preferences.
export const FOCUS_TIMER_PRESETS_SECONDS: ReadonlyArray<{ label: string; seconds: number }> = [
{ label: "2 min", seconds: 120 },
{ label: "5 min", seconds: 300 },
{ label: "10 min", seconds: 600 },
{ label: "15 min", seconds: 900 },
];

View File

@@ -8,6 +8,7 @@
import Titlebar from "$lib/components/Titlebar.svelte";
import ToastViewport from "$lib/components/ToastViewport.svelte";
import ResizeHandles from "$lib/components/ResizeHandles.svelte";
import FocusTimer from "$lib/components/FocusTimer.svelte";
import { hasTauriRuntime } from "$lib/utils/runtime.js";
import { loadOsInfo, isLinux } from "$lib/utils/osInfo.js";
import { page, settings, saveSettings } from "$lib/stores/page.svelte.js";
@@ -396,6 +397,13 @@
in the bottom-right of the viewport. (Day 3 of the upgrade plan) -->
<ToastViewport />
<!-- Global focus-timer overlay. Renders nothing until a `kon:start-timer`
event fires; then pins a shrinking colour ring to the top-right.
Phase 1 of the 2026-04-23 feature-complete roadmap — closes the
visual-time-representation gap from docs/brief/feature-set.md and
wires the dangling emit in MicroSteps.svelte. -->
<FocusTimer />
<!-- Invisible resize margins for frameless (macOS/Windows). On Linux we
use native decorations, so ResizeHandles would compete with the
compositor's own resize and is suppressed. -->