All files / widgets/Chatbox/mobile Chatbox.native.tsx

52.02% Statements 77/148
58.33% Branches 63/108
36.84% Functions 7/19
54.22% Lines 77/142

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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558                                                                    1x 1x   1x         1x                                             9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x 9x     9x 9x   9x                         9x   9x                         9x 5x                                                   9x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x       9x       9x               9x       9x                                                                           9x         9x                           9x                                       9x 3x                                                                                                 9x           9x 5x 5x           9x 5x 5x 5x 5x 5x 5x 5x 5x                                 9x 5x 5x 5x 5x 5x 5x 5x 5x       9x 9x                                                                                                                                                                                                                                                                                                                   1x                                                                                          
import React from 'react';
import { ChatboxNativeProps, MessageType } from './Chatbox.native.types';
import {
  Dimensions,
  Platform,
  Pressable,
  ScrollView,
  StyleSheet,
  Text,
  useWindowDimensions,
  View,
} from 'react-native';
import {
  Chat,
  PaperclipIcon,
  User,
  X,
  XFill,
} from '@sb/ui/components/atoms/Icons/mobile/Icons.native';
import { colors } from '@sb/styles/colors';
import Animated, { useAnimatedStyle, useSharedValue, withSpring } from 'react-native-reanimated';
import { cn } from '@sb/libs';
import { useTheme } from '@sb/ui/components/Themes/ThemeProvider';
import { Input } from '@sb/ui/components/atoms/Input/mobile/Input.native';
import { Button } from '@sb/ui/components/atoms/Button/mobile/Button.native';
import EmojiPicker from 'rn-emoji-picker';
import { emojis } from 'rn-emoji-picker/dist/data';
import { Emoji } from 'rn-emoji-picker/dist/interfaces';
import { launchImageLibraryAsync, MediaTypeOptions } from 'expo-image-picker';
import { useChatBox } from '@sb/hooks/pages/useChatBox';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { chatStore } from '@sb/stores';
 
const screen = Dimensions.get('screen');
const closedWidth = 60;
 
const clamp = (value: number, min: number, max: number) => {
  'worklet';
  return Math.min(Math.max(value, min), max);
};
 
export const ChatBox: React.FC<ChatboxNativeProps> = ({
  id = 'chatbox',
  className,
  messages,
  headerTemplate,
  footerTemplate,
  headerClassName,
  footerClassName,
  inputPlaceholder = 'Type a message…',
  sendButtonLabel = 'Send',
  showTypingIndicator = false,
  isVisible = false,
  onSendMessage,
  onShow,
  onHide,
  enableEmojis = false,
  enableAttachments = false,
  messageVariant = 'bubble',
  showHeader = true,
  showFooter = false,
  headerHeight,
  footerHeight,
}) => {
  const insets = useSafeAreaInsets();
  const effectiveHeaderH = headerHeight;
  const effectiveFooterH = footerHeight;
  const width = useSharedValue(60);
  const height = useSharedValue(60);
  const borderRadius = useSharedValue(50);
  const isOpen = useSharedValue(isVisible);
  const [openState, setOpenState] = React.useState(isVisible);
 
  const { width: winW, height: winH } = useWindowDimensions();
  const topOffset = insets.top + (effectiveHeaderH || 0);
  const bottomOffset = effectiveFooterH || insets.bottom;
  const isAndroid = Platform.OS === 'android';
  const baseHeight = isAndroid ? winH : screen.height;
  const openW = screen.width;
  const openH = Math.max(220, baseHeight - topOffset - bottomOffset);
 
  const defaultX = screen.width;
  const defaultY = screen.height - (effectiveFooterH || insets.bottom);
  const translateX = useSharedValue(defaultX);
  const translateY = useSharedValue(defaultY);
  const startX = useSharedValue(0);
  const startY = useSharedValue(0);
 
  // Remember the position of last collapsed chat bubble
  const lastCollapsedX = useSharedValue(defaultX);
  const lastCollapsedY = useSharedValue(defaultY);
 
  const { theme } = useTheme();
 
  const {
    chatMessages,
    inputVal,
    isTyping,
    showEmojiPicker,
    setInputVal,
    handleShowEmojiPicker,
    updateText,
    handleOnSend,
    setShowEmojiPicker,
    setMessage,
  } = useChatBox(messages, isVisible, onSendMessage);
 
  const clampPositionForSize = (collapsedX: number, collapsedY: number, w: number, h: number) => {
    'worklet';
    const anchorRight = collapsedX + closedWidth;
    const anchorBottom = collapsedY + closedWidth;
    const minX = 0;
    const topOffset = insets.top + (effectiveHeaderH || 0);
    const maxX = Math.max(minX, screen.width - w);
    const maxY = Math.max(topOffset, baseHeight - h - (effectiveFooterH || insets.bottom));
    const targetX = clamp(anchorRight - w, minX, maxX);
    const targetY = clamp(anchorBottom - h, topOffset, maxY);
    return { targetX, targetY };
  };
 
  const handleOpen = () => {
    Iif (!isOpen.value) {
      // Save where the bubble currently is
      lastCollapsedX.value = translateX.value;
      lastCollapsedY.value = translateY.value;
 
      const { targetX, targetY } = clampPositionForSize(
        lastCollapsedX.value,
        lastCollapsedY.value,
        openW,
        openH
      );
 
      translateX.value = withSpring(targetX, { damping: 18, stiffness: 160 });
      translateY.value = withSpring(targetY, { damping: 18, stiffness: 160 });
      startX.value = targetX;
      startY.value = targetY;
      width.value = withSpring(openW, { damping: 18, stiffness: 160 });
      height.value = withSpring(openH, { damping: 18, stiffness: 160 });
      borderRadius.value = 0;
      isOpen.value = true;
      setOpenState(true);
      onShow?.();
      chatStore.setState({ isDraggable: false });
    }
  };
 
  const handleClose = () => {
    Eif (isOpen.value) {
      // Animate size down and return to the exact spot where the user opened it
      translateX.value = withSpring(lastCollapsedX.value, { damping: 18, stiffness: 160 });
      translateY.value = withSpring(lastCollapsedY.value, { damping: 18, stiffness: 160 });
      width.value = withSpring(closedWidth, { damping: 18, stiffness: 160 });
      height.value = withSpring(closedWidth, { damping: 18, stiffness: 160 });
      borderRadius.value = withSpring(50, { damping: 18, stiffness: 160 });
      isOpen.value = false;
      setOpenState(false);
      onHide?.();
      chatStore.setState({ isDraggable: true });
    }
  };
 
  const handleDismiss = () => {
    chatStore.getState().close();
  };
 
  const containerAnimateStyle = useAnimatedStyle(() => {
    return {
      width: width.value,
      height: height.value,
      borderRadius: borderRadius.value,
    };
  });
 
  const dragStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: translateX.value }, { translateY: translateY.value }],
  }));
 
  const panGesture = Gesture.Pan()
    .onStart(() => {
      'worklet';
      startX.value = translateX.value;
      startY.value = translateY.value;
    })
    .onUpdate((e) => {
      'worklet';
      if (isOpen.value) return;
      const minX = 0;
      const topOffset = insets.top + (effectiveHeaderH || 0);
      const maxX = Math.max(minX, screen.width - width.value);
      const maxY = Math.max(
        topOffset,
        baseHeight - height.value - (effectiveFooterH || insets.bottom)
      );
      translateX.value = clamp(startX.value + e.translationX, minX, maxX);
      translateY.value = clamp(startY.value + e.translationY, topOffset, maxY);
    })
    .onEnd(() => {
      'worklet';
      if (isOpen.value) return;
      const minX = 0;
      const maxX = Math.max(minX, screen.width - width.value);
      const midpoint = maxX / 2;
      const targetX = translateX.value <= midpoint ? minX : maxX;
      const topOffset = insets.top + (effectiveHeaderH || 0);
      const limitedMaxY = Math.max(
        topOffset,
        baseHeight - height.value - (effectiveFooterH || insets.bottom)
      );
      const targetY = clamp(translateY.value, topOffset, limitedMaxY);
      // translateX.value = withSpring(targetX, { damping: 18, stiffness: 160 });
      // translateY.value = withSpring(targetY, { damping: 18, stiffness: 160 });
      lastCollapsedX.value = targetX;
      lastCollapsedY.value = targetY;
    });
 
  const handleOnEmojiSelect = (emoji: Emoji) => {
    setInputVal((p) => p + emoji.emoji);
    setShowEmojiPicker(false);
  };
 
  const handlePickAttachment = async () => {
    const result = await launchImageLibraryAsync({
      mediaTypes: MediaTypeOptions.All,
      allowsEditing: true,
      quality: 1,
    });
 
    if (!result.canceled) {
      const name = result.assets[0].fileName;
      if (!name) return;
      setMessage(name);
    }
  };
 
  const shadowContainerStyle = [
    Platform.select({
      ios: {
        shadowColor: colors[theme].shadowMedium,
        shadowOffset: { width: 0, height: 4 },
        shadowOpacity: 0.25,
        shadowRadius: 8,
      },
      android: {
        elevation: 8,
      },
      default: {
        shadowColor: colors[theme].shadowMedium,
        shadowOffset: { width: 0, height: 4 },
        shadowOpacity: 0.25,
        shadowRadius: 8,
      },
    }),
  ];
 
  const renderMessage = (msg: MessageType) => (
    <Pressable
      key={msg.id}
      className={cn(
        'mt-3 w-[65%] rounded-t-[20px]',
        msg.sender === 'user' ? 'self-end rounded-l-[20px]' : 'rounded-r-[20px]',
        messageVariant === 'bubble' && 'rounded-2xl'
      )}
      style={{
        backgroundColor:
          msg.sender === 'user' ? colors[theme].colorAccent : colors[theme].colorPrimary,
      }}
      accessibilityLabel={`message from ${msg.sender}`}
    >
      <View className={'px-3 py-3'}>
        {typeof msg.content === 'string' ? (
          <Text
            className={cn('font-normal')}
            style={{
              color: msg.sender !== 'user' ? colors[theme].colorText_Main : undefined,
            }}
          >
            {msg.content}
          </Text>
        ) : (
          msg.content
        )}
        {msg.sender !== 'system' && (msg.timestamp || msg.status) && (
          <View className={'mt-2 flex flex-row'}>
            {msg.timestamp && (
              <Text
                className={cn('text-sm font-normal', msg.sender !== 'user' && 'text-text-main')}
              >
                {msg.timestamp}
              </Text>
            )}
            {msg.status && (
              <Text
                className={cn('text-sm font-normal', msg.sender !== 'user' && 'text-text-main')}
                style={{ marginLeft: msg.timestamp ? 8 : 0 }}
              >
                {msg.status}
              </Text>
            )}
          </View>
        )}
      </View>
    </Pressable>
  );
 
  const renderEmojis = () => (
    <Pressable className={'mr-2'} onPress={handleShowEmojiPicker}>
      <Text>😊</Text>
    </Pressable>
  );
 
  React.useEffect(() => {
    if (isVisible) {
      handleOpen();
    } else E{
      handleClose();
    }
  }, [isVisible]);
 
  React.useEffect(() => {
    if (isOpen.value) {
      width.value = withSpring(openW, { damping: 18, stiffness: 160 });
      height.value = withSpring(openH, { damping: 18, stiffness: 160 });
      translateX.value = withSpring(0, { damping: 18, stiffness: 160 });
      translateY.value = withSpring(topOffset, { damping: 18, stiffness: 160 });
      startX.value = 0;
      startY.value = topOffset;
      borderRadius.value = 0;
    } else E{
      // Keep collapsed bubble within new bounds
      const minX = 0;
      const maxX = Math.max(minX, winW - closedWidth);
      const maxY = Math.max(topOffset, baseHeight - closedWidth - bottomOffset);
      const clampedX = clamp(lastCollapsedX.value, minX, maxX);
      const clampedY = clamp(lastCollapsedY.value, topOffset, maxY);
      lastCollapsedX.value = clampedX;
      lastCollapsedY.value = clampedY;
      translateX.value = clampedX;
      translateY.value = clampedY;
      startX.value = clampedX;
      startY.value = clampedY;
    }
  }, [winW, winH, openW, openH, topOffset, bottomOffset]);
 
  React.useEffect(() => {
    Eif (isVisible && isOpen.value && openState) {
      width.value = openW;
      height.value = openH;
      translateX.value = 0;
      translateY.value = topOffset;
      borderRadius.value = 0;
      lastCollapsedX.value = screen.width - closedWidth;
      lastCollapsedY.value = baseHeight - closedWidth - bottomOffset;
    }
  }, []);
 
  Iif (!isVisible && !openState) return null;
  return (
    <>
      <GestureDetector gesture={panGesture}>
        <Animated.View
          id={id}
          testID={id}
          style={[
            styles.container,
            openState ? styles.containerOpen : styles.containerCollapsed,
            containerAnimateStyle,
            dragStyle,
            shadowContainerStyle,
          ]}
          className={cn('bg-primary-background', className)}
          accessibilityLabel={`Chatbox`}
        >
          {!openState && (
            <View>
              <Pressable testID={'open_button'} style={[styles.iconContainer]} onPress={handleOpen}>
                <Chat size={26} />
              </Pressable>
              <Pressable
                testID={'dismiss_button'}
                accessibilityLabel={'dismiss chatbox'}
                style={styles.dismissButton}
                onPress={handleDismiss}
              >
                <XFill width={20} height={20} color={colors[theme].colorSecondary} />
              </Pressable>
            </View>
          )}
          {openState && (
            <View
              style={[
                styles.contentContainer,
                {
                  backgroundColor: colors[theme].alternateBackground,
                },
              ]}
            >
              {showHeader && (
                <View
                  className={cn('px-5 py-4', headerClassName)}
                  testID={'header'}
                  style={[
                    styles.contentHeader,
                    {
                      backgroundColor: colors[theme].colorPrimary_Background,
                    },
                  ]}
                >
                  <User color={colors[theme].colorIcon_Fill_Light} />
                  {typeof headerTemplate === 'string' ? (
                    <Text
                      style={{ color: colors[theme].colorText_Main }}
                      className={'font-Bold text-[16px]'}
                    >
                      {headerTemplate}
                    </Text>
                  ) : headerTemplate === undefined ? (
                    <Text
                      className={'font-Bold text-[16px]'}
                      style={{ color: colors[theme].colorText_Main }}
                    >
                      Chat
                    </Text>
                  ) : (
                    headerTemplate
                  )}
                  <Pressable testID={'close_btn'} onPress={handleClose}>
                    <X color={colors[theme].colorIcon_Fill_Light} size={15} />
                  </Pressable>
                </View>
              )}
              <View
                className={'w-full'}
                style={[
                  styles.messageContainer,
                  {
                    backgroundColor: colors[theme].alternateBackground,
                  },
                ]}
              >
                <ScrollView
                  scrollEnabled
                  style={{ flexGrow: 1 }}
                  className={'flex h-[90%] flex-col px-2'}
                >
                  {chatMessages && chatMessages.length > 0 && chatMessages.map(renderMessage)}
                  {showTypingIndicator && isTyping && <Text className="bottom-0">Typing…</Text>}
                </ScrollView>
                <View
                  className={cn(
                    'absolute bottom-0 flex w-full flex-row items-center justify-between border-t-[0.3px] px-3 pt-6',
                    footerClassName
                  )}
                  style={{
                    backgroundColor: colors[theme].alternateBackground,
                  }}
                >
                  <View className={'flex flex-1 flex-row items-center'}>
                    {enableEmojis && renderEmojis()}
                    <View
                      className={'w-[85%] rounded-md border'}
                      style={{ borderColor: colors[theme].colorInput_Disabled_Background }}
                    >
                      <Input
                        testID={'message_input'}
                        onChangeText={updateText}
                        floatingLabel={true}
                        value={inputVal}
                        placeholder={inputPlaceholder}
                        name={'message'}
                        accessibilityLabel={'chat message input'}
                      />
                    </View>
                  </View>
                  {enableAttachments && (
                    <Pressable
                      testID={'attachment_btn'}
                      onPress={handlePickAttachment}
                      accessibilityLabel="send attachment"
                    >
                      <PaperclipIcon color={colors[theme].colorSecondary} />
                    </Pressable>
                  )}
                  <Button
                    label={sendButtonLabel}
                    onPress={handleOnSend}
                    variant={'primary'}
                    className="px-5 py-[12px]"
                    accessibilityLabel={'send message'}
                  />
                </View>
              </View>
              {footerTemplate && showFooter && <View className="chatFooter">{footerTemplate}</View>}
            </View>
          )}
        </Animated.View>
      </GestureDetector>
      {showEmojiPicker && (
        <EmojiPicker
          emojis={emojis}
          loading={false}
          autoFocus={true}
          darkMode={false}
          perLine={7}
          onSelect={handleOnEmojiSelect}
        />
      )}
    </>
  );
};
 
const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    borderRadius: 50,
    zIndex: 9999,
  },
  containerOpen: {
    overflow: 'hidden',
  },
  containerCollapsed: {
    overflow: 'visible',
  },
  iconContainer: {
    width: 60,
    height: 60,
    justifyContent: 'center',
    alignItems: 'center',
  },
  dismissButton: {
    position: 'absolute',
    top: 0,
    right: -2,
    width: 20,
    height: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
  contentContainer: {
    flexDirection: 'column',
    overflow: 'hidden',
    height: '100%',
  },
  contentHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    width: '100%',
  },
  messageContainer: {
    flexDirection: 'column',
    justifyContent: 'space-evenly',
  },
});