Skip to content

ModernChatbot Component

Overview

The ModernChatbot component is a sophisticated chat interface that enables users to interact with the BidScript AI assistant. It provides a modern, animated UI with support for document uploads, message history, and real-time responses.

Features

  1. Interactive Chat Interface: A collapsible chat window with smooth animations and transitions.
  2. Document Upload: Support for uploading various file types (PDF, Word, Excel, PowerPoint, images, etc.) for AI processing.
  3. Message History: Maintains a scrollable history of the conversation between the user and the AI.
  4. Loading Indicators: Visual feedback during AI processing with animated loading indicators.
  5. Copy to Clipboard: Ability to copy AI responses to the clipboard.
  6. Responsive Design: Adapts to different screen sizes and maintains usability.

Implementation

The component is built using React with Framer Motion for animations and integrates with the BidScript API for AI interactions.

import * as React from "react";
import { motion, AnimatePresence, useAnimation } from "framer-motion";
import {
  MessageCircle,
  X,
  Send,
  Plus,
  Paperclip,
  Clipboard,
  FileText,
  File,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useSession } from "next-auth/react";
import apiClient from "@/lib/apiClient";

// Component implementation...

State Management

The component manages several state variables:

State Variable Type Description
isOpen boolean Controls the visibility of the chat window
messages array Stores the conversation history
inputValue string Manages the input field value
uploadedFiles array Tracks files uploaded for processing
isProcessing boolean Indicates when the AI is processing a request

File Upload Functionality

The component supports uploading various document types for AI processing:

const handleFileUpload = async (file: File) => {
  const fileType = getFileType(file.name);

  if (fileType === "unknown") {
    console.error("Unsupported file type:", file.name);
    return;
  }

  // Convert file to base64
  const reader = new FileReader();
  reader.onload = (e) => {
    const base64Data = e.target?.result as string;
    setUploadedFiles((prev) => [
      ...prev,
      {
        name: file.name,
        type: fileType,
        status: "success",
        data: base64Data.split(",")[1], // Remove data URL prefix
      },
    ]);
  };
  reader.readAsDataURL(file);
  setShowDocumentMenu(false);
};

API Integration

The component communicates with the BidScript backend API to process user queries and uploaded documents:

const handleSubmit = async (e: React.FormEvent) => {
  e.preventDefault();
  if (!visibleMessage.trim()) return;

  // Add user message to chat
  setMessages((prev) => [...prev, { text: visibleMessage, isBot: false }]);
  setIsProcessing(true);

  // Prepare request with user message and any uploaded documents
  const requestBody = {
    userID: userID,
    query: visibleMessage,
    documents: uploadedFiles.map((file) => ({
      name: file.name,
      type: file.type,
      content: file.data,
    })),
  };

  try {
    // Send request to API
    const response = await apiClient.post(`/chat`, requestBody);

    // Process response
    const { response: answer } = response.data;
    setMessages((prev) => {
      const updatedMessages = [...prev];
      updatedMessages.pop();
      return [...updatedMessages, { text: answer, isBot: true }];
    });

    // Clear uploaded files after successful submission
    setUploadedFiles([]);
  } catch (error) {
    // Handle errors
    console.error("Error fetching data:", error);
    setMessages((prev) => {
      const updatedMessages = [...prev];
      updatedMessages.pop();
      return [
        ...updatedMessages,
        {
          text: "Sorry, I encountered an error. Please try again.",
          isBot: true,
        },
      ];
    });
  } finally {
    setIsProcessing(false);
  }
};

UI Components

The ModernChatbot consists of several key UI elements:

  1. Chat Button: A floating button that opens the chat interface
  2. Chat Window: The main interface containing:
  3. Header with title and close button
  4. Message history area
  5. File upload area
  6. Input field with send button

Animations

The component uses Framer Motion for smooth animations:

  • Fade and slide animations for the chat window opening/closing
  • Loading animations for the AI typing indicator
  • Transition animations for messages appearing in the chat

Usage

import { ModernChatbotComponent } from "@/components/modern-chatbot";

const AppLayout = () => {
  return (
    <div className="app-container">
      {/* App content */}
      <ModernChatbotComponent />
    </div>
  );
};

Dependencies

  • React
  • Framer Motion
  • Lucide React (for icons)
  • Next Auth (for user session)
  • Custom UI components from the application's component library