feat: complete triage, multi-task lists, kanban, workspace wiki, and admin management
MindSift CI & Docker Release / Build, Test in Container & Push (push) Failing after 16s

This commit is contained in:
sandrodach committed 2026-10-24 22:08:43 +02:00
1 parent 5c4e130862
commit 4ef71b61cd
12 files changed
+3940 -664

No files matched your search

@@ -0,0 +1,953 @@
import React, { useEffect, useState } from 'react';
import {
X,
User as UserIcon,
Shield,
Bell,
Key,
Users,
Settings as SettingsIcon,
Plus,
Trash2,
Check,
Copy,
RefreshCw,
LogOut,
Terminal,
Download,
AlertTriangle,
Lock,
Share2,
} from 'lucide-react';
import { APIKey, Organization, SystemSettings, Team, User } from '../../lib/types';
import { api, clearToken, getToken, triggerHaptic } from '../../lib/api';
interface SettingsModalProps {
currentUser: User | null;
onClose: () => void;
onUserUpdated: (u: User) => void;
onLoggedOut: () => void;
}
type SettingsTab = 'profile' | 'alarms' | 'webhooks' | 'teams' | 'admin';
export const SettingsModal: React.FC<SettingsModalProps> = ({
currentUser,
onClose,
onUserUpdated,
onLoggedOut,
}) => {
const [activeTab, setActiveTab] = useState<SettingsTab>('profile');
// --- Profile State ---
const [displayName, setDisplayName] = useState(currentUser?.displayName || '');
const [email, setEmail] = useState(currentUser?.email || '');
const [newPassword, setNewPassword] = useState('');
const [profileMsg, setProfileMsg] = useState<{ type: 'ok' | 'err'; text: string } | null>(null);
// --- Alarms / Discord State ---
const [discordWebhookUrl, setDiscordWebhookUrl] = useState(currentUser?.discordWebhookUrl || '');
const [notifyBeforeMinutes, setNotifyBeforeMinutes] = useState(currentUser?.notifyBeforeMinutes || 30);
const [alarmMsg, setAlarmMsg] = useState<{ type: 'ok' | 'err'; text: string } | null>(null);
const [testingDiscord, setTestingDiscord] = useState(false);
// --- Webhooks / API Keys State ---
const [apiKeys, setApiKeys] = useState<APIKey[]>([]);
const [newKeyName, setNewKeyName] = useState('');
const [newlyCreatedKey, setNewlyCreatedKey] = useState<string | null>(null);
const [copiedKey, setCopiedKey] = useState(false);
// --- Organizations & Teams State ---
const [orgs, setOrgs] = useState<Organization[]>([]);
const [teams, setTeams] = useState<Team[]>([]);
const [newOrgName, setNewOrgName] = useState('');
const [selectedOrgId, setSelectedOrgId] = useState('');
const [newTeamName, setNewTeamName] = useState('');
const [newTeamDesc, setNewTeamDesc] = useState('');
// --- Admin State ---
const [adminUsers, setAdminUsers] = useState<User[]>([]);
const [systemSettings, setSystemSettings] = useState<SystemSettings>({
sharingMode: 'teams_only',
allowRegistration: true,
instanceName: 'MindSift',
});
const [newAdminUserEmail, setNewAdminUserEmail] = useState('');
const [newAdminUserPassword, setNewAdminUserPassword] = useState('');
const [newAdminUserDisplayName, setNewAdminUserDisplayName] = useState('');
const [newAdminUserRole, setNewAdminUserRole] = useState<'member' | 'admin'>('member');
const [resetPwdUserId, setResetPwdUserId] = useState<string | null>(null);
const [resetPwdVal, setResetPwdVal] = useState('');
useEffect(() => {
loadKeys();
loadOrgsAndTeams();
if (currentUser?.role === 'admin') {
loadAdminData();
}
}, []);
const loadKeys = async () => {
try {
const keys = await api.getAPIKeys();
setApiKeys(keys);
} catch {
// ignore
}
};
const loadOrgsAndTeams = async () => {
try {
const [o, t] = await Promise.all([api.getOrganizations(), api.getUserTeams()]);
setOrgs(o);
setTeams(t);
if (o.length > 0 && !selectedOrgId) {
setSelectedOrgId(o[0].id);
}
} catch {
// ignore
}
};
const loadAdminData = async () => {
try {
const [u, s] = await Promise.all([api.adminGetUsers(), api.adminGetSettings()]);
setAdminUsers(u);
setSystemSettings(s);
} catch {
// ignore
}
};
// --- Profile Handlers ---
const handleSaveProfile = async (e: React.FormEvent) => {
e.preventDefault();
setProfileMsg(null);
try {
const patch: any = { displayName, email };
if (newPassword.trim()) {
patch.password = newPassword.trim();
}
const updated = await api.updateSettings(patch);
onUserUpdated(updated);
setNewPassword('');
setProfileMsg({ type: 'ok', text: 'Profil erfolgreich gespeichert.' });
} catch (err: any) {
setProfileMsg({ type: 'err', text: err.message || 'Fehler beim Speichern' });
}
};
// --- Alarms Handlers ---
const handleSaveAlarms = async (e: React.FormEvent) => {
e.preventDefault();
setAlarmMsg(null);
try {
const updated = await api.updateSettings({
discordWebhookUrl: discordWebhookUrl.trim(),
notifyBeforeMinutes: Number(notifyBeforeMinutes),
});
onUserUpdated(updated);
setAlarmMsg({ type: 'ok', text: 'Discord Alarm-Einstellungen gespeichert.' });
} catch (err: any) {
setAlarmMsg({ type: 'err', text: err.message || 'Fehler beim Speichern' });
}
};
const handleTestDiscordWebhook = async () => {
if (!discordWebhookUrl.trim()) {
setAlarmMsg({ type: 'err', text: 'Bitte zuerst eine Discord Webhook URL eingeben.' });
return;
}
setTestingDiscord(true);
setAlarmMsg(null);
try {
const res = await fetch(discordWebhookUrl.trim(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
content: '🔔 **MindSift Test-Alarm**: Verbindung zu Discord erfolgreich hergestellt!',
embeds: [
{
title: 'MindSift Aufgaben-Alarm eingerichtet',
description: 'Du erhältst hier Benachrichtigungen, wenn Aufgaben fällig werden.',
color: 3066993,
footer: { text: 'MindSift System Test' },
},
],
}),
});
if (!res.ok) {
throw new Error(`Discord antwortete mit Status ${res.status}`);
}
setAlarmMsg({ type: 'ok', text: '✅ Test-Nachricht erfolgreich an Discord gesendet!' });
} catch (err: any) {
setAlarmMsg({ type: 'err', text: `Fehler: ${err.message}` });
} finally {
setTestingDiscord(false);
}
};
// --- Webhook / Key Handlers ---
const handleCreateAPIKey = async (e: React.FormEvent) => {
e.preventDefault();
triggerHaptic(15);
try {
const created = await api.createAPIKey(newKeyName.trim() || 'Home Assistant / Script');
if (created.rawKey) {
setNewlyCreatedKey(created.rawKey);
}
setNewKeyName('');
loadKeys();
} catch (err: any) {
alert(err.message);
}
};
const handleDeleteAPIKey = async (id: string) => {
if (!window.confirm('Schlüssel widerrufen?')) return;
await api.deleteAPIKey(id);
loadKeys();
};
const handleCopy = (text: string) => {
navigator.clipboard.writeText(text);
setCopiedKey(true);
setTimeout(() => setCopiedKey(false), 2000);
};
const handleExportData = async () => {
const data = await api.exportAll();
const blob = new Blob([JSON.stringify(data, null, 2)], {
type: 'application/json;charset=utf-8',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `mindsift-backup-${new Date().toISOString().slice(0, 10)}.json`;
a.click();
URL.revokeObjectURL(url);
};
// --- Orgs & Teams Handlers ---
const handleCreateOrg = async (e: React.FormEvent) => {
e.preventDefault();
if (!newOrgName.trim()) return;
try {
const created = await api.createOrganization(newOrgName.trim());
setOrgs((prev) => [...prev, created]);
setSelectedOrgId(created.id);
setNewOrgName('');
} catch (err: any) {
alert(err.message);
}
};
const handleCreateTeam = async (e: React.FormEvent) => {
e.preventDefault();
if (!selectedOrgId || !newTeamName.trim()) return;
try {
const created = await api.createOrgTeam(selectedOrgId, newTeamName.trim(), newTeamDesc.trim());
setTeams((prev) => [...prev, created]);
setNewTeamName('');
setNewTeamDesc('');
} catch (err: any) {
alert(err.message);
}
};
// --- Admin Handlers ---
const handleUpdateSystemSettings = async (patch: Partial<SystemSettings>) => {
const next = { ...systemSettings, ...patch };
setSystemSettings(next);
try {
await api.adminUpdateSettings(next);
} catch (err: any) {
alert(err.message);
}
};
const handleAdminCreateUser = async (e: React.FormEvent) => {
e.preventDefault();
try {
const created = await api.adminCreateUser({
email: newAdminUserEmail,
password: newAdminUserPassword,
displayName: newAdminUserDisplayName || newAdminUserEmail.split('@')[0],
role: newAdminUserRole,
});
setAdminUsers((prev) => [...prev, created]);
setNewAdminUserEmail('');
setNewAdminUserPassword('');
setNewAdminUserDisplayName('');
} catch (err: any) {
alert(err.message);
}
};
const handleToggleUserActive = async (u: User) => {
try {
const updated = await api.adminUpdateUser(u.id, { isActive: !u.isActive });
setAdminUsers((prev) => prev.map((item) => (item.id === u.id ? updated : item)));
} catch (err: any) {
alert(err.message);
}
};
const handleToggleUserRole = async (u: User) => {
const nextRole = u.role === 'admin' ? 'member' : 'admin';
try {
const updated = await api.adminUpdateUser(u.id, { role: nextRole });
setAdminUsers((prev) => prev.map((item) => (item.id === u.id ? updated : item)));
} catch (err: any) {
alert(err.message);
}
};
const handleConfirmResetPassword = async (userId: string) => {
if (!resetPwdVal.trim()) return;
try {
await api.adminResetPassword(userId, resetPwdVal.trim());
alert('Passwort erfolgreich zurückgesetzt.');
setResetPwdUserId(null);
setResetPwdVal('');
} catch (err: any) {
alert(err.message);
}
};
const handleAdminDeleteUser = async (userId: string) => {
if (!window.confirm('Benutzer unwiderruflich löschen? Alle Daten dieses Nutzers werden gelöscht.')) return;
try {
await api.adminDeleteUser(userId);
setAdminUsers((prev) => prev.filter((u) => u.id !== userId));
} catch (err: any) {
alert(err.message);
}
};
const baseUrl = window.location.origin;
const curlExample = `curl -X POST ${baseUrl}/api/v1/inbox \\
-H "Authorization: Bearer ${newlyCreatedKey || apiKeys[0]?.keyPrefix || 'DEIN_API_KEY'}" \\
-H "Content-Type: application/json" \\
-d '{"content": "Server-Backup abgeschlossen #homelab #backup", "priority": "high", "target": "task"}'`;
return (
<div className="fixed inset-0 z-50 bg-black/75 backdrop-blur-sm flex items-center justify-center p-2 sm:p-4">
<div className="w-full max-w-3xl bg-panel border border-border shadow-2xl flex flex-col max-h-[90vh] overflow-hidden">
{/* Header */}
<div className="p-3 bg-canvas border-b border-border flex items-center justify-between">
<div className="flex items-center gap-2">
<SettingsIcon className="w-4 h-4 text-accent" />
<h2 className="text-sm font-bold text-white tracking-tight">
Konto-Einstellungen & Administration
</h2>
</div>
<button
onClick={onClose}
className="p-1 text-zinc-400 hover:text-white transition-colors"
>
<X className="w-4 h-4" />
</button>
</div>
{/* Modal Navigation Tabs */}
<div className="flex items-stretch border-b border-border bg-canvas overflow-x-auto no-scrollbar text-xs">
<button
onClick={() => setActiveTab('profile')}
className={`h-9 px-3.5 flex items-center gap-1.5 font-medium border-r border-border transition-colors ${
activeTab === 'profile' ? 'bg-panel text-white border-b-2 border-b-accent' : 'text-zinc-400 hover:text-white'
}`}
>
<UserIcon className="w-3.5 h-3.5" />
<span>Profil & Sicherheit</span>
</button>
<button
onClick={() => setActiveTab('alarms')}
className={`h-9 px-3.5 flex items-center gap-1.5 font-medium border-r border-border transition-colors ${
activeTab === 'alarms' ? 'bg-panel text-white border-b-2 border-b-accent' : 'text-zinc-400 hover:text-white'
}`}
>
<Bell className="w-3.5 h-3.5" />
<span>Alarme & Discord</span>
</button>
<button
onClick={() => setActiveTab('webhooks')}
className={`h-9 px-3.5 flex items-center gap-1.5 font-medium border-r border-border transition-colors ${
activeTab === 'webhooks' ? 'bg-panel text-white border-b-2 border-b-accent' : 'text-zinc-400 hover:text-white'
}`}
>
<Key className="w-3.5 h-3.5" />
<span>Webhooks & Export</span>
</button>
<button
onClick={() => setActiveTab('teams')}
className={`h-9 px-3.5 flex items-center gap-1.5 font-medium border-r border-border transition-colors ${
activeTab === 'teams' ? 'bg-panel text-white border-b-2 border-b-accent' : 'text-zinc-400 hover:text-white'
}`}
>
<Users className="w-3.5 h-3.5" />
<span>Organisationen & Teams</span>
</button>
{currentUser?.role === 'admin' && (
<button
onClick={() => setActiveTab('admin')}
className={`h-9 px-3.5 flex items-center gap-1.5 font-medium border-r border-border transition-colors ${
activeTab === 'admin' ? 'bg-panel text-accent font-semibold border-b-2 border-b-accent' : 'text-zinc-400 hover:text-white'
}`}
>
<Shield className="w-3.5 h-3.5 text-accent" />
<span>Administration</span>
</button>
)}
</div>
{/* Modal Body */}
<div className="p-4 overflow-y-auto flex-1 space-y-4 text-xs">
{/* TAB 1: PROFIL & SICHERHEIT */}
{activeTab === 'profile' && (
<div className="space-y-4 max-w-lg">
<div>
<h3 className="text-sm font-semibold text-white mb-1">Benutzerprofil bearbeiten</h3>
<p className="text-zinc-400 text-xs">
Passe deinen Anzeigenamen und dein Anmeldekennwort an.
</p>
</div>
{profileMsg && (
<div
className={`p-2 border text-xs ${
profileMsg.type === 'ok'
? 'bg-blue-900/20 border-accent text-blue-200'
: 'bg-red-900/20 border-red-500 text-red-200'
}`}
>
{profileMsg.text}
</div>
)}
<form onSubmit={handleSaveProfile} className="space-y-3">
<div>
<label className="block text-zinc-400 mb-1">Anzeigename</label>
<input
type="text"
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
required
className="w-full h-8 px-2.5 input-field text-white"
/>
</div>
<div>
<label className="block text-zinc-400 mb-1">E-Mail-Adresse</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full h-8 px-2.5 input-field text-white"
/>
</div>
<div>
<label className="block text-zinc-400 mb-1">Neues Passwort (leer lassen für keine Änderung)</label>
<input
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="Mindestens 4 Zeichen"
className="w-full h-8 px-2.5 input-field text-white"
/>
</div>
<div className="flex items-center justify-between pt-2 border-t border-border">
<button
type="button"
onClick={onLoggedOut}
className="text-red-400 hover:underline flex items-center gap-1.5 py-1"
>
<LogOut className="w-3.5 h-3.5" />
<span>Abmelden</span>
</button>
<button type="submit" className="btn-primary h-8 px-4 text-xs">
Änderungen speichern
</button>
</div>
</form>
</div>
)}
{/* TAB 2: ALARME & DISCORD */}
{activeTab === 'alarms' && (
<div className="space-y-4 max-w-lg">
<div>
<h3 className="text-sm font-semibold text-white mb-1">Aufgaben-Alarme & Discord Benachrichtigungen</h3>
<p className="text-zinc-400 text-xs leading-relaxed">
Trage deine Discord Webhook URL ein, damit der MindSift Server dich automatisch erinnert, sobald Aufgaben fällig werden.
</p>
</div>
{alarmMsg && (
<div
className={`p-2 border text-xs ${
alarmMsg.type === 'ok'
? 'bg-blue-900/20 border-accent text-blue-200'
: 'bg-red-900/20 border-red-500 text-red-200'
}`}
>
{alarmMsg.text}
</div>
)}
<form onSubmit={handleSaveAlarms} className="space-y-3">
<div>
<label className="block text-zinc-400 mb-1">Discord Webhook URL</label>
<input
type="url"
value={discordWebhookUrl}
onChange={(e) => setDiscordWebhookUrl(e.target.value)}
placeholder="https://discord.com/api/webhooks/123456789/token..."
className="w-full h-8 px-2.5 input-field text-white font-mono text-xs"
/>
</div>
<div>
<label className="block text-zinc-400 mb-1">Vorwarnzeit vor Fälligkeit</label>
<select
value={notifyBeforeMinutes}
onChange={(e) => setNotifyBeforeMinutes(Number(e.target.value))}
className="w-full h-8 px-2 input-field text-white bg-canvas"
>
<option value={0}>Direkt bei Fälligkeit</option>
<option value={15}>15 Minuten vorher</option>
<option value={30}>30 Minuten vorher</option>
<option value={60}>1 Stunde vorher</option>
<option value={1440}>1 Tag vorher</option>
</select>
</div>
<div className="flex items-center justify-between pt-2 border-t border-border">
<button
type="button"
onClick={handleTestDiscordWebhook}
disabled={testingDiscord || !discordWebhookUrl.trim()}
className="btn-action h-8 px-3 text-xs disabled:opacity-40"
>
<span>{testingDiscord ? 'Sende Test…' : 'Webhook testen'}</span>
</button>
<button type="submit" className="btn-primary h-8 px-4 text-xs">
Alarm-Einstellungen sichern
</button>
</div>
</form>
</div>
)}
{/* TAB 3: WEBHOOKS & EXPORT */}
{activeTab === 'webhooks' && (
<div className="space-y-4">
<div>
<h3 className="text-sm font-semibold text-white mb-1">Private Webhook Keys & Daten-Export</h3>
<p className="text-zinc-400 text-xs">
Erstelle API-Keys für eigene Bash-Skripte, Home Assistant oder Cronjobs, um Gedanken direkt per Curl zu erfassen.
</p>
</div>
{/* API Key Creator */}
<form onSubmit={handleCreateAPIKey} className="flex gap-2">
<input
type="text"
value={newKeyName}
onChange={(e) => setNewKeyName(e.target.value)}
placeholder="Key Bezeichnung (z.B. Smart Home, Backup Skript)…"
className="flex-1 h-8 px-2.5 input-field text-xs text-white"
/>
<button type="submit" className="btn-primary h-8 px-3 text-xs flex items-center gap-1">
<Plus className="w-3.5 h-3.5" />
<span>Key erstellen</span>
</button>
</form>
{newlyCreatedKey && (
<div className="p-2.5 bg-accent/15 border border-accent/40 flex items-center justify-between gap-2">
<div className="min-w-0">
<p className="text-[10px] text-accent font-semibold">Neuer Key (jetzt kopieren):</p>
<code className="text-xs font-mono text-white break-all">{newlyCreatedKey}</code>
</div>
<button onClick={() => handleCopy(newlyCreatedKey)} className="btn-primary h-7 px-2.5 text-xs">
{copiedKey ? 'Kopiert!' : 'Kopieren'}
</button>
</div>
)}
{/* Keys list */}
<div className="border border-border divide-y divide-border bg-canvas">
{apiKeys.length === 0 ? (
<div className="p-3 text-center text-zinc-500 text-xs">Noch keine API-Schlüssel angelegt.</div>
) : (
apiKeys.map((k) => (
<div key={k.id} className="p-2 flex items-center justify-between">
<div>
<p className="font-semibold text-white">{k.name}</p>
<p className="text-[10px] text-zinc-500 font-mono">Präfix: {k.keyPrefix}••••••••</p>
</div>
<button
onClick={() => handleDeleteAPIKey(k.id)}
className="btn-icon btn-icon-danger"
title="Key löschen"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
))
)}
</div>
{/* Interactive Curl Example */}
<div>
<div className="flex items-center justify-between mb-1">
<span className="font-semibold text-zinc-300 flex items-center gap-1">
<Terminal className="w-3 h-3 text-accent" /> Curl Schnellbefehl für eigene Skripte:
</span>
<button onClick={() => handleCopy(curlExample)} className="text-zinc-400 hover:text-white text-[10px]">
{copiedKey ? 'Kopiert!' : 'Kopieren'}
</button>
</div>
<pre className="p-2.5 bg-black/60 border border-border text-[11px] font-mono text-zinc-300 overflow-x-auto whitespace-pre">
{curlExample}
</pre>
</div>
{/* Data Export Button */}
<div className="pt-2 border-t border-border flex items-center justify-between">
<div>
<h4 className="font-semibold text-white">Vollständiger Daten-Export</h4>
<p className="text-zinc-500 text-[11px]">Sichere alle Notizen, Aufgaben, Listen und Metadaten als JSON.</p>
</div>
<button onClick={handleExportData} className="btn-action h-8 px-3 text-xs flex items-center gap-1.5">
<Download className="w-3.5 h-3.5 text-accent" />
<span>Backup herunterladen</span>
</button>
</div>
</div>
)}
{/* TAB 4: ORGANISATIONEN & TEAMS */}
{activeTab === 'teams' && (
<div className="space-y-4">
<div>
<h3 className="text-sm font-semibold text-white mb-1">Organisationen & Teams gründen</h3>
<p className="text-zinc-400 text-xs">
Erstelle Organisationen und unterteile sie in Teams, um Aufgabenlisten und Workspace-Dokumente gemeinsam zu bearbeiten.
</p>
</div>
{/* Org Creator */}
<div className="p-3 bg-canvas border border-border space-y-2">
<h4 className="font-semibold text-white">Neue Organisation</h4>
<form onSubmit={handleCreateOrg} className="flex gap-2">
<input
type="text"
value={newOrgName}
onChange={(e) => setNewOrgName(e.target.value)}
placeholder="Name der Organisation (z.B. Familie, Startup, Homelab Crew)…"
className="flex-1 h-8 px-2.5 input-field text-xs text-white"
/>
<button type="submit" className="btn-primary h-8 px-3 text-xs">
Organisation anlegen
</button>
</form>
</div>
{/* Team Creator inside Org */}
{orgs.length > 0 && (
<div className="p-3 bg-canvas border border-border space-y-2">
<h4 className="font-semibold text-white">Neues Team in Organisation</h4>
<form onSubmit={handleCreateTeam} className="space-y-2">
<div className="flex gap-2">
<select
value={selectedOrgId}
onChange={(e) => setSelectedOrgId(e.target.value)}
className="h-8 px-2 input-field text-white bg-panel"
>
{orgs.map((o) => (
<option key={o.id} value={o.id}>
{o.name}
</option>
))}
</select>
<input
type="text"
value={newTeamName}
onChange={(e) => setNewTeamName(e.target.value)}
placeholder="Team Name (z.B. DevOps, Einkauf)…"
required
className="flex-1 h-8 px-2.5 input-field text-xs text-white"
/>
</div>
<div className="flex gap-2">
<input
type="text"
value={newTeamDesc}
onChange={(e) => setNewTeamDesc(e.target.value)}
placeholder="Optionale Teambeschreibung…"
className="flex-1 h-8 px-2.5 input-field text-xs text-white"
/>
<button type="submit" className="btn-primary h-8 px-3 text-xs">
Team erstellen
</button>
</div>
</form>
</div>
)}
{/* Active Teams List */}
<div className="space-y-2">
<h4 className="font-semibold text-zinc-300">Deine Teams ({teams.length}):</h4>
<div className="border border-border divide-y divide-border bg-canvas">
{teams.length === 0 ? (
<div className="p-3 text-center text-zinc-500">Du bist noch keinem Team beigetreten.</div>
) : (
teams.map((t) => (
<div key={t.id} className="p-2.5 flex items-center justify-between">
<div>
<p className="font-bold text-white flex items-center gap-1.5">
<Users className="w-3.5 h-3.5 text-accent" />
<span>{t.name}</span>
</p>
{t.description && <p className="text-zinc-400 text-[11px]">{t.description}</p>}
</div>
<span className="text-[10px] text-zinc-500 font-mono">ID: {t.id}</span>
</div>
))
)}
</div>
</div>
</div>
)}
{/* TAB 5: ADMIN BEREICH */}
{activeTab === 'admin' && currentUser?.role === 'admin' && (
<div className="space-y-4">
<div>
<h3 className="text-sm font-semibold text-white mb-1">Server-Administration & Benutzersteuerung</h3>
<p className="text-zinc-400 text-xs">
Steuere die Instanz-Einstellungen, das Sharing-Verhalten und verwalte registrierte Benutzer.
</p>
</div>
{/* Server Sharing Isolation Setting */}
<div className="p-3 bg-canvas border border-border space-y-3">
<h4 className="font-semibold text-white flex items-center gap-1.5">
<Share2 className="w-3.5 h-3.5 text-accent" />
<span>Sharing-Isolationsmodus</span>
</h4>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
<button
type="button"
onClick={() => handleUpdateSystemSettings({ sharingMode: 'open' })}
className={`p-2.5 text-left border transition-colors ${
systemSettings.sharingMode === 'open'
? 'bg-panel border-accent text-white'
: 'border-border text-zinc-400 hover:text-white'
}`}
>
<p className="font-bold text-xs">Offen (Open)</p>
<p className="text-[10px] text-zinc-400 mt-0.5">Alle Benutzer können Spaces finden und beitreten.</p>
</button>
<button
type="button"
onClick={() => handleUpdateSystemSettings({ sharingMode: 'teams_only' })}
className={`p-2.5 text-left border transition-colors ${
systemSettings.sharingMode === 'teams_only'
? 'bg-panel border-accent text-white'
: 'border-border text-zinc-400 hover:text-white'
}`}
>
<p className="font-bold text-xs">Teams isoliert</p>
<p className="text-[10px] text-zinc-400 mt-0.5">Sharing ausschließlich innerhalb zugewiesener Teams.</p>
</button>
<button
type="button"
onClick={() => handleUpdateSystemSettings({ sharingMode: 'strict_private' })}
className={`p-2.5 text-left border transition-colors ${
systemSettings.sharingMode === 'strict_private'
? 'bg-panel border-accent text-white'
: 'border-border text-zinc-400 hover:text-white'
}`}
>
<p className="font-bold text-xs">Strikt Privat</p>
<p className="text-[10px] text-zinc-400 mt-0.5">Vollständige Benutzer-Isolation; kein Teilen möglich.</p>
</button>
</div>
<div className="flex items-center justify-between pt-2 border-t border-border">
<span className="text-zinc-300">Öffentliche Registrierung erlauben:</span>
<button
type="button"
onClick={() =>
handleUpdateSystemSettings({ allowRegistration: !systemSettings.allowRegistration })
}
className={`px-3 py-1 text-xs border ${
systemSettings.allowRegistration
? 'bg-accent/20 border-accent text-accent'
: 'bg-zinc-800 border-zinc-700 text-zinc-400'
}`}
>
{systemSettings.allowRegistration ? 'Aktiviert' : 'Deaktiviert'}
</button>
</div>
</div>
{/* User Creation by Admin */}
<div className="p-3 bg-canvas border border-border space-y-2">
<h4 className="font-semibold text-white">Neuen Benutzer anlegen</h4>
<form onSubmit={handleAdminCreateUser} className="space-y-2">
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
<input
type="email"
value={newAdminUserEmail}
onChange={(e) => setNewAdminUserEmail(e.target.value)}
placeholder="E-Mail"
required
className="h-8 px-2.5 input-field text-white"
/>
<input
type="password"
value={newAdminUserPassword}
onChange={(e) => setNewAdminUserPassword(e.target.value)}
placeholder="Initial-Passwort"
required
className="h-8 px-2.5 input-field text-white"
/>
<div className="flex gap-2">
<input
type="text"
value={newAdminUserDisplayName}
onChange={(e) => setNewAdminUserDisplayName(e.target.value)}
placeholder="Anzeigename"
className="flex-1 h-8 px-2.5 input-field text-white"
/>
<select
value={newAdminUserRole}
onChange={(e) => setNewAdminUserRole(e.target.value as any)}
className="h-8 px-2 input-field text-white bg-panel"
>
<option value="member">Member</option>
<option value="admin">Admin</option>
</select>
</div>
</div>
<div className="flex justify-end">
<button type="submit" className="btn-primary h-7 px-3 text-xs">
Benutzer erstellen
</button>
</div>
</form>
</div>
{/* Users Table */}
<div className="space-y-2">
<h4 className="font-semibold text-zinc-300">Registrierte Benutzer ({adminUsers.length}):</h4>
<div className="border border-border divide-y divide-border bg-canvas overflow-x-auto">
{adminUsers.map((u) => (
<div key={u.id} className="p-2.5 flex items-center justify-between gap-3 text-xs">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="font-bold text-white">{u.displayName}</span>
<span
className={`px-1.5 py-0.2 text-[10px] uppercase font-bold border ${
u.role === 'admin'
? 'bg-accent/20 border-accent/40 text-accent'
: 'bg-zinc-800 border-zinc-700 text-zinc-400'
}`}
>
{u.role}
</span>
{!u.isActive && (
<span className="px-1.5 py-0.2 text-[10px] bg-red-900/30 border border-red-500/40 text-red-300">
Deaktiviert
</span>
)}
</div>
<p className="text-zinc-500 text-[11px] font-mono">{u.email}</p>
{/* Reset password inline form */}
{resetPwdUserId === u.id && (
<div className="mt-2 flex items-center gap-1.5 bg-panel p-1.5 border border-border">
<input
type="password"
value={resetPwdVal}
onChange={(e) => setResetPwdVal(e.target.value)}
placeholder="Neues Passwort…"
className="h-6 px-2 input-field text-xs text-white"
/>
<button
onClick={() => handleConfirmResetPassword(u.id)}
className="btn-primary h-6 px-2 text-[10px]"
>
Speichern
</button>
<button
onClick={() => setResetPwdUserId(null)}
className="btn-action h-6 px-1.5 text-[10px]"
>
Abbrechen
</button>
</div>
)}
</div>
<div className="flex items-center gap-1.5 flex-shrink-0">
<button
onClick={() => handleToggleUserActive(u)}
className="btn-action h-7 px-2 text-[11px]"
title="Aktiv / Deaktivieren"
>
{u.isActive ? 'Deaktivieren' : 'Aktivieren'}
</button>
<button
onClick={() => handleToggleUserRole(u)}
className="btn-action h-7 px-2 text-[11px]"
title="Rolle wechseln"
>
{u.role === 'admin' ? 'Zu Member' : 'Zu Admin'}
</button>
<button
onClick={() => {
setResetPwdUserId(u.id);
setResetPwdVal('');
}}
className="btn-action h-7 px-2 text-[11px]"
title="Passwort zurücksetzen"
>
<Lock className="w-3 h-3 text-zinc-400" />
</button>
{u.id !== currentUser.id && (
<button
onClick={() => handleAdminDeleteUser(u.id)}
className="btn-icon btn-icon-danger"
title="Benutzer löschen"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
)}
</div>
</div>
))}
</div>
</div>
</div>
)}
</div>
</div>
</div>
);
};
File diff suppressed because it is too large. Load diff
+479 -178
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useState, useMemo } from 'react';
import React, { useEffect, useState, useMemo, useRef } from 'react';
import {
FilePlus,
FolderPlus,
@@ -14,6 +14,7 @@ import {
CheckSquare,
Heading1,
Heading2,
Heading3,
List,
Code,
Sparkles,
@@ -22,6 +23,14 @@ import {
X,
ArrowUp,
ArrowDown,
Bold,
Italic,
Strikethrough,
Link,
Table as TableIcon,
Percent,
Minus,
ExternalLink,
} from 'lucide-react';
import { BlockType, Document, DocumentBlock } from '../../lib/types';
import { api, triggerHaptic } from '../../lib/api';
@@ -31,7 +40,7 @@ interface WorkspaceViewProps {
onStatsChange: () => void;
}
const ICONS = ['🚀', '💡', '📄', '🏡', '⚡', '🎯', '🍕', '🛠️', '🧠', '🔥', '🏔️', '📦'];
const ICONS = ['🚀', '💡', '📄', '🏡', '⚡', '🎯', '🍕', '🛠️', '🧠', '🔥', '🏔️', '📦', '📑', '⚙️', '📊'];
interface FolderTreeItem {
path: string;
@@ -50,6 +59,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
const [searchQuery, setSearchQuery] = useState('');
const [saveState, setSaveState] = useState<'saved' | 'saving'>('saved');
const [showIconPicker, setShowIconPicker] = useState(false);
const [showWikiLinkMenu, setShowWikiLinkMenu] = useState(false);
// Folder state
const [customFolders, setCustomFolders] = useState<string[]>(() => {
@@ -65,6 +75,9 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
const [newFolderParent, setNewFolderParent] = useState<string | null>(null);
const [newFolderName, setNewFolderName] = useState('');
// Active focused block ref
const [lastFocusedBlockId, setLastFocusedBlockId] = useState<string | null>(null);
const loadDocs = async (selectId?: string | null) => {
const list = await api.getDocuments();
setDocs(list);
@@ -95,6 +108,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
await api.updateDocument(updatedDoc.id, {
title: updatedDoc.title,
icon: updatedDoc.icon,
folderPath: updatedDoc.folderPath,
blocks: updatedDoc.blocks,
tags: updatedDoc.tags,
isPinned: updatedDoc.isPinned,
@@ -105,6 +119,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
};
const getDocFolder = (doc: Document): string => {
if (doc.folderPath) return doc.folderPath;
const tag = doc.tags?.find((t) => t.startsWith('folder:'));
return tag ? tag.replace('folder:', '') : '';
};
@@ -138,12 +153,14 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
const handleCreateDoc = async (folderPath?: string | null) => {
triggerHaptic(15);
const tags = ['projekt'];
if (folderPath) {
tags.push(`folder:${folderPath}`);
const path = folderPath || '';
if (path) {
tags.push(`folder:${path}`);
}
const created = await api.createDocument({
title: 'Neues Projekt / Notiz',
icon: '💡',
folderPath: path,
blocks: [
{
id: `blk_${Date.now()}_1`,
@@ -158,100 +175,74 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
{
id: `blk_${Date.now()}_3`,
type: 'todo',
content: 'Ersten Punkt abhaken',
content: 'Ersten Meilenstein definieren',
checked: false,
},
],
tags,
isPinned: false,
});
if (folderPath) {
setExpandedFolders((prev) => {
const next = new Set(prev);
next.add(folderPath);
return next;
});
}
await loadDocs(created.id);
onStatsChange();
};
const handleDeleteDoc = async (docId: string) => {
const handleDeleteDoc = async (id: string) => {
if (!window.confirm('Dokument wirklich löschen?')) return;
triggerHaptic(20);
await api.deleteDocument(docId);
const remaining = docs.filter((d) => d.id !== docId);
await api.deleteDocument(id);
const remaining = docs.filter((d) => d.id !== id);
setDocs(remaining);
setSelectedDoc(remaining[0] || null);
onStatsChange();
};
const handleChangeDocFolder = (targetFolder: string) => {
const handleChangeDocFolder = async (folderPath: string) => {
if (!selectedDoc) return;
const cleanTags = (selectedDoc.tags || []).filter((t) => !t.startsWith('folder:'));
if (targetFolder) {
cleanTags.push(`folder:${targetFolder}`);
const cleanPath = folderPath.trim();
const updatedTags = (selectedDoc.tags || []).filter((t) => !t.startsWith('folder:'));
if (cleanPath) {
updatedTags.push(`folder:${cleanPath}`);
}
persistDocument({ ...selectedDoc, tags: cleanTags });
const updatedDoc = {
...selectedDoc,
folderPath: cleanPath,
tags: updatedTags,
};
await persistDocument(updatedDoc);
};
const handleStartCreateFolder = (parentPath: string | null = null) => {
triggerHaptic(10);
setNewFolderParent(parentPath);
const handleStartCreateFolder = (parentPath?: string | null) => {
setNewFolderParent(parentPath || null);
setNewFolderName('');
setIsCreatingFolder(true);
if (parentPath) {
setExpandedFolders((prev) => new Set([...prev, parentPath]));
}
};
const handleConfirmCreateFolder = () => {
const trimmed = newFolderName.trim().replace(/^\/+|\/+$/g, '');
const trimmed = newFolderName.trim();
if (!trimmed) {
setIsCreatingFolder(false);
return;
}
const fullPath = newFolderParent ? `${newFolderParent}/${trimmed}` : trimmed;
if (!customFolders.includes(fullPath)) {
const updated = [...customFolders, fullPath];
setCustomFolders(updated);
const next = [...customFolders, fullPath].sort((a, b) => a.localeCompare(b));
setCustomFolders(next);
try {
localStorage.setItem('mindsift_workspace_folders', JSON.stringify(updated));
localStorage.setItem('mindsift_workspace_folders', JSON.stringify(next));
} catch {
// fallback
// ignore
}
}
setExpandedFolders((prev) => {
const next = new Set(prev);
next.add(fullPath);
if (newFolderParent) next.add(newFolderParent);
return next;
});
setExpandedFolders((prev) => new Set([...prev, fullPath]));
setIsCreatingFolder(false);
setNewFolderName('');
setNewFolderParent(null);
};
const handleDeleteFolder = (folderPath: string, e: React.MouseEvent) => {
e.stopPropagation();
triggerHaptic(15);
const updated = customFolders.filter(
(p) => p !== folderPath && !p.startsWith(folderPath + '/')
);
setCustomFolders(updated);
try {
localStorage.setItem('mindsift_workspace_folders', JSON.stringify(updated));
} catch {
// fallback
}
// Keep docs safe: drop folder prefix so they fall back to root
docs.forEach((d) => {
const f = getDocFolder(d);
if (f === folderPath || f.startsWith(folderPath + '/')) {
const nextTags = (d.tags || []).filter((t) => !t.startsWith('folder:'));
persistDocument({ ...d, tags: nextTags });
}
});
};
const toggleFolder = (folderPath: string) => {
setExpandedFolders((prev) => {
const next = new Set(prev);
@@ -264,12 +255,12 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
});
};
const addBlock = (type: BlockType, afterIndex?: number) => {
const addBlock = (type: BlockType, afterIndex?: number, defaultContent = '') => {
if (!selectedDoc) return;
const newBlock: DocumentBlock = {
id: `blk_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
type,
content: '',
content: defaultContent,
checked: false,
lang: type === 'code' ? 'bash' : undefined,
};
@@ -282,6 +273,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
}
persistDocument({ ...selectedDoc, blocks: nextBlocks });
setLastFocusedBlockId(newBlock.id);
};
const updateBlock = (blockId: string, patch: Partial<DocumentBlock>) => {
@@ -308,6 +300,32 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
persistDocument({ ...selectedDoc, blocks: nextBlocks });
};
// --- TOP TOOLBAR FORMATTING HELPERS ---
const applyInlineFormat = (prefix: string, suffix = prefix) => {
if (!selectedDoc) return;
const targetBlockId = lastFocusedBlockId || selectedDoc.blocks[selectedDoc.blocks.length - 1]?.id;
if (!targetBlockId) return;
const block = selectedDoc.blocks.find((b) => b.id === targetBlockId);
if (!block) return;
const newContent = `${block.content} ${prefix}Text${suffix}`;
updateBlock(targetBlockId, { content: newContent });
};
const insertWikiLink = (targetDocTitle: string) => {
if (!selectedDoc) return;
const targetBlockId = lastFocusedBlockId || selectedDoc.blocks[selectedDoc.blocks.length - 1]?.id;
if (!targetBlockId) return;
const block = selectedDoc.blocks.find((b) => b.id === targetBlockId);
if (!block) return;
const newContent = `${block.content} [[${targetDocTitle}]]`;
updateBlock(targetBlockId, { content: newContent });
setShowWikiLinkMenu(false);
};
const handleExportMarkdown = () => {
if (!selectedDoc) return;
const lines: string[] = [`# ${selectedDoc.icon} ${selectedDoc.title}`, ''];
@@ -334,6 +352,15 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
case 'code':
lines.push('```' + (b.lang || ''), b.content, '```', '');
break;
case 'table':
lines.push(b.content, '');
break;
case 'progress':
lines.push(`<!-- progress: ${b.content} -->`, '');
break;
case 'divider':
lines.push('---', '');
break;
default:
lines.push(b.content, '');
}
@@ -348,75 +375,118 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
URL.revokeObjectURL(url);
};
const filteredDocs = docs.filter(
(d) =>
d.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
(d.content && d.content.toLowerCase().includes(searchQuery.toLowerCase()))
);
// Build recursive folder tree
const buildTree = (parentPath: string = '', depth: number = 0): FolderTreeItem[] => {
const directChildren = allFolderPaths.filter((p) => {
if (parentPath === '') {
return !p.includes('/');
// Helper to render text with clickable Wiki-Links
const renderTextWithWikiLinks = (text: string) => {
const parts = text.split(/(\[\[.*?\]\])/g);
return parts.map((part, i) => {
if (part.startsWith('[[') && part.endsWith(']]')) {
const linkTitle = part.slice(2, -2).trim();
const target = docs.find((d) => d.title.toLowerCase() === linkTitle.toLowerCase());
return (
<span
key={i}
onClick={(e) => {
e.stopPropagation();
if (target) setSelectedDoc(target);
}}
className={`inline-flex items-center gap-1 px-1.5 py-0.2 mx-0.5 border text-xs font-medium cursor-pointer transition-colors ${
target
? 'bg-accent/20 border-accent/40 text-accent hover:bg-accent/30'
: 'bg-zinc-800 border-zinc-700 text-zinc-400 hover:text-white'
}`}
title={target ? `Öffne: ${target.title}` : `Dokument "${linkTitle}" existiert noch nicht`}
>
<span>📄</span>
<span>{linkTitle}</span>
<ExternalLink className="w-2.5 h-2.5 opacity-60" />
</span>
);
}
return p.startsWith(parentPath + '/') && !p.slice(parentPath.length + 1).includes('/');
});
return directChildren.map((p) => {
const name = p.split('/').pop() || p;
const matchingDocs = filteredDocs.filter((d) => getDocFolder(d) === p);
return {
path: p,
name,
depth,
subfolders: buildTree(p, depth + 1),
docs: matchingDocs,
};
return <span key={i}>{part}</span>;
});
};
const rootTree = useMemo(() => buildTree('', 0), [allFolderPaths, filteredDocs]);
const rootDocs = useMemo(
() => filteredDocs.filter((d) => !getDocFolder(d)),
[filteredDocs]
);
// --- FOLDER TREE CALCULATION ---
const filteredDocs = useMemo(() => {
if (!searchQuery.trim()) return docs;
const q = searchQuery.toLowerCase();
return docs.filter(
(d) => d.title.toLowerCase().includes(q) || d.content.toLowerCase().includes(q)
);
}, [docs, searchQuery]);
const renderDocItem = (doc: Document, depth: number = 0) => {
const active = selectedDoc?.id === doc.id;
const { rootTree, rootDocs } = useMemo(() => {
const folderMap = new Map<string, FolderTreeItem>();
allFolderPaths.forEach((path) => {
const parts = path.split('/');
const name = parts[parts.length - 1];
folderMap.set(path, {
path,
name,
depth: parts.length - 1,
subfolders: [],
docs: [],
});
});
filteredDocs.forEach((doc) => {
const folder = getDocFolder(doc);
if (folder && folderMap.has(folder)) {
folderMap.get(folder)!.docs.push(doc);
}
});
const rootFolders: FolderTreeItem[] = [];
allFolderPaths.forEach((path) => {
const item = folderMap.get(path)!;
const lastSlash = path.lastIndexOf('/');
if (lastSlash === -1) {
rootFolders.push(item);
} else {
const parentPath = path.substring(0, lastSlash);
const parent = folderMap.get(parentPath);
if (parent) {
parent.subfolders.push(item);
} else {
rootFolders.push(item);
}
}
});
const rootOnlyDocs = filteredDocs.filter((d) => !getDocFolder(d));
return { rootTree: rootFolders, rootDocs: rootOnlyDocs };
}, [allFolderPaths, filteredDocs]);
const renderDocItem = (doc: Document, depth: number) => {
const isSelected = selectedDoc?.id === doc.id;
return (
<button
<div
key={doc.id}
type="button"
onClick={() => setSelectedDoc(doc)}
style={{ paddingLeft: `${depth * 14 + 10}px` }}
className={`w-full text-left py-1.5 pr-2 transition-colors flex items-center justify-between gap-2 border-l-2 ${
active
? 'tree-node-active'
: 'border-l-transparent text-zinc-300 hover:bg-panel-elevated hover:text-white'
style={{ paddingLeft: `${depth * 14 + 16}px` }}
className={`group flex items-center justify-between py-1.5 pr-2 border-l-2 transition-colors cursor-pointer text-xs ${
isSelected
? 'bg-panel-elevated border-accent text-white font-medium'
: 'border-transparent text-zinc-400 hover:text-white hover:bg-white/[0.02]'
}`}
>
<div className="flex items-center gap-1.5 min-w-0">
<span className="text-xs leading-none flex-shrink-0">
{doc.icon ? doc.icon : <FileText className="w-3.5 h-3.5 text-zinc-400" />}
</span>
<span className="text-xs truncate font-normal">{doc.title || 'Ohne Titel'}</span>
<div className="flex items-center gap-2 min-w-0 flex-1">
<span className="text-sm flex-shrink-0">{doc.icon}</span>
<span className="truncate">{doc.title || 'Unbenannt'}</span>
{doc.isPinned && <Pin className="w-2.5 h-2.5 text-accent flex-shrink-0" />}
</div>
{doc.isPinned && <Pin className="w-3 h-3 text-accent flex-shrink-0" />}
</button>
</div>
);
};
const renderFolder = (node: FolderTreeItem) => {
const renderFolder = (node: FolderTreeItem): React.ReactNode => {
const isExpanded = expandedFolders.has(node.path);
const isCreatingSubfolder = isCreatingFolder && newFolderParent === node.path;
const totalItems =
node.docs.length +
node.subfolders.reduce((acc, s) => acc + s.docs.length, 0);
const totalItems = node.docs.length + node.subfolders.length;
return (
<div key={node.path} className="select-none">
{/* Folder Header Row */}
<div
onClick={() => toggleFolder(node.path)}
style={{ paddingLeft: `${node.depth * 14 + 8}px` }}
@@ -439,7 +509,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
<span className="text-[10px] text-zinc-500 font-mono">({totalItems})</span>
</div>
{/* Folder Actions on Hover */}
<div className="opacity-0 group-hover:opacity-100 flex items-center gap-1 transition-opacity">
<button
type="button"
@@ -463,24 +532,15 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
>
<FolderPlus className="w-3 h-3" />
</button>
<button
type="button"
onClick={(e) => handleDeleteFolder(node.path, e)}
className="p-1 hover:bg-red-500/20 text-zinc-500 hover:text-red-400"
title="Ordner entfernen"
>
<Trash2 className="w-3 h-3" />
</button>
</div>
</div>
{/* Subfolder inline creation input */}
{isCreatingSubfolder && (
<div
style={{ paddingLeft: `${(node.depth + 1) * 14 + 8}px` }}
className="py-1 pr-2 flex items-center gap-1.5 bg-canvas"
className="py-1 pr-2 flex items-center gap-1 bg-canvas"
>
<Folder className="w-3.5 h-3.5 text-zinc-400 flex-shrink-0" />
<Folder className="w-3 h-3 text-zinc-400 flex-shrink-0" />
<input
type="text"
autoFocus
@@ -490,8 +550,8 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
if (e.key === 'Enter') handleConfirmCreateFolder();
if (e.key === 'Escape') setIsCreatingFolder(false);
}}
placeholder="Unterordnername…"
className="flex-1 h-6 px-1.5 input-field"
placeholder="Unterordner…"
className="flex-1 h-6 px-1.5 input-field text-xs"
/>
<button
type="button"
@@ -512,7 +572,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
</div>
)}
{/* Expanded Folder Content */}
{isExpanded && (
<div>
{node.subfolders.map(renderFolder)}
@@ -537,9 +596,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
<div className="grid grid-cols-1 lg:grid-cols-12 gap-2">
{/* Left Document & Folder Explorer Tree */}
<div className="lg:col-span-4 panel-surface flex flex-col self-start">
{/* Top Explorer Action Bar */}
<div className="p-2 panel-header space-y-2">
{/* Quick Search */}
<div className="relative">
<Search className="w-3.5 h-3.5 text-zinc-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
<input
@@ -551,7 +608,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
/>
</div>
{/* Monochromatic Square Action Buttons */}
<div className="flex items-center gap-1.5">
<button
type="button"
@@ -575,7 +631,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
</div>
</div>
{/* Root Folder Creation Input */}
{isCreatingFolder && newFolderParent === null && (
<div className="p-2 panel-header bg-canvas flex items-center gap-1.5">
<Folder className="w-3.5 h-3.5 text-zinc-400 flex-shrink-0" />
@@ -610,7 +665,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
</div>
)}
{/* Empty State */}
{isEmpty ? (
<div className="p-6 my-3 mx-2 border border-dashed border-border bg-canvas/50 text-center">
<Folder className="w-7 h-7 text-zinc-600 mx-auto mb-2" />
@@ -638,7 +692,6 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
</div>
</div>
) : (
/* File Explorer Tree View */
<div className="py-1 max-h-[calc(100vh-240px)] overflow-y-auto">
{rootTree.map(renderFolder)}
{rootDocs.map((doc) => renderDocItem(doc, 0))}
@@ -651,25 +704,24 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
)}
</div>
{/* Right Block Editor */}
{/* Right Word / Notion Formatted Editor */}
<div className="lg:col-span-8">
{selectedDoc ? (
<div className="p-4 panel-surface">
{/* Document Top Action Bar */}
<div className="flex flex-wrap items-center justify-between gap-3 pb-3 mb-3 panel-header">
<div className="p-4 panel-surface space-y-3">
{/* Document Header & Metadata */}
<div className="flex flex-wrap items-center justify-between gap-3 pb-3 panel-header">
<div className="flex flex-wrap items-center gap-2 text-xs text-zinc-400">
<span className="badge-accent">
<Check className="w-3 h-3" />
{saveState === 'saving' ? 'Speichert…' : 'Gespeichert'}
</span>
{/* Folder Breadcrumb Selector */}
<div className="flex items-center gap-1.5">
<Folder className="w-3.5 h-3.5 text-zinc-500" />
<select
value={getDocFolder(selectedDoc)}
onChange={(e) => handleChangeDocFolder(e.target.value)}
className="input-field px-2 py-0.5"
className="input-field px-2 py-0.5 text-xs bg-canvas"
>
<option value="">(Kein Ordner / Root)</option>
{allFolderPaths.map((fp) => (
@@ -699,9 +751,10 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
type="button"
onClick={handleExportMarkdown}
className="btn-action"
title="Als Markdown-Datei (.md) herunterladen"
>
<Download className="w-3.5 h-3.5 text-accent" />
<span>Markdown (.md)</span>
<span>Export (.md)</span>
</button>
<button
@@ -716,7 +769,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
</div>
{/* Document Icon & Title */}
<div className="flex items-center gap-3 mb-4 relative">
<div className="flex items-center gap-3 relative">
<button
type="button"
onClick={() => setShowIconPicker((prev) => !prev)}
@@ -727,7 +780,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
</button>
{showIconPicker && (
<div className="absolute top-12 left-0 z-20 p-2.5 panel-surface flex flex-wrap gap-1 w-64 shadow-xl">
<div className="absolute top-12 left-0 z-20 p-2.5 panel-surface flex flex-wrap gap-1 w-64 shadow-xl border border-border">
{ICONS.map((ic) => (
<button
key={ic}
@@ -753,12 +806,140 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
/>
</div>
{/* Blocks Stack */}
<div className="space-y-3">
{/* NOTION / WORD RICH FORMATTING TOOLBAR */}
<div className="p-1.5 bg-canvas border border-border flex flex-wrap items-center gap-1 text-xs">
{/* Text styling buttons */}
<button
type="button"
onClick={() => applyInlineFormat('**')}
className="p-1 hover:bg-panel text-zinc-300 hover:text-white"
title="Fett (**text**)"
>
<Bold className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() => applyInlineFormat('*')}
className="p-1 hover:bg-panel text-zinc-300 hover:text-white"
title="Kursiv (*text*)"
>
<Italic className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() => applyInlineFormat('~~')}
className="p-1 hover:bg-panel text-zinc-300 hover:text-white"
title="Durchgestrichen (~~text~~)"
>
<Strikethrough className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() => applyInlineFormat('`')}
className="p-1 hover:bg-panel text-zinc-300 hover:text-white"
title="Inline Code (`code`)"
>
<Code className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() => applyInlineFormat('[Link](', ')')}
className="p-1 hover:bg-panel text-zinc-300 hover:text-white"
title="Link einfügen"
>
<Link className="w-3.5 h-3.5" />
</button>
<span className="w-px h-4 bg-border mx-1" />
{/* Wiki-Link Popover Button */}
<div className="relative">
<button
type="button"
onClick={() => setShowWikiLinkMenu((prev) => !prev)}
className="px-2 py-0.5 bg-panel border border-border text-[11px] text-accent flex items-center gap-1 hover:bg-panel-hover"
title="Auf anderes Dokument verlinken ([[Dokumentname]])"
>
<span>[[ Wiki-Link ]]</span>
</button>
{showWikiLinkMenu && (
<div className="absolute top-7 left-0 z-30 w-56 bg-panel border border-border p-1.5 shadow-2xl space-y-1">
<p className="text-[10px] text-zinc-400 px-1.5 pb-1 border-b border-border">
Dokument zum Verlinken wählen:
</p>
<div className="max-h-48 overflow-y-auto">
{docs
.filter((d) => d.id !== selectedDoc.id)
.map((d) => (
<button
key={d.id}
type="button"
onClick={() => insertWikiLink(d.title)}
className="w-full text-left px-2 py-1 text-xs text-zinc-300 hover:text-white hover:bg-panel-hover truncate flex items-center gap-1.5"
>
<span>{d.icon}</span>
<span className="truncate">{d.title}</span>
</button>
))}
{docs.length <= 1 && (
<div className="p-2 text-center text-[11px] text-zinc-500">
Keine weiteren Dokumente vorhanden
</div>
)}
</div>
</div>
)}
</div>
<span className="w-px h-4 bg-border mx-1" />
{/* Custom Elements: Table & Progress */}
<button
type="button"
onClick={() =>
addBlock(
'table',
undefined,
'| Spalte 1 | Spalte 2 | Spalte 3 |\n|---|---|---|\n| Inhalt A | Inhalt B | Inhalt C |\n| Wert 1 | Wert 2 | Wert 3 |'
)
}
className="px-2 py-0.5 bg-panel border border-border text-[11px] text-zinc-300 hover:text-white flex items-center gap-1"
title="Tabelle einfügen"
>
<TableIcon className="w-3 h-3 text-accent" />
<span>Tabelle</span>
</button>
<button
type="button"
onClick={() => addBlock('progress', undefined, '50')}
className="px-2 py-0.5 bg-panel border border-border text-[11px] text-zinc-300 hover:text-white flex items-center gap-1"
title="Fortschrittsbalken einfügen"
>
<Percent className="w-3 h-3 text-accent" />
<span>Fortschritt</span>
</button>
<button
type="button"
onClick={() => addBlock('divider')}
className="p-1 hover:bg-panel text-zinc-400 hover:text-white"
title="Trennlinie"
>
<Minus className="w-3.5 h-3.5" />
</button>
</div>
{/* BLOCKS STACK */}
<div className="space-y-3 pt-2">
{selectedDoc.blocks.map((block, idx) => (
<div key={block.id} className="group flex items-start gap-2">
{/* Block Renderer */}
<div
key={block.id}
onClick={() => setLastFocusedBlockId(block.id)}
className="group flex items-start gap-2"
>
<div className="flex-1 min-w-0">
{/* H1 */}
{block.type === 'h1' && (
<input
type="text"
@@ -769,6 +950,7 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
/>
)}
{/* H2 */}
{block.type === 'h2' && (
<input
type="text"
@@ -779,16 +961,36 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
/>
)}
{block.type === 'paragraph' && (
<textarea
rows={Math.max(1, Math.ceil(block.content.length / 75))}
{/* H3 */}
{block.type === 'h3' && (
<input
type="text"
value={block.content}
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
placeholder="Text schreiben…"
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 leading-relaxed focus:outline-none resize-none font-normal"
placeholder="Unterabschnitt…"
className="w-full bg-transparent text-sm font-semibold text-zinc-200 focus:outline-none pt-1"
/>
)}
{/* PARAGRAPH with Wiki-Link support */}
{block.type === 'paragraph' && (
<div className="space-y-1">
<textarea
rows={Math.max(1, Math.ceil((block.content || '').length / 75))}
value={block.content}
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
placeholder="Text schreiben… (nutze [[Dokument]] für Wiki-Links)"
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 leading-relaxed focus:outline-none resize-none font-normal"
/>
{block.content.includes('[[') && (
<div className="text-xs text-zinc-400 pt-0.5">
{renderTextWithWikiLinks(block.content)}
</div>
)}
</div>
)}
{/* TODO */}
{block.type === 'todo' && (
<div className="flex items-center gap-2.5 py-1">
<input
@@ -797,48 +999,72 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
onChange={(e) => updateBlock(block.id, { checked: e.target.checked })}
className="w-3.5 h-3.5 accent-accent cursor-pointer"
/>
<input
type="text"
value={block.content}
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
placeholder="To-Do Punkt…"
className={`w-full bg-transparent text-xs sm:text-sm focus:outline-none ${
block.checked ? 'line-through text-zinc-500' : 'text-white'
}`}
/>
<div className="flex-1">
<input
type="text"
value={block.content}
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
placeholder="To-Do Punkt…"
className={`w-full bg-transparent text-xs sm:text-sm focus:outline-none ${
block.checked ? 'line-through text-zinc-500' : 'text-white'
}`}
/>
{block.content.includes('[[') && (
<div className="text-xs text-zinc-400">
{renderTextWithWikiLinks(block.content)}
</div>
)}
</div>
</div>
)}
{/* BULLET */}
{block.type === 'bullet' && (
<div className="flex items-center gap-2.5 py-0.5">
<span className="w-1.5 h-1.5 bg-accent flex-shrink-0" />
<input
type="text"
value={block.content}
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
placeholder="Listenpunkt…"
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 focus:outline-none"
/>
<div className="flex-1">
<input
type="text"
value={block.content}
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
placeholder="Listenpunkt…"
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 focus:outline-none"
/>
{block.content.includes('[[') && (
<div className="text-xs text-zinc-400">
{renderTextWithWikiLinks(block.content)}
</div>
)}
</div>
</div>
)}
{/* CALLOUT */}
{block.type === 'callout' && (
<div className="p-2.5 bg-canvas border border-accent/40 flex items-start gap-2">
<Sparkles className="w-3.5 h-3.5 text-accent flex-shrink-0 mt-0.5" />
<textarea
rows={2}
value={block.content}
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
placeholder="Wichtiger Hinweis oder Zusammenfassung…"
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 focus:outline-none resize-none"
/>
<div className="flex-1 space-y-1">
<textarea
rows={2}
value={block.content}
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
placeholder="Wichtiger Hinweis oder Zusammenfassung…"
className="w-full bg-transparent text-xs sm:text-sm text-zinc-200 focus:outline-none resize-none"
/>
{block.content.includes('[[') && (
<div className="text-xs text-zinc-400">
{renderTextWithWikiLinks(block.content)}
</div>
)}
</div>
</div>
)}
{/* CODE */}
{block.type === 'code' && (
<div className="p-2.5 bg-canvas border border-border font-mono text-xs text-zinc-200">
<textarea
rows={Math.max(2, block.content.split('\n').length)}
rows={Math.max(2, (block.content || '').split('\n').length)}
value={block.content}
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
placeholder="// Code oder Shell-Kommando…"
@@ -846,9 +1072,62 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
/>
</div>
)}
{/* TABLE */}
{block.type === 'table' && (
<div className="p-2.5 bg-canvas border border-border space-y-2">
<div className="flex items-center justify-between text-[11px] text-zinc-400 border-b border-border pb-1">
<span className="flex items-center gap-1 font-semibold text-zinc-300">
<TableIcon className="w-3 h-3 text-accent" /> Markdown Tabelle
</span>
</div>
<textarea
rows={Math.max(3, (block.content || '').split('\n').length)}
value={block.content}
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
placeholder="| Spalte 1 | Spalte 2 |\n|---|---|\n| Inhalt | Wert |"
className="w-full bg-transparent font-mono text-xs text-zinc-200 focus:outline-none resize-none"
/>
</div>
)}
{/* PROGRESS BAR */}
{block.type === 'progress' && (
<div className="p-2.5 bg-canvas border border-border space-y-2">
<div className="flex items-center justify-between text-xs">
<span className="text-zinc-300 font-medium flex items-center gap-1">
<Percent className="w-3 h-3 text-accent" /> Fortschritt
</span>
<span className="font-mono text-accent font-semibold">
{parseInt(block.content) || 0}%
</span>
</div>
<div className="w-full bg-panel h-2.5 overflow-hidden border border-border">
<div
className="bg-accent h-full transition-all"
style={{ width: `${Math.min(100, Math.max(0, parseInt(block.content) || 0))}%` }}
/>
</div>
<input
type="range"
min="0"
max="100"
value={parseInt(block.content) || 0}
onChange={(e) => updateBlock(block.id, { content: e.target.value })}
className="w-full accent-accent cursor-pointer"
/>
</div>
)}
{/* DIVIDER */}
{block.type === 'divider' && (
<div className="py-2">
<hr className="border-border" />
</div>
)}
</div>
{/* Block Reorder & Delete Controls */}
{/* Block Controls */}
<div className="opacity-0 group-hover:opacity-100 flex items-center gap-0.5 transition-opacity pt-1">
<button
type="button"
@@ -879,9 +1158,9 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
))}
</div>
{/* Add Block Toolbar */}
{/* Bottom Add Block Toolbar */}
<div className="mt-4 pt-3 border-t border-border flex flex-wrap items-center gap-1.5">
<span className="text-xs text-zinc-400 mr-1">+ Block:</span>
<span className="text-xs text-zinc-400 mr-1">+ Neuer Block:</span>
<button
type="button"
@@ -933,10 +1212,32 @@ export const WorkspaceView: React.FC<WorkspaceViewProps> = ({
<button
type="button"
onClick={() => addBlock('h1')}
onClick={() =>
addBlock(
'table',
undefined,
'| Spalte 1 | Spalte 2 |\n|---|---|\n| Inhalt A | Inhalt B |'
)
}
className="btn-action h-6 px-2 text-xs"
>
<Heading1 className="w-3 h-3 text-accent" /> H1
<TableIcon className="w-3 h-3 text-accent" /> Tabelle
</button>
<button
type="button"
onClick={() => addBlock('progress', undefined, '50')}
className="btn-action h-6 px-2 text-xs"
>
<Percent className="w-3 h-3 text-accent" /> Fortschritt
</button>
<button
type="button"
onClick={() => addBlock('divider')}
className="btn-action h-6 px-2 text-xs"
>
<Minus className="w-3 h-3 text-accent" /> Trennlinie
</button>
</div>
</div>