| import { useState, useEffect, useRef, useCallback } from "react"; |
|
|
| interface CommentDialogProps { |
| open: boolean; |
| onClose: () => void; |
| onSubmit: (text: string) => void; |
| } |
|
|
| export function CommentDialog({ open, onClose, onSubmit }: CommentDialogProps) { |
| const [text, setText] = useState(""); |
| const dialogRef = useRef<HTMLDialogElement>(null); |
| const inputRef = useRef<HTMLTextAreaElement>(null); |
|
|
| useEffect(() => { |
| const dialog = dialogRef.current; |
| if (!dialog) return; |
|
|
| if (open && !dialog.open) { |
| dialog.showModal(); |
| setText(""); |
| setTimeout(() => inputRef.current?.focus(), 50); |
| } else if (!open && dialog.open) { |
| dialog.close(); |
| } |
| }, [open]); |
|
|
| const handleClose = useCallback(() => { |
| dialogRef.current?.close(); |
| onClose(); |
| }, [onClose]); |
|
|
| useEffect(() => { |
| const dialog = dialogRef.current; |
| if (!dialog) return; |
| const onCancel = () => onClose(); |
| dialog.addEventListener("close", onCancel); |
| return () => dialog.removeEventListener("close", onCancel); |
| }, [onClose]); |
|
|
| const handleSubmit = () => { |
| if (!text.trim()) return; |
| onSubmit(text.trim()); |
| setText(""); |
| handleClose(); |
| }; |
|
|
| return ( |
| <dialog ref={dialogRef} className="ed-dialog"> |
| <div className="ed-dialog__body" style={{ padding: "16px" }}> |
| <textarea |
| ref={inputRef} |
| className="form-input" |
| rows={3} |
| placeholder="Add your comment..." |
| value={text} |
| onChange={(e) => setText(e.target.value)} |
| onKeyDown={(e) => { |
| if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) handleSubmit(); |
| }} |
| style={{ marginBottom: 12 }} |
| /> |
| <div className="ed-dialog__actions" style={{ padding: 0 }}> |
| <button className="btn" onClick={handleClose}> |
| Cancel |
| </button> |
| <button |
| className="btn btn--primary" |
| onClick={handleSubmit} |
| disabled={!text.trim()} |
| > |
| Comment |
| </button> |
| </div> |
| </div> |
| </dialog> |
| ); |
| } |
|
|