Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/chat/ChatThreadPage.tsx
T

208 lines
9.5 KiB
TypeScript

import { useRef } from "react";
import { useTranslation } from "react-i18next";
import { FeatherArrowLeft, FeatherMessageSquare, FeatherSend } from "@subframe/core";
import type { ChatMentionAutocompleteVM, ChatMentionSuggestionVM, ChatThreadVM } from "@hivegrid/view-models";
import { Alert } from "~/ui/components/Alert";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { LoadingIndicatorSkeleton } from "~/ui/components/LoadingIndicatorSkeleton";
import { TextArea } from "~/ui/components/TextArea";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { ChatMessageFeatureCard } from "./ChatMessageFeatureCard";
import { ChatMentionAutocomplete } from "./ChatMentionAutocomplete";
export type ChatOptimisticThreadReply = Readonly<{
clientMessageId: string;
authorLabel: string;
bodyMarkdown: string;
createdAtIso: string;
deliveryState: "sending" | "sent" | "failed";
failureReasonKey: string | null;
}>;
export function ChatThreadPage({
vm,
draft,
busy,
errorKey,
featureErrorKeys,
mentionAutocomplete,
optimisticReplies = [],
actions,
}: {
readonly vm: ChatThreadVM;
readonly draft: string;
readonly busy: boolean;
readonly errorKey: string | null;
readonly featureErrorKeys?: Readonly<Record<string, string>>;
readonly optimisticReplies?: readonly ChatOptimisticThreadReply[];
readonly mentionAutocomplete?: {
readonly vm: ChatMentionAutocompleteVM | null;
readonly open: boolean;
readonly loading: boolean;
readonly activeIndex: number;
readonly listboxId: string;
};
readonly actions: {
readonly onBack: (href: string) => void;
readonly onDraftChange: (value: string, caret: number) => void;
readonly onSendReply: (value: string) => void;
readonly onToggleReaction: (messageId: string, emoji: string, active: boolean) => void;
readonly onTogglePin: (messageId: string, pinned: boolean) => void;
readonly onEditMessage: (messageId: string, body: string) => void;
readonly onDeleteMessage: (messageId: string) => void;
readonly onMentionActiveIndexChange?: (index: number) => void;
readonly onMentionSelect?: (suggestion: ChatMentionSuggestionVM) => number | null;
readonly onMentionKeyDown?: (key: "ArrowDown" | "ArrowUp" | "Enter" | "Escape") => boolean;
readonly onRetryReply?: (clientMessageId: string) => void;
readonly onDiscardReply?: (clientMessageId: string) => void;
readonly onRetryFeature?: (messageId: string) => void;
readonly onRetry: () => void;
};
}): React.JSX.Element {
const { t } = useTranslation();
const data = vm.status === "ready" ? vm.data : null;
const composerRef = useRef<HTMLTextAreaElement | null>(null);
function selectMention(suggestion: ChatMentionSuggestionVM): void {
const nextCaret = actions.onMentionSelect?.(suggestion) ?? null;
if (nextCaret === null) return;
requestAnimationFrame(() => {
composerRef.current?.focus();
composerRef.current?.setSelectionRange(nextCaret, nextCaret);
});
}
function sendDraft(): void {
const body = draft.trim();
if (!body || busy) return;
actions.onSendReply(body);
requestAnimationFrame(() => composerRef.current?.focus());
}
return (
<PageShell uiId="ui.chat.thread" className="mobile:[&_button]:min-h-11 mobile:[&_button]:min-w-11">
<PageHeader
icon={<FeatherMessageSquare className={PAGE_HEADER_ICON_CLASS} />}
title={data ? t("chat.thread.title", { channel: data.channelTitle }) : t("chat.thread.titleFallback")}
subtitle={data ? t("chat.thread.replyCount", { count: data.replyCount }) : undefined}
actions={
<Button variant="tertiary" icon={<FeatherArrowLeft />} onClick={() => data && actions.onBack(data.backHref)} disabled={!data}>
{t("shared.back")}
</Button>
}
/>
<PageBody>
{vm.status === "loading" || vm.status === "idle" ? (
<LoadingIndicatorSkeleton variant="list" aria-label={t("shared.loading")} />
) : vm.status === "error" ? (
<EmptyState
outlined
variant="error"
title={t("shared.error")}
body={t(vm.error.messageKey)}
action={<Button onClick={actions.onRetry}>{t("shared.retry")}</Button>}
/>
) : !data ? (
<EmptyState outlined title={t("chat.thread.empty.headline")} body={t("chat.thread.empty.body")} />
) : (
<ButtonGroup align="stack">
{errorKey ? <Alert variant="error" title={t(errorKey)} notDismissible /> : null}
<ChatMessageFeatureCard message={data.parent} featureErrorKey={featureErrorKeys?.[data.parent.id]} actions={actions} />
{data.replies.length === 0 && optimisticReplies.length === 0 ? (
<EmptyState outlined title={t(data.emptyRepliesHeadlineKey)} body={t(data.emptyRepliesBodyKey)} />
) : (
<>
{data.replies.map((reply) => (
<ChatMessageFeatureCard key={reply.id} message={reply} featureErrorKey={featureErrorKeys?.[reply.id]} actions={actions} />
))}
{optimisticReplies.map((reply) => (
<Card
key={reply.clientMessageId}
id={`message-local-${reply.clientMessageId}`}
variant={reply.deliveryState === "failed" ? "default" : "information"}
data-delivery-state={reply.deliveryState}
data-ui-id="ui.chat.thread.optimisticReply"
>
<ButtonGroup align="space-between">
<strong>{reply.authorLabel}</strong>
<BadgeFeedback farbe={reply.deliveryState === "failed" ? "subtle-negative" : "subtle-neutral"} size="small" role="status">
{t(`chat.message.delivery.${reply.deliveryState}`)}
</BadgeFeedback>
</ButtonGroup>
<p>{reply.bodyMarkdown}</p>
{reply.deliveryState === "failed" ? (
<ButtonGroup align="end" role="alert">
<span>{t(reply.failureReasonKey ?? "chat.message.sendFailed")}</span>
<Button variant="tertiary" onClick={() => actions.onRetryReply?.(reply.clientMessageId)}>
{t("shared.retry")}
</Button>
<Button variant="ghost" onClick={() => actions.onDiscardReply?.(reply.clientMessageId)}>
{t("shared.remove")}
</Button>
</ButtonGroup>
) : null}
</Card>
))}
</>
)}
{data.canReply ? (
<ButtonGroup align="stack">
<TextArea label={t("chat.thread.replyLabel")} showLabel>
<TextArea.Input
ref={composerRef}
value={draft}
placeholder={t(data.composerPlaceholderKey)}
onChange={(event) => actions.onDraftChange(event.target.value, event.target.selectionStart ?? event.target.value.length)}
onKeyDown={(event) => {
if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return;
if (
actions.onMentionKeyDown &&
["ArrowDown", "ArrowUp", "Enter", "Escape"].includes(event.key) &&
actions.onMentionKeyDown(event.key as "ArrowDown" | "ArrowUp" | "Enter" | "Escape")
) {
event.preventDefault();
return;
}
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
sendDraft();
}
}}
role="combobox"
aria-autocomplete="list"
aria-expanded={mentionAutocomplete?.open ?? false}
aria-controls={mentionAutocomplete?.open ? mentionAutocomplete.listboxId : undefined}
aria-activedescendant={
mentionAutocomplete?.open && !mentionAutocomplete.loading && (mentionAutocomplete.vm?.total ?? 0) > 0
? `${mentionAutocomplete.listboxId}-option-${mentionAutocomplete.activeIndex}`
: undefined
}
/>
</TextArea>
{mentionAutocomplete ? (
<ChatMentionAutocomplete
{...mentionAutocomplete}
actions={{
onSelect: selectMention,
onActiveIndexChange: actions.onMentionActiveIndexChange ?? (() => undefined),
}}
/>
) : null}
<Button variant="primary" icon={<FeatherSend />} onClick={sendDraft} disabled={busy || draft.trim().length === 0} loading={busy}>
{t("chat.thread.sendReply")}
</Button>
</ButtonGroup>
) : (
<Alert variant="neutral" title={t("chat.composer.permissionDenied")} notDismissible />
)}
</ButtonGroup>
)}
</PageBody>
</PageShell>
);
}