All files / apps/host/src/components/ChatBox index.tsx

94.91% Statements 56/59
93.58% Branches 73/78
84.21% Functions 16/19
94.64% Lines 53/56

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 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                                    1x 9x 9x                                     9x   9x   9x   1x         9x   9x 9x 3x     9x 9x     9x 9x 7x   6x 6x       6x 6x   6x       9x                                       6x 6x 6x 3x   6x   6x       6x           6x                                         6x 5x     6x 6x               6x 6x   6x 7x 1x 1x     2x                                   1x       6x 3x 2x   1x 1x                                     6x   6x 1x                                       6x                           1x                                                                     1x                                    
import React, { useCallback, useEffect, useRef } from 'react';
import { Bubble, GiftedChat, MessageText } from 'react-native-gifted-chat';
import { KeyboardStickyView } from 'react-native-keyboard-controller';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Platform, TextInput, TouchableOpacity, View } from 'react-native';
 
import { ArrowUpIcon, CameraIcon, ImageIcon, StopIcon } from '@repo/ui/icons';
 
import { Block, ChatMessage } from '@/types/chat';
 
import { BOT, USER } from '../../contexts/ChatContext';
import { LoadingSlider } from '../LoadingSlider';
 
import { ChatBlock } from './ChatBlock';
import { ImagePreview } from './ImagePreview';
import { useStyles } from './styles';
import { useChatBox } from './useChatBox';
 
export const ChatBox = () => {
  const styles = useStyles();
  const insets = useSafeAreaInsets();
  const {
    messages,
    text,
    setText,
    keyboardHeight,
    isStreaming,
    selectedImage,
    setSelectedImage,
    inputRef,
    isInitializing,
    processingActionIds,
    handlePickImage,
    handleLaunchCamera,
    onSend: originalOnSend,
    handleCancel,
    onReset,
    handleAction,
    initThread,
  } = useChatBox();
 
  const giftedChatRef = useRef<any>(null);
 
  const onSend = useCallback(
    (value?: string) => {
      originalOnSend(value);
    },
    [originalOnSend],
  );
 
  const inputBottomPadding = Platform.OS === 'ios' ? 20 : insets.bottom + 8;
 
  useEffect(() => {
    if (messages.length > 0) {
      giftedChatRef.current?.scrollToOffset({ offset: 0, animated: true });
    }
  }, [messages]);
  useEffect(() => {
    initThread();
  }, [initThread]);
 
  const filteredMessages = React.useMemo(() => {
    return messages.filter(m => {
      if (m.user._id !== BOT._id) return true;
 
      const hasConfirmationBlock = m.blocks?.some(b => b.type === 'confirmation');
      const isResolvedExplicitConfirmation = hasConfirmationBlock && !m.pendingAction;
 
      // Also hide "fallback" confirmation messages that have no blocks or text once resolved
      const hasNoContent =
        (!m.blocks || m.blocks.length === 0) && (!m.text || m.text.trim() === '');
      const isResolvedFallback = hasNoContent && !m.pendingAction;
 
      return !isResolvedExplicitConfirmation && !isResolvedFallback;
    });
  }, [messages]);
 
  return (
    <View style={styles.container}>
      {/* Header is now managed by BottomSheetModal handleComponent */}
 
      <View style={[styles.chatView, { paddingBottom: keyboardHeight }]}>
        {messages.length === 0 && isInitializing ? (
          <View style={styles.loadingContainer}>
            <LoadingSlider width={70} height={70} />
          </View>
        ) : (
          <GiftedChat
            messagesContainerRef={giftedChatRef}
            messages={filteredMessages}
            user={USER}
            renderInputToolbar={() => null}
            renderAvatar={null}
            renderDay={() => null}
            renderTime={() => null}
            messagesContainerStyle={styles.messagesContainer}
            renderBubble={props => {
              const chatMsg = props.currentMessage as ChatMessage;
              const isImageOnly = !!chatMsg.image && !chatMsg.text;
              const hasConfirmationBlock = Boolean(
                chatMsg.blocks?.some(block => block.type === 'confirmation'),
              );
              const hasBlocks = Boolean(chatMsg.blocks && chatMsg.blocks.length > 0);
              const shouldRenderPendingActionFallback =
                chatMsg.user._id === BOT._id &&
                chatMsg.pendingAction?.id &&
                chatMsg.pendingAction?.status === 'awaiting_confirmation' &&
                !hasConfirmationBlock;
              const pendingActionFallbackBlock: Block = {
                type: 'confirmation',
                title: 'Please confirm',
                description: 'Confirm or cancel this pending action.',
              };
 
              return (
                <Bubble
                  {...props}
                  textStyle={{
                    right: styles.userText,
                  }}
                  wrapperStyle={{
                    right: [
                      styles.userBubble,
                      isImageOnly
                        ? { backgroundColor: 'transparent', padding: 0, minHeight: 0 }
                        : {},
                    ],
                    left: [
                      styles.botBubble,
                      hasBlocks || shouldRenderPendingActionFallback
                        ? { backgroundColor: 'transparent', padding: 0 }
                        : {},
                    ],
                  }}
                  renderMessageText={bubbleProps => {
                    if (hasBlocks) return null;
                    return <MessageText {...bubbleProps} />;
                  }}
                  renderCustomView={() => {
                    const blocks = chatMsg.blocks || [];
                    const bubbleBlockTypes = [
                      'text',
                      'suggestions',
                      'table',
                      'confirmation',
                      'error',
                    ];
 
                    const elements: React.ReactNode[] = [];
                    let currentBubble: Block[] = [];
 
                    const flushBubble = () => {
                      if (currentBubble.length > 0) {
                        const bubbleKey = `bubble-${elements.length}`;
                        elements.push(
                          <View key={bubbleKey} style={styles.bubbleContainer}>
                            {currentBubble.map((b, i) => (
                              <ChatBlock
                                key={i}
                                block={b}
                                msgId={chatMsg._id as string}
                                pendingAction={chatMsg.pendingAction}
                                isActionProcessing={
                                  !!(
                                    chatMsg.pendingAction?.id &&
                                    processingActionIds.includes(chatMsg.pendingAction.id)
                                  )
                                }
                                onSend={onSend}
                                onReset={onReset}
                                handleAction={handleAction}
                              />
                            ))}
                          </View>,
                        );
                        currentBubble = [];
                      }
                    };
 
                    blocks.forEach(block => {
                      if (bubbleBlockTypes.includes(block.type)) {
                        currentBubble.push(block);
                      } else {
                        flushBubble();
                        elements.push(
                          <ChatBlock
                            key={`standalone-${elements.length}`}
                            block={block}
                            msgId={chatMsg._id as string}
                            pendingAction={chatMsg.pendingAction}
                            isActionProcessing={
                              !!(
                                chatMsg.pendingAction?.id &&
                                processingActionIds.includes(chatMsg.pendingAction.id)
                              )
                            }
                            onSend={onSend}
                            onReset={onReset}
                            handleAction={handleAction}
                          />,
                        );
                      }
                    });
                    flushBubble();
 
                    if (shouldRenderPendingActionFallback) {
                      elements.push(
                        <View key="fallback-bubble" style={styles.bubbleContainer}>
                          <ChatBlock
                            block={pendingActionFallbackBlock}
                            msgId={chatMsg._id as string}
                            pendingAction={chatMsg.pendingAction}
                            isActionProcessing={
                              !!(
                                chatMsg.pendingAction?.id &&
                                processingActionIds.includes(chatMsg.pendingAction.id)
                              )
                            }
                            onSend={onSend}
                            onReset={onReset}
                            handleAction={handleAction}
                          />
                        </View>,
                      );
                    }
 
                    return elements.length > 0 ? (
                      <View style={chatMsg.user._id === BOT._id ? styles.botBlocksContainer : {}}>
                        {elements}
                      </View>
                    ) : null;
                  }}
                />
              );
            }}
          />
        )}
      </View>
 
      <KeyboardStickyView offset={{ opened: 0 }} style={styles.interactiveSticky}>
        <ImagePreview uri={selectedImage?.uri || null} onRemove={() => setSelectedImage(null)} />
 
        <View style={[styles.inputRow, { paddingBottom: inputBottomPadding }]}>
          <View style={styles.plusMenuContainer}>
            <TouchableOpacity
              testID="chat-pick-image-button"
              onPress={handlePickImage}
              style={[(isStreaming || isInitializing) && styles.disabledSendBtn]}
              disabled={isStreaming || isInitializing}
            >
              <ImageIcon width={24} height={24} />
            </TouchableOpacity>
            <TouchableOpacity
              testID="chat-launch-camera-button"
              onPress={handleLaunchCamera}
              style={[(isStreaming || isInitializing) && styles.disabledSendBtn]}
              disabled={isStreaming || isInitializing}
            >
              <CameraIcon width={24} height={24} />
            </TouchableOpacity>
          </View>
 
          <TextInput
            ref={inputRef}
            value={text}
            onChangeText={setText}
            placeholder="Ask Flash Bot"
            placeholderTextColor="#888"
            style={styles.input}
            multiline
            autoFocus
          />
 
          <TouchableOpacity
            testID="chat-send-button"
            onPress={isStreaming ? handleCancel : () => onSend()}
            disabled={!isStreaming && !text.trim() && !selectedImage && isInitializing}
          >
            <View
              style={[!isStreaming && !text.trim() && !selectedImage && styles.disabledSendBtn]}
            >
              {isStreaming ? (
                <StopIcon width={32} height={32} />
              ) : (
                <ArrowUpIcon width={32} height={32} color="#fff" />
              )}
            </View>
          </TouchableOpacity>
        </View>
      </KeyboardStickyView>
    </View>
  );
};