465 lines
19 KiB
TypeScript
465 lines
19 KiB
TypeScript
import { useEffect, useRef, useState } from "react";
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction, useFetcher, useLoaderData, useNavigate, useRevalidator } from "react-router";
|
|
import { CatalogError } from "@hivegrid/foundation";
|
|
import { extractChatMentions, findChatMentionQuery, insertChatMention, type ChatMentionQuery, type ChatMentionType } from "@hivegrid/realtime";
|
|
import type { ChatMentionAutocompleteVM, ChatMentionSuggestionVM, ChatResolvedMentionVM, ChatThreadVM } from "@hivegrid/view-models";
|
|
|
|
import { ChatThreadPage, type ChatOptimisticThreadReply } from "~/components/screens/chat/ChatThreadPage";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { useChatChannelRealtime } from "~/modules/chat/client/useChatChannelRealtime";
|
|
import {
|
|
beginChatMessageMutation,
|
|
chatMessageMutationErrors,
|
|
failedChatMessageMutationForMessage,
|
|
overlayChatThreadMessageMutations,
|
|
reconcileChatThreadMessageMutations,
|
|
retryChatMessageMutation,
|
|
settleChatMessageMutation,
|
|
type ChatOptimisticMessageMutation,
|
|
type ChatOptimisticMessageMutationInput,
|
|
} from "~/modules/chat/client/chatMessageMutationOptimistic";
|
|
import {
|
|
beginChatFeatureMutation,
|
|
chatFeatureErrorsByMessageId,
|
|
failedChatFeatureMutationForMessage,
|
|
overlayChatThreadFeatureMutations,
|
|
reconcileChatThreadFeatureMutations,
|
|
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, changeChatReaction, createChatThreadReply, loadChatThreadPage } from "~/modules/chat/services/ChatMessageFeaturesService.server";
|
|
import { editMemberChatMessage, removeMemberChatMessage } from "~/modules/chat/services/ChatMessageMutationsService.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: ChatThreadVM;
|
|
};
|
|
|
|
type ActionData = {
|
|
readonly ok: boolean;
|
|
readonly intent: string;
|
|
readonly requestId: string;
|
|
readonly errorKey: string | null;
|
|
readonly messageId: string | null;
|
|
};
|
|
|
|
type PendingThreadReply = ChatOptimisticThreadReply &
|
|
Readonly<{
|
|
requestId: string;
|
|
serverMessageId: string | null;
|
|
}>;
|
|
|
|
type MentionLoaderData = {
|
|
readonly query: string;
|
|
readonly type: ChatMentionType | null;
|
|
readonly vm: ChatMentionAutocompleteVM;
|
|
};
|
|
|
|
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
|
const [{ t }, context] = await Promise.all([getTranslations(request), loadChatContext({ request, params })]);
|
|
const result = await loadChatThreadPage({
|
|
context,
|
|
tenantSlug: params.tenant ?? "",
|
|
chatId: params.id ?? "",
|
|
threadId: params.threadId ?? "",
|
|
labels: featureLabels(t),
|
|
});
|
|
const { vm } = result;
|
|
const channelTitle = vm.status === "ready" ? vm.data.channelTitle : t("chat.thread.titleFallback");
|
|
return Response.json({
|
|
title: `${t("chat.thread.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 intent = formValue(formData, "intent");
|
|
const requestId = formValue(formData, "requestId");
|
|
const chatId = params.id ?? "";
|
|
const threadId = params.threadId ?? "";
|
|
let messageId: string | null = null;
|
|
try {
|
|
if (intent === "reply") {
|
|
const result = await createChatThreadReply({
|
|
context,
|
|
chatId,
|
|
threadId,
|
|
requestId,
|
|
clientMessageId: formValue(formData, "clientMessageId"),
|
|
body: formValue(formData, "body"),
|
|
});
|
|
messageId = result.message.id;
|
|
} else if (intent === "reaction") {
|
|
await changeChatReaction({
|
|
context,
|
|
chatId,
|
|
requestId,
|
|
messageId: formValue(formData, "messageId"),
|
|
emoji: formValue(formData, "emoji"),
|
|
active: formValue(formData, "active") === "true",
|
|
});
|
|
} else if (intent === "pin") {
|
|
await changeChatMessagePin({
|
|
context,
|
|
chatId,
|
|
requestId,
|
|
messageId: formValue(formData, "messageId"),
|
|
pinned: formValue(formData, "pinned") === "true",
|
|
});
|
|
} else if (intent === "edit_message") {
|
|
await editMemberChatMessage({
|
|
context,
|
|
chatId,
|
|
requestId,
|
|
messageId: formValue(formData, "messageId"),
|
|
body: formValue(formData, "body"),
|
|
});
|
|
} else if (intent === "delete_message") {
|
|
await removeMemberChatMessage({
|
|
context,
|
|
chatId,
|
|
requestId,
|
|
messageId: formValue(formData, "messageId"),
|
|
});
|
|
} else {
|
|
return Response.json({ ok: false, intent, requestId, errorKey: "chat.errors.invalidInput", messageId: null } satisfies ActionData, { status: 400 });
|
|
}
|
|
return Response.json({ ok: true, intent, requestId, errorKey: null, messageId } satisfies ActionData);
|
|
} catch (error) {
|
|
if (error instanceof CatalogError) {
|
|
return Response.json({ ok: false, intent, requestId, errorKey: error.i18nKey, messageId: null } satisfies ActionData, { status: error.status });
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export const meta: MetaFunction = ({ data }) => [{ title: (data as LoaderData | undefined)?.title }];
|
|
|
|
export default function ChatThreadRoute(): React.JSX.Element {
|
|
const loaderData = useLoaderData<LoaderData>();
|
|
const authoritativeVm = loaderData.vm;
|
|
const navigate = useNavigate();
|
|
const revalidator = useRevalidator();
|
|
const fetcher = useFetcher<ActionData>();
|
|
const mentionFetcher = useFetcher<MentionLoaderData>();
|
|
const { csrf, routing } = useRootData();
|
|
const [draft, setDraft] = useState("");
|
|
const [composerCaret, setComposerCaret] = useState(0);
|
|
const [mentionQuery, setMentionQuery] = useState<ChatMentionQuery | null>(null);
|
|
const [mentionActiveIndex, setMentionActiveIndex] = useState(0);
|
|
const [featureMutations, setFeatureMutations] = useState<readonly ChatOptimisticFeatureMutation[]>([]);
|
|
const [messageMutations, setMessageMutations] = useState<readonly ChatOptimisticMessageMutation[]>([]);
|
|
const [pendingReplies, setPendingReplies] = useState<readonly PendingThreadReply[]>([]);
|
|
const submittedIntent = useRef<string | null>(null);
|
|
const handledReplyResponse = useRef<string | null>(null);
|
|
const vm = overlayChatThreadMessageMutations(overlayChatThreadFeatureMutations(authoritativeVm, featureMutations), messageMutations);
|
|
const mentionResponseMatches = mentionQuery !== null && mentionFetcher.data?.query === mentionQuery.query && mentionFetcher.data.type === mentionQuery.kind;
|
|
const mentionVm = mentionResponseMatches ? (mentionFetcher.data?.vm ?? null) : null;
|
|
const mentionItems = mentionVm?.groups.flatMap((group) => group.items) ?? [];
|
|
|
|
useEffect(() => {
|
|
const query = findChatMentionQuery(draft, composerCaret);
|
|
setMentionQuery(query);
|
|
setMentionActiveIndex(0);
|
|
if (!query) return;
|
|
const timer = window.setTimeout(() => {
|
|
const search = new URLSearchParams({ q: query.query });
|
|
if (query.kind) search.set("type", query.kind);
|
|
void mentionFetcher.load(`/${encodeURIComponent(loaderData.tenantSlug)}/chat/${encodeURIComponent(loaderData.chatId)}/mentions?${search.toString()}`);
|
|
}, 200);
|
|
return () => window.clearTimeout(timer);
|
|
}, [composerCaret, draft, loaderData.chatId, loaderData.tenantSlug]);
|
|
|
|
useEffect(() => {
|
|
if (fetcher.state !== "idle" || !fetcher.data?.ok || submittedIntent.current === null) return;
|
|
submittedIntent.current = null;
|
|
}, [fetcher.data, fetcher.state]);
|
|
|
|
useEffect(() => {
|
|
const result = fetcher.data;
|
|
if (fetcher.state !== "idle" || !result || result.intent !== "reply" || handledReplyResponse.current === result.requestId) return;
|
|
handledReplyResponse.current = result.requestId;
|
|
setPendingReplies((current) =>
|
|
current.map((reply) =>
|
|
reply.requestId !== result.requestId
|
|
? reply
|
|
: {
|
|
...reply,
|
|
deliveryState: result.ok ? "sent" : "failed",
|
|
failureReasonKey: result.ok ? null : (result.errorKey ?? "chat.message.sendFailed"),
|
|
serverMessageId: result.messageId,
|
|
}
|
|
)
|
|
);
|
|
if (result.ok) revalidator.revalidate();
|
|
}, [fetcher.data, fetcher.state, revalidator]);
|
|
|
|
useEffect(() => {
|
|
if (authoritativeVm.status !== "ready") return;
|
|
const hydratedIds = new Set(authoritativeVm.data.replies.map((reply) => reply.id));
|
|
setPendingReplies((current) => current.filter((reply) => !reply.serverMessageId || !hydratedIds.has(reply.serverMessageId)));
|
|
}, [authoritativeVm]);
|
|
|
|
useEffect(() => {
|
|
setFeatureMutations((current) => reconcileChatThreadFeatureMutations(current, authoritativeVm));
|
|
setMessageMutations((current) => reconcileChatThreadMessageMutations(current, authoritativeVm));
|
|
}, [authoritativeVm]);
|
|
|
|
useEffect(() => {
|
|
if (fetcher.state !== "idle" || !fetcher.data || fetcher.data.intent === "reply") return;
|
|
if (fetcher.data.intent === "edit_message" || fetcher.data.intent === "delete_message") {
|
|
setMessageMutations((current) => settleChatMessageMutation(current, 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 submit(intent: string, values: Record<string, string>): void {
|
|
if (fetcher.state !== "idle") return;
|
|
submittedIntent.current = intent;
|
|
const formData = new FormData();
|
|
formData.set("csrf", csrf ?? "");
|
|
formData.set("intent", intent);
|
|
formData.set("requestId", crypto.randomUUID());
|
|
for (const [key, value] of Object.entries(values)) formData.set(key, value);
|
|
void fetcher.submit(formData, { method: "post" });
|
|
}
|
|
|
|
function sendReply(body: string): void {
|
|
const normalized = body.trim();
|
|
if (!normalized || fetcher.state !== "idle") return;
|
|
const requestId = crypto.randomUUID();
|
|
const clientMessageId = crypto.randomUUID();
|
|
handledReplyResponse.current = null;
|
|
setPendingReplies((current) => [
|
|
...current,
|
|
{
|
|
requestId,
|
|
clientMessageId,
|
|
serverMessageId: null,
|
|
authorLabel: loaderData.currentUserId,
|
|
bodyMarkdown: normalized,
|
|
createdAtIso: new Date().toISOString(),
|
|
deliveryState: "sending",
|
|
failureReasonKey: null,
|
|
},
|
|
]);
|
|
setDraft("");
|
|
setComposerCaret(0);
|
|
setMentionQuery(null);
|
|
submit("reply", { body: normalized, clientMessageId, requestId });
|
|
}
|
|
|
|
function retryReply(clientMessageId: string): void {
|
|
if (fetcher.state !== "idle") return;
|
|
const failed = pendingReplies.find((reply) => reply.clientMessageId === clientMessageId && reply.deliveryState === "failed");
|
|
if (!failed) return;
|
|
const requestId = crypto.randomUUID();
|
|
handledReplyResponse.current = null;
|
|
setPendingReplies((current) =>
|
|
current.map((reply) =>
|
|
reply.clientMessageId === clientMessageId ? { ...reply, requestId, serverMessageId: null, deliveryState: "sending", failureReasonKey: null } : reply
|
|
)
|
|
);
|
|
submit("reply", { body: failed.bodyMarkdown, clientMessageId, requestId });
|
|
}
|
|
|
|
function submitFeatureMutation(mutation: ChatOptimisticFeatureMutationInput): void {
|
|
if (fetcher.state !== "idle") return;
|
|
setFeatureMutations((current) => beginChatFeatureMutation(current, mutation));
|
|
submit(mutation.kind, {
|
|
requestId: mutation.requestId,
|
|
messageId: mutation.messageId,
|
|
...(mutation.kind === "reaction" ? { emoji: mutation.emoji, active: String(mutation.active) } : { pinned: String(mutation.pinned) }),
|
|
});
|
|
}
|
|
|
|
function beginFeatureMutation(
|
|
input:
|
|
| { readonly kind: "reaction"; readonly messageId: string; readonly emoji: string; readonly active: boolean }
|
|
| { readonly kind: "pin"; readonly messageId: string; readonly pinned: boolean }
|
|
): void {
|
|
submitFeatureMutation({
|
|
...input,
|
|
requestId: crypto.randomUUID(),
|
|
actorLabel: loaderData.currentUserId,
|
|
startedAtIso: new Date().toISOString(),
|
|
} as ChatOptimisticFeatureMutationInput);
|
|
}
|
|
|
|
function retryFeatureMutation(messageId: string): void {
|
|
const messageMutation = failedChatMessageMutationForMessage(messageMutations, messageId);
|
|
if (messageMutation) {
|
|
setMessageMutations((current) => retryChatMessageMutation(current, messageMutation.requestId));
|
|
submit(messageMutation.kind, {
|
|
requestId: messageMutation.requestId,
|
|
messageId: messageMutation.messageId,
|
|
...(messageMutation.kind === "edit_message" ? { body: messageMutation.bodyMarkdown } : {}),
|
|
});
|
|
return;
|
|
}
|
|
const mutation = failedChatFeatureMutationForMessage(featureMutations, messageId);
|
|
if (!mutation) return;
|
|
submitFeatureMutation(mutation);
|
|
}
|
|
|
|
function submitMessageMutation(mutation: ChatOptimisticMessageMutationInput): void {
|
|
if (fetcher.state !== "idle") return;
|
|
setMessageMutations((current) => beginChatMessageMutation(current, mutation));
|
|
submit(mutation.kind, {
|
|
requestId: mutation.requestId,
|
|
messageId: mutation.messageId,
|
|
...(mutation.kind === "edit_message" ? { body: mutation.bodyMarkdown } : {}),
|
|
});
|
|
}
|
|
|
|
function mentionsForEditedBody(messageId: string, body: string): readonly ChatResolvedMentionVM[] {
|
|
if (vm.status !== "ready") return [];
|
|
const message = [vm.data.parent, ...vm.data.replies].find((candidate) => candidate.id === messageId);
|
|
if (!message) return [];
|
|
const available = new Map(message.mentions.map((mention) => [`${mention.kind}\u0000${mention.id}`, mention]));
|
|
try {
|
|
return extractChatMentions(body).flatMap((mention) => {
|
|
const resolved = available.get(`${mention.type}\u0000${mention.id}`);
|
|
return resolved ? [resolved] : [];
|
|
});
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function selectMention(suggestion: ChatMentionSuggestionVM): number | null {
|
|
if (!mentionQuery) return null;
|
|
const inserted = insertChatMention(draft, mentionQuery, { type: suggestion.kind, id: suggestion.id });
|
|
setDraft(inserted.body);
|
|
setComposerCaret(inserted.caret);
|
|
setMentionQuery(null);
|
|
return inserted.caret;
|
|
}
|
|
|
|
function handleMentionKeyDown(key: "ArrowDown" | "ArrowUp" | "Enter" | "Escape"): boolean {
|
|
if (!mentionQuery) return false;
|
|
if (key === "Escape") {
|
|
setMentionQuery(null);
|
|
return true;
|
|
}
|
|
if (key === "ArrowDown" || key === "ArrowUp") {
|
|
if (mentionItems.length === 0) return false;
|
|
setMentionActiveIndex((current) =>
|
|
key === "ArrowDown" ? (current + 1) % mentionItems.length : (current - 1 + mentionItems.length) % mentionItems.length
|
|
);
|
|
return true;
|
|
}
|
|
const selected = mentionItems[mentionActiveIndex];
|
|
if (!selected) return false;
|
|
selectMention(selected);
|
|
return true;
|
|
}
|
|
|
|
return (
|
|
<ChatThreadPage
|
|
vm={vm}
|
|
draft={draft}
|
|
busy={fetcher.state !== "idle"}
|
|
errorKey={fetcher.data?.ok === false && fetcher.data.intent === "reply" ? fetcher.data.errorKey : null}
|
|
featureErrorKeys={{ ...chatFeatureErrorsByMessageId(featureMutations), ...chatMessageMutationErrors(messageMutations) }}
|
|
mentionAutocomplete={{
|
|
vm: mentionVm,
|
|
open: mentionQuery !== null,
|
|
loading: mentionQuery !== null && (!mentionResponseMatches || mentionFetcher.state !== "idle"),
|
|
activeIndex: Math.min(mentionActiveIndex, Math.max(0, mentionItems.length - 1)),
|
|
listboxId: "chat-thread-mention-listbox",
|
|
}}
|
|
optimisticReplies={pendingReplies}
|
|
actions={{
|
|
onBack: (href) => void navigate(href),
|
|
onDraftChange: (value, caret) => {
|
|
setDraft(value);
|
|
setComposerCaret(caret);
|
|
},
|
|
onSendReply: sendReply,
|
|
onToggleReaction: (messageId, emoji, active) => beginFeatureMutation({ kind: "reaction", messageId, emoji, active }),
|
|
onTogglePin: (messageId, pinned) => beginFeatureMutation({ kind: "pin", messageId, pinned }),
|
|
onEditMessage: (messageId, body) =>
|
|
submitMessageMutation({
|
|
kind: "edit_message",
|
|
messageId,
|
|
bodyMarkdown: body,
|
|
mentions: mentionsForEditedBody(messageId, body),
|
|
requestId: crypto.randomUUID(),
|
|
startedAtIso: new Date().toISOString(),
|
|
}),
|
|
onDeleteMessage: (messageId) =>
|
|
submitMessageMutation({
|
|
kind: "delete_message",
|
|
messageId,
|
|
requestId: crypto.randomUUID(),
|
|
startedAtIso: new Date().toISOString(),
|
|
}),
|
|
onMentionActiveIndexChange: setMentionActiveIndex,
|
|
onMentionSelect: selectMention,
|
|
onMentionKeyDown: handleMentionKeyDown,
|
|
onRetryReply: retryReply,
|
|
onDiscardReply: (clientMessageId) => setPendingReplies((current) => current.filter((reply) => reply.clientMessageId !== clientMessageId)),
|
|
onRetryFeature: retryFeatureMutation,
|
|
onRetry: () => revalidator.revalidate(),
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function formValue(formData: FormData, key: string): string {
|
|
return formData.get(key)?.toString().trim() ?? "";
|
|
}
|
|
|
|
function featureLabels(t: (key: string) => string) {
|
|
return {
|
|
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"),
|
|
};
|
|
}
|
|
|
|
export function ErrorBoundary(): React.JSX.Element {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: CHAT_MODULE_KEY, breadcrumbKey: "chat.thread.breadcrumb" };
|