feat(ST-1105): add NavBar bell + sheet + answer-modal + Zustand store + SSE hook

UI-volledig voor de Claude vraag-antwoord-flow (M11). Bel-icon links van avatar
in NavBar; klik opent slide-over rechts met openstaande vragen; klik op een vraag
opent een modal voor antwoord. Story-assignee = current user krijgt visuele
"voor jou"-emphase met primary-container accent en error-color badge-ring.

Bestanden:
- stores/notifications-store.ts — Zustand store met init/upsert/remove +
  openCount/forYouCount selectors (vereenvoudigd vs solo-store: geen pendingOps,
  geen optimistic-echo-onderdrukking)
- lib/realtime/use-notifications-realtime.ts — EventSource hook met state-
  event en message-event handling, exponential-backoff reconnect, Page
  Visibility pause-resume
- components/notifications/notifications-bridge.tsx — Server Component die
  initial open-questions fetcht via productAccessFilter
- components/notifications/notifications-realtime-mount.tsx — tiny client
  island dat de store hydrateert + de hook activeert
- components/notifications/notifications-sheet.tsx — shadcn Sheet met item-
  lijst, "voor jou"-accent voor assignee-vragen, lege staat
- components/notifications/answer-modal.tsx — Dialog met options-radio of
  free-text Textarea (max 4000), char-counter, demo-blok via Tooltip; bij
  succes optimistisch remove + sheet blijft open zodat meerdere vragen
  achter elkaar te beantwoorden zijn
- components/shared/notifications-bell.tsx — Bell-icon met badge (count >9 → "9+"),
  ring-accent als forYouCount > 0, ARIA-label voor screenreaders

Wiring:
- components/shared/nav-bar.tsx — <NotificationsBell /> rechts naast <UserMenu>
- app/(app)/layout.tsx — <NotificationsBridge /> naast <SoloRealtimeBridge />,
  user.id (server-side) als prop

base-ui-aanpassingen: SheetTrigger/TooltipTrigger gebruiken render-prop ipv
asChild (geen Radix).

Quality gates: lint 0 errors, tsc clean, vitest 146/146, npm run build groen.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Janpeter Visser 2026-04-28 01:25:07 +02:00
parent 009375a131
commit 3243282bfd
9 changed files with 594 additions and 1 deletions

View file

@ -9,6 +9,7 @@ import { NavBar } from '@/components/shared/nav-bar'
import { MinWidthBanner } from '@/components/shared/min-width-banner'
import { StatusBar } from '@/components/shared/status-bar'
import { SoloRealtimeBridge } from '@/components/solo/realtime-bridge'
import { NotificationsBridge } from '@/components/notifications/notifications-bridge'
import { AlertToast } from '@/components/shared/alert-toast'
import { Suspense } from 'react'
@ -92,6 +93,7 @@ export default async function AppLayout({ children }: { children: React.ReactNod
</main>
<StatusBar />
<SoloRealtimeBridge />
<NotificationsBridge userId={session.userId} />
<Suspense>
<AlertToast />
</Suspense>

View file

@ -0,0 +1,157 @@
'use client'
// ST-1105: Modal waar de gebruiker een Claude-vraag beantwoordt (M11).
//
// Free-text Textarea (max 4000) of multiple-choice via knoppen wanneer de
// vraag `options` heeft. Submit roept answerQuestion-Server-Action aan via
// useTransition; bij succes wordt de vraag uit de store verwijderd
// (optimistisch) en sluit de modal. Demo-modus: textarea readOnly + submit
// disabled met tooltip.
import { useState, useTransition } from 'react'
import Link from 'next/link'
import { ExternalLink } from 'lucide-react'
import { toast } from 'sonner'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { answerQuestion } from '@/actions/questions'
import { useNotificationsStore, type NotificationQuestion } from '@/stores/notifications-store'
const MAX_ANSWER_CHARS = 4000
interface AnswerModalProps {
question: NotificationQuestion | null
isDemo: boolean
onClose: () => void
}
export function AnswerModal({ question, isDemo, onClose }: AnswerModalProps) {
const [answer, setAnswer] = useState('')
const [pending, startTransition] = useTransition()
if (!question) return null
const charsLeft = MAX_ANSWER_CHARS - answer.length
const tooLong = charsLeft < 0
const submitDisabled = isDemo || pending || answer.trim().length === 0 || tooLong
function submit(text: string) {
if (!question) return
if (isDemo) {
toast.error('Niet beschikbaar in demo-modus')
return
}
startTransition(async () => {
const res = await answerQuestion(question.id, text)
if (!res.ok) {
toast.error(res.error)
return
}
// Optimistisch verwijderen — SSE-event komt anders later met dezelfde
// remove en kost een extra render
useNotificationsStore.getState().remove(question.id)
toast.success('Antwoord verstuurd')
setAnswer('')
onClose()
})
}
return (
<Dialog open={!!question} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>Beantwoord Claude</DialogTitle>
<DialogDescription>
<span className="font-mono">{question.story_code ?? 'story'}</span>
{' — '}
{question.story_title}
</DialogDescription>
</DialogHeader>
<Link
href={`/products/${question.product_id}/sprint`}
className="text-primary inline-flex items-center gap-1 self-start text-xs hover:underline"
>
<ExternalLink className="h-3.5 w-3.5" />
<span>Open in Sprint</span>
</Link>
<div className="bg-surface-container-low rounded-md border p-3 text-sm whitespace-pre-wrap">
{question.question}
</div>
{question.options && question.options.length > 0 ? (
<div className="space-y-2">
<p className="text-muted-foreground text-xs">Kies een van de opties:</p>
<div className="flex flex-col gap-2">
{question.options.map((opt) => (
<Button
key={opt}
type="button"
variant="outline"
className="justify-start"
disabled={isDemo || pending}
onClick={() => submit(opt)}
>
{opt}
</Button>
))}
</div>
</div>
) : (
<div className="space-y-1">
<Textarea
value={answer}
onChange={(e) => setAnswer(e.target.value)}
placeholder="Typ je antwoord…"
rows={5}
maxLength={MAX_ANSWER_CHARS}
readOnly={isDemo}
aria-label="Antwoord op Claude's vraag"
/>
<div
className={
tooLong
? 'text-error text-right text-xs'
: 'text-muted-foreground text-right text-xs'
}
>
{charsLeft} tekens over
</div>
</div>
)}
<DialogFooter>
<Button variant="ghost" onClick={onClose} disabled={pending}>
Annuleren
</Button>
{(!question.options || question.options.length === 0) && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={<span className="inline-flex" />}>
<Button
onClick={() => submit(answer)}
disabled={submitDisabled}
>
{pending ? 'Bezig…' : 'Verstuur'}
</Button>
</TooltipTrigger>
{isDemo && (
<TooltipContent>Niet beschikbaar in demo-modus</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
)}
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View file

@ -0,0 +1,62 @@
// ST-1105: Mount-component voor de notifications-realtime hook (M11).
//
// Server Component dat de initial open-questions fetch't met
// productAccessFilter en doorgeeft aan een minimal client-island; client opent
// daarna de SSE-stream voor live updates.
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'
import { NotificationsRealtimeMount } from './notifications-realtime-mount'
import type { NotificationQuestion } from '@/stores/notifications-store'
interface NotificationsBridgeProps {
userId: string
}
export async function NotificationsBridge({ userId }: NotificationsBridgeProps) {
const products = await prisma.product.findMany({
where: { archived: false, ...productAccessFilter(userId) },
select: { id: true },
})
const productIds = products.map((p) => p.id)
const openQuestions =
productIds.length === 0
? []
: await prisma.claudeQuestion.findMany({
where: {
status: 'open',
expires_at: { gt: new Date() },
product_id: { in: productIds },
},
orderBy: { created_at: 'desc' },
take: 100,
select: {
id: true,
product_id: true,
story_id: true,
task_id: true,
question: true,
options: true,
created_at: true,
expires_at: true,
story: { select: { code: true, title: true, assignee_id: true } },
},
})
const initial: NotificationQuestion[] = openQuestions.map((q) => ({
id: q.id,
product_id: q.product_id,
story_id: q.story_id,
task_id: q.task_id,
story_code: q.story.code,
story_title: q.story.title,
assignee_id: q.story.assignee_id,
question: q.question,
options: Array.isArray(q.options) ? (q.options as string[]) : null,
created_at: q.created_at.toISOString(),
expires_at: q.expires_at.toISOString(),
}))
return <NotificationsRealtimeMount initial={initial} />
}

View file

@ -0,0 +1,23 @@
// ST-1105: Tiny client island dat de notifications-store hydrateert met
// server-side fetched initial questions en de SSE-realtime hook activeert.
'use client'
import { useEffect } from 'react'
import { useNotificationsStore, type NotificationQuestion } from '@/stores/notifications-store'
import { useNotificationsRealtime } from '@/lib/realtime/use-notifications-realtime'
interface Props {
initial: NotificationQuestion[]
}
export function NotificationsRealtimeMount({ initial }: Props) {
// Hydrate de store met server-side-rendered data zodat de bell-count direct
// klopt zonder te wachten op de SSE state-event.
useEffect(() => {
useNotificationsStore.getState().init(initial)
}, [initial])
useNotificationsRealtime()
return null
}

View file

@ -0,0 +1,106 @@
'use client'
// ST-1105: Slide-over (rechts) met de lijst van openstaande Claude-vragen (M11).
//
// Story-assignee = currentUser krijgt een primary-container accent ("voor jou").
// Klik op een item opent de AnswerModal voor die specifieke vraag. Sheet blijft
// open na een succesvol antwoord zodat meerdere antwoorden achter elkaar kunnen.
import { useState } from 'react'
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@/components/ui/sheet'
import { useNotificationsStore } from '@/stores/notifications-store'
import { AnswerModal } from './answer-modal'
import { cn } from '@/lib/utils'
import type { NotificationQuestion } from '@/stores/notifications-store'
interface NotificationsSheetProps {
trigger: React.ReactNode
currentUserId: string
isDemo: boolean
}
export function NotificationsSheet({
trigger,
currentUserId,
isDemo,
}: NotificationsSheetProps) {
const [open, setOpen] = useState(false)
const [activeQuestion, setActiveQuestion] = useState<NotificationQuestion | null>(null)
const questions = useNotificationsStore((s) => s.questions)
return (
<>
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger render={trigger as React.ReactElement} />
<SheetContent side="right" className="w-full sm:max-w-md">
<SheetHeader>
<SheetTitle>Vragen van Claude ({questions.length})</SheetTitle>
<SheetDescription>
Beantwoord open vragen om Claude verder te laten werken.
</SheetDescription>
</SheetHeader>
{questions.length === 0 ? (
<div className="text-muted-foreground mt-8 px-4 py-6 text-center text-sm">
Geen openstaande vragen. Lekker bezig!
</div>
) : (
<ul className="mt-4 flex flex-col gap-2 px-4 pb-4">
{questions.map((q) => {
const forYou = q.assignee_id === currentUserId
return (
<li key={q.id}>
<button
type="button"
onClick={() => setActiveQuestion(q)}
className={cn(
'border-border w-full rounded-md border p-3 text-left transition-colors hover:bg-surface-container',
forYou &&
'bg-primary-container text-primary-container-foreground border-primary/30 hover:bg-primary-container/80',
)}
>
<div className="flex items-baseline gap-2">
<span className="font-mono text-xs opacity-80">
{q.story_code ?? '—'}
</span>
<span className="line-clamp-1 text-sm font-medium">
{q.story_title}
</span>
</div>
<p
className={cn(
'line-clamp-2 mt-1 text-sm',
forYou ? 'opacity-90' : 'text-muted-foreground',
)}
>
{q.question}
</p>
{forYou && (
<span className="mt-2 inline-block rounded bg-primary/20 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide">
Voor jou
</span>
)}
</button>
</li>
)
})}
</ul>
)}
</SheetContent>
</Sheet>
<AnswerModal
question={activeQuestion}
isDemo={isDemo}
onClose={() => setActiveQuestion(null)}
/>
</>
)
}

View file

@ -16,6 +16,7 @@ import {
} from '@/components/ui/dropdown-menu'
import { AppIcon } from '@/components/shared/app-icon'
import { UserMenu } from '@/components/shared/user-menu'
import { NotificationsBell } from '@/components/shared/notifications-bell'
import { cn } from '@/lib/utils'
import { setActiveProductAction } from '@/actions/active-product'
@ -179,8 +180,9 @@ export function NavBar({
)}
</div>
{/* Rechts: account-menu */}
{/* Rechts: notifications + account-menu */}
<div className="flex items-center gap-2 flex-1 justify-end">
<NotificationsBell currentUserId={userId} isDemo={isDemo} />
<UserMenu userId={userId} username={username} email={email} roles={roles} />
</div>
</header>

View file

@ -0,0 +1,54 @@
'use client'
// ST-1105: Bell-icon in de NavBar met badge van het aantal open Claude-vragen
// voor de ingelogde gebruiker (M11).
//
// Klik opent <NotificationsSheet />. Story-assignee-vragen ("voor jou") worden
// gemarkeerd met een ring-accent op het badge zodat ook bij gelijke totaal-
// count de prioriteit zichtbaar is.
import { Bell } from 'lucide-react'
import { useNotificationsStore } from '@/stores/notifications-store'
import { NotificationsSheet } from '@/components/notifications/notifications-sheet'
import { cn } from '@/lib/utils'
interface NotificationsBellProps {
currentUserId: string
isDemo: boolean
}
export function NotificationsBell({ currentUserId, isDemo }: NotificationsBellProps) {
const total = useNotificationsStore((s) => s.questions.length)
const forYou = useNotificationsStore((s) =>
s.questions.filter((q) => q.assignee_id === currentUserId).length,
)
return (
<NotificationsSheet
currentUserId={currentUserId}
isDemo={isDemo}
trigger={
<button
type="button"
aria-label={`Notificaties — ${total} open vragen${forYou > 0 ? `, ${forYou} voor jou` : ''}`}
className="relative inline-flex h-9 w-9 items-center justify-center rounded-full hover:bg-surface-container focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<Bell className="h-5 w-5 text-foreground" />
{total > 0 && (
<span
role="status"
className={cn(
'absolute -right-0.5 -top-0.5 inline-flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-medium leading-none',
forYou > 0
? 'bg-error text-error-foreground ring-2 ring-background'
: 'bg-primary text-primary-foreground',
)}
>
{total > 9 ? '9+' : total}
</span>
)}
</button>
}
/>
)
}

View file

@ -0,0 +1,126 @@
// ST-1105: Client hook die de notificatie-SSE stream beheert (M11).
//
// Mount via <NotificationsBridge /> in (app)/layout zodat hij Server Action-
// refreshes overleeft. Opent EventSource('/api/realtime/notifications'),
// dispatcht state-/message-events naar de notifications-store.
//
// Vereenvoudigde versie van useSoloRealtime — geen view-transitions, geen
// connecting-indicator-debounce. Wel: reconnect met exponential backoff en
// pause bij hidden tab.
'use client'
import { useEffect, useRef } from 'react'
import { useNotificationsStore, type NotificationQuestion } from '@/stores/notifications-store'
const BACKOFF_START_MS = 1_000
const BACKOFF_MAX_MS = 30_000
interface NotifyPayload {
op: 'I' | 'U'
entity: 'question'
id: string
product_id: string
story_id: string
task_id: string | null
assignee_id: string | null
status: 'open' | 'answered' | 'cancelled' | 'expired'
}
interface StateEvent {
questions: NotificationQuestion[]
}
export function useNotificationsRealtime() {
const sourceRef = useRef<EventSource | null>(null)
const backoffRef = useRef<number>(BACKOFF_START_MS)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(() => {
const init = useNotificationsStore.getState().init
const remove = useNotificationsStore.getState().remove
const close = () => {
if (sourceRef.current) {
sourceRef.current.close()
sourceRef.current = null
}
if (reconnectTimerRef.current) {
clearTimeout(reconnectTimerRef.current)
reconnectTimerRef.current = null
}
}
const connect = () => {
close()
const source = new EventSource('/api/realtime/notifications', {
withCredentials: true,
})
sourceRef.current = source
source.addEventListener('open', () => {
backoffRef.current = BACKOFF_START_MS
})
source.addEventListener('state', (ev) => {
try {
const data = JSON.parse((ev as MessageEvent).data) as StateEvent
init(data.questions ?? [])
} catch {
// ignore malformed
}
})
source.addEventListener('message', (ev) => {
try {
const payload = JSON.parse(ev.data) as NotifyPayload
if (payload.entity !== 'question') return
// Bij open of nieuwe insert → upsert (server stuurt geen vraag-tekst
// mee in de payload, dus we doen een mini-fetch via de same SSE's
// initial-state on reconnect; hier voor MVP alleen status-handling).
if (payload.status === 'open') {
// Inkomende open vraag: we hebben de details nog niet — beste optie is
// herfetchen door opnieuw te verbinden, of via een API. Voor v1
// forceren we een reconnect zodat het volgende state-event de
// volledige details meelevert.
close()
connect()
return
}
// Niet-open status (answered/cancelled/expired) → verwijderen uit lijst
remove(payload.id)
} catch {
// ignore malformed
}
})
source.addEventListener('error', () => {
// EventSource herconnect zelf bij netwerkfouten; voor server-close
// (after 240s) doen we een eigen backoff
if (sourceRef.current?.readyState === EventSource.CLOSED) {
const delay = backoffRef.current
backoffRef.current = Math.min(delay * 2, BACKOFF_MAX_MS)
reconnectTimerRef.current = setTimeout(connect, delay)
}
})
}
const onVisibilityChange = () => {
if (document.visibilityState === 'visible') {
if (!sourceRef.current || sourceRef.current.readyState === EventSource.CLOSED) {
connect()
}
} else {
close()
}
}
connect()
document.addEventListener('visibilitychange', onVisibilityChange)
return () => {
document.removeEventListener('visibilitychange', onVisibilityChange)
close()
}
}, [])
}

View file

@ -0,0 +1,61 @@
// ST-1105: Zustand store voor het Claude vraag-antwoord-kanaal (M11).
//
// Houdt de huidige set van **open** vragen voor de ingelogde gebruiker bij —
// gevoed door:
// - Initial-state-event van /api/realtime/notifications (init)
// - Realtime SSE-events op scrum4me_changes (upsert/remove)
// - Server Action answerQuestion (optimistic remove via removeOptimistic)
//
// Eenvoudiger dan solo-store: geen drag-and-drop, geen view-transitions, geen
// pending-ops om optimistic-echo te onderdrukken — antwoorden zijn discrete
// acties en de stream kan met dubbele update-events leven.
import { create } from 'zustand'
export interface NotificationQuestion {
id: string
product_id: string
story_id: string
task_id: string | null
story_code: string | null
story_title: string
assignee_id: string | null
question: string
options: string[] | null
created_at: string
expires_at: string
}
interface NotificationsState {
questions: NotificationQuestion[]
init: (qs: NotificationQuestion[]) => void
upsert: (q: NotificationQuestion) => void
remove: (id: string) => void
openCount: () => number
forYouCount: (userId: string | null) => number
}
export const useNotificationsStore = create<NotificationsState>((set, get) => ({
questions: [],
init: (qs) => set({ questions: qs }),
upsert: (q) =>
set((state) => {
const idx = state.questions.findIndex((x) => x.id === q.id)
if (idx === -1) return { questions: [q, ...state.questions] }
const next = state.questions.slice()
next[idx] = q
return { questions: next }
}),
remove: (id) =>
set((state) => ({ questions: state.questions.filter((q) => q.id !== id) })),
openCount: () => get().questions.length,
forYouCount: (userId) => {
if (!userId) return 0
return get().questions.filter((q) => q.assignee_id === userId).length
},
}))