Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,151 @@
// AK-P3 follow-up — macOS-style in-app notification toasts (top-right, below
// the shell header). Unread IN_APP deliveries pop up as dismissible toasts:
// X hides the toast (persisted per browser via localStorage, the delivery
// stays unread in the center), clicking the body marks it read and follows
// the deeplink. Data comes from the notifications route loader plus the
// shared SSE hook, so live arrivals toast too when the stream is available.
import { useEffect, useMemo, useState } from "react";
import { useFetcher, useNavigate } from "react-router";
import { useTranslation } from "react-i18next";
import { FeatherX } from "@subframe/core";
import type { NotificationCenterVM } from "@hivegrid/view-models";
import { Toast } from "~/ui/components/Toast";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { useNotificationsStream, type NotificationsStreamState } from "~/components/notifications/useNotificationsStream";
import { useRootData } from "~/utils/data/useRootData";
import { useLocaleFormatters } from "~/locale/format";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
const MAX_VISIBLE_TOASTS = 3;
const MAX_STORED_DISMISSED_IDS = 200;
function storageKeyFor(tenantSlug: string): string {
return `hg.notification-toasts.dismissed.${tenantSlug}`;
}
function readDismissedIds(tenantSlug: string): string[] {
if (typeof window === "undefined") return [];
try {
const raw = window.localStorage.getItem(storageKeyFor(tenantSlug));
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === "string") : [];
} catch {
return [];
}
}
function persistDismissedIds(tenantSlug: string, ids: string[]): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(storageKeyFor(tenantSlug), JSON.stringify(ids.slice(-MAX_STORED_DISMISSED_IDS)));
} catch {
// Storage may be unavailable (private mode) — toasts then reappear on reload.
}
}
/**
* Shared shell notification state: loads the notification-center data once per
* tenant and keeps it live via the SSE hook. Drives both the bell badge
* (unreadCount) and the toast stack (items).
*/
export function useShellNotifications(tenantSlug: string | null): { items: NotificationsStreamState["items"]; unreadCount: number } {
const loadFetcher = useFetcher<{ vm: NotificationCenterVM; streamUrl: string }>({ key: "notification-toasts" });
useEffect(() => {
if (tenantSlug) loadFetcher.load(appPath({ tenantSlug, path: "notifications", mode: "host-aware" }));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantSlug]);
const initialItems = useMemo(
() => (loadFetcher.data?.vm.status === "ready" && loadFetcher.data.vm.data ? loadFetcher.data.vm.data.items : []),
[loadFetcher.data]
);
const stream = useNotificationsStream(tenantSlug && loadFetcher.data ? loadFetcher.data.streamUrl : null, initialItems);
return { items: stream.items, unreadCount: stream.unreadCount };
}
export function NotificationToasts({ tenantSlug, items }: { tenantSlug: string; items: NotificationsStreamState["items"] }) {
const { t } = useTranslation();
const navigate = useNavigate();
const rootData = useRootData();
const formatters = useLocaleFormatters();
const markFetcher = useFetcher({ key: "notification-toasts-mark" });
const [dismissedIds, setDismissedIds] = useState<string[]>(() => readDismissedIds(tenantSlug));
const notificationsPath = appPath({ tenantSlug, path: "notifications", mode: "host-aware" });
useEffect(() => {
setDismissedIds(readDismissedIds(tenantSlug));
}, [tenantSlug]);
const visibleToasts = items
.filter((item) => !item.isRead && !dismissedIds.includes(item.id))
.slice(0, MAX_VISIBLE_TOASTS);
function dismiss(id: string) {
const next = [...dismissedIds, id];
setDismissedIds(next);
persistDismissedIds(tenantSlug, next);
}
function open(item: (typeof visibleToasts)[number]) {
dismiss(item.id);
const form = new FormData();
form.set("action", "mark-read");
form.set("deliveryId", item.id);
if (rootData?.csrf) form.set("csrf", rootData.csrf);
markFetcher.submit(form, { method: "post", action: notificationsPath });
navigate(item.deeplinkHref ?? notificationsPath);
}
if (visibleToasts.length === 0) return null;
return (
<div
className="pointer-events-none fixed right-4 top-16 z-50 flex w-full max-w-[336px] flex-col items-end gap-2"
data-ui-id="ui.notifications.toasts"
>
{visibleToasts.map((item) => (
<div key={item.id} className="pointer-events-auto relative w-full" data-ui-id={`ui.notifications.toast.${item.id}`}>
<button
type="button"
className="absolute right-2.5 top-2.5 z-10 flex h-5 w-5 items-center justify-center rounded-md text-icon-neutral-primary hover:bg-surface-neutral-tertiary"
aria-label={t("notifications.toasts.dismiss")}
onClick={() => dismiss(item.id)}
data-ui-id={`ui.notifications.toast.${item.id}.dismiss`}
>
<FeatherX />
</button>
<button type="button" className="w-full text-left" onClick={() => open(item)} data-ui-id={`ui.notifications.toast.${item.id}.open`}>
<Toast
variant="neutral"
hideProgress
hideUndo
className="w-full min-w-0 gap-0 px-4 py-2.5 pr-9"
title={
<span className="flex min-w-0 flex-col gap-1">
<span className="line-clamp-1 min-w-0 break-all" title={item.subjectLabel ? `${t(item.messageKey)}: ${item.subjectLabel}` : String(t(item.messageKey))}>
{item.subjectLabel ? `${t(item.messageKey)}: ${item.subjectLabel}` : t(item.messageKey)}
</span>
<span className="flex min-w-0 items-center gap-2 text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{item.createdAtIso ? (
<span className="whitespace-nowrap">{formatters.date(item.createdAtIso, { dateStyle: "short", timeStyle: "short" })}</span>
) : null}
{item.tagKey && item.tagTone ? (
<BadgeFeedback farbe={item.tagTone} size="small">
{t(item.tagKey)}
</BadgeFeedback>
) : null}
</span>
</span>
}
/>
</button>
</div>
))}
</div>
);
}
export default NotificationToasts;
@@ -0,0 +1,65 @@
// The confirmation that drops in at the top of the screen after a save.
//
// Two rules it exists to enforce:
// 1. Success is never optimistic. The toast is driven by the server's answer
// (`ok: true`), not by the click, so "Gespeichert" cannot appear over a
// write that failed.
// 2. An error says what went wrong. The message comes from the action's
// i18n key, never from a raw provider string or an HTTP code (A.1).
//
// Pure/presentational: it renders the copy it is handed. Firing it is the
// `useSaveToast` hook's job.
import { FeatherAlertCircle, FeatherCheckCircle } from "@subframe/core";
export type SaveToastVariant = "success" | "error";
export type SaveToastProps = {
variant: SaveToastVariant;
/** Resolved headline, e.g. "Gespeichert". */
title: string;
/** Resolved detail. On an error this is what went wrong and what to do. */
description?: string | null;
};
const VARIANT = {
success: {
frame: "border-border-positive-subtle bg-surface-feedback-subtle-positive",
icon: "text-icon-feedback-positive",
title: "text-text-feedback-positive",
},
error: {
frame: "border-border-negative-subtle bg-surface-feedback-subtle-negative",
icon: "text-icon-feedback-negative",
title: "text-text-feedback-negative",
},
} as const;
export function SaveToast({ variant, title, description }: SaveToastProps) {
const tone = VARIANT[variant];
return (
<div
// `role="status"` for the success and `role="alert"` for the failure: a
// screen reader should interrupt for a save that did not happen, and not
// for one that did.
role={variant === "error" ? "alert" : "status"}
aria-live={variant === "error" ? "assertive" : "polite"}
className={`flex w-full max-w-[420px] items-start gap-3 rounded-md border border-solid px-4 py-3 shadow-lg ${tone.frame}`}
data-ui-id={`ui.saveToast.${variant}`}
>
{variant === "success" ? (
<FeatherCheckCircle className={`mt-0.5 text-body-large-0 font-body-large-0 ${tone.icon}`} aria-hidden />
) : (
<FeatherAlertCircle className={`mt-0.5 text-body-large-0 font-body-large-0 ${tone.icon}`} aria-hidden />
)}
<div className="flex min-w-0 grow flex-col gap-0.5">
<span className={`text-body-default-medium-0 font-body-default-medium-0 ${tone.title}`}>{title}</span>
{description ? (
<span className="break-words text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{description}</span>
) : null}
</div>
</div>
);
}
export default SaveToast;
@@ -14,6 +14,12 @@ import {
const RECONNECT_DELAY_MS = 1_000;
const MAX_RECONNECT_DELAY_MS = 30_000;
/**
* A connection only counts as healthy once it survived this long. Resetting the
* backoff on every `open`/message meant a stream that dropped right after the
* snapshot reconnected once per second forever instead of backing off.
*/
const STABLE_CONNECTION_MS = 15_000;
type StreamPayload = {
cursor?: unknown;
@@ -46,6 +52,7 @@ function normalizeStreamItem(value: unknown): NotificationCenterItemVM | null {
sentAtIso: serializeDateField(record.sentAt),
readAtIso: serializeDateField(record.readAt),
lastError: typeof record.lastError === "string" ? record.lastError : null,
payloadMetadata: typeof record.payloadMetadata === "object" ? record.payloadMetadata : undefined,
deeplink: typeof record.deeplink === "string" ? record.deeplink : null,
});
}
@@ -97,10 +104,13 @@ export function useNotificationsStream(
const cursorRef = useRef<string | null>(null);
const reconnectTimerRef = useRef<number | null>(null);
const reconnectDelayRef = useRef(RECONNECT_DELAY_MS);
const connectedAtRef = useRef<number | null>(null);
useEffect(() => {
// Revalidated loader data merges over the live state (never truncates it).
setItems((currentItems) => mergeNotificationCenterItems(initialItems.slice(0, NOTIFICATION_CENTER_MAX_ITEMS), currentItems));
// merge(current, incoming): incoming wins per id — the fresh loader data
// must be the incoming side, otherwise stale live state shadows it.
setItems((currentItems) => mergeNotificationCenterItems(currentItems, initialItems.slice(0, NOTIFICATION_CENTER_MAX_ITEMS)));
}, [initialItems]);
useEffect(() => {
@@ -116,6 +126,7 @@ export function useNotificationsStream(
}
function connect() {
clearReconnectTimer();
connectedAtRef.current = null;
source = new EventSource(buildReconnectUrl(activeStreamUrl, cursorRef.current));
setConnectionStatusKey("notifications.center.realtime.connecting");
function handleMessage(event: MessageEvent) {
@@ -123,17 +134,24 @@ export function useNotificationsStream(
if (!parsed) return;
if (parsed.cursor && parsed.items.length > 0) cursorRef.current = parsed.cursor;
setItems((currentItems) => mergeNotificationCenterItems(currentItems, parsed.items));
reconnectDelayRef.current = RECONNECT_DELAY_MS;
setConnectionStatusKey("notifications.center.realtime.connected");
}
function handleOpen() {
reconnectDelayRef.current = RECONNECT_DELAY_MS;
connectedAtRef.current = Date.now();
setConnectionStatusKey("notifications.center.realtime.connected");
}
function handleError() {
if (closed) return;
source?.close();
setConnectionStatusKey("notifications.center.realtime.reconnecting");
// Only a connection that actually held counts as healthy. Otherwise a
// stream that dies right after opening keeps resetting the backoff and
// reconnects once per second forever.
const openedAt = connectedAtRef.current;
if (openedAt !== null && Date.now() - openedAt >= STABLE_CONNECTION_MS) {
reconnectDelayRef.current = RECONNECT_DELAY_MS;
}
connectedAtRef.current = null;
const reconnectDelay = reconnectDelayRef.current;
reconnectDelayRef.current = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
reconnectTimerRef.current = window.setTimeout(connect, reconnectDelay);