feat(chat): add submit button and auto-resizing textareas for multiline messaging
This commit is contained in:
parent
441a6c4453
commit
a2c0de037f
4 changed files with 214 additions and 90 deletions
|
|
@ -1,12 +1,13 @@
|
|||
/**
|
||||
* @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";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { SendHorizontal, Loader2 } from "lucide-react";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @returns {JSX.Element} The rendered chat input component.
|
||||
* @returns {JSX.Element} The rendered chat input form component.
|
||||
*/
|
||||
export function ChatInput(props: ChatInputProps) {
|
||||
const { placeholderName, onMessageSent, type } = props;
|
||||
const [content, setContent] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
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
|
||||
* @function handleKeyDown
|
||||
* @param {React.KeyboardEvent<HTMLInputElement>} e - The keyboard event object.
|
||||
* @returns {Promise<void>} Resolves when the message submission finishes or fails.
|
||||
* @function handleSubmit
|
||||
* @param {React.FormEvent} [e] - Optional form submit event.
|
||||
* @returns {Promise<void>} Resolves when the message submission is complete.
|
||||
*/
|
||||
const handleKeyDown = async (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
const handleSubmit = async (e?: React.FormEvent) => {
|
||||
if (e) e.preventDefault();
|
||||
|
||||
if (!content.trim() || isLoading) return;
|
||||
if (!trimmedContent || isLoading) return;
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
setIsLoading(true);
|
||||
|
||||
const endpoint =
|
||||
props.type === "dm"
|
||||
? `/api/dm/${props.conversationId}`
|
||||
: "/api/messages";
|
||||
const endpoint = isDm
|
||||
? `/api/dm/${props.conversationId}`
|
||||
: "/api/messages";
|
||||
|
||||
const payload =
|
||||
props.type === "dm"
|
||||
? { content: content.trim() }
|
||||
: {
|
||||
content: content.trim(),
|
||||
channelId: props.channelId,
|
||||
serverId: props.serverId,
|
||||
};
|
||||
const payload = isDm
|
||||
? { content: trimmedContent }
|
||||
: {
|
||||
content: trimmedContent,
|
||||
channelId: props.channelId,
|
||||
serverId: props.serverId,
|
||||
};
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
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);
|
||||
if (!response.ok) {
|
||||
throw new Error("Error sending message");
|
||||
}
|
||||
|
||||
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"
|
||||
? `Message @${props.placeholderName}`
|
||||
: `Message #${props.placeholderName}`;
|
||||
/**
|
||||
* Handles keyboard events to submit messages on Enter key press without shift.
|
||||
*
|
||||
* @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 (
|
||||
<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">
|
||||
<input
|
||||
type="text"
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
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}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={isLoading}
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ export type MessageWithMember = Omit<Message, "channelId"> & {
|
|||
* @interface ChatItemProps
|
||||
* @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 {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, 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 {"chat" | "dm"} props.type - The type of chat context.
|
||||
* @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, newContent: string) => void} [props.onEditSuccess] - Callback on successful edit.
|
||||
* @returns {JSX.Element} The rendered chat item component.
|
||||
|
|
@ -193,6 +193,7 @@ export function ChatItem({
|
|||
{isEditing ? (
|
||||
<ChatItemEdit
|
||||
content={content}
|
||||
initialContent={message.content}
|
||||
setContent={setContent}
|
||||
onSave={handleEdit}
|
||||
onCancel={() => {
|
||||
|
|
@ -202,7 +203,7 @@ export function ChatItem({
|
|||
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}
|
||||
</p>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
/**
|
||||
* @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";
|
||||
|
||||
import { Pencil, Trash2 } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { Pencil, Trash2, Check, X, Loader2 } from "lucide-react";
|
||||
|
||||
/**
|
||||
* 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 {() => void} props.onEdit - Callback function triggered when the edit button is clicked.
|
||||
|
|
@ -35,6 +36,52 @@ export function ChatItemActions({
|
|||
onDelete,
|
||||
isDeleting,
|
||||
}: 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 (
|
||||
<div className="opacity-0 group-hover:opacity-100 flex items-center gap-1 transition-all">
|
||||
<button
|
||||
|
|
@ -47,9 +94,9 @@ export function ChatItemActions({
|
|||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDelete}
|
||||
onClick={handleDeleteClick}
|
||||
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"
|
||||
>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
|
|
|
|||
|
|
@ -1,16 +1,18 @@
|
|||
/**
|
||||
* @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";
|
||||
|
||||
import { Check, X } from "lucide-react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Check, X, Loader2 } from "lucide-react";
|
||||
|
||||
/**
|
||||
* Properties for the ChatItemEdit component.
|
||||
*
|
||||
* @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 {function} setContent - Callback function to update the message content state.
|
||||
* @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.
|
||||
*/
|
||||
interface ChatItemEditProps {
|
||||
initialContent?: string;
|
||||
content: string;
|
||||
setContent: (value: string) => void;
|
||||
onSave: () => void;
|
||||
|
|
@ -29,6 +32,7 @@ interface ChatItemEditProps {
|
|||
* Renders an inline text input field with save and cancel buttons for editing chat messages.
|
||||
*
|
||||
* @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 {function} props.setContent - Callback function to update the message content state.
|
||||
* @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.
|
||||
*/
|
||||
export function ChatItemEdit({
|
||||
initialContent,
|
||||
content,
|
||||
setContent,
|
||||
onSave,
|
||||
onCancel,
|
||||
isLoading,
|
||||
}: 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
|
||||
* @param {React.KeyboardEvent<HTMLInputElement>} e - The keyboard event object.
|
||||
* @param {React.KeyboardEvent<HTMLTextAreaElement>} e - The keyboard event object.
|
||||
* @returns {void}
|
||||
*/
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === "Enter") {
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
onSave();
|
||||
if (isValidAndChanged && !isLoading) {
|
||||
onSave();
|
||||
}
|
||||
} else if (e.key === "Escape") {
|
||||
onCancel();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<input
|
||||
type="text"
|
||||
<div className="mt-1 flex items-start gap-2">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
rows={1}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
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
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSave}
|
||||
disabled={isLoading}
|
||||
className="p-1 text-muted hover:text-foreground cursor-pointer"
|
||||
>
|
||||
<Check className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
className="p-1 text-muted hover:text-foreground cursor-pointer"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
<div className="flex items-center gap-1 shrink-0 mt-0.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSave}
|
||||
disabled={!isValidAndChanged || isLoading}
|
||||
title={isValidAndChanged ? "Save changes" : "No changes to save"}
|
||||
className="p-1 text-muted hover:text-foreground disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Check className="w-4 h-4" />
|
||||
)}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue