File size: 9,857 Bytes
76fc93a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import { useState, useEffect, useCallback, useRef } from "react";
import { CheckCircle, Trash2, Send, MessageCircle } from "lucide-react";
import type { Editor } from "@tiptap/core";
import type { CommentStore, CommentData } from "../editor/comments";

interface Props {
  editor: Editor | null;
  commentStore: CommentStore | null;
  user: { name: string; color: string; avatarUrl?: string };
}

interface CommentPosition {
  id: string;
  top: number;
}

function buildMarkPositions(editor: Editor): Map<string, number> {
  const map = new Map<string, number>();
  editor.state.doc.descendants((node, pos) => {
    for (const mark of node.marks) {
      if (mark.type.name === "comment" && !map.has(mark.attrs.commentId)) {
        map.set(mark.attrs.commentId, pos);
      }
    }
  });
  return map;
}

export function CommentMarginIcons({ editor, commentStore, user }: Props) {
  const [positions, setPositions] = useState<CommentPosition[]>([]);
  const [activeId, setActiveId] = useState<string | null>(null);
  const [activeComment, setActiveComment] = useState<CommentData | null>(null);
  const [replyText, setReplyText] = useState("");
  const popoverRef = useRef<HTMLDivElement>(null);
  const replyInputRef = useRef<HTMLTextAreaElement>(null);

  const activeIdRef = useRef<string | null>(null);
  activeIdRef.current = activeId;

  const updatePositions = useCallback(() => {
    if (!editor || !commentStore) return;
    if (activeIdRef.current) return; // freeze while popover open
    const comments = commentStore.getAll().filter((c) => !c.resolved);
    if (comments.length === 0) {
      setPositions([]);
      return;
    }

    const scrollParent = editor.view.dom.closest(".editor-scroll");
    if (!scrollParent) return;
    const scrollTop = scrollParent.scrollTop;
    const scrollRect = scrollParent.getBoundingClientRect();

    const markPos = buildMarkPositions(editor);
    const result: CommentPosition[] = [];

    for (const c of comments) {
      const pos = markPos.get(c.id);
      if (pos === undefined) continue;
      try {
        const coords = editor.view.coordsAtPos(pos);
        const top = coords.top - scrollRect.top + scrollTop;
        result.push({ id: c.id, top });
      } catch { /* not mapped */ }
    }

    result.sort((a, b) => a.top - b.top);
    const MIN_GAP = 32;
    for (let i = 1; i < result.length; i++) {
      if (result[i].top < result[i - 1].top + MIN_GAP) {
        result[i].top = result[i - 1].top + MIN_GAP;
      }
    }
    setPositions(result);
  }, [editor, commentStore]);

  useEffect(() => {
    updatePositions();
    if (!commentStore) return;
    return commentStore.observe(updatePositions);
  }, [commentStore, updatePositions]);

  useEffect(() => {
    if (!editor) return;
    const scrollParent = editor.view.dom.closest(".editor-scroll");
    if (!scrollParent) return;

    let timer = 0;
    const debounced = () => {
      clearTimeout(timer);
      timer = window.setTimeout(updatePositions, 120);
    };
    scrollParent.addEventListener("scroll", debounced, { passive: true });
    editor.on("update", debounced);
    return () => {
      scrollParent.removeEventListener("scroll", debounced);
      editor.off("update", debounced);
      clearTimeout(timer);
    };
  }, [editor, updatePositions]);

  // Also open popover when clicking on a comment-mark in the text
  useEffect(() => {
    if (!editor || !commentStore) return;
    const handleSelection = () => {
      const { from, to } = editor.state.selection;
      if (from !== to) return;
      const resolved = editor.state.doc.resolve(from);
      for (const mark of resolved.marks()) {
        if (mark.type.name === "comment" && mark.attrs.commentId) {
          const id = mark.attrs.commentId as string;
          const comment = commentStore.get(id);
          if (comment && !comment.resolved) {
            setActiveId(id);
            setActiveComment(comment);
            setReplyText("");
            return;
          }
        }
      }
    };
    editor.on("selectionUpdate", handleSelection);
    return () => { editor.off("selectionUpdate", handleSelection); };
  }, [editor, commentStore]);

  // Refresh active comment data from store
  useEffect(() => {
    if (!activeId || !commentStore) return;
    const refresh = () => {
      const updated = commentStore.get(activeId);
      if (updated) setActiveComment(updated);
      else { setActiveComment(null); setActiveId(null); }
    };
    return commentStore.observe(refresh);
  }, [activeId, commentStore]);

  // Recalculate positions when popover closes (unfreeze)
  const prevActiveId = useRef<string | null>(null);
  useEffect(() => {
    if (prevActiveId.current && !activeId) {
      setTimeout(updatePositions, 50);
    }
    prevActiveId.current = activeId;
  }, [activeId, updatePositions]);

  // Close on outside click
  useEffect(() => {
    if (!activeId) return;
    const handler = (e: MouseEvent) => {
      if (popoverRef.current && !popoverRef.current.contains(e.target as Node)) {
        const target = e.target as HTMLElement;
        if (target.closest(".comment-margin-icon")) return;
        setActiveId(null);
        setActiveComment(null);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [activeId]);

  const handleIconClick = (id: string) => {
    if (!commentStore) return;
    if (activeId === id) {
      setActiveId(null);
      setActiveComment(null);
      return;
    }
    const comment = commentStore.get(id);
    if (!comment) return;
    setActiveId(id);
    setActiveComment(comment);
    setReplyText("");
  };

  const handleReply = () => {
    if (!replyText.trim() || !commentStore || !activeId) return;
    commentStore.addReply(activeId, {
      id: `r_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`,
      author: user.name,
      authorColor: user.color,
      text: replyText.trim(),
      createdAt: Date.now(),
    });
    setReplyText("");
    setTimeout(() => replyInputRef.current?.focus(), 50);
  };

  const removeMarkAndData = useCallback((id: string) => {
    if (!commentStore || !editor) return;
    commentStore.remove(id);
    const { doc, tr } = editor.state;
    const markType = editor.schema.marks.comment;
    doc.descendants((node, pos) => {
      node.marks.forEach((mark) => {
        if (mark.type === markType && mark.attrs.commentId === id) {
          tr.removeMark(pos, pos + node.nodeSize, markType);
        }
      });
    });
    editor.view.dispatch(tr);
    setActiveId(null);
    setActiveComment(null);
  }, [commentStore, editor]);

  const activePos = positions.find((p) => p.id === activeId);

  const formatTime = (ts: number) =>
    new Date(ts).toLocaleString(undefined, {
      month: "short", day: "numeric", hour: "2-digit", minute: "2-digit",
    });

  return (
    <div className="comment-margin-strip">
      {positions.map((p) => (
        <div
          key={p.id}
          className={`comment-margin-icon ${activeId === p.id ? "comment-margin-icon--active" : ""}`}
          style={{ top: p.top }}
          onClick={() => handleIconClick(p.id)}
        >
          <MessageCircle size={14} />
        </div>
      ))}

      {activeComment && activePos && (
        <div
          ref={popoverRef}
          className="comment-popover"
          style={{ top: activePos.top }}
        >
          <div className="comment-popover__thread">
            <div className="comment-popover__message">
              <div className="comment-popover__header">
                <span className="comment-popover__author" style={{ color: activeComment.authorColor }}>
                  {activeComment.author}
                </span>
                <span className="comment-popover__time">{formatTime(activeComment.createdAt)}</span>
              </div>
              <div className="comment-popover__text">{activeComment.text}</div>
            </div>

            {activeComment.replies.map((reply) => (
              <div key={reply.id} className="comment-popover__message comment-popover__reply">
                <div className="comment-popover__header">
                  <span className="comment-popover__author" style={{ color: reply.authorColor }}>
                    {reply.author}
                  </span>
                  <span className="comment-popover__time">{formatTime(reply.createdAt)}</span>
                </div>
                <div className="comment-popover__text">{reply.text}</div>
              </div>
            ))}
          </div>

          <div className="comment-popover__input-row">
            <textarea
              ref={replyInputRef}
              className="comment-popover__input"
              rows={1}
              placeholder="Reply..."
              value={replyText}
              onChange={(e) => setReplyText(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  handleReply();
                }
              }}
            />
            <button
              className="comment-popover__send"
              onClick={handleReply}
              disabled={!replyText.trim()}
              aria-label="Send reply"
            >
              <Send size={14} />
            </button>
          </div>

          <div className="comment-popover__actions">
            <button className="comment-popover__resolve" onClick={() => removeMarkAndData(activeComment.id)}>
              <CheckCircle size={14} />
              Resolve
            </button>
            <button className="comment-popover__delete" onClick={() => removeMarkAndData(activeComment.id)}>
              <Trash2 size={14} />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}