File size: 2,103 Bytes
d15d7f7
561e6f0
 
 
 
 
 
 
 
 
d15d7f7
 
561e6f0
 
d15d7f7
 
 
 
 
561e6f0
d15d7f7
 
 
561e6f0
 
 
d15d7f7
 
 
 
 
 
 
 
 
 
 
 
 
561e6f0
 
 
 
d15d7f7
561e6f0
 
 
d15d7f7
 
 
 
 
 
561e6f0
 
 
 
 
 
d15d7f7
561e6f0
d15d7f7
 
561e6f0
d15d7f7
 
 
561e6f0
 
 
 
d15d7f7
 
 
 
561e6f0
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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>
  );
}