@blockspark/chat-widget 1.0.20 → 1.0.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ChatWidget-CkiqiScx.cjs +2 -0
- package/dist/ChatWidget-CkiqiScx.cjs.map +1 -0
- package/dist/{ChatWidget-Bs0XV_7i.js → ChatWidget-CsEN9biV.js} +14 -156
- package/dist/ChatWidget-CsEN9biV.js.map +1 -0
- package/dist/components/ChatWidget.d.ts.map +1 -1
- package/dist/core/stateManager.d.ts +1 -14
- package/dist/core/stateManager.d.ts.map +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +125 -239
- package/dist/index.esm.js.map +1 -1
- package/dist/nuxt.cjs.js +1 -1
- package/dist/nuxt.esm.js +2 -2
- package/dist/sanitize-BYa4jHJ0.cjs +4 -0
- package/dist/sanitize-BYa4jHJ0.cjs.map +1 -0
- package/dist/{sanitize-Cm1kskSD.js → sanitize-Q7JIm8H8.js} +14 -31
- package/dist/sanitize-Q7JIm8H8.js.map +1 -0
- package/dist/services/chatService.d.ts +3 -18
- package/dist/services/chatService.d.ts.map +1 -1
- package/dist/services/dialogflowBackendService.d.ts +2 -0
- package/dist/services/dialogflowBackendService.d.ts.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/vue.cjs.js +1 -1
- package/dist/vue.esm.js +2 -2
- package/package.json +1 -1
- package/dist/ChatWidget-Bs0XV_7i.js.map +0 -1
- package/dist/ChatWidget-PcqRrOmi.cjs +0 -2
- package/dist/ChatWidget-PcqRrOmi.cjs.map +0 -1
- package/dist/sanitize-C8MB41vY.cjs +0 -4
- package/dist/sanitize-C8MB41vY.cjs.map +0 -1
- package/dist/sanitize-Cm1kskSD.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ChatWidget-CsEN9biV.js","sources":["../src/core/stateManager.ts","../src/composables/useChatWidget.ts","../src/components/ChatWidget.vue"],"sourcesContent":["/**\n * State Manager - Framework Agnostic\n * Manages widget state independently of framework\n */\n\nimport type { WidgetState, WidgetConfig, ChatMessage } from './types';\nimport {\n createDialogflowSession,\n sendDialogflowMessage,\n type DialogflowBackendConfig,\n} from '../services/dialogflowBackendService';\nimport { \n createChatService, \n ChatResolvedError,\n type WebSocketMessage\n} from '../services/chatService';\n\nexport class WidgetStateManager {\n private state: WidgetState;\n private config: WidgetConfig;\n private listeners: Set<(state: WidgetState) => void> = new Set();\n private chatMode: 'ai' | 'human' = 'ai';\n private chatId: string | null = null;\n private supportSessionId: string | null = null;\n private chatService: ReturnType<typeof createChatService> | null = null;\n \n // Additional state for human support\n private wsConnected: boolean = false;\n private agentTyping: boolean = false;\n private currentAgent: { name: string; id?: string } = { name: 'Agent' };\n private isConnectingToAgent: boolean = false;\n private agentAccepted: boolean = false;\n private chatResolved: boolean = false;\n private historyLoaded: string | null = null;\n \n // Typing timeout refs (stored as class properties since we can't use refs)\n private typingTimeout: NodeJS.Timeout | null = null;\n private agentTypingTimeout: NodeJS.Timeout | null = null;\n\n constructor(config: WidgetConfig) {\n this.config = config;\n this.state = {\n isOpen: false,\n showWelcomePopup: false,\n messages: [],\n inputValue: '',\n isLoading: false,\n error: null,\n sessionId: null,\n chatMode: 'ai',\n };\n \n // Initialize ChatService\n this.chatService = createChatService({\n baseUrl: this.config.backendBaseUrl || 'http://localhost:8012',\n wsUrl: this.config.backendWsUrl || 'ws://localhost:8012',\n debug: this.config.debug || false,\n });\n \n // Load chat mode and chat IDs from localStorage if available\n if (typeof window !== 'undefined' && window.localStorage) {\n const savedMode = localStorage.getItem('chartsconnectect_chat_mode');\n this.chatMode = savedMode === 'HUMAN' ? 'human' : 'ai';\n this.state.chatMode = this.chatMode;\n \n this.chatId = localStorage.getItem('chartsconnect_chat_id');\n this.supportSessionId = localStorage.getItem('chartsconnect_session_id');\n }\n }\n\n /**\n * Subscribe to state changes\n */\n subscribe(listener: (state: WidgetState) => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Get current state\n */\n getState(): WidgetState {\n return { ...this.state };\n }\n\n /**\n * Update state and notify listeners\n */\n private setState(updates: Partial<WidgetState>): void {\n this.state = { ...this.state, ...updates };\n this.listeners.forEach(listener => listener(this.getState()));\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<WidgetConfig>): void {\n this.config = { ...this.config, ...config };\n }\n\n /**\n * Open chat\n */\n async openChat(): Promise<void> {\n this.setState({ isOpen: true });\n if (this.state.showWelcomePopup) {\n this.setState({ showWelcomePopup: false });\n }\n \n // Initialize Dialogflow session when chat opens (if in AI mode and no session exists)\n if (this.state.chatMode === 'ai' && !this.state.sessionId && this.config.dfProjectId && this.config.dfAgentId) {\n try {\n this.setState({ isLoading: true });\n const dialogflowConfig: DialogflowBackendConfig = {\n dfProjectId: this.config.dfProjectId,\n dfLocation: this.config.dfLocation || 'us-central1',\n dfAgentId: this.config.dfAgentId,\n languageCode: this.config.languageCode || 'en',\n backendBaseUrl: this.config.backendBaseUrl || 'http://localhost:8012',\n };\n \n const session = await createDialogflowSession(dialogflowConfig);\n this.setState({ \n sessionId: session.session_id,\n isLoading: false,\n });\n \n // Add welcome message from Dialogflow if available\n if (session.message) {\n const welcomeMessage: ChatMessage = {\n id: `welcome-${Date.now()}`,\n text: session.message,\n sender: 'bot',\n timestamp: new Date(),\n richContent: session.richContent,\n };\n this.setState({\n messages: [welcomeMessage],\n });\n }\n } catch (error: any) {\n console.error('Error initializing Dialogflow session:', error);\n this.setState({ \n isLoading: false,\n error: error.message || 'Failed to initialize chat',\n });\n \n // Show fallback welcome message\n const fallbackMessage: ChatMessage = {\n id: `fallback-${Date.now()}`,\n text: this.config.fallbackWelcomeMessage || 'Hello! How can I help you today?',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [fallbackMessage],\n });\n }\n }\n }\n\n /**\n * Close chat\n */\n closeChat(): void {\n this.setState({ isOpen: false });\n }\n\n /**\n * Close welcome popup\n */\n closeWelcomePopup(): void {\n this.setState({ showWelcomePopup: false });\n }\n\n /**\n * Toggle chat\n */\n toggleChat(): void {\n const willBeOpen = !this.state.isOpen;\n this.setState({ isOpen: willBeOpen });\n if (willBeOpen && this.state.showWelcomePopup) {\n this.setState({ showWelcomePopup: false });\n }\n }\n\n /**\n * Set input value\n */\n setInputValue(value: string): void {\n this.setState({ inputValue: value });\n }\n\n /**\n * Clear error\n */\n clearError(): void {\n this.setState({ error: null });\n }\n\n /**\n * Send message\n */\n async sendMessage(text: string, skipUserMessage: boolean = false): Promise<void> {\n if (!text.trim() || this.state.isLoading) {\n return;\n }\n\n // Add user message unless skipped (e.g., when chip button already added it)\n if (!skipUserMessage) {\n const userMessage: ChatMessage = {\n id: `user-${Date.now()}`,\n text: text.trim(),\n sender: 'user',\n timestamp: new Date(),\n };\n\n this.setState({\n messages: [...this.state.messages, userMessage],\n inputValue: '',\n isLoading: true,\n error: null,\n });\n } else {\n this.setState({\n inputValue: '',\n isLoading: true,\n error: null,\n });\n }\n\n try {\n if (this.state.chatMode === 'human') {\n // Human support mode\n await this.sendHumanMessage(text);\n } else {\n // AI mode (Dialogflow)\n await this.sendAIMessage(text);\n }\n } catch (error: any) {\n console.error('Error sending message:', error);\n \n // chat_resolved is a normal terminal condition, not an error\n if (error instanceof ChatResolvedError || error?.name === 'ChatResolvedError' || error?.message === 'chat_resolved') {\n this.enterResolvedState(this.chatId);\n return;\n }\n \n // Add error message to chat\n const errorMessage: ChatMessage = {\n id: `error-${Date.now()}`,\n text: this.config.debug \n ? `Error: ${error.message || 'Failed to send message'}`\n : error.message?.includes('CORS') || error.message?.includes('Failed to fetch')\n ? 'Unable to connect to Dialogflow. Please check your configuration and network.'\n : 'Sorry, I\\'m having trouble processing your message. Please try again.',\n sender: 'bot',\n timestamp: new Date(),\n };\n \n this.setState({\n messages: [...this.state.messages, errorMessage],\n error: error.message || 'Failed to send message',\n isLoading: false,\n });\n }\n }\n\n /**\n * Send message to Dialogflow\n */\n private async sendAIMessage(text: string): Promise<void> {\n if (!this.config.dfProjectId || !this.config.dfAgentId) {\n throw new Error('Dialogflow configuration is missing');\n }\n\n const dialogflowConfig: DialogflowBackendConfig = {\n dfProjectId: this.config.dfProjectId!,\n dfLocation: this.config.dfLocation || 'us-central1',\n dfAgentId: this.config.dfAgentId!,\n languageCode: this.config.languageCode || 'en',\n backendBaseUrl: this.config.backendBaseUrl || 'http://localhost:8012',\n };\n\n // Create session if needed\n if (!this.state.sessionId) {\n const session = await createDialogflowSession(dialogflowConfig);\n this.setState({ sessionId: session.session_id });\n }\n\n // Send message (correct parameter order: message, sessionId, config)\n if (this.config.debug) {\n console.log('Sending message to Dialogflow:', {\n message: text,\n sessionId: this.state.sessionId,\n hasConfig: !!dialogflowConfig,\n });\n }\n \n const response = await sendDialogflowMessage(\n text,\n this.state.sessionId!,\n dialogflowConfig\n );\n\n if (this.config.debug) {\n console.log('Dialogflow response:', {\n response: response.response,\n hasRichContent: !!response.richContent,\n richContent: response.richContent,\n });\n }\n\n // Check for handoff\n if (response.handoff === true) {\n // Add bot response first\n const botMessage: ChatMessage = {\n id: `bot-${Date.now()}`,\n text: response.response || this.config.fallbackWelcomeMessage || 'No response',\n sender: 'bot',\n timestamp: new Date(),\n richContent: response.richContent,\n };\n this.setState({\n messages: [...this.state.messages, botMessage],\n isLoading: false,\n });\n \n // Proceed directly with handoff — user details collected by Dialogflow via webhook\n await this.handleHandoff();\n return;\n }\n \n const botMessage: ChatMessage = {\n id: `bot-${Date.now()}`,\n text: response.response || this.config.fallbackWelcomeMessage || 'No response',\n sender: 'bot',\n timestamp: new Date(),\n richContent: response.richContent,\n };\n\n this.setState({\n messages: [...this.state.messages, botMessage],\n isLoading: false,\n });\n }\n\n /**\n * Send message to human support\n */\n private async sendHumanMessage(text: string): Promise<void> {\n if (!this.chatId || !this.supportSessionId) {\n const errorMessage: ChatMessage = {\n id: `error-${Date.now()}`,\n text: 'Chat session not initialized. Please try again.',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, errorMessage],\n isLoading: false,\n });\n return;\n }\n\n if (!this.chatService) {\n throw new Error('Chat service not initialized');\n }\n\n // Send typing_stop before sending message\n this.chatService.sendTypingIndicator('typing_stop');\n if (this.typingTimeout) {\n clearTimeout(this.typingTimeout);\n this.typingTimeout = null;\n }\n\n try {\n // Try WebSocket first, fallback to REST API\n const sentViaWs = this.chatService.sendMessageViaWebSocket(text.trim());\n \n if (!sentViaWs) {\n // Fallback to REST API\n await this.chatService.sendMessageToAgent(this.chatId, this.supportSessionId, text.trim());\n }\n \n this.setState({ isLoading: false });\n } catch (error: any) {\n // chat_resolved is a normal terminal condition, not an error\n if (error instanceof ChatResolvedError || error?.name === 'ChatResolvedError' || error?.message === 'chat_resolved') {\n this.enterResolvedState(this.chatId);\n return;\n }\n\n // Handle 401/404 - clear chat_id and reinitialize\n if (error.message?.includes('Chat not found') ||\n error.message?.includes('unauthorized') ||\n error.message?.includes('401') ||\n error.message?.includes('404')) {\n if (this.config.debug) {\n console.log('⚠️ Chat expired. Re-initializing...');\n }\n \n // Clear chat_id\n this.chatId = null;\n this.supportSessionId = null;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.removeItem('chartsconnect_chat_id');\n localStorage.removeItem('chartsconnect_session_id');\n }\n \n // Try to reinitialize chat\n try {\n const newSession = await this.chatService.startSupportChat(\n this.state.sessionId || null\n );\n this.chatId = newSession.chat_id;\n this.supportSessionId = newSession.session_id;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.setItem('chartsconnect_chat_id', this.chatId);\n localStorage.setItem('chartsconnect_session_id', this.supportSessionId);\n }\n \n // Retry sending message\n if (this.chatId && this.supportSessionId) {\n await this.chatService.sendMessageToAgent(\n this.chatId,\n this.supportSessionId,\n text.trim()\n );\n }\n this.setState({ isLoading: false });\n return;\n } catch (retryError: any) {\n if (retryError instanceof ChatResolvedError || retryError?.message === 'chat_resolved') {\n this.enterResolvedState(this.chatId);\n return;\n }\n throw retryError;\n }\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Switch to human mode\n */\n switchToHumanMode(): void {\n this.chatMode = 'human';\n this.setState({ chatMode: 'human' });\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.setItem('chartsconnect_chat_mode', 'HUMAN');\n }\n }\n\n /**\n * Switch to AI mode\n */\n switchToBotMode(): void {\n this.chatMode = 'ai';\n this.setState({ chatMode: 'ai' });\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.setItem('chartsconnect_chat_mode', 'BOT');\n }\n }\n\n /**\n * Initialize welcome popup\n */\n initializeWelcomePopup(): void {\n if (this.config.showWelcomePopup !== false) {\n const delay = this.config.welcomePopupDelay || 1500;\n setTimeout(() => {\n if (!this.state.isOpen) {\n this.setState({ showWelcomePopup: true });\n }\n }, delay);\n }\n }\n\n /**\n * Handle handoff from Dialogflow to human support\n */\n async handleHandoff(): Promise<void> {\n if (!this.chatService) {\n throw new Error('Chat service not initialized');\n }\n\n try {\n this.isConnectingToAgent = true;\n \n // Get Dialogflow session ID if available\n const dialogflowSessionId = this.state.sessionId;\n \n // STEP 1: Ensure chat is initialized\n const session = await this.chatService.ensureChatInitialized(\n this.chatId,\n this.supportSessionId,\n dialogflowSessionId || null\n );\n \n if (!session || !session.chat_id) {\n throw new Error('Failed to initialize chat session');\n }\n \n const currentChatId = session.chat_id;\n const currentSupportSessionId = session.session_id;\n \n // Update state if chat was newly initialized\n if (currentChatId !== this.chatId) {\n this.chatId = currentChatId;\n this.supportSessionId = currentSupportSessionId;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.setItem('chartsconnect_chat_id', this.chatId);\n localStorage.setItem('chartsconnect_session_id', this.supportSessionId);\n }\n if (this.config.debug) {\n console.log('✅ Chat initialized:', { chatId: currentChatId, sessionId: currentSupportSessionId });\n }\n }\n\n // STEP 2: Request handoff\n try {\n await this.chatService.requestHandoff(\n currentChatId,\n currentSupportSessionId,\n 'Customer requested human agent',\n dialogflowSessionId || null\n );\n \n if (this.config.debug) {\n console.log('✅ Handoff requested successfully');\n }\n } catch (handoffError: any) {\n // Handle 401/404 or \"chat not found\" - clear chat_id and retry\n if (handoffError.message?.includes('Invalid chat_id') || \n handoffError.message?.includes('Chat not found') ||\n handoffError.message?.includes('unauthorized') ||\n handoffError.message?.includes('400') ||\n handoffError.message?.includes('401') ||\n handoffError.message?.includes('404') ||\n handoffError.message?.includes('expired')) {\n if (this.config.debug) {\n console.log('⚠️ Chat expired or not found. Re-initializing chat...');\n }\n \n // Clear old chat_id\n this.chatId = null;\n this.supportSessionId = null;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.removeItem('chartsconnect_chat_id');\n localStorage.removeItem('chartsconnect_session_id');\n }\n \n // Create new chat session\n const newSession = await this.chatService.startSupportChat(\n dialogflowSessionId || null\n );\n \n if (!newSession || !newSession.chat_id) {\n throw new Error('Failed to re-initialize chat session');\n }\n \n this.chatId = newSession.chat_id;\n this.supportSessionId = newSession.session_id;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.setItem('chartsconnect_chat_id', this.chatId);\n localStorage.setItem('chartsconnect_session_id', this.supportSessionId);\n }\n \n // Retry handoff with new chat_id\n await this.chatService.requestHandoff(\n this.chatId,\n this.supportSessionId,\n 'Customer requested human agent',\n dialogflowSessionId || null\n );\n \n if (this.config.debug) {\n console.log('✅ Handoff requested successfully after retry');\n }\n } else {\n throw handoffError;\n }\n }\n\n // Switch to human mode\n this.switchToHumanMode();\n this.chatResolved = false;\n this.agentAccepted = false;\n\n // Connect WebSocket with handlers\n if (currentChatId && currentSupportSessionId) {\n this.chatService.connectWebSocket(\n currentChatId,\n currentSupportSessionId,\n (message: WebSocketMessage) => {\n this.handleWebSocketMessage(message);\n },\n (connected: boolean) => {\n this.wsConnected = connected;\n }\n );\n }\n \n this.isConnectingToAgent = false;\n } catch (error: any) {\n console.error('Error handling handoff:', error);\n const errorMessage: ChatMessage = {\n id: `error-${Date.now()}`,\n text: this.config.debug\n ? `Handoff error: ${error.message}`\n : 'Failed to connect to agent. Please try again.',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, errorMessage],\n });\n this.isConnectingToAgent = false;\n }\n }\n\n /**\n * Handle WebSocket messages\n */\n private handleWebSocketMessage(message: WebSocketMessage): void {\n switch (message.type) {\n case 'message':\n if (message.content) {\n // Only display messages from agent\n if (message.sender_type === 'agent' || !message.sender_type) {\n const agentMessage: ChatMessage = {\n id: message.id || `agent-${Date.now()}`,\n text: message.content,\n sender: 'agent',\n timestamp: new Date(message.timestamp || Date.now()),\n };\n \n // Avoid duplicate messages\n const existingIds = new Set(this.state.messages.map(m => m.id));\n if (!existingIds.has(agentMessage.id)) {\n this.setState({\n messages: [...this.state.messages, agentMessage],\n });\n }\n \n // Hide typing indicator when message received\n this.agentTyping = false;\n if (this.agentTypingTimeout) {\n clearTimeout(this.agentTypingTimeout);\n this.agentTypingTimeout = null;\n }\n }\n }\n break;\n\n case 'typing_start':\n if (message.sender_type === 'agent') {\n this.agentTyping = true;\n // Auto-hide after 3 seconds if no message received\n if (this.agentTypingTimeout) {\n clearTimeout(this.agentTypingTimeout);\n }\n this.agentTypingTimeout = setTimeout(() => {\n this.agentTyping = false;\n }, 3000);\n }\n break;\n\n case 'typing_stop':\n if (message.sender_type === 'agent') {\n this.agentTyping = false;\n if (this.agentTypingTimeout) {\n clearTimeout(this.agentTypingTimeout);\n this.agentTypingTimeout = null;\n }\n }\n break;\n\n case 'agent_changed':\n if (message.to_agent) {\n this.currentAgent = {\n id: message.to_agent_id,\n name: message.to_agent,\n };\n\n // Add system message to chat\n const systemMessage: ChatMessage = {\n id: `system-${Date.now()}`,\n text: message.from_agent\n ? `Chat has been transferred from ${message.from_agent} to ${message.to_agent}`\n : `Chat has been transferred to ${message.to_agent}`,\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, systemMessage],\n });\n }\n break;\n\n case 'agent_accepted':\n this.agentAccepted = true;\n this.isConnectingToAgent = false;\n const acceptedMessage: ChatMessage = {\n id: message.id || `agent-accepted-${Date.now()}`,\n text: 'You can chat now, the agent has accepted your request.',\n sender: 'bot',\n timestamp: message.timestamp ? new Date(message.timestamp) : new Date(),\n };\n const existingIds = new Set(this.state.messages.map(m => m.id));\n if (!existingIds.has(acceptedMessage.id)) {\n this.setState({\n messages: [...this.state.messages, acceptedMessage],\n });\n }\n if (message.to_agent) {\n this.currentAgent = {\n name: message.to_agent,\n id: message.to_agent_id,\n };\n }\n break;\n\n case 'chat_resolved':\n case 'chat_ended':\n this.enterResolvedState(message.chat_id || null);\n break;\n\n case 'chat_info':\n if (message.status === 'active') {\n this.isConnectingToAgent = false;\n this.agentAccepted = true;\n } else if (message.status === 'resolved' || message.status === 'ended') {\n this.enterResolvedState(message.chat_id || null);\n }\n if (message.agent_id) {\n this.currentAgent = {\n ...this.currentAgent,\n id: message.agent_id,\n };\n }\n break;\n\n case 'error':\n console.error('WebSocket error:', message.error);\n const errorMessage: ChatMessage = {\n id: `error-${Date.now()}`,\n text: message.error || 'An error occurred. Please try again.',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, errorMessage],\n });\n break;\n }\n }\n\n /**\n * Enter resolved state\n */\n private enterResolvedState(resolvedChatId?: string | null): void {\n this.chatResolved = true;\n this.isConnectingToAgent = false;\n this.agentAccepted = false;\n this.agentTyping = false;\n if (this.agentTypingTimeout) {\n clearTimeout(this.agentTypingTimeout);\n this.agentTypingTimeout = null;\n }\n\n // Stop WS + prevent any reuse of the old chat_id\n if (this.chatService) {\n this.chatService.disconnectWebSocket();\n }\n this.chatId = null;\n this.supportSessionId = null;\n if (typeof window !== 'undefined' && window.localStorage) {\n localStorage.removeItem('chartsconnect_chat_id');\n localStorage.removeItem('chartsconnect_session_id');\n }\n \n // Add thank you message before reset\n const thankYouMessage: ChatMessage = {\n id: `resolved-${Date.now()}`,\n text: 'Thank you for contacting us!',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, thankYouMessage],\n });\n \n // Automatically reset to BOT mode after showing thank you message\n setTimeout(async () => {\n this.switchToBotMode();\n this.chatResolved = false;\n this.setState({\n messages: [],\n sessionId: null, // Clear session ID to force recreation\n });\n // Recreate Dialogflow session to start fresh\n if (this.config.dfProjectId && this.config.dfAgentId && this.state.isOpen) {\n try {\n this.setState({ isLoading: true });\n const dialogflowConfig: DialogflowBackendConfig = {\n dfProjectId: this.config.dfProjectId,\n dfLocation: this.config.dfLocation || 'us-central1',\n dfAgentId: this.config.dfAgentId,\n languageCode: this.config.languageCode || 'en',\n backendBaseUrl: this.config.backendBaseUrl || 'http://localhost:8012',\n };\n \n const session = await createDialogflowSession(dialogflowConfig);\n this.setState({ \n sessionId: session.session_id,\n isLoading: false,\n });\n \n // Add welcome message from Dialogflow if available\n if (session.message) {\n const welcomeMessage: ChatMessage = {\n id: `welcome-${Date.now()}`,\n text: session.message,\n sender: 'bot',\n timestamp: new Date(),\n richContent: session.richContent,\n };\n this.setState({\n messages: [welcomeMessage],\n });\n }\n } catch (error: any) {\n console.error('Error recreating Dialogflow session after handoff:', error);\n this.setState({ \n isLoading: false,\n error: error.message || 'Failed to initialize chat',\n });\n \n // Show fallback welcome message\n const fallbackMessage: ChatMessage = {\n id: `fallback-${Date.now()}`,\n text: this.config.fallbackWelcomeMessage || 'Hello! How can I help you today?',\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [fallbackMessage],\n });\n }\n }\n }, 2000);\n }\n\n /**\n * Load message history\n */\n async loadMessageHistory(preserveExisting: boolean = false): Promise<void> {\n if (!this.chatService || !this.chatId || !this.supportSessionId) {\n return;\n }\n\n try {\n if (this.chatId && this.supportSessionId) {\n const history = await this.chatService.loadMessageHistory(this.chatId, this.supportSessionId);\n \n const historyMessages: ChatMessage[] = history.map((msg: any) => ({\n id: msg.id || `history-${Date.now()}-${Math.random()}`,\n text: msg.content,\n sender: msg.sender_type === 'agent' ? 'agent' : 'user',\n timestamp: new Date(msg.timestamp),\n }));\n\n if (preserveExisting) {\n // Merge with existing messages, avoiding duplicates\n const existingIds = new Set(this.state.messages.map(m => m.id));\n const newMessages = historyMessages.filter(m => !existingIds.has(m.id));\n \n // Combine existing messages with new history messages\n // Sort by timestamp to maintain chronological order\n const combined = [...this.state.messages, ...newMessages].sort((a, b) => \n a.timestamp.getTime() - b.timestamp.getTime()\n );\n \n this.setState({\n messages: combined,\n });\n } else {\n // Replace all messages\n this.setState({\n messages: historyMessages,\n });\n }\n }\n } catch (error: any) {\n console.error('Error loading message history:', error);\n if (this.config.debug) {\n const errorMessage: ChatMessage = {\n id: `error-${Date.now()}`,\n text: `Failed to load chat history: ${error.message}`,\n sender: 'bot',\n timestamp: new Date(),\n };\n this.setState({\n messages: [...this.state.messages, errorMessage],\n });\n }\n }\n }\n\n /**\n * Get additional state for UI (not in WidgetState but needed by components)\n */\n getAdditionalState() {\n return {\n wsConnected: this.wsConnected,\n agentTyping: this.agentTyping,\n currentAgent: this.currentAgent,\n isConnectingToAgent: this.isConnectingToAgent,\n agentAccepted: this.agentAccepted,\n chatResolved: this.chatResolved,\n };\n }\n\n /**\n * Cleanup\n */\n destroy(): void {\n if (this.typingTimeout) {\n clearTimeout(this.typingTimeout);\n }\n if (this.agentTypingTimeout) {\n clearTimeout(this.agentTypingTimeout);\n }\n if (this.chatService) {\n this.chatService.disconnectWebSocket();\n }\n this.listeners.clear();\n }\n}\n","/**\n * useChatWidget Composable\n * Headless mode for Vue 3 - use logic without UI\n */\n\nimport { ref, computed, onUnmounted, watch, readonly, type Ref } from 'vue';\nimport { WidgetStateManager } from '../core/stateManager';\nimport type { WidgetConfig, WidgetState, ChatMessage } from '../core/types';\n\nexport interface UseChatWidgetReturn {\n // State\n state: Readonly<Ref<WidgetState>>;\n isOpen: Readonly<Ref<boolean>>;\n messages: Readonly<Ref<ChatMessage[]>>;\n isLoading: Readonly<Ref<boolean>>;\n error: Readonly<Ref<string | null>>;\n chatMode: Readonly<Ref<'ai' | 'human'>>;\n\n // Additional state\n wsConnected: Readonly<Ref<boolean>>;\n agentTyping: Readonly<Ref<boolean>>;\n currentAgent: Readonly<Ref<{ name: string; id?: string }>>;\n isConnectingToAgent: Readonly<Ref<boolean>>;\n\n // Actions\n openChat: () => Promise<void>;\n closeChat: () => void;\n sendMessage: (text: string) => Promise<void>;\n toggleChat: () => Promise<void>;\n setInputValue: (value: string) => void;\n clearError: () => void;\n\n // Manager instance (for advanced usage)\n manager: WidgetStateManager;\n}\n\n/**\n * Headless chat widget composable\n * Use this for custom UI implementations\n */\nexport function useChatWidget(config: WidgetConfig): UseChatWidgetReturn {\n // Create state manager\n const manager = new WidgetStateManager(config);\n\n // Reactive state\n const state = ref<WidgetState>(manager.getState());\n const wsConnected = ref(false);\n const agentTyping = ref(false);\n const currentAgent = ref<{ name: string; id?: string }>({ name: 'Agent' });\n const isConnectingToAgent = ref(false);\n\n // Subscribe to state changes\n const unsubscribe = manager.subscribe((newState) => {\n state.value = { ...newState };\n \n // Update additional state\n const additional = manager.getAdditionalState();\n wsConnected.value = additional.wsConnected;\n agentTyping.value = additional.agentTyping;\n currentAgent.value = additional.currentAgent;\n isConnectingToAgent.value = additional.isConnectingToAgent;\n });\n\n // Computed properties\n const isOpen = computed(() => state.value.isOpen);\n const messages = computed(() => state.value.messages);\n const isLoading = computed(() => state.value.isLoading);\n const error = computed(() => state.value.error);\n const chatMode = computed(() => state.value.chatMode);\n\n // Actions\n const openChat = async () => {\n await manager.openChat();\n };\n\n const closeChat = () => {\n manager.closeChat();\n };\n\n const sendMessage = async (text: string) => {\n await manager.sendMessage(text);\n };\n\n const toggleChat = async () => {\n await manager.toggleChat();\n };\n\n const setInputValue = (value: string) => {\n manager.setInputValue(value);\n };\n\n const clearError = () => {\n manager.clearError();\n };\n\n // Cleanup on unmount\n onUnmounted(() => {\n unsubscribe();\n manager.destroy();\n });\n\n // Watch config changes\n watch(\n () => config,\n (newConfig) => {\n manager.updateConfig(newConfig);\n },\n { deep: true }\n );\n\n return {\n state: state as Readonly<Ref<WidgetState>>,\n isOpen: isOpen as Readonly<Ref<boolean>>,\n messages: messages as Readonly<Ref<ChatMessage[]>>,\n isLoading: isLoading as Readonly<Ref<boolean>>,\n error: error as Readonly<Ref<string | null>>,\n chatMode: chatMode as Readonly<Ref<'ai' | 'human'>>,\n wsConnected: wsConnected as Readonly<Ref<boolean>>,\n agentTyping: agentTyping as Readonly<Ref<boolean>>,\n currentAgent: currentAgent as Readonly<Ref<{ name: string; id?: string }>>,\n isConnectingToAgent: isConnectingToAgent as Readonly<Ref<boolean>>,\n openChat,\n closeChat,\n sendMessage,\n toggleChat,\n setInputValue,\n clearError,\n manager,\n };\n}\n","<template>\n <div class=\"custom-chat-widget\" v-bind=\"$attrs\">\n <!-- Welcome Popup -->\n <div\n v-if=\"state.showWelcomePopup && !state.isOpen\"\n class=\"custom-welcome-popup\"\n @click=\"handleOpenChat\"\n >\n <div class=\"custom-welcome-header\">\n <div class=\"custom-welcome-title\">{{ config.welcomeTitle }}</div>\n <button\n class=\"custom-close-popup\"\n @click.stop=\"handleCloseWelcomePopup\"\n aria-label=\"Close welcome popup\"\n >\n ×\n </button>\n </div>\n <div class=\"custom-welcome-message\">{{ config.welcomeMessage }}</div>\n <div class=\"custom-welcome-cta\">{{ config.welcomeCta }}</div>\n </div>\n\n <!-- Chat Toggle Button -->\n <button\n v-if=\"!state.isOpen\"\n class=\"custom-chat-toggle-btn\"\n @click=\"handleOpenChat\"\n aria-label=\"Open chat\"\n >\n <svg\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n >\n <path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\"></path>\n </svg>\n </button>\n\n <!-- Chat Window -->\n <div v-if=\"state.isOpen\" class=\"custom-chat-window\">\n <div class=\"custom-chat-header\">\n <div class=\"custom-chat-header-content\">\n <div class=\"custom-chat-title\">{{ config.title }}</div>\n <div class=\"custom-chat-subtitle\">\n {{ config.subtitle }}\n <span v-if=\"state.chatMode === 'human'\" class=\"custom-mode-indicator\">\n • {{ wsConnected ? '🟢 Connected' : '🟡 Connecting...' }}\n </span>\n </div>\n <div v-if=\"state.chatMode === 'human'\" class=\"custom-mode-badge\">\n Human Support Mode\n </div>\n <div v-if=\"state.chatMode === 'human'\" class=\"custom-agent-info\">\n <span class=\"custom-agent-label\">Agent:</span>\n <span class=\"custom-agent-name\">{{ currentAgent.name }}</span>\n </div>\n <div v-if=\"state.chatMode === 'ai'\" class=\"custom-mode-badge\">\n Bot Mode\n </div>\n </div>\n <button\n class=\"custom-chat-close-btn\"\n @click=\"handleCloseChat\"\n aria-label=\"Close chat\"\n >\n ×\n </button>\n </div>\n\n <div class=\"custom-chat-messages\" ref=\"messagesContainer\">\n <!-- Empty State -->\n <div v-if=\"isInitializing && state.messages.length === 0\" class=\"custom-chat-empty\">\n <div class=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n <p>Initializing chat...</p>\n </div>\n <div v-else-if=\"!isInitializing && state.messages.length === 0\" class=\"custom-chat-empty\">\n <div class=\"custom-chat-empty-icon\">👋</div>\n <p>{{ config.emptyStateMessage }}</p>\n </div>\n\n <!-- Messages -->\n <div\n v-for=\"message in state.messages\"\n :key=\"message.id\"\n :class=\"[\n 'custom-message', \n `custom-message-${message.sender}`,\n { 'custom-handoff-message': isHandoffMessage(message.text) }\n ]\"\n >\n <div \n class=\"custom-message-content\"\n :class=\"{ 'custom-handoff-content': isHandoffMessage(message.text) }\"\n v-html=\"safeLinkifyText(message.text).replace(/\\n/g, '<br>')\"\n ></div>\n \n <!-- Rich Content (Chips) -->\n <div\n v-if=\"message.richContent && Array.isArray(message.richContent) && message.richContent.length > 0\"\n class=\"custom-chips-container\"\n >\n <template v-for=\"(contentGroup, groupIndex) in message.richContent\" :key=\"groupIndex\">\n <template v-if=\"!Array.isArray(contentGroup)\">\n <div\n v-if=\"contentGroup.type === 'chips' && contentGroup.options\"\n class=\"custom-chips-group\"\n >\n <button\n v-for=\"(chip, chipIndex) in contentGroup.options\"\n :key=\"chipIndex\"\n class=\"custom-chip-button\"\n type=\"button\"\n @click=\"handleChipClick(chip.text, chip.payload)\"\n >\n {{ chip.text }}\n </button>\n </div>\n </template>\n <template v-else>\n <template\n v-for=\"(content, contentIndex) in contentGroup\"\n :key=\"`${groupIndex}-${contentIndex}`\"\n >\n <div\n v-if=\"content.type === 'chips' && content.options\"\n class=\"custom-chips-group\"\n >\n <button\n v-for=\"(chip, chipIndex) in content.options\"\n :key=\"chipIndex\"\n class=\"custom-chip-button\"\n type=\"button\"\n @click=\"handleChipClick(chip.text, chip.payload)\"\n >\n {{ chip.text }}\n </button>\n </div>\n </template>\n </template>\n </template>\n </div>\n\n <div class=\"custom-message-time\">\n {{ formatTime(message.timestamp) }}\n </div>\n </div>\n\n <!-- Loading Indicator -->\n <div v-if=\"state.isLoading\" class=\"custom-message custom-message-bot\">\n <div class=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n </div>\n\n <!-- Connecting to Agent Indicator -->\n <div v-if=\"isConnectingToAgent\" class=\"custom-message custom-message-bot\">\n <div class=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n </div>\n\n <!-- Agent Typing Indicator -->\n <div v-if=\"state.chatMode === 'human' && agentTyping\" class=\"custom-message custom-message-bot\">\n <div class=\"custom-typing-indicator\">\n <span></span>\n <span></span>\n <span></span>\n </div>\n </div>\n\n <div ref=\"messagesEndRef\"></div>\n </div>\n\n <!-- Input Form -->\n <form class=\"custom-chat-input-form\" @submit.prevent=\"handleSubmit\">\n <input\n type=\"text\"\n class=\"custom-chat-input\"\n :value=\"state.inputValue\"\n @input=\"handleInput\"\n :placeholder=\"config.inputPlaceholder\"\n :disabled=\"state.isLoading || isInitializing || isStartingNewChat\"\n />\n <button\n type=\"submit\"\n class=\"custom-chat-send-btn\"\n :disabled=\"!state.inputValue.trim() || state.isLoading || isInitializing || isStartingNewChat\"\n >\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n >\n <line x1=\"22\" y1=\"2\" x2=\"11\" y2=\"13\"></line>\n <polygon points=\"22 2 15 22 11 13 2 9 22 2\"></polygon>\n </svg>\n </button>\n </form>\n </div>\n </div>\n</template>\n\n<script setup lang=\"ts\">\nimport { ref, computed, onMounted, nextTick, watch } from 'vue';\nimport { useChatWidget } from '../composables/useChatWidget';\nimport { safeLinkifyText } from '../utils/sanitize';\nimport type { WidgetConfig } from '../core/types';\n\n// Handle attributes properly to avoid Vue warnings\n// For Vue 3.3+, defineOptions is available as a compiler macro\n// @ts-ignore - defineOptions is a compiler macro\ndefineOptions({\n inheritAttrs: false, // We handle attrs manually via v-bind=\"$attrs\"\n});\n\n// Props\nconst props = withDefaults(defineProps<WidgetConfig>(), {\n title: '💬 Charts Connect AI Assistant',\n subtitle: \"We're here to help\",\n welcomeTitle: '👋 Welcome to Charts Connect',\n welcomeMessage: \"My name is Charts Connect AI Assistant and I'll guide you.\",\n welcomeCta: '💬 Click here to start chatting!',\n showWelcomePopup: true,\n welcomePopupDelay: 1500,\n fallbackWelcomeMessage: \"Hello! I'm Charts Connect AI Assistant. How can I help you today?\",\n inputPlaceholder: 'Type your message...',\n emptyStateMessage: \"Hi! I'm Charts Connect AI Assistant. How can I help you today?\",\n debug: false,\n});\n\n// Use headless composable\nconst {\n state,\n isOpen,\n messages,\n isLoading,\n error,\n chatMode,\n wsConnected,\n agentTyping,\n currentAgent,\n isConnectingToAgent: isConnectingToAgentFromComposable,\n openChat,\n closeChat,\n sendMessage,\n toggleChat,\n setInputValue,\n clearError,\n manager,\n} = useChatWidget(props);\n\n// Refs\nconst messagesEndRef = ref<HTMLDivElement | null>(null);\nconst messagesContainer = ref<HTMLDivElement | null>(null);\n\n// Computed config (for reactivity)\nconst config = computed(() => props);\n\n// Computed state for initialization and connection (matching React component)\nconst isInitializing = computed(() => {\n return state.value.isLoading && state.value.messages.length === 0 && !state.value.sessionId;\n});\n\nconst isStartingNewChat = computed(() => {\n // This would be tracked in manager if needed, for now return false\n return false;\n});\n\n// Use isConnectingToAgent from composable (already computed in manager)\nconst isConnectingToAgent = isConnectingToAgentFromComposable;\n\n// Auto-scroll to bottom when messages change\nwatch(\n () => messages.value.length,\n () => {\n nextTick(() => {\n messagesEndRef.value?.scrollIntoView({ behavior: 'smooth' });\n });\n }\n);\n\n// Handlers\nconst handleOpenChat = async () => {\n // Ensure immediate UI response\n if (!state.value.isOpen) {\n state.value.isOpen = true;\n state.value.showWelcomePopup = false;\n }\n await openChat();\n};\n\nconst handleCloseChat = () => {\n closeChat();\n};\n\nconst handleCloseWelcomePopup = () => {\n manager.closeWelcomePopup();\n};\n\nconst handleInput = (event: Event) => {\n const target = event.target as HTMLInputElement;\n setInputValue(target.value);\n};\n\nconst handleSubmit = async (event: Event) => {\n event.preventDefault();\n if (state.value.inputValue.trim()) {\n await sendMessage(state.value.inputValue);\n }\n};\n\nconst handleChipClick = async (chipText: string, payload?: string) => {\n const messageToSend = chipText || payload || '';\n await sendMessage(messageToSend);\n};\n\n// Utility functions\nconst formatTime = (date: Date): string => {\n return date.toLocaleTimeString([], {\n hour: '2-digit',\n minute: '2-digit',\n });\n};\n\n// Check if message is a handoff message\nconst isHandoffMessage = (text: string): boolean => {\n return text.includes('👤') || \n text.includes('being connected') || \n text.includes('live support agent') ||\n text.includes('transfer your conversation');\n};\n\n// Initialize welcome popup on mount (SSR-safe)\nonMounted(() => {\n if (config.value.showWelcomePopup && typeof window !== 'undefined') {\n manager.initializeWelcomePopup();\n }\n});\n</script>\n\n<style scoped>\n/* Styles are imported separately by users */\n/* This ensures SSR compatibility */\n</style>\n"],"names":["botMessage","existingIds","_openBlock","_createElementBlock","_mergeProps","$attrs","_unref","_createElementVNode","_toDisplayString","_Fragment","_renderList","_normalizeClass"],"mappings":";;AAiBO,MAAM,mBAAmB;AAAA,EAsB9B,YAAY,QAAsB;AAnBlC,SAAQ,gCAAmD,IAAA;AAC3D,SAAQ,WAA2B;AACnC,SAAQ,SAAwB;AAChC,SAAQ,mBAAkC;AAC1C,SAAQ,cAA2D;AAGnE,SAAQ,cAAuB;AAC/B,SAAQ,cAAuB;AAC/B,SAAQ,eAA8C,EAAE,MAAM,QAAA;AAC9D,SAAQ,sBAA+B;AACvC,SAAQ,gBAAyB;AACjC,SAAQ,eAAwB;AAChC,SAAQ,gBAA+B;AAGvC,SAAQ,gBAAuC;AAC/C,SAAQ,qBAA4C;AAGlD,SAAK,SAAS;AACd,SAAK,QAAQ;AAAA,MACX,QAAQ;AAAA,MACR,kBAAkB;AAAA,MAClB,UAAU,CAAA;AAAA,MACV,YAAY;AAAA,MACZ,WAAW;AAAA,MACX,OAAO;AAAA,MACP,WAAW;AAAA,MACX,UAAU;AAAA,IAAA;AAIZ,SAAK,cAAc,kBAAkB;AAAA,MACnC,SAAS,KAAK,OAAO,kBAAkB;AAAA,MACvC,OAAO,KAAK,OAAO,gBAAgB;AAAA,MACnC,OAAO,KAAK,OAAO,SAAS;AAAA,IAAA,CAC7B;AAGD,QAAI,OAAO,WAAW,eAAe,OAAO,cAAc;AACxD,YAAM,YAAY,aAAa,QAAQ,4BAA4B;AACnE,WAAK,WAAW,cAAc,UAAU,UAAU;AAClD,WAAK,MAAM,WAAW,KAAK;AAE3B,WAAK,SAAS,aAAa,QAAQ,uBAAuB;AAC1D,WAAK,mBAAmB,aAAa,QAAQ,0BAA0B;AAAA,IACzE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,UAAU,UAAoD;AAC5D,SAAK,UAAU,IAAI,QAAQ;AAC3B,WAAO,MAAM;AACX,WAAK,UAAU,OAAO,Q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AY,CAAC,EAAE,MAAM,CAAC;IACtB,4BAA4B;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,6BAA6B;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,wCAAwC;IACxC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,yDAAyD;IACzD,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,4CAA4C;IAC5C,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,uCAAuC;IACvC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,iCAAiC;IACjC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,mCAAmC;IACnC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,4BAA4B;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,gDAAgD;IAChD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,0BAA0B;IAC1B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mCAAmC;IACnC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,4DAA4D;IAC5D,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,mDAAmD;IACnD,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,CAAC,OAAO,UAAU,UAAU,CAAC,EACjC,KAAwC,EACxC,QAA+B,EAC/B,YAA6C,EAC7C,cAA6E,EAC7E,UAA+C,EAC/C,gBAAgB,EAAE,kBAAyB,EAC3C,iBAAwB,EACxB,sBAA4F,EAC5F,gBAAyC,EACzC,iBAAoF,EACpF,KAAa,EACb,WAAW,EACX,UAA0B,EAC1B,SAAS,EACT,YAAmB,EACnB,cAAc,EACd,YAAY,GACb,EAAE,eAAe,2CAqxCjB"}
|
|
@@ -11,11 +11,6 @@ export declare class WidgetStateManager {
|
|
|
11
11
|
private chatId;
|
|
12
12
|
private supportSessionId;
|
|
13
13
|
private chatService;
|
|
14
|
-
private collectingUserInfo;
|
|
15
|
-
private userInfoStep;
|
|
16
|
-
private collectedUserName;
|
|
17
|
-
private collectedUserEmail;
|
|
18
|
-
private collectedUserMobile;
|
|
19
14
|
private wsConnected;
|
|
20
15
|
private agentTyping;
|
|
21
16
|
private currentAgent;
|
|
@@ -90,18 +85,10 @@ export declare class WidgetStateManager {
|
|
|
90
85
|
* Initialize welcome popup
|
|
91
86
|
*/
|
|
92
87
|
initializeWelcomePopup(): void;
|
|
93
|
-
/**
|
|
94
|
-
* Start user info collection for handoff
|
|
95
|
-
*/
|
|
96
|
-
private startUserInfoCollection;
|
|
97
|
-
/**
|
|
98
|
-
* Handle user info collection
|
|
99
|
-
*/
|
|
100
|
-
private handleUserInfoCollection;
|
|
101
88
|
/**
|
|
102
89
|
* Handle handoff from Dialogflow to human support
|
|
103
90
|
*/
|
|
104
|
-
handleHandoff(
|
|
91
|
+
handleHandoff(): Promise<void>;
|
|
105
92
|
/**
|
|
106
93
|
* Handle WebSocket messages
|
|
107
94
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stateManager.d.ts","sourceRoot":"","sources":["../../src/core/stateManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAe,MAAM,SAAS,CAAC;AAYtE,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,KAAK,CAAc;IAC3B,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,SAAS,CAAgD;IACjE,OAAO,CAAC,QAAQ,CAAwB;IACxC,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,gBAAgB,CAAuB;IAC/C,OAAO,CAAC,WAAW,CAAqD;IAGxE,OAAO,CAAC,
|
|
1
|
+
{"version":3,"file":"stateManager.d.ts","sourceRoot":"","sources":["../../src/core/stateManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAe,MAAM,SAAS,CAAC;AAYtE,qBAAa,kBAAk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+F9B;;OAEG;IACH,iBAAiB,IAAI,IAAI;IAQzB;;OAEG;IACH,eAAe,IAAI,IAAI;IAQvB;;OAEG;IACH,sBAAsB,IAAI,IAAI;IAW9B;;OAEG;IACG,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IA4IpC;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAsI9B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IA6F1B;;OAEG;IACG,kBAAkB,CAAC,gBAAgB,GAAE,OAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAqD1E;;OAEG;IACH,kBAAkB;;;;kBAz3BY,MAAM;iBAAO,MAAM;;;;;;IAo4BjD;;OAEG;IACH,OAAO,IAAI,IAAI;CAYhB"}
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("react/jsx-runtime"),t=require("react"),n=require("./sanitize-C8MB41vY.cjs"),s=require("react-dom");var a="undefined"!=typeof document?document.currentScript:null;const o="chartsconnectect_chat_mode",r="chartsconnect_chat_id",i="chartsconnect_session_id";function c({title:s="💬 Charts Connect AI Assistant",subtitle:a="We're here to help",welcomeTitle:c="👋 Welcome to Charts Connect",welcomeMessage:l="My name is Charts Connect AI Assistant and I'll guide you.",welcomeCta:d="💬 Click here to start chatting!",showWelcomePopup:u=!0,welcomePopupDelay:m=1500,fallbackWelcomeMessage:h="Hello! I'm Charts Connect AI Assistant. How can I help you today?",inputPlaceholder:g="Type your message...",emptyStateMessage:p="Hi! I'm Charts Connect AI Assistant. How can I help you today?",debug:f=!1,dfProjectId:w,dfLocation:x="us-central1",dfAgentId:y,languageCode:_="en",backendBaseUrl:v,backendWsUrl:S}){const[b,D]=t.useState(!1),[C,j]=t.useState(!1),[N,T]=t.useState([]),[k,I]=t.useState(""),[E,A]=t.useState(!1),[R,O]=t.useState(null),[$,M]=t.useState(!1),[P,U]=t.useState(!1),[L,H]=t.useState(!1),[V,B]=t.useState(!1),[W,F]=t.useState({name:"Agent"}),[q,z]=t.useState(!1),[K,G]=t.useState(!1),[X,Y]=t.useState(!1),[J,Q]=t.useState(!1),[Z,ee]=t.useState(null),[te,ne]=t.useState(""),[se,ae]=t.useState(""),[oe,re]=t.useState(""),ie=t.useRef(""),ce=t.useRef(null),le=t.useRef(null),de=t.useRef(null),ue=t.useRef(!1),me=t.useRef(null),he=()=>v||"undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_BASE_URL,ge=t.useRef(n.createChatService({baseUrl:he(),wsUrl:S||"undefined"!=typeof process&&process.env?.REACT_APP_BACKEND_WS_URL,debug:f})),pe=t.useRef(null),{currentMode:fe,switchToHumanMode:we,switchToBotMode:xe,chatId:ye,sessionId:_e,setChatId:ve,setSessionId:Se}=function(){const[e,n]=t.useState(()=>"HUMAN"===localStorage.getItem(o)?"HUMAN":"BOT"),[s,a]=t.useState(()=>localStorage.getItem(r)),[c,l]=t.useState(()=>localStorage.getItem(i));t.useEffect(()=>{localStorage.setItem(o,e)},[e]);const d=t.useCallback(e=>{a(e),e?localStorage.setItem(r,e):localStorage.removeItem(r)},[]),u=t.useCallback(e=>{l(e),e?localStorage.setItem(i,e):localStorage.removeItem(i)},[]),m=t.useCallback(()=>{n("HUMAN")},[]),h=t.useCallback(()=>{n("BOT")},[]),g=t.useCallback(e=>!1,[]);return{currentMode:e,switchToHumanMode:m,switchToBotMode:h,isHandoffTriggered:g,chatId:s,sessionId:c,setChatId:d,setSessionId:u}}(),be=t.useCallback(e=>{G(!0),U(!1),Q(!1),B(!1),de.current&&(clearTimeout(de.current),de.current=null),ge.current.disconnectWebSocket(),ve(null),Se(null),O(null);const t={id:`resolved-${Date.now()}`,text:"Thank you for contacting us!",sender:"bot",timestamp:new Date};T(e=>[...e,t]),setTimeout(()=>{xe(),G(!1),T([]),z(!1),ee(null),ne(""),ae(""),re(""),ie.current="",me.current&&me.current().catch(console.error)},2e3)},[ve,Se,xe]);t.useCallback(async()=>{if(!X){Y(!0);try{const e=ie.current||te||null,t=se||null,n=oe||null,s=await ge.current.startSupportChat(R||null,e,t,n);we(),ve(s.chat_id),Se(s.session_id),G(!1),I("")}catch(e){T(t=>[...t,{id:`error-new-chat-${Date.now()}`,text:f?`Error: ${e?.message||"Failed to start a new chat."}`:"Sorry, I couldn't start a new chat. Please try again.",sender:"bot",timestamp:new Date}])}finally{Y(!1)}}},[se,oe,te,f,X,R,ve,Se,we]);const De=()=>{if(w&&y)return{dfProjectId:w,dfLocation:x||"us-central1",dfAgentId:y,languageCode:_||"en",backendBaseUrl:he()}};t.useEffect(()=>{if(!u)return;const e=setTimeout(()=>{j(!0)},m);return()=>clearTimeout(e)},[u,m]),t.useEffect(()=>{ce.current?.scrollIntoView({behavior:"smooth"})},[N]);const Ce=t.useCallback(e=>{if(e.to_agent){F({id:e.to_agent_id,name:e.to_agent});const t={id:`system-${Date.now()}`,text:e.from_agent?`Chat has been transferred from ${e.from_agent} to ${e.to_agent}`:`Chat has been transferred to ${e.to_agent}`,sender:"bot",timestamp:new Date};T(e=>[...e,t])}},[f]),je=t.useCallback(e=>{switch(e.type){case"message":if(e.content)if("agent"!==e.sender_type&&e.sender_type)f&&e.sender_type;else{const t={id:e.id||`agent-${Date.now()}`,text:e.content,sender:"agent",timestamp:new Date(e.timestamp||Date.now())};T(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),B(!1),de.current&&(clearTimeout(de.current),de.current=null)}break;case"typing_start":"agent"===e.sender_type&&(B(!0),de.current&&clearTimeout(de.current),de.current=setTimeout(()=>{B(!1)},3e3));break;case"typing_stop":"agent"===e.sender_type&&(B(!1),de.current&&(clearTimeout(de.current),de.current=null));break;case"agent_changed":Ce(e);break;case"chat_info":"active"===e.status?(U(!1),Q(!0)):"resolved"!==e.status&&"ended"!==e.status||be(e.chat_id||null),e.agent_id&&F(t=>({...t,id:e.agent_id}));break;case"agent_accepted":Q(!0),U(!1);const t={id:e.id||`agent-accepted-${e.chat_id||Date.now()}-${Date.now()}`,text:"You can chat now, the agent has accepted your request.",sender:"bot",timestamp:e.timestamp?new Date(e.timestamp):new Date};T(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),e.to_agent&&F({name:e.to_agent,id:e.to_agent_id});break;case"chat_resolved":case"chat_ended":be(e.chat_id||null);break;case"error":const n={id:`error-${Date.now()}`,text:e.error||"An error occurred. Please try again.",sender:"bot",timestamp:new Date};T(e=>[...e,n])}},[f,be,Ce]),Ne=t.useCallback(e=>{4e3===e.code&&be(ye)},[ye,be]),Te=t.useCallback(e=>{H(e),e&&U(!1)},[]);t.useEffect(()=>{if("HUMAN"===fe&&ye&&_e)return ge.current.connectWebSocket(ye,_e,je,Te,Ne),()=>{ge.current.disconnectWebSocket()}},[fe,ye,_e,je,Te,Ne]);const ke=t.useCallback(async(e=!0)=>{if(ye&&_e)try{A(!0);const t=(await ge.current.loadMessageHistory(ye,_e)).map(e=>({id:e.id||`msg-${Date.now()}-${Math.random()}`,text:e.content,sender:"agent"===e.sender_type?"agent":"user",timestamp:new Date(e.timestamp)}));T(e?e=>{const n=new Set(e.map(e=>e.id)),s=t.filter(e=>!n.has(e.id));return[...e,...s].sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}:t)}catch(t){if(f){const e={id:`error-${Date.now()}`,text:`Failed to load chat history: ${t.message}`,sender:"bot",timestamp:new Date};T(t=>[...t,e])}}finally{A(!1)}},[ye,_e,f]);t.useEffect(()=>{if("HUMAN"===fe&&ye&&_e){const e=`${ye}-${_e}`;if(pe.current!==e){pe.current=e;setTimeout(()=>{0===N.length&&ke(!1).catch(console.error)},0)}}else"BOT"===fe&&(pe.current=null)},[fe,ye,_e,ke,N.length]);const Ie=async(e=!1,t=!1)=>{if(R&&!e&&!t)return R;if(ue.current){if(await new Promise(e=>setTimeout(e,100)),R)return R;throw new Error("Session creation in progress. Please try again.")}ue.current=!0;try{M(!0);const e=De();if(!e)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId and dfAgentId.");const s=t&&R?R:null,a=await n.createDialogflowSession(e,s);if(O(a.session_id),a.message){const e={id:`welcome-${Date.now()}`,text:a.message,sender:"bot",timestamp:new Date,richContent:a.richContent};T(t=>0===t.length?[e]:[e,...t])}return a.session_id}catch(s){const e={id:`error-${Date.now()}`,text:f?`Error: ${s.message||"Failed to create session. Please check your Dialogflow configuration."}`:h,sender:"bot",timestamp:new Date};return T(t=>[...t,e]),null}finally{M(!1),ue.current=!1}};me.current=Ie;const Ee=async(e,t,s=!1)=>{if(!e.trim())return;if(q){if("name"===Z){const t=e.trim();ne(t),ie.current=t,ee("email");const n={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};T(e=>[...e,n]);const s={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your email address:",sender:"bot",timestamp:new Date};return T(e=>[...e,s]),void I("")}if("email"===Z){const t=e.trim();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)){const e={id:(Date.now()+1).toString(),text:"Please provide a valid email address:",sender:"bot",timestamp:new Date};return T(t=>[...t,e]),void I("")}ae(t),ee("mobile");const n={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};T(e=>[...e,n]);const s={id:(Date.now()+1).toString(),text:"Thank you! Now please provide your mobile number:",sender:"bot",timestamp:new Date};return T(e=>[...e,s]),void I("")}if("mobile"===Z){const t=e.trim();if(!/^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,9}$/.test(t)||t.length<10){const e={id:(Date.now()+1).toString(),text:"Please provide a valid mobile number (e.g., +1234567890):",sender:"bot",timestamp:new Date};return T(t=>[...t,e]),void I("")}re(t);const n={id:Date.now().toString(),text:t,sender:"user",timestamp:new Date};T(e=>[...e,n]);const s=ie.current,a=se;return z(!1),ee(null),ie.current="",await(async(e,t,n)=>{try{U(!0);const a=R,o=await ge.current.ensureChatInitialized(ye,_e,a||null,e||null,t||null,n||null);if(!o||!o.chat_id)throw new Error("Failed to initialize chat session");const r=o.chat_id,i=o.session_id;r!==ye&&(ve(r),Se(i));try{await ge.current.requestHandoff(r,i,"Customer requested human agent",a||null,e||null,t||null,n||null)}catch(s){if(!(s.message?.includes("Invalid chat_id")||s.message?.includes("Chat not found")||s.message?.includes("unauthorized")||s.message?.includes("400")||s.message?.includes("401")||s.message?.includes("404")||s.message?.includes("expired")))throw s;{ve(null),Se(null);const s=await ge.current.startSupportChat(a||null,e||null,t||null,n||null);if(!s||!s.chat_id)throw new Error("Failed to re-initialize chat session");const o=s.chat_id,r=s.session_id;ve(o),Se(r),await ge.current.requestHandoff(o,r,"Customer requested human agent",a||null,e||null,t||null,n||null);const i=`${o}-${r}`;pe.current!==i&&(pe.current=i,await ke(!0))}}we(),G(!1),Q(!1);const c={id:`connecting-${Date.now()}`,text:"Connecting you to a human agent...",sender:"bot",timestamp:new Date};T(e=>[...e,c]);const l=`${r}-${i}`;pe.current=l}catch(a){const e={id:`error-${Date.now()}`,text:f?`Handoff error: ${a.message}`:"Failed to connect to agent. Please try again.",sender:"bot",timestamp:new Date};T(t=>[...t,e]),U(!1)}})(s,a,t),void I("")}}if("HUMAN"===fe){if(!ye||!_e){const e={id:Date.now().toString(),text:"Chat session not initialized. Please try again.",sender:"bot",timestamp:new Date};return void T(t=>[...t,e])}if(!s){const n={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};T(e=>[...e,n])}ge.current.sendTypingIndicator("typing_stop"),le.current&&(clearTimeout(le.current),le.current=null),I(""),A(!0);try{ge.current.sendMessageViaWebSocket(e.trim())||await ge.current.sendMessageToAgent(ye,_e,e.trim())}catch(o){if(o instanceof n.ChatResolvedError||"ChatResolvedError"===o?.name||"chat_resolved"===o?.message)return void be(ye);if(o.message?.includes("Chat not found")||o.message?.includes("unauthorized")||o.message?.includes("401")||o.message?.includes("404")){ve(null),Se(null);try{const t=await ge.current.startSupportChat(R||null,null,null,null);ve(t.chat_id),Se(t.session_id);try{await ge.current.sendMessageToAgent(t.chat_id,t.session_id,e.trim())}catch(r){if(r instanceof n.ChatResolvedError||"ChatResolvedError"===r?.name||"chat_resolved"===r?.message)return void be(t.chat_id);throw r}return}catch(r){if(r instanceof n.ChatResolvedError||"ChatResolvedError"===r?.name||"chat_resolved"===r?.message)return void be(ye);const e={id:(Date.now()+1).toString(),text:f?`Error: ${r.message||"Failed to send message."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};T(t=>[...t,e])}}else{const e={id:(Date.now()+1).toString(),text:f?`Error: ${o.message||"Failed to send message to agent."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};T(t=>[...t,e])}}finally{A(!1)}return}let a=R;if(!a)try{if(a=await Ie(),!a){const e={id:Date.now().toString(),text:f?"Failed to create session. Please check the console for details.":"Sorry, I'm having trouble connecting. Please try again.",sender:"bot",timestamp:new Date};return void T(t=>[...t,e])}}catch(o){const e={id:Date.now().toString(),text:f?`Connection Error: ${o.message||"Please check your Dialogflow configuration."}`:"Sorry, I'm having trouble connecting. Please check your configuration.",sender:"bot",timestamp:new Date};return void T(t=>[...t,e])}if(!s){const n={id:Date.now().toString(),text:t||e.trim(),sender:"user",timestamp:new Date};T(e=>[...e,n])}I(""),A(!0);try{const t=De();if(!t)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId and dfAgentId.");const s=await n.sendDialogflowMessage(e.trim(),a,t);if(!0===s.handoff){const e={id:(Date.now()+1).toString(),text:s.response,sender:"bot",timestamp:new Date(s.timestamp||Date.now()),richContent:s.richContent};T(t=>[...t,e]),z(!0),ee("name"),ne(""),ae(""),ie.current="";const t={id:(Date.now()+2).toString(),text:"To connect you with a human agent, I'll need some information. Please provide your name:",sender:"bot",timestamp:new Date};return void T(e=>[...e,t])}const o={id:(Date.now()+1).toString(),text:s.response,sender:"bot",timestamp:new Date(s.timestamp||Date.now()),richContent:s.richContent};T(e=>[...e,o])}catch(o){const e={id:(Date.now()+1).toString(),text:f?`Error: ${o.message||"Failed to send message. Please check your Dialogflow configuration."}`:o.message?.includes("Failed to fetch")||o.message?.includes("CORS")?"Unable to connect to Dialogflow. Please check your configuration and network.":"Sorry, I'm having trouble processing your message. Please try again.",sender:"bot",timestamp:new Date};T(t=>[...t,e])}finally{A(!1)}};t.useEffect(()=>()=>{le.current&&clearTimeout(le.current),de.current&&clearTimeout(de.current)},[]);const Ae=async()=>{D(!0),j(!1),R||await Ie()},Re=e=>e.includes("👤")||e.includes("being connected")||e.includes("live support agent")||e.includes("transfer your conversation")||e.includes("✅")||e.includes("🔄");return t.useEffect(()=>()=>{ge.current.disconnectWebSocket()},[]),e.jsxs(e.Fragment,{children:[C&&!b&&e.jsxs("div",{className:"custom-welcome-popup",onClick:Ae,children:[e.jsxs("div",{className:"custom-welcome-header",children:[e.jsx("div",{className:"custom-welcome-title",children:c}),e.jsx("button",{className:"custom-close-popup",onClick:e=>{e.stopPropagation(),j(!1)},children:"×"})]}),e.jsx("div",{className:"custom-welcome-message",children:l}),e.jsx("div",{className:"custom-welcome-cta",children:d})]}),!b&&e.jsx("button",{className:"custom-chat-toggle-btn",onClick:Ae,"aria-label":"Open chat",children:e.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),b&&e.jsxs("div",{className:"custom-chat-window",children:[e.jsxs("div",{className:"custom-chat-header",children:[e.jsxs("div",{className:"custom-chat-header-content",children:[e.jsx("div",{className:"custom-chat-title",children:s}),e.jsxs("div",{className:"custom-chat-subtitle",children:[a,"HUMAN"===fe&&e.jsxs("span",{className:"custom-mode-indicator",children:[" ","• ",L?"🟢 Connected":"🟡 Connecting..."]})]}),"HUMAN"===fe&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"custom-mode-badge",children:"Human Support Mode"}),e.jsxs("div",{className:"custom-agent-info",children:[e.jsx("span",{className:"custom-agent-label",children:"Agent:"}),e.jsx("span",{className:"custom-agent-name",children:W.name})]})]}),"BOT"===fe&&e.jsx("div",{className:"custom-mode-badge",children:"Bot Mode"})]}),e.jsx("button",{className:"custom-chat-close-btn",onClick:()=>{D(!1),"HUMAN"===fe&&ge.current.disconnectWebSocket()},"aria-label":"Close chat",children:"×"})]}),e.jsxs("div",{className:"custom-chat-messages",children:[$&&0===N.length&&e.jsxs("div",{className:"custom-chat-empty",children:[e.jsxs("div",{className:"custom-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsx("p",{children:"Initializing chat..."})]}),!$&&0===N.length&&e.jsxs("div",{className:"custom-chat-empty",children:[e.jsx("div",{className:"custom-chat-empty-icon",children:"👋"}),e.jsx("p",{children:p})]}),N.map(t=>e.jsxs("div",{className:`custom-message custom-message-${t.sender} ${Re(t.text)?"custom-handoff-message":""}`,children:[e.jsx("div",{className:"custom-message-content "+(Re(t.text)?"custom-handoff-content":""),dangerouslySetInnerHTML:{__html:n.linkifyText(t.text).replace(/\n/g,"<br>")}}),(f&&t.richContent,t.richContent&&Array.isArray(t.richContent)&&t.richContent.length>0?e.jsx("div",{className:"custom-chips-container",children:t.richContent.map((t,n)=>{if(!Array.isArray(t)){const s=t;return s&&"chips"===s.type&&s.options?e.jsx("div",{className:"custom-chips-group",children:s.options.map((t,n)=>e.jsx("button",{className:"custom-chip-button",onClick:()=>{const e={id:Date.now().toString(),text:t.text,sender:"user",timestamp:new Date};T(t=>[...t,e]),Ee(t.text,t.text,!0)},type:"button",children:t.text},n))},n):null}return t.map((t,s)=>t&&"chips"===t.type&&t.options?e.jsx("div",{className:"custom-chips-group",children:t.options.map((t,n)=>e.jsx("button",{className:"custom-chip-button",onClick:()=>{const e={id:Date.now().toString(),text:t.text,sender:"user",timestamp:new Date};T(t=>[...t,e]),Ee(t.text,t.text,!0)},type:"button",children:t.text},n))},`${n}-${s}`):null)})}):null),e.jsx("div",{className:"custom-message-time",children:t.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]},t.id)),E&&e.jsx("div",{className:"custom-message custom-message-bot",children:e.jsxs("div",{className:"custom-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]})}),P&&e.jsxs("div",{className:"custom-message custom-message-bot",children:[e.jsxs("div",{className:"custom-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsx("div",{className:"custom-message-content",children:"Connecting to agent..."})]}),"HUMAN"===fe&&V&&e.jsxs("div",{className:"custom-agent-typing-indicator",children:[e.jsxs("span",{className:"custom-typing-dots",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsx("span",{className:"custom-typing-text",children:"Agent is typing..."})]}),e.jsx("div",{ref:ce})]}),e.jsxs("form",{className:"custom-chat-input-form",onSubmit:e=>{e.preventDefault(),Ee(k)},children:[e.jsx("input",{type:"text",className:"custom-chat-input",value:k,onChange:e=>{const t=e.target.value;I(t),"HUMAN"===fe&&L&&(ge.current.sendTypingIndicator("typing_start"),le.current&&clearTimeout(le.current),le.current=setTimeout(()=>{ge.current.sendTypingIndicator("typing_stop"),le.current=null},2e3))},placeholder:g,disabled:E||$||X}),e.jsx("button",{type:"submit",className:"custom-chat-send-btn",disabled:!k.trim()||E||$||X,children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),e.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]})]})]})}function l(){const e="undefined"==typeof window;if("undefined"!=typeof process&&void 0!==process.env){const t=process.env;if(t?.NEXT_RUNTIME)return{name:"next",version:t.NEXT_VERSION,isSSR:e}}if("undefined"!=typeof process&&void 0!==process.env){const t=process.env;if(t?.NUXT||globalThis.__NUXT__)return{name:"nuxt",version:t.NUXT_VERSION,isSSR:e}}if(globalThis.__NUXT__)return{name:"nuxt",version:void 0,isSSR:e};if(void 0!=={url:"undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("index.cjs.js",document.baseURI).href}){const t={url:"undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("index.cjs.js",document.baseURI).href};if(t.env?.DEV)return{name:"vite",version:t.env?.VITE_VERSION,isSSR:e}}return function(){if("undefined"!=typeof window&&(window.React||window.react))return!0;if("undefined"!=typeof document&&window.__REACT_DEVTOOLS_GLOBAL_HOOK__)return!0;return!1}()?{name:"react",version:d(),isSSR:e}:function(){if("undefined"!=typeof window&&(window.Vue||window.vue))return!0;if("undefined"!=typeof window&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__)return!0;return!1}()?{name:"vue",version:u(),isSSR:e}:{name:"vanilla",isSSR:e}}function d(){try{if("undefined"!=typeof window&&window.React?.version)return window.React.version;if("undefined"!=typeof window&&window.__REACT_DEVTOOLS_GLOBAL_HOOK__){const e=window.__REACT_DEVTOOLS_GLOBAL_HOOK__;if(e.renderers&&e.renderers.size>0){return Array.from(e.renderers.values())[0].version}}}catch{}}function u(){try{if("undefined"!=typeof window&&window.Vue?.version)return window.Vue.version;if("undefined"!=typeof window&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__){const e=window.__VUE_DEVTOOLS_GLOBAL_HOOK__;if(e.apps&&e.apps.length>0){return e.apps[0].version}}}catch{}}let m=null;var h,g=s;h=g.createRoot,g.hydrateRoot;class p{constructor(e,t){if(this.root=null,this.config=t,"string"==typeof e){const t=document.querySelector(e);if(!t)throw new Error(`Container element "${e}" not found`);this.container=t}else this.container=e;this.root=h(this.container),this.render()}render(){this.root&&this.root.render(t.createElement(c,this.config))}updateConfig(e){this.config={...this.config,...e},this.render()}destroy(){this.root&&(this.root.unmount(),this.root=null)}}exports.createDialogflowSession=n.createDialogflowSession,exports.sendDialogflowMessage=n.sendDialogflowMessage,exports.ChatWidget=c,exports.ReactChatWidget=c,exports.VanillaChatWidget=p,exports.createChatWidget=function(e,t){return new p(e,t)},exports.default=c,exports.getFramework=function(){return m?{name:m,isSSR:"undefined"==typeof window}:l()},exports.setFramework=function(e){m=e};
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("react/jsx-runtime"),t=require("react"),s=require("./sanitize-BYa4jHJ0.cjs"),n=require("react-dom");var r="undefined"!=typeof document?document.currentScript:null;const a="chartsconnectect_chat_mode",o="chartsconnect_chat_id",i="chartsconnect_session_id";function c({title:n="💬 Charts Connect AI Assistant",subtitle:r="We're here to help",welcomeTitle:c="👋 Welcome to Charts Connect",welcomeMessage:l="My name is Charts Connect AI Assistant and I'll guide you.",welcomeCta:u="💬 Click here to start chatting!",showWelcomePopup:d=!0,welcomePopupDelay:m=1500,fallbackWelcomeMessage:h="Hello! I'm Charts Connect AI Assistant. How can I help you today?",inputPlaceholder:g="Type your message...",emptyStateMessage:f="Hi! I'm Charts Connect AI Assistant. How can I help you today?",debug:p=!1,dfProjectId:w,dfLocation:y="us-central1",dfAgentId:_,languageCode:x="en",backendBaseUrl:v,backendWsUrl:b}){const S=t.useRef(0),C=(e="msg")=>`${e}-${Date.now()}-${++S.current}`,[j,T]=t.useState(!1),[N,k]=t.useState(!1),[I,D]=t.useState([]),[R,E]=t.useState(""),[A,O]=t.useState(!1),[M,U]=t.useState(null),[H,L]=t.useState(!1),[P,$]=t.useState(!1),[V,B]=t.useState(!1),[F,W]=t.useState(!1),[q,z]=t.useState({name:"Agent"}),[G,K]=t.useState(!1),[X,Y]=t.useState(!1),[J,Q]=t.useState(!1),Z=t.useRef(null),ee=t.useRef(null),te=t.useRef(null),se=t.useRef(!1),ne=t.useRef(null),re=t.useRef(null),ae=()=>v||"https://chartconnect.blockspark.in",oe=t.useRef(s.createChatService({baseUrl:ae(),wsUrl:b||"wss://chartconnect.blockspark.in",debug:p})),ie=t.useRef(null),{currentMode:ce,switchToHumanMode:le,switchToBotMode:ue,chatId:de,sessionId:me,setChatId:he,setSessionId:ge}=function(){const[e,s]=t.useState(()=>"HUMAN"===localStorage.getItem(a)?"HUMAN":"BOT"),[n,r]=t.useState(()=>localStorage.getItem(o)),[c,l]=t.useState(()=>localStorage.getItem(i));t.useEffect(()=>{localStorage.setItem(a,e)},[e]);const u=t.useCallback(e=>{r(e),e?localStorage.setItem(o,e):localStorage.removeItem(o)},[]),d=t.useCallback(e=>{l(e),e?localStorage.setItem(i,e):localStorage.removeItem(i)},[]),m=t.useCallback(()=>{s("HUMAN")},[]),h=t.useCallback(()=>{s("BOT")},[]),g=t.useCallback(e=>!1,[]);return{currentMode:e,switchToHumanMode:m,switchToBotMode:h,isHandoffTriggered:g,chatId:n,sessionId:c,setChatId:u,setSessionId:d}}(),fe=t.useCallback(e=>{K(!0),$(!1),Q(!1),W(!1),te.current&&(clearTimeout(te.current),te.current=null),oe.current.disconnectWebSocket(),he(null),ge(null),U(null);const t={id:C("resolved"),text:"Thank you for contacting us!",sender:"bot",timestamp:new Date};D(e=>[...e,t]),ne.current&&clearTimeout(ne.current),ne.current=setTimeout(()=>{ne.current=null,ue(),K(!1),D([]),re.current&&re.current().catch(console.error)},2e3)},[he,ge,ue]);t.useCallback(async()=>{if(!X){Y(!0);try{const e=await oe.current.startSupportChat(M||null);le(),he(e.chat_id),ge(e.session_id),K(!1),E("")}catch(e){D(t=>[...t,{id:C("error"),text:p?`Error: ${e?.message||"Failed to start a new chat."}`:"Sorry, I couldn't start a new chat. Please try again.",sender:"bot",timestamp:new Date}])}finally{Y(!1)}}},[p,X,M,he,ge,le]);const pe=()=>{if(w&&_)return{dfProjectId:w,dfLocation:y||"us-central1",dfAgentId:_,languageCode:x||"en",backendBaseUrl:ae()}};t.useEffect(()=>{if(!d)return;const e=setTimeout(()=>{j||k(!0)},m);return()=>clearTimeout(e)},[d,m,j]);const we=t.useRef(null);t.useEffect(()=>(we.current&&clearTimeout(we.current),we.current=setTimeout(()=>{Z.current?.scrollIntoView({behavior:"smooth"})},80),()=>{we.current&&clearTimeout(we.current)}),[I]);const ye=t.useCallback(e=>{if(e.to_agent){z({id:e.to_agent_id,name:e.to_agent});const t={id:C("system"),text:e.from_agent?`Chat has been transferred from ${e.from_agent} to ${e.to_agent}`:`Chat has been transferred to ${e.to_agent}`,sender:"bot",timestamp:new Date};D(e=>[...e,t])}},[p]),_e=t.useCallback(e=>{switch(e.type){case"message":if(e.content)if("agent"!==e.sender_type&&e.sender_type)p&&e.sender_type;else{const t={id:e.id||C("agent"),text:e.content,sender:"agent",timestamp:new Date(e.timestamp||Date.now())};D(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),W(!1),te.current&&(clearTimeout(te.current),te.current=null)}break;case"typing_start":"agent"===e.sender_type&&(W(!0),te.current&&clearTimeout(te.current),te.current=setTimeout(()=>{W(!1)},3e3));break;case"typing_stop":"agent"===e.sender_type&&(W(!1),te.current&&(clearTimeout(te.current),te.current=null));break;case"agent_changed":ye(e);break;case"chat_info":"active"===e.status?($(!1),Q(!0)):"resolved"!==e.status&&"ended"!==e.status||fe(e.chat_id||null),e.agent_id&&z(t=>({...t,id:e.agent_id}));break;case"agent_accepted":Q(!0),$(!1);const t={id:e.id||C("agent-accepted"),text:"You can chat now, the agent has accepted your request.",sender:"bot",timestamp:e.timestamp?new Date(e.timestamp):new Date};D(e=>new Set(e.map(e=>e.id)).has(t.id)?e:[...e,t]),e.to_agent&&z({name:e.to_agent,id:e.to_agent_id});break;case"chat_resolved":case"chat_ended":fe(e.chat_id||null);break;case"error":const s={id:C("error"),text:e.error||"An error occurred. Please try again.",sender:"bot",timestamp:new Date};D(e=>[...e,s])}},[p,fe,ye]),xe=t.useCallback(e=>{4e3===e.code&&fe(de)},[de,fe]),ve=t.useCallback(e=>{B(e),e&&$(!1)},[]);t.useEffect(()=>{if("HUMAN"===ce&&de&&me)return oe.current.connectWebSocket(de,me,_e,ve,xe),()=>{oe.current.disconnectWebSocket()}},[ce,de,me,_e,ve,xe]);const be=t.useCallback(async(e=!0)=>{if(de&&me)try{O(!0);const t=(await oe.current.loadMessageHistory(de,me)).map(e=>({id:e.id||C("history"),text:e.content,sender:"agent"===e.sender_type?"agent":"user",timestamp:new Date(e.timestamp)}));D(e?e=>{const s=new Set(e.map(e=>e.id)),n=t.filter(e=>!s.has(e.id));return[...e,...n].sort((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())}:t)}catch(t){if(p){const e={id:C("error"),text:`Failed to load chat history: ${t.message}`,sender:"bot",timestamp:new Date};D(t=>[...t,e])}}finally{O(!1)}},[de,me,p]);t.useEffect(()=>{if("HUMAN"===ce&&de&&me){const e=`${de}-${me}`;if(ie.current!==e){ie.current=e;setTimeout(()=>{0===I.length&&be(!1).catch(console.error)},0)}}else"BOT"===ce&&(ie.current=null)},[ce,de,me,be,I.length]);const Se=async(e=!1,t=!1)=>{if(M&&!e&&!t)return M;if(se.current){if(await new Promise(e=>setTimeout(e,100)),M)return M;throw new Error("Session creation in progress. Please try again.")}se.current=!0;try{L(!0);const e=pe();if(!e)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId and dfAgentId.");const n=t&&M?M:null,r=await s.createDialogflowSession(e,n);if(U(r.session_id),r.message){const e={id:C("welcome"),text:r.message,sender:"bot",timestamp:new Date,richContent:r.richContent};D(t=>0===t.length?[e]:[e,...t])}return r.session_id}catch(n){const e={id:C("error"),text:p?`Error: ${n.message||"Failed to create session. Please check your Dialogflow configuration."}`:h,sender:"bot",timestamp:new Date};return D(t=>[...t,e]),null}finally{L(!1),se.current=!1}};re.current=Se;const Ce=t.useRef(!1),je=async(e,t,s=!1)=>{if(e.trim()&&!Ce.current){Ce.current=!0;try{await Te(e,t,s)}finally{Ce.current=!1}}},Te=async(e,t,n=!1)=>{if(!e.trim())return;if("HUMAN"===ce){if(!de||!me){const e={id:C("msg"),text:"Chat session not initialized. Please try again.",sender:"bot",timestamp:new Date};return void D(t=>[...t,e])}if(!n){const s={id:C("msg"),text:t||e.trim(),sender:"user",timestamp:new Date};D(e=>[...e,s])}oe.current.sendTypingIndicator("typing_stop"),ee.current&&(clearTimeout(ee.current),ee.current=null),E(""),O(!0);try{oe.current.sendMessageViaWebSocket(e.trim())||await oe.current.sendMessageToAgent(de,me,e.trim())}catch(a){if(a instanceof s.ChatResolvedError||"ChatResolvedError"===a?.name||"chat_resolved"===a?.message)return void fe(de);if(a.message?.includes("Chat not found")||a.message?.includes("unauthorized")||a.message?.includes("401")||a.message?.includes("404")){he(null),ge(null);try{const t=await oe.current.startSupportChat(M||null);he(t.chat_id),ge(t.session_id);try{await oe.current.sendMessageToAgent(t.chat_id,t.session_id,e.trim())}catch(o){if(o instanceof s.ChatResolvedError||"ChatResolvedError"===o?.name||"chat_resolved"===o?.message)return void fe(t.chat_id);throw o}return}catch(o){if(o instanceof s.ChatResolvedError||"ChatResolvedError"===o?.name||"chat_resolved"===o?.message)return void fe(de);const e={id:C("msg"),text:p?`Error: ${o.message||"Failed to send message."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};D(t=>[...t,e])}}else{const e={id:C("msg"),text:p?`Error: ${a.message||"Failed to send message to agent."}`:"Sorry, I'm having trouble sending your message. Please try again.",sender:"bot",timestamp:new Date};D(t=>[...t,e])}}finally{O(!1)}return}let r=M;if(!r)try{if(r=await Se(),!r){const e={id:C("msg"),text:p?"Failed to create session. Please check the console for details.":"Sorry, I'm having trouble connecting. Please try again.",sender:"bot",timestamp:new Date};return void D(t=>[...t,e])}}catch(a){const e={id:C("msg"),text:p?`Connection Error: ${a.message||"Please check your Dialogflow configuration."}`:"Sorry, I'm having trouble connecting. Please check your configuration.",sender:"bot",timestamp:new Date};return void D(t=>[...t,e])}if(!n){const s={id:C("msg"),text:t||e.trim(),sender:"user",timestamp:new Date};D(e=>[...e,s])}E(""),O(!0);try{const t=pe();if(!t)throw new Error("Dialogflow configuration is missing. Please provide dfProjectId and dfAgentId.");const n=await s.sendDialogflowMessage(e.trim(),r,t);if(!0===n.handoff){if(n.response||n.richContent){const e={id:C("msg"),text:n.response,sender:"bot",timestamp:new Date(n.timestamp||Date.now()),richContent:n.richContent};D(t=>[...t,e])}return void(await(async(e,t)=>{try{$(!0);const n=M,r=e&&t?{chat_id:e,session_id:t}:await oe.current.ensureChatInitialized(de,me,n||null);if(!r||!r.chat_id)throw new Error("Failed to initialize chat session");const a=r.chat_id,o=r.session_id;if(a!==de&&(he(a),ge(o)),!e)try{await oe.current.requestHandoff(a,o,"Customer requested human agent",n||null)}catch(s){if(!(s.message?.includes("Invalid chat_id")||s.message?.includes("Chat not found")||s.message?.includes("unauthorized")||s.message?.includes("400")||s.message?.includes("401")||s.message?.includes("404")||s.message?.includes("expired")))throw s;{he(null),ge(null);const e=await oe.current.startSupportChat(n||null);if(!e||!e.chat_id)throw new Error("Failed to re-initialize chat session");const t=e.chat_id,s=e.session_id;he(t),ge(s),await oe.current.requestHandoff(t,s,"Customer requested human agent",n||null);const r=`${t}-${s}`;ie.current!==r&&(ie.current=r,await be(!0))}}le(),K(!1),Q(!1);const i=`${a}-${o}`;ie.current=i}catch(a){const t={id:C("error"),text:p?`Handoff error: ${a.message}`:"Failed to connect to agent. Please try again.",sender:"bot",timestamp:new Date};D(e=>[...e,t]),$(!1)}})(n.chat_id,n.support_session_id))}if(n.response||n.richContent){const e={id:C("msg"),text:n.response,sender:"bot",timestamp:new Date(n.timestamp||Date.now()),richContent:n.richContent};D(t=>[...t,e])}}catch(a){const e={id:C("msg"),text:p?`Error: ${a.message||"Failed to send message. Please check your Dialogflow configuration."}`:a.message?.includes("Failed to fetch")||a.message?.includes("CORS")?"Unable to connect to Dialogflow. Please check your configuration and network.":"Sorry, I'm having trouble processing your message. Please try again.",sender:"bot",timestamp:new Date};D(t=>[...t,e])}finally{O(!1)}};t.useEffect(()=>()=>{ee.current&&clearTimeout(ee.current),te.current&&clearTimeout(te.current)},[]);const Ne=async()=>{T(!0),k(!1),M||await Se()},ke=e=>e.includes("👤")||e.includes("being connected")||e.includes("live support agent")||e.includes("transfer your conversation")||e.includes("✅")||e.includes("🔄");return t.useEffect(()=>()=>{oe.current.disconnectWebSocket()},[]),e.jsxs(e.Fragment,{children:[N&&!j&&e.jsxs("div",{className:"custom-welcome-popup",onClick:Ne,children:[e.jsxs("div",{className:"custom-welcome-header",children:[e.jsx("div",{className:"custom-welcome-title",children:c}),e.jsx("button",{className:"custom-close-popup",onClick:e=>{e.stopPropagation(),k(!1)},children:"×"})]}),e.jsx("div",{className:"custom-welcome-message",children:l}),e.jsx("div",{className:"custom-welcome-cta",children:u})]}),!j&&e.jsx("button",{className:"custom-chat-toggle-btn",onClick:Ne,"aria-label":"Open chat",children:e.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),j&&e.jsxs("div",{className:"custom-chat-window",children:[e.jsxs("div",{className:"custom-chat-header",children:[e.jsxs("div",{className:"custom-chat-header-content",children:[e.jsx("div",{className:"custom-chat-title",children:n}),e.jsxs("div",{className:"custom-chat-subtitle",children:[r,"HUMAN"===ce&&e.jsxs("span",{className:"custom-mode-indicator",children:[" ","• ",V?"🟢 Connected":"🟡 Connecting..."]})]}),"HUMAN"===ce&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"custom-mode-badge",children:"Human Support Mode"}),e.jsxs("div",{className:"custom-agent-info",children:[e.jsx("span",{className:"custom-agent-label",children:"Agent:"}),e.jsx("span",{className:"custom-agent-name",children:q.name})]})]}),"BOT"===ce&&e.jsx("div",{className:"custom-mode-badge",children:"Bot Mode"})]}),e.jsx("button",{className:"custom-chat-close-btn",onClick:()=>{T(!1),"HUMAN"===ce&&oe.current.disconnectWebSocket()},"aria-label":"Close chat",children:"×"})]}),e.jsxs("div",{className:"custom-chat-messages",children:[H&&0===I.length&&e.jsxs("div",{className:"custom-chat-empty",children:[e.jsxs("div",{className:"custom-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsx("p",{children:"Initializing chat..."})]}),!H&&0===I.length&&e.jsxs("div",{className:"custom-chat-empty",children:[e.jsx("div",{className:"custom-chat-empty-icon",children:"👋"}),e.jsx("p",{children:f})]}),I.map(t=>e.jsxs("div",{className:`custom-message custom-message-${t.sender} ${ke(t.text)?"custom-handoff-message":""}`,children:[e.jsx("div",{className:"custom-message-content "+(ke(t.text)?"custom-handoff-content":""),dangerouslySetInnerHTML:{__html:s.linkifyText(t.text).replace(/\n/g,"<br>")}}),(p&&t.richContent,t.richContent&&Array.isArray(t.richContent)&&t.richContent.length>0?e.jsx("div",{className:"custom-chips-container",children:t.richContent.map((t,s)=>{if(!Array.isArray(t)){const n=t;return n&&"chips"===n.type&&n.options?e.jsx("div",{className:"custom-chips-group",children:n.options.map((t,s)=>e.jsx("button",{className:"custom-chip-button",onClick:()=>{const e={id:C("msg"),text:t.text,sender:"user",timestamp:new Date};D(t=>[...t,e]),je(t.text,t.text,!0)},type:"button",children:t.text},s))},s):null}return t.map((t,n)=>t&&"chips"===t.type&&t.options?e.jsx("div",{className:"custom-chips-group",children:t.options.map((t,s)=>e.jsx("button",{className:"custom-chip-button",onClick:()=>{const e={id:C("msg"),text:t.text,sender:"user",timestamp:new Date};D(t=>[...t,e]),je(t.text,t.text,!0)},type:"button",children:t.text},s))},`${s}-${n}`):null)})}):null),e.jsx("div",{className:"custom-message-time",children:t.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]},t.id)),A&&e.jsx("div",{className:"custom-message custom-message-bot",children:e.jsxs("div",{className:"custom-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]})}),P&&e.jsx("div",{className:"custom-message custom-message-bot",children:e.jsxs("div",{className:"custom-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]})}),"HUMAN"===ce&&F&&e.jsx("div",{className:"custom-message custom-message-bot",children:e.jsxs("div",{className:"custom-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]})}),e.jsx("div",{ref:Z})]}),e.jsxs("form",{className:"custom-chat-input-form",onSubmit:e=>{e.preventDefault(),je(R)},children:[e.jsx("input",{type:"text",className:"custom-chat-input",value:R,onChange:e=>{const t=e.target.value;E(t),"HUMAN"===ce&&V&&(oe.current.sendTypingIndicator("typing_start"),ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{oe.current.sendTypingIndicator("typing_stop"),ee.current=null},2e3))},placeholder:g,disabled:A||H||X}),e.jsx("button",{type:"submit",className:"custom-chat-send-btn",disabled:!R.trim()||A||H||X,children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),e.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]})]})]})}function l(){const e="undefined"==typeof window;if("undefined"!=typeof process&&void 0!==process.env){const t=process.env;if(t?.NEXT_RUNTIME)return{name:"next",version:t.NEXT_VERSION,isSSR:e}}if("undefined"!=typeof process&&void 0!==process.env){const t=process.env;if(t?.NUXT||globalThis.__NUXT__)return{name:"nuxt",version:t.NUXT_VERSION,isSSR:e}}if(globalThis.__NUXT__)return{name:"nuxt",version:void 0,isSSR:e};if(void 0!=={url:"undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index.cjs.js",document.baseURI).href}){const t={url:"undefined"==typeof document?require("url").pathToFileURL(__filename).href:r&&"SCRIPT"===r.tagName.toUpperCase()&&r.src||new URL("index.cjs.js",document.baseURI).href};if(t.env?.DEV)return{name:"vite",version:t.env?.VITE_VERSION,isSSR:e}}return function(){if("undefined"!=typeof window&&(window.React||window.react))return!0;if("undefined"!=typeof document&&window.__REACT_DEVTOOLS_GLOBAL_HOOK__)return!0;return!1}()?{name:"react",version:u(),isSSR:e}:function(){if("undefined"!=typeof window&&(window.Vue||window.vue))return!0;if("undefined"!=typeof window&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__)return!0;return!1}()?{name:"vue",version:d(),isSSR:e}:{name:"vanilla",isSSR:e}}function u(){try{if("undefined"!=typeof window&&window.React?.version)return window.React.version;if("undefined"!=typeof window&&window.__REACT_DEVTOOLS_GLOBAL_HOOK__){const e=window.__REACT_DEVTOOLS_GLOBAL_HOOK__;if(e.renderers&&e.renderers.size>0){return Array.from(e.renderers.values())[0].version}}}catch{}}function d(){try{if("undefined"!=typeof window&&window.Vue?.version)return window.Vue.version;if("undefined"!=typeof window&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__){const e=window.__VUE_DEVTOOLS_GLOBAL_HOOK__;if(e.apps&&e.apps.length>0){return e.apps[0].version}}}catch{}}let m=null;var h,g=n;h=g.createRoot,g.hydrateRoot;class f{constructor(e,t){if(this.root=null,this.config=t,"string"==typeof e){const t=document.querySelector(e);if(!t)throw new Error(`Container element "${e}" not found`);this.container=t}else this.container=e;this.root=h(this.container),this.render()}render(){this.root&&this.root.render(t.createElement(c,this.config))}updateConfig(e){this.config={...this.config,...e},this.render()}destroy(){this.root&&(this.root.unmount(),this.root=null)}}exports.createDialogflowSession=s.createDialogflowSession,exports.sendDialogflowMessage=s.sendDialogflowMessage,exports.ChatWidget=c,exports.ReactChatWidget=c,exports.VanillaChatWidget=f,exports.createChatWidget=function(e,t){return new f(e,t)},exports.default=c,exports.getFramework=function(){return m?{name:m,isSSR:"undefined"==typeof window}:l()},exports.setFramework=function(e){m=e};
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|