import { useMentions } from "@replyke/react-js";
import { useState, useRef } from "react";
function CommentInput() {
const [content, setContent] = useState("");
const [cursorPosition, setCursorPosition] = useState(0);
const [isSelectionActive, setIsSelectionActive] = useState(false);
const inputRef = useRef<HTMLTextAreaElement>(null);
const focus = () => {
inputRef.current?.focus();
};
const {
isMentionActive,
loading,
mentionSuggestions,
handleMentionClick,
mentions,
addMention,
resetMentions,
} = useMentions({
content,
setContent,
focus,
cursorPosition,
isSelectionActive,
});
const handleTextChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setContent(e.target.value);
setCursorPosition(e.target.selectionStart);
};
const handleSelectionChange = () => {
if (inputRef.current) {
const start = inputRef.current.selectionStart;
const end = inputRef.current.selectionEnd;
setCursorPosition(start);
setIsSelectionActive(start !== end);
}
};
return (
<div>
<textarea
ref={inputRef}
value={content}
onChange={handleTextChange}
onSelect={handleSelectionChange}
onKeyUp={handleSelectionChange}
onMouseUp={handleSelectionChange}
placeholder="Type @ to mention someone..."
/>
{isMentionActive && (
<div className="mention-suggestions">
{loading ? (
<div>Loading suggestions...</div>
) : (
mentionSuggestions.map((user) => (
<div
key={user.id}
onClick={() => handleMentionClick(user)}
className="mention-suggestion"
>
@{user.username} - {user.name}
</div>
))
)}
</div>
)}
<div>
<strong>Current mentions:</strong>
{mentions.map((mention) => (
<span key={mention.id}>@{mention.username} </span>
))}
</div>
</div>
);
}