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

67.3% Statements 35/52
68.18% Branches 45/66
57.14% Functions 8/14
71.42% Lines 35/49

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                                      1x                                                   1x                     1x 2x 2x               2x                           1x                   10x 10x 10x   10x 8x 8x       10x   10x 2x 2x 2x     10x   1x             1x     2x       2x 2x                                       4x   4x             1x                     1x                         2x   1x                                                                               1x                                           2x 2x     2x         2x                                            
import React, { useEffect, useState } from 'react';
import Animated, {
  useAnimatedStyle,
  useSharedValue,
  withDelay,
  withRepeat,
  withSequence,
  withTiming,
} from 'react-native-reanimated';
import { ActivityIndicator, Pressable, Text, TouchableOpacity, View } from 'react-native';
 
import { StopIcon, TickCircleIcon } from '@repo/ui/icons';
import { useTheme } from '@repo/ui/themes';
 
import { Block } from '@/types/chat';
 
import { useStyles } from './styles';
import { TableUserRow } from './TableUserRow';
 
const Dot = ({ delay }: { delay: number }) => {
  const styles = useStyles();
  const translateY = useSharedValue(0);
 
  React.useEffect(() => {
    translateY.value = withDelay(
      delay,
      withRepeat(
        withSequence(
          withTiming(-6, { duration: 300 }),
          withTiming(0, { duration: 300 }),
          withTiming(0, { duration: 600 }),
        ),
        -1,
        false,
      ),
    );
  }, [delay, translateY]);
 
  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateY: translateY.value }],
  }));
 
  return <Animated.View style={[styles.dot, animatedStyle]} />;
};
 
const ThinkingDots = () => {
  const styles = useStyles();
  return (
    <View style={styles.thinkingContainer}>
      <Dot delay={0} />
      <Dot delay={150} />
      <Dot delay={300} />
    </View>
  );
};
 
const getMeaningfulMessage = (suggestion: string): string => {
  const lowerItem = suggestion.toLowerCase().trim();
  const map: Record<string, string> = {
    'user list': 'I would like to see the on-behalf user list',
    'manager list': 'I would like to see the on-behalf manager list',
    add: 'Could you help me add people to the list?',
    edit: 'Could you help me edit people in the list?',
    remove: 'Could you help me remove people from the list?',
  };
 
  return map[lowerItem] || suggestion;
};
 
interface ChatBlockProps {
  block: Block;
  msgId: string;
  pendingAction: any;
  isActionProcessing?: boolean;
  onSend: (text?: string) => void;
  onReset: () => void;
  handleAction: (msgId: string, actionId: string, type: 'confirm' | 'cancel') => void;
  onSuggestionPress?: () => void;
}
 
export const ChatBlock: React.FC<ChatBlockProps> = ({
  block,
  msgId,
  pendingAction,
  isActionProcessing,
  onSend,
  onReset,
  handleAction,
  onSuggestionPress,
}) => {
  const styles = useStyles();
  const theme = useTheme();
  const [submittingType, setSubmittingType] = useState<'confirm' | 'cancel' | null>(null);
 
  useEffect(() => {
    Eif (!isActionProcessing) {
      setSubmittingType(null);
    }
  }, [isActionProcessing]);
 
  const isLoading = isActionProcessing || submittingType !== null;
 
  const handleActionWithInstantFeedback = (type: 'confirm' | 'cancel') => {
    Iif (isLoading) return;
    setSubmittingType(type);
    handleAction(msgId, pendingAction.id, type);
  };
 
  switch (block.type) {
    case 'text':
      return (
        <View>
          {block.text ? <Text style={styles.blockText}>{block.text}</Text> : null}
          {block.isStreaming && <ThinkingDots />}
        </View>
      );
    case 'suggestions':
      return (
        <View style={styles.blockSuggestions}>
          {block.items?.map((item, i) => (
            <TouchableOpacity
              key={i}
              style={styles.suggestionItem}
              onPress={() => {
                onSend(getMeaningfulMessage(item));
                onSuggestionPress?.();
              }}
            >
              <Text style={styles.suggestionText}>{item}</Text>
            </TouchableOpacity>
          ))}
        </View>
      );
    case 'table':
      return (
        <View style={styles.blockTable}>
          {block.title && <Text style={styles.tableTitle}>{block.title}</Text>}
          {block.rows?.map((row, i) => (
            <View key={i} style={styles.tableRow}>
              <TableUserRow row={row} />
            </View>
          ))}
        </View>
      );
    case 'confirmation':
      Iif (!pendingAction) return null;
 
      return (
        <View style={styles.blockConfirmation}>
          <Text style={styles.confirmationTitle}>{block.title || 'Please confirm'}</Text>
          <Text style={styles.confirmationDesc}>{block.description}</Text>
          <View style={styles.actionRow}>
            <Pressable
              style={[styles.confirmBtn, isLoading && styles.disabledSendBtn]}
              onPress={() => handleActionWithInstantFeedback('confirm')}
              disabled={isLoading}
            >
              {submittingType === 'confirm' || (isLoading && submittingType === null) ? (
                <ActivityIndicator color={theme.theme.colors.white} />
              ) : (
                <Text style={styles.confirmText}>Confirm</Text>
              )}
            </Pressable>
            <Pressable
              style={[styles.cancelBtn, isLoading && styles.disabledSendBtn]}
              onPress={() => handleActionWithInstantFeedback('cancel')}
              disabled={isLoading}
            >
              {submittingType === 'cancel' || (isLoading && submittingType === null) ? (
                <ActivityIndicator color={theme.theme.colors.gray90} />
              ) : (
                <Text style={styles.cancelText}>Cancel</Text>
              )}
            </Pressable>
          </View>
        </View>
      );
    case 'status':
      switch (block.status) {
        case 'success':
          return (
            <View style={styles.successBlockContainer}>
              <View style={styles.successCard}>
                {!!block.title && (
                  <Text style={styles.successCardTitle}>{block.title.toUpperCase()}</Text>
                )}
 
                {block.data && block.data.information && (
                  <View style={styles.successCardBody}>
                    {block.data.information.map((row, i) => (
                      <View key={i} style={styles.tableRow}>
                        <TableUserRow row={row} />
                      </View>
                    ))}
                  </View>
                )}
 
                <View style={styles.successCardFooter}>
                  <Text style={styles.successCardFooterDate}>
                    {`Updated at ${new Date().toLocaleTimeString('en-US', {
                      hour: '2-digit',
                      minute: '2-digit',
                    })} • ${new Date().toLocaleDateString('en-US', {
                      month: 'short',
                      day: 'numeric',
                      year: 'numeric',
                    })}`}
                  </Text>
                </View>
              </View>
 
              <View style={styles.successMessageRow}>
                <TickCircleIcon width={20} height={20} color="#10B981" />
                <Text style={styles.successMessageText}>
                  {block.description || 'Action completed successfully'}
                </Text>
              </View>
            </View>
          );
        case 'cancelled':
          return (
            <View style={styles.blockStatus}>
              <Text style={styles.cancelledText}>
                Looks like someone changed their mind. Operation was cancelled by the user
              </Text>
            </View>
          );
        case 'cancel_stream':
          return (
            <View style={styles.blockStatus}>
              <StopIcon width={24} height={24} />
              <Text style={styles.cancelledText}>{block.title || 'You stopped this response'}</Text>
            </View>
          );
        default:
          return (
            <View style={styles.blockStatus}>
              <Text style={styles.statusText}>{block.title || 'Status'}</Text>
            </View>
          );
      }
    case 'error': {
      const text = block.text?.toLowerCase() || '';
      const message = block.message?.toLowerCase() || '';
 
      const isNetworkError =
        text.includes('http 0:') ||
        message.includes('http 0:') ||
        text.includes('network') ||
        message.includes('network');
 
      return (
        <View>
          <View style={styles.errorHeader}>
            <Text style={styles.errorTitle}>Service Error</Text>
          </View>
 
          <Text style={styles.errorText}>
            {isNetworkError
              ? 'Oops, looks like your connection dropped. Please try again.'
              : block.text || block.message}
          </Text>
 
          <TouchableOpacity style={styles.retryBtn} onPress={onReset}>
            <Text style={styles.retryText}>Reset Thread</Text>
          </TouchableOpacity>
        </View>
      );
    }
    default:
      return null;
  }
};