import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, redirect, useFetcher, useLoaderData, useNavigate, useRevalidator, } from "react-router"; import { CatalogError } from "@hivegrid/foundation"; import { chatErrors } from "@hivegrid/chat"; import type { ChatChannelListFilterState, ChatChannelListVM, ChatChannelNotificationPreference } from "@hivegrid/view-models"; import { ChatChannelListPage } from "~/components/screens/chat/ChatChannelListPage"; import ServerError from "~/components/ui/errors/ServerError"; import { getTranslations } from "~/locale/i18next.server"; import { loadChatContext } from "~/modules/chat/routes/chatAccess.server"; import { chatChannelListFilterHref, chatChannelListPageHref, normalizeChatChannelQuery, parseChatChannelListCursor, parseChatChannelListFilter, } from "~/modules/chat/routes/chatListFilter"; import { mergeChatChannelListPages, sameChatChannelListFilter } from "~/modules/chat/routes/chatListPagination"; import { CHAT_MODULE_KEY, chatChannelPath } from "~/modules/chat/routes/chatRoutePaths"; import { joinPublicChatChannel, loadMemberChatChannels, updateOwnChatChannelPreferences } from "~/modules/chat/services/ChatService.server"; import { useRootData } from "~/utils/data/useRootData"; import { validateCSRFToken } from "~/utils/session.server"; type LoaderData = { readonly title: string; readonly tenantSlug: string; readonly pageCursor: string | null; readonly vm: ChatChannelListVM; }; type ActionData = { readonly errorKey: string | null; readonly mutation?: Readonly<{ chatId: string; isPinned: boolean; notificationPreference: ChatChannelNotificationPreference; }>; }; const QUERY_DEBOUNCE_MS = 250; const CHANNEL_PAGE_LIMIT = 50; export const loader = async ({ request, params }: LoaderFunctionArgs) => { const [{ t }, context] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]); const tenantSlug = params.tenant ?? ""; const url = new URL(request.url); const filter = parseChatChannelListFilter(url); const pageCursor = parseChatChannelListCursor(url); const vm = await loadMemberChatChannels({ context, tenantSlug, filter, afterCursor: pageCursor, limit: CHANNEL_PAGE_LIMIT, labels: { directMessage: t("chat.channel.fallback.directMessage"), unnamedGroup: t("chat.channel.fallback.group"), unnamedProject: t("chat.channel.fallback.project"), unknownUser: t("chat.participant.unknown"), unknownMention: t("chat.mention.unknown"), }, }); return Response.json({ title: `${t("chat.nav.title")} | ${process.env.APP_NAME}`, tenantSlug, pageCursor: pageCursor ?? null, vm, } satisfies LoaderData); }; export async function action({ request, params }: ActionFunctionArgs): Promise { const context = await loadChatContext({ request, params }); const formData = await request.formData(); await validateCSRFToken(request, { formData }); const intent = formData.get("intent")?.toString() ?? ""; const chatId = formData.get("chatId")?.toString().trim() ?? ""; if (!chatId || chatId.length > 191 || chatId.includes("\0")) { return Response.json({ errorKey: "chat.errors.invalidInput" } satisfies ActionData, { status: 400 }); } try { if (intent === "join") { const result = await joinPublicChatChannel({ context, chatId, requestId: crypto.randomUUID() }); return redirect(`${chatChannelPath(params.tenant ?? "", result.chatId)}?toast=${encodeURIComponent("chat.toast.channelJoined")}`); } const requestId = normalizePreferenceRequestId(formData.get("requestId")); if (intent === "set-pin") { const isPinned = parseFormBoolean(formData.get("isPinned")); const mutation = await updateOwnChatChannelPreferences({ context, chatId, requestId, isPinned }); return Response.json({ errorKey: null, mutation } satisfies ActionData); } if (intent === "set-notification") { const notificationPreference = parseNotificationPreference(formData.get("notificationPreference")); const mutation = await updateOwnChatChannelPreferences({ context, chatId, requestId, notificationPreference }); return Response.json({ errorKey: null, mutation } satisfies ActionData); } return Response.json({ errorKey: "chat.errors.invalidInput" } satisfies ActionData, { status: 400 }); } catch (error) { if (error instanceof CatalogError) { return Response.json({ errorKey: error.i18nKey } satisfies ActionData, { status: error.status }); } throw error; } } export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }]; export default function ChatChannelListRoute(): React.JSX.Element { const { tenantSlug, vm } = useLoaderData(); const navigate = useNavigate(); const revalidator = useRevalidator(); const pageFetcher = useFetcher(); const { csrf } = useRootData(); const filter = vm.status === "ready" ? vm.data.filter : DEFAULT_FILTER; const [query, setQuery] = useState(filter.query); const [pagination, setPagination] = useState<{ readonly baseVm: ChatChannelListVM; readonly mergedVm: ChatChannelListVM }>({ baseVm: vm, mergedVm: vm, }); const [joinState, setJoinState] = useState<{ readonly channelId: string | null; readonly errorKey: string | null }>({ channelId: null, errorKey: null, }); const [preferenceState, setPreferenceState] = useState<{ readonly channelId: string | null; readonly errorKey: string | null; readonly overrides: Readonly>>; }>({ channelId: null, errorKey: null, overrides: {} }); const queryTimer = useRef | null>(null); const locallyEditedQuery = useRef(null); const requestedCursor = useRef(null); useEffect(() => { if (locallyEditedQuery.current !== null && filter.query !== locallyEditedQuery.current) return; locallyEditedQuery.current = null; setQuery(filter.query); }, [filter.query]); useEffect(() => { requestedCursor.current = null; setPagination({ baseVm: vm, mergedVm: vm }); }, [vm]); useEffect(() => { if (pageFetcher.state !== "idle") return; const cursor = requestedCursor.current; if (!cursor) return; requestedCursor.current = null; const fetched = pageFetcher.data; if (!isLoaderData(fetched) || fetched.pageCursor !== cursor || fetched.tenantSlug !== tenantSlug || vm.status !== "ready" || fetched.vm.status !== "ready") return; if (!sameChatChannelListFilter(vm.data.filter, fetched.vm.data.filter)) return; setPagination((current) => ({ baseVm: vm, mergedVm: mergeChatChannelListPages(current.baseVm === vm ? current.mergedVm : vm, fetched.vm), })); }, [pageFetcher.data, pageFetcher.state, tenantSlug, vm]); useEffect(() => { if (pageFetcher.state !== "idle" || joinState.channelId === null || !isActionData(pageFetcher.data)) return; setJoinState({ channelId: null, errorKey: pageFetcher.data.errorKey }); }, [joinState.channelId, pageFetcher.data, pageFetcher.state]); useEffect(() => { if (pageFetcher.state !== "idle" || preferenceState.channelId === null || !isActionData(pageFetcher.data)) return; const response = pageFetcher.data; if (response.errorKey) { setPreferenceState((current) => { const nextOverrides = { ...current.overrides }; delete nextOverrides[current.channelId ?? ""]; return { channelId: null, errorKey: response.errorKey, overrides: nextOverrides }; }); return; } setPreferenceState((current) => ({ ...current, channelId: null, errorKey: null })); revalidator.revalidate(); }, [pageFetcher.data, pageFetcher.state, preferenceState.channelId, revalidator]); useEffect(() => { if (vm.status !== "ready" || Object.keys(preferenceState.overrides).length === 0) return; setPreferenceState((current) => { const nextOverrides = { ...current.overrides }; for (const row of vm.data.rows) { const override = nextOverrides[row.id]; if (!override) continue; const pinMatches = override.isPinned === undefined || override.isPinned === row.isPinned; const notificationMatches = override.notificationPreference === undefined || override.notificationPreference === row.notificationPreference; if (pinMatches && notificationMatches) delete nextOverrides[row.id]; } if (Object.keys(nextOverrides).length === Object.keys(current.overrides).length) return current; return { ...current, overrides: nextOverrides }; }); }, [preferenceState.overrides, vm]); useEffect( () => () => { if (queryTimer.current) clearTimeout(queryTimer.current); }, [] ); const pagedVm = pagination.baseVm === vm ? pagination.mergedVm : vm; const openFilter = useCallback( (nextFilter: ChatChannelListFilterState, replace = false) => { void navigate(chatChannelListFilterHref(tenantSlug, nextFilter), { replace }); }, [navigate, tenantSlug] ); const displayVm = useMemo(() => { if (pagedVm.status !== "ready") return pagedVm; const overriddenRows = pagedVm.data.rows.map((row) => { const override = preferenceState.overrides[row.id]; if (!override) return row; const notificationPreference = override.notificationPreference ?? row.notificationPreference; return { ...row, ...(override.isPinned === undefined ? {} : { isPinned: override.isPinned }), notificationPreference, isMuted: notificationPreference === "muted", }; }); const rows = pagedVm.data.filter.view === "pinned" ? overriddenRows.filter((row) => row.isPinned) : [...overriddenRows.filter((row) => row.isPinned), ...overriddenRows.filter((row) => !row.isPinned)]; return { ...pagedVm, data: { ...pagedVm.data, rows, filter: query === pagedVm.data.filter.query ? pagedVm.data.filter : { ...pagedVm.data.filter, query }, }, }; }, [pagedVm, preferenceState.overrides, query]); return ( void navigate(detailHref), onCreateGroup: (href) => void navigate(href), onCreateDm: (href) => void navigate(href), onOpenMessageSearch: (href) => void navigate(href), onOpenMentions: (href) => void navigate(href), onJoinChannel: (channelId, joinHref) => { if (pageFetcher.state !== "idle" || requestedCursor.current !== null || joinState.channelId !== null) return; const formData = new FormData(); formData.set("intent", "join"); formData.set("chatId", channelId); formData.set("csrf", csrf ?? ""); setJoinState({ channelId, errorKey: null }); void pageFetcher.submit(formData, { method: "post", action: joinHref }); }, onSetPinned: (channelId, isPinned) => { submitPreferenceMutation(channelId, { intent: "set-pin", isPinned }); }, onSetNotificationPreference: (channelId, notificationPreference) => { submitPreferenceMutation(channelId, { intent: "set-notification", notificationPreference }); }, onQueryChange: (nextQuery) => { locallyEditedQuery.current = normalizeChatChannelQuery(nextQuery); setQuery(nextQuery); if (queryTimer.current) clearTimeout(queryTimer.current); queryTimer.current = setTimeout(() => { queryTimer.current = null; openFilter({ ...filter, query: nextQuery }, true); }, QUERY_DEBOUNCE_MS); }, onViewChange: (view) => { if (queryTimer.current) clearTimeout(queryTimer.current); openFilter({ ...filter, query, view }); }, onShowArchivedChange: (showArchived) => { if (queryTimer.current) clearTimeout(queryTimer.current); openFilter({ ...filter, query, showArchived }); }, onLoadMore: (cursor) => { if (pageFetcher.state !== "idle" || requestedCursor.current !== null) return; requestedCursor.current = cursor; void pageFetcher.load(chatChannelListPageHref(tenantSlug, filter, cursor)); }, onRetry: () => revalidator.revalidate(), }} /> ); function submitPreferenceMutation( channelId: string, mutation: | { readonly intent: "set-pin"; readonly isPinned: boolean } | { readonly intent: "set-notification"; readonly notificationPreference: ChatChannelNotificationPreference } ): void { if (pageFetcher.state !== "idle" || requestedCursor.current !== null || preferenceState.channelId !== null) return; const formData = new FormData(); formData.set("intent", mutation.intent); formData.set("chatId", channelId); formData.set("requestId", crypto.randomUUID()); formData.set("csrf", csrf ?? ""); if (mutation.intent === "set-pin") formData.set("isPinned", String(mutation.isPinned)); else formData.set("notificationPreference", mutation.notificationPreference); setPreferenceState((current) => ({ channelId, errorKey: null, overrides: { ...current.overrides, [channelId]: { ...current.overrides[channelId], ...(mutation.intent === "set-pin" ? { isPinned: mutation.isPinned } : { notificationPreference: mutation.notificationPreference }), }, }, })); void pageFetcher.submit(formData, { method: "post" }); } } const DEFAULT_FILTER: ChatChannelListFilterState = { query: "", view: "all", showArchived: false, }; function isLoaderData(data: LoaderData | ActionData | undefined): data is LoaderData { return Boolean(data && "vm" in data && "pageCursor" in data); } function isActionData(data: LoaderData | ActionData | undefined): data is ActionData { return Boolean(data && "errorKey" in data); } function normalizePreferenceRequestId(value: FormDataEntryValue | null): string { const requestId = typeof value === "string" ? value.trim() : ""; if (!requestId || requestId.length > 191 || requestId.includes("\0")) throw new CatalogError(chatErrors.invalidInput); return requestId; } function parseFormBoolean(value: FormDataEntryValue | null): boolean { if (value === "true") return true; if (value === "false") return false; throw new CatalogError(chatErrors.invalidInput); } function parseNotificationPreference(value: FormDataEntryValue | null): ChatChannelNotificationPreference { if (value === "all_messages" || value === "mentions_only" || value === "muted") return value; throw new CatalogError(chatErrors.invalidInput); } export function ErrorBoundary(): React.JSX.Element { return ; } export const handle = { moduleKey: CHAT_MODULE_KEY };