Phase 6 abgeschlossen: Aktenchat, Kanäle, Echtzeit, Benachrichtigungen
Ein Ereignisstrom mit Themen (/api/stream), in dem der Dateistrom aus Phase 5 aufgegangen ist. Zwei Prüfungen: beim Verbinden, welche Themen der Nutzer abonnieren darf, und je Ereignis wird der Inhalt mit seinen Rechten geladen. Das zweite ist nicht nur Vorsicht - eine Umklassifizierung wirkt dadurch in einer offenen Verbindung sofort. In der pg_notify-Nutzlast steht nie ein Inhalt, nur Thema, Art und Kennung. Der Aktenchat sendet optimistisch mit clientseitiger UUIDv7, die zugleich Idempotenzschlüssel ist. Antworten, vier feste Reaktionen, Bearbeiten mit sichtbarem editedAt, Zurückziehen mit Platzhalter - Löschen gibt es nicht, und eine Regel in der Datenbank hält das fest. Eine zurückgezogene Nachricht kommt ohne Text an, nicht ausgeblendet. Aktenzeichen im Text werden zu Vorschaukarten, serverseitig aufgelöst. Eine Akte, die der Leser nicht sehen darf, sieht darin genauso aus wie eine, die es gar nicht gibt. "Als Vermerk übernehmen" steht sichtbar an jeder Nachricht. Der Vermerk gehört dem Verfasser, nicht dem Übernehmenden; ein Systemeintrag nennt den Ursprung, damit der Wortlaut später nicht für die Akte geschrieben wirkt. Bei den Discord-Benachrichtigungen entscheidet die Web-App, wer was erfährt, und der Worker liefert nur aus. Die Alternative hätte geheissen, die Sichtbarkeitsprüfung im Worker ein zweites Mal zu bauen. In meta steht ein Titel nur, wenn er hinaus darf - ab Stufe 3 keiner. Postausgang als Tabelle, angestossen über LISTEN, mit Takt als Sicherheitsnetz. Nebenbei riss das Budget der Fallakte erneut (122 kB). Drei Schritte zurück auf 119,6: Chattexte in eine eigene i18n-Datei, ein gemeinsames AddPanel statt viermal derselbe Aufklapp-Code, und eine eigene UUIDv7 statt des Pakets - die Sortierbarkeit, auf der die Nachlieferung beruht, steht damit im eigenen Code und hat Tests. Unterwegs habe ich NotifyMode und User.notifyMode ein zweites Mal angelegt, obwohl es beides seit dem Grundgerüst gibt. Die Migration schlug fehl und die Datenbank musste von Hand aufgeräumt werden; die Lehre steht in docs/13. 155 Tests im Web-Paket, 15 in der Datenbank, 7 im Worker, 32 e2e.
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useTransition, type ReactNode } from 'react'
|
||||
import { commonText } from '@/lib/i18n/common'
|
||||
|
||||
/**
|
||||
* Ein aufklappbares Formular zum Hinzufügen.
|
||||
*
|
||||
* Beteiligte, Verknüpfungen, Dokumente, Zuordnungen — überall derselbe Ablauf:
|
||||
* ein Knopf, ein kleines Formular, eine Server Action, eine Fehlermeldung an
|
||||
* Ort und Stelle. Das viermal zu wiederholen kostete nicht nur Zeilen, sondern
|
||||
* auch Bündelgrösse auf der Fallakte, die ohnehin die dichteste Seite ist.
|
||||
*
|
||||
* Der Rückruf bekommt `schliessen`, damit das Formular nur nach einem Erfolg
|
||||
* zugeht — ein Fehler soll die Eingabe nicht wegräumen.
|
||||
*/
|
||||
export function AddPanel({
|
||||
label,
|
||||
hint,
|
||||
children,
|
||||
submitLabel,
|
||||
onSubmit,
|
||||
disabled,
|
||||
}: {
|
||||
label: string
|
||||
hint?: string
|
||||
/** Die Eingabefelder. Bekommen den Wartezustand über `disabled`. */
|
||||
children: ReactNode
|
||||
submitLabel?: string
|
||||
onSubmit: () => Promise<{ ok: boolean; error?: string }>
|
||||
disabled?: boolean
|
||||
}) {
|
||||
const [offen, setOffen] = useState(false)
|
||||
const [fehler, setFehler] = useState<string | null>(null)
|
||||
const [pending, startTransition] = useTransition()
|
||||
|
||||
if (!offen) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOffen(true)}
|
||||
className="mt-4 border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent"
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-4 border border-line p-3">
|
||||
{hint ? <p className="max-w-(--container-measure) text-2xs text-text-dim">{hint}</p> : null}
|
||||
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
{children}
|
||||
<button
|
||||
type="button"
|
||||
disabled={pending || disabled}
|
||||
onClick={() =>
|
||||
startTransition(async () => {
|
||||
setFehler(null)
|
||||
const ergebnis = await onSubmit()
|
||||
if (ergebnis.ok) setOffen(false)
|
||||
else setFehler(ergebnis.error ?? commonText.retry)
|
||||
})
|
||||
}
|
||||
className="border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent disabled:text-text-dim"
|
||||
>
|
||||
{submitLabel ?? label}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOffen(false)}
|
||||
className="font-condensed text-2xs text-text-dim"
|
||||
>
|
||||
{commonText.cancel}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{fehler ? <p className="mt-2 font-condensed text-2xs text-stamp-4">{fehler}</p> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Die Auswahlfelder in einem `AddPanel` sehen überall gleich aus. */
|
||||
export function PanelSelect({
|
||||
value,
|
||||
onChange,
|
||||
label,
|
||||
children,
|
||||
}: {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
label: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<select
|
||||
value={value}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
aria-label={label}
|
||||
className="border border-line bg-raised px-2 py-1 text-2xs"
|
||||
>
|
||||
{children}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useTransition } from 'react'
|
||||
import { uuidv7 } from '@/lib/uuidv7'
|
||||
import { chatText } from '@/lib/i18n/chat'
|
||||
import { commonText } from '@/lib/i18n/common'
|
||||
import { REACTIONS } from '@/lib/chat/terms'
|
||||
import { useStream } from '@/components/realtime/useStream'
|
||||
import { MessageBody } from './MessageBody'
|
||||
import {
|
||||
adoptAsEntryAction,
|
||||
editMessageAction,
|
||||
markReadAction,
|
||||
sendMessageAction,
|
||||
toggleReactionAction,
|
||||
withdrawMessageAction,
|
||||
} from '@/app/(app)/chat/actions'
|
||||
import type { ChatMessageView } from '@/lib/chat/view'
|
||||
|
||||
export type ChatScopeView =
|
||||
| { kind: 'case'; caseNumber: string; caseId: string }
|
||||
| { kind: 'channel'; key: string; channelId: string }
|
||||
|
||||
type Reaktion = { messageId: string; userId: string; key: string }
|
||||
|
||||
/**
|
||||
* Aktenchat und Kanalchat.
|
||||
*
|
||||
* Optisch klar vom Verlauf abgesetzt, weil er inhaltlich etwas anderes ist:
|
||||
* formlos, kein Aktenbestandteil. Die Zeitachse des Verlaufs hat eine
|
||||
* durchgehende Linie, der Chat nicht — der Unterschied muss ohne Beschriftung
|
||||
* erkennbar sein. Siehe docs/10-design-system.md.
|
||||
*
|
||||
* Gesendet wird optimistisch: die Nachricht steht sofort da, mit einer
|
||||
* clientseitig erzeugten UUIDv7 als Kennung. Kommt dieselbe Kennung über den
|
||||
* Strom zurück, wird der optimistische Eintrag ersetzt statt verdoppelt — und
|
||||
* ein wiederholtes Absenden nach einem Netzfehler erzeugt keine zweite
|
||||
* Nachricht. Siehe docs/09-performance-und-ux.md.
|
||||
*/
|
||||
export function Chat({
|
||||
scope,
|
||||
topic,
|
||||
initial,
|
||||
initialReactions,
|
||||
currentUserId,
|
||||
lastReadAt,
|
||||
canAdopt,
|
||||
mentionNames,
|
||||
}: {
|
||||
scope: ChatScopeView
|
||||
topic: string
|
||||
initial: ChatMessageView[]
|
||||
initialReactions: Reaktion[]
|
||||
currentUserId: string
|
||||
lastReadAt: string | null
|
||||
canAdopt: boolean
|
||||
mentionNames: Record<string, string>
|
||||
}) {
|
||||
const [nachrichten, setNachrichten] = useState(initial)
|
||||
const [reaktionen, setReaktionen] = useState(initialReactions)
|
||||
const [text, setText] = useState('')
|
||||
const [antwortAuf, setAntwortAuf] = useState<string | null>(null)
|
||||
const [bearbeitet, setBearbeitet] = useState<string | null>(null)
|
||||
const [entwurf, setEntwurf] = useState('')
|
||||
const [fehler, setFehler] = useState<string | null>(null)
|
||||
const [pending, startTransition] = useTransition()
|
||||
const ende = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Die Trennlinie friert beim ersten Rendern ein: sie soll nicht
|
||||
// verschwinden, während man liest.
|
||||
const [grenze] = useState(lastReadAt)
|
||||
|
||||
const namen = useMemo(() => new Map(Object.entries(mentionNames)), [mentionNames])
|
||||
|
||||
const eingetroffen = useCallback((data: unknown) => {
|
||||
const nachricht = data as ChatMessageView
|
||||
setNachrichten((bisher) => {
|
||||
const index = bisher.findIndex((n) => n.id === nachricht.id)
|
||||
// Dedupe über die Kennung: der optimistische Eintrag wird ersetzt.
|
||||
if (index >= 0) {
|
||||
const kopie = [...bisher]
|
||||
kopie[index] = nachricht
|
||||
return kopie
|
||||
}
|
||||
return [...bisher, nachricht]
|
||||
})
|
||||
}, [])
|
||||
|
||||
useStream([topic], {
|
||||
'chat.new': eingetroffen,
|
||||
'chat.edit': eingetroffen,
|
||||
'chat.withdrawn': eingetroffen,
|
||||
'chat.adopted': eingetroffen,
|
||||
'chat.reaction': () => {
|
||||
// Reaktionen sind zu klein für ein eigenes Nutzlastformat; die Ansicht
|
||||
// holt sie beim nächsten Laden nach.
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
ende.current?.scrollIntoView({ block: 'nearest' })
|
||||
}, [nachrichten.length])
|
||||
|
||||
// Beim Verlassen der Seite die Lesemarke setzen, nicht beim Öffnen: sonst
|
||||
// wäre die Trennlinie beim Neuladen sofort weg.
|
||||
useEffect(() => {
|
||||
const scopeId = scope.kind === 'case' ? scope.caseId : scope.channelId
|
||||
return () => {
|
||||
void markReadAction({ scopeType: scope.kind, scopeId })
|
||||
}
|
||||
}, [scope])
|
||||
|
||||
function senden() {
|
||||
const inhalt = text.trim()
|
||||
if (!inhalt) return
|
||||
|
||||
const id = uuidv7()
|
||||
const optimistisch: ChatMessageView = {
|
||||
id,
|
||||
body: inhalt,
|
||||
authorId: currentUserId,
|
||||
authorName: namen.get('__self__') ?? commonText.loading,
|
||||
replyToId: antwortAuf,
|
||||
editedAt: null,
|
||||
withdrawnAt: null,
|
||||
adoptedEntryId: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
previews: {},
|
||||
}
|
||||
|
||||
setNachrichten((bisher) => [...bisher, optimistisch])
|
||||
setText('')
|
||||
setAntwortAuf(null)
|
||||
setFehler(null)
|
||||
|
||||
startTransition(async () => {
|
||||
const ergebnis = await sendMessageAction({
|
||||
id,
|
||||
scope: scope.kind === 'case' ? { kind: 'case', caseNumber: scope.caseNumber } : { kind: 'channel', key: scope.key },
|
||||
body: inhalt,
|
||||
replyToId: optimistisch.replyToId,
|
||||
})
|
||||
if (!ergebnis.ok) {
|
||||
// Der optimistische Eintrag verschwindet wieder, der Text kommt
|
||||
// zurück ins Feld. Nichts geht verloren.
|
||||
setNachrichten((bisher) => bisher.filter((n) => n.id !== id))
|
||||
setText(inhalt)
|
||||
setFehler(ergebnis.error)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const nachId = new Map(nachrichten.map((n) => [n.id, n]))
|
||||
|
||||
return (
|
||||
<div className="border border-line">
|
||||
<div className="border-b border-line px-4 py-2">
|
||||
<p className="font-condensed text-xs text-text-dim">{chatText.heading}</p>
|
||||
<p className="mt-0.5 text-2xs text-text-dim">{chatText.hint}</p>
|
||||
</div>
|
||||
|
||||
<ol className="max-h-[28rem] space-y-4 overflow-y-auto px-4 py-4">
|
||||
{nachrichten.length === 0 ? (
|
||||
<li className="text-text-dim">{chatText.empty}</li>
|
||||
) : null}
|
||||
|
||||
{nachrichten.map((nachricht, index) => {
|
||||
const vorherige = nachrichten[index - 1]
|
||||
const neuAbHier =
|
||||
grenze !== null &&
|
||||
nachricht.createdAt > grenze &&
|
||||
(!vorherige || vorherige.createdAt <= grenze)
|
||||
|
||||
return (
|
||||
<li key={nachricht.id}>
|
||||
{neuAbHier ? (
|
||||
<p className="mb-3 flex items-center gap-3 font-condensed text-2xs text-stamp-3">
|
||||
<span className="h-px grow bg-stamp-3" />
|
||||
{chatText.unreadDivider}
|
||||
<span className="h-px grow bg-stamp-3" />
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{nachricht.replyToId ? (
|
||||
<p className="mb-1 border-l-(length:--spacing-edge) border-line pl-2 text-2xs text-text-dim">
|
||||
{chatText.replyingTo} {nachId.get(nachricht.replyToId)?.authorName ?? '—'}:{' '}
|
||||
{(nachId.get(nachricht.replyToId)?.body ?? '').slice(0, 80)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex flex-wrap items-baseline gap-x-3 text-2xs text-text-dim">
|
||||
<span className="font-condensed">{nachricht.authorName}</span>
|
||||
<time dateTime={nachricht.createdAt}>
|
||||
{new Date(nachricht.createdAt).toLocaleString('de-DE')}
|
||||
</time>
|
||||
{nachricht.editedAt ? <span>{chatText.edited}</span> : null}
|
||||
{nachricht.adoptedEntryId ? (
|
||||
<span className="font-condensed text-accent">{chatText.adopted}</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{nachricht.withdrawnAt ? (
|
||||
<p className="mt-0.5 text-sm text-text-dim italic">{chatText.withdrawn}</p>
|
||||
) : bearbeitet === nachricht.id ? (
|
||||
<div className="mt-1">
|
||||
<textarea
|
||||
value={entwurf}
|
||||
onChange={(event) => setEntwurf(event.target.value)}
|
||||
rows={2}
|
||||
className="block w-full border border-line bg-raised px-3 py-2 text-sm"
|
||||
/>
|
||||
<div className="mt-1 flex gap-3">
|
||||
<button
|
||||
type="button"
|
||||
disabled={pending}
|
||||
onClick={() =>
|
||||
startTransition(async () => {
|
||||
const ergebnis = await editMessageAction({
|
||||
id: nachricht.id,
|
||||
body: entwurf,
|
||||
})
|
||||
if (ergebnis.ok) setBearbeitet(null)
|
||||
else setFehler(ergebnis.error)
|
||||
})
|
||||
}
|
||||
className="font-condensed text-2xs text-accent"
|
||||
>
|
||||
{chatText.editSave}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBearbeitet(null)}
|
||||
className="font-condensed text-2xs text-text-dim"
|
||||
>
|
||||
{commonText.cancel}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-0.5">
|
||||
<MessageBody
|
||||
body={nachricht.body}
|
||||
mentionNames={namen}
|
||||
previews={new Map(Object.entries(nachricht.previews))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-2xs">
|
||||
{REACTIONS.map((key) => {
|
||||
const anzahl = reaktionen.filter(
|
||||
(r) => r.messageId === nachricht.id && r.key === key,
|
||||
).length
|
||||
const eigene = reaktionen.some(
|
||||
(r) => r.messageId === nachricht.id && r.key === key && r.userId === currentUserId,
|
||||
)
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
title={chatText.reactions[key]}
|
||||
onClick={() =>
|
||||
startTransition(async () => {
|
||||
// Sofort umschalten, der Server bestätigt nur.
|
||||
setReaktionen((bisher) =>
|
||||
eigene
|
||||
? bisher.filter(
|
||||
(r) =>
|
||||
!(r.messageId === nachricht.id && r.key === key && r.userId === currentUserId),
|
||||
)
|
||||
: [...bisher, { messageId: nachricht.id, userId: currentUserId, key }],
|
||||
)
|
||||
await toggleReactionAction({ id: nachricht.id, key })
|
||||
})
|
||||
}
|
||||
className={`border px-1.5 py-0.5 font-mono ${
|
||||
eigene ? 'border-accent text-accent' : 'border-line text-text-dim'
|
||||
}`}
|
||||
>
|
||||
{chatText.reactionSymbols[key]}
|
||||
{anzahl > 0 ? ` ${anzahl}` : ''}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
|
||||
{!nachricht.withdrawnAt ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAntwortAuf(nachricht.id)}
|
||||
className="font-condensed text-text-dim"
|
||||
>
|
||||
{chatText.reply}
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{/* Die Brücke zum Aktenbestand steht sichtbar an jeder
|
||||
Nachricht, nicht in einem Kontextmenü. Siehe docs/06. */}
|
||||
{canAdopt && !nachricht.withdrawnAt && !nachricht.adoptedEntryId ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={pending}
|
||||
onClick={() =>
|
||||
startTransition(async () => {
|
||||
const ergebnis = await adoptAsEntryAction({ id: nachricht.id })
|
||||
if (!ergebnis.ok) setFehler(ergebnis.error)
|
||||
})
|
||||
}
|
||||
className="font-condensed text-accent"
|
||||
>
|
||||
{chatText.adopt}
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
{nachricht.authorId === currentUserId && !nachricht.withdrawnAt ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setBearbeitet(nachricht.id)
|
||||
setEntwurf(nachricht.body)
|
||||
}}
|
||||
className="font-condensed text-text-dim"
|
||||
>
|
||||
{chatText.edit}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={pending}
|
||||
onClick={() =>
|
||||
startTransition(async () => {
|
||||
await withdrawMessageAction({ id: nachricht.id })
|
||||
})
|
||||
}
|
||||
className="font-condensed text-text-dim"
|
||||
>
|
||||
{chatText.withdraw}
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
<div ref={ende} />
|
||||
</ol>
|
||||
|
||||
<div className="border-t border-line px-4 py-3">
|
||||
{antwortAuf ? (
|
||||
<p className="mb-2 flex items-center gap-3 text-2xs text-text-dim">
|
||||
{chatText.replyingTo} {nachId.get(antwortAuf)?.authorName ?? '—'}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAntwortAuf(null)}
|
||||
className="font-condensed"
|
||||
>
|
||||
{chatText.cancelReply}
|
||||
</button>
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(event) => setText(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
// Eingabetaste sendet, Umschalt+Eingabe macht einen Umbruch.
|
||||
if (event.key === 'Enter' && !event.shiftKey) {
|
||||
event.preventDefault()
|
||||
senden()
|
||||
}
|
||||
}}
|
||||
rows={2}
|
||||
placeholder={chatText.placeholder}
|
||||
aria-label={chatText.placeholder}
|
||||
className="block w-full border border-line bg-raised px-3 py-2 text-sm"
|
||||
/>
|
||||
|
||||
<div className="mt-2 flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={senden}
|
||||
disabled={text.trim() === ''}
|
||||
className="border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent disabled:text-text-dim"
|
||||
>
|
||||
{chatText.send}
|
||||
</button>
|
||||
{fehler ? <span className="font-condensed text-2xs text-stamp-4">{fehler}</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
'use client'
|
||||
|
||||
import dynamic from 'next/dynamic'
|
||||
import { useEffect, useRef, useState, type ComponentProps } from 'react'
|
||||
import { chatText } from '@/lib/i18n/chat'
|
||||
import { SkeletonLine } from '@/components/Skeleton'
|
||||
import type { Chat } from './Chat'
|
||||
|
||||
const ChatInner = dynamic(() => import('./Chat').then((modul) => modul.Chat), {
|
||||
loading: () => <Platzhalter />,
|
||||
// Der Chat wird ohnehin erst nach dem Scrollen gebraucht und lebt von einer
|
||||
// offenen Verbindung. Ihn auf dem Server mitzurendern brächte nichts und
|
||||
// zöge sein Bündel in die erste Ladung der Fallakte.
|
||||
ssr: false,
|
||||
})
|
||||
|
||||
/**
|
||||
* Lädt den Chat erst, wenn er in Sichtweite kommt.
|
||||
*
|
||||
* Zwei Gründe, beide handfest: die Fallakte ist das, weswegen die Seite
|
||||
* geöffnet wird — ihr Bündelbudget soll nicht für einen Chat draufgehen, den
|
||||
* viele nie aufklappen. Und der Chat hält eine offene Verbindung zum
|
||||
* Ereignisstrom; wer nur die Akte liest, soll sie nicht aufbauen.
|
||||
*
|
||||
* Der Platzhalter hat die Höhe des Chats, damit beim Nachladen nichts springt.
|
||||
* Siehe docs/09-performance-und-ux.md.
|
||||
*/
|
||||
export function ChatLazy(props: ComponentProps<typeof Chat>) {
|
||||
const [sichtbar, setSichtbar] = useState(false)
|
||||
const anker = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const element = anker.current
|
||||
if (!element) return
|
||||
|
||||
// Ohne IntersectionObserver (sehr alte Browser) sofort laden: lieber
|
||||
// grösser als kaputt.
|
||||
if (typeof IntersectionObserver === 'undefined') {
|
||||
setSichtbar(true)
|
||||
return
|
||||
}
|
||||
|
||||
const beobachter = new IntersectionObserver(
|
||||
(eintraege) => {
|
||||
if (eintraege.some((eintrag) => eintrag.isIntersecting)) {
|
||||
setSichtbar(true)
|
||||
beobachter.disconnect()
|
||||
}
|
||||
},
|
||||
// Etwas vorher anfangen, damit er beim Ankommen schon steht.
|
||||
{ rootMargin: '300px' },
|
||||
)
|
||||
beobachter.observe(element)
|
||||
return () => beobachter.disconnect()
|
||||
}, [])
|
||||
|
||||
return <div ref={anker}>{sichtbar ? <ChatInner {...props} /> : <Platzhalter />}</div>
|
||||
}
|
||||
|
||||
function Platzhalter() {
|
||||
return (
|
||||
<div className="border border-line">
|
||||
<div className="border-b border-line px-4 py-2">
|
||||
<p className="font-condensed text-xs text-text-dim">{chatText.heading}</p>
|
||||
</div>
|
||||
<div className="space-y-3 px-4 py-4">
|
||||
<SkeletonLine width="12rem" />
|
||||
<SkeletonLine width="70%" />
|
||||
<SkeletonLine width="55%" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import Link from 'next/link'
|
||||
import { chatText } from '@/lib/i18n/chat'
|
||||
import { splitBody } from '@/lib/chat/mentions'
|
||||
import { stampColor } from '@/components/StampMark'
|
||||
import type { CasePreview } from '@/lib/chat/preview'
|
||||
|
||||
/**
|
||||
* Nachrichtentext mit hervorgehobenen Erwähnungen und Aktenzeichen.
|
||||
*
|
||||
* Der Text wird **zerlegt**, nicht als HTML gebaut: kein
|
||||
* `dangerouslySetInnerHTML` für Nutzerinhalte, siehe docs/07.
|
||||
*
|
||||
* Die Vorschaukarte zu einem Aktenzeichen ist serverseitig aufgelöst. Eine
|
||||
* Akte, die der Leser nicht sehen darf, sieht hier genauso aus wie eine, die
|
||||
* es gar nicht gibt.
|
||||
*/
|
||||
export function MessageBody({
|
||||
body,
|
||||
mentionNames,
|
||||
previews,
|
||||
}: {
|
||||
body: string
|
||||
/** Anzeigename je erwähntem Benutzernamen, kleingeschrieben. */
|
||||
mentionNames: Map<string, string>
|
||||
previews: Map<string, CasePreview>
|
||||
}) {
|
||||
const stuecke = splitBody(body)
|
||||
|
||||
return (
|
||||
<p className="max-w-(--container-measure) text-sm whitespace-pre-wrap">
|
||||
{stuecke.map((stueck, index) => {
|
||||
if (stueck.kind === 'text') return <span key={index}>{stueck.value}</span>
|
||||
|
||||
if (stueck.kind === 'mention') {
|
||||
const name = stueck.value.slice(1).toLowerCase()
|
||||
const bekannt = mentionNames.has(name)
|
||||
return (
|
||||
<span
|
||||
key={index}
|
||||
className={bekannt ? 'font-condensed text-accent' : undefined}
|
||||
title={bekannt ? mentionNames.get(name) : undefined}
|
||||
>
|
||||
{stueck.value}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const vorschau = previews.get(stueck.value)
|
||||
if (!vorschau) return <span key={index}>{stueck.value}</span>
|
||||
|
||||
if (!vorschau.visible) {
|
||||
return (
|
||||
<span key={index} className="font-mono text-2xs text-text-dim">
|
||||
{stueck.value} · {chatText.hiddenCase}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={index}
|
||||
href={`/faelle/${vorschau.caseNumber}`}
|
||||
prefetch
|
||||
className="inline-flex items-baseline gap-2 border-l-(length:--spacing-edge) pl-2 no-underline"
|
||||
style={{ borderColor: stampColor(vorschau.classification) }}
|
||||
>
|
||||
<span className="font-mono text-2xs text-text-dim">{vorschau.caseNumber}</span>
|
||||
<span className="text-sm">{vorschau.title}</span>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { useCallback, useRef, useState, useTransition } from 'react'
|
||||
import { attachmentText } from '@/lib/i18n/documents'
|
||||
import { MAX_FILE_BYTES, formatBytes } from '@/lib/files/limits'
|
||||
import { releaseAttachmentAction } from '@/app/(app)/dateien/actions'
|
||||
import { useScanEvents, type ScanEvent } from './useScanEvents'
|
||||
import { useStream, type ScanEvent } from '@/components/realtime/useStream'
|
||||
|
||||
export type AttachmentView = {
|
||||
id: string
|
||||
@@ -39,11 +39,14 @@ type Laufend = { key: string; name: string; progress: number; error?: string }
|
||||
*/
|
||||
export function Attachments({
|
||||
target,
|
||||
topic,
|
||||
initial,
|
||||
canUpload,
|
||||
canRelease,
|
||||
}: {
|
||||
target: UploadTarget
|
||||
/** Thema des Besitzers, damit die Prüfergebnisse ankommen. */
|
||||
topic: string
|
||||
initial: AttachmentView[]
|
||||
canUpload: boolean
|
||||
canRelease: boolean
|
||||
@@ -73,7 +76,7 @@ export function Attachments({
|
||||
)
|
||||
}, [])
|
||||
|
||||
useScanEvents(uebernehmen)
|
||||
useStream([topic], { 'attachment.scanned': (data) => uebernehmen(data as ScanEvent) })
|
||||
|
||||
function hochladen(datei: File) {
|
||||
const key = `${datei.name}-${Date.now()}-${Math.random()}`
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import { attachmentText, documentText } from '@/lib/i18n/documents'
|
||||
import { MAX_FILE_BYTES } from '@/lib/files/limits'
|
||||
import { useScanEvents, type ScanEvent } from './useScanEvents'
|
||||
import { useStream, type ScanEvent } from '@/components/realtime/useStream'
|
||||
import type { SaveSection } from '@/components/sections/types'
|
||||
|
||||
/**
|
||||
@@ -22,6 +22,7 @@ export function PhotoField({
|
||||
fieldKey,
|
||||
label,
|
||||
documentNumber,
|
||||
topic,
|
||||
initialAttachmentId,
|
||||
initialUrl,
|
||||
initialVersion,
|
||||
@@ -31,6 +32,8 @@ export function PhotoField({
|
||||
fieldKey: string
|
||||
label: string
|
||||
documentNumber: string
|
||||
/** Thema des Besitzers, damit das Prüfergebnis ankommt. */
|
||||
topic: string
|
||||
initialAttachmentId: string | null
|
||||
initialUrl: string | null
|
||||
initialVersion: number
|
||||
@@ -61,7 +64,7 @@ export function PhotoField({
|
||||
[wartetAuf],
|
||||
)
|
||||
|
||||
useScanEvents(geprueft)
|
||||
useStream([topic], { 'attachment.scanned': (data) => geprueft(data as ScanEvent) })
|
||||
|
||||
function waehlen(datei: File) {
|
||||
setFehler(null)
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
|
||||
export type ScanEvent = {
|
||||
id: string
|
||||
scanStatus: 'PENDING' | 'CLEAN' | 'BLOCKED' | 'FAILED'
|
||||
scanMessage: string | null
|
||||
mimeType: string
|
||||
sizeBytes: number
|
||||
blurhash: string | null
|
||||
width: number | null
|
||||
height: number | null
|
||||
hasThumb: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Hört auf das Ende von Dateiprüfungen.
|
||||
*
|
||||
* Eine einzige Verbindung je Seite, vom Browser selbst wieder aufgebaut, wenn
|
||||
* sie abreisst. Kein Abfragen im Sekundentakt: eine Prüfung dauert je nach
|
||||
* Dateigrösse zwischen einer und dreissig Sekunden, und solange im Leerlauf zu
|
||||
* fragen wäre auf einem Heimserver unhöflich.
|
||||
*/
|
||||
export function useScanEvents(onScanned: (event: ScanEvent) => void): void {
|
||||
useEffect(() => {
|
||||
const quelle = new EventSource('/api/events')
|
||||
|
||||
const handler = (message: MessageEvent<string>) => {
|
||||
try {
|
||||
onScanned(JSON.parse(message.data) as ScanEvent)
|
||||
} catch {
|
||||
// Kaputte Nutzlast ignorieren, der nächste Seitenaufbau hat den Stand.
|
||||
}
|
||||
}
|
||||
|
||||
quelle.addEventListener('attachment.scanned', handler as EventListener)
|
||||
return () => {
|
||||
quelle.removeEventListener('attachment.scanned', handler as EventListener)
|
||||
quelle.close()
|
||||
}
|
||||
}, [onScanned])
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef } from 'react'
|
||||
|
||||
/**
|
||||
* Eine Verbindung zum Ereignisstrom, so lange die Ansicht offen ist.
|
||||
*
|
||||
* `EventSource` baut nach einem Abriss von selbst wieder auf und schickt dabei
|
||||
* die zuletzt gesehene Kennung mit, sodass der Server nachliefern kann. Das
|
||||
* Aufräumen bei Tabwechsel übernimmt der Browser: eine Verbindung ohne
|
||||
* Verkehr kostet nichts.
|
||||
*
|
||||
* Die Rückrufe stehen in einem Ref, damit ein neu erzeugter Handler nicht die
|
||||
* ganze Verbindung neu aufbaut — sonst reisst der Strom bei jedem Tastendruck
|
||||
* im Eingabefeld ab.
|
||||
*/
|
||||
export type StreamHandlers = Record<string, (data: unknown) => void>
|
||||
|
||||
export function useStream(topics: string[], handlers: StreamHandlers): void {
|
||||
const aktuell = useRef(handlers)
|
||||
aktuell.current = handlers
|
||||
|
||||
// Die Themen als Zeichenkette, damit ein neues Array mit gleichem Inhalt
|
||||
// keine neue Verbindung auslöst.
|
||||
const schluessel = topics.filter(Boolean).sort().join(',')
|
||||
|
||||
useEffect(() => {
|
||||
if (!schluessel) return
|
||||
|
||||
const quelle = new EventSource(`/api/stream?topics=${encodeURIComponent(schluessel)}`)
|
||||
const angemeldet: [string, EventListener][] = []
|
||||
|
||||
for (const name of Object.keys(aktuell.current)) {
|
||||
const listener: EventListener = (event) => {
|
||||
const nachricht = event as MessageEvent<string>
|
||||
try {
|
||||
aktuell.current[name]?.(JSON.parse(nachricht.data))
|
||||
} catch {
|
||||
// Kaputte Nutzlast ignorieren; der nächste Seitenaufbau hat den Stand.
|
||||
}
|
||||
}
|
||||
quelle.addEventListener(name, listener)
|
||||
angemeldet.push([name, listener])
|
||||
}
|
||||
|
||||
return () => {
|
||||
for (const [name, listener] of angemeldet) quelle.removeEventListener(name, listener)
|
||||
quelle.close()
|
||||
}
|
||||
// Absichtlich nur an den Themen: die Rückrufe hängen im Ref.
|
||||
}, [schluessel])
|
||||
}
|
||||
|
||||
export type ScanEvent = {
|
||||
id: string
|
||||
scanStatus: 'PENDING' | 'CLEAN' | 'BLOCKED' | 'FAILED'
|
||||
scanMessage: string | null
|
||||
mimeType: string
|
||||
sizeBytes: number
|
||||
blurhash: string | null
|
||||
width: number | null
|
||||
height: number | null
|
||||
hasThumb: boolean
|
||||
}
|
||||
@@ -20,6 +20,7 @@ export function Sections({
|
||||
sections,
|
||||
canEdit,
|
||||
documentNumber,
|
||||
topic,
|
||||
photoUrls,
|
||||
}: {
|
||||
scope: string
|
||||
@@ -28,6 +29,8 @@ export function Sections({
|
||||
canEdit: boolean
|
||||
/** Nur bei Dokumenten gesetzt: Ziel für das Lichtbild. */
|
||||
documentNumber?: string
|
||||
/** Thema für die Rückmeldung der Dateiprüfung. */
|
||||
topic?: string
|
||||
/** Bereits geprüfte Lichtbilder, je Feldschlüssel. */
|
||||
photoUrls?: Record<string, string>
|
||||
}) {
|
||||
@@ -77,6 +80,7 @@ export function Sections({
|
||||
fieldKey={field.key}
|
||||
label={field.label}
|
||||
documentNumber={documentNumber}
|
||||
topic={topic ?? ''}
|
||||
initialAttachmentId={
|
||||
section.visible && typeof section.value === 'string' ? section.value : null
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user