import { useEffect, useRef, useState } from "react"; import { Link } from "react-router"; import { useTranslation } from "react-i18next"; import { Description as DialogDescription, Title as DialogTitle } from "@radix-ui/react-dialog"; import { FeatherArrowDown, FeatherArrowLeft, FeatherAtSign, FeatherCheckSquare, FeatherEdit3, FeatherFile, FeatherImage, FeatherLink, FeatherMessageSquare, FeatherPaperclip, FeatherPin, FeatherRefreshCw, FeatherSend, FeatherSettings, FeatherSquare, FeatherTrash2, FeatherX, } from "@subframe/core"; import { chatMessageIdentityKey, type ChatAttachmentVM, type ChatChannelDetailVM, type ChatMentionAutocompleteVM, type ChatMentionSuggestionVM, type ChatMessageVM, } from "@hivegrid/view-models"; import { useLocaleFormatters } from "~/locale/format"; import type { ChatPendingAttachment } from "~/modules/chat/client/useChatAttachmentUploads"; import { useChatMessageViewport } from "~/modules/chat/client/useChatMessageViewport"; import { renderSanitizedChatMarkdown } from "~/utils/html-sanitizer"; import { Alert } from "~/ui/components/Alert"; import { Avatar } from "~/ui/components/Avatar"; 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 { Dialog } from "~/ui/components/Dialog"; import { EmptyState } from "~/ui/components/EmptyState"; import { LoadingIndicatorSkeleton } from "~/ui/components/LoadingIndicatorSkeleton"; import { Progress } from "~/ui/components/Progress"; import { TextArea } from "~/ui/components/TextArea"; import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell"; import { ChatMentionAutocomplete } from "./ChatMentionAutocomplete"; export type ChatChannelDetailActions = { readonly onBack: () => void; readonly onDraftChange: (draft: string, storageKey: string, caret: number) => void; readonly onSend: (bodyMarkdown: string) => boolean | void | Promise; readonly onRetryMessage: (clientMessageId: string) => void | Promise; readonly onDiscardMessage: (clientMessageId: string) => void; readonly onMessageVisibilityChange: (messageId: string, createdAtIso: string, visible: boolean) => void; readonly onRetryConnection: () => void | Promise; readonly onLoadOlder: (cursor: string) => void | Promise; readonly onOpenSettings: () => void; readonly onOpenPinned?: () => void; readonly onOpenThread?: (messageId: string, href: string | null) => void; readonly onToggleReaction?: (messageId: string, emoji: string, active: boolean) => void; readonly onTogglePin?: (messageId: string, pinned: boolean) => void; readonly onRetryFeature?: (messageId: string) => 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 onAddFiles?: (files: FileList) => void; readonly onAddPhotos?: (files: FileList) => void; readonly onStartRecording?: () => void | Promise; readonly onStopRecording?: () => void; readonly onCancelRecording?: () => void; readonly onRetryAttachment?: (clientId: string) => void; readonly onRemoveAttachment?: (clientId: string) => void; readonly onMarkAsTask?: (messageId: string) => void; }; export type ChatChannelDetailPageProps = { readonly vm: ChatChannelDetailVM; readonly actions: ChatChannelDetailActions; readonly draft: string; readonly sending?: boolean; readonly actionErrorKey?: string | null; readonly actionSuccessKey?: string | null; readonly featureErrorKeys?: Readonly>; readonly pendingAttachments?: readonly ChatPendingAttachment[]; readonly isStartingRecording?: boolean; readonly isRecording?: boolean; readonly recordingDurationSeconds?: number; readonly markingTaskMessageId?: string | null; readonly focusedMessageId?: string | null; readonly scrollStorageKey?: string; readonly mentionAutocomplete?: { readonly vm: ChatMentionAutocompleteVM | null; readonly open: boolean; readonly loading: boolean; readonly activeIndex: number; readonly listboxId: string; }; }; function DetailShell({ title, subtitle, avatar, onBack, onOpenSettings, onOpenPinned, showSettings = false, showPinned = false, children, }: { readonly title: React.ReactNode; readonly subtitle?: React.ReactNode; readonly avatar?: { readonly imageUrl: string | null; readonly fallbackLabel: string }; readonly onBack: () => void; readonly onOpenSettings?: () => void; readonly showSettings?: boolean; readonly onOpenPinned?: () => void; readonly showPinned?: boolean; readonly children: React.ReactNode; }): React.JSX.Element { const { t } = useTranslation(); return ( {avatar.fallbackLabel} ) : ( ) } title={title} subtitle={subtitle} actions={ {showPinned && onOpenPinned ? ( ) : null} {showSettings && onOpenSettings ? ( ) : null} } /> {children} ); } function MessageVisibilityMarker({ enabled, messageId, createdAtIso, onVisibilityChange, children, }: { readonly enabled: boolean; readonly messageId: string; readonly createdAtIso: string; readonly onVisibilityChange: (messageId: string, createdAtIso: string, visible: boolean) => void; readonly children: React.ReactNode; }): React.JSX.Element { const ref = useRef(null); const onVisibilityChangeRef = useRef(onVisibilityChange); useEffect(() => { onVisibilityChangeRef.current = onVisibilityChange; }, [onVisibilityChange]); useEffect(() => { const element = ref.current; if (!enabled || !element || typeof IntersectionObserver === "undefined") return; let visible = false; const observer = new IntersectionObserver( (entries) => { const entry = entries.find((candidate) => candidate.target === element); if (!entry) return; const nextVisible = entry.isIntersecting && entry.intersectionRatio >= requiredMessageVisibilityRatio(entry.boundingClientRect.height); if (nextVisible === visible) return; visible = nextVisible; onVisibilityChangeRef.current(messageId, createdAtIso, visible); }, { threshold: requiredMessageVisibilityRatio(element.getBoundingClientRect().height) } ); observer.observe(element); return () => { observer.disconnect(); if (visible) onVisibilityChangeRef.current(messageId, createdAtIso, false); }; }, [createdAtIso, enabled, messageId]); return
{children}
; } function requiredMessageVisibilityRatio(elementHeight: number): number { if (!Number.isFinite(elementHeight) || elementHeight <= 0) return 0.6; return Math.min(0.6, 240 / elementHeight); } function attachmentIcon(attachment: Pick): React.JSX.Element { if (attachment.kind === "image") return ; if (attachment.kind === "voice") return ; return ; } function MessageAttachments({ message }: { readonly message: ChatMessageVM }): React.JSX.Element | null { const { t } = useTranslation(); const formatters = useLocaleFormatters(); const isLocalEcho = message.source === "local_echo"; if (message.attachments.length === 0) return null; return ( {message.attachments.map((attachment) => { if (attachment.scanStatus === "blocked") { return ; } if (attachment.scanStatus === "pending") { return ; } return ( {!isLocalEcho && attachment.kind === "image" && attachment.previewHref ? ( {attachment.altText ) : null} {!isLocalEcho && attachment.kind === "voice" ? ( // Voice Notes intentionally have no transcript in AK-P15b v1. // eslint-disable-next-line jsx-a11y/media-has-caption ) : null} {attachmentIcon(attachment)} {attachment.fileName} {formatters.number(attachment.sizeBytes, { style: "unit", unit: "byte", unitDisplay: "narrow" })} {!isLocalEcho && attachment.kind !== "voice" ? ( ) : null} ); })} ); } function MessageLinks({ message }: { readonly message: ChatMessageVM }): React.JSX.Element | null { if (message.linkPreviews.length === 0) return null; return ( {message.linkPreviews.map((preview) => { const canonicalHost = new URL(preview.url).hostname.toLowerCase(); return ( {canonicalHost} {preview.title ?? preview.url} {preview.description ? {preview.description} : null} ); })} ); } function DeliveryState({ message, actions }: { readonly message: ChatMessageVM; readonly actions: ChatChannelDetailActions }): React.JSX.Element | null { const { t } = useTranslation(); if (!message.author?.isCurrentUser || !message.readAggregate) return null; if (message.deliveryState === "failed") { return ( {t(message.failureReasonKey ?? "chat.message.sendFailed")} {message.retryable ? ( ) : null} ); } if (message.deliveryState === "sending") { return ( {t(message.deliveryStateKey)} ); } if (message.readAggregate.recipientCount > 0) { return ( {t(message.readAggregate.labelKey, { readCount: message.readAggregate.readCount, recipientCount: message.readAggregate.recipientCount, })} ); } return ( {t(message.deliveryStateKey)} ); } function SystemMessageCard({ message, actions }: { readonly message: ChatMessageVM; readonly actions: ChatChannelDetailActions }): React.JSX.Element { const { t } = useTranslation(); const formatters = useLocaleFormatters(); const systemEvent = message.systemEvent; const eventLabel = t(systemEvent?.labelKey ?? "chat.systemEvent.generic", systemEvent?.values ?? {}); const eventBadge = ( {eventLabel} ); return ( {systemEvent?.href ? {eventBadge} : eventBadge} {formatters.date(message.createdAtIso, { hour: "2-digit", minute: "2-digit" })} ); } function MessageCard({ message, actions, featureErrorKey, markingTaskMessageId, focused, }: { readonly message: ChatMessageVM; readonly actions: ChatChannelDetailActions; readonly featureErrorKey?: string; readonly markingTaskMessageId?: string | null; readonly focused: boolean; }): React.JSX.Element { const { t } = useTranslation(); const formatters = useLocaleFormatters(); const [editOpen, setEditOpen] = useState(false); const [deleteOpen, setDeleteOpen] = useState(false); const [editDraft, setEditDraft] = useState(message.bodyMarkdown ?? ""); if (message.bodyFormat === "system" || message.author === null) { return ; } const isOwn = message.author.isCurrentUser; const renderedBody = message.bodyMarkdown ? replaceMentionTokensWithLabels(message.bodyMarkdown, message.mentions) : null; return ( <> {!isOwn ? ( {message.author.avatar.fallbackLabel} ) : null} {message.author.displayName} {formatters.date(message.createdAtIso, { hour: "2-digit", minute: "2-digit" })} {message.editedAtIso ? ( {t("chat.message.edited")} ) : null} {message.pin ? ( ) : null} {message.tombstoneKey ? ( ) : renderedBody ? (
) : null} {message.mentions.length > 0 ? ( {message.mentions.map((mention) => { const badge = ( ); return mention.href ? ( {badge} ) : ( {badge} ); })} ) : null} {featureErrorKey ? ( {actions.onRetryFeature ? ( ) : null} ) : null} {message.reactions.length > 0 || message.thread ? ( {message.reactions.map((reaction) => ( ))} {message.thread ? ( {t("chat.message.threadReplies", { count: message.thread.replyCount })} ) : null} ) : null} {message.actions.canReact || message.actions.canReply || message.actions.canPin || message.actions.canMarkAsTask || message.actions.canEdit || message.actions.canDelete ? ( {message.actions.canReact ? ( ) : null} {message.actions.canReply ? ( ) : null} {message.actions.canPin ? ( ) : null} {message.actions.canMarkAsTask ? ( ) : null} {message.actions.canEdit && actions.onEditMessage ? ( ) : null} {message.actions.canDelete && actions.onDeleteMessage ? ( ) : null} ) : null} setEditOpen(open)}> {t("chat.message.editTitle")} setDeleteOpen(open)}> {t("chat.message.deleteConfirmTitle")} {t("chat.message.deleteConfirmBody")} ); } function messageViewportKey(message: ChatMessageVM): string { return chatMessageIdentityKey(message); } function replaceMentionTokensWithLabels(markdown: string, mentions: ChatMessageVM["mentions"]): string { const labels = new Map(mentions.map((mention) => [`${mention.kind}\u0000${mention.id}`, mention.label])); return markdown.replace(/<@(user|project|contact|company):([A-Za-z0-9._-]{1,500})>/gu, (_token, kind: string, id: string) => { const label = labels.get(`${kind}\u0000${id}`) ?? "@"; return `@${label.replace(/([\\`*_{}\[\]()<>#+\-.!|])/gu, "\\$1")}`; }); } function messageAnnouncementPreview(message: ChatMessageVM, fallback: string): string { if (!message.bodyMarkdown) return fallback; const plainText = message.bodyMarkdown .replace(/<[^>]*>/g, " ") .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1") .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1") .replace(/[`*_~>#]/g, " ") .replace(/^\s*[-+]\s+/gm, "") .replace(/\s+/g, " ") .trim(); return plainText.slice(0, 160) || fallback; } function useAnnouncementKey(latestKey: string | null): string | null { const [announcementKey, setAnnouncementKey] = useState(null); useEffect(() => { setAnnouncementKey(null); if (!latestKey) return; const handle = setTimeout(() => setAnnouncementKey(latestKey), 0); return () => clearTimeout(handle); }, [latestKey]); return announcementKey; } function ConnectionState({ vm, onRetry, }: { readonly vm: NonNullable["connection"]; readonly onRetry: () => void | Promise; }): React.JSX.Element | null { const { t } = useTranslation(); const liveStatus = ( {t(vm.stateLabelKey)} ); if (vm.state === "online") return liveStatus; const variant = vm.state === "blocked" ? "error" : vm.state === "connecting" ? "neutral" : "warning"; return ( <> {liveStatus} void onRetry()}> {t("shared.retry")} ) : undefined } notDismissible={!vm.canRetry} data-connection-state={vm.state} /> ); } function PendingAttachmentQueue({ attachments, actions, }: { readonly attachments: readonly ChatPendingAttachment[]; readonly actions: ChatChannelDetailActions; }): React.JSX.Element | null { const { t } = useTranslation(); const formatters = useLocaleFormatters(); if (attachments.length === 0) return null; return ( {attachments.map((attachment) => ( {attachmentIcon(attachment)} {attachment.fileName} {formatters.number(attachment.sizeBytes, { style: "unit", unit: "byte", unitDisplay: "narrow" })} {attachment.status === "error" ? ( ) : null} } data-ui-id="ui.chat.channelDetail.error" /> ); } if (vm.status === "empty" || !vm.data) { return ( ); } const { composer, connection, header, history, messageGroups, presence, typingLabels } = vm.data; const onlineCount = presence.filter((entry) => entry.status === "online").length; const awayCount = presence.length - onlineCount; const visibleTypingLabels = typingLabels.slice(0, 2); const remainingTypingCount = Math.max(0, typingLabels.length - visibleTypingLabels.length); const remoteAnnouncementMessage = announcementKey ? vm.data.messages.find((message) => messageViewportKey(message) === announcementKey) : null; const hasReadyAttachment = pendingAttachments.some((attachment) => attachment.status === "ready" && attachment.fileId !== null); const hasBlockingAttachment = pendingAttachments.some((attachment) => attachment.status !== "ready"); function changeDraft(value: string, caret: number): void { actions.onDraftChange(value, composer.draftStorageKey, caret); } function selectMention(suggestion: ChatMentionSuggestionVM): void { const nextCaret = actions.onMentionSelect?.(suggestion) ?? null; if (nextCaret === null) return; requestAnimationFrame(() => { composerInputRef.current?.focus(); composerInputRef.current?.setSelectionRange(nextCaret, nextCaret); }); } async function sendDraft(): Promise { const body = draft.trim(); if ((!body && !hasReadyAttachment) || hasBlockingAttachment || !composer.canSend || sending) return; try { await actions.onSend(body); } catch { // The controlled draft remains visible. The route surfaces transport errors. } finally { composerInputRef.current?.focus(); } } return ( {header.dmAuditBannerKey ? ( ) : null} {actionErrorKey ? : null} {actionSuccessKey ? : null} {presence.length > 0 ? ( {onlineCount > 0 ? ( {t("chat.channel.presenceOnline", { count: onlineCount })} ) : null} {awayCount > 0 ? ( {t("chat.channel.presenceAway", { count: awayCount })} ) : null} ) : null}
{history.hasOlder && history.olderCursor ? ( ) : null} {messageGroups.length === 0 ? ( ) : ( messageGroups.map((group) => (
{group.messages.map((message) => ( ))}
)) )}
{remoteAnnouncementMessage ? ( {remoteAnnouncementMessage.systemEvent ? t("chat.channel.newSystemMessageAnnouncement", { message: t(remoteAnnouncementMessage.systemEvent.labelKey, remoteAnnouncementMessage.systemEvent.values), }) : t("chat.channel.newMessageAnnouncement", { author: remoteAnnouncementMessage.author?.displayName ?? t("chat.participant.unknown"), preview: messageAnnouncementPreview( remoteAnnouncementMessage, remoteAnnouncementMessage.tombstoneKey ? t(remoteAnnouncementMessage.tombstoneKey) : t("chat.attachments.sentFallback") ), })} ) : null} {viewport.newMessageCount > 0 ? ( {t(vm.data.newMessagesLabelKey, { count: viewport.newMessageCount })} ) : null} {typingLabels.length > 0 ? ( 0 ? t("chat.channel.typingOverflow", { names: visibleTypingLabels.join(", "), count: remainingTypingCount }) : t("chat.channel.typing", { count: visibleTypingLabels.length, names: visibleTypingLabels.join(", ") }) } notDismissible data-ui-id="ui.chat.channelDetail.typing" /> ) : null}
{!composer.enabled && composer.disabledReasonKey ? : null} {mentionAutocomplete ? ( undefined), }} /> ) : null} {composer.canAttachFiles ? ( <> { if (event.currentTarget.files) actions.onAddFiles?.(event.currentTarget.files); event.currentTarget.value = ""; }} data-ui-id="ui.chat.channelDetail.fileInput" /> { if (event.currentTarget.files) actions.onAddPhotos?.(event.currentTarget.files); event.currentTarget.value = ""; }} data-ui-id="ui.chat.channelDetail.photoInput" /> ) : null} {composer.canRecordVoice ? ( {isRecording ? ( ) : null} ) : null}
); } function formatRecordingDuration(durationSeconds: number): string { const safeSeconds = Math.max(0, Math.floor(durationSeconds)); return `${Math.floor(safeSeconds / 60)}:${String(safeSeconds % 60).padStart(2, "0")}`; }