# Programmatic installation

For more control over initialization and configuration, you can create and manage the chat widget programmatically. Make sure to include programatic configuration in the script tag so that the chat widget does not open automatically:

```auto
<script
  src="https://cal.assembledhq.com/static/js/public-chat.js"
  data-company-id="YOUR_COMPANY_ID"
  data-disable-auto-init="true"
  data-debug="true"
></script>
```

Next, initialize the chat widget in javascript when you’d like to see the widget appear by invoking the async `init` function like so:

```auto
// Initialize the chat widget separately
await window.assembled.init();
```

## Configuration options

The chat widget can be configured with the following options:

| Option | Type | Description |
| --- | --- | --- |
| `data-company-id` | string | **Required.** Your Assembled company identifier |
| `data-profile-id` | string | Target a specific chat profile within your company |
| `data-disable-auto-init` | boolean | When enabled, will prevent the chat widget launcher from appearing by default. |
| `data-disable-close-button` | boolean | When enabled, will hide the "X" close button in the chat header. |
| `data-activated` | boolean | Override the default activation state. Overriding this setting means that the activation settings on the chat settings page will no longer have any effect. |
| `data-button-color` | string | Set the button color for the chat button. By default, this property is defined in the chat settings page. |
| `data-disable-launcher` | boolean | When set to "true", will prevent the launcher from being shown. Best used when there is a separate button or entry point that opens the widget itself from within your own UI. By default, this property is defined in the chat settings page. |
| `data-disable-header` | boolean | When set to "true", will prevent the header from being shown. Best used in conjunction with the "embedded" display mode. |
| `data-launcher-size` | string | Set the size of the chat widget launcher. Valid values are `small`, `medium` , `large`. By default, this property is defined in the chat settings page. |
| `data-launcher-position` | string | Set the position of the chat widget launcher. Valid values are `bottom-right`, `bottom-left` , `top-right`, and `top-left`. |
| `data-launcher-offset-x` | number | Set the horizontal offset of the chat widget launcher. Default is 10px. |
| `data-launcher-offset-y` | number | Set the vertical offset of the chat widget launcher. Default is 10px. |
| `data-icon-src` | string | Set the icon URL for the chat widget launcher. By default, this property is defined in the chat settings page. |
| `data-open-chat-text` | string | Set the custom text displayed when hovering over closed launcher. By default, this property is defined in the chat settings page. |
| `data-close-chat-text` | string | Set the custom text displayed when hovering over open launcher. By default, this property is defined in the chat settings page. |
| `data-enable-gradient` | boolean | Enable gradient styling on the launcher button. By default, this property is defined in the chat settings page. |
| `data-enable-dragging` | boolean | Make the launcher draggable by users. By default, this property is defined in the chat settings page. |
| `data-attachment-icon-variant` | string | Set the icon displayed for the file attachment button in the text input bar. Valid values are `paperclip`,` plus`, `image`. The default value is `paperclip`. |
| `data-input-border-radius` | string | Set the border radius of the text input bar at the bottom of the chat widget (e.g. `6px`). |
| `data-message-border-radius` | string | Set the border radius of chat message bubbles (e.g. `6px`). |
| `data-debug` | boolean | Enable debugging and logging in the browser console for easier implementation. Remove this property on production. |

## Widget control

### Showing or hiding the launcher button

The launcher button is the entry point that users can click to start a conversation.

```auto
// Open the launcher button
window.assembled.showLauncher();

// Hide the launcher button
window.assembled.hideLauncher();
```

### Opening and closing the chat widget

The widget contains the complete chat interface where users can type messages and view responses.

```auto
// Open the chat widget (will also show the launcher)
window.assembled.open();

// Close the chat widget
window.assembled.close();
```

### Adjusting position of the chat widget

The widget supports programmatic positioning of the launcher through the setPosition method, which allows you to anchor the chat widget to a corner with customer margins.

```auto
window.assembled.setPosition({
  anchor: 'bottom-right', // 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
  offsetX: 25, // px from horizontal edge
  offsetY: 25 // px from vertical edge
});
```

Note: The provided position is validated against the viewport and will default to the original position of the launcher if the provided position is outside of the viewport. The function will return true if the position was successfully applied and false if the position is invalid or out of bounds.

### Dragging control

Enable or disable the ability for users to drag the launcher around the screen:

```auto
// Enable dragging
window.assembled.setDraggable(true);

// Disable dragging
window.assembled.setDraggable(false);
```

Note: When dragging is enabled, users can click and drag the launcher to reposition it. The position is automatically saved and restored on subsequent page loads.

### Debug mode

Control debug logging to help with development and troubleshooting:

```auto
// Enable debug logging
window.assembled.setDebug(true);

// Disable debug logging
window.assembled.setDebug(false);
```

Debug messages are prefixed with [Assembled] and logged to the browser console.

### Checking loading status

Determine if the chat widget has finished loading and is ready for interaction:

```auto
const isReady = window.assembled.isReady();
```

### Integration with Single Page Applications (SPAs)

Use the teardown function to prevent memory leaks and degraded performance in your SPA.

```auto
// Cleanup and remove the entire chat widget
window.assembled.teardown();
```

### Activation management

The chat widget supports two modes of activation control:

1. **Server-Controlled Activation**: By default, Assembled manages the activation state of the chat widget based on your settings in the Assembled dashboard.
2. **Client-Side Override**: You can override the server activation state by setting the `activated` option during initialization:

```auto
const chat = window.assembled.createAssembledChat({
  companyId: 'YOUR_COMPANY_ID',
  activated: true // Force activation regardless of server settings
});
```

### Style customization

While we recommend using the default styles configured in your Assembled dashboard, you can override them for specific pages:

```auto
const chat = createAssembledChat({
  companyId: 'YOUR_COMPANY_ID',
  buttonColor: '#FF0000',                      // Custom button color (hex)
  launcherSize: 'large',                       // Custom launcher size
  iconSrc: 'https://your-domain.com/icon.png', // Custom launcher icon
  openChatText: 'Need help?',                  // Custom open text
  closeChatText: 'Close support',              // Custom close text
  enableGradient: true,                        // Enable gradient effect
  launcherZIndex: 99999                        // Control stacking order
});
```

## Embedded Display Mode

Embedded mode allows you to place the chat widget directly inside a container element on your page, giving you full control over where the chat appears within your layout.

### Manual Script Tag Configuration

You can configure embedded mode directly in the script tag:

```auto
<!-- Add a container element in your HTML -->
<div id="chat-container"></div>

<!-- Add the script with embedded mode attributes -->
<script
  src="https://cal.assembledhq.com/static/js/public-chat.js"
  data-company-id="YOUR_COMPANY_ID"
  data-profile-id="YOUR_PROFILE_ID"
  data-display-mode="embedded"
  data-embedded-container="#chat-container"
></script>
```

### Configuration via Chat Settings

You can also configure embedded mode through the Chat Settings UI:

- Navigate to **Chat Settings** → **Theme** tab
- Under **Display mode**, select "Embedded"
- In the **Container** selector field, enter a CSS selector (e.g., `#chat-container` or `.chat-wrapper`)
- Save your settings

#### Important Notes:

- The container element must exist in the DOM before the script loads
- The container selector must be unique on the page
- The embedded widget will fill its container; ensure the container has appropriate dimensions

## Event handling

The chat widget dispatches custom events that you can listen for to track user interactions and widget behavior. All events are dispatched through a unified `assembledevent` event with detailed payload information.

### Listening to events

To listen for chat widget events, add an event listener for `assembledevent`:

```auto
window.addEventListener('assembledevent', (event) => {
  const { event_type, payload } = event.detail;
  console.log('Event type:', event_type);
  console.log('Event payload:', payload);
});
```

You can also track specific events by checking the event type:

```auto
window.addEventListener('assembledevent', (event) => {
  const { event_type, payload } = event.detail;

switch (event_type) {
    case 'load':
      console.log('Chat widget loaded');
      window.assembled.isReady() // true if widget is ready
      break;
    case 'error':
      console.error('Chat widget failed to load:', payload);
      break;
    case 'open':
      console.log('Chat widget opened');
      break;
    case 'message_sent':
      console.log('User sent a message:', payload.message);
      break;
    case 'handoff_triggered':
      console.log('Conversation triggered the handoff form, type:', payload.escalation_type);
      break;
    case 'handoff_submitted':
      console.log('Handoff submitted, type:', payload.escalation_type);
      break;
  }
});
```

### Available event types

Below is a list of the available event types, along with their payloads and corresponding Typescript types:

|     |     |     |
| --- | --- | --- |
| Event type | Description | Payload |
| `load` | Widget has loaded and is ready for interaction | None |
| `error` | Widget failed to load and could not initialize | None |
| `open` | Widget was opened | None |
| `close` | Widget was closed | None |
| `message_sent` | User sent a message on the chat interface | ```auto<br>{ <br>  message: string;<br>  role: 'user' | 'assistant' | 'agent';<br>  created_at: number;<br>}<br>``` |
| `message_received` | Message received from the AI or a human agent | ```auto<br>{ <br>  message: string;<br>  role: 'user' | 'assistant' | 'agent';<br>  created_at: number;<br>}<br>``` |
| `handoff_triggered` | Conversation triggered an escalation to an agent and the handoff form was displayed. | ```auto<br>{<br>  escalation_type?: 'live_chat' | 'case' | 'form_link' | 'none';<br>}<br>``` |
| `handoff_submitted` | User submitted the handoff form with their information and is being connected to a human agent (either via email or live chat). | ```auto<br>{<br>  email: string;<br>  name?: string;<br>  description?: string;<br>  additional_fields?: Record<string, string>;<br>  selected_case_tagging_option_id?: string;<br>  escalation_type?: 'live_chat' | 'case' | 'form_link' | 'none';<br>}<br>``` |
| `csat_submitted` | User submitted the satisfaction survey | ```auto<br>{ <br>  rating: number;<br>  additional_feedback?: string;<br>}<br>``` |

#### Escalation Type

The `escalation_type` field, available on `handoff_triggered` and `handoff_submitted` indicates the destination of the handoff.

- `live_chat` 
- `case` 
- `form_link` 
- `none`

**Note**: The escalation_type reflects the actual escalation path taken at runtime, which may differ from the configured default if business hours fallback is enabled.

## Mobile responsiveness

The chat widget automatically adjusts its layout for mobile devices (screens <= 480px width). On mobile:

- The widget expands to full screen
- The launcher position adjusts automatically
- Touch interactions are optimized for mobile use

## Error handling

The chat widget includes built-in error handling and logging. Common errors will be logged to the console with the prefix `[Assembled]`. We recommend monitoring these logs during implementation and testing.

## Best practices

1. **Initialization**: Always initialize the chat widget after the DOM is loaded
2. **Authentication**: Implement user authentication early in your page lifecycle
3. **Cleanup**: Call `teardown()` when removing the widget from the page
4. **Mobile**: Test thoroughly on mobile devices
5. **Error Handling**: Monitor console logs during implementation
