This repository has been archived on 2026-11-18. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
everythingbutwork/apps/web/src/components/time/TimerPill.tsx
T
Raffael SheikhandClaude Opus 4.8 a1cf6f3883
ci / quality (push) Failing after 45s
ci / build (push) Has been skipped
deploy / deploy (push) Successful in 53s
chore(format): Prettier über das gesamte Repo
Behebt die rote CI (format:check schlug an 36 Alt-Bestand-Dateien fehl:
migrations/meta-Snapshots, seed.ts, schemas/lead.ts, README u. a.) und erzwingt
nebenbei einen frischen web-Build beim Auto-Deploy (apps/web-Dateien geaendert
-> COPY-Layer invalidiert -> Vite baut neu).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 17:50:07 +02:00

296 lines
10 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import { Play, Square, Plus } from 'lucide-react';
import { clsx } from 'clsx';
import { toast } from 'sonner';
import { trpc } from '../../lib/trpc';
import { formatDuration } from '../../lib/format-duration';
import { TIME_CATEGORIES } from '../../lib/time-categories';
const CATEGORY_LABEL: Record<string, string> = Object.fromEntries(
TIME_CATEGORIES.map((c) => [c.value, c.label]),
);
const CATEGORY_DOT: Record<string, string> = {
focus: 'bg-[var(--color-ink)]',
meeting: 'bg-[var(--color-ampel-amber-fg)]',
admin: 'bg-[var(--color-ink-muted)]',
learning: 'bg-[var(--color-ampel-green-fg)]',
break: 'bg-[var(--color-ampel-amber-fg)]',
other: 'bg-[var(--color-border-strong)]',
};
type Active = {
id: string;
startedAt: string | Date;
category: string;
description: string | null;
todoId: string | null;
todoTitle: string | null;
};
function labelOf(a: Active): string {
return a.description || a.todoTitle || CATEGORY_LABEL[a.category] || 'Timer';
}
function elapsedOf(a: Active): number {
return Math.max(0, Math.round((Date.now() - new Date(a.startedAt).getTime()) / 1000));
}
export function TimerPill() {
const utils = trpc.useUtils();
const nowQuery = trpc.time.now.useQuery(undefined, { refetchInterval: 30_000 });
const todayQuery = trpc.dayEntry.today.useQuery();
const [pickerOpen, setPickerOpen] = useState(false);
const [panelOpen, setPanelOpen] = useState(false);
const [, setTick] = useState(0);
const pickerRef = useRef<HTMLDivElement>(null);
const active: Active[] = nowQuery.data ?? [];
// Sekunden-Tick nur wenn etwas läuft.
useEffect(() => {
if (active.length === 0) return undefined;
const id = window.setInterval(() => setTick((t) => t + 1), 1000);
return () => window.clearInterval(id);
}, [active.length]);
useEffect(() => {
if (!pickerOpen && !panelOpen) return undefined;
function onClick(e: MouseEvent) {
if (pickerRef.current && !pickerRef.current.contains(e.target as Node)) {
setPickerOpen(false);
setPanelOpen(false);
}
}
function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') {
setPickerOpen(false);
setPanelOpen(false);
}
}
document.addEventListener('mousedown', onClick);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onClick);
document.removeEventListener('keydown', onKey);
};
}, [pickerOpen, panelOpen]);
const invalidate = async () => {
await utils.time.now.invalidate();
await utils.time.listToday.invalidate();
};
const startMutation = trpc.time.start.useMutation({
onSuccess: async () => {
await invalidate();
setPickerOpen(false);
toast('Timer läuft.');
},
});
const count = active.length;
const longest = count > 0 ? Math.max(...active.map(elapsedOf)) : 0;
return (
<div className="relative flex items-center gap-1.5" ref={pickerRef}>
{count > 0 ? (
<button
type="button"
onClick={() => setPanelOpen((o) => !o)}
aria-expanded={panelOpen}
className="inline-flex items-center gap-2 rounded-full bg-[var(--color-ampel-red-bg)] px-2.5 py-1 text-xs font-medium text-[var(--color-ampel-red-fg)] hover:bg-red-200"
title={count === 1 ? 'Timer' : `${count} Timer laufen`}
>
<span className="flex h-1.5 w-1.5 items-center justify-center">
<span className="absolute h-1.5 w-1.5 animate-ping rounded-full bg-[var(--color-ampel-red-fg)] opacity-60" />
<span className="relative h-1.5 w-1.5 rounded-full bg-[var(--color-ampel-red-fg)]" />
</span>
<span className="max-w-[160px] truncate">
{count === 1 ? labelOf(active[0]!) : `${count} Timer`}
</span>
<span className="font-mono tabular-nums">{formatDuration(longest)}</span>
</button>
) : (
<button
type="button"
onClick={() => setPickerOpen((o) => !o)}
aria-expanded={pickerOpen}
aria-haspopup="menu"
className="inline-flex items-center gap-1 rounded-full bg-black/5 px-2.5 py-1 text-xs font-medium text-[var(--color-ink-muted)] hover:bg-black/10 hover:text-[var(--color-ink)]"
title="Timer starten"
>
<Play size={10} fill="currentColor" />
<span>Start</span>
</button>
)}
{pickerOpen && (
<QuickPicker
todos={(todayQuery.data?.todos ?? []).filter((t) => t.status === 'open')}
onClose={() => setPickerOpen(false)}
onStart={(payload) => startMutation.mutate(payload)}
pending={startMutation.isPending}
/>
)}
{panelOpen && count > 0 && (
<TimersPanel
active={active}
onAdd={() => {
setPanelOpen(false);
setPickerOpen(true);
}}
onChanged={invalidate}
/>
)}
</div>
);
}
function TimersPanel({
active,
onAdd,
onChanged,
}: {
active: Active[];
onAdd: () => void;
onChanged: () => Promise<void>;
}) {
const stopMutation = trpc.time.stop.useMutation({ onSuccess: onChanged });
return (
<div className="absolute right-0 top-full z-40 mt-2 w-[320px] rounded-[var(--radius-lg)] border border-[var(--color-border)] bg-[var(--color-surface-elevated)] p-3 shadow-[var(--shadow-lg)]">
<p className="px-1 text-xs font-medium text-[var(--color-ink-muted)]">
Läuft gerade ({active.length})
</p>
<div className="mt-2 space-y-1.5">
{active.map((a) => (
<div key={a.id} className="rounded-[var(--radius-md)] px-1 py-1">
<div className="flex items-center gap-2">
<span className={clsx('h-2 w-2 shrink-0 rounded-full', CATEGORY_DOT[a.category])} />
<span className="flex-1 truncate text-sm">{labelOf(a)}</span>
<span className="font-mono text-xs tabular-nums text-[var(--color-ink-muted)]">
{formatDuration(elapsedOf(a))}
</span>
<button
type="button"
onClick={() => stopMutation.mutate({ id: a.id })}
aria-label="Stoppen"
title="Stoppen"
className="inline-flex h-6 w-6 items-center justify-center rounded-[var(--radius-md)] text-[var(--color-ink-muted)] hover:bg-black/5 hover:text-[var(--color-ink)]"
>
<Square size={12} fill="currentColor" />
</button>
</div>
</div>
))}
</div>
<button
type="button"
onClick={onAdd}
className="mt-2 flex w-full items-center gap-2 border-t border-[var(--color-border)] px-1 pt-2 text-sm text-[var(--color-ink-muted)] hover:text-[var(--color-ink)]"
>
<Plus size={12} /> Weiteren Task starten
</button>
</div>
);
}
function QuickPicker({
todos,
onClose,
onStart,
pending,
}: {
todos: Array<{ id: string; title: string }>;
onClose: () => void;
onStart: (input: {
todoId?: string;
category: 'focus' | 'meeting' | 'admin' | 'learning' | 'break' | 'other';
description?: string;
}) => void;
pending: boolean;
}) {
const [description, setDescription] = useState('');
return (
<div
role="menu"
className="absolute right-0 top-full z-40 mt-2 w-[320px] rounded-[var(--radius-lg)] border border-[var(--color-border)] bg-[var(--color-surface-elevated)] p-3 shadow-[var(--shadow-lg)]"
>
<p className="px-1 text-xs font-medium text-[var(--color-ink-muted)]">Was machst du jetzt?</p>
{todos.length > 0 && (
<div className="mt-2 space-y-0.5">
<p className="px-1 text-[10px] uppercase tracking-wide text-[var(--color-ink-faint)]">
Deine ToDos heute
</p>
{todos.map((t) => (
<button
key={t.id}
type="button"
onClick={() => onStart({ todoId: t.id, category: 'focus' })}
disabled={pending}
className="flex w-full items-center gap-2 rounded-[var(--radius-md)] px-2 py-1.5 text-left text-sm hover:bg-black/5"
>
<Play size={10} className="text-[var(--color-ink-muted)]" />
<span className="truncate">{t.title}</span>
</button>
))}
</div>
)}
<div className="mt-3 space-y-0.5">
<p className="px-1 text-[10px] uppercase tracking-wide text-[var(--color-ink-faint)]">
Andere Tätigkeit
</p>
{TIME_CATEGORIES.filter((c) => c.value !== 'focus').map((c) => (
<button
key={c.value}
type="button"
onClick={() =>
onStart({ category: c.value, description: description.trim() || undefined })
}
disabled={pending}
className="flex w-full items-center gap-2 rounded-[var(--radius-md)] px-2 py-1.5 text-left text-sm hover:bg-black/5"
>
<Play size={10} className="text-[var(--color-ink-muted)]" />
<span>{c.label}</span>
</button>
))}
</div>
<div className="mt-3 border-t border-[var(--color-border)] pt-2">
<label
htmlFor="timer-freetext"
className="block px-1 text-[10px] uppercase tracking-wide text-[var(--color-ink-faint)]"
>
Mit freiem Text
</label>
<div className="mt-1 flex gap-1.5">
<input
id="timer-freetext"
type="text"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="z. B. Kunde Schmidt — Call"
maxLength={200}
className="flex-1 rounded-[var(--radius-md)] border border-[var(--color-border)] bg-white px-2 py-1.5 text-sm"
/>
<button
type="button"
disabled={pending || !description.trim()}
onClick={() => onStart({ category: 'focus', description: description.trim() })}
className="inline-flex items-center gap-1 rounded-[var(--radius-md)] bg-[var(--color-brand)] px-3 py-1.5 text-xs font-medium text-[var(--color-brand-fg)] disabled:opacity-50"
>
<Plus size={12} /> Start
</button>
</div>
</div>
<button
type="button"
onClick={onClose}
className="mt-2 block w-full rounded-[var(--radius-md)] px-2 py-1 text-xs text-[var(--color-ink-faint)] hover:bg-black/5"
>
Abbrechen
</button>
</div>
);
}