UNPKG

@agentman/chat-widget

Version:

Agentman Chat Widget for easy integration with web applications

379 lines (378 loc) 10.1 kB
import type { ChatConfig, ChatTheme } from './types/types'; /** * ChatWidget - Refactored component-based chat widget with welcome screen * * This simplified version delegates UI management to ViewManager and focuses on: * - Orchestrating component interactions * - Managing widget lifecycle * - Handling agent initialization * - Coordinating state and persistence */ export declare class ChatWidget { private static instances; private config; private state; private element; private containerId; private theme; private assets; private configManager; private stateManager; private styleManager; private persistenceManager; private promptManager; private stickyElementObserver; private viewManager; private conversationManager; private apiService; private messageService; private agentService; private isSwitchingConversation; private floatingPromptsTimeout; private inputBarCleanup; private inputBarTypewriterCleanup; private eventBus; private errorHandler; private messageHandler; private fileHandler; private conversationOrchestrator; private logger; private eventSubscriptions; private supportedMimeTypes; private supportsAttachments; private agentCapabilities; private isInitializingAgent; private isInputBarFullMode; private inputBarSheetController; private resizeTimeout; private saveDebounceTimer; private urlChangeDebounceTimer; private boundHandleResize; private boundHandleUrlChange; private welcomeCardStateMap; private isWelcomeCardAnimating; private activeWelcomeCard; constructor(config: ChatConfig & { containerId: string; }); /** * Initialize configuration */ private initializeConfig; /** * Initialize state management */ private initializeState; /** * Initialize assets and theme */ private initializeAssets; /** * Initialize core services */ private initializeServices; /** * Initialize core managers (but not agent yet) */ private initializeManagers; /** * Create the widget structure and view manager */ private createWidget; /** * Initialize sheet behavior for input-bar-full mode */ private initializeInputBarFullModeUI; private expandInputBarFullSheet; private collapseInputBarFullSheet; /** * Mount widget to appropriate container */ private mountToContainer; /** * Setup event listeners for EventBus communication */ private setupEventListeners; /** * Emit toggle event (called by ViewManager) */ private emitToggleEvent; /** * Handle expand button click */ private handleExpand; /** * Emit send event (called by ViewManager) */ private emitSendEvent; /** * Handle input key events */ private handleInputKey; /** * Emit prompt click event (called by ViewManager) */ private emitPromptClickEvent; /** * Handle attachment button click */ private handleAttachmentClick; /** * Handle file selection */ private handleFileSelect; /** * Handle attachment removal */ private handleAttachmentRemove; /** * Handle view transitions */ private handleViewTransition; /** * Handle window resize */ private handleResize; /** * Handle URL changes for dynamic prompts (debounced) */ private handleUrlChange; /** * Get resolved prompts based on current URL */ private getResolvedPrompts; /** * Handle state changes */ private handleStateChange; /** * Update UI based on current state */ private updateUI; /** * Update responsive layout */ private updateResponsiveLayout; /** * Ensure FileHandler is initialized */ private ensureFileHandler; /** * Ensure a conversation exists, creating one if necessary * Used when files are uploaded from welcome screen */ private ensureConversationExists; /** * Ensure ConversationOrchestrator is initialized */ private ensureConversationOrchestrator; /** * Public API methods */ /** * Get current view type */ getCurrentView(): 'welcome' | 'conversation'; /** * Start a new conversation (reset to welcome screen) */ startNewConversation(): Promise<void>; /** * Apply theme CSS variables to the widget element */ private applyThemeToWidget; /** * Apply position CSS variables to the widget element */ private applyPositionToWidget; /** * Initialize sticky element observer to detect bottom sticky bars */ private initializeStickyElementObserver; /** * Update theme colors */ updateTheme(theme: Partial<ChatTheme>): void; /** * Get the current conversation ID * Returns null if no conversation has been created yet * @returns {string | null} The current conversation ID or null */ getConversationId(): string | null; /** * Getter property for conversation ID * Provides easy access: chatWidget.conversationId */ get conversationId(): string | null; /** * Destroy the widget and clean up */ destroy(): void; /** * Event Handlers for EventBus communication */ /** * Handle user input events from EventBus */ private handleUserInputEvent; /** * Handle prompt click events from EventBus */ private handlePromptClickEvent; /** * Handle view transition events from EventBus */ private handleViewTransitionEvent; /** * Conversation management methods */ /** * Handle new conversation creation */ private handleNewConversation; /** * Handle conversation switching */ private handleSwitchConversation; /** * Handle conversation deletion */ private handleDeleteConversation; /** * Handle conversations click from welcome screen */ private handleConversationsClickFromWelcome; /** * Handle conversation list view toggle */ private handleToggleListView; /** * Handle minimize button click from conversation list view * This collapses to the variant-specific state */ private handleMinimizeFromConversationList; /** * Setup conversation management features */ private setupConversationManagement; /** * Update conversation header buttons based on current conversation count */ private updateConversationHeaderButtons; /** * Initialize agent and fetch capabilities */ private initializeAgent; /** * Process agent capabilities from API metadata */ private processAgentCapabilities; /** * Get agent capabilities */ getAgentCapabilities(): { supportedMimeTypes: string[]; supportsAttachments: boolean; metadata: any; }; /** * Restore the current conversation from persistence */ private restoreCurrentConversation; /** * Check if floating prompts have been dismissed by user */ private areFloatingPromptsDismissed; /** * Mark floating prompts as dismissed */ private dismissFloatingPrompts; /** * Reset floating prompts dismissal (allow them to show again) * Called when user manually opens widget, showing re-engagement */ private resetFloatingPromptsDismissal; /** * Determine the AgentClosedView mode based on config (with backward compatibility) * Priority: agentClosedView > messagePrompts.show > default */ private getClosedViewMode; /** * Show AgentClosedView based on configuration * Determines which mode to display: toggle-only, floating-prompts, or welcome-card */ private showFloatingPrompts; /** * Hide floating prompts */ private hideFloatingPrompts; /** * Show welcome card (with optional prompts) * @param prompts Optional array of prompt strings to display in the card */ private showWelcomeCard; /** * Apply position-aware card placement based on widget position config */ private applyWelcomeCardPosition; /** * Ensure card stays within viewport boundaries */ private ensureCardInViewport; /** * Dismiss welcome card with collapse animation * @param card The welcome card element to dismiss * @param openWidget Whether to open the widget after dismissing (default: false) * @param shouldDismissPrompts Whether to mark prompts as dismissed in localStorage (default: false) */ private dismissWelcomeCard; /** * Restore toggle button to its original location */ private restoreToggleButton; /** * Cleanup welcome card and remove event listeners * @param shouldDismiss Whether to mark prompts as dismissed in localStorage (default: false) */ private cleanupWelcomeCard; /** * Show modern AI input bar at bottom of screen * @param prompts Optional array of prompt strings */ private showInputBar; /** * Typewriter effect for input bar (single message) */ private startTypewriterEffect; /** * Typewriter effect that cycles through multiple messages */ private startTypewriterEffectCycling; /** * Handle input bar prompt click */ private handleInputBarPromptClick; /** * Handle input bar submission */ private handleInputBarSubmit; /** * Hide input bar and restore toggle button */ private hideInputBar; /** * Escape HTML to prevent XSS */ private escapeHtml; /** * Static methods */ /** * Get existing instance by container ID */ static getInstance(containerId: string): ChatWidget | undefined; /** * Destroy all instances */ static destroyAll(): void; }