2026-09-11 12:53:55 -05:00
|
|
|
import { useCallback, useEffect, useMemo } from "react";
|
2026-09-03 15:58:13 -05:00
|
|
|
import axios from "axios";
|
|
|
|
|
import useSWR from "swr";
|
|
|
|
|
import { useWs } from "@/api/ws";
|
2026-09-11 12:53:55 -05:00
|
|
|
import type { Notice } from "@/types/notice";
|
2026-09-03 15:58:13 -05:00
|
|
|
|
|
|
|
|
/**
|
2026-09-11 12:53:55 -05:00
|
|
|
* Active notices come from a REST snapshot, then from every `notices`
|
|
|
|
|
* websocket payload. Dismissed notices are fetched only while the history is
|
|
|
|
|
* shown, and again when the active list changes or the tab regains focus. A
|
|
|
|
|
* purge in another tab leaves the active list unchanged, so only focus
|
|
|
|
|
* catches it.
|
2026-09-03 15:58:13 -05:00
|
|
|
*/
|
2026-09-11 12:53:55 -05:00
|
|
|
export function useNotices(showDismissed: boolean) {
|
2026-09-03 15:58:13 -05:00
|
|
|
const { data: initial, mutate } = useSWR<Notice[]>("notices", {
|
|
|
|
|
revalidateOnFocus: false,
|
|
|
|
|
});
|
2026-09-11 12:53:55 -05:00
|
|
|
const { data: history, mutate: mutateHistory } = useSWR<Notice[]>(
|
|
|
|
|
showDismissed ? ["notices", { include_dismissed: true }] : null,
|
2026-09-03 15:58:13 -05:00
|
|
|
);
|
|
|
|
|
const {
|
|
|
|
|
value: { payload },
|
|
|
|
|
} = useWs("notices", "");
|
|
|
|
|
|
|
|
|
|
const live = useMemo(
|
|
|
|
|
() =>
|
|
|
|
|
payload && typeof payload === "string"
|
|
|
|
|
? (JSON.parse(payload) as Notice[])
|
|
|
|
|
: undefined,
|
|
|
|
|
[payload],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// once a websocket frame has arrived it is the source of truth; a dismiss
|
|
|
|
|
// still shows up because the registry publishes a new frame after it
|
|
|
|
|
const notices = live ?? initial;
|
|
|
|
|
|
2026-09-11 12:53:55 -05:00
|
|
|
// refetch the history whenever the active list changes; SWR ignores the
|
|
|
|
|
// call while the history is hidden
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
mutateHistory();
|
|
|
|
|
}, [live, mutateHistory]);
|
|
|
|
|
|
|
|
|
|
const dismissed = useMemo(
|
|
|
|
|
() =>
|
|
|
|
|
history
|
|
|
|
|
?.filter((notice) => notice.dismissed_at !== null)
|
|
|
|
|
.sort((a, b) => (b.dismissed_at ?? 0) - (a.dismissed_at ?? 0)),
|
|
|
|
|
[history],
|
|
|
|
|
);
|
2026-09-03 15:58:13 -05:00
|
|
|
|
|
|
|
|
const dismiss = useCallback(
|
|
|
|
|
async (id: string) => {
|
|
|
|
|
await axios.post(`notices/${id}/dismiss`);
|
|
|
|
|
mutate();
|
|
|
|
|
},
|
2026-09-11 12:53:55 -05:00
|
|
|
[mutate],
|
2026-09-03 15:58:13 -05:00
|
|
|
);
|
|
|
|
|
|
2026-09-11 12:53:55 -05:00
|
|
|
return { notices, dismissed, dismiss, mutateDismissed: mutateHistory };
|
2026-09-03 15:58:13 -05:00
|
|
|
}
|