> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bubblav.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Reference

> Control the BubblaV widget programmatically using the JavaScript SDK.

The BubblaV SDK provides programmatic control over your chat widget. Use it to open/close the widget, send messages, listen to events, and more.

<Note>
  The SDK is automatically loaded when you add the widget to your site. For React, Vue, and Angular projects, we recommend using our NPM packages for better type safety and framework integration.
</Note>

***

## Installation

### NPM Packages (Recommended)

For framework projects, use our official NPM packages:

<Tabs>
  <Tab title="React">
    **1. Install the package:**

    ```bash theme={null}
    npm install @bubblav/ai-chatbot-react
    ```

    **2. Add the widget to your app:**

    ```tsx theme={null}
    import { BubblaVWidget } from '@bubblav/ai-chatbot-react';

    function App() {
      return (
        <BubblaVWidget websiteId="your-website-id" />
      );
    }
    ```

    **3. Control the widget programmatically:**

    ```tsx theme={null}
    import { useBubblaVWidget } from '@bubblav/ai-chatbot-react';

    function MyComponent() {
      const widget = useBubblaVWidget();

      const handleSupportClick = () => {
        widget?.open();
        widget?.sendMessage('Hello! I need help.');
      };

      return <button onClick={handleSupportClick}>Get Support</button>;
    }
    ```
  </Tab>

  <Tab title="Vue">
    **1. Install the package:**

    ```bash theme={null}
    npm install @bubblav/ai-chatbot-vue
    ```

    **2. Add the widget to your app:**

    ```vue theme={null}
    <script setup>
    import { BubblaVWidget } from '@bubblav/ai-chatbot-vue';
    </script>

    <template>
      <BubblaVWidget website-id="your-website-id" />
    </template>
    ```

    **3. Control the widget programmatically:**

    ```vue theme={null}
    <script setup>
    import { useBubblaVWidget } from '@bubblav/ai-chatbot-vue';

    const widget = useBubblaVWidget();

    const handleSupportClick = () => {
      widget?.open();
      widget?.sendMessage('Hello! I need help.');
    };
    </script>

    <template>
      <button @click="handleSupportClick">Get Support</button>
    </template>
    ```
  </Tab>

  <Tab title="Angular">
    **1. Install the package:**

    ```bash theme={null}
    npm install @bubblav/ai-chatbot-angular
    ```

    **2. Add the widget to your app:**

    ```ts theme={null}
    import { Component } from '@angular/core';
    import { BubblaVWidgetComponent } from '@bubblav/ai-chatbot-angular';

    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [BubblaVWidgetComponent],
      template: `<bubblav-widget websiteId="your-website-id" />`
    })
    export class AppComponent {}
    ```

    **3. Control the widget programmatically:**

    ```ts theme={null}
    import { Component, inject } from '@angular/core';
    import { BubblaVWidgetService } from '@bubblav/ai-chatbot-angular';

    @Component({
      selector: 'app-support',
      template: `<button (click)="handleSupportClick()">Get Support</button>`
    })
    export class SupportComponent {
      private bubblav = inject(BubblaVWidgetService);

      handleSupportClick() {
        this.bubblav.open();
        this.bubblav.sendMessage('Hello! I need help.');
      }
    }
    ```
  </Tab>
</Tabs>

<Tip>
  NPM packages provide full TypeScript support, framework-specific patterns, and better lifecycle management.
</Tip>

***

### Global SDK

For vanilla JavaScript or when not using a framework, the SDK is available as `window.BubblaV`:

```javascript theme={null}
// Check if SDK is ready
if (window.BubblaV) {
  window.BubblaV.open();
}

// Or use the ready callback
window.BubblaV.ready(() => {
  window.BubblaV.sendMessage('Hello!');
});
```

<Note>
  The SDK may not be available immediately. Use the `ready()` callback to ensure it's loaded.
</Note>

***

## SDK Methods

### Widget Control

#### `open()`

Opens the chat widget.

```javascript theme={null}
BubblaV.open();
```

**Use cases:**

* Trigger chat from a custom button
* Open chat after a user action
* Start conversation proactively

***

#### `close()`

Closes the chat widget.

```javascript theme={null}
BubblaV.close();
```

**Use cases:**

* Close chat after a conversation
* Respond to user dismiss action

***

#### `toggle()`

Toggles the widget open/closed state.

```javascript theme={null}
BubblaV.toggle();
```

**Use cases:**

* Single button to toggle widget
* Keyboard shortcuts for chat access

***

#### `openSearch()`

Opens the search interface (modal).

```javascript theme={null}
BubblaV.openSearch();
```

**Use cases:**

* Trigger search from a custom button
* Open search after a user action

***

#### `isOpen()`

Checks if the widget is currently open.

```javascript theme={null}
if (BubblaV.isOpen()) {
  console.log('Widget is open');
}
```

**Returns:** `boolean`

***

### Messaging

#### `sendMessage(text, conversationId?)`

Sends a message programmatically.

```javascript theme={null}
// Send a simple message
BubblaV.sendMessage('Hello, I need help!');

// Send to a specific conversation
BubblaV.sendMessage('Where is my order?', 'conv_123');
```

| Parameter        | Type     | Required | Description            |
| ---------------- | -------- | -------- | ---------------------- |
| `text`           | `string` | Yes      | Message text to send   |
| `conversationId` | `string` | No       | Target conversation ID |

**Use cases:**

* Start conversation with a suggested message
* Send contextual help based on page content
* Pre-fill messages based on user actions

***

#### `showGreeting(data)`

Shows a greeting message to the user with optional sender information.

```javascript theme={null}
// Show default greeting
BubblaV.showGreeting();

// Show custom message
BubblaV.showGreeting('Hi! How can I help you today?');

// Show greeting with sender info
BubblaV.showGreeting({
  message: 'Hi! How can I help you today?',
  senderName: 'Support Team',
  senderAvatarUrl: 'https://example.com/avatar.png',
  timestamp: new Date().toISOString()
});
```

| Parameter | Type                 | Required | Description                                                                           |
| --------- | -------------------- | -------- | ------------------------------------------------------------------------------------- |
| `data`    | `string` \| `object` | No       | Message string or object with `message`, `senderName`, `senderAvatarUrl`, `timestamp` |

**Use cases:**

* Display contextual greetings based on page
* Show agent-specific messages with avatar
* Time-based greetings (good morning, etc.)
* Campaign-specific messages

***

#### `hideGreeting()`

Hides the greeting message.

```javascript theme={null}
BubblaV.hideGreeting();
```

***

### Configuration

#### `getConfig()`

Gets the current widget configuration.

```javascript theme={null}
const config = BubblaV.getConfig();
console.log('Widget config:', config);
```

**Returns:** `object` with current configuration

***

#### `setDebug(enabled)`

Enables or disables debug mode.

```javascript theme={null}
// Enable debug mode
BubblaV.setDebug(true);

// Disable debug mode
BubblaV.setDebug(false);
```

<Warning>
  Only enable debug mode in development. It logs detailed information to the console.
</Warning>

***

## Event System

The SDK emits events for various widget actions. Listen to events to respond to user interactions.

### `on(event, callback)`

Register an event listener.

```javascript theme={null}
BubblaV.on('chat:opened', () => {
  console.log('Chat widget opened');
});

BubblaV.on('message:received', (message) => {
  console.log('New message:', message);
});
```

### `off(event, callback)`

Unregister an event listener.

```javascript theme={null}
const handler = () => console.log('Chat opened');

BubblaV.on('chat:opened', handler);
// Later...
BubblaV.off('chat:opened', handler);
```

***

## Available Events

| Event                | Description                                              | Payload                                                                               |
| -------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `chat:opened`        | Triggered when the chat widget is opened.                | `undefined`                                                                           |
| `chat:closed`        | Triggered when the chat widget is closed.                | `undefined`                                                                           |
| `search:opened`      | Triggered when the search interface is opened.           | `{ mode: string }`                                                                    |
| `search:closed`      | Triggered when the search interface is closed.           | `{ mode: string }`                                                                    |
| `message:sent`       | Triggered when a message is sent by the user.            | `{ conversation_id: string, text: string }`                                           |
| `message:received`   | Triggered when a message is received from the bot/agent. | `{ conversation_id: string, message_id: string, text: string, fromVisitor: boolean }` |
| `message:rated`      | Triggered when a specific message is rated.              | `{ conversation_id: string, message_id: string, rating: 'up' \| 'down' }`             |
| `conversation:rated` | Triggered when the conversation is rated.                | `{ conversation_id: string, rating: number }`                                         |
| `widget:expanded`    | Triggered when the widget is expanded (desktop).         | `undefined`                                                                           |
| `widget:collapsed`   | Triggered when the widget is collapsed (desktop).        | `undefined`                                                                           |
| `search:query`       | Triggered when a search query is submitted.              | `{ query: string, source: "input" \| "suggestion" }`                                  |
| `ready`              | Triggered when the widget is fully loaded.               | `undefined`                                                                           |

***

## Framework Examples

### React

#### Using Hooks

```tsx theme={null}
'use client';

import { useRef } from 'react';
import { BubblaVWidget, useBubblaVWidget, useBubblaVEvent } from '@bubblav/ai-chatbot-react';
import type { BubblaVWidgetRef } from '@bubblav/ai-chatbot-react';

function SupportButton() {
  const widgetRef = useRef<BubblaVWidgetRef>(null);
  const widget = useBubblaVWidget();

  // Listen to events
  useBubblaVEvent('chat:opened', () => {
    console.log('Support chat opened');
  });

  const openSupport = () => {
    widget?.open();
  };

  return (
    <>
      <button onClick={openSupport}>Get Support</button>
      <BubblaVWidget ref={widgetRef} websiteId="your-website-id" />
    </>
  );
}
```

#### Using the Widget Component

```tsx theme={null}
import { BubblaVWidget } from '@bubblav/ai-chatbot-react';

function App() {
  return (
    <BubblaVWidget
      websiteId="your-website-id"
      bubbleColor="#3b82f6"
      position="bottom-right"
    />
  );
}
```

***

### Vue

#### Using Composition API

```vue theme={null}
<script setup>
import { ref } from 'vue';
import { BubblaVWidget, useBubblaVWidget, useBubblaVEvent } from '@bubblav/ai-chatbot-vue';

const widgetRef = ref(null);
const widget = useBubblaVWidget();

// Listen to events
useBubblaVEvent('chat:opened', () => {
  console.log('Support chat opened');
});

const openSupport = () => {
  widget?.open();
};
</script>

<template>
  <button @click="openSupport">Get Support</button>
  <BubblaVWidget ref="widgetRef" website-id="your-website-id" />
</template>
```

#### Using Options API

```vue theme={null}
<script>
import { BubblaVWidget } from '@bubblav/ai-chatbot-vue';

export default {
  components: { BubblaVWidget },
  methods: {
    openSupport() {
      this.$bubblav.open();
    }
  }
};
</script>

<template>
  <button @click="openSupport">Get Support</button>
  <BubblaVWidget website-id="your-website-id" />
</template>
```

***

### Angular

```ts theme={null}
import { Component, inject } from '@angular/core';
import { BubblaVWidgetComponent, BubblaVWidgetService } from '@bubblav/ai-chatbot-angular';

@Component({
  selector: 'app-support',
  standalone: true,
  imports: [BubblaVWidgetComponent],
  template: `
    <button (click)="openSupport()">Get Support</button>
    <bubblav-widget websiteId="your-website-id" />
  `
})
export class SupportComponent {
  private bubblav = inject(BubblaVWidgetService);

  constructor() {
    // Listen to events
    this.bubblav.on('chat:opened', () => {
      console.log('Support chat opened');
    });
  }

  openSupport() {
    this.bubblav.open();
  }
}
```

***

## TypeScript Support

All NPM packages include full TypeScript definitions:

```typescript theme={null}
import type {
  BubblaVWidgetProps,
  BubblaVWidgetRef,
  BubblaVSDK,
  BubblaVEvent
} from '@bubblav/ai-chatbot-react';

// Full type safety
const config: BubblaVWidgetProps = {
  websiteId: 'your-website-id',
  bubbleColor: '#3b82f6',
  position: 'bottom-right'
};

// Type-safe event listeners
const eventHandler: BubblaVEvent<'chat:opened'> = () => {
  console.log('Chat opened');
};
```

***

## Best Practices

1. **Prefer NPM Packages**
   For React, Vue, and Angular projects, use the NPM packages instead of the global SDK for better type safety and lifecycle management.

2. **Wait for Ready State**
   Always check if the SDK is ready before using it:

   ```javascript theme={null}
   BubblaV.ready(() => {
     BubblaV.open();
   });
   ```

3. **Clean Up Listeners**
   Remove event listeners when they're no longer needed:

   ```javascript theme={null}
   const handler = () => console.log('Opened');
   BubblaV.on('chat:opened', handler);
   // Later...
   BubblaV.off('chat:opened', handler);
   ```

4. **Handle Edge Cases**
   Check if methods exist before calling:

   ```javascript theme={null}
   if (BubblaV && typeof BubblaV.open === 'function') {
     BubblaV.open();
   }
   ```

5. **Use Environment Variables**
   Store your website ID in environment variables:

   ```env theme={null}
   # Next.js
   NEXT_PUBLIC_BUBBLAV_WEBSITE_ID=your-website-id

   # Nuxt
   NUXT_PUBLIC_BUBBLAV_WEBSITE_ID=your-website-id
   ```

   ```tsx theme={null}
   <BubblaVWidget websiteId={process.env.NEXT_PUBLIC_BUBBLAV_WEBSITE_ID} />
   ```

***

## Full SDK Reference

```typescript theme={null}
interface BubblaVSDK {
  // Widget control
  open(): void;
  close(): void;
  toggle(): void;
  openSearch(): void;
  isOpen(): boolean;

  // Messaging
  sendMessage(text: string, conversationId?: string): void;
  showGreeting(data: string | { message?: string; senderName?: string; senderAvatarUrl?: string; timestamp?: string }): void;
  hideGreeting(): void;

  // Configuration
  getConfig(): Record<string, unknown>;
  setDebug(enabled: boolean): void;

  // Events
  on(event: string, callback: (...args: unknown[]) => void): void;
  off(event: string, callback: (...args: unknown[]) => void): void;
  emit(event: string, data?: unknown): void;

  // Lifecycle
  ready(callback: () => void): void;

  // Analytics
  track(eventName: string, properties?: Record<string, unknown>): void;
}
```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Widget Design" icon="palette" href="/user-guide/widget-design">
    Customize widget appearance and behavior
  </Card>

  <Card title="Starter Templates" icon="code" href="/developer-guide/starter-templates">
    Quick-start templates for Next.js and Nuxt
  </Card>
</CardGroup>
