168 lines
6.6 KiB
TypeScript
168 lines
6.6 KiB
TypeScript
import { useEffect, useState } from "react";
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData, useNavigate, useRevalidator } from "react-router";
|
|
import { CatalogError } from "@hivegrid/foundation";
|
|
import type { ChatPinnedMessagesVM } from "@hivegrid/view-models";
|
|
|
|
import { ChatPinnedMessagesPage } from "~/components/screens/chat/ChatPinnedMessagesPage";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { useChatChannelRealtime } from "~/modules/chat/client/useChatChannelRealtime";
|
|
import {
|
|
beginChatFeatureMutation,
|
|
chatFeatureErrorsByMessageId,
|
|
failedChatFeatureMutationForMessage,
|
|
overlayChatPinnedFeatureMutations,
|
|
reconcileChatPinnedFeatureMutations,
|
|
settleChatFeatureMutation,
|
|
type ChatOptimisticFeatureMutation,
|
|
type ChatOptimisticFeatureMutationInput,
|
|
} from "~/modules/chat/client/ChatFeatureOptimistic";
|
|
import { loadChatContext } from "~/modules/chat/routes/chatAccess.server";
|
|
import { CHAT_MODULE_KEY } from "~/modules/chat/routes/chatRoutePaths";
|
|
import { changeChatMessagePin, loadChatPinnedPage } from "~/modules/chat/services/ChatMessageFeaturesService.server";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
import { validateCSRFToken } from "~/utils/session.server";
|
|
|
|
type LoaderData = {
|
|
readonly title: string;
|
|
readonly tenantSlug: string;
|
|
readonly currentUserId: string;
|
|
readonly chatId: string;
|
|
readonly eventCursor: string;
|
|
readonly vm: ChatPinnedMessagesVM;
|
|
};
|
|
type ActionData = { readonly ok: boolean; readonly requestId: string; readonly messageId: string; readonly errorKey: string | null };
|
|
|
|
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
|
const [{ t }, context] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
|
|
const result = await loadChatPinnedPage({
|
|
context,
|
|
tenantSlug: params.tenant ?? "",
|
|
chatId: params.id ?? "",
|
|
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"),
|
|
},
|
|
});
|
|
const { vm } = result;
|
|
const channelTitle = vm.status === "ready" ? vm.data.channelTitle : t("chat.pinned.titleFallback");
|
|
return Response.json({
|
|
title: `${t("chat.pinned.title", { channel: channelTitle })} | ${process.env.APP_NAME}`,
|
|
tenantSlug: params.tenant ?? "",
|
|
currentUserId: context.userId,
|
|
chatId: params.id ?? "",
|
|
eventCursor: result.eventCursor,
|
|
vm,
|
|
} satisfies LoaderData);
|
|
}
|
|
|
|
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
|
const context = await loadChatContext({ request, params });
|
|
const formData = await request.formData();
|
|
await validateCSRFToken(request, { formData });
|
|
const messageId = formData.get("messageId")?.toString().trim() ?? "";
|
|
const requestId = formData.get("requestId")?.toString().trim() ?? "";
|
|
try {
|
|
await changeChatMessagePin({
|
|
context,
|
|
chatId: params.id ?? "",
|
|
messageId,
|
|
pinned: false,
|
|
requestId,
|
|
});
|
|
return Response.json({ ok: true, requestId, messageId, errorKey: null } satisfies ActionData);
|
|
} catch (error) {
|
|
if (error instanceof CatalogError) {
|
|
return Response.json({ ok: false, requestId, messageId, errorKey: error.i18nKey } satisfies ActionData, { status: error.status });
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
|
|
|
export default function ChatPinnedMessagesRoute(): React.JSX.Element {
|
|
const loaderData = useLoaderData<LoaderData>();
|
|
const authoritativeVm = loaderData.vm;
|
|
const navigate = useNavigate();
|
|
const revalidator = useRevalidator();
|
|
const fetcher = useFetcher<ActionData>();
|
|
const { csrf, routing } = useRootData();
|
|
const [featureMutations, setFeatureMutations] = useState<readonly ChatOptimisticFeatureMutation[]>([]);
|
|
const vm = overlayChatPinnedFeatureMutations(authoritativeVm, featureMutations);
|
|
useEffect(() => {
|
|
setFeatureMutations((current) => reconcileChatPinnedFeatureMutations(current, authoritativeVm));
|
|
}, [authoritativeVm]);
|
|
useEffect(() => {
|
|
if (fetcher.state !== "idle" || !fetcher.data) return;
|
|
setFeatureMutations((current) => settleChatFeatureMutation(current, fetcher.data!.requestId, fetcher.data!));
|
|
}, [fetcher.data, fetcher.state]);
|
|
useChatChannelRealtime({
|
|
enabled: vm.status === "ready",
|
|
tenantSlug: loaderData.tenantSlug,
|
|
chatId: loaderData.chatId,
|
|
initialCursor: loaderData.eventCursor,
|
|
csrfToken: csrf ?? null,
|
|
routing,
|
|
initialMessages: [],
|
|
currentUser: {
|
|
userId: loaderData.currentUserId,
|
|
displayName: loaderData.currentUserId,
|
|
avatar: { imageUrl: null, fallbackLabel: "?" },
|
|
isCurrentUser: true,
|
|
},
|
|
unknownAuthorLabel: "?",
|
|
resolveAuthor: () => null,
|
|
revalidate: () => revalidator.revalidate(),
|
|
});
|
|
|
|
function submitFeatureMutation(mutation: ChatOptimisticFeatureMutationInput): void {
|
|
if (fetcher.state !== "idle") return;
|
|
setFeatureMutations((current) => beginChatFeatureMutation(current, mutation));
|
|
const formData = new FormData();
|
|
formData.set("csrf", csrf ?? "");
|
|
formData.set("requestId", mutation.requestId);
|
|
formData.set("messageId", mutation.messageId);
|
|
void fetcher.submit(formData, { method: "post" });
|
|
}
|
|
|
|
function unpin(messageId: string): void {
|
|
submitFeatureMutation({
|
|
kind: "pin",
|
|
requestId: crypto.randomUUID(),
|
|
messageId,
|
|
pinned: false,
|
|
actorLabel: loaderData.currentUserId,
|
|
startedAtIso: new Date().toISOString(),
|
|
});
|
|
}
|
|
|
|
function retryFeatureMutation(messageId: string): void {
|
|
const mutation = failedChatFeatureMutationForMessage(featureMutations, messageId);
|
|
if (mutation?.kind === "pin") submitFeatureMutation(mutation);
|
|
}
|
|
return (
|
|
<ChatPinnedMessagesPage
|
|
vm={vm}
|
|
busyMessageId={fetcher.state === "idle" ? null : (fetcher.formData?.get("messageId")?.toString() ?? null)}
|
|
errorKey={null}
|
|
featureErrorKeys={chatFeatureErrorsByMessageId(featureMutations)}
|
|
actions={{
|
|
onBack: (href) => void navigate(href),
|
|
onUnpin: unpin,
|
|
onRetryFeature: retryFeatureMutation,
|
|
onRetry: () => revalidator.revalidate(),
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary(): React.JSX.Element {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: CHAT_MODULE_KEY, breadcrumbKey: "chat.pinned.breadcrumb" };
|