feat(events): deliver state changes to the configurable operator event center

This commit is contained in:
DCCONSTRUCTIONS
2026-11-21 20:58:27 +03:00
parent d4ed96f3cd
commit 1b67d5f7df
35 changed files with 2058 additions and 8 deletions
@@ -0,0 +1,22 @@
export type NotificationTone='success'|'error'|'warning'|'info';
export interface NotificationMessage {id:string;tone:NotificationTone|'loading';title:string;description?:string;durationMs?:number|null}
export interface NotificationRecord {sequence:number;identity:string;at:number;tone:NotificationTone;title:string;description:string;source:string;read:number}
export interface NotificationPage {items:NotificationRecord[];unread:number;latest:number;retention_limit:number}
export async function notificationRequest<T>(path='',method='GET',body?:unknown):Promise<T>{
const response=await fetch('/api/v1/notifications'+path,{method,credentials:'same-origin',cache:'no-store',signal:AbortSignal.timeout(10000),headers:body===undefined?{}:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});
if(!response.ok)throw new Error('История уведомлений временно недоступна.');
return response.json();
}
export function mergeNotifications(current:NotificationRecord[],incoming:NotificationRecord[]){
return [...new Map([...current,...incoming].map(item=>[item.sequence,item])).values()].sort((a,b)=>b.sequence-a.sequence).slice(0,5000);
}
export function networkToasts(items:NotificationRecord[],seen:Set<string>,now:number){
const result:NotificationMessage[]=[];
for(const item of items){
if(seen.has(item.identity))continue;
seen.add(item.identity);
if(item.source!=='interface'&&now-item.at<=120&&now>=item.at-10)result.push({id:item.identity,tone:item.tone,title:item.title,description:item.description});
}
while(seen.size>5000)seen.delete(seen.values().next().value!);
return result;
}
@@ -0,0 +1,56 @@
import {createContext,useContext,useEffect,useRef,useState} from 'react';
import {mergeNotifications,networkToasts,notificationRequest,type NotificationMessage,type NotificationPage,type NotificationRecord} from './history';
export function useNotificationHistory(){
const [items,setItems]=useState<NotificationRecord[]>([]),[unread,setUnread]=useState(0),[open,setOpen]=useState(false),[error,setError]=useState(''),[loading,setLoading]=useState(true),[more,setMore]=useState(false),[toasts,setToasts]=useState<NotificationMessage[]>([]);
const seen=useRef(new Set<string>()),readThrough=useRef(0);
useEffect(()=>{
let live=true, stream:EventSource|undefined, retry:ReturnType<typeof setTimeout>|undefined;
async function connect(){
try{
const initial=await notificationRequest<NotificationPage>();
if(!live)return;
setItems(initial.items);setUnread(initial.unread);setMore(initial.items.length===100);
setLoading(false);setError('');
stream=new EventSource('/api/v1/notifications/events?after='+initial.latest);
stream.onopen=()=>{if(live)setError('');};
stream.onerror=()=>{if(live)setError('Восстанавливаем связь с центром событий…');};
stream.onmessage=event=>{
if(!live)return;
const page:NotificationPage=JSON.parse(event.data);
setUnread(page.unread);setError('');
if(page.items.length){
setItems(old=>mergeNotifications(old,page.items));
const incoming=networkToasts(page.items,seen.current,Date.now()/1000);
if(incoming.length)setToasts(old=>[...old,...incoming].slice(-5));
}
};
}catch{
if(live){setLoading(false);setError('Восстанавливаем связь с центром событий…');retry=setTimeout(connect,5000);}
}
}
void connect();
return()=>{live=false;stream?.close();clearTimeout(retry);};
},[]);
const maximum=items[0]?.sequence??0;
useEffect(()=>{
if(!open||!unread||maximum<=readThrough.current)return;
let active=true,timer:ReturnType<typeof setTimeout>|undefined;
async function markRead(){
try{
await notificationRequest('/read','POST',{through:maximum});
if(active){readThrough.current=maximum;setItems(old=>old.map(item=>item.sequence<=maximum?{...item,read:1}:item));}
}catch{if(active)timer=setTimeout(markRead,5000);}
}
void markRead();
return()=>{active=false;clearTimeout(timer);};
},[open,maximum,unread]);
const loadMore=async()=>{
if(loading||!items.length)return;setLoading(true);
try{const page=await notificationRequest<NotificationPage>('?before='+items[items.length-1].sequence);setItems(old=>mergeNotifications(old,page.items));setMore(page.items.length===100);setError('');}
catch(e){setError(e instanceof Error?e.message:'История недоступна.');}finally{setLoading(false);}
};
return {items,unread,open,setOpen,error,loading,more,loadMore,toasts,dismiss:(id:string)=>setToasts(old=>old.filter(item=>item.id!==id))};
}
export const NotificationContext=createContext<ReturnType<typeof useNotificationHistory>|null>(null);
export function useNotifications(){const context=useContext(NotificationContext);if(!context)throw new Error('Notification host missing');return context;}