# DEVELOPER GUIDE: chat

## Quick Summary
The chat directory provides a comprehensive set of React components and hooks for building chat interfaces. It includes visual components for chat bubbles, messages, input fields, and message lists, along with utility hooks for managing auto-scrolling behavior. The architecture separates presentation components (direct files) from behavioral logic (hooks subdirectory), enabling flexible and reusable chat UI implementations.

## Files and Subdirectories Overview
- **Direct files:**
  - `chat-bubble.tsx` - Complete chat bubble component system with avatar, message, timestamp, and actions
  - `chat-input.tsx` - Styled textarea component for chat message input
  - `chat-message-list.tsx` - Scrollable container for chat messages with auto-scroll functionality
  - `message-loading.tsx` - Loading spinner component for pending messages

- **Subdirectories:**
  - `hooks/` - Custom React hooks for chat functionality, primarily auto-scrolling behavior

## Developer API Reference

### Direct Files

#### chat-bubble.tsx
**Purpose:** Provides a complete chat bubble system with avatar, message content, timestamps, and action buttons
**Import:** `import { ChatBubble, ChatBubbleAvatar, ChatBubbleMessage, ChatBubbleTimestamp, ChatBubbleAction, ChatBubbleActionWrapper } from "@/lib/components/ui/chat/chat-bubble"`

**Components:**
- `ChatBubble` - Main container component with variant support for sent/received messages
  - Props: `variant?: "sent" | "received"`, `layout?: "default" | "ai"`
- `ChatBubbleAvatar` - Avatar component for message sender
  - Props: `src?: string`, `fallback?: string`, `className?: string`
- `ChatBubbleMessage` - Message content container with styling variants
  - Props: `variant?: "sent" | "received"`, `layout?: "default" | "ai"`, `isComplete?: boolean`
- `ChatBubbleTimestamp` - Timestamp display component
  - Props: `timestamp: string`
- `ChatBubbleAction` - Action button component for message interactions
  - Props: `icon: React.ReactNode`, extends Button props
- `ChatBubbleActionWrapper` - Container for action buttons with hover effects
  - Props: `variant?: "sent" | "received"`

#### chat-input.tsx
**Purpose:** Styled textarea component specifically designed for chat message input
**Import:** `import { ChatInput } from "@/lib/components/ui/chat/chat-input"`

**Components:**
- `ChatInput` - Enhanced textarea with chat-specific styling and behavior
  - Props: Extends `React.TextareaHTMLAttributes<HTMLTextAreaElement>`

#### chat-message-list.tsx
**Purpose:** Scrollable container for chat messages with auto-scroll and scroll-to-bottom functionality
**Import:** `import { ChatMessageList, type ChatMessageListRef } from "@/lib/components/ui/chat/chat-message-list"`

**Components:**
- `ChatMessageList` - Scrollable message container with auto-scroll behavior
  - Props: `smooth?: boolean`, extends `React.HTMLAttributes<HTMLDivElement>`
  - Ref: `ChatMessageListRef` with `scrollToBottom(): void` method

#### message-loading.tsx
**Purpose:** Loading indicator for pending chat messages
**Import:** `import MessageLoading from "@/lib/components/ui/chat/message-loading"`

**Components:**
- `MessageLoading` - Spinner component for loading states
  - Props: `className?: string`

### Subdirectory APIs

#### hooks/
**Purpose:** Provides custom React hooks for chat functionality, primarily auto-scrolling behavior
**Key Exports:** `useAutoScroll` hook for managing automatic scrolling in chat interfaces
**Import Examples:**
```typescript
import { useAutoScroll } from "@/lib/components/ui/chat/hooks/useAutoScroll"
```

## Complete Usage Guide

### 1. Basic Chat Message Display

```tsx
import { 
  ChatBubble, 
  ChatBubbleAvatar, 
  ChatBubbleMessage, 
  ChatBubbleTimestamp 
} from "@/lib/components/ui/chat/chat-bubble";

function BasicMessage({ message, isUser }) {
  return (
    <ChatBubble variant={isUser ? "sent" : "received"}>
      <ChatBubbleAvatar 
        src={message.avatar} 
        fallback={message.name[0]} 
      />
      <ChatBubbleMessage variant={isUser ? "sent" : "received"}>
        {message.content}
        <ChatBubbleTimestamp timestamp={message.timestamp} />
      </ChatBubbleMessage>
    </ChatBubble>
  );
}
```

### 2. Interactive Chat Messages with Actions

```tsx
import { 
  ChatBubble, 
  ChatBubbleMessage, 
  ChatBubbleAction, 
  ChatBubbleActionWrapper 
} from "@/lib/components/ui/chat/chat-bubble";
import { Copy, ThumbsUp } from "lucide-react";

function InteractiveMessage({ message, onCopy, onLike }) {
  return (
    <ChatBubble variant="received">
      <ChatBubbleMessage variant="received">
        {message.content}
        <ChatBubbleActionWrapper variant="received">
          <ChatBubbleAction 
            icon={<Copy />} 
            onClick={() => onCopy(message.content)}
          />
          <ChatBubbleAction 
            icon={<ThumbsUp />} 
            onClick={() => onLike(message.id)}
          />
        </ChatBubbleActionWrapper>
      </ChatBubbleMessage>
    </ChatBubble>
  );
}
```

### 3. Complete Chat Interface

```tsx
import { useState, useRef } from "react";
import { ChatMessageList, type ChatMessageListRef } from "@/lib/components/ui/chat/chat-message-list";
import { ChatInput } from "@/lib/components/ui/chat/chat-input";
import { ChatBubble, ChatBubbleMessage } from "@/lib/components/ui/chat/chat-bubble";
import MessageLoading from "@/lib/components/ui/chat/message-loading";
import { useAutoScroll } from "@/lib/components/ui/chat/hooks/useAutoScroll";

function ChatInterface() {
  const [messages, setMessages] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [inputValue, setInputValue] = useState("");
  const messageListRef = useRef<ChatMessageListRef>(null);

  const handleSendMessage = async () => {
    if (!inputValue.trim()) return;
    
    const newMessage = {
      id: Date.now(),
      content: inputValue,
      isUser: true,
      timestamp: new Date().toLocaleTimeString()
    };
    
    setMessages(prev => [...prev, newMessage]);
    setInputValue("");
    setIsLoading(true);
    
    // Simulate AI response
    setTimeout(() => {
      setMessages(prev => [...prev, {
        id: Date.now(),
        content: "AI response here",
        isUser: false,
        timestamp: new Date().toLocaleTimeString()
      }]);
      setIsLoading(false);
    }, 1000);
  };

  return (
    <div className="flex flex-col h-96 border rounded-lg">
      <ChatMessageList ref={messageListRef}>
        {messages.map(message => (
          <ChatBubble key={message.id} variant={message.isUser ? "sent" : "received"}>
            <ChatBubbleMessage variant={message.isUser ? "sent" : "received"}>
              {message.content}
            </ChatBubbleMessage>
          </ChatBubble>
        ))}
        {isLoading && (
          <ChatBubble variant="received">
            <ChatBubbleMessage variant="received">
              <MessageLoading />
            </ChatBubbleMessage>
          </ChatBubble>
        )}
      </ChatMessageList>
      
      <div className="p-4 border-t">
        <div className="flex gap-2">
          <ChatInput
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder="Type your message..."
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleSendMessage();
              }
            }}
          />
          <button onClick={handleSendMessage}>Send</button>
        </div>
      </div>
    </div>
  );
}
```

### 4. AI Chat Layout

```tsx
import { ChatBubble, ChatBubbleMessage } from "@/lib/components/ui/chat/chat-bubble";

function AIMessage({ message }) {
  return (
    <ChatBubble variant="received" layout="ai">
      <ChatBubbleMessage variant="received" layout="ai">
        {message.content}
      </ChatBubbleMessage>
    </ChatBubble>
  );
}
```

### 5. Custom Auto-Scroll Implementation

```tsx
import { useAutoScroll } from "@/lib/components/ui/chat/hooks/useAutoScroll";

function CustomChatList({ messages }) {
  const { 
    scrollRef, 
    isAtBottom, 
    scrollToBottom, 
    disableAutoScroll,
    userHasScrolled 
  } = useAutoScroll({
    content: messages,
    smooth: true,
    offset: 50
  });

  return (
    <div className="relative h-96">
      <div 
        ref={scrollRef}
        className="h-full overflow-y-auto p-4"
        onWheel={disableAutoScroll}
        onTouchMove={disableAutoScroll}
      >
        {messages.map(message => (
          <div key={message.id}>{message.content}</div>
        ))}
      </div>
      
      {!isAtBottom && userHasScrolled && (
        <button 
          onClick={scrollToBottom}
          className="absolute bottom-4 right-4 bg-blue-500 text-white p-2 rounded-full"
        >
          ↓
        </button>
      )}
    </div>
  );
}
```

This chat system provides a complete foundation for building modern chat interfaces with proper message styling, auto-scrolling behavior, loading states, and interactive elements. The modular design allows you to use individual components or combine them for full chat functionality.

# content_hash: 4ebf6e5472fe9ac1f8f4916bd17181aaed0431f963ac60ddc2dfe0136f9a808a
