Files
MindSift/frontend/src/features/capture/InstantCaptureBar.tsx
T
sandrodach d39d1d1122
MindSift CI & Docker Release / Build, Test in Container & Push (push) Successful in 57s
feat: complete workspace, triage, outliner and sharing overhaul (tasks 1-26)
2026-10-27 19:46:46 +01:00

576 lines
23 KiB
TypeScript

import React, { useEffect, useRef, useState } from 'react';
import {
Mic,
MicOff,
ArrowUp,
Sparkles,
Calendar,
Check,
CheckSquare,
ShoppingCart,
FileText,
Layers,
ChevronDown,
AlertTriangle,
Flame,
} from 'lucide-react';
import { PriorityLevel, SharedList, Thought } from '../../lib/types';
import { api, triggerHaptic } from '../../lib/api';
export type CaptureTarget = 'inbox' | 'task' | 'list_item' | 'document';
interface InstantCaptureBarProps {
onCaptured: (thought: Thought, target?: CaptureTarget) => void;
lists?: SharedList[];
autoFocusTrigger?: number;
inlineOptions?: boolean;
defaultShowOptions?: boolean;
hideTargetPicker?: boolean;
fixedTarget?: CaptureTarget;
}
export const InstantCaptureBar: React.FC<InstantCaptureBarProps> = ({
onCaptured,
lists = [],
autoFocusTrigger = 0,
inlineOptions = false,
defaultShowOptions = false,
hideTargetPicker = false,
fixedTarget,
}) => {
const [content, setContent] = useState('');
const [priority, setPriority] = useState<PriorityLevel>('normal');
const [dueDate, setDueDate] = useState('');
const [target, setTarget] = useState<CaptureTarget>(fixedTarget || 'inbox');
const [targetListId, setTargetListId] = useState<string>('');
const [showOptions, setShowOptions] = useState(defaultShowOptions || hideTargetPicker);
const [isListening, setIsListening] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [justSavedLabel, setJustSavedLabel] = useState<string | null>(null);
const [isMultiline, setIsMultiline] = useState(false);
const inputRef = useRef<HTMLTextAreaElement>(null);
const containerRef = useRef<HTMLFormElement>(null);
const recognitionRef = useRef<any>(null);
const baseVoiceTextRef = useRef('');
const hasVoiceInputRef = useRef(false);
const adjustHeight = (el?: HTMLTextAreaElement | null) => {
const targetEl = el || inputRef.current;
if (!targetEl) return;
targetEl.style.height = 'auto';
if (targetEl.value) {
const scrollH = targetEl.scrollHeight;
targetEl.style.height = `${Math.min(scrollH, 140)}px`;
setIsMultiline(targetEl.value.includes('\n') || scrollH > 28);
} else {
setIsMultiline(false);
}
};
useEffect(() => {
adjustHeight();
}, [content]);
useEffect(() => {
inputRef.current?.focus();
}, [autoFocusTrigger]);
useEffect(() => {
if (!targetListId && lists.length > 0) {
setTargetListId(lists[0].id);
}
}, [lists, targetListId]);
// Close dropdown on outside click
useEffect(() => {
if (inlineOptions) return;
const handleClickOutside = (e: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setShowOptions(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [inlineOptions]);
// Global keyboard shortcut: 'c' or '/' focuses the Instant Capture input immediately
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const el = e.target as HTMLElement;
const isEditing =
el.tagName === 'INPUT' ||
el.tagName === 'TEXTAREA' ||
el.isContentEditable;
if (!isEditing && (e.key === 'c' || e.key === 'C' || e.key === '/')) {
e.preventDefault();
inputRef.current?.focus();
} else if (e.key === 'Escape' && document.activeElement === inputRef.current) {
setContent('');
setIsMultiline(false);
setShowOptions(false);
inputRef.current?.blur();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
const toggleVoiceDictation = () => {
const SpeechRecognition =
(window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
if (!SpeechRecognition) {
alert('Spracheingabe wird von diesem Browser nicht direkt unterstützt (bitte Chrome, Edge oder Safari nutzen).');
return;
}
if (isListening && recognitionRef.current) {
recognitionRef.current.stop();
setIsListening(false);
return;
}
try {
baseVoiceTextRef.current = content.replace(/\s*\[…\]$/, '').trim();
hasVoiceInputRef.current = true;
const recognition = new SpeechRecognition();
recognition.lang = 'de-DE';
recognition.continuous = false;
recognition.interimResults = true;
recognition.onstart = () => {
setIsListening(true);
triggerHaptic(20);
};
recognition.onresult = (event: any) => {
let transcript = '';
for (let i = 0; i < event.results.length; i++) {
transcript += event.results[i][0].transcript;
}
const base = baseVoiceTextRef.current;
setContent(base ? `${base} ${transcript}` : transcript);
};
recognition.onerror = () => {
setIsListening(false);
};
recognition.onend = () => {
setIsListening(false);
inputRef.current?.focus();
};
recognitionRef.current = recognition;
recognition.start();
} catch {
setIsListening(false);
}
};
const executeCapture = async (
overrideTarget?: CaptureTarget,
overrideListId?: string
) => {
const trimmed = content.trim();
if (!trimmed || isSubmitting) return;
const effectiveTarget = fixedTarget || overrideTarget || target;
const effectiveListId =
overrideListId || targetListId || (lists.length > 0 ? lists[0].id : '');
const capturedPriority = priority;
const capturedDueDate = dueDate;
const capturedSource = hasVoiceInputRef.current || isListening ? 'voice' : 'manual';
hasVoiceInputRef.current = false;
// Optimistically clear input immediately so the UI feels instant (<10ms) in all browsers
setContent('');
setIsMultiline(false);
setPriority('normal');
setDueDate('');
setTarget(fixedTarget || 'inbox');
setShowOptions(defaultShowOptions || hideTargetPicker);
setIsSubmitting(true);
triggerHaptic(15);
if (inputRef.current) {
inputRef.current.style.height = 'auto';
}
const savedMsg =
effectiveTarget === 'task'
? 'Als Aufgabe!'
: effectiveTarget === 'list_item'
? 'Auf Liste!'
: effectiveTarget === 'document'
? 'Als Notiz!'
: 'In Triage!';
setJustSavedLabel(savedMsg);
setTimeout(() => setJustSavedLabel(null), 1600);
inputRef.current?.focus();
try {
const created = await api.captureThought(
trimmed,
capturedPriority,
capturedSource,
capturedDueDate,
{
target: effectiveTarget,
targetListId: effectiveTarget === 'list_item' ? effectiveListId : '',
}
);
onCaptured(created, effectiveTarget);
} catch {
// Restore text if capture unexpectedly failed completely
setContent(trimmed);
} finally {
setIsSubmitting(false);
}
};
const handleSubmit = async (e?: React.FormEvent) => {
if (e) e.preventDefault();
await executeCapture();
};
const selectedList = lists.find((l) => l.id === targetListId) || lists[0];
const getTargetLabel = () => {
if (target === 'task') return 'Direkt-Aufgabe';
if (target === 'list_item') return selectedList ? `${selectedList.icon} ${selectedList.title}` : 'Auf Liste';
if (target === 'document') return 'Direkt-Notiz';
return 'Quick Dump';
};
return (
<div className="w-full">
<form ref={containerRef} onSubmit={handleSubmit} className="relative">
{/* Quick-Capture Input Bar (Radius controlled by --radius-pill / multiline) */}
<div
className={`flex ${
isMultiline ? 'items-end py-1.5 min-h-[36px]' : 'items-center h-9'
} pl-1.5 pr-1.5 bg-panel border capture-pill ${
isMultiline ? 'capture-bar-multiline' : 'rounded-full'
} transition-all duration-150 ${
isListening
? 'border-accent bg-panel'
: 'border-border focus-within:border-accent'
}`}
>
<div
className={`w-6 h-6 capture-pill rounded-full bg-accent text-on-accent flex items-center justify-center mr-2 flex-shrink-0 ${
isMultiline ? 'self-start mt-1' : ''
}`}
>
<Sparkles className="w-3 h-3" />
</div>
<textarea
ref={inputRef}
rows={1}
value={content}
onChange={(e) => {
setContent(e.target.value);
adjustHeight(e.target);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && (!e.shiftKey || e.ctrlKey || e.metaKey)) {
e.preventDefault();
executeCapture();
}
}}
placeholder={
isListening
? 'Ich höre zu…'
: hideTargetPicker || fixedTarget === 'inbox'
? 'Quick Dump erfassen… (Enter zum Speichern)'
: target === 'task'
? 'Neue Aufgabe direkt anlegen… (Enter / Shift+Enter für Mehrzeiler)'
: target === 'list_item'
? `Eintrag direkt zu "${selectedList?.title || 'Liste'}" hinzufügen…`
: target === 'document'
? 'Neue Workspace-Notiz direkt anlegen… (Enter / Shift+Enter für Mehrzeiler)'
: 'Quick Dump: Gedanke reinrotzen… (C / Enter, Shift+Enter für Mehrzeiler)'
}
className="w-full bg-transparent text-main placeholder-faint text-xs sm:text-sm focus:outline-none resize-none leading-5 py-0.5 overflow-y-auto"
style={{ minHeight: '22px', maxHeight: '140px' }}
autoComplete="off"
/>
<div
className={`flex items-center gap-1 ml-2 flex-shrink-0 ${
isMultiline ? 'self-end mb-0.5' : ''
}`}
>
{/* Target & Options Toggle Pill (Hidden when target picker is disabled) */}
{!hideTargetPicker && (
<button
type="button"
onClick={() => setShowOptions((prev) => !prev)}
title="Ziel wählen (Quick Dump, direkt als Aufgabe, auf Liste oder als Notiz) & Optionen"
className={`h-6 px-2.5 capture-pill rounded-full text-[11px] flex items-center gap-1 transition-colors cursor-pointer ${
showOptions || target !== 'inbox' || priority !== 'normal' || dueDate
? 'bg-accent-dim text-accent border border-accent-border font-medium'
: 'text-muted hover:text-main hover:bg-panel-elevated border border-transparent'
}`}
>
{target === 'task' ? (
<CheckSquare className="w-3 h-3" />
) : target === 'list_item' ? (
<ShoppingCart className="w-3 h-3" />
) : target === 'document' ? (
<FileText className="w-3 h-3" />
) : (
<Layers className="w-3 h-3" />
)}
<span className={`${inlineOptions ? 'inline' : 'hidden md:inline'} max-w-[110px] truncate`}>
{getTargetLabel()}
</span>
{dueDate && <span className="hidden lg:inline text-[10px] opacity-80">• {dueDate.slice(5)}</span>}
<ChevronDown className={`w-3 h-3 opacity-70 transition-transform ${showOptions ? 'rotate-180' : ''}`} />
</button>
)}
{/* Voice Dictation Button */}
<button
type="button"
onClick={toggleVoiceDictation}
title="Spracheingabe"
className={`w-6 h-6 capture-pill rounded-full flex items-center justify-center transition-colors ${
isListening
? 'bg-accent-dim text-accent'
: 'text-muted hover:text-main hover:bg-panel-elevated'
}`}
>
{isListening ? <MicOff className="w-3 h-3" /> : <Mic className="w-3 h-3" />}
</button>
{/* Instant Send Button */}
<button
type="submit"
disabled={!content.trim() || isSubmitting}
className={`h-6 px-2.5 capture-pill rounded-full font-medium text-[11px] flex items-center gap-1 transition-all ${
content.trim()
? 'bg-accent hover:bg-accent-hover text-on-accent cursor-pointer shadow-sm'
: 'bg-panel-elevated text-faint cursor-not-allowed'
}`}
>
{justSavedLabel ? (
<>
<Check className="w-3 h-3" />
<span className="inline">{justSavedLabel}</span>
</>
) : (
<>
<ArrowUp className="w-3 h-3" />
<span className="inline">
{hideTargetPicker || (fixedTarget || target) === 'inbox'
? 'Quick Dump'
: target === 'task'
? 'Als Aufgabe'
: target === 'list_item'
? 'Auf Liste'
: target === 'document'
? 'Als Notiz'
: 'Dump'}
</span>
</>
)}
</button>
</div>
</div>
{/* Expandable Target & Metadata Panel (Theme-controlled Dropdown or Inline) */}
{showOptions && (
<div
className={
inlineOptions
? 'mt-3 p-3 panel-surface border border-border rounded-xl space-y-3 text-xs animate-in fade-in duration-150'
: 'absolute top-full left-0 right-0 mt-1.5 z-50 p-3 panel-surface shadow-panel space-y-3 text-xs'
}
>
{/* Row 1: Where should this entry go? (Omitted when hideTargetPicker is true) */}
{!hideTargetPicker && (
<>
<div>
<div className="flex items-center justify-between mb-1.5">
<span className="text-[11px] font-semibold uppercase tracking-wider text-muted">
Wohin damit? {content.trim() ? '(Klick speichert sofort oder wählt Ziel)' : '(Ziel für Eingabe wählen)'}
</span>
<span className="text-[11px] text-faint">
Standard: Quick Dump für späteres Swipen
</span>
</div>
<div className="grid grid-cols-2 sm:grid-cols-4 gap-1.5">
{/* Option 1: Quick Dump (Triage) */}
<button
type="button"
onClick={() => {
setTarget('inbox');
if (content.trim()) {
executeCapture('inbox');
}
}}
className={`min-h-[36px] px-2.5 border rounded-btn flex items-center gap-1.5 text-left transition-colors cursor-pointer ${
target === 'inbox'
? 'bg-accent-dim border-accent text-main font-medium'
: 'bg-canvas border-border text-muted hover:text-main hover:bg-panel-hover'
}`}
>
<Layers className="w-3.5 h-3.5 text-accent flex-shrink-0" />
<span className="truncate">Quick Dump (Triage)</span>
</button>
{/* Option 2: Direct Task */}
<button
type="button"
onClick={() => {
setTarget('task');
if (content.trim()) {
executeCapture('task');
}
}}
className={`min-h-[36px] px-2.5 border rounded-btn flex items-center gap-1.5 text-left transition-colors cursor-pointer ${
target === 'task'
? 'bg-accent-dim border-accent text-main font-medium'
: 'bg-canvas border-border text-muted hover:text-main hover:bg-panel-hover'
}`}
>
<CheckSquare className="w-3.5 h-3.5 text-accent flex-shrink-0" />
<span className="truncate">Direkt als Aufgabe</span>
</button>
{/* Option 3: Direct List Item */}
<button
type="button"
onClick={() => {
setTarget('list_item');
if (!targetListId && lists.length > 0) {
setTargetListId(lists[0].id);
}
}}
className={`min-h-[36px] px-2.5 border rounded-btn flex items-center gap-1.5 text-left transition-colors cursor-pointer ${
target === 'list_item'
? 'bg-accent-dim border-accent text-main font-medium'
: 'bg-canvas border-border text-muted hover:text-main hover:bg-panel-hover'
}`}
>
<ShoppingCart className="w-3.5 h-3.5 text-accent flex-shrink-0" />
<span className="truncate">Direkt auf Liste…</span>
</button>
{/* Option 4: Direct Workspace Note */}
<button
type="button"
onClick={() => {
setTarget('document');
if (content.trim()) {
executeCapture('document');
}
}}
className={`min-h-[36px] px-2.5 border rounded-btn flex items-center gap-1.5 text-left transition-colors cursor-pointer ${
target === 'document'
? 'bg-accent-dim border-accent text-main font-medium'
: 'bg-canvas border-border text-muted hover:text-main hover:bg-panel-hover'
}`}
>
<FileText className="w-3.5 h-3.5 text-accent flex-shrink-0" />
<span className="truncate">Direkt als Notiz</span>
</button>
</div>
</div>
{/* Optional Sub-Row: Shared List Picker */}
{lists.length > 0 && (
<div className="pt-2 border-t border-border flex flex-wrap items-center gap-1.5">
<span className="text-muted mr-1 flex items-center gap-1">
<ShoppingCart className="w-3 h-3 text-accent" />
Liste:
</span>
{lists.map((lst) => {
const isSelected = target === 'list_item' && targetListId === lst.id;
return (
<button
key={lst.id}
type="button"
onClick={() => {
setTarget('list_item');
setTargetListId(lst.id);
if (content.trim()) {
executeCapture('list_item', lst.id);
}
}}
className={`min-h-[30px] px-2.5 border rounded-btn text-xs flex items-center gap-1.5 transition-colors cursor-pointer ${
isSelected
? 'bg-accent text-on-accent border-accent font-medium'
: 'bg-canvas border-border text-muted hover:text-main hover:bg-panel-hover'
}`}
>
<span>{lst.icon}</span>
<span>{lst.title}</span>
</button>
);
})}
</div>
)}
</>
)}
{/* Row 2: Priority & Due Date */}
<div className={`${!hideTargetPicker ? 'pt-2 border-t border-border' : ''} flex flex-wrap items-center justify-between gap-2.5`}>
<div className="flex flex-wrap items-center gap-1.5">
<span className="text-muted text-[11px] font-semibold mr-1">Priorität:</span>
{(['low', 'normal', 'high', 'urgent'] as PriorityLevel[]).map((p) => {
const config: Record<PriorityLevel, { label: string; icon?: React.ReactNode; activeClass: string }> = {
low: { label: 'Niedrig', activeClass: 'bg-canvas border-strong text-main font-semibold shadow-xs' },
normal: { label: 'Normal', activeClass: 'bg-accent/15 border-accent text-accent font-semibold shadow-xs' },
high: { label: 'Wichtig', icon: <AlertTriangle className="w-3 h-3 text-status-warn" />, activeClass: 'bg-status-warn/15 border-status-warn text-status-warn font-semibold shadow-xs' },
urgent: { label: 'Dringend', icon: <Flame className="w-3 h-3 text-status-err" />, activeClass: 'bg-status-err/15 border-status-err text-status-err font-semibold shadow-xs' },
};
const active = priority === p;
const item = config[p];
return (
<button
key={p}
type="button"
onClick={() => {
triggerHaptic(10);
setPriority(p);
}}
className={`min-h-[30px] px-2.5 py-1 border rounded-btn text-xs flex items-center gap-1 transition-colors cursor-pointer ${
active
? item.activeClass
: 'bg-canvas text-muted hover:text-main border-border'
}`}
>
{item.icon}
<span>{item.label}</span>
</button>
);
})}
</div>
<div className="flex items-center gap-1.5">
<span className="text-muted text-[11px] font-semibold flex items-center gap-1">
<Calendar className="w-3.5 h-3.5 text-accent" />
Fällig am:
</span>
<input
type="date"
value={dueDate}
onChange={(e) => setDueDate(e.target.value)}
className="input-field px-2.5 py-1 text-xs min-h-[30px]"
/>
</div>
</div>
</div>
)}
</form>
</div>
);
};