Files
superbrain/web/app/(app)/calendar/client.tsx
T
Andrew S Erwin da70346e45 Sidebar reorganization + page tags, kanban explicit-only, bookmark group-by, calendar views
Sidebar (web/components/sidebar.tsx) reorganized to the requested structure:
Quick find at the top; a Pages group (All Pages tree with the existing
rename/reorder/pin/subpage/delete interactions, Pinned Pages, Untagged
Pages); a Bookmarks group (All Bookmarks, Calendar, and expandable carets
for Tags / Kanban / Collections / Contacts listing their entities with
deep-links /tags?tag=, /kanban?column=, /collections?id=, /contacts?open=);
Trash at the bottom. Collapsed desktop rail is a flat icon list; the mobile
drawer shows the full grouped nav.

Page tagging (new): PageTag join (migration 023 + schema.sql, db-converge
proven), POST/DELETE /api/pages/{id}/tags with owner-or-TagShare validation
(same rule as bookmark tags), tags exposed in the page list/detail
projections so the sidebar can compute the untagged subset. Tagging is
metadata (no content-version bump) and cascades on page/tag delete.
Dragging a page from Untagged Pages onto a tag assigns it (custom drag MIME
keeps it distinct from page reorder).

Kanban: only explicitly-placed cards render (no auto-populate of unassigned
bookmarks); the sidebar caret lists the existing columns and ?column=
scrolls/rings the target. e2e updated to assert no-auto-populate then place
the card explicitly.

All Bookmarks: a Group by selector (None/Calendar/Tags/Kanban/Collections/
Contacts) rendering grouped sections via shared row/card renderers; the
default None path is byte-identical to before (205-row table, same keys).
Collections grouping fetches membership once, sequence-guarded.

Calendar: Day/Week/Month/Year/List views (Month default), adaptive
prev/next + Today, date-sorted list; SSR-safe (date-fns only, post-mount
today), internal overflow containers so no page-level horizontal scroll.

Deep-link page wrappers for kanban/collections/contacts pass searchParams
into the clients' initial selection.

Test gate: the -race internal/http suite now exceeds the default 10m go
test timeout (~14m cold-cache), so the tests service and Makefile test
target use -timeout 30m; the suite passes in full.

Verified: regressions 20/20, real-stack e2e all pass, lint/SSR-lint/build
0 errors, db-converge green, full Go integration suite green; browser
checks of the grouped sidebar, drag-to-tag, bookmark group-by and every
calendar view show correct rendering with no horizontal overflow.
2026-11-18 14:23:26 -06:00

385 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use client'
import { useState, useEffect, useCallback, useMemo, useRef } from 'react'
import { Button } from '@/components/ui/button'
import { BookmarkCard } from '@/components/bookmark-card'
import { BookmarkDetailSheet } from '@/components/bookmark-detail-sheet'
import { ChevronLeft, ChevronRight, Share2 } from 'lucide-react'
import { format, startOfMonth, endOfMonth, startOfWeek, endOfWeek, eachDayOfInterval, isSameDay, isSameMonth, addDays, addMonths, addYears, getDay, parseISO } from 'date-fns'
import type { Bookmark } from '@/components/app-shell'
import { Input } from '@/components/ui/input'
import { toast } from 'sonner'
import { fetchBookmarks } from '@/lib/bookmarks'
import { cn } from '@/lib/utils'
// Review L-4: a fixed, obviously-not-current placeholder. The real month and
// today are set after mount (to avoid an SSR/client hydration mismatch), and
// the calendar renders a skeleton until then instead of briefly presenting
// this epoch as the current month.
const INITIAL_DATE = new Date(2000, 0, 1)
type CalendarView = 'day' | 'week' | 'month' | 'year' | 'list'
// Month stays the default so the classic grid is what loads first.
const VIEWS: { id: CalendarView; label: string }[] = [
{ id: 'day', label: 'Day' },
{ id: 'week', label: 'Week' },
{ id: 'month', label: 'Month' },
{ id: 'year', label: 'Year' },
{ id: 'list', label: 'List' },
]
export function CalendarClient() {
// currentMonth anchors every period view (day/week/month/year); List shows
// all due dates and ignores it.
const [currentMonth, setCurrentMonth] = useState<Date>(INITIAL_DATE)
const [today, setToday] = useState<Date>(INITIAL_DATE)
const [ready, setReady] = useState(false)
const [view, setView] = useState<CalendarView>('month')
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
const [selectedDay, setSelectedDay] = useState<Date | null>(null)
const [selectedBookmark, setSelectedBookmark] = useState<Bookmark | null>(null)
const [loading, setLoading] = useState(true)
const [sharedDates, setSharedDates] = useState<any[]>([])
const [shareQuery, setShareQuery] = useState('')
const [shareUsers, setShareUsers] = useState<any[]>([])
// Debounced user search; failures keep the previous results silently.
useEffect(() => {
const q = shareQuery.trim()
const t = setTimeout(async () => {
if (q.length < 2) { setShareUsers([]); return }
try {
const res = await fetch(`/api/users/search?q=${encodeURIComponent(q)}`)
if (res.ok) setShareUsers(await res.json())
} catch { /* transient; retried on next keystroke */ }
}, q.length < 2 ? 0 : 250)
return () => clearTimeout(t)
}, [shareQuery])
useEffect(() => {
const timer = setTimeout(() => { const now = new Date(); setCurrentMonth(now); setToday(now); setReady(true) }, 0)
return () => clearTimeout(timer)
}, [])
// Review M-11: bookmark-change events and slow initial loads can overlap;
// only the newest pass may publish its data.
const loadSeq = useRef(0)
const load = useCallback(async () => {
const seq = ++loadSeq.current
setLoading(true)
try {
const [mine, shared, dates] = await Promise.all([fetchBookmarks(), fetchBookmarks(new URLSearchParams({ shared: 'true' })), fetch('/api/shared-dates')])
if (seq !== loadSeq.current) return
const sharedDatesJson = dates.ok ? await dates.json() : null
if (seq !== loadSeq.current) return
setBookmarks([...mine, ...shared])
if (sharedDatesJson) setSharedDates(sharedDatesJson)
} catch { if (seq === loadSeq.current) toast.error('Could not load calendar') }
finally { if (seq === loadSeq.current) setLoading(false) }
}, [])
useEffect(() => { const timer = setTimeout(load, 0); window.addEventListener('superbrain:bookmarks-changed', load); return () => { clearTimeout(timer); window.removeEventListener('superbrain:bookmarks-changed', load) } }, [load])
const days = useMemo(() => {
const start = startOfMonth(currentMonth)
const end = endOfMonth(currentMonth)
return eachDayOfInterval({ start, end })
}, [currentMonth])
const startDayOfWeek = getDay(startOfMonth(currentMonth))
const bookmarksByDay = useMemo(() => {
const map: Record<string, Bookmark[]> = {}
for (const b of bookmarks) {
if (b?.dueDate) {
const key = b.dueDate.slice(0, 10)
if (!map[key]) map[key] = []
map[key].push(b)
}
}
return map
}, [bookmarks])
const sharedDateKeys = useMemo(() => new Set(sharedDates.map(s => s.date.slice(0, 10))), [sharedDates])
// Week columns follow the month grid's Sun..Sat order (date-fns default).
const weekDays = useMemo(() => eachDayOfInterval({ start: startOfWeek(currentMonth), end: endOfWeek(currentMonth) }), [currentMonth])
const yearMonths = useMemo(() => Array.from({ length: 12 }, (_, i) => new Date(currentMonth.getFullYear(), i, 1)), [currentMonth])
// List view: every day with due bookmarks or a shared date, ascending;
// ISO date keys sort chronologically as plain strings.
const listGroups = useMemo(() => {
const keys = Array.from(new Set([...Object.keys(bookmarksByDay), ...sharedDateKeys])).sort()
return keys.map(key => ({
key,
shared: sharedDates.filter(s => s.date.slice(0, 10) === key),
bookmarks: [...(bookmarksByDay[key] ?? [])].sort((a, b) => (a.dueDate ?? '') < (b.dueDate ?? '') ? -1 : (a.dueDate ?? '') > (b.dueDate ?? '') ? 1 : 0),
}))
}, [bookmarksByDay, sharedDates, sharedDateKeys])
const periodLabel = useMemo(() => {
if (view === 'day') return format(currentMonth, 'EEE, MMM d, yyyy')
if (view === 'week') {
const start = startOfWeek(currentMonth)
const end = endOfWeek(currentMonth)
return start.getFullYear() === end.getFullYear()
? `${format(start, 'MMM d')} – ${format(end, 'MMM d, yyyy')}`
: `${format(start, 'MMM d, yyyy')} – ${format(end, 'MMM d, yyyy')}`
}
if (view === 'year') return format(currentMonth, 'yyyy')
return format(currentMonth, 'MMMM yyyy')
}, [view, currentMonth])
const step = (dir: -1 | 1) => setCurrentMonth(d => {
if (view === 'day') return addDays(d, dir)
if (view === 'week') return addDays(d, dir * 7)
if (view === 'year') return addYears(d, dir)
return addMonths(d, dir)
})
const goToday = () => { const now = new Date(); setCurrentMonth(now); setToday(now) }
// The selected-day detail panel, shared by Month/Week (below the grid) and
// the Day view, where the anchor day is the view itself.
const renderDayPanel = (day: Date) => {
const key = format(day, 'yyyy-MM-dd')
const dayBookmarks = bookmarksByDay[key] ?? []
const dayShared = sharedDates.filter(s => s.date.slice(0, 10) === key)
return (
<div className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="font-medium">{format(day, 'EEEE, MMMM d, yyyy')}</h2>
<div className="flex gap-2"><Input placeholder="Share date with user…" value={shareQuery} onChange={e => setShareQuery(e.target.value)} /></div>
</div>
{/* Review L-9: sharing a date is broader than the old label said. */}
<p className="text-xs text-muted-foreground">Recipients will see your bookmarks due that day, including their notes.</p>
{shareUsers.map(u => <Button key={u.id} size="sm" variant="outline" onClick={async () => { const res = await fetch('/api/shared-dates', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ date: key, recipientIds: [u.id] }) }); if (!res.ok) { toast.error('Could not share date'); return } toast.success('Date shared'); setShareQuery(''); setShareUsers([]); load() }}>Share with {u.name || u.email}</Button>)}
{dayShared.map(s => <div key={s.id} className="flex items-center gap-2 text-xs text-muted-foreground"><span>{s.creator.name || s.creator.email} shared with {s.recipient.name || s.recipient.email}</span><Button size="xs" variant="ghost" onClick={async () => { const res = await fetch(`/api/shared-dates/${s.id}`, { method: 'DELETE' }); if (!res.ok) { toast.error('Only the owner can stop sharing'); return } load() }}>Stop sharing</Button></div>)}
{dayBookmarks.length === 0 ? (
<p className="text-sm text-muted-foreground">No bookmarks on this date</p>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
{dayBookmarks.map((b: Bookmark) => (
<BookmarkCard key={b.id} bookmark={b} compact onClick={() => setSelectedBookmark(b)} />
))}
</div>
)}
</div>
)
}
if (!ready) {
return (
<div className="space-y-6">
<div>
<h1 className="font-display text-2xl font-bold tracking-tight">Calendar</h1>
<p className="text-sm text-muted-foreground mt-1">Bookmarks organized by due date</p>
</div>
<div className="h-[60vh] animate-pulse rounded-lg border border-border/60 bg-muted/30" aria-label="Loading calendar" />
</div>
)
}
return (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="font-display text-2xl font-bold tracking-tight">Calendar</h1>
<p className="text-sm text-muted-foreground mt-1">Bookmarks organized by due date</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<div role="group" aria-label="Calendar view" className="flex items-center gap-0.5 rounded-lg border border-border/60 bg-muted/30 p-0.5">
{VIEWS.map(v => (
<Button key={v.id} size="xs" variant={view === v.id ? 'secondary' : 'ghost'} aria-pressed={view === v.id} onClick={() => setView(v.id)}>{v.label}</Button>
))}
</div>
{view !== 'list' && (
<div className="flex items-center gap-2">
<Button variant="outline" size="icon-sm" aria-label={`Previous ${view}`} onClick={() => step(-1)}>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="font-medium text-sm min-w-[140px] whitespace-nowrap text-center">{periodLabel}</span>
<Button variant="outline" size="icon-sm" aria-label={`Next ${view}`} onClick={() => step(1)}>
<ChevronRight className="h-4 w-4" />
</Button>
<Button variant="outline" size="sm" onClick={goToday}>Today</Button>
</div>
)}
</div>
</div>
{view === 'month' && <div className="grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden">
{['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map(d => (
<div key={d} className="bg-muted/50 px-0.5 py-2 text-center text-xs font-medium text-muted-foreground sm:px-2"><span className="sm:hidden">{d[0]}</span><span className="hidden sm:inline">{d}</span></div>
))}
{Array.from({ length: startDayOfWeek }).map((_, i) => (
<div key={`empty-${i}`} className="bg-card min-h-[80px]" />
))}
{days.map(day => {
const key = format(day, 'yyyy-MM-dd')
const dayBookmarks = bookmarksByDay[key] ?? []
const isSelected = selectedDay ? isSameDay(day, selectedDay) : false
const isToday = isSameDay(day, today)
return (
<div
key={key}
role="button"
tabIndex={0}
aria-pressed={isSelected}
aria-label={format(day, 'EEEE, MMMM d, yyyy')}
onClick={() => setSelectedDay(day)}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedDay(day) } }}
className={`bg-card min-h-[64px] p-1 sm:min-h-[80px] sm:p-1.5 cursor-pointer transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary ${
isSelected ? 'ring-2 ring-primary ring-inset' : ''
}`}
>
<span className={`text-xs font-medium inline-flex h-6 w-6 items-center justify-center rounded-full ${
isToday ? 'bg-primary text-primary-foreground' : 'text-foreground'
}`}>
{format(day, 'd')}
</span>
<div className="space-y-0.5 mt-0.5">
{sharedDates.filter(s => s.date.slice(0, 10) === key).map(s => <p key={s.id} className="truncate text-[10px] text-primary" title={s.note || ''}>Shared: {s.creator.name || s.creator.email}</p>)}
{dayBookmarks.slice(0, 2).map((b: Bookmark) => (
<div key={b.id} role="button" tabIndex={0} className="text-[10px] truncate rounded bg-primary/10 text-primary px-1 py-0.5 cursor-pointer focus-visible:outline-1 focus-visible:outline-primary" onClick={(e: React.MouseEvent) => { e.stopPropagation(); setSelectedBookmark(b) }} onKeyDown={(e: React.KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); setSelectedBookmark(b) } }}>
{b.title ?? 'Untitled'}
</div>
))}
{dayBookmarks.length > 2 && (
<div className="text-[10px] text-muted-foreground px-1">+{dayBookmarks.length - 2} more</div>
)}
</div>
</div>
)
})}
</div>}
{view === 'day' && renderDayPanel(currentMonth)}
{view === 'week' && (
<div className="overflow-x-auto rounded-lg">
<div className="grid min-w-[640px] grid-cols-7 gap-px bg-border rounded-lg overflow-hidden">
{weekDays.map(day => {
const key = format(day, 'yyyy-MM-dd')
return (
<div key={`header-${key}`} className="bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground">
{format(day, 'EEE')}{' '}
<span className={cn('inline-flex h-5 w-5 items-center justify-center rounded-full align-middle', isSameDay(day, today) && 'bg-primary text-primary-foreground')}>{format(day, 'd')}</span>
</div>
)
})}
{weekDays.map(day => {
const key = format(day, 'yyyy-MM-dd')
const dayBookmarks = bookmarksByDay[key] ?? []
const isSelected = selectedDay ? isSameDay(day, selectedDay) : false
return (
<div
key={key}
role="button"
tabIndex={0}
aria-pressed={isSelected}
aria-label={format(day, 'EEEE, MMMM d, yyyy')}
onClick={() => setSelectedDay(day)}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedDay(day) } }}
className={cn('bg-card min-h-[160px] p-1.5 cursor-pointer transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary', isSelected && 'ring-2 ring-primary ring-inset')}
>
<div className="space-y-0.5">
{sharedDates.filter(s => s.date.slice(0, 10) === key).map(s => <p key={s.id} className="truncate text-[10px] text-primary" title={s.note || ''}>Shared: {s.creator.name || s.creator.email}</p>)}
{dayBookmarks.slice(0, 4).map((b: Bookmark) => (
<div key={b.id} role="button" tabIndex={0} className="text-[10px] truncate rounded bg-primary/10 text-primary px-1 py-0.5 cursor-pointer focus-visible:outline-1 focus-visible:outline-primary" onClick={(e: React.MouseEvent) => { e.stopPropagation(); setSelectedBookmark(b) }} onKeyDown={(e: React.KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); setSelectedBookmark(b) } }}>
{b.title ?? 'Untitled'}
</div>
))}
{dayBookmarks.length > 4 && (
<div className="text-[10px] text-muted-foreground px-1">+{dayBookmarks.length - 4} more</div>
)}
</div>
</div>
)
})}
</div>
</div>
)}
{view === 'year' && (
<div className="overflow-x-auto">
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
{yearMonths.map(month => {
const monthKey = format(month, 'yyyy-MM')
const monthDays = eachDayOfInterval({ start: startOfMonth(month), end: endOfMonth(month) })
const lead = getDay(startOfMonth(month))
const openMonth = () => { setCurrentMonth(month); setView('month') }
return (
<div
key={monthKey}
role="button"
tabIndex={0}
aria-label={`Open ${format(month, 'MMMM yyyy')}`}
onClick={openMonth}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openMonth() } }}
className={cn('rounded-lg border bg-card p-2 cursor-pointer transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary', isSameMonth(month, currentMonth) ? 'border-primary/50' : 'border-border/60')}
>
<p className="mb-1 text-center text-xs font-medium">{format(month, 'MMMM')}</p>
<div className="grid grid-cols-7 gap-y-0.5 text-center">
{['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((d, i) => <span key={`wd-${i}`} className="text-[9px] text-muted-foreground">{d}</span>)}
{Array.from({ length: lead }).map((_, i) => <span key={`empty-${i}`} />)}
{monthDays.map(day => {
const key = format(day, 'yyyy-MM-dd')
const hasItems = (bookmarksByDay[key]?.length ?? 0) > 0 || sharedDateKeys.has(key)
return (
<span key={key} className={cn('rounded-full text-[10px] leading-4', isSameDay(day, today) ? 'bg-primary text-primary-foreground' : hasItems ? 'font-semibold text-primary' : 'text-muted-foreground')}>
{format(day, 'd')}
</span>
)
})}
</div>
</div>
)
})}
</div>
</div>
)}
{view === 'list' && (
listGroups.length === 0 ? (
<p className="text-sm text-muted-foreground">No bookmarks with due dates</p>
) : (
<div className="divide-y divide-border/60 overflow-hidden rounded-lg border border-border/60 bg-card">
{listGroups.map(group => {
const day = parseISO(group.key)
return (
<div key={group.key}>
<div className="bg-muted/50 px-3 py-1.5 text-xs font-medium text-muted-foreground">
{format(day, 'EEEE, MMMM d, yyyy')}{isSameDay(day, today) ? ' · Today' : ''}
</div>
{group.shared.map(s => <p key={s.id} className="truncate px-3 py-1 text-xs text-primary" title={s.note || ''}>Shared: {s.creator.name || s.creator.email}</p>)}
{group.bookmarks.map((b: Bookmark) => (
<div
key={b.id}
role="button"
tabIndex={0}
aria-label={b.title ?? 'Untitled'}
onClick={() => setSelectedBookmark(b)}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedBookmark(b) } }}
className="cursor-pointer px-3 py-2 transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary"
>
<span className="block truncate text-sm">{b.title ?? 'Untitled'}</span>
</div>
))}
</div>
)
})}
</div>
)
)}
{selectedDay && (view === 'month' || view === 'week') && renderDayPanel(selectedDay)}
<BookmarkDetailSheet bookmark={selectedBookmark} onClose={() => setSelectedBookmark(null)} onUpdate={load} />
</div>
)
}