feat(chat): add submit button and auto-resizing textareas for multiline messaging

This commit is contained in:
Chneemann 2026-09-06 12:45:25 +02:00
parent 441a6c4453
commit a2c0de037f
No known key found for this signature in database
4 changed files with 214 additions and 90 deletions

View file

@ -1,12 +1,13 @@
/** /**
* @file components/chat/ChatInput.tsx * @file components/chat/ChatInput.tsx
* @description Input component for sending chat messages within channels or direct message conversations, handling submission via keyboard events and API requests. * @description Input component for sending chat messages within channels or direct message conversations, handling submission via form submit and API requests.
*/ */
"use client"; "use client";
import { useState } from "react"; import { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { SendHorizontal, Loader2 } from "lucide-react";
/** /**
* Base properties shared across all ChatInput variations. * Base properties shared across all ChatInput variations.
@ -39,89 +40,130 @@ type ChatInputProps = BaseChatInputProps &
); );
/** /**
* Renders an input field for writing and submitting chat messages with loading states and keyboard event handlers. * Renders an auto-expanding chat input form allowing users to send messages via API calls with keyboard shortcut support.
* *
* @param {ChatInputProps} props - The component props. * @param {ChatInputProps} props - The component props.
* @returns {JSX.Element} The rendered chat input component. * @returns {JSX.Element} The rendered chat input form component.
*/ */
export function ChatInput(props: ChatInputProps) { export function ChatInput(props: ChatInputProps) {
const { placeholderName, onMessageSent, type } = props;
const [content, setContent] = useState(""); const [content, setContent] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const router = useRouter(); const router = useRouter();
const trimmedContent = content.trim();
const isDm = type === "dm";
// Automatically adjust the height to fit the content
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = "auto";
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
}
}, [content]);
/** /**
* Handles keydown events on the input element to submit messages when pressing Enter without Shift. * Handles the asynchronous form submission and sending of the chat message.
* *
* @async * @async
* @function handleKeyDown * @function handleSubmit
* @param {React.KeyboardEvent<HTMLInputElement>} e - The keyboard event object. * @param {React.FormEvent} [e] - Optional form submit event.
* @returns {Promise<void>} Resolves when the message submission finishes or fails. * @returns {Promise<void>} Resolves when the message submission is complete.
*/ */
const handleKeyDown = async (e: React.KeyboardEvent<HTMLInputElement>) => { const handleSubmit = async (e?: React.FormEvent) => {
if (e.key === "Enter" && !e.shiftKey) { if (e) e.preventDefault();
e.preventDefault();
if (!content.trim() || isLoading) return; if (!trimmedContent || isLoading) return;
try { try {
setIsLoading(true); setIsLoading(true);
const endpoint = const endpoint = isDm
props.type === "dm" ? `/api/dm/${props.conversationId}`
? `/api/dm/${props.conversationId}` : "/api/messages";
: "/api/messages";
const payload = const payload = isDm
props.type === "dm" ? { content: trimmedContent }
? { content: content.trim() } : {
: { content: trimmedContent,
content: content.trim(), channelId: props.channelId,
channelId: props.channelId, serverId: props.serverId,
serverId: props.serverId, };
};
const response = await fetch(endpoint, { const response = await fetch(endpoint, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload), body: JSON.stringify(payload),
}); });
if (!response.ok) { if (!response.ok) {
throw new Error("Error sending message"); throw new Error("Error sending message");
}
const data = await response.json();
setContent("");
if (props.onMessageSent) {
props.onMessageSent(data);
} else {
router.refresh();
}
} catch (error) {
console.error("Error sending the message:", error);
} finally {
setIsLoading(false);
} }
const data = await response.json();
setContent("");
if (textareaRef.current) {
textareaRef.current.style.height = "auto";
}
if (onMessageSent) {
onMessageSent(data);
} else {
router.refresh();
}
} catch (error) {
console.error("Error sending the message:", error);
} finally {
setIsLoading(false);
} }
}; };
const placeholderText = /**
props.type === "dm" * Handles keyboard events to submit messages on Enter key press without shift.
? `Message @${props.placeholderName}` *
: `Message #${props.placeholderName}`; * @function handleKeyDown
* @param {React.KeyboardEvent<HTMLTextAreaElement>} e - The keyboard event object.
*/
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSubmit();
}
};
const placeholderText = isDm
? `Message @${placeholderName}`
: `Message #${placeholderName}`;
return ( return (
<div className="bg-surface border border-surface rounded-lg p-2.5 flex items-center focus-within:ring-1 focus-within:ring-accent transition-all"> <form
<input onSubmit={handleSubmit}
type="text" className="bg-surface border border-surface rounded-lg p-2.5 flex items-end gap-2 focus-within:ring-1 focus-within:ring-accent transition-all"
>
<textarea
ref={textareaRef}
rows={1}
value={content} value={content}
onChange={(e) => setContent(e.target.value)} onChange={(e) => setContent(e.target.value)}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
disabled={isLoading} disabled={isLoading}
placeholder={placeholderText} placeholder={placeholderText}
className="w-full bg-transparent outline-none text-foreground placeholder-muted text-sm disabled:opacity-50" className="w-full bg-transparent outline-none text-foreground placeholder-muted text-sm disabled:opacity-50 resize-none max-h-40 min-h-6"
/> />
</div> <button
type="submit"
disabled={!trimmedContent || isLoading}
title="Send Message"
className="p-1 rounded-md text-muted hover:text-white hover:bg-accent/20 disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-muted transition-colors cursor-pointer disabled:cursor-not-allowed shrink-0 scrollbar-thin"
>
{isLoading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<SendHorizontal className="w-4 h-4" />
)}
</button>
</form>
); );
} }

View file

@ -42,7 +42,7 @@ export type MessageWithMember = Omit<Message, "channelId"> & {
* @interface ChatItemProps * @interface ChatItemProps
* @property {"chat" | "dm"} type - The type of chat context (channel chat or direct message). * @property {"chat" | "dm"} type - The type of chat context (channel chat or direct message).
* @property {MessageWithMember} message - The message object containing member and content data. * @property {MessageWithMember} message - The message object containing member and content data.
* @property {string} [currentUserId] - The unique identifier of the currently logged-in user. * @property {string} currentUserId - The unique identifier of the currently logged-in user.
* @property {(id: string) => void} [onDeleteSuccess] - Optional callback executed when a message is successfully deleted. * @property {(id: string) => void} [onDeleteSuccess] - Optional callback executed when a message is successfully deleted.
* @property {(id: string, newContent: string) => void} [onEditSuccess] - Optional callback executed when a message is successfully edited. * @property {(id: string, newContent: string) => void} [onEditSuccess] - Optional callback executed when a message is successfully edited.
*/ */
@ -60,7 +60,7 @@ interface ChatItemProps {
* @param {ChatItemProps} props - The component props. * @param {ChatItemProps} props - The component props.
* @param {"chat" | "dm"} props.type - The type of chat context. * @param {"chat" | "dm"} props.type - The type of chat context.
* @param {MessageWithMember} props.message - The message object. * @param {MessageWithMember} props.message - The message object.
* @param {string} [props.currentUserId] - The unique identifier of the current user. * @param {string} props.currentUserId - The unique identifier of the current user.
* @param {(id: string) => void} [props.onDeleteSuccess] - Callback on successful deletion. * @param {(id: string) => void} [props.onDeleteSuccess] - Callback on successful deletion.
* @param {(id: string, newContent: string) => void} [props.onEditSuccess] - Callback on successful edit. * @param {(id: string, newContent: string) => void} [props.onEditSuccess] - Callback on successful edit.
* @returns {JSX.Element} The rendered chat item component. * @returns {JSX.Element} The rendered chat item component.
@ -193,6 +193,7 @@ export function ChatItem({
{isEditing ? ( {isEditing ? (
<ChatItemEdit <ChatItemEdit
content={content} content={content}
initialContent={message.content}
setContent={setContent} setContent={setContent}
onSave={handleEdit} onSave={handleEdit}
onCancel={() => { onCancel={() => {
@ -202,7 +203,7 @@ export function ChatItem({
isLoading={isLoading} isLoading={isLoading}
/> />
) : ( ) : (
<p className="text-foreground text-sm leading-relaxed wrap-break-words mt-0.5"> <p className="text-foreground text-sm leading-relaxed whitespace-pre-wrap wrap-break-words mt-0.5">
{message.content} {message.content}
</p> </p>
)} )}

View file

@ -1,11 +1,12 @@
/** /**
* @file components/chat/ChatItemActions.tsx * @file components/chat/ChatItemActions.tsx
* @description Action buttons component for editing or deleting chat messages on hover. * @description Action buttons component for editing or deleting chat messages on hover with deletion confirmation state.
*/ */
"use client"; "use client";
import { Pencil, Trash2 } from "lucide-react"; import { useState } from "react";
import { Pencil, Trash2, Check, X, Loader2 } from "lucide-react";
/** /**
* Properties for the ChatItemActions component. * Properties for the ChatItemActions component.
@ -22,7 +23,7 @@ interface ChatItemActionsProps {
} }
/** /**
* Renders action buttons (edit and delete) for a chat message item on hover. * Renders action buttons (edit and delete) for a chat message item on hover with an inline delete confirmation step.
* *
* @param {ChatItemActionsProps} props - The component props. * @param {ChatItemActionsProps} props - The component props.
* @param {() => void} props.onEdit - Callback function triggered when the edit button is clicked. * @param {() => void} props.onEdit - Callback function triggered when the edit button is clicked.
@ -35,6 +36,52 @@ export function ChatItemActions({
onDelete, onDelete,
isDeleting, isDeleting,
}: ChatItemActionsProps) { }: ChatItemActionsProps) {
const [isConfirming, setIsConfirming] = useState(false);
const handleDeleteClick = () => {
if (!isConfirming) {
setIsConfirming(true);
return;
}
onDelete();
};
const handleCancelDelete = () => {
setIsConfirming(false);
};
if (isConfirming) {
return (
<div className="flex items-center gap-1 px-1 shadow-sm">
<span className="text-xs text-muted px-1 select-none">Delete?</span>
<button
type="button"
onClick={handleDeleteClick}
disabled={isDeleting}
className="p-1 text-muted hover:text-destructive focus:outline-none transition-all cursor-pointer shrink-0 disabled:opacity-50"
title="Confirm deletion"
aria-label="Confirm deletion"
>
{isDeleting ? (
<Loader2 className="w-3.5 h-3.5 animate-spin" />
) : (
<Check className="w-3.5 h-3.5" />
)}
</button>
<button
type="button"
onClick={handleCancelDelete}
disabled={isDeleting}
className="p-1 text-muted hover:text-foreground focus:outline-none transition-all cursor-pointer shrink-0"
title="Cancel"
aria-label="Cancel deletion"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
);
}
return ( return (
<div className="opacity-0 group-hover:opacity-100 flex items-center gap-1 transition-all"> <div className="opacity-0 group-hover:opacity-100 flex items-center gap-1 transition-all">
<button <button
@ -47,9 +94,9 @@ export function ChatItemActions({
</button> </button>
<button <button
type="button" type="button"
onClick={onDelete} onClick={handleDeleteClick}
disabled={isDeleting} disabled={isDeleting}
className="p-1 text-muted hover:text-red-400 focus:outline-none transition-all cursor-pointer shrink-0 disabled:opacity-50" className="p-1 text-muted hover:text-destructive focus:outline-none transition-all cursor-pointer shrink-0 disabled:opacity-50"
aria-label="Delete message" aria-label="Delete message"
> >
<Trash2 className="w-3.5 h-3.5" /> <Trash2 className="w-3.5 h-3.5" />

View file

@ -1,16 +1,18 @@
/** /**
* @file components/chat/ChatItemEdit.tsx * @file components/chat/ChatItemEdit.tsx
* @description Component allowing users to edit an existing chat message inline with keyboard support. * @description Component allowing users to edit an existing chat message inline with auto-resizing textarea and keyboard support.
*/ */
"use client"; "use client";
import { Check, X } from "lucide-react"; import { useEffect, useRef } from "react";
import { Check, X, Loader2 } from "lucide-react";
/** /**
* Properties for the ChatItemEdit component. * Properties for the ChatItemEdit component.
* *
* @interface ChatItemEditProps * @interface ChatItemEditProps
* @property {string} [initialContent] - The original unedited text content of the message.
* @property {string} content - The current text content of the message being edited. * @property {string} content - The current text content of the message being edited.
* @property {function} setContent - Callback function to update the message content state. * @property {function} setContent - Callback function to update the message content state.
* @property {function} onSave - Callback function invoked to save the edited message. * @property {function} onSave - Callback function invoked to save the edited message.
@ -18,6 +20,7 @@ import { Check, X } from "lucide-react";
* @property {boolean} isLoading - Flag indicating whether a save operation is currently in progress. * @property {boolean} isLoading - Flag indicating whether a save operation is currently in progress.
*/ */
interface ChatItemEditProps { interface ChatItemEditProps {
initialContent?: string;
content: string; content: string;
setContent: (value: string) => void; setContent: (value: string) => void;
onSave: () => void; onSave: () => void;
@ -29,6 +32,7 @@ interface ChatItemEditProps {
* Renders an inline text input field with save and cancel buttons for editing chat messages. * Renders an inline text input field with save and cancel buttons for editing chat messages.
* *
* @param {ChatItemEditProps} props - The component props. * @param {ChatItemEditProps} props - The component props.
* @param {string} [props.initialContent] - The original message content.
* @param {string} props.content - The current text content of the message being edited. * @param {string} props.content - The current text content of the message being edited.
* @param {function} props.setContent - Callback function to update the message content state. * @param {function} props.setContent - Callback function to update the message content state.
* @param {function} props.onSave - Callback function invoked to save the edited message. * @param {function} props.onSave - Callback function invoked to save the edited message.
@ -37,54 +41,84 @@ interface ChatItemEditProps {
* @returns {JSX.Element} The rendered inline message editing component. * @returns {JSX.Element} The rendered inline message editing component.
*/ */
export function ChatItemEdit({ export function ChatItemEdit({
initialContent,
content, content,
setContent, setContent,
onSave, onSave,
onCancel, onCancel,
isLoading, isLoading,
}: ChatItemEditProps) { }: ChatItemEditProps) {
const textareaRef = useRef<HTMLTextAreaElement>(null);
// If `initialContent` is not passed, the era is considered unchanged if `content` is empty
const isChanged =
initialContent !== undefined
? content.trim() !== initialContent.trim()
: true;
const isValidAndChanged = isChanged && content.trim().length > 0;
// Automatically adjust the height to fit the content
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = "auto";
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
}
}, [content]);
/** /**
* Handles keyboard events within the input field for quick actions (Enter to save, Escape to cancel). * Handles keyboard events for saving on Enter or cancelling on Escape.
* *
* @function handleKeyDown * @function handleKeyDown
* @param {React.KeyboardEvent<HTMLInputElement>} e - The keyboard event object. * @param {React.KeyboardEvent<HTMLTextAreaElement>} e - The keyboard event object.
* @returns {void} * @returns {void}
*/ */
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter") { if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault(); e.preventDefault();
onSave(); if (isValidAndChanged && !isLoading) {
onSave();
}
} else if (e.key === "Escape") { } else if (e.key === "Escape") {
onCancel(); onCancel();
} }
}; };
return ( return (
<div className="mt-1 flex items-center gap-2"> <div className="mt-1 flex items-start gap-2">
<input <textarea
type="text" ref={textareaRef}
rows={1}
value={content} value={content}
onChange={(e) => setContent(e.target.value)} onChange={(e) => setContent(e.target.value)}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
disabled={isLoading} disabled={isLoading}
className="w-full bg-background border border-surface rounded px-2 py-1 text-sm text-foreground outline-none focus:ring-1 focus:ring-accent" className="w-full bg-background border-none outline-none focus:ring-1 focus:ring-accent resize-none max-h-40 min-h-6 px-1 py-0.5 text-sm text-foreground overflow-y-auto scrollbar-thin"
autoFocus autoFocus
/> />
<button <div className="flex items-center gap-1 shrink-0 mt-0.5">
type="button" <button
onClick={onSave} type="button"
disabled={isLoading} onClick={onSave}
className="p-1 text-muted hover:text-foreground cursor-pointer" disabled={!isValidAndChanged || isLoading}
> title={isValidAndChanged ? "Save changes" : "No changes to save"}
<Check className="w-4 h-4" /> className="p-1 text-muted hover:text-foreground disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
</button> >
<button {isLoading ? (
type="button" <Loader2 className="w-4 h-4 animate-spin" />
onClick={onCancel} ) : (
className="p-1 text-muted hover:text-foreground cursor-pointer" <Check className="w-4 h-4" />
> )}
<X className="w-4 h-4" /> </button>
</button> <button
type="button"
onClick={onCancel}
disabled={isLoading}
title="Cancel"
className="p-1 text-muted hover:text-foreground disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
>
<X className="w-4 h-4" />
</button>
</div>
</div> </div>
); );
} }