All files / apps/chatbot/src/components/MessageList MessageItem.tsx

100% Statements 38/38
95.83% Branches 46/48
100% Functions 9/9
100% Lines 34/34

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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206                                  2x                         2x 22x   2x 4x 4x   4x                               2x           18x 18x   18x   14x 14x   14x         14x             14x     14x   14x 13x                     14x   11x 1x     10x 11x   10x           10x   11x                                   14x 14x       14x 4x 1x                 10x             22x                                                                                                      
import React from "react";
import Animated, { Easing, FadeInDown } from "react-native-reanimated";
import { Image, Text, View } from "react-native";
 
import { makeStyles } from "@repo/ui/themes/makeStyles";
import { textStyles } from "@repo/ui/themes/typography";
 
import { useStyles as useSharedStyles } from "@/components/styles";
 
import { groupBlocks } from "@/utils/blockGrouping";
 
import { BOT, USER } from "@/constants/chat";
 
import { Block, ChatMessage } from "@/types/chat";
 
import { ChatBlock } from "./blocks";
 
const PENDING_ACTION_FALLBACK_BLOCK: Block = {
  type: "confirmation",
  title: "Please confirm",
  description: "Confirm or cancel this pending action.",
};
 
interface MessageItemProps {
  message: ChatMessage;
  processingActionIds: string[];
  onReset: () => void;
  handleAction: (msgId: string, actionId: string, type: "confirm" | "cancel") => void;
}
 
const isEmptyStreamingText = (block: Block) =>
  block.type === "text" && !block.text?.trim() && !!block.isStreaming;
 
const UserMessage = ({ message }: { message: ChatMessage }) => {
  const styles = useStyles();
  const isImageOnly = !!message.image && !message.text;
 
  return (
    <Animated.View
      entering={FadeInDown.duration(800).easing(Easing.out(Easing.ease))}
      style={styles.userMessageContainer}
    >
      {isImageOnly && message.image ? (
        <Image source={{ uri: message.image }} style={styles.userImage} />
      ) : (
        <View style={styles.userBubble}>
          <Text style={styles.userText}>{message.text.trim()}</Text>
        </View>
      )}
    </Animated.View>
  );
};
 
export const MessageItem = ({
  message,
  processingActionIds,
  onReset,
  handleAction,
}: MessageItemProps) => {
  const shared = useSharedStyles();
  const styles = useStyles();
 
  if (message.user._id === USER._id) return <UserMessage message={message} />;
 
  const blocks = message.blocks || [];
  const hasConfirmationBlock = blocks.some((b) => b.type === "confirmation");
  const shouldRenderPendingActionFallback =
    message.user._id === BOT._id &&
    !!message.pendingAction?.id &&
    message.pendingAction?.status === "awaiting_confirmation" &&
    !hasConfirmationBlock;
 
  const isActionProcessing = !!(
    message.pendingAction?.id && processingActionIds.includes(message.pendingAction.id)
  );
 
  // An expired confirmation renders as plain text (see ConfirmationBlock), so
  // it must get the hugging bubble — only live confirmations need a wide card.
  const expiresAtMs =
    typeof message.pendingAction?.expiresAt === "string"
      ? Date.parse(message.pendingAction.expiresAt)
      : NaN;
  const isConfirmationExpired = !Number.isNaN(expiresAtMs) && expiresAtMs <= Date.now();
 
  const renderBlock = (block: Block, key: string) => (
    <ChatBlock
      key={key}
      block={block}
      msgId={message._id as string}
      pendingAction={message.pendingAction ?? null}
      isActionProcessing={isActionProcessing}
      onReset={onReset}
      handleAction={handleAction}
    />
  );
 
  const renderedElements = [
    ...groupBlocks(blocks).map((group, index) => {
      if (group.kind === "standalone") {
        return renderBlock(group.block, `standalone-${index}`);
      }
 
      const hasWideBlock = group.blocks.some(
        (b) => b.type === "table" || (b.type === "confirmation" && !isConfirmationExpired),
      );
      const bubbleStyle = group.blocks.every(isEmptyStreamingText)
        ? shared.emptyStreamingContainer
        : hasWideBlock
          ? shared.bubbleContainerWide
          : shared.bubbleContainer;
 
      return (
        <View key={`bubble-${index}`} style={bubbleStyle}>
          {group.blocks.map((b, i) => renderBlock(b, String(i)))}
        </View>
      );
    }),
    ...(shouldRenderPendingActionFallback
      ? [
          <View
            key="fallback-bubble"
            style={isConfirmationExpired ? shared.bubbleContainer : shared.bubbleContainerWide}
          >
            {renderBlock(PENDING_ACTION_FALLBACK_BLOCK, "fallback")}
          </View>,
        ]
      : []),
  ];
 
  // A bot turn that is still streaming its first token enters slightly later so
  // the thinking shimmer is not immediately shoved aside by the real bubble.
  const isThinking = message.user._id === BOT._id && blocks.some(isEmptyStreamingText);
  const enteringAnimation = isThinking
    ? FadeInDown.delay(350).duration(600).easing(Easing.out(Easing.ease))
    : FadeInDown.duration(800).easing(Easing.out(Easing.ease));
 
  if (renderedElements.length === 0) {
    if (!message.text) return null;
    return (
      <Animated.View entering={enteringAnimation} style={styles.botMessageContainer}>
        <View style={shared.bubbleContainer}>
          <Text style={shared.blockText}>{message.text}</Text>
        </View>
      </Animated.View>
    );
  }
 
  return (
    <Animated.View entering={enteringAnimation} style={styles.botBlocksContainer}>
      {renderedElements}
    </Animated.View>
  );
};
 
const useStyles = makeStyles((theme) => ({
  userMessageContainer: {
    flexDirection: "row",
    justifyContent: "flex-end",
    paddingHorizontal: 12,
    paddingVertical: 10,
    width: "100%",
  },
  userImage: {
    width: 192,
    height: 144,
    borderRadius: 12,
  },
  userBubble: {
    backgroundColor: theme.isNewTheme
      ? theme.colors.background.selectedStrong
      : theme.colors.slate97,
    borderTopLeftRadius: 18,
    borderTopRightRadius: 18,
    borderBottomLeftRadius: 18,
    borderBottomRightRadius: 4,
    paddingVertical: 10,
    paddingHorizontal: 16,
    maxWidth: "80%",
    shadowColor: theme.colors.shadow.black,
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.05,
    shadowRadius: 2,
    elevation: 1,
  },
  userText: {
    ...textStyles.content.regular,
    fontSize: 15,
    color: theme.colors.text.white,
    lineHeight: 20,
  },
  botMessageContainer: {
    flexDirection: "row",
    justifyContent: "flex-start",
    paddingHorizontal: 12,
    paddingVertical: 10,
    width: "100%",
  },
  botBlocksContainer: {
    gap: 8,
    width: "100%",
    paddingHorizontal: 12,
    paddingVertical: 10,
    alignItems: "flex-start",
  },
}));