Files
ProjectE/apps/web/components/settings/settings-domains.tsx
T
Hermes f388f124e8 fix(p1): wire New habit/New project buttons + fix Domain Add
Bug #3 (HIGH): New habit button on /habits did not open the create
dialog. The HabitCreateDialog was mounted but the topbar's
useCreateDialogStore had no consumer on /habits, so topbar clicks
were no-ops.

Bug #4 (HIGH): New project button on /projects had the same issue.

Fix: mount CreateItemDialog (type=habit or type=project) on each
page so the topbar store is consumed. Switch the page-level button
to use the store too. The existing local HabitCreateDialog /
ProjectCreateDialog still work as a fallback.

Bug #5 (HIGH): Domain Add button on /settings/domains opened the
Command Palette instead of creating the domain. Two-part cause:
1. The sticky topbar Quick add button was visually overlapping
   the form Add button (both anchored top-right). On click the
   topbar handleCreate fired and dispatched a synthetic Cmd+K
   opening the palette.
2. /api/domains POST required a slug field that the form did not
   send, returning 400.

Fix: hide the topbar Quick add button on pages without a relevant
quick-create (only show on /projects, /habits, /tasks). Make the
form Add button explicit type=button with stopPropagation as
defense in depth. Auto-generate the domain slug from the name
on the server when not provided.

Bug #3 + Bug #4 + Bug #5 all fixed in this commit.
2026-07-31 01:06:04 +00:00

291 lines
9.9 KiB
TypeScript

'use client';
import { useEffect, useState } from 'react';
import { Plus, Trash2, Pencil } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
interface Domain {
id: string;
name: string;
color: string;
icon: string;
sort_order: number;
}
export function SettingsDomains() {
const [domains, setDomains] = useState<Domain[]>([]);
const [newDomainName, setNewDomainName] = useState('');
const [newDomainColor, setNewDomainColor] = useState('#3b82f6');
const [loading, setLoading] = useState(true);
const [creating, setCreating] = useState(false);
const [deletingId, setDeletingId] = useState<string | null>(null);
const [domainToDelete, setDomainToDelete] = useState<Domain | null>(null);
const [error, setError] = useState<string | null>(null);
const [status, setStatus] = useState<string | null>(null);
const [editing, setEditing] = useState<Domain | null>(null);
const [editName, setEditName] = useState('');
const [editColor, setEditColor] = useState('#3b82f6');
const [saving, setSaving] = useState(false);
useEffect(() => {
fetchDomains();
}, []);
useEffect(() => {
if (editing) {
setEditName(editing.name);
setEditColor(editing.color || '#3b82f6');
}
}, [editing]);
async function fetchDomains() {
setLoading(true);
setError(null);
try {
const response = await fetch('/api/domains?sort=sort_order');
if (!response.ok) throw new Error('Unable to load domains.');
const data = await response.json();
setDomains(data.items || []);
} catch (error) {
console.error('Failed to fetch domains:', error);
setError('Unable to load domains. Please try again.');
} finally {
setLoading(false);
}
}
async function addDomain() {
if (!newDomainName.trim()) return;
setCreating(true);
setError(null);
setStatus(null);
try {
const response = await fetch('/api/domains', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: newDomainName,
color: newDomainColor,
icon: '📁',
sort_order: domains.length,
}),
});
if (!response.ok) throw new Error('Unable to add domain.');
setNewDomainName('');
setStatus('Domain added successfully.');
await fetchDomains();
} catch (error) {
console.error('Failed to add domain:', error);
setError('Unable to add domain. Please try again.');
} finally {
setCreating(false);
}
}
async function deleteDomain() {
if (!domainToDelete) return;
setDeletingId(domainToDelete.id);
setError(null);
setStatus(null);
try {
const response = await fetch('/api/domains/' + domainToDelete.id, { method: 'DELETE' });
if (!response.ok) throw new Error('Unable to delete domain.');
setDomainToDelete(null);
setStatus('Domain deleted successfully.');
await fetchDomains();
} catch (error) {
console.error('Failed to delete domain:', error);
setError('Unable to delete domain. Please try again.');
} finally {
setDeletingId(null);
}
}
async function handleEditSave() {
if (!editing || !editName.trim()) return;
setSaving(true);
setError(null);
setStatus(null);
try {
const response = await fetch('/api/domains/' + editing.id, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: editName.trim(),
color: editColor,
}),
});
if (!response.ok) throw new Error('Unable to update domain.');
setEditing(null);
setStatus('Domain updated successfully.');
await fetchDomains();
} catch (error) {
console.error('Failed to update domain:', error);
setError('Unable to update domain. Please try again.');
} finally {
setSaving(false);
}
}
return (
<Card>
<CardHeader>
<CardTitle>Domains</CardTitle>
<CardDescription>Manage your workspace domains (e.g., Personal, Work, OTS).</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{error && (
<div className="flex items-center justify-between gap-3 text-sm text-destructive" role="alert">
<span>{error}</span>
<Button variant="outline" size="sm" onClick={fetchDomains} disabled={loading}>Retry</Button>
</div>
)}
{status && <p className="text-sm text-muted-foreground" role="status">{status}</p>}
{/* Existing domains */}
<div className="space-y-2">
{loading ? (
<p className="text-sm text-muted-foreground">Loading domains...</p>
) : (
domains.map((domain) => (
<div key={domain.id} className="flex items-center justify-between rounded-lg border p-3">
<div className="flex items-center gap-3">
<div
className="h-4 w-4 rounded"
style={{ backgroundColor: domain.color }}
/>
<span className="font-medium">{domain.name}</span>
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
onClick={() => setEditing(domain)}
aria-label={'Edit domain: ' + domain.name}
>
<Pencil className="h-4 w-4" aria-hidden="true" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => setDomainToDelete(domain)}
aria-label={'Delete domain: ' + domain.name}
disabled={deletingId === domain.id}
>
<Trash2 className="h-4 w-4 text-destructive" aria-hidden="true" />
</Button>
</div>
</div>
))
)}
</div>
{/* Add new domain */}
<div className="relative z-50 flex gap-2">
<label htmlFor="new-domain-name" className="sr-only">
New domain name
</label>
<div className="flex gap-2 flex-1">
<Input
id="new-domain-name"
placeholder="New domain name"
value={newDomainName}
onChange={(e) => setNewDomainName(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && addDomain()}
disabled={creating}
className="flex-1"
/>
<input
type="color"
value={newDomainColor}
onChange={(e) => setNewDomainColor(e.target.value)}
className="h-10 w-10 cursor-pointer rounded border"
title="Domain color"
disabled={creating}
/>
</div>
<Button type="button" onClick={(e) => { e.stopPropagation(); addDomain(); }} disabled={creating || !newDomainName.trim()}>
<Plus className="mr-1 h-4 w-4" />
{creating ? 'Adding...' : 'Add'}
</Button>
</div>
{/* Edit Domain Dialog */}
<Dialog open={!!editing} onOpenChange={(o) => !o && setEditing(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit domain</DialogTitle>
<DialogDescription>Update the domain name and color.</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="edit-domain-name">Name</Label>
<Input
id="edit-domain-name"
value={editName}
onChange={(e) => setEditName(e.target.value)}
autoFocus
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="edit-domain-color">Color</Label>
<input
id="edit-domain-color"
type="color"
value={editColor}
onChange={(e) => setEditColor(e.target.value)}
className="h-10 w-10 cursor-pointer rounded border"
/>
</div>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setEditing(null)}>Cancel</Button>
<Button onClick={handleEditSave} disabled={saving || !editName.trim()}>
{saving ? 'Saving...' : 'Save'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<AlertDialog open={!!domainToDelete} onOpenChange={(open) => !open && setDomainToDelete(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {domainToDelete?.name}?</AlertDialogTitle>
<AlertDialogDescription>This cannot be undone.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={!!deletingId}>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={deleteDomain} disabled={!!deletingId}>
{deletingId ? 'Deleting...' : 'Delete domain'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</CardContent>
</Card>
);
}