Scrum4Me/lib/realtime/use-solo-realtime.ts
Madhura68 cefd54e56d chore(ST-806): cleanup debug-pages, document realtime, restore strict mode
M8 acceptance heeft de end-to-end pipeline bevestigd: trigger → NOTIFY →
SSE → store → View Transition. De cycling-symptomen waren een artefact
van testen via terminal (alt-tab triggert visibility-pause-by-design),
geen bug. Tijd om de tijdelijke instrumentatie en debug-pagina's weg te
halen en de architectuur op te schrijven.

- Verwijder /debug-realtime, /(app)/debug-realtime-app, /api/debug/*
- Strip debug-logs uit /api/realtime/solo (closed-reden alleen in dev)
- reactStrictMode weer aan
- CONNECTING_INDICATOR_DELAY_MS 2s → 4s (minder flikker bij micro-disconnects)
- Nieuwe sectie "Realtime updates (M8)" in scrum4me-architecture.md:
  diagram, NOTIFY-bron, server-filter, connection lifecycle inclusief
  visibility-pause + bekende beperking, animatie, auth
- DIRECT_URL env-rij uitgebreid met realtime-doel
- GET /api/realtime/solo gedocumenteerd in API.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 13:53:07 +02:00

153 lines
5.3 KiB
TypeScript

// ST-803 + ST-805 (refactor in ST-806-acceptance): client-side hook die de
// Solo Paneel realtime stream beheert.
//
// - Mount in de (app)-layout via SoloRealtimeBridge zodat hij Server Action-
// refreshes overleeft (anders kapt Next.js' soft-navigation de SSE).
// - Opent EventSource('/api/realtime/solo?product_id=...') wanneer
// productId niet null is; sluit de stream als productId null wordt.
// - Reconnect met exponential backoff (1s → 30s, reset bij ready).
// - Pauseert bij document.visibilityState === 'hidden', resumes bij visible.
// - Cleanup op unmount.
// - Connection-status (status, showConnectingIndicator) wordt naar de
// solo-store geschreven; UI-componenten lezen daar uit.
// - Dispatcht events naar de solo-store via handleRealtimeEvent. Task-
// updates worden in document.startViewTransition + flushSync gewikkeld
// zodat het kanban-kaartje soepel naar zijn nieuwe kolom animeert
// (animatie A — vereist view-transition-name op de cards).
'use client'
import { useEffect, useRef } from 'react'
import { flushSync } from 'react-dom'
import { useSoloStore } from '@/stores/solo-store'
import type { RealtimeEvent, RealtimeStatus } from '@/stores/solo-store'
const BACKOFF_START_MS = 1_000
const BACKOFF_MAX_MS = 30_000
const CONNECTING_INDICATOR_DELAY_MS = 4_000
export function useSoloRealtime(productId: string | null) {
const sourceRef = useRef<EventSource | null>(null)
const backoffRef = useRef<number>(BACKOFF_START_MS)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const indicatorTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(() => {
const setStatus = useSoloStore.getState().setRealtimeStatus
const handleEvent = useSoloStore.getState().handleRealtimeEvent
if (!productId) {
// Geen actief product (gebruiker zit niet op /solo) — stream uit
setStatus('disconnected', false)
return
}
const close = () => {
if (sourceRef.current) {
sourceRef.current.close()
sourceRef.current = null
}
if (reconnectTimerRef.current) {
clearTimeout(reconnectTimerRef.current)
reconnectTimerRef.current = null
}
}
const scheduleIndicator = (next: RealtimeStatus) => {
if (indicatorTimerRef.current) {
clearTimeout(indicatorTimerRef.current)
indicatorTimerRef.current = null
}
if (next === 'open') {
setStatus('open', false)
} else {
// Status meteen bijwerken, indicator pas na 4s — voorkomt flikker
// bij microscopische disconnects.
setStatus(next, false)
indicatorTimerRef.current = setTimeout(() => {
setStatus(useSoloStore.getState().realtimeStatus, true)
}, CONNECTING_INDICATOR_DELAY_MS)
}
}
const connect = () => {
close()
scheduleIndicator('connecting')
const source = new EventSource(
`/api/realtime/solo?product_id=${encodeURIComponent(productId)}`,
)
sourceRef.current = source
source.addEventListener('ready', () => {
backoffRef.current = BACKOFF_START_MS
scheduleIndicator('open')
})
source.onmessage = (e) => {
if (!e.data) return
try {
const payload = JSON.parse(e.data) as RealtimeEvent
// Animatie A: kanban-move animeren via View Transitions API. Voor
// task UPDATE-events wrap'en we de store-update in een view
// transition. flushSync forceert React om synchroon te renderen
// tijdens de transition-callback zodat de nieuwe DOM-state wordt
// gesnapshot voor de animatie.
const animate =
payload.entity === 'task' &&
payload.op === 'U' &&
typeof document !== 'undefined' &&
typeof (document as Document & { startViewTransition?: unknown }).startViewTransition ===
'function'
if (animate) {
;(
document as Document & {
startViewTransition: (cb: () => void) => unknown
}
).startViewTransition(() => {
flushSync(() => handleEvent(payload))
})
} else {
handleEvent(payload)
}
} catch (err) {
if (process.env.NODE_ENV !== 'production') {
console.error('[realtime] failed to parse event', err, e.data)
}
}
}
source.onerror = () => {
if (sourceRef.current !== source) return
close()
scheduleIndicator('disconnected')
if (document.visibilityState === 'hidden') return
const delay = backoffRef.current
backoffRef.current = Math.min(backoffRef.current * 2, BACKOFF_MAX_MS)
reconnectTimerRef.current = setTimeout(connect, delay)
}
}
const onVisibility = () => {
if (document.visibilityState === 'hidden') {
close()
scheduleIndicator('disconnected')
} else if (sourceRef.current === null) {
backoffRef.current = BACKOFF_START_MS
connect()
}
}
if (document.visibilityState === 'visible') {
connect()
}
document.addEventListener('visibilitychange', onVisibility)
return () => {
document.removeEventListener('visibilitychange', onVisibility)
if (indicatorTimerRef.current) clearTimeout(indicatorTimerRef.current)
close()
}
}, [productId])
}