All files / src/components/assistant AiAssistantChatMessage.tsx

6.55% Statements 4/61
0% Branches 0/56
0% Functions 0/20
7.84% Lines 4/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                            1x   1x   1x                                                   1x                                                                                                                                                                                                                                                                  
import React, { ReactElement, useEffect } from "react";
import { Divider } from "antd";
import { Avatar, Bubble, Flex, FlexItem, Typing } from "@chatui/core";
import { stopPropagationAndPreventDefault } from "@utils/ObjectUtils";
import { CheckOutlined, CopyOutlined, InfoCircleOutlined, LoadingOutlined, ReloadOutlined } from "@ant-design/icons";
import { isPendingMessage, isReceivedMessage, isSystemMessage, Message, ReceivedMessage } from "../chat/ChatBox";
import { copyToClipBoard } from "@utils/StringUtils";
import {
  AssistantFailedReplyMessageContent,
  AssistantMessageContent,
  isAssistantAskMessageContent,
  isAssistantFailedReplyMessageContent,
  isAssistantReplyMessageContent,
  isAssistantSuccessReplyMessageContent
} from "./AiAssistantComponent";
import { ChatMessageProps } from "./FetchUtils";
import { useTranslation } from "react-i18next";
import "./AiAssistant.less";
import { AvatarData } from "@utils/FetchUtilsProps";
import { getAvatarForUser } from "@utils/FetchUtils";
import ReactMarkdownWrap from "../wrap/ReactMarkdownWrap";
 
const DefaultAvatarImageSrc = "/images/default-avatar.svg";
 
const userAvatarDataCache: Record<number, Promise<AvatarData>> = {};
 
export const getAvatarDataOfUser = (userId: number): Promise<AvatarData> => {
  const promise = userAvatarDataCache[userId];
  if (promise) {
    return promise;
  }
  userAvatarDataCache[userId] = getAvatarForUser(userId).then((data) => ({
    ...data,
    avatar: data.avatar || DefaultAvatarImageSrc,
    name: undefined,
  }));
  return userAvatarDataCache[userId];
};
 
export interface AiAssistantChatMessageProps {
  // key: string;
  msg: Message<AssistantMessageContent>;
  reAsk: (message: ReceivedMessage<AssistantFailedReplyMessageContent>) => Promise<ChatMessageProps> | undefined;
  barrierIndex?: number;
}
 
interface ChatMessageOptions {
  inRetry: boolean;
  inHover: boolean;
  inCopy: boolean;
}
 
const AiAssistantChatMessage = (props: AiAssistantChatMessageProps): ReactElement => {
  const { msg, reAsk, barrierIndex } = props;
  const [chatMessageOptions, setChatMessageOptions] = React.useState<ChatMessageOptions>({
    inRetry: false,
    inHover: false,
    inCopy: false,
  });
  const { content, user, position } = msg;
  const { t } = useTranslation();
  const [avatarData, setAvatarData] = React.useState<AvatarData | undefined>(undefined);
 
  useEffect(() => {
    getAvatarDataOfUser(user.id).then((data) => setAvatarData(data));
  }, [user.id]);
 
  const options: JSX.Element[] = [];
  const copyOption = (text: string): JSX.Element => <div
    key="copyIcon"
    style={{
      display: "flex",
      flexDirection: "row",
    }}
    onClick={() => {
      setChatMessageOptions((prev) => ({ ...prev, inCopy: true }));
      copyToClipBoard(text).finally(() => setTimeout(() =>
        setChatMessageOptions((prev) => ({ ...prev, inCopy: false })), 3000));
    }}
  >
    <CopyOutlined className="assistant-panel-msg-options-item" style={{
      opacity: chatMessageOptions.inHover && !chatMessageOptions.inCopy ? 1 : 0,
      transitionDuration: "0.2s",
      transitionTimingFunction: "ease-out",
    }} />
    <CheckOutlined className="assistant-panel-msg-options-item" style={{
      marginLeft: -15,
      opacity: chatMessageOptions.inCopy ? 1 : 0,
      transitionDuration: "0.2s",
      transitionTimingFunction: "ease-out",
      color: "#2eed2e",
    }} />
  </div>;
 
  const divider = isReceivedMessage(msg) && msg.index === barrierIndex
    ? <Divider style={{ width: "100%" }}>
      <div style={{ opacity: 0.3 }}>{t("assistant:New conversation")}</div>
    </Divider>
    : undefined;
 
  let contentText = undefined;
  let isTypingMessage = false;
  if (isSystemMessage(msg)) {
    isTypingMessage = true;
  } else if (isAssistantAskMessageContent(content)) {
    if (isPendingMessage(msg)) {
      if (msg.status === "pending") {
        options.push(<LoadingOutlined key="sendingIcon" className="assistant-panel-msg-options-item" />);
      }
      if (msg.status === "fail") {
        options.push(<InfoCircleOutlined key="sentFailedIcon" className="assistant-panel-msg-options-item" />);
      }
    } else {
      options.push(copyOption(content.ask));
    }
    contentText = content.ask;
  } else if (isAssistantReplyMessageContent(content) && isReceivedMessage(msg)) {
    if (isAssistantFailedReplyMessageContent(content)) {
      contentText = content.errMsg;
      if (!content.forbiddenRetry) {
        options.push(<ReloadOutlined
          key="reAskIcon"
          spin={chatMessageOptions.inRetry}
          className="assistant-panel-msg-options-item"
          onClick={() => {
            setChatMessageOptions((prev) => ({ ...prev, inRetry: true }));
            reAsk(msg as ReceivedMessage<AssistantFailedReplyMessageContent>)?.finally(() =>
              setChatMessageOptions((prev) => ({ ...prev, inRetry: false })));
          }} />);
      }
    } else if (isAssistantSuccessReplyMessageContent(content)) {
      options.push(copyOption(content.reply));
      contentText = content.reply;
    }
  }
 
  const messageContent = chatMessageOptions.inRetry || isTypingMessage ?
    (<Typing />) : (<Bubble
                      type="text"
                      content={<ReactMarkdownWrap
                                 className="chatbox-react-wrap"
                      >
                                 {contentText ?? ""}
                               </ReactMarkdownWrap>}
                    />);
 
  const isLeftPos = (position === "left");
 
  return <Flex
    className={isLeftPos ? "assistant-panel-msg-container-left" : "assistant-panel-msg-container-right"}
    onMouseEnter={() => setChatMessageOptions((prev) => ({ ...prev, inHover: true }))}
    onMouseLeave={() => setChatMessageOptions((prev) => ({ ...prev, inHover: false }))}
    onClick={(e) => stopPropagationAndPreventDefault(e)}
  >
    <Flex
      className={isLeftPos ? "chatMessage-left" : "chatMessage-right"}
    >
      <div className={isLeftPos ? "assistant-panel-msg-avatar-left" : "assistant-panel-msg-avatar-right"}>
        <Avatar src={avatarData?.avatar} shape="square" size="sm" />
      </div>
      <FlexItem>
        <div style={{
          marginRight: isLeftPos ? -72 : 0,
          marginLeft: (!isLeftPos) ? -72 : 0,
        }}>
          {messageContent}
        </div>
      </FlexItem>
      <Flex className="assistant-panel-msg-options" style={{
        marginRight: (!isLeftPos) ? 35 : 0,
        marginLeft: isLeftPos ? 30 : 0,
        alignItems: isLeftPos ? "flex-start" : "flex-end",
      }}>
        {options}
      </Flex>
    </Flex>
    {divider}
  </Flex>;
};
 
export default AiAssistantChatMessage;