@buni.ai/chatbot-angular
v1.0.17
Published
Angular components and services for BuniAI chat widget
Maintainers
Readme
@buni.ai/chatbot-angular
Angular components and services for seamless BuniAI chat widget integration.
🚀 Quick Start
Installation
npm install @buni.ai/chatbot-angularBasic Usage
Option 1: Using the Service (Recommended)
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { BuniChatService } from '@buni.ai/chatbot-angular';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
template: `
<div>
<h1>My Angular App</h1>
<button (click)="toggle()">
{{ (isOpen$ | async) ? 'Close Chat' : 'Open Chat' }}
</button>
<button (click)="setCustomer()">
Set Customer Data
</button>
<p>Unread messages: {{ unreadCount$ | async }}</p>
<p>Widget ready: {{ (isReady$ | async) ? 'Yes' : 'No' }}</p>
</div>
`
})
export class AppComponent implements OnInit {
isOpen$: Observable<boolean>;
isReady$: Observable<boolean>;
unreadCount$: Observable<number>;
constructor(private buniChatService: BuniChatService) {
this.isOpen$ = this.buniChatService.isOpen$;
this.isReady$ = this.buniChatService.isReady$;
this.unreadCount$ = this.buniChatService.unreadCount$;
}
async ngOnInit() {
await this.buniChatService.initialize({
token: 'your-widget-token',
config: {
position: 'bottom-right',
theme: 'light',
primaryColor: '#007bff'
},
onReady: () => {
console.log('✅ BuniAI widget loaded!');
},
onNewMessage: (data) => {
console.log('💬 New message:', data);
}
});
}
toggle() {
this.buniChatService.toggle();
}
setCustomer() {
this.buniChatService.setCustomerData({
name: 'John Doe',
email: '[email protected]',
userId: '12345'
});
}
}Option 2: Using the Component
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<div>
<h1>My Angular App</h1>
<buni-chat-widget
token="your-widget-token"
[config]="{
position: 'bottom-right',
theme: 'light'
}"
[onReady]="onReady"
[onNewMessage]="onNewMessage">
</buni-chat-widget>
</div>
`
})
export class AppComponent {
onReady = () => {
console.log('Widget is ready!');
};
onNewMessage = (data: any) => {
console.log('New message received:', data);
};
}Option 3: Using the Module
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BuniChatModule } from '@buni.ai/chatbot-angular';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
BuniChatModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }<!-- app.component.html -->
<div>
<h1>My Angular App</h1>
<buni-chat-widget token="your-widget-token"></buni-chat-widget>
<buni-chat-button
[showText]="true"
openText="Chat with us"
closeText="Close chat"
(clicked)="onChatToggled($event)">
</buni-chat-button>
</div>📖 API Reference
BuniChatService
Injectable service for managing the BuniAI chat widget.
Properties
class BuniChatService {
// Observable state
state$: Observable<BuniChatState>;
isOpen$: Observable<boolean>;
isReady$: Observable<boolean>;
isMinimized$: Observable<boolean>;
unreadCount$: Observable<number>;
}Methods
| Method | Parameters | Returns | Description |
|--------|------------|---------|-------------|
| initialize | options: BuniChatOptions | Promise<void> | Initialize the widget |
| show | - | void | Show the chat widget |
| hide | - | void | Hide the chat widget |
| toggle | - | void | Toggle widget visibility |
| minimize | - | void | Minimize the widget |
| maximize | - | void | Maximize the widget |
| destroy | - | void | Destroy the widget instance |
| setCustomerData | data: CustomerData | void | Set customer information |
| getCustomerData | - | CustomerData \| null | Get current customer data |
| setSessionVariables | variables: SessionVariables | void | Set session variables |
| sendMessage | message: string | void | Send a message |
| clearChat | - | void | Clear chat history |
<buni-chat-widget>
Angular component for rendering the chat widget.
Inputs
| Input | Type | Default | Description |
|-------|------|---------|-------------|
| token | string | - | Your BuniAI widget token (required) |
| config | object | {} | Widget configuration options |
| onReady | function | - | Callback when widget is ready |
| onNewMessage | function | - | Callback for new messages |
| onVisibilityChanged | function | - | Callback for visibility changes |
| onError | function | - | Callback for errors |
<buni-chat-button>
Floating chat button component.
Inputs
| Input | Type | Default | Description |
|-------|------|---------|-------------|
| openText | string | 'Chat with us' | Text when chat is closed |
| closeText | string | 'Close chat' | Text when chat is open |
| showText | boolean | true | Whether to show text |
Outputs
| Output | Type | Description |
|--------|------|-------------|
| clicked | EventEmitter<boolean> | Emitted when button is clicked |
Configuration Options
interface BuniChatOptions {
token: string;
config?: {
position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
theme?: 'light' | 'dark' | 'auto';
primaryColor?: string;
welcomeMessage?: string;
placeholder?: string;
showBranding?: boolean;
};
onReady?: (data: any) => void;
onNewMessage?: (data: any) => void;
onVisibilityChanged?: (data: any) => void;
onError?: (error: Error) => void;
}🎯 Advanced Examples
Reactive State Management
import { Component, OnInit, OnDestroy } from '@angular/core';
import { BuniChatService } from '@buni.ai/chatbot-angular';
import { Subject, takeUntil, combineLatest } from 'rxjs';
@Component({
selector: 'app-chat-manager',
template: `
<div class="chat-status">
<div *ngIf="chatState$ | async as state">
<p>Status: {{ state.isLoaded ? 'Ready' : 'Loading...' }}</p>
<p>Visibility: {{ state.isOpen ? 'Open' : 'Closed' }}</p>
<p>Unread: {{ state.unreadCount }}</p>
<p>Minimized: {{ state.isMinimized ? 'Yes' : 'No' }}</p>
</div>
<button (click)="toggleChat()" [disabled]="!(isReady$ | async)">
Toggle Chat
</button>
</div>
`
})
export class ChatManagerComponent implements OnInit, OnDestroy {
private destroy$ = new Subject<void>();
chatState$ = this.buniChatService.state$;
isReady$ = this.buniChatService.isReady$;
constructor(private buniChatService: BuniChatService) {}
async ngOnInit() {
await this.buniChatService.initialize({
token: 'your-token',
config: { position: 'bottom-right' }
});
// Listen to state changes
this.chatState$
.pipe(takeUntil(this.destroy$))
.subscribe(state => {
console.log('Chat state changed:', state);
});
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
toggleChat() {
this.buniChatService.toggle();
}
}Custom Customer Data Management
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { BuniChatService } from '@buni.ai/chatbot-angular';
@Component({
selector: 'app-customer-form',
template: `
<form [formGroup]="customerForm" (ngSubmit)="updateCustomer()">
<input formControlName="name" placeholder="Name" />
<input formControlName="email" placeholder="Email" />
<select formControlName="plan">
<option value="free">Free</option>
<option value="pro">Pro</option>
<option value="enterprise">Enterprise</option>
</select>
<button type="submit">Update Customer Data</button>
</form>
`
})
export class CustomerFormComponent implements OnInit {
customerForm: FormGroup;
constructor(
private fb: FormBuilder,
private buniChatService: BuniChatService
) {
this.customerForm = this.fb.group({
name: [''],
email: [''],
plan: ['free']
});
}
async ngOnInit() {
await this.buniChatService.initialize({
token: 'your-token'
});
}
updateCustomer() {
const formValue = this.customerForm.value;
this.buniChatService.setCustomerData({
name: formValue.name,
email: formValue.email,
userId: `user_${Date.now()}`,
customFields: {
plan: formValue.plan,
registrationDate: new Date().toISOString()
}
});
}
}Integration with NgRx Store
// chat.effects.ts
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { BuniChatService } from '@buni.ai/chatbot-angular';
import { switchMap, map, catchError } from 'rxjs/operators';
import { of } from 'rxjs';
@Injectable()
export class ChatEffects {
initializeChat$ = createEffect(() =>
this.actions$.pipe(
ofType(ChatActions.initializeChat),
switchMap(action =>
this.buniChatService.initialize(action.options).then(() =>
ChatActions.initializeChatSuccess()
).catch(error =>
ChatActions.initializeChatFailure({ error })
)
)
)
);
constructor(
private actions$: Actions,
private buniChatService: BuniChatService
) {}
}
// chat.component.ts
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { BuniChatService } from '@buni.ai/chatbot-angular';
import { ChatActions } from './store/chat.actions';
@Component({
selector: 'app-chat',
template: `
<div>
<button (click)="initializeFromStore()">Initialize via Store</button>
<button (click)="toggle()">Toggle Chat</button>
</div>
`
})
export class ChatComponent {
constructor(
private store: Store,
private buniChatService: BuniChatService
) {}
initializeFromStore() {
this.store.dispatch(ChatActions.initializeChat({
options: {
token: 'your-token',
config: { position: 'bottom-right' }
}
}));
}
toggle() {
this.buniChatService.toggle();
}
}Event Handling with RxJS
import { Component, OnInit, OnDestroy } from '@angular/core';
import { BuniChatService } from '@buni.ai/chatbot-angular';
import { Subject, takeUntil, filter, debounceTime } from 'rxjs';
@Component({
selector: 'app-chat-analytics',
template: `
<div>
<p>Messages received: {{ messageCount }}</p>
<p>Chat opened: {{ openCount }} times</p>
<p>Last activity: {{ lastActivity | date:'medium' }}</p>
</div>
`
})
export class ChatAnalyticsComponent implements OnInit, OnDestroy {
private destroy$ = new Subject<void>();
messageCount = 0;
openCount = 0;
lastActivity: Date | null = null;
constructor(private buniChatService: BuniChatService) {}
async ngOnInit() {
await this.buniChatService.initialize({
token: 'your-token',
onNewMessage: (data) => {
this.messageCount++;
this.lastActivity = new Date();
},
onVisibilityChanged: (data) => {
if (data.visibility === 'visible') {
this.openCount++;
}
this.lastActivity = new Date();
}
});
// Track state changes with RxJS
this.buniChatService.state$
.pipe(
takeUntil(this.destroy$),
filter(state => state.isLoaded),
debounceTime(1000)
)
.subscribe(state => {
console.log('Chat analytics update:', {
messageCount: this.messageCount,
openCount: this.openCount,
unreadCount: state.unreadCount
});
});
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}🔧 TypeScript Support
Full TypeScript support is included:
import {
BuniChatOptions,
CustomerData,
SessionVariables,
BuniChatState
} from '@buni.ai/chatbot-angular';
const options: BuniChatOptions = {
token: 'your-token',
config: {
position: 'bottom-right',
theme: 'light'
}
};
const customerData: CustomerData = {
name: 'John Doe',
email: '[email protected]',
userId: '12345'
};🤝 Requirements
- Angular 15+
- RxJS 7+
- Modern browser with ES2020 support
📦 Module Import
import { NgModule } from '@angular/core';
import { BuniChatModule } from '@buni.ai/chatbot-angular';
@NgModule({
imports: [BuniChatModule],
// ...
})
export class AppModule { }📝 License
MIT © BuniAI
