File size: 4,607 Bytes
2f48928
 
 
 
 
 
 
 
 
ba947c9
2f48928
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4498c94
 
 
 
 
 
2f48928
 
4498c94
 
 
 
 
 
2f48928
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use client';

import { useEffect, useRef, useState } from 'react';
import { api } from '@/lib/client/api';
import { getSocket } from '@/lib/client/socket';
import MessageItem from './MessageItem';
import Composer from './Composer';
import { Spinner } from '../ui';
import { ChatMessage } from './types';
import { X } from 'lucide-react';

export default function ThreadPanel({
  root, channelId, conversationId, onClose,
}: {
  root: ChatMessage;
  channelId?: string;
  conversationId?: string;
  onClose: () => void;
}) {
  const [rootMsg, setRootMsg] = useState<ChatMessage>(root);
  const [replies, setReplies] = useState<ChatMessage[] | null>(null);
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setReplies(null);
    api<{ root: ChatMessage; replies: ChatMessage[] }>(`/api/messages/${root.id}/thread`)
      .then((res) => {
        setRootMsg(res.root);
        setReplies(res.replies);
        setTimeout(() => scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight }), 30);
      })
      .catch(() => setReplies([]));
  }, [root.id]);

  useEffect(() => {
    const socket = getSocket();
    const onNew = (m: ChatMessage) => {
      if (m.parentId !== root.id) return;
      setReplies((prev) => (prev && !prev.some((x) => x.id === m.id) ? [...prev, m] : prev));
      setTimeout(() => scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' }), 30);
    };
    const onReactions = (p: { messageId: string; reactions: { emoji: string; userId: string }[] }) => {
      setReplies((prev) => prev?.map((x) => (x.id === p.messageId ? { ...x, reactions: p.reactions } : x)) ?? null);
      setRootMsg((prev) => (prev.id === p.messageId ? { ...prev, reactions: p.reactions } : prev));
    };
    socket.on('message:new', onNew);
    socket.on('message:reactions', onReactions);
    return () => {
      socket.off('message:new', onNew);
      socket.off('message:reactions', onReactions);
    };
  }, [root.id]);

  const basePath = channelId ? `/api/channels/${channelId}` : `/api/conversations/${conversationId}`;

  async function sendReply(content: string, attachmentIds: string[]) {
    const res = await api<{ message?: ChatMessage; command?: boolean; ephemeral?: string }>(`${basePath}/messages`, {
      method: 'POST', json: { content, attachmentIds, parentId: root.id },
    });
    if (res.command) return { ephemeral: res.ephemeral };
    if (res.message) {
      setReplies((prev) => (prev && !prev.some((x) => x.id === res.message!.id) ? [...prev, res.message!] : prev));
    }
  }

  return (
    <aside className="flex w-full max-w-sm flex-col border-l border-gray-200 bg-white max-md:absolute max-md:inset-0 max-md:z-20 md:w-96">
      <div className="flex h-[52px] shrink-0 items-center gap-2 border-b border-gray-200 px-4">
        <span className="font-display text-[15px] font-bold text-gray-900">Thread</span>
        <span className="rounded-full bg-primary-50 px-2 py-0.5 text-[10px] font-bold text-primary-600">
          {(replies?.length ?? rootMsg.replyCount)} repl{(replies?.length ?? rootMsg.replyCount) === 1 ? 'y' : 'ies'}
        </span>
        <button onClick={onClose} className="ml-auto rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600" aria-label="Close thread"><X className="h-4 w-4" /></button>
      </div>
      <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto py-2">
        <div className="mx-2 mb-1 rounded-xl bg-gray-50 py-1.5">
          <MessageItem message={rootMsg} showHeader isThreadReply onEdited={(u) => setRootMsg({ ...rootMsg, ...u })} onDeleted={onClose} />
        </div>
        <div className="mx-4 my-2 flex items-center gap-2 text-[11px] font-semibold text-gray-400">
          <hr className="flex-1 border-gray-100" />
          <span>replies</span>
          <hr className="flex-1 border-gray-100" />
        </div>
        {replies === null && <Spinner label="Loading thread…" />}
        {replies?.map((m, i) => (
          <MessageItem
            key={m.id}
            message={m}
            showHeader={i === 0 || replies[i - 1].senderId !== m.senderId}
            isThreadReply
            onEdited={(u) => setReplies((p) => p?.map((x) => (x.id === u.id ? { ...x, ...u } : x)) ?? null)}
            onDeleted={(id) => setReplies((p) => p?.map((x) => (x.id === id ? { ...x, deletedAt: new Date().toISOString() } : x)) ?? null)}
          />
        ))}
      </div>
      <Composer placeholder="Reply in thread…" onSend={sendReply} channelId={channelId} conversationId={conversationId} threadMode />
    </aside>
  );
}