import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { useQuery } from '@tanstack/react-query'; import { Link, useOutletContext, useParams } from 'react-router-dom'; import type { StoredMessage } from 'tinode-sdk'; import { Drafty } from 'tinode-sdk'; import { Icon } from '@/app/Icon'; import { Toast } from '@/app/Toast'; import { EmojiPanel } from '@/features/messages/EmojiPanel'; import { ForwardPickerModal } from '@/features/messages/ForwardPickerModal'; import { MentionPicker } from '@/features/messages/MentionPicker'; import { MessageContextMenu } from '@/features/messages/MessageContextMenu'; import { MessageRow } from '@/features/messages/MessageBubble'; import { VoiceRecorder } from '@/features/messages/VoiceRecorder'; import { GroupAnnouncementModal } from '@/features/groups/GroupAnnouncementModal'; import { JoinRequestsModal } from '@/features/groups/JoinRequestsModal'; import { useBootstrap } from '@/lib/api/hooks'; import { favoriteMessages, type MediaType, recallMessage } from '@/lib/api/messages'; import { getAllGroupMembers, getGroup, getGroupGovernance, getGroupMutes, getGroupSummary } from '@/lib/api/groups'; import { avatarBgClass, avatarLetter } from '@/lib/avatar'; import { FETCH_PAGE_TRIGGER, MESSAGES_PAGE } from '@/lib/config'; import { useClickOutside } from '@/lib/hooks'; import { availableActions, recallRemainingSeconds, type MessageAction } from '@/lib/messages/actions'; import { isRecalled } from '@/lib/messages/dispatch'; import { renderDrafty } from '@/lib/messages/drafty'; import { buildMentionedContent, detectMentionTrigger, type PendingMention } from '@/lib/messages/mentions'; import { sendFile, sendImage, sendVoice } from '@/lib/tinode/attachments'; import { useChatList, useTinode, useTopicMessages } from '@/lib/tinode/hooks'; import { forwardMessage, sendPrebuiltContent, sendReply, sendText } from '@/lib/tinode/send'; import { closeConversation, ensureTopicAttached, openConversation } from '@/lib/tinode/topics'; import { useCallStore } from '@/stores/calls'; import { requestConfirm } from '@/stores/confirmDialog'; import { notImplemented } from '@/stores/globalToast'; import { useMessageJumpStore } from '@/stores/messageJump'; import { useSessionStore } from '@/stores/session'; interface OutletCtx { onToggleDetail: () => void; /** Whether the detail panel is CURRENTLY shown -- at >=1280px this is the persisted * (localStorage) docked-panel state, at 960-1279px the temporary drawer state. Drives the * header "i" button's highlight. */ detailVisible: boolean; /** Opens the shared history-search modal (owned by MessagesLayout, the closest common ancestor of * this view and DetailColumn, which can also open it from its own "查找聊天记录" row). */ onOpenHistory: (tab: 'text' | MediaType) => void; } interface ContextMenuState { x: number; y: number; msg: StoredMessage; } export function ConversationView() { const { topicId } = useParams(); const { onToggleDetail, detailVisible, onOpenHistory } = useOutletContext(); const myUserId = useSessionStore((s) => s.myUserId); const tinode = useTinode(); const contacts = useChatList(); const contact = contacts.find((c) => c.topic === topicId); const messages = useTopicMessages(topicId); const bootstrap = useBootstrap(); // Keyed by topicId, not a single string -- ConversationView is one long-lived instance reused // across every conversation (the route is `:topicId`, React Router doesn't remount on param // change), so a plain single draft leaks the PREVIOUS conversation's unsent text into whichever // one you open next. const [draftByTopic, setDraftByTopic] = useState>({}); const draft = (topicId && draftByTopic[topicId]) || ''; const setDraft = (value: string) => { if (topicId) setDraftByTopic((prev) => ({ ...prev, [topicId]: value })); }; // Same per-topic keying as draftByTopic, and for the same reason -- a mention picked while // composing in group A must not still be "pending" if the user switches to group B and back // before sending (buildMentionedContent would then splice a real MN entity for a name that's // just inert leftover text in a completely different conversation's draft). const [mentionsByTopic, setMentionsByTopic] = useState>({}); const pendingMentions = (topicId && mentionsByTopic[topicId]) || []; const [mentionTrigger, setMentionTrigger] = useState<{ start: number; query: string } | null>(null); const [groupModal, setGroupModal] = useState<'announcement' | 'join-requests' | null>(null); const textareaRef = useRef(null); const [menu, setMenu] = useState(null); const [selectMode, setSelectMode] = useState(false); const [selectedSeqs, setSelectedSeqs] = useState>(new Set()); const [loadingOlder, setLoadingOlder] = useState(false); const [recording, setRecording] = useState(false); const [bulkForwardOpen, setBulkForwardOpen] = useState(false); const [replyTo, setReplyTo] = useState(null); const [forwardMsg, setForwardMsg] = useState(null); const [emojiOpen, setEmojiOpen] = useState(false); const emojiContainerRef = useRef(null); const mentionContainerRef = useRef(null); // Neither popover had a way to dismiss except re-clicking its own toggle -- a real gap a user // report caught (open the emoji panel, click elsewhere in the app, and it just sits there). useClickOutside(emojiContainerRef, () => setEmojiOpen(false), emojiOpen); useClickOutside(mentionContainerRef, () => setMentionTrigger(null), !!mentionTrigger); const [errorToast, setErrorToast] = useState(''); const [successToast, setSuccessToast] = useState(''); const streamRef = useRef(null); const autoScrollRef = useRef(true); // "Jump to message" (HistorySearchModal result click, via stores/messageJump.ts). `highlightedSeq` // drives MessageRow's brief flash; `pendingJumpSeqRef` is a ref (not state) because it's read/written // across two different effects below without needing a render of its own. const jumpTarget = useMessageJumpStore((s) => s.target); const [highlightedSeq, setHighlightedSeq] = useState(null); const pendingJumpSeqRef = useRef(null); // Bumped every time a conversation is (re)opened below -- NOT the same as comparing topicId by // value, which would false-positive if the user opens A, then B, then A again within a single // loadOlder() round trip: topicId ends up back at "A" even though the DOM has since been torn // down and rebuilt by the intervening open/close cycle, so a same-topicId check alone would wrongly // treat that as "still the same open" and apply a scroll-restore computed against content that // isn't there anymore. const openGenerationRef = useRef(0); // Every "fire and forget" send/recall/favorite/forward action below used to swallow its own // failure with an empty `.catch(() => {})` (or, for forward, no catch at all) -- e.g. an // over-size-limit attachment would throw a friendly Chinese error from uploadFile() that then // just vanished, leaving the user staring at nothing happening with no idea why. const showError = (err: unknown, fallback: string) => setErrorToast(err instanceof Error ? err.message : fallback); // docs/IM-前后端对接文档.md §4.16: "成功 Toast 只在至少一项成功时展示,部分失败需给出汇总" -- this // response's `created_count`/`existing_count`/`failed[]` were being resolved and thrown away // entirely, so favoriting from a message's context menu or the multi-select bar gave the user // total silence either way: no confirmation on full success, and no way to learn that some of // several selected messages weren't actually favorited. const notifyFavoriteResult = (result: { created_count: number; existing_count: number; failed: Array<{ seq: number; reason: string }> }) => { if (result.created_count + result.existing_count > 0) setSuccessToast('已收藏'); if (result.failed.length) setErrorToast(`${result.failed.length} 条消息收藏失败`); }; useEffect(() => { if (!topicId) return undefined; // Unlike every other action in this component (see showError's own comment above), a failed // subscribe here used to just vanish into an empty `.catch(() => {})` -- the user would land on // a totally blank message list with no error, no retry, and (since the noteRead effect below // only fires once `messages.length > 0`) a read receipt that can never be sent, leaving the chat // list's unread badge permanently stuck for a conversation that in fact never loaded at all. openConversation(topicId).catch((err) => showError(err, '加载会话失败,请重试')); return () => { closeConversation(topicId).catch(() => {}); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [topicId]); // useLayoutEffect, not useEffect -- this component never remounts on topicId change (route is // `:topicId`), so a plain useEffect (which fires after paint) can let one frame render with the // PREVIOUS conversation's select-mode/menu/etc. still showing over the new conversation's message // list underneath, self-correcting only on the next tick. useLayoutEffect(() => { openGenerationRef.current += 1; setSelectMode(false); setSelectedSeqs(new Set()); setMenu(null); setReplyTo(null); setForwardMsg(null); setBulkForwardOpen(false); setEmojiOpen(false); // Without this, a mention picker left open while typing in group A reappears in group B after a // fast conversation switch (isGroup is true there too), anchored to a caret offset that describes // A's draft, not B's -- picking a suggestion would splice "@Name" into the wrong text at the wrong // position. setMentionTrigger(null); // Unmounting VoiceRecorder stops its media stream via its own cleanup effect -- without this, // a recording started in conversation A silently keeps going after navigating to B, and its // onSend callback (re-created every render off the CURRENT topicId) would publish the eventual // recording into B instead of the conversation the user was actually recording in. setRecording(false); // Without these two, a "加载更多" in flight when the user switches conversations leaves a // stale spinner showing (never resolves against the topic it started on) and, if the PREVIOUS // conversation had been scrolled up when it was left, the ref carries that `false` into the // NEW conversation and silently skips scrolling it to the bottom on open. setLoadingOlder(false); autoScrollRef.current = true; // An error toast from the previous conversation (e.g. "图片发送失败") would otherwise keep // showing over whichever conversation is now open, misattributing the failure. setErrorToast(''); setSuccessToast(''); // A jump-to-message request still pending when the user switches away (its fetch was in flight, // or it resolved but the scroll-on-mount effect hadn't fired yet) would otherwise survive into // the NEW conversation and, once ITS messages populate, try to scroll+highlight whatever row in // B happens to share the SAME seq number the user searched for in A -- seq is per-topic, so a // collision across two different conversations is completely ordinary, not a rare edge case. pendingJumpSeqRef.current = null; setHighlightedSeq(null); }, [topicId]); useEffect(() => { if (autoScrollRef.current) { streamRef.current?.scrollTo({ top: streamRef.current.scrollHeight }); } // `topicId` is included so switching between two conversations that both happen to have // already loaded the same number of messages (e.g. both exactly MESSAGES_PAGE on first open) // still scrolls the newly-opened one to the bottom -- `messages.length` alone wouldn't change. }, [messages.length, topicId]); // Consumes a pending "jump to message" request (HistorySearchModal result click). Fetches directly // via `since`/`before` (arbitrary absolute seq bounds per the Tinode wire protocol, not required to // be adjacent to whatever's already cached) rather than routing through loadOlder()'s gap-fill -- // that machinery is scoped to backfilling holes within the currently-visible min/max span, not // "there's an entirely separate old cluster somewhere else the user wants to see right now". useEffect(() => { if (!jumpTarget || jumpTarget.topic !== topicId) return; useMessageJumpStore.getState().clear(); const seq = jumpTarget.seq; pendingJumpSeqRef.current = seq; if (messages.some((m) => m.seq === seq)) return; // already loaded -- the effect below scrolls to it autoScrollRef.current = false; // otherwise the scroll-to-bottom effect above fights this jump const t = tinode.getTopic(topicId); const half = Math.floor(MESSAGES_PAGE / 2); t.getMeta(t.startMetaQuery().withData(Math.max(1, seq - half), seq + half + 1, MESSAGES_PAGE).build()).catch(() => { pendingJumpSeqRef.current = null; showError(null, '未能加载该消息,可能已被删除'); }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [jumpTarget, topicId]); // Performs the actual scroll+highlight once the target row exists in the DOM -- covers both the // "already loaded" case (this and the effect above run in the same commit, so the ref is already // set by the time this checks) and the "had to fetch first" case (re-fires once `messages` picks up // the newly-arrived data via useTopicMessages' own subscription, no manual wiring needed here). useEffect(() => { const seq = pendingJumpSeqRef.current; if (seq == null) return; const el = streamRef.current?.querySelector(`[data-seq="${seq}"]`); if (!el) return; pendingJumpSeqRef.current = null; el.scrollIntoView({ block: 'center' }); setHighlightedSeq(seq); window.setTimeout(() => setHighlightedSeq((cur) => (cur === seq ? null : cur)), 2000); }, [messages, jumpTarget]); useEffect(() => { if (!topicId || messages.length === 0) return; tinode.getTopic(topicId).noteRead(0); }, [topicId, messages.length, tinode]); // Computed independently of `topic` below (not `topic.isGroupType()`) so this and the group-data // queries it gates can sit before the `if (!topicId)` early return, alongside every other hook -- // `tinode.getTopic()` is a cheap cache lookup-or-create either way, calling it twice is harmless. const isGroup = !!topicId && tinode.getTopic(topicId).isGroupType(); const membersQuery = useQuery({ queryKey: ['group-members', topicId], queryFn: () => getAllGroupMembers(topicId || ''), enabled: isGroup, }); const groupProfileQuery = useQuery({ queryKey: ['group', topicId], queryFn: () => getGroup(topicId || ''), enabled: isGroup, }); const groupSummaryQuery = useQuery({ queryKey: ['group-summary', topicId], queryFn: () => getGroupSummary(topicId || ''), enabled: isGroup, }); const governanceQuery = useQuery({ queryKey: ['group-governance', topicId], queryFn: () => getGroupGovernance(topicId || ''), enabled: isGroup, }); const mutesQuery = useQuery({ queryKey: ['group-mutes', topicId], queryFn: () => getGroupMutes(topicId || ''), enabled: isGroup, }); const memberByUserId = useMemo(() => new Map((membersQuery.data || []).map((m) => [m.user_id, m])), [membersQuery.data]); const myMember = myUserId ? memberByUserId.get(myUserId) : undefined; const isGroupAdmin = myMember?.role === 'owner' || myMember?.role === 'admin'; const groupSublineParts = [ governanceQuery.data?.join_approval ? '已开启进群验证' : null, mutesQuery.data?.items.length ? `${mutesQuery.data.items.length} 位成员被禁言` : null, ].filter(Boolean); if (!topicId) return null; const topic = tinode.getTopic(topicId); const peerName = contact?.public?.fn || topicId; const groupMemberCount = groupProfileQuery.data?.member_count ?? membersQuery.data?.length ?? 0; // `peerName` is the GROUP's own name for a group topic, not any member's -- reusing it to label // "who is being quoted" (as both the reply-composer preview and the actual sent quote block used // to) meant every single group-chat reply permanently displayed "回复 <群名>:…" for every member, // regardless of who actually sent the quoted message. `memberByUserId` already resolves this // correctly per-bubble (senderName below); reused here for the identical lookup rather than a // second, divergent resolution path. const quotedSenderLabel = (fromUserId: string | undefined) => { if (myUserId && fromUserId === myUserId) return '我'; if (isGroup && fromUserId) return memberByUserId.get(fromUserId)?.display_name || fromUserId; return peerName; }; /** * "加载更多" (README §3.2/old app's messages-view.jsx): not simple since/before paging -- computes * which seq ranges are actually missing from the local cache within the currently-visible window * (topic.msgHasMoreMessages) and fills exactly those gaps (topic.getMessagesPage), since messages * can have server-side deletions punching holes in an otherwise-contiguous range. */ const loadOlder = async () => { if (loadingOlder) return; const calledForGeneration = openGenerationRef.current; const el = streamRef.current; const min = topic.minMsgSeq(); const max = topic.maxMsgSeq(); const gaps = topic.msgHasMoreMessages(min, max, false); if (gaps.length === 0) return; setLoadingOlder(true); const prevHeight = el?.scrollHeight ?? 0; const prevTop = el?.scrollTop ?? 0; try { await topic.getMessagesPage(MESSAGES_PAGE, gaps, min, max); } finally { // If the conversation was closed and reopened (even back to this SAME topicId) while this was // in flight, `el` now shows content from a different open/close cycle -- prevTop/prevHeight // were measured against content that isn't there anymore, so applying them would jump the // current conversation's scroll to a meaningless spot. Comparing topicId alone would miss an // A->B->A round trip (same string, different generation); only the specific open this request // was made for should ever clear its own loading flag or touch the scroll position. if (openGenerationRef.current === calledForGeneration) { setLoadingOlder(false); requestAnimationFrame(() => { if (el) el.scrollTop = prevTop + (el.scrollHeight - prevHeight); }); } } }; const handleScroll = () => { const el = streamRef.current; if (!el) return; autoScrollRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80; if (el.scrollTop <= FETCH_PAGE_TRIGGER) { loadOlder(); } }; const submit = () => { const text = draft.trim(); if (!text) return; setDraft(''); setMentionTrigger(null); if (replyTo) { // Mentions inside a reply don't get spliced into real MN entities -- a quoted reply that also // pings someone is a rare enough compound case that it isn't worth a second stitching path; // the "@name" text still sends fine, just without the entity/highlight. sendReply(topic, text, replyTo, quotedSenderLabel(replyTo.from)).catch((err) => showError(err, '发送失败')); setReplyTo(null); } else if (pendingMentions.length > 0) { sendPrebuiltContent(topic, buildMentionedContent(text, pendingMentions)).catch((err) => showError(err, '发送失败')); } else { sendText(topic, text).catch((err) => showError(err, '发送失败')); } if (topicId) setMentionsByTopic((prev) => ({ ...prev, [topicId]: [] })); }; const handleDraftChange = (e: React.ChangeEvent) => { const value = e.target.value; setDraft(value); if (isGroup) setMentionTrigger(detectMentionTrigger(value, e.target.selectionStart ?? value.length)); }; const pickMention = (choice: PendingMention) => { if (!mentionTrigger || !topicId) return; const before = draft.slice(0, mentionTrigger.start); const after = draft.slice(mentionTrigger.start + 1 + mentionTrigger.query.length); const inserted = `${before}@${choice.label} `; setDraft(inserted + after); setMentionsByTopic((prev) => ({ ...prev, [topicId]: [...(prev[topicId] || []), choice] })); setMentionTrigger(null); setEmojiOpen(false); // Matches insertMentionTrigger's own restore below -- without an explicit setSelectionRange // (deferred so the textarea's DOM value has actually updated to `inserted + after` first), the // cursor doesn't reliably land right after the just-inserted "@Name ", making it awkward to keep // typing; a bare focus() alone doesn't move the caret to a specific offset. Deferred via // setTimeout(0), not requestAnimationFrame -- rAF callbacks are paused outright while the tab is // backgrounded/hidden (confirmed live: an rAF scheduled right after a click never fired at all // in a hidden tab, a setTimeout(0) scheduled the same way fired normally), and this restore needs // to run regardless of whether the tab happens to be foregrounded at that exact moment. const el = textareaRef.current; setTimeout(() => { el?.focus(); el?.setSelectionRange(inserted.length, inserted.length); }, 0); }; /** README §4.3's composer "@" toolbar icon -- same effect as typing '@' by hand, for groups. */ const insertMentionTrigger = () => { const el = textareaRef.current; const pos = el?.selectionStart ?? draft.length; const needsSpace = pos > 0 && !/\s/.test(draft[pos - 1] ?? ' '); const insertion = `${needsSpace ? ' ' : ''}@`; const next = draft.slice(0, pos) + insertion + draft.slice(pos); setDraft(next); setMentionTrigger({ start: pos + insertion.length - 1, query: '' }); setEmojiOpen(false); setTimeout(() => { el?.focus(); el?.setSelectionRange(pos + insertion.length, pos + insertion.length); }, 0); }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Escape' && mentionTrigger) { setMentionTrigger(null); return; } // A picked mention should delete as one atomic "@label" unit on Backspace, not character by // character (README §4.3 doesn't spell this out explicitly, but every real chat app treats an // inserted mention this way, and a user report confirmed the plain-textarea default -- delete // one character at a time -- read as broken here specifically). Only intercepts a plain caret // (no active selection) sitting right after one of THIS topic's actually-tracked mentions, so // an unrelated hand-typed "foo@bar" is untouched. if (e.key === 'Backspace' && topicId && pendingMentions.length > 0) { const el = e.currentTarget; if (el.selectionStart === el.selectionEnd) { const pos = el.selectionStart; const before = draft.slice(0, pos); const hit = pendingMentions.find((m) => before.endsWith(`@${m.label} `) || before.endsWith(`@${m.label}`)); if (hit) { const token = before.endsWith(`@${hit.label} `) ? `@${hit.label} ` : `@${hit.label}`; const newBefore = before.slice(0, before.length - token.length); const next = newBefore + draft.slice(pos); e.preventDefault(); setDraft(next); setMentionsByTopic((prev) => ({ ...prev, [topicId]: (prev[topicId] || []).filter((m) => m !== hit) })); requestAnimationFrame(() => el.setSelectionRange(newBefore.length, newBefore.length)); return; } } } if (e.key !== 'Enter' || e.shiftKey) return; // Guards against CJK IME candidate-selection Enter keystrokes being mistaken for submit -- // a real, unfixed bug class in the old app (confirmed by its own research: zero isComposing/ // compositionstart/keyCode-229 guards anywhere in that codebase). if (e.nativeEvent.isComposing) return; e.preventDefault(); submit(); }; const toggleSelect = (seq: number) => { setSelectedSeqs((prev) => { const next = new Set(prev); if (next.has(seq)) next.delete(seq); else next.add(seq); return next; }); }; const exitSelectMode = () => { setSelectMode(false); setSelectedSeqs(new Set()); }; const bulkDelete = async () => { if (selectedSeqs.size === 0) return; if (!(await requestConfirm({ message: `删除已选择的 ${selectedSeqs.size} 条消息?`, danger: true }))) return; topic.delMessagesList([...selectedSeqs], false); exitSelectMode(); }; const bulkFavorite = () => { if (selectedSeqs.size === 0) return; // Same recalled-mid-session race as bulkForward above -- a message favorited with null content // would just be a useless empty entry in 我的收藏 with no way to tell what it used to say. const seqs = [...selectedSeqs].filter((seq) => { const msg = topic.findMessage(seq); return !msg || !isRecalled(msg); }); if (seqs.length) { favoriteMessages(seqs.map((seq) => ({ topic: topicId, seq }))) .then(notifyFavoriteResult) .catch((err) => showError(err, '收藏失败')); } exitSelectMode(); }; const bulkForward = (targetTopics: string[], comment: string) => { // `selectedSeqs` is a Set, which iterates in INSERTION (click) order, not numeric order -- a // user who happened to click message #10 before #3 would otherwise forward them in that click // order, landing #10 ahead of #3 in the target conversation and misrepresenting which one was // actually said first. const orderedSeqs = [...selectedSeqs].sort((a, b) => a - b); for (const targetTopic of targetTopics) { // A target that isn't the conversation currently open (i.e. almost any real forward target) // is not actually subscribed, and publishing on an unsubscribed topic is rejected outright by // the SDK -- see ensureTopicAttached's own comment for why this is the common case, not an // edge case. ensureTopicAttached(targetTopic) .then((target) => { for (const seq of orderedSeqs) { const msg = topic.findMessage(seq); // A message can be recalled by its sender AFTER it was already selected (the checkbox // itself refuses a NEW selection of a recalled message, but can't retroactively un-select // one recalled mid-session) -- forwarding null content would silently send an empty bubble // with a misleading "forwarded from" tag rather than the message the user actually picked. if (msg && !isRecalled(msg)) forwardMessage(topicId, msg, target).catch((err) => showError(err, '转发失败')); } if (comment) sendText(target, comment).catch((err) => showError(err, '附言发送失败')); }) .catch((err) => showError(err, '转发失败')); } setBulkForwardOpen(false); exitSelectMode(); }; const handleAction = (action: MessageAction) => { const msg = menu?.msg; setMenu(null); if (!msg || typeof msg.seq !== 'number') return; switch (action) { case 'copy': navigator.clipboard.writeText(Drafty.toPlainText(msg.content ?? '')).catch(() => {}); break; case 'recall': recallMessage(topicId, msg.seq) .then(() => topic.delMessagesList([msg.seq], true)) .catch((err) => showError(err, '撤回失败')); break; case 'delete': topic.delMessagesList([msg.seq], false); break; case 'select': setSelectMode(true); setSelectedSeqs(new Set([msg.seq])); break; case 'quote': setReplyTo(msg); break; case 'favorite': favoriteMessages([{ topic: topicId, seq: msg.seq }]) .then(notifyFavoriteResult) .catch((err) => showError(err, '收藏失败')); break; case 'forward': setForwardMsg(msg); break; } }; const handlePickImage = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; e.target.value = ''; if (file) sendImage(topic, file).catch((err) => showError(err, '图片发送失败')); }; const handlePickFile = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; e.target.value = ''; if (file) sendFile(topic, file).catch((err) => showError(err, '文件发送失败')); }; return (
{selectMode ? ( <> 已选择 {selectedSeqs.size} 条消息 ) : ( <>
{isGroup ? null : ( <> )}
)}
{isGroup && groupSummaryQuery.data?.announcement?.content ? ( ) : null} {isGroup && isGroupAdmin && !!groupSummaryQuery.data?.pending_join_request_count ? (
{groupSummaryQuery.data.pending_join_request_count} 条新的进群申请
) : null}
{loadingOlder ?
加载中…
: null} {messages.map((msg) => { const sender = isGroup && msg.from ? memberByUserId.get(msg.from) : undefined; return ( setMenu({ x: e.clientX, y: e.clientY, msg: m })} onError={setErrorToast} /> ); })}
{selectMode ? (
) : (
{replyTo ? (
回复 {quotedSenderLabel(replyTo.from)}:{renderDrafty(replyTo.content)}
) : null}
{emojiOpen ? (
{ // Same restore-focus-and-caret dance as insertMentionTrigger/pickMention above // -- clicking the emoji button moves DOM focus to it like any button click, // and without this the textarea stays unfocused until the user clicks back // into it (confirmed by a user report: Enter didn't send right after picking // an emoji because the textarea itself had lost focus). Inserts at the actual // caret position rather than always appending to the end, matching how a // mention insertion already behaves, so the two don't disagree about where // "here" is. setTimeout(0), not requestAnimationFrame -- see insertMentionTrigger's // own comment for why (rAF never fires at all while the tab is hidden). const el = textareaRef.current; const pos = el?.selectionStart ?? draft.length; const next = draft.slice(0, pos) + emoji + draft.slice(pos); setDraft(next); setEmojiOpen(false); setTimeout(() => { el?.focus(); el?.setSelectionRange(pos + emoji.length, pos + emoji.length); }, 0); }} />
) : null}
{isGroup ? ( ) : null} {mentionTrigger && isGroup ? (
) : null}
{recording ? ( setRecording(false)} onSend={(blob, durationMs) => { setRecording(false); sendVoice(topic, blob, durationMs).catch((err) => showError(err, '语音发送失败')); }} /> ) : ( <> {/* textarea + send button must share one flex row (design: 02-messages.dc.html's `display:flex; align-items:flex-end; gap:12px`) -- they were previously two block-level siblings with no shared flex parent (the actual parent only had `flex-none`, a flex-CHILD property that does nothing to make ITSELF a flex container), so the button fell to its own line below the textarea instead of sitting beside it. */}