개발/React

리액트 - 채팅방 들어오고 나갈 때 표시하기 (Message Separator)

피로물든딸기 2024. 3. 31. 00:33
반응형

리액트 전체 링크

 

참고

- https://chatscope.io/storybook/react/?path=/docs/components-messageseparator--docs

 

chat-ui-kit-react로 채팅창 UI 만들기
로그인 + 채팅방 UI 만들기
채팅방 변경하기
채팅방 들어오고 나갈 때 표시하기
Socket.IO로 채팅하기
Socket.IO Room으로 채팅방 관리하기
Socket.IO namespace로 채팅방 관리하기
Socket.IO로 중복 로그인 제한하기

- Socket.IO Middleware로 중복 로그인 방지하기

 

채팅방을 들어오거나 나갈 때, separator를 이용해 표시해 보자.


MessageSeparator 추가하기

 

먼저 MessageList에 임의로 Separator를 추가해 보자.

  <MessageList>
    {getMessageComponent(messages)}
    <MessageSeparator content="Joe has entered the chatroom." />
    <MessageSeparator content="Joe has left the chatroom." />
  </MessageList>

 

다음과 같이 채팅창에 이 추가 된다.

 

이제 기본 메시지는 모두 빈 메시지로 처리하자.

const defaultMessage = [];
const defaultMessagePatrik = [];
const totalMessages = [defaultMessage, defaultMessagePatrik];

 

getMessageComponenttype에 따라 Separator를 만들거나 기존 Messagereturn하면 된다.

  const getMessageComponent = (totalMessages) => {
    let data = totalMessages[activeID];

    return data.map((item, index) => {
      return item.type === "separator" ? (
        <MessageSeparator key={index} content={item.content} />
      ) : (
        <Message key={index} model={item.model}>
          {item.avatar ? (
            <Avatar src={item.avatar.src} name={item.avatar.name} />
          ) : null}
        </Message>
      );
    });
  };

 

여기서는 방을 변경할 때, 채팅방을 나가는 것으로 가정한다.

같은 방을 클릭할 경우에는 아무 이벤트도 발생하지 않는다.

  const changeRoom = (index) => {
    if(activeID === index) return;
    
    let leftSeparator = {
      type : "separator",
      content : `${loginID} has left the chatroom.`,
    }

    let enterSeparator = {
      type : "separator",
      content : `${loginID} has entered the chatroom.`,
    }

    let temp = [...totalMessages];
    temp[activeID].push(leftSeparator);
    temp[index].push(enterSeparator);

    setMessages(temp);
    setActiveID(index);
  }

  const getConversationComponent = (data) => {
    return data.map((item, index) => {
      return (
        <Conversation
          ...
          onClick={() => changeRoom(index)}
        >
          <Avatar name={item.name} src={item.src} status={item.status} />
        </Conversation>
      );
    });
  };

 

마지막으로 최초 진입 시, 넘겨 받은 loginIDSeparator를 만들면 된다.

  const init = () => {
    setLoginID(location.state.loginID);

    let enterSeparator = {
      type : "separator",
      content : `${location.state.loginID} has entered the chatroom.`,
    }

    let temp = [...totalMessages];
    temp[activeID].push(enterSeparator);

    setMessages(temp);    
  };

 

전체 코드는 다음과 같다.

import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";

import styles from "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";

import {
  MainContainer,
  ChatContainer,
  MessageList,
  Message,
  MessageInput,
  Avatar,
  Sidebar,
  ConversationList,
  Conversation,
  ConversationHeader,
  VoiceCallButton,
  VideoCallButton,
  InfoButton,
  MessageSeparator,
} from "@chatscope/chat-ui-kit-react";

const AVATAR_IMAGE =
  "https://img1.daumcdn.net/thumb/C428x428/?scode=mtistory2&fname=https%3A%2F%2Ftistory3.daumcdn.net%2Ftistory%2F4431109%2Fattach%2F3af65be1d8b64ece859b8f6d07fafadc";

const AVATAR_MAP = {
  Lilly: "https://chatscope.io/storybook/react/assets/lilly-aj6lnGPk.svg",
  Joe: "https://chatscope.io/storybook/react/assets/joe-v8Vy3KOS.svg",
  Emily: "https://chatscope.io/storybook/react/assets/emily-xzL8sDL2.svg",
  Akane: "https://chatscope.io/storybook/react/assets/akane-MXhWvx63.svg",
  Eliot: "https://chatscope.io/storybook/react/assets/eliot-JNkqSAth.svg",
  Zoe: "https://chatscope.io/storybook/react/assets/zoe-E7ZdmXF0.svg",
};

const defaultMessage = [];
const defaultMessagePatrik = [];
const totalMessages = [defaultMessage, defaultMessagePatrik];

const defaultConversation = [
  {
    info: "",
    lastSenderName: "bloodstrawberry",
    name: "bloodstrawberry",
    src: AVATAR_IMAGE,
    status: "available",
  },
  {
    info: "",
    lastSenderName: "Patrik",
    name: "Patrik",
    src: "https://chatscope.io/storybook/react/assets/patrik-yC7svbAR.svg",
    status: "invisible",
  },
];

const ChatUI = () => {
  const location = useLocation();
  const [loginID, setLoginID] = useState("");

  const [activeID, setActiveID] = useState(0);
  const [messages, setMessages] = useState(totalMessages);

  const getMessageComponent = (totalMessages) => {
    let data = totalMessages[activeID];

    return data.map((item, index) => {
      return item.type === "separator" ? (
        <MessageSeparator key={index} content={item.content} />
      ) : (
        <Message key={index} model={item.model}>
          {item.avatar ? (
            <Avatar src={item.avatar.src} name={item.avatar.name} />
          ) : null}
        </Message>
      );
    });
  };

  const changeRoom = (index) => {
    if(activeID === index) return;
    
    let leftSeparator = {
      type : "separator",
      content : `${loginID} has left the chatroom.`,
    }

    let enterSeparator = {
      type : "separator",
      content : `${loginID} has entered the chatroom.`,
    }

    let temp = [...totalMessages];
    temp[activeID].push(leftSeparator);
    temp[index].push(enterSeparator);

    setMessages(temp);
    setActiveID(index);
  }

  const getConversationComponent = (data) => {
    return data.map((item, index) => {
      return (
        <Conversation
          key={index}
          active={index === activeID}
          info={item.info}
          lastSenderName={item.lastSenderName}
          name={item.name}
          onClick={() => changeRoom(index)}
        >
          <Avatar name={item.name} src={item.src} status={item.status} />
        </Conversation>
      );
    });
  };

  const handleSend = (input) => {
    let newMessage = {
      model: {
        message: input,
        direction: "outgoing",
      },
    };

    let temp = [...totalMessages];
    temp[activeID].push(newMessage);
    setMessages(temp);
  };

  const init = () => {
    setLoginID(location.state.loginID);

    let enterSeparator = {
      type : "separator",
      content : `${location.state.loginID} has entered the chatroom.`,
    }

    let temp = [...totalMessages];
    temp[activeID].push(enterSeparator);

    setMessages(temp);    
  };

  useEffect(init, []);

  return (
    <div>
      <Conversation
        info="I'm fine, thank you, and you?"
        lastSenderName={loginID}
        name={loginID}
      >
        <Avatar name={loginID} src={AVATAR_MAP[loginID]} status="available" />
      </Conversation>
      <MessageSeparator style={{ marginTop: 5, marginBottom: 5 }} />
      <MainContainer
        responsive
        style={{
          height: "600px",
        }}
      >
        <Sidebar position="left">
          <ConversationList>
            {getConversationComponent(defaultConversation)}
          </ConversationList>
        </Sidebar>
        <ChatContainer>
          <ConversationHeader>
            <ConversationHeader.Back />
            <Avatar
              name={defaultConversation[activeID].name}
              src={defaultConversation[activeID].src}
            />
            {activeID === 0 ? (
              <ConversationHeader.Content
                info="Active 10 mins ago"
                userName="bloodstrawberry"
              />
            ) : (
              <ConversationHeader.Content
                info="Active 7 hours ago"
                userName="Patrik"
              />
            )}
            <ConversationHeader.Actions>
              <VoiceCallButton />
              <VideoCallButton />
              <InfoButton />
            </ConversationHeader.Actions>
          </ConversationHeader>
          <MessageList>
            {getMessageComponent(messages)}
          </MessageList>

          <MessageInput placeholder="Type message here" onSend={handleSend} />
        </ChatContainer>
      </MainContainer>
    </div>
  );
};

export default ChatUI;
반응형