npm package: @onlive.ai/chat
Description: A comprehensive web components package for real-time chat functionality built with Lit and LiveKit. This package provides a complete chat interface with support for text messaging, voice communication, multimedia sharing, form handling, and conversation m
Latest version: 0.3.54

# @onlive.ai/chat

A comprehensive web components package for real-time chat functionality built with Lit and LiveKit. This package provides a complete chat interface with support for text messaging, voice communication, multimedia sharing, form handling, and conversation management.

## 🚀 Features

### Core Chat Features
- **Real-time messaging** with LiveKit integration
- **Voice chat support** with audio visualization
- **Text-based conversations** with markdown support
- **Message persistence** with server/client options
- **Message reactions** (👍/👎) and reporting
- **Conversation evaluation** and feedback system

### Rich Media Support
- **Multimedia sharing** (images, videos, documents)
- **Media visualizer** for viewing shared content
- **Audio device selection** and management
- **Voice amplitude visualization** with D3.js

### Form Integration
- **Interactive forms** within chat messages
- **Dynamic field validation** with @onlive.ai/flow
- **Form submission tracking** and analytics
- **Multi-step form workflows**

### User Experience
- **Message grouping** by participant
- **Typing indicators** and loading states
- **Auto-scroll** to latest messages
- **Link handling** with domain restrictions
- **Multi-language support** with localization
- **Custom theming** and styling support

### Analytics & Tracking
- **Event tracking** with @onlive.ai/tracker
- **User interaction analytics**
- **Form submission metrics**
- **Conversation flow analysis**

## 📦 Installation

### Using pnpm
```bash
pnpm add @onlive.ai/chat
```

### Using npm
```bash
npm install @onlive.ai/chat
```

### Using yarn
```bash
yarn add @onlive.ai/chat
```

## 🏗️ Package Structure

```
packages/chat/
├── components/
│   ├── actions/          # Action buttons and controls
│   ├── audio-device/     # Audio device selection
│   ├── chat/            # Main chat component
│   ├── evaluation/      # Conversation rating
│   ├── media-visualizer/ # Media gallery viewer
│   ├── message/         # Message display component
│   ├── player/          # Media player component
│   ├── send/            # Message input component
│   └── wave/            # Voice amplitude visualization
├── locales/             # Internationalization files
├── theme/               # Base styling and themes
├── translations/        # Language translations
├── index.ts            # Main exports
└── package.json        # Package configuration
```

## 🔧 Basic Usage

### Simple Text Chat

```typescript
import '@onlive.ai/chat';
import { LivekitService } from '@onlive.ai/common-121/services/livekit.service.js';

// Create LiveKit service instance
const livekitService = new LivekitService({
  baseUrl: 'https://your-livekit-server.com',
  organizationId: 'your-org-id'
});

// Initialize chat room
const room = await livekitService.createRoom({
  language: 'en',
  timezone: 'America/New_York'
});
```

```html
<och-chat
  lang="en"
  .livekitService="${livekitService}"
  .options="${{
    agent: {
      id: 'agent-123',
      type: 'text',
      name: 'Assistant',
      image: '/path/to/avatar.png'
    }
  }}"
></och-chat>
```

### Voice Chat Configuration

```html
<och-chat
  lang="en"
  .livekitService="${livekitService}"
  .audioService="${audioService}"
  .options="${{
    agent: {
      id: 'voice-agent-456',
      type: 'voice',
      name: 'Voice Assistant',
      image: '/path/to/voice-avatar.png'
    }
  }}"
></och-chat>
```

### With Custom Styling and Tracking

```typescript
import { Tracker } from '@onlive.ai/tracker';

const tracker = new Tracker({
  apiKey: 'your-tracking-key',
  endpoint: 'https://analytics.example.com'
});

const customStyles = new CSSStyleSheet();
customStyles.replaceSync(`
  .och__chat {
    --ol-color-primary: #your-brand-color;
  }
`);
```

```html
<och-chat
  lang="en"
  .livekitService="${livekitService}"
  .context="${{
    tracker: tracker,
    customStyles: customStyles
  }}"
  .options="${chatOptions}"
></och-chat>
```

## 📋 Component API

### OCHChat (Main Component)

#### Properties
- `lang: string` - Language code for localization
- `livekitService: LivekitService` - LiveKit service instance
- `audioService?: AudioService` - Audio service for voice features
- `organizationId?: string` - Organization identifier
- `options?: ChatOptions` - Chat configuration options
- `tracking?: TrackingOptions` - Analytics configuration
- `context: PackageContext` - Shared context for styling and tracking

#### Events
- `open-link` - Fired when a link is clicked
- `organization-call` - Fired when requesting a meeting
- `conversation-ended` - Fired when conversation is completed
- `restart-conversation` - Fired when restarting chat

#### Chat Options
```typescript
interface ChatOptions {
  agent?: {
    id: string;
    type: 'text' | 'voice';
    name: string;
    image: string;
  };
  browser?: {
    allowedDomains?: string[];
  };
}
```

### OCHMessage (Message Display)

#### Properties
- `messages: ChatMessage[]` - Array of messages to display
- `from?: ChatMessage["from"]` - Message sender information
- `lang: string` - Language for localization
- `loading?: boolean` - Show loading state

#### Events
- `submit-form` - Fired when form is submitted
- `cancel-form` - Fired when form is cancelled
- `open-link` - Fired when link is clicked
- `click-media` - Fired when media is clicked
- `report-message` - Fired when message is reported

### OCHSend (Message Input)

#### Properties
- `disabled?: boolean` - Disable the entire component
- `sendDisabled?: boolean` - Disable only send button
- `inputDisabled?: boolean` - Disable only input field
- `lang: string` - Language for localization

#### Events
- `send` - Fired when message is sent

## 🌍 Internationalization

The package supports multiple languages with built-in localization:

```typescript
import { configureLocalization } from '@lit/localize';

configureLocalization({
  sourceLocale: 'en',
  targetLocales: ['es', 'fr', 'de', 'it'],
  loadLocale: (locale) => import(`./locales/${locale}.js`)
});
```

Supported languages:
- English (en)
- Spanish (es)
- French (fr)
- German (de)
- Italian (it)

## 🎨 Styling and Theming

### CSS Custom Properties

The components use CSS custom properties for theming:

```css
och-chat {
  --ol-color-primary: #0066cc;
  --ol-color-neutral-50: #f9fafb;
  --ol-color-neutral-800: #1f2937;
  --ol-spacing-small: 0.5rem;
  --ol-spacing-medium: 1rem;
  --ol-spacing-large: 1.5rem;
}
```

### Custom Styles

You can provide custom styles through the context:

```typescript
const customStyleSheet = new CSSStyleSheet();
customStyleSheet.replaceSync(`
  .och__chat__messages {
    background: linear-gradient(to bottom, #f0f0f0, #ffffff);
  }
  
  .och__message {
    border-radius: 12px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
`);

const chatContext = {
  customStyles: customStyleSheet,
  tracker: yourTracker
};
```

## 📊 Analytics Integration

The package integrates with `@onlive.ai/tracker` for comprehensive analytics:

### Tracked Events
- **Element interactions** (button clicks, input focus)
- **Message sending** and receiving
- **Form submissions** and cancellations
- **Link clicks** and navigation
- **Conversation flow** events
- **Media interactions**

### Event Types
```typescript
interface TrackingEvents {
  'element_click': ElementClickData;
  'element_interaction': InteractionData;
  'form_submit': FormSubmissionData;
  'impression': ImpressionData;
}
```

## 🔌 LiveKit Integration

### Room Management
```typescript
// Create a room
const room = await livekitService.createRoom({
  language: 'en',
  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
  affinity: {
    agentId: 'your-agent-id',
    agentType: 'text'
  }
});

// Subscribe to messages
livekitService.subscribeMessages((messages) => {
  console.log('New messages:', messages);
});

// Send a message
await livekitService.sendMessage('Hello, world!');
```

### Voice Chat Features
```typescript
// Enable microphone
await room.localParticipant.setMicrophoneEnabled(true);

// Handle audio tracks
room.on(RoomEvent.TrackSubscribed, (track, publication) => {
  if (track.kind === Track.Kind.Audio) {
    const audioElement = track.attach();
    document.body.appendChild(audioElement);
  }
});
```

## 🛠️ Development

### Prerequisites
- Node.js 18+
- pnpm 8+

### Setup
```bash
# Install dependencies
pnpm install

# Build the package
pnpm run build:package

# Extract localization strings
pnpm run localize:extract

# Build localization files
pnpm run localize:build
```

### Testing
```bash
# Run in development mode
pnpm run dev

# Build for production
pnpm run build

# Clean build artifacts
pnpm run clean
```

## 📝 Distribution Formats

The package is distributed in multiple formats:

- **ES Modules** (`index.js`) - Modern bundlers
- **CommonJS** (`index.cjs`) - Node.js compatibility
- **TypeScript Definitions** (`index.d.ts`) - Type support

## 🔗 Dependencies

### Core Dependencies
- `@lit/context` - Component context management
- `@lit/localize` - Internationalization support
- `@livekit/components-core` - LiveKit integration
- `@onlive.ai/flow` - Form component integration
- `@onlive.ai/ui` - UI component library
- `@onlive.ai/common-121` - Shared utilities
- `@onlive.ai/tracker` - Analytics tracking

### Visualization Dependencies
- `d3` - Data visualization library
- `d3-shape` - Shape generation for audio visualization

### Utility Dependencies
- `mime` - File type detection
- `timeago.js` - Relative time formatting

## 🤝 Integration Examples

### With React
```jsx
import '@onlive.ai/chat';
import { useRef, useEffect } from 'react';

function ChatComponent() {
  const chatRef = useRef(null);
  
  useEffect(() => {
    if (chatRef.current) {
      chatRef.current.livekitService = livekitService;
      chatRef.current.options = chatOptions;
    }
  }, []);
  
  return (
    <och-chat
      ref={chatRef}
      lang="en"
    />
  );
}
```

### With Angular
```typescript
import '@onlive.ai/chat';

@Component({
  template: `
    <och-chat
      [lang]="language"
      [livekitService]="livekitService"
      [options]="chatOptions"
      (conversation-ended)="onConversationEnded($event)"
    ></och-chat>
  `
})
export class ChatComponent {
  language = 'en';
  livekitService = new LivekitService(config);
  chatOptions = { /* your options */ };
  
  onConversationEnded(event: CustomEvent) {
    console.log('Conversation ended:', event.detail);
  }
}
```

### With Vue.js
```vue
<template>
  <och-chat
    :lang="language"
    :livekitService="livekitService"
    :options="chatOptions"
    @conversation-ended="onConversationEnded"
  />
</template>

<script>
import '@onlive.ai/chat';

export default {
  data() {
    return {
      language: 'en',
      livekitService: new LivekitService(config),
      chatOptions: { /* your options */ }
    };
  },
  methods: {
    onConversationEnded(event) {
      console.log('Conversation ended:', event.detail);
    }
  }
};
</script>
```

## 📱 Browser Compatibility

- **Chrome/Edge** 88+
- **Firefox** 78+
- **Safari** 14+
- **Mobile browsers** with ES2020 support

## 📄 License

This package is part of the Onlive 121 ecosystem and follows the project's licensing terms.