@zango-core/nice-telephony
v0.1.0
Published
React hook-based NICE telephony calling package for Zango applications
Readme
@zango-core/nice-telephony
React hook-based NICE telephony calling package for Zango applications.
Installation
pnpm add @zango-core/nice-telephonyFeatures
- 🎯 Simple Hook API - Single
useNiceTelephonyhook for all telephony operations - 🔄 Auto-initialization - Automatically initializes on mount (configurable)
- 📞 Call Management - Place calls with comprehensive state tracking
- 🔔 Real-time Events - Built-in event polling for call state updates
- 🎨 TypeScript Support - Full type definitions included
- 🔧 Configurable - Customizable API endpoints, timeouts, and callbacks
- 📊 State Management - Powered by Zustand for efficient state updates
- 🎉 Notifications - Built-in toast notifications with react-hot-toast
Quick Start
Basic Usage
import { useNiceTelephony } from '@zango-core/nice-telephony';
function CallButton() {
const { placeCall, callState, isInitialized } = useNiceTelephony();
const handleCall = async () => {
const result = await placeCall({
destinationNumber: '+1234567890'
});
if (result.success && result.notesLink) {
window.open(result.notesLink, '_blank');
}
};
return (
<button
onClick={handleCall}
disabled={!isInitialized || callState !== 'idle'}
>
{callState === 'dialing' ? 'Dialing...' : 'Call Patient'}
</button>
);
}With Configuration
import { useNiceTelephony } from '@zango-core/nice-telephony';
function MyComponent() {
const telephony = useNiceTelephony({
autoInitialize: true,
maxRetries: 3,
eventPollTimeout: 60,
enableNotifications: true,
onCallStateChange: (state) => {
console.log('Call state changed:', state);
},
onError: (error) => {
console.error('Telephony error:', error);
}
});
return (
<div>
<p>Status: {telephony.sessionState}</p>
<p>Agent ID: {telephony.agentId}</p>
{/* Your UI here */}
</div>
);
}API Reference
useNiceTelephony(config?)
Main hook that provides all telephony functionality.
Configuration Options
interface UseNiceTelephonyConfig {
autoInitialize?: boolean; // Auto-init on mount (default: true)
maxRetries?: number; // Session join retry count (default: 3)
eventPollTimeout?: number; // Event polling timeout in seconds (default: 60)
onCallStateChange?: (state: CallState) => void; // Call state change callback
onError?: (error: NiceError) => void; // Error callback
baseApiUrl?: string; // Custom API base URL
enableNotifications?: boolean; // Show toast notifications (default: true)
}Return Value
interface UseNiceTelephonyReturn {
// Initialization
initialize: () => Promise<void>;
isInitialized: boolean;
isInitializing: boolean;
// Call Management
placeCall: (options: PlaceCallOptions) => Promise<PlaceCallResult>;
// State
callState: CallState; // 'idle' | 'dialing' | 'active' | 'disconnected'
sessionState: SessionState; // 'disconnected' | 'connecting' | 'connected'
agentState: AgentState; // 'available' | 'busy' | 'unavailable'
// Session Info
sessionId: string | null;
agentId: string | null;
// Error Handling
lastError: NiceError | null;
clearError: () => void;
// Advanced
disconnect: () => void;
reconnect: () => Promise<void>;
}placeCall(options)
Place an outbound call.
Options
interface PlaceCallOptions {
destinationNumber: string; // Required: Phone number to call
notesKey?: string; // Optional: Key for notes reference
callbackUrl?: string; // Optional: URL for callback handling
callbackPackage?: string; // Optional: Package identifier for callback
recordUuid?: string; // Optional: UUID for recording reference
}Return Value
interface PlaceCallResult {
success: boolean;
notesLink?: string; // Link to call notes (if available)
error?: string; // Error message (if failed)
}Advanced Usage
Manual Initialization
const telephony = useNiceTelephony({
autoInitialize: false // Disable auto-initialization
});
// Initialize manually when needed
const handleLogin = async () => {
await telephony.initialize();
};Custom API Endpoint
const telephony = useNiceTelephony({
baseApiUrl: '/custom/telephony/api/endpoint'
});Accessing Zustand Store (Advanced)
For advanced use cases, you can directly access the Zustand store:
import { useNiceTelephonyStore } from '@zango-core/nice-telephony';
function AdvancedComponent() {
const callState = useNiceTelephonyStore((state) => state.callState);
const setCallState = useNiceTelephonyStore((state) => state.setCallState);
// Use store selectors for optimal re-renders
return <div>Call State: {callState}</div>;
}Error Handling
const telephony = useNiceTelephony({
onError: (error) => {
switch (error.type) {
case 'AUTH_ERROR':
console.error('Authentication failed:', error.message);
break;
case 'SESSION_ERROR':
console.error('Session error:', error.message);
break;
case 'CALL_ERROR':
console.error('Call failed:', error.message);
break;
case 'EVENT_POLLING_ERROR':
console.error('Event polling error:', error.message);
break;
case 'INITIALIZATION_ERROR':
console.error('Initialization failed:', error.message);
break;
}
}
});TypeScript Support
Full TypeScript definitions are included. Import types as needed:
import type {
CallState,
AgentState,
SessionState,
NiceError,
PlaceCallOptions,
PlaceCallResult,
UseNiceTelephonyConfig,
UseNiceTelephonyReturn
} from '@zango-core/nice-telephony';API Endpoints
Default hardcoded endpoints (can be overridden via baseApiUrl config):
- Get Tokens:
/nice/telephony/api/?action=get_tokens - Join Session:
/nice/telephony/api/?action=agent_session_join - Get Events:
/nice/telephony/api/?action=get_next_event - Place Call:
/telephony/api/view/?action=call&provider=nice - Route Call:
/nice/telephony/api/?action=route_call - Update Call:
/nice/telephony/api/?action=update_call_details
Dependencies
This package has the following peer dependencies:
react^18.0.0react-dom^18.0.0
And includes these dependencies:
axios- HTTP clientzustand- State management
Build
# Development
pnpm dev
# Build library
pnpm build
# Build and watch
pnpm build:watch
# Preview build
pnpm previewPackage Structure
@zango-core/nice-telephony/
├── dist/
│ ├── zango-nice-telephony.js # ES Module
│ ├── zango-nice-telephony.umd.cjs # UMD Module
│ ├── index.d.ts # TypeScript declarations
│ └── *.map # Source maps
├── src/
│ ├── hooks/ # React hooks
│ ├── stores/ # Zustand stores
│ ├── services/ # API services
│ ├── types/ # TypeScript types
│ ├── utils/ # Utilities
│ ├── constants/ # Constants
│ └── index.ts # Main exports
└── package.jsonLicense
ISC
Author
Zango Team
