Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
57.1 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import Accessibility from '@app/features/accessibility/state/Accessibility';
import {ConfirmModal} from '@app/features/app/components/dialogs/ConfirmModal';
import {reportSkeletonComposerLayout} from '@app/features/app/components/skeleton/SkeletonLayoutMemory';
import {useContextMenuHoverState} from '@app/features/app/hooks/useContextMenuHoverState';
import {useSkeletonLayoutReport} from '@app/features/app/hooks/useSkeletonLayoutMemoryCapture';
import RuntimeConfig from '@app/features/app/state/RuntimeConfig';
import {Limits} from '@app/features/app/utils/UserLimits';
import {fetchSlowmodeState} from '@app/features/channel/commands/ChannelCommands';
import {ChannelAttachmentArea} from '@app/features/channel/components/ChannelAttachmentArea';
import {
	type ChannelComposerDismissalRequest,
	requestChannelComposerAffordanceDismissal,
} from '@app/features/channel/components/ChannelComposerDismissal';
import {EditBar} from '@app/features/channel/components/ChannelEditBar';
import {ReplyBar} from '@app/features/channel/components/ChannelReplyBar';
import {ChannelStickersArea} from '@app/features/channel/components/ChannelStickersArea';
import {
	CHANNEL_DESCRIPTOR,
	MESSAGE_CHANNEL_DESCRIPTOR,
	MESSAGE_GROUP_DESCRIPTOR,
	MESSAGE_USER_DESCRIPTOR,
	OPEN_MENU_DESCRIPTOR,
	YOU_DO_NOT_HAVE_PERMISSION_TO_SEND_MESSAGES_DESCRIPTOR,
} from '@app/features/channel/components/channel_textarea/shared';
import lexicalStyles from '@app/features/channel/components/LexicalChannelTextareaContent.module.css';
import {
	getMentionDescription,
	getMentionTitle,
	MentionEveryonePopout,
} from '@app/features/channel/components/MentionEveryonePopout';
import {MessageCharacterCounter} from '@app/features/channel/components/MessageCharacterCounter';
import {SlashCommandParamBar} from '@app/features/channel/components/SlashCommandParamBar';
import {SlowmodeIndicator} from '@app/features/channel/components/SlowmodeIndicator';
import {TypingAnnouncer, TypingUsers, usePresentableTypingUsers} from '@app/features/channel/components/TypingUsers';
import wrapperStyles from '@app/features/channel/components/textarea/InputWrapper.module.css';
import {MobileTextareaPlusBottomSheet} from '@app/features/channel/components/textarea/MobileTextareaPlusBottomSheet';
import {TextareaButton} from '@app/features/channel/components/textarea/TextareaButton';
import {TextareaButtons} from '@app/features/channel/components/textarea/TextareaButtons';
import styles from '@app/features/channel/components/textarea/TextareaInput.module.css';
import {TextareaPlusMenu} from '@app/features/channel/components/textarea/TextareaPlusMenu';
import {useChannelComposerDraftFocusRestore} from '@app/features/channel/components/useChannelComposerDraftFocusRestore';
import {useChannelComposerGlobalShortcuts} from '@app/features/channel/components/useChannelComposerGlobalShortcuts';
import {useChannelComposerPaste} from '@app/features/channel/components/useChannelComposerPaste';
import {useComposerShowAllButtons} from '@app/features/channel/hooks/useComposerShowAllButtons';
import type {Channel} from '@app/features/channel/models/Channel';
import ChannelSearch from '@app/features/channel/state/ChannelSearch';
import ChannelSticker from '@app/features/channel/state/ChannelSticker';
import Channels from '@app/features/channel/state/Channels';
import * as ChannelDisplayUtils from '@app/features/channel/utils/ChannelUtils';
import ExpressionPicker from '@app/features/emoji/state/ExpressionPicker';
import type {FlatEmoji} from '@app/features/emoji/types/EmojiTypes';
import {ExpressionPickerSheet} from '@app/features/expressions/components/modals/ExpressionPickerSheet';
import GuildGuilds from '@app/features/guild/state/Guilds';
import {CANCEL_DESCRIPTOR, CONTINUE_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';
import type {ComposerHandle} from '@app/features/lexical/composer/ComposerHandle';
import {insertComposerEmoji} from '@app/features/lexical/composer/ComposerInsertion';
import {LexicalComposerInput} from '@app/features/lexical/composer/LexicalComposerInput';
import {
	LexicalMessageCommandResolutionStatus,
	LexicalMessageCommandResolver,
} from '@app/features/lexical/composer/LexicalMessageCommand';
import type {SlashCommandComposerState} from '@app/features/lexical/composer/slashSlots';
import type {SlashSlotResolvers} from '@app/features/lexical/composer/slashSlotValidation';
import {type TriggerType, useLexicalAutocomplete} from '@app/features/lexical/composer/useLexicalAutocomplete';
import * as DraftCommands from '@app/features/messaging/commands/DraftCommands';
import * as MessageCommands from '@app/features/messaging/commands/MessageCommands';
import {showAttachmentPermissionDeniedModal} from '@app/features/messaging/components/alerts/AttachmentPermissionDeniedModal';
import {FileSizeTooLargeModal} from '@app/features/messaging/components/alerts/FileSizeTooLargeModal';
import {TooManyAttachmentsModal} from '@app/features/messaging/components/alerts/TooManyAttachmentsModal';
import {useTextareaAttachments} from '@app/features/messaging/hooks/useCloudUpload';
import {useMarkdownKeybinds} from '@app/features/messaging/hooks/useMarkdownKeybinds';
import {type SendMessageFunction, useMessageSubmission} from '@app/features/messaging/hooks/useMessageSubmission';
import {useTextareaDraftAndTyping} from '@app/features/messaging/hooks/useTextareaDraftAndTyping';
import {useTextareaEditing} from '@app/features/messaging/hooks/useTextareaEditing';
import {useTextareaExpressionHandlers} from '@app/features/messaging/hooks/useTextareaExpressionHandlers';
import {useTextareaExpressionPicker} from '@app/features/messaging/hooks/useTextareaExpressionPicker';
import {useTextareaSegments} from '@app/features/messaging/hooks/useTextareaSegments';
import {shouldBlockSubmissionForSlowmode, useTextareaSubmit} from '@app/features/messaging/hooks/useTextareaSubmit';
import {
	createMentionConfirmationSnapshot,
	type MentionConfirmationEvent,
	type MentionConfirmationInfo,
	selectMentionConfirmationModel,
	transitionMentionConfirmationSnapshot,
} from '@app/features/messaging/state/MentionConfirmationStateMachine';
import MessageEdit from '@app/features/messaging/state/MessageEdit';
import MessageEditMobile from '@app/features/messaging/state/MessageEditMobile';
import MessageReply from '@app/features/messaging/state/MessageReply';
import Messages from '@app/features/messaging/state/MessagingMessages';
import {CloudUpload} from '@app/features/messaging/upload/CloudUpload';
import {canAttachFilesInChannel} from '@app/features/messaging/utils/AttachmentPermissionUtils';
import {openFilePicker} from '@app/features/messaging/utils/FilePickerUtils';
import * as FileUploadUtils from '@app/features/messaging/utils/FileUploadUtils';
import {
	canSubmitComposerContent,
	getComposerMessageContent,
	hasVisibleMessageContent,
} from '@app/features/messaging/utils/MessageRequestUtils';
import * as ReplaceCommandUtils from '@app/features/messaging/utils/ReplaceCommandUtils';
import type {MentionSegment} from '@app/features/messaging/utils/TextareaSegmentManager';
import {
	resolveTypedEmojiShortcodes,
	resolveTypedEmojiToken,
} from '@app/features/messaging/utils/TypedEmojiShortcodeUtils';
import {ComponentBus} from '@app/features/platform/utils/ComponentBus';
import {useSlowmode} from '@app/features/slowmode/hooks/useSlowmode';
import {openCreateThread} from '@app/features/threads/commands/ThreadNavigation';
import ActiveComposer from '@app/features/threads/state/ActiveComposer';
import {canStartThreadIn} from '@app/features/threads/utils/ThreadActionRules';
import * as ContextMenuCommands from '@app/features/ui/commands/ContextMenuCommands';
import * as ModalCommands from '@app/features/ui/commands/ModalCommands';
import {modal} from '@app/features/ui/commands/ModalCommands';
import * as PopoutCommands from '@app/features/ui/commands/PopoutCommands';
import {SlashCommandIcon} from '@app/features/ui/components/icons/SlashCommandIcon';
import {openPopout} from '@app/features/ui/popover/PopoverPopout';
import ContextMenuState from '@app/features/ui/state/ContextMenu';
import KeyboardMode from '@app/features/ui/state/KeyboardMode';
import MobileLayout from '@app/features/ui/state/MobileLayout';
import Users from '@app/features/user/state/Users';
import {openVoiceMessageComposerModal} from '@app/features/voice/components/VoiceMessageComposerModal';
import {flxElementClassName} from '@app/lib/react';
import {msg} from '@lingui/core/macro';
import {useLingui} from '@lingui/react/macro';
import {PlusIcon} from '@phosphor-icons/react';
import {observer} from 'mobx-react-lite';
import type React from 'react';
import {useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState} from 'react';

const PLUS_MENU_DOUBLE_CLICK_MS = 500;
const MESSAGE_SCROLLER_SELECTOR = '[data-flx="channel.messages.scroller"][data-fluxer-scroll-container="true"]';
const MESSAGE_SCROLLER_BOTTOM_THRESHOLD = 16;
const getActiveMessageScroller = (): HTMLElement | null =>
	document.querySelector<HTMLElement>(MESSAGE_SCROLLER_SELECTOR);
const isMessageScrollerNearBottom = (scrollerElement: HTMLElement): boolean =>
	scrollerElement.scrollHeight <=
	scrollerElement.scrollTop + scrollerElement.clientHeight + MESSAGE_SCROLLER_BOTTOM_THRESHOLD;
const CLEAR_COMMAND_DESCRIPTOR = msg({
	message: 'Clear command',
	comment: 'Accessible label for the composer button that clears the slash command currently being composed.',
});

const PLUS_ICON_PROPS = {weight: 'bold'} as const;

export interface ChannelTextareaControls {
	submit: () => void;
	insertEmoji: (emoji: FlatEmoji) => void;
	uploadFiles: () => void;
	focus: () => void;
}
const NON_COMMAND_TRIGGERS: Array<TriggerType> = ['mention', 'channel', 'emoji', 'meme', 'gif', 'sticker'];

export const LexicalChannelTextareaContent = observer(
	({
		accountKey,
		channel,
		draft,
		draftSegments,
		disabled,
		inputSuppressed = false,
		typingEnabled = true,
		onSubmit: onSubmitOverride,
		enableReply = true,
		enableEditLast = true,
		enableSlashCommands = true,
		submitOnEnter = true,
		draftChannelId,
		placeholder,
		bare = false,
		controlsRef,
		onValueChange,
	}: {
		accountKey: string | null;
		channel: Channel;
		draft: string | null;
		draftSegments: ReadonlyArray<MentionSegment>;
		disabled: boolean;
		inputSuppressed?: boolean;
		typingEnabled?: boolean;
		onSubmit?: SendMessageFunction;
		enableReply?: boolean;
		enableEditLast?: boolean;
		enableSlashCommands?: boolean;
		submitOnEnter?: boolean;
		draftChannelId?: string;
		placeholder?: string;
		bare?: boolean;
		controlsRef?: React.MutableRefObject<ChannelTextareaControls | null>;
		onValueChange?: (value: string) => void;
	}) => {
		const {i18n} = useLingui();
		const composerKey = draftChannelId ?? channel.id;
		const ownsChannelEdits = draftChannelId == null;
		const editingMessageId = ownsChannelEdits ? MessageEdit.getEditingMessageId(channel.id) : null;
		const editingMobileMessageId = ownsChannelEdits ? MessageEditMobile.getEditingMobileMessageId(channel.id) : null;
		const isEditingMessageInComposer = editingMobileMessageId != null;
		let initialDraftDisplay = '';
		if (!disabled && !isEditingMessageInComposer && draft !== null) {
			initialDraftDisplay = draft;
		}
		const [isFocused, setIsFocused] = useState(false);
		const [isInputAreaFocused, setIsInputAreaFocused] = useState(false);
		const initialDraftRef = useRef({
			display: initialDraftDisplay,
			segments: initialDraftDisplay.length === 0 ? [] : draftSegments.map((segment) => ({...segment})),
		});
		const [value, setValue] = useState(() => initialDraftRef.current.display);
		const [slashCommandState, setSlashCommandState] = useState<SlashCommandComposerState>({
			hasSlots: false,
			activeSlot: null,
		});
		const [mentionConfirmationSnapshot, setMentionConfirmationSnapshot] = useState(createMentionConfirmationSnapshot);
		const mentionConfirmationModel = selectMentionConfirmationModel(mentionConfirmationSnapshot);
		const pendingMentionConfirmation = mentionConfirmationModel.pending;
		const mentionPopoutKey = useMemo(() => `mention-everyone-${channel.id}`, [channel.id]);
		const mentionModalKey = useMemo(() => `mention-everyone-modal-${channel.id}`, [channel.id]);
		const [mobilePlusSheetOpen, setMobilePlusSheetOpen] = useState(false);
		const autocompleteListId = useId();
		const handleRef = useRef<ComposerHandle | null>(null);
		const editorDisplayRef = useRef(initialDraftRef.current.display);
		const editableRef = useRef<HTMLDivElement | null>(null);
		const expressionPickerTriggerRef = useRef<HTMLButtonElement>(null);
		const invisibleExpressionPickerTriggerRef = useRef<HTMLDivElement>(null);
		const containerRef = useRef<HTMLDivElement>(null);
		const showAllButtons = useComposerShowAllButtons(containerRef, MobileLayout.enabled);
		const typingStatusRailLeftRef = useRef<HTMLElement>(null);
		const contentAreaRef = useRef<HTMLElement | null>(null);
		const plusButtonRef = useRef<HTMLButtonElement | null>(null);
		const plusMenuOpenedAtRef = useRef(0);
		const plusBackdropPressHandledAtRef = useRef(0);
		const plusPressRef = useRef<{wasOpen: boolean; openedAt: number}>({wasOpen: false, openedAt: 0});
		const textareaInputDisabled = disabled || inputSuppressed;
		useMarkdownKeybinds(isFocused && !textareaInputDisabled, {preserveEditableFocusActions: true});
		const plusContextMenuOpen = useContextMenuHoverState(plusButtonRef);
		useEffect(() => {
			editableRef.current = containerRef.current
				? containerRef.current.querySelector<HTMLDivElement>('[data-channel-textarea]')
				: null;
		}, []);
		useChannelComposerDraftFocusRestore({
			handleRef,
			editableRef,
			initialDraft: initialDraftRef.current.display,
			textareaInputDisabled,
			inlineEditActive: editingMessageId != null,
		});
		useEffect(() => {
			const contentArea = contentAreaRef.current;
			if (contentArea == null) {
				return;
			}
			const handleContentMouseDown = (event: MouseEvent): void => {
				const editable = contentArea.querySelector<HTMLElement>('[data-channel-textarea]');
				const target = event.target;
				const defaultView = contentArea.ownerDocument.defaultView;
				if (editable == null || defaultView == null || !(target instanceof defaultView.Node)) {
					return;
				}
				if (target === editable || editable.contains(target)) {
					return;
				}
				event.preventDefault();
				const handle = handleRef.current;
				if (handle != null) {
					handle.focus();
				}
			};
			contentArea.addEventListener('mousedown', handleContentMouseDown);
			return () => contentArea.removeEventListener('mousedown', handleContentMouseDown);
		}, []);
		useEffect(() => {
			if (!inputSuppressed) return;
			if (editableRef.current && document.activeElement === editableRef.current) {
				editableRef.current.blur();
			}
			setIsFocused(false);
			setIsInputAreaFocused(false);
		}, [inputSuppressed]);
		const showGifButton = Accessibility.showGifButton && RuntimeConfig.gifEnabled;
		const showMemesButton = Accessibility.showMemesButton;
		const showStickersButton = Accessibility.showStickersButton;
		const showEmojiButton = Accessibility.showEmojiButton;
		const showMessageSendButton = Accessibility.showMessageSendButton;
		const desktopComposerActionCount = [
			showAllButtons && showGifButton,
			showAllButtons && showMemesButton,
			showAllButtons && showStickersButton,
			showEmojiButton,
			showMessageSendButton,
		].filter(Boolean).length;
		let mobileComposerActionCount = 1;
		if (showEmojiButton) {
			mobileComposerActionCount += 1;
		}
		useSkeletonLayoutReport(
			() =>
				reportSkeletonComposerLayout({
					desktopActionCount: desktopComposerActionCount,
					mobileActionCount: mobileComposerActionCount,
					sendDividerVisible: showMessageSendButton,
				}),
			`${desktopComposerActionCount}|${mobileComposerActionCount}|${showMessageSendButton}`,
		);
		const mobileLayout = MobileLayout;
		const replyingMessage = enableReply ? MessageReply.getReplyingMessage(channel.id) : null;
		const referencedMessage = enableReply ? MessageReply.getReferencedMessage(channel.id) : null;
		const editingMessage = editingMobileMessageId ? Messages.getMessage(channel.id, editingMobileMessageId) : null;
		const editingMessageForComposer = editingMessage === undefined ? null : editingMessage;
		const isEditingMessageOnMobile = editingMessageForComposer !== null && mobileLayout.enabled;
		const maxMessageLength = Limits.getMaxMessageLength();
		const premiumMaxLength = Limits.getStockValue('max_message_length', maxMessageLength);
		const maxAttachments = Limits.getMaxAttachmentsPerMessage();
		const uploadAttachments = useTextareaAttachments(composerKey);
		const {isSlowmodeActive, slowmodeRemaining, isSlowmodeEnabled, isSlowmodeImmune} = useSlowmode(channel);
		const rateLimitPerUser = channel.rateLimitPerUser === undefined ? 0 : channel.rateLimitPerUser;
		const shouldFetchSlowmode = Boolean(channel.guildId) && rateLimitPerUser > 0;
		useEffect(() => {
			if (!shouldFetchSlowmode) return;
			void fetchSlowmodeState(channel.id);
		}, [channel.id, shouldFetchSlowmode]);
		const {segmentManagerRef, previousValueRef, displayToActual, clearSegments} = useTextareaSegments();
		const segmentsSeededRef = useRef(false);
		if (!segmentsSeededRef.current) {
			segmentsSeededRef.current = true;
			segmentManagerRef.current.setSegments(initialDraftRef.current.segments.map((segment) => ({...segment})));
			previousValueRef.current = initialDraftRef.current.display;
		}
		const [wireValue, setWireValue] = useState(() =>
			segmentManagerRef.current.displayToActual(initialDraftRef.current.display),
		);
		const handleEditorChange = useCallback(
			(display: string, segments: Array<MentionSegment>, wire: string) => {
				editorDisplayRef.current = display;
				segmentManagerRef.current.setSegments(segments);
				previousValueRef.current = display;
				setValue(display);
				setWireValue(wire);
			},
			[previousValueRef, segmentManagerRef],
		);
		useLayoutEffect(() => {
			if (value === editorDisplayRef.current) {
				return;
			}
			editorDisplayRef.current = value;
			const handle = handleRef.current;
			if (handle !== null) {
				handle.hydrate(value, segmentManagerRef.current.getSegmentsCopy());
			}
		}, [value, segmentManagerRef]);
		const handleEmojiSelect = useCallback(
			(emoji: FlatEmoji, shiftKey?: boolean): boolean => {
				const didInsert = insertComposerEmoji(handleRef.current, emoji, {reactionShorthand: true});
				if (didInsert && !shiftKey) {
					ExpressionPicker.close();
					PopoutCommands.close(`expression-picker-${channel.id}`);
				}
				return didInsert;
			},
			[channel.id],
		);
		const {sendMessage, sendOptimisticMessage} = useMessageSubmission({
			accountKey,
			channel,
			referencedMessage,
			replyingMessage,
			clearSegments,
		});
		const handleSendMessage: SendMessageFunction = useCallback(
			(...args) => {
				if (!(onSubmitOverride ?? sendMessage)(...args)) {
					return false;
				}
				const handle = handleRef.current;
				if (handle !== null) {
					handle.clear();
				}
				setValue('');
				clearSegments();
				return true;
			},
			[onSubmitOverride, sendMessage, clearSegments, value],
		);
		const sendExpressionMessage: typeof sendOptimisticMessage = useCallback(
			(messageData, sendOptions) => {
				if (!onSubmitOverride) {
					sendOptimisticMessage(messageData, sendOptions);
					return;
				}
				onSubmitOverride(
					messageData.content,
					sendOptions.hasAttachments,
					messageData.stickers ?? [],
					sendOptions.favoriteMemeId,
				);
			},
			[onSubmitOverride, sendOptimisticMessage],
		);
		const sendMentionConfirmationEvent = useCallback((event: MentionConfirmationEvent) => {
			setMentionConfirmationSnapshot((snapshot) => transitionMentionConfirmationSnapshot(snapshot, event));
		}, []);
		const currentMentionConfirmationSourceContent = useMemo(() => wireValue.trim(), [wireValue]);
		const currentMentionConfirmationSourceContentRef = useRef(currentMentionConfirmationSourceContent);
		const pendingMentionConfirmationRef = useRef<MentionConfirmationInfo | null>(pendingMentionConfirmation);
		const handleSendMessageRef = useRef(handleSendMessage);
		currentMentionConfirmationSourceContentRef.current = currentMentionConfirmationSourceContent;
		pendingMentionConfirmationRef.current = pendingMentionConfirmation;
		handleSendMessageRef.current = handleSendMessage;
		useEffect(() => {
			sendMentionConfirmationEvent({type: 'mentionConfirmation.reset'});
		}, [channel.id, sendMentionConfirmationEvent]);
		useEffect(() => {
			sendMentionConfirmationEvent({
				type: 'mentionConfirmation.composerChanged',
				sourceContent: currentMentionConfirmationSourceContent,
			});
		}, [currentMentionConfirmationSourceContent, sendMentionConfirmationEvent]);
		const handleMentionConfirmationNeeded = useCallback(
			(info: MentionConfirmationInfo) => {
				sendMentionConfirmationEvent({
					type: 'mentionConfirmation.requested',
					info,
					currentSourceContent: currentMentionConfirmationSourceContentRef.current,
				});
			},
			[sendMentionConfirmationEvent],
		);
		const handleMentionConfirm = useCallback(() => {
			const pending = pendingMentionConfirmationRef.current;
			if (!pending) {
				return;
			}
			const pendingSticker = ChannelSticker.getPendingSticker(channel.id);
			const stickerItems = pendingSticker ? [pendingSticker.toJSON()] : undefined;
			let didSend = false;
			if (pending.tts) {
				didSend = handleSendMessageRef.current(pending.content, false, true, stickerItems);
			} else if (stickerItems) {
				didSend = handleSendMessageRef.current(pending.content, false, stickerItems);
			} else {
				didSend = handleSendMessageRef.current(pending.content, false);
			}
			if (!didSend) return;
			sendMentionConfirmationEvent({type: 'mentionConfirmation.confirmed'});
			if (pendingSticker) {
				ChannelSticker.removePendingSticker(channel.id);
			}
		}, [channel.id, sendMentionConfirmationEvent]);
		const handleMentionCancel = useCallback(() => {
			sendMentionConfirmationEvent({type: 'mentionConfirmation.dismissed'});
			const handle = handleRef.current;
			if (handle !== null) {
				handle.focus();
			}
		}, [sendMentionConfirmationEvent]);
		useEffect(() => {
			if (!pendingMentionConfirmation) {
				return;
			}
			if (mobileLayout.enabled) {
				const index = pendingMentionConfirmation.mentionType;
				const title = getMentionTitle(i18n, index, pendingMentionConfirmation.roleName);
				const description = getMentionDescription(
					index,
					pendingMentionConfirmation.memberCount,
					pendingMentionConfirmation.roleName,
				);
				ModalCommands.pushWithKey(
					modal(() => (
						<ConfirmModal
							title={title}
							description={description}
							primaryText={i18n._(CONTINUE_DESCRIPTOR)}
							secondaryText={i18n._(CANCEL_DESCRIPTOR)}
							onPrimary={() => {
								handleMentionConfirm();
							}}
							onSecondary={() => {
								handleMentionCancel();
							}}
							data-flx="channel.lexical-channel-textarea-content.confirm-modal"
						/>
					)),
					mentionModalKey,
				);
				return () => {
					ModalCommands.popWithKey(mentionModalKey);
				};
			}
			const containerElement = containerRef.current;
			if (!containerElement) {
				return;
			}
			openPopout(
				containerElement,
				{
					render: ({onClose}) => (
						<MentionEveryonePopout
							mentionType={pendingMentionConfirmation.mentionType}
							memberCount={pendingMentionConfirmation.memberCount}
							roleName={pendingMentionConfirmation.roleName}
							onConfirm={() => {
								handleMentionConfirm();
								onClose();
							}}
							onCancel={() => {
								handleMentionCancel();
								onClose();
							}}
							data-flx="channel.lexical-channel-textarea-content.mention-everyone-popout"
						/>
					),
					position: 'top-start',
					offsetMainAxis: 8,
					shouldAutoUpdate: true,
					returnFocusRef: editableRef,
					onCloseRequest: () => {
						handleMentionCancel();
						return true;
					},
				},
				mentionPopoutKey,
			);
			return () => {
				PopoutCommands.close(mentionPopoutKey);
			};
		}, [
			pendingMentionConfirmation,
			mentionPopoutKey,
			mentionModalKey,
			handleMentionConfirm,
			handleMentionCancel,
			mobileLayout.enabled,
			i18n,
		]);
		const {
			autocompleteQuery,
			autocompleteOptions,
			autocompleteType,
			isAutocompleteAttached,
			isSlotMenu,
			onCursorMove,
			handleSelect,
			specialMentionsAllowed,
		} = useLexicalAutocomplete({
			channel,
			handleRef,
			allowedTriggers: enableSlashCommands ? undefined : NON_COMMAND_TRIGGERS,
			i18n,
		});
		const isAutocompleteVisible = !textareaInputDisabled && isAutocompleteAttached;
		const resolveTypedEmojiContent = useCallback(
			(content: string): string => {
				return resolveTypedEmojiShortcodes({
					content,
					channel,
					i18n,
				});
			},
			[channel, i18n],
		);
		const composerEmojiResolver = useCallback(
			(shortcodeName: string) => {
				let guildId: string | null = null;
				if (channel.guildId !== undefined) {
					guildId = channel.guildId;
				}
				return resolveTypedEmojiToken(shortcodeName, channel, guildId, i18n);
			},
			[channel, i18n],
		);
		const trimmedMessageContent = useMemo(
			() => resolveTypedEmojiContent(wireValue.trim()),
			[resolveTypedEmojiContent, wireValue],
		);
		const composerMessageContent = useMemo(
			() => getComposerMessageContent(trimmedMessageContent, isEditingMessageOnMobile),
			[isEditingMessageOnMobile, trimmedMessageContent],
		);
		const hasMessageContent = useMemo(() => hasVisibleMessageContent(composerMessageContent), [composerMessageContent]);
		const isSubmissionBlockedBySlowmode = useMemo(
			() =>
				shouldBlockSubmissionForSlowmode(
					isSlowmodeActive,
					isEditingMessageInComposer,
					null,
					enableSlashCommands ? LexicalMessageCommandResolver.resolve(handleRef.current) : null,
					enableSlashCommands && ReplaceCommandUtils.isReplaceCommand(wireValue),
				),
			[enableSlashCommands, handleRef, isEditingMessageInComposer, isSlowmodeActive, value, wireValue],
		);
		useChannelComposerPaste({
			channel,
			attachmentKey: composerKey,
			handleRef,
			editableRef,
			isFocused,
			maxMessageLength,
			maxAttachments,
			uploadAttachments,
			textareaInputDisabled,
		});
		const handleOpenMobilePlusSheet = useCallback(() => {
			setMobilePlusSheetOpen(true);
		}, []);
		const handleCloseMobilePlusSheet = useCallback(() => {
			setMobilePlusSheetOpen(false);
		}, []);
		const handleFileButtonClick = useCallback(async () => {
			if (textareaInputDisabled) {
				return;
			}
			const files = await openFilePicker({multiple: true});
			if (files.length === 0) {
				return;
			}
			if (!canAttachFilesInChannel(channel)) {
				showAttachmentPermissionDeniedModal(channel);
				return;
			}
			const result = await FileUploadUtils.handleFileUpload(
				channel.id,
				files,
				uploadAttachments.length,
				maxAttachments,
				composerKey,
			);
			if (!result.success) {
				if (result.error === 'too_many_attachments') {
					ModalCommands.push(
						modal(() => (
							<TooManyAttachmentsModal data-flx="channel.lexical-channel-textarea-content.handle-file-button-click.too-many-attachments-modal" />
						)),
					);
				} else if (result.error === 'file_size_too_large') {
					ModalCommands.push(
						modal(() => (
							<FileSizeTooLargeModal
								oversizedFileCount={result.oversizedFileCount}
								data-flx="channel.lexical-channel-textarea-content.handle-file-button-click.file-size-too-large-modal"
							/>
						)),
					);
				}
				return;
			}
			if (files.length > 0) {
				const handle = handleRef.current;
				if (handle !== null) {
					handle.focus();
				}
			}
		}, [channel, composerKey, textareaInputDisabled, maxAttachments, uploadAttachments.length]);
		const handleUploadMessageAsFile = useCallback(async () => {
			if (textareaInputDisabled) {
				return;
			}
			if (!canAttachFilesInChannel(channel)) {
				showAttachmentPermissionDeniedModal(channel);
				return;
			}
			const result = await FileUploadUtils.convertTextToFile(
				channel.id,
				value,
				uploadAttachments.length,
				maxAttachments,
				composerKey,
			);
			if (!result.success) {
				if (result.error === 'too_many_attachments') {
					ModalCommands.push(
						modal(() => (
							<TooManyAttachmentsModal data-flx="channel.lexical-channel-textarea-content.handle-upload-message-as-file.too-many-attachments-modal" />
						)),
					);
				} else if (result.error === 'file_size_too_large') {
					ModalCommands.push(
						modal(() => (
							<FileSizeTooLargeModal
								oversizedFileCount={result.oversizedFileCount}
								data-flx="channel.lexical-channel-textarea-content.handle-upload-message-as-file.file-size-too-large-modal"
							/>
						)),
					);
				}
				return;
			}
			const handle = handleRef.current;
			if (handle !== null) {
				handle.clear();
			}
			setValue('');
			DraftCommands.deleteDraft(accountKey, composerKey);
			if (handle !== null) {
				handle.focus();
			}
		}, [accountKey, textareaInputDisabled, value, channel, uploadAttachments.length, maxAttachments, composerKey]);
		useTextareaExpressionHandlers({
			setValue,
			previousValueRef,
			segmentManagerRef,
			sendOptimisticMessage: sendExpressionMessage,
			enabled: !textareaInputDisabled,
			channelId: draftChannelId ?? channel.id,
		});
		const {expressionPickerOpen, setExpressionPickerOpen, handleExpressionPickerTabToggle, selectedTab} =
			useTextareaExpressionPicker({
				channelId: channel.id,
				onEmojiSelect: handleEmojiSelect,
				expressionPickerTriggerRef,
				invisibleExpressionPickerTriggerRef,
				textareaRef: editableRef,
				enabled: !textareaInputDisabled,
			});
		useTextareaEditing({
			editingMessage: editingMessageForComposer,
			isMobileEditMode: mobileLayout.enabled,

			setValue,
			previousValueRef,
		});
		const hasPendingSticker = ChannelSticker.getPendingSticker(channel.id) !== null;
		const hasAttachments = uploadAttachments.length > 0;
		const previousComposerBoundaryState = useRef({channelId: channel.id, hasAttachments, hasPendingSticker});
		const wasAtBottomBeforeComposerBoundaryChange = useRef(true);
		useEffect(() => {
			const scrollerElement = getActiveMessageScroller();
			if (!scrollerElement) return undefined;
			const updateWasAtBottom = () => {
				wasAtBottomBeforeComposerBoundaryChange.current = isMessageScrollerNearBottom(scrollerElement);
			};
			updateWasAtBottom();
			scrollerElement.addEventListener('scroll', updateWasAtBottom, {passive: true});
			return () => {
				scrollerElement.removeEventListener('scroll', updateWasAtBottom);
			};
		}, [channel.id]);
		useEffect(() => {
			const previous = previousComposerBoundaryState.current;
			const isSameChannel = previous.channelId === channel.id;
			const attachmentBoundaryChanged = isSameChannel && previous.hasAttachments !== hasAttachments;
			const stickerBoundaryChanged = isSameChannel && previous.hasPendingSticker !== hasPendingSticker;
			if (
				wasAtBottomBeforeComposerBoundaryChange.current &&
				(stickerBoundaryChanged || attachmentBoundaryChanged) &&
				Messages.getMessages(channel.id).hasMoreAfter
			) {
				ComponentBus.dispatch('FORCE_JUMP_TO_PRESENT', {channelId: channel.id});
			}
			previousComposerBoundaryState.current = {channelId: channel.id, hasAttachments, hasPendingSticker};
			const scrollerElement = getActiveMessageScroller();
			if (scrollerElement) {
				wasAtBottomBeforeComposerBoundaryChange.current = isMessageScrollerNearBottom(scrollerElement);
			}
		}, [channel.id, hasAttachments, hasPendingSticker]);
		const showAttachments = hasAttachments;
		const showStickers = hasPendingSticker;
		const isOverCharacterLimit = composerMessageContent.length > maxMessageLength;
		const canSubmit = canSubmitComposerContent({
			inputDisabled: textareaInputDisabled,
			isSubmissionBlockedBySlowmode,
			isOverCharacterLimit,
			hasMessageContent,
			hasAttachments,
			hasPendingSticker,
			isEditingMessageOnMobile,
		});
		const {onSubmit} = useTextareaSubmit({
			draftOwner: accountKey,
			channelId: channel.id,
			guildId: channel.guildId === undefined ? null : channel.guildId,
			editingMessage: editingMessageForComposer,
			isMobileEditMode: mobileLayout.enabled,
			uploadAttachmentsLength: uploadAttachments.length,
			hasPendingSticker,
			value,
			setValue,
			displayToActual,
			composerHandleRef: handleRef,
			clearSegments,
			isSlowmodeActive,
			handleSendMessage,
			onMentionConfirmationNeeded: handleMentionConfirmationNeeded,
			commandsEnabled: enableSlashCommands,
			i18n: i18n,
		});
		const handleClearSlashCommand = useCallback(() => {
			const handle = handleRef.current;
			if (handle !== null) {
				handle.clear();
			}
			setValue('');
			clearSegments();
			DraftCommands.deleteDraft(accountKey, draftChannelId ?? channel.id);
			if (handle !== null) {
				handle.focus();
			}
		}, [accountKey, channel.id, clearSegments, draftChannelId]);
		const handleCancelEdit = useCallback(() => {
			setValue('');
			clearSegments();
		}, [clearSegments]);
		const focusComposer = useCallback(() => {
			const handle = handleRef.current;
			if (handle !== null) {
				handle.focus();
			}
		}, []);
		const dismissTopmostComposerAffordance = useCallback((): boolean => {
			if (editingMessageId !== null) {
				MessageCommands.stopEdit(channel.id);
				return true;
			}
			if (hasPendingSticker) {
				ChannelSticker.removePendingSticker(channel.id);
				focusComposer();
				return true;
			}
			if (hasAttachments) {
				CloudUpload.clearTextarea(composerKey);
				focusComposer();
				return true;
			}
			const slashCommandResolution = LexicalMessageCommandResolver.resolve(handleRef.current);
			if (slashCommandResolution.status !== LexicalMessageCommandResolutionStatus.NO_COMMAND) {
				handleClearSlashCommand();
				return true;
			}
			if (editingMessageForComposer !== null && mobileLayout.enabled) {
				MessageCommands.stopEditMobile(channel.id);
				handleCancelEdit();
				focusComposer();
				return true;
			}
			if (replyingMessage !== null) {
				MessageCommands.stopReply(channel.id);
				focusComposer();
				return true;
			}
			return false;
		}, [
			channel.id,
			composerKey,
			editingMessageForComposer,
			editingMessageId,
			focusComposer,
			handleCancelEdit,
			handleClearSlashCommand,
			hasAttachments,
			hasPendingSticker,
			mobileLayout.enabled,
			replyingMessage,
		]);
		useEffect(() => {
			return ComponentBus.subscribe('TEXTAREA_DISMISS_AFFORDANCE', (request?: unknown) => {
				const dismissalRequest = request as ChannelComposerDismissalRequest | undefined;
				if (dismissalRequest?.channelId !== channel.id) {
					return false;
				}
				return dismissTopmostComposerAffordance();
			});
		}, [channel.id, dismissTopmostComposerAffordance]);
		const handleEscapeKey = useCallback(
			(event: React.KeyboardEvent<HTMLElement>) => {
				if (event.defaultPrevented || event.nativeEvent.isComposing) return;
				if (event.key !== 'Escape' || event.shiftKey) return;
				if (requestChannelComposerAffordanceDismissal(channel.id)) {
					event.preventDefault();
					event.stopPropagation();
					return;
				}
				if (isInputAreaFocused && KeyboardMode.keyboardModeEnabled) {
					event.preventDefault();
					KeyboardMode.exitKeyboardMode();
					return;
				}
				if (Accessibility.escapeExitsKeyboardMode) {
					KeyboardMode.exitKeyboardMode();
				}
			},
			[channel.id, isInputAreaFocused, KeyboardMode.keyboardModeEnabled, Accessibility.escapeExitsKeyboardMode],
		);
		const slotResolvers = useMemo<SlashSlotResolvers>(() => {
			const guildId = channel.guildId;
			return {
				resolveUser: (query) => {
					const user = Users.getUserByTag(query);
					return user ? {id: user.id} : null;
				},
				resolveChannel: (query) => {
					if (!guildId) {
						return null;
					}
					const found = Channels.getGuildChannels(guildId).find((candidate) => {
						const name = candidate.name === undefined ? '' : candidate.name;
						return name.toLowerCase() === query.toLowerCase();
					});
					return found ? {id: found.id} : null;
				},
				resolveRole: (query) => {
					if (!guildId) {
						return null;
					}
					const found = GuildGuilds.getGuildRoles(guildId).find(
						(role) => role.name.toLowerCase() === query.toLowerCase(),
					);
					return found ? {id: found.id} : null;
				},
			};
		}, [channel.guildId]);
		const handleEditorKeyDown = useCallback(
			(event: React.KeyboardEvent<HTMLElement>) => {
				handleEscapeKey(event);
			},
			[handleEscapeKey],
		);
		const handleSubmit = useCallback(() => {
			if (!canSubmit) {
				return;
			}
			if (hasAttachments && !canAttachFilesInChannel(channel)) {
				showAttachmentPermissionDeniedModal(channel);
				return;
			}
			onSubmit();
		}, [canSubmit, channel, hasAttachments, onSubmit]);
		useEffect(() => {
			if (!controlsRef) return;
			controlsRef.current = {
				submit: handleSubmit,
				insertEmoji: (emoji) => {
					insertComposerEmoji(handleRef.current, emoji, {reactionShorthand: true});
				},
				uploadFiles: () => {
					void handleFileButtonClick();
				},
				focus: () => handleRef.current?.focus(),
			};
			return () => {
				controlsRef.current = null;
			};
		}, [controlsRef, handleSubmit, handleFileButtonClick]);
		useEffect(() => {
			onValueChange?.(value);
		}, [onValueChange, value]);
		const handleArrowUpEmpty = useCallback(() => {
			if (KeyboardMode.keyboardModeEnabled) {
				ComponentBus.dispatch('FOCUS_BOTTOMMOST_MESSAGE', {channelId: channel.id});
				return true;
			}
			if (!enableEditLast) {
				return false;
			}
			const message = Messages.getLastEditableMessage(channel.id);
			if (!message) {
				return false;
			}
			MessageCommands.startEdit(channel.id, message.id, message.content);
			return true;
		}, [channel.id, enableEditLast]);
		useTextareaDraftAndTyping({
			draftOwner: accountKey,
			channelId: draftChannelId ?? channel.id,
			value,
			setValue,
			draft,
			draftSegments,
			previousValueRef,
			segmentManagerRef,
			enabled: !disabled,
			typingEnabled: typingEnabled && !textareaInputDisabled,
			isEditingMessageInComposer,
		});
		useChannelComposerGlobalShortcuts({
			channel,
			handleRef,
			editableRef,
			textareaInputDisabled,
			isFocused,
			handleArrowUpEmpty,
		});
		let placeholderText: string;
		if (placeholder) {
			placeholderText = placeholder;
		} else if (disabled) {
			placeholderText = i18n._(YOU_DO_NOT_HAVE_PERMISSION_TO_SEND_MESSAGES_DESCRIPTOR);
		} else if (channel.guildId != null) {
			placeholderText = i18n._(MESSAGE_CHANNEL_DESCRIPTOR, {channelName: channel.name || i18n._(CHANNEL_DESCRIPTOR)});
		} else if (channel.isDM()) {
			placeholderText = i18n._(MESSAGE_USER_DESCRIPTOR, {userName: ChannelDisplayUtils.getDMDisplayName(channel)});
		} else {
			placeholderText = i18n._(MESSAGE_GROUP_DESCRIPTOR, {groupName: ChannelDisplayUtils.getDMDisplayName(channel)});
		}
		useEffect(() => ActiveComposer.register(draftChannelId ?? channel.id), [channel.id, draftChannelId]);
		useEffect(() => {
			const unsubscribe = ComponentBus.subscribe('FOCUS_TEXTAREA', (payload?: unknown) => {
				const payloadValue = payload === null || payload === undefined ? {} : payload;
				const {channelId, enterKeyboardMode} = payloadValue as {
					channelId?: string;
					enterKeyboardMode?: boolean;
				};
				if (channelId ? channelId !== composerKey : !ActiveComposer.accepts(composerKey)) return;
				if (textareaInputDisabled) return false;
				if (editingMessageId && !mobileLayout.enabled) return false;
				if (enterKeyboardMode) {
					KeyboardMode.enterKeyboardMode(true);
				} else {
					KeyboardMode.exitKeyboardMode();
				}
				const handle = handleRef.current;
				if (handle !== null) {
					handle.focus();
				}
				return true;
			});
			return unsubscribe;
		}, [composerKey, editingMessageId, textareaInputDisabled, mobileLayout.enabled]);
		const wasEditingInlineRef = useRef(false);
		useEffect(() => {
			const isEditingInline = editingMessageId != null && !mobileLayout.enabled;
			if (wasEditingInlineRef.current && !isEditingInline && !textareaInputDisabled) {
				const handle = handleRef.current;
				if (handle !== null) {
					handle.focus();
				}
			}
			wasEditingInlineRef.current = isEditingInline;
		}, [editingMessageId, mobileLayout.enabled, textareaInputDisabled]);
		useEffect(() => {
			if (textareaInputDisabled) return;
			const unsubscribe = ComponentBus.subscribe('TEXTAREA_UPLOAD_FILE', (payload?: unknown) => {
				const payloadValue = payload === null || payload === undefined ? {} : payload;
				const {channelId} = payloadValue as {channelId?: string};
				if (channelId ? channelId !== composerKey : !ActiveComposer.accepts(composerKey)) return;
				handleFileButtonClick();
			});
			return unsubscribe;
		}, [composerKey, textareaInputDisabled, handleFileButtonClick]);
		useEffect(() => {
			const unsubscribe = ComponentBus.subscribe('TEXTAREA_SEND_VOICE_MESSAGE', (payload?: unknown) => {
				const payloadValue = payload === null || payload === undefined ? {} : payload;
				const {channelId} = payloadValue as {channelId?: string};
				if (channelId ? channelId !== composerKey : !ActiveComposer.accepts(composerKey)) return undefined;
				if (mobileLayout.enabled || textareaInputDisabled || draftChannelId != null) return false;
				openVoiceMessageComposerModal(channel.id);
				return true;
			});
			return unsubscribe;
		}, [channel.id, composerKey, draftChannelId, textareaInputDisabled, mobileLayout.enabled]);
		const isPlusContextMenuOpen = useCallback(() => {
			const plusButton = plusButtonRef.current;
			const contextMenu = ContextMenuState.contextMenu;
			return Boolean(
				plusButton !== null &&
					contextMenu !== null &&
					contextMenu !== undefined &&
					contextMenu.target.target === plusButton,
			);
		}, []);
		const isFastPlusMenuRepeatPress = useCallback((timeStamp: number, openedAt = plusMenuOpenedAtRef.current) => {
			if (openedAt <= 0) return false;
			const elapsed = timeStamp - openedAt;
			return elapsed >= 0 && elapsed <= PLUS_MENU_DOUBLE_CLICK_MS;
		}, []);
		const handlePlusMenuClosed = useCallback(() => {
			plusMenuOpenedAtRef.current = 0;
		}, []);
		const closePlusMenuFromRepeatPress = useCallback(
			(timeStamp: number, openedAt = plusMenuOpenedAtRef.current) => {
				ContextMenuCommands.close();
				if (isFastPlusMenuRepeatPress(timeStamp, openedAt)) {
					void handleFileButtonClick();
				}
			},
			[handleFileButtonClick, isFastPlusMenuRepeatPress],
		);
		const handlePlusMenuBackdropMouseDown = useCallback(
			(event: React.MouseEvent<HTMLElement>) => {
				if (textareaInputDisabled) {
					return false;
				}
				const plusButton = plusButtonRef.current;
				if (!plusButton) {
					return false;
				}
				const rect = plusButton.getBoundingClientRect();
				const isOnPlusButton =
					event.clientX >= rect.left &&
					event.clientX <= rect.right &&
					event.clientY >= rect.top &&
					event.clientY <= rect.bottom;
				if (!isOnPlusButton) {
					return false;
				}
				plusBackdropPressHandledAtRef.current = event.timeStamp;
				closePlusMenuFromRepeatPress(event.timeStamp);
				return true;
			},
			[closePlusMenuFromRepeatPress, textareaInputDisabled],
		);
		const openPlusMenu = useCallback(
			(openedAt: number) => {
				if (textareaInputDisabled) {
					return;
				}
				const plusButton = plusButtonRef.current;
				if (!plusButton) {
					return;
				}
				const rect = plusButton.getBoundingClientRect();
				const scrollX = window.scrollX || window.pageXOffset || 0;
				const scrollY = window.scrollY || window.pageYOffset || 0;
				const point = {x: rect.left + scrollX, y: rect.top + scrollY};
				plusMenuOpenedAtRef.current = openedAt;
				plusBackdropPressHandledAtRef.current = 0;
				ContextMenuCommands.openForElement(
					plusButton,
					() => (
						<TextareaPlusMenu
							onUploadFile={handleFileButtonClick}
							canAttachFiles={canAttachFilesInChannel(channel)}
							canSendMessages={!textareaInputDisabled}
							textareaValue={value}
							onUploadAsFile={handleUploadMessageAsFile}
							onSendVoiceMessage={
								mobileLayout.enabled || draftChannelId != null
									? undefined
									: () => {
											ContextMenuCommands.close();
											if (!textareaInputDisabled) {
												openVoiceMessageComposerModal(channel.id);
											}
										}
							}
							onCreateThread={
								draftChannelId == null && canStartThreadIn(channel)
									? () => {
											ContextMenuCommands.close();
											openCreateThread(channel, null);
										}
									: undefined
							}
							data-flx="channel.lexical-channel-textarea-content.open-plus-menu.textarea-plus-menu"
						/>
					),
					{
						point,
						config: {
							align: 'bottom-left',
							onClose: handlePlusMenuClosed,
							onBackdropMouseDown: handlePlusMenuBackdropMouseDown,
						},
					},
				);
			},
			[
				channel.id,
				handleFileButtonClick,
				handlePlusMenuBackdropMouseDown,
				handlePlusMenuClosed,
				handleUploadMessageAsFile,
				mobileLayout.enabled,
				textareaInputDisabled,
				value,
			],
		);
		const handlePlusMenuMouseDown = useCallback(
			(event: React.MouseEvent<HTMLButtonElement>) => {
				const wasOpen = isPlusContextMenuOpen();
				plusPressRef.current = {wasOpen, openedAt: plusMenuOpenedAtRef.current};
				if (wasOpen) {
					event.stopPropagation();
				}
			},
			[isPlusContextMenuOpen],
		);
		const handlePlusMenuClick = useCallback(
			(event: React.MouseEvent<HTMLButtonElement>) => {
				event.preventDefault();
				event.stopPropagation();
				if (textareaInputDisabled) {
					return;
				}
				if (mobileLayout.enabled) {
					handleOpenMobilePlusSheet();
					return;
				}
				if (
					plusBackdropPressHandledAtRef.current > 0 &&
					Math.abs(event.timeStamp - plusBackdropPressHandledAtRef.current) < 250
				) {
					plusBackdropPressHandledAtRef.current = 0;
					return;
				}
				const press = plusPressRef.current;
				plusPressRef.current = {wasOpen: false, openedAt: 0};
				const wasOpen = press.wasOpen || isPlusContextMenuOpen();
				const openedAt = press.openedAt || plusMenuOpenedAtRef.current;
				if (wasOpen) {
					closePlusMenuFromRepeatPress(event.timeStamp, openedAt);
					return;
				}
				openPlusMenu(event.timeStamp);
			},
			[
				closePlusMenuFromRepeatPress,
				handleOpenMobilePlusSheet,
				isPlusContextMenuOpen,
				mobileLayout.enabled,
				textareaInputDisabled,
				openPlusMenu,
			],
		);
		const isSlashParamBarVisible = slashCommandState.activeSlot != null;
		const isMobileEditBarVisible = editingMessage && mobileLayout.enabled;
		const isReplyBarVisible = !isMobileEditBarVisible && referencedMessage != null;
		const presentableTypingUsers = usePresentableTypingUsers(channel);
		const isTypingStatusVisible = !isAutocompleteVisible && presentableTypingUsers.length > 0;
		const isSlowmodeIndicatorVisible = isSlowmodeEnabled;
		const hasLeadingStatusContent = isMobileEditBarVisible || isReplyBarVisible || isSlashParamBarVisible;
		let shouldReplyMention = false;
		if (replyingMessage !== null && replyingMessage !== undefined) {
			shouldReplyMention = replyingMessage.mentioning;
		}
		let topBarContent: React.ReactNode = null;
		if (isMobileEditBarVisible) {
			topBarContent = (
				<EditBar
					channel={channel}
					onCancel={handleCancelEdit}
					data-flx="channel.lexical-channel-textarea-content.edit-bar"
				/>
			);
		} else if (referencedMessage !== null) {
			topBarContent = (
				<ReplyBar
					replyingMessageObject={referencedMessage}
					shouldReplyMention={shouldReplyMention}
					setShouldReplyMention={(mentioning) => MessageCommands.setReplyMentioning(channel.id, mentioning)}
					channel={channel}
					data-flx="channel.lexical-channel-textarea-content.reply-bar"
				/>
			);
		}
		const renderSection = (content: React.ReactNode, sectionClassName?: string) => (
			<flx-channel-textarea-section
				className={flxElementClassName(wrapperStyles.stackSection, sectionClassName)}
				data-flx="channel.lexical-channel-textarea-content.render-section.flx-channel-textarea-section"
			>
				{content}
			</flx-channel-textarea-section>
		);
		return (
			<>
				<flx-channel-textarea
					ref={containerRef}
					className={flxElementClassName(
						wrapperStyles.box,
						wrapperStyles.composerRoot,
						wrapperStyles.wrapperSides,
						styles.textareaOuter,
						bare && styles.textareaOuterBare,
						!bare && mobileLayout.enabled && styles.textareaOuterMobile,
						!bare && wrapperStyles.roundedAll,
						textareaInputDisabled && wrapperStyles.disabled,
						!bare && !mobileLayout.enabled && styles.textareaOuterRow,
					)}
					data-flx="channel.lexical-channel-textarea-content.textarea-outer"
				>
					{!bare && (
						<flx-channel-textarea-status-rail
							className={flxElementClassName(wrapperStyles.statusRail)}
							data-flx="channel.lexical-channel-textarea-content.flx-channel-textarea-status-rail"
						>
							<flx-channel-textarea-status-rail-left
								ref={typingStatusRailLeftRef}
								className={flxElementClassName(wrapperStyles.statusRailLeft)}
								data-flx="channel.lexical-channel-textarea-content.flx-channel-textarea-status-rail-left"
							>
								{isTypingStatusVisible && (
									<flx-channel-textarea-typing-slot
										className={flxElementClassName(wrapperStyles.statusTypingSlot)}
										data-flx="channel.lexical-channel-textarea-content.flx-channel-textarea-typing-slot"
									>
										<TypingUsers
											channel={channel}
											withText={true}
											showAvatars={true}
											overflowContainerRef={typingStatusRailLeftRef}
											data-flx="channel.lexical-channel-textarea-content.typing-users"
										/>
									</flx-channel-textarea-typing-slot>
								)}
								<TypingAnnouncer
									channel={channel}
									data-flx="channel.lexical-channel-textarea-content.typing-announcer"
								/>
							</flx-channel-textarea-status-rail-left>
							{isSlowmodeIndicatorVisible && (
								<flx-channel-textarea-slowmode-slot
									className={flxElementClassName(wrapperStyles.statusSlowmodeSlot)}
									data-flx="channel.lexical-channel-textarea-content.flx-channel-textarea-slowmode-slot"
								>
									<SlowmodeIndicator
										slowmodeRemaining={slowmodeRemaining}
										slowmodeDuration={channel.rateLimitPerUser * 1000}
										isImmune={isSlowmodeImmune}
										data-flx="channel.lexical-channel-textarea-content.slowmode-indicator"
									/>
								</flx-channel-textarea-slowmode-slot>
							)}
						</flx-channel-textarea-status-rail>
					)}
					{hasLeadingStatusContent && (
						<div className={wrapperStyles.composerActionStack} data-flx="channel.textarea.composer-action-stack">
							{topBarContent !== null && (
								<div className={wrapperStyles.composerActionRow} data-flx="channel.textarea.composer-action-row">
									{topBarContent}
								</div>
							)}
							{slashCommandState.activeSlot !== null && (
								<div className={wrapperStyles.composerActionRow} data-flx="channel.textarea.slash-command-action-row">
									<SlashCommandParamBar
										activeSlot={slashCommandState.activeSlot}
										onClear={handleClearSlashCommand}
										data-flx="channel.lexical-channel-textarea-content.slash-command-param-bar"
									/>
								</div>
							)}
						</div>
					)}
					{showAttachments &&
						renderSection(
							<ChannelAttachmentArea
								channelId={composerKey}
								data-flx="channel.lexical-channel-textarea-content.channel-attachment-area"
							/>,
							styles.collapsibleSection,
						)}
					{showStickers &&
						renderSection(
							<ChannelStickersArea
								channelId={channel.id}
								hasAttachments={hasAttachments}
								data-flx="channel.lexical-channel-textarea-content.channel-stickers-area"
							/>,
							styles.collapsibleSection,
						)}
					{renderSection(
						<flx-channel-textarea-box
							className={flxElementClassName(
								styles.mainWrapperDense,
								bare && styles.mainWrapperBare,
								textareaInputDisabled && wrapperStyles.disabled,
							)}
							data-flx="channel.lexical-channel-textarea-content.main-wrapper-dense"
						>
							{!bare && (
								<flx-channel-textarea-upload-column
									className={flxElementClassName(styles.uploadButtonColumn, styles.sideButtonPadding)}
									data-flx="channel.lexical-channel-textarea-content.upload-button-column"
								>
									<TextareaButton
										iconProps={PLUS_ICON_PROPS}
										icon={slashCommandState.hasSlots ? SlashCommandIcon : PlusIcon}
										label={slashCommandState.hasSlots ? i18n._(CLEAR_COMMAND_DESCRIPTOR) : i18n._(OPEN_MENU_DESCRIPTOR)}
										disabled={textareaInputDisabled}
										aria-hidden={textareaInputDisabled ? true : undefined}
										onMouseDown={slashCommandState.hasSlots ? undefined : handlePlusMenuMouseDown}
										onClick={slashCommandState.hasSlots ? handleClearSlashCommand : handlePlusMenuClick}
										forceHover={!slashCommandState.hasSlots && plusContextMenuOpen}
										className={plusContextMenuOpen ? styles.plusButtonAboveBackdrop : undefined}
										ref={plusButtonRef}
										data-flx="channel.lexical-channel-textarea-content.plus-button-above-backdrop.clear-slash-command"
									/>
								</flx-channel-textarea-upload-column>
							)}
							<flx-channel-textarea-content
								ref={contentAreaRef}
								className={flxElementClassName(styles.contentAreaDense)}
								data-flx="channel.lexical-channel-textarea-content.content-area-dense"
							>
								<flx-channel-textarea-composer
									className={flxElementClassName(lexicalStyles.composerHost)}
									data-flx="channel.lexical-channel-textarea-content.flx-channel-textarea-composer"
								>
									<LexicalComposerInput
										placeholder={placeholderText}
										disabled={textareaInputDisabled}
										handleRef={handleRef}
										initialValue={initialDraftRef.current.display}
										initialSegments={initialDraftRef.current.segments}
										slotResolvers={slotResolvers}
										emojiShortcodeResolver={composerEmojiResolver}
										specialMentionsAllowed={specialMentionsAllowed}
										channelId={channel.id}
										guildId={channel.guildId}
										submitOnEnter={submitOnEnter && !mobileLayout.enabled}
										maxWireLength={maxMessageLength}
										silentMessagePrefix={!isEditingMessageOnMobile}
										focusRingTarget={containerRef}
										focusRingEnabled={!textareaInputDisabled && Accessibility.showTextareaFocusRing}
										className={lexicalStyles.composerEditable}
										autocompleteOptions={autocompleteOptions}
										autocompleteType={autocompleteType}
										autocompleteQuery={autocompleteQuery}
										autocompleteEnabled={!textareaInputDisabled}
										slotMenuActive={isSlotMenu}
										autocompleteReferenceElement={containerRef.current}
										autocompleteListboxId={autocompleteListId}
										onAutocompleteSelect={handleSelect}
										onChange={handleEditorChange}
										onCursorMove={onCursorMove}
										onEnter={handleSubmit}
										onArrowUp={handleArrowUpEmpty}
										onKeyDown={handleEditorKeyDown}
										onFocus={() => {
											ActiveComposer.focus(draftChannelId ?? channel.id);
											setIsFocused(true);
											setIsInputAreaFocused(true);
											ChannelSearch.setInputFocused(channel.id, false);
										}}
										onBlur={() => {
											setIsFocused(false);
											setIsInputAreaFocused(false);
										}}
										onSlashCommandStateChange={setSlashCommandState}
										data-flx="channel.lexical-channel-textarea-content.lexical-composer-input.editor-change"
									/>
								</flx-channel-textarea-composer>
							</flx-channel-textarea-content>
							{!bare && (
								<TextareaButtons
									disabled={textareaInputDisabled}
									showAllButtons={showAllButtons}
									showGifButton={showGifButton}
									showMemesButton={showMemesButton}
									showStickersButton={showStickersButton}
									showEmojiButton={showEmojiButton}
									showMessageSendButton={showMessageSendButton}
									canRecordVoice={draftChannelId == null && canAttachFilesInChannel(channel)}
									isEditingMessage={isEditingMessageInComposer || editingMessageId != null}
									hasPendingSticker={hasPendingSticker}
									voiceTooltipAnchorRef={contentAreaRef}
									expressionPickerOpen={expressionPickerOpen}
									selectedTab={selectedTab}
									isMobile={mobileLayout.enabled}
									isSlowmodeActive={isSubmissionBlockedBySlowmode}
									isOverLimit={isOverCharacterLimit}
									hasContent={hasMessageContent}
									hasAttachments={uploadAttachments.length > 0}
									expressionPickerTriggerRef={expressionPickerTriggerRef}
									invisibleExpressionPickerTriggerRef={invisibleExpressionPickerTriggerRef}
									onExpressionPickerToggle={handleExpressionPickerTabToggle}
									onSubmit={handleSubmit}
									channelId={channel.id}
									data-flx="channel.lexical-channel-textarea-content.textarea-buttons.submit"
								/>
							)}
						</flx-channel-textarea-box>,
						styles.inputSection,
					)}
					<MessageCharacterCounter
						currentLength={composerMessageContent.length}
						maxLength={maxMessageLength}
						canUpgrade={maxMessageLength < premiumMaxLength}
						premiumMaxLength={premiumMaxLength}
						data-flx="channel.lexical-channel-textarea-content.message-character-counter"
					/>
				</flx-channel-textarea>
				{mobileLayout.enabled && (
					<>
						<ExpressionPickerSheet
							isOpen={expressionPickerOpen}
							onClose={() => setExpressionPickerOpen(false)}
							channelId={channel.id}
							onEmojiSelect={handleEmojiSelect}
							data-flx="channel.lexical-channel-textarea-content.expression-picker-sheet"
						/>
						<MobileTextareaPlusBottomSheet
							isOpen={mobilePlusSheetOpen}
							onClose={handleCloseMobilePlusSheet}
							onUploadFile={handleFileButtonClick}
							textareaValue={value}
							onUploadAsFile={handleUploadMessageAsFile}
							data-flx="channel.lexical-channel-textarea-content.mobile-textarea-plus-bottom-sheet"
						/>
					</>
				)}
			</>
		);
	},
);