chatnest 3.4.0 → 3.4.2

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/readme.md CHANGED
@@ -1,306 +1,462 @@
1
1
  # ChatNest
2
2
 
3
- ![ChatNest](https://i.ibb.co.com/ts1T0q7/chatnest.jpg) _____________________________________________________________________________________
3
+ <p align="center">
4
+ <img src="https://i.ibb.co.com/ts1T0q7/chatnest.jpg" alt="ChatNest" width="400">
5
+ </p>
4
6
 
5
- ChatNest is a lightweight, customizable, and easy-to-integrate JavaScript widget for adding chat functionality to your web applications. It comes with a flexible configuration system, allowing you to tailor the chatbot's appearance and behavior to suit your app's needs.
6
-
7
- ## Table of Contents
8
- - [Key Features](#key-features)
9
- - [Installation](#installation)
10
- - [Usage](#usage)
11
- - [Configuration Options](#configuration-options)
12
- - [Example Initialization with Full Configuration](#example-initialization-with-full-configuration)
13
- - [Dependencies](#dependencies)
14
-
15
- ## Key Features
16
-
17
- 1. **Seamless Integration with LLMs using LangChain or RAG (Retrieval-Augmented Generation)**
18
- - **LangChain Integration**: ChatNest is fully compatible with LangChain, allowing developers to harness the power of large language models (LLMs) directly within their chat interface. This enables dynamic and context-aware responses by structuring conversation history, improving response generation, and enabling multi-turn conversations.
19
- - **RAG-Based Conversational AI**: With RAG, ChatNest offers access to real-time knowledge bases, document databases, and custom data sources, allowing users to retrieve and interact with up-to-date and accurate information. This setup is ideal for applications that require responses grounded in specific knowledge domains, like customer support, product information, or knowledge retrieval.
20
-
21
- 2. **Flexible Configuration System**
22
- - Developers can control chatbot settings, such as default endpoints (e.g., `deleteEndpoint` for clearing history or `apiEndpoint` for main interactions), response types, themes, and interaction prompts.
23
- - ChatNest supports custom API routes, allowing developers to set up and route requests to specific RAG or LangChain endpoints for highly optimized and tailored performance.
24
-
25
- 3. **Customizable UI**
26
- - ChatNest is designed to blend seamlessly with your app’s visual style. You can adjust colors, fonts, and layout, enabling a fully branded chatbot experience.
27
- - The widget is also mobile-responsive, ensuring optimal user experience across all devices.
28
-
29
- ## Use Cases
30
-
31
- - **Customer Support**: ChatNest, combined with LangChain or RAG, can serve as a smart assistant capable of answering questions based on real-time data from your knowledge base.
32
- - **Product Recommendations**: For e-commerce, ChatNest can pull from product databases, providing users with personalized recommendations and detailed product descriptions.
33
- - **Knowledge Retrieval**: ChatNest can act as a virtual assistant in educational platforms, retrieving information from research papers, textbooks, or articles, enhancing learning experiences.
34
- - **Internal Tools**: Enhance productivity by allowing team members to interact with internal databases or corporate knowledge resources through the chat interface.
7
+ A lightweight, customizable AI chat widget. Drop it into any website in minutes.
35
8
 
9
+ ---
36
10
 
37
11
  ## Installation
38
12
 
39
- To include ChatNest in your project, add the following CDN link to your HTML file:
40
-
13
+ **CDN**
41
14
  ```html
42
- <script src="https://cdn.jsdelivr.net/npm/chatnest@3.4.0"></script>
15
+ <script src="https://cdn.jsdelivr.net/npm/chatnest@3.4.2/dist/chatnest.min.js"></script>
43
16
  ```
44
17
 
45
- Alternatively, you can install it using npm:
46
-
18
+ **npm**
47
19
  ```bash
48
20
  npm install chatnest
49
21
  ```
22
+ ```js
23
+ import Chatnest from 'chatnest';
24
+ ```
25
+
26
+ ---
27
+
28
+ ## Quick Start
50
29
 
51
- ## Usage
52
- Once ChatNest is included, you can initialize the chat widget by creating an instance of EasyChatWidget in your JavaScript code. For example:
53
-
54
- ```javascript
55
- document.addEventListener('DOMContentLoaded', () => {
56
- const chatWidget = new EasyChatWidget({
57
- botName: 'Support Bot',
58
- botImage: 'https://example.com/bot-image.png',
59
- greeting: 'Hi there! How can I assist you today?',
60
- apiEndpoint: 'https://your-api-endpoint.com/chat',
61
- primaryColor: '#1a73e8',
62
- width: '400px',
63
- height: '600px'
30
+ ```html
31
+ <script src="https://cdn.jsdelivr.net/npm/chatnest@3.4.2/dist/chatnest.min.js"></script>
32
+ <script>
33
+ document.addEventListener('DOMContentLoaded', () => {
34
+ new Chatnest({
35
+ botName: 'Support Bot',
36
+ apiEndpoint: 'https://your-api.com/chat',
37
+ primaryColor: '#0084ff'
64
38
  });
65
- });
39
+ });
40
+ </script>
66
41
  ```
67
42
 
68
- ## Configuration Options
69
-
70
- Below are the available configuration options you can set when initializing EasyChatWidget.
71
-
72
-
73
- | **Option** | **Type** | **Default Value** | **Description** |
74
- |--------------------------|---------------------|----------------------------------------------|-------------------------------------------------------------------------------------------------------|
75
- | `botName` | `string` | `'Chat Assistant'` | The name of the chatbot displayed in the widget header. |
76
- | `botImage` | `string` | ![default](data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"%3E%3Cpath fill="%23fff" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"%3E%3C/path%3E%3C/svg%3E) | The image displayed for the bot in the chat. |
77
- | `greeting` | `string` | `'Hello! How can I help you today?'` | The initial greeting message displayed to users when they open the chat widget. |
78
- | `placeholder` | `string` | `'Type your message here...'` | Placeholder text shown in the message input field. |
79
- | `primaryColor` | `string` | `'#0084ff'` | Primary color used for styling widget buttons, highlights, and other accents. Supports hex colors and CSS gradients (e.g., `'linear-gradient(to right, #2563eb, #9333ea)'`). |
80
- | `fontSize` | `string` | `clampFontSize(config.fontSize || 14)` | Font size for text in the widget, automatically clamped to prevent extremes. |
81
- | `width` | `string` | `'400px'` (300px - 600px) | Width of the chat widget, restricted between 300px and 600px for responsive layouts. |
82
- | `height` | `string` | `'600px'` (400px - 800px) | Height of the chat widget, restricted between 400px and 800px for optimal usability. |
83
- | `showTimestamp` | `boolean` | `false` | If `true`, timestamps are displayed next to each message. |
84
- | `enableTypingIndicator` | `boolean` | `true` | Displays a typing indicator when the bot is processing messages. |
85
- | `enableMarkdown` | `boolean` | `true` | Enables Markdown formatting in bot responses. Requires `Marked.js` as a dependency. |
86
- | `enableHistory` | `boolean` | `true` | Saves chat history locally, persisting it when the page is refreshed. |
87
- | `maxHistoryLength` | `number` | `100` | Maximum number of messages to store in chat history. |
88
- | `separateSubpageHistory` | `boolean` | `false` | If `true`, chat history is stored separately for each subpage of the application. |
89
- | `enableTypewriter` | `boolean` | `true` | Enables a typewriter effect for bot responses. |
90
- | `typewriterSpeed` | `object` | `{ min: 30, max: 70 }` | Speed range (in milliseconds) for the typewriter effect. |
91
- | `typewritewithscroll` | `boolean` | `false` | When `true`: AI response uses typewriter effect WITH scrolling. When `false`: typewriter WITHOUT scrolling. |
92
- | `chips` | `array` | `[]` | Array of predefined response options displayed as clickable chips. |
93
- | `customStyles` | `object` | `{}` | Custom CSS styles for widget components. |
94
- | `onInit` | `function` | `null` | Callback function executed when the widget is initialized. |
95
- | `onMessage` | `function` | `null` | Callback function executed when a message is sent or received. |
96
- | `onError` | `function` | `null` | Callback function executed when an error occurs. |
97
- | `apiEndpoint` | `string` | `'http://localhost:7000/chat'` | The API endpoint for the bot's chat backend. Adjusts based on the site's protocol (e.g., `https://`). |
98
- | `apiKey` | `string` | `''` | API key used for authentication with the backend. |
99
- | `apiHeaders` | `object` | `{ 'Content-Type': 'application/json' }` | HTTP headers sent with each API request. |
100
- | `apiRequestFormat` | `object` | `{ query: 'query', userId: 'userId', domain: 'domain' }` | Defines the format of API requests, specifying the query, user ID, and domain fields. |
101
- | `apiResponseFormat` | `object` | `{ response: 'response' }` | Defines the format of API responses, specifying the field containing the bot's response. |
102
- | `apiMethod` | `string` | `'POST'` | HTTP method used for API requests (e.g., `POST` or `GET`). |
103
- | `apiTimeout` | `number` | `30000` (30 seconds) | Timeout duration for API requests, in milliseconds. |
104
- | `deleteEndpoint` | `string` | `formatApiEndpoint(config.deleteEndpoint) or ${formatApiEndpoint(config.apiEndpoint).replace(/\/chat$/, '')}/delete-history` | Endpoint for deleting chat history, defaulting to a modified `apiEndpoint` if not explicitly set. |
105
- | `feedbackEndpoint` | `string` | `${config.apiEndpoint}/feedback` | Endpoint used for sending feedback data. If not provided, it defaults to `${config.apiEndpoint}/feedback`. |
106
- | `hubspot.enabled` | `boolean` | `false` | Specifies whether the HubSpot integration is enabled. |
107
- | `hubspot.portalId` | `string` | `''` | The HubSpot portal ID for the integration. |
108
- | `hubspot.formGuid` | `string` | `''` | The GUID of the HubSpot form to be used. |
109
- | `hubspot.triggerKeywords` | `Array<string>` | `['pricing', 'demo', 'contact', 'quote', 'help', 'support']` | Keywords that trigger the HubSpot form display. |
110
- | `hubspot.formShownToUsers` | `Set` | `new Set()` | Tracks users who have been shown the HubSpot form. |
111
- | `hubspot.formSubmittedUsers` | `Set` | `new Set()` | Tracks users who have submitted the HubSpot form. |
112
- | `position` | `string` | `'bottom-right'` | Specifies the position of the HubSpot form on the screen. |
113
- | `enableFileUpload` | `boolean` | `true` | Show/hide file upload button. Set to `false` to disable file upload functionality. |
114
- | `enableDeleteButton` | `boolean` | `true` | Show/hide delete chat history button. Set to `false` to hide the delete button. |
115
- | `useMultipartFormData` | `boolean` | `true` | Use multipart form data for API calls. Required for file uploads and some API endpoints. |
116
- | `apiDataFormat` | `string` | `'json'` | API data format: `'json'` or `'form-data'`. Use `'form-data'` for multipart requests. |
117
- | `typingIndicatorColor` | `string` | `'#666'` | Color for the typing indicator dots. Use a single color for all 3 dots. |
118
- | `showTypingText` | `boolean` | `true` | Show/hide the "AI is thinking..." text below the typing indicator dots. |
119
- | `toggleButtonIcon` | `string` | `null` | Custom icon for the toggle button when closed. When open, shows a down arrow. Supports emoji, image URL, or SVG. |
120
- | `chatBackgroundImage` | `string` | `null` | Custom background image for the chat messages section. Supports image URLs. |
121
- | `chatBackgroundColor` | `string` | `'#ffffff'` | Custom background color for the chat messages section. Used when no image is set. Default: white. |
122
- | `sendButtonIconSize` | `number` | `24` | Size of the send button icon in pixels. Default: 24px. |
123
- | `enableEnhancedMobileInput` | `boolean` | `true` | Enhanced mobile input handling for better touch interaction and focus management. Default: true. |
124
- | `aiAvatar` | `string` | `null` | AI avatar for bot messages. Supports emoji, image URL, or SVG. Default: robot emoji (🤖). |
125
- | `showAiAvatar` | `boolean` | `true` | Show AI avatar in bot messages. Default: true. |
126
- | `botSubname` | `string` | `null` | Subname or descriptive text for the bot (displayed in chat header under bot name). Default: null. |
127
- | `showBotSubname` | `boolean` | `true` | Show bot subname in chat header. Default: true. |
128
- | `showFormOnStart` | `boolean` | `true` | Show HubSpot form when chat opens (instead of trigger words). Default: true. |
129
- | `useEmailAsUserId` | `boolean` | `true` | Use email from form as user ID. Default: true. |
130
- | `showBranding` | `boolean` | `true` | Show/hide the branding section below the chat input. Default: true. |
131
- | `brandingText` | `string` | `'Powered by NeuroBrain'` | Company name for branding. The widget will show "Powered by [Company]" where [Company] is extracted from this text (removing "Powered by" prefix if present). Company name will be bold and linked. |
132
- | `brandingUrl` | `string` | `'https://neurobrains.co/'` | URL that the branding text links to. Default: 'https://neurobrains.co/'. |
133
- | `showMessageActions` | `boolean` | `true` | Show/hide message action buttons (copy, like, dislike, regenerate) on AI responses. Default: true. |
134
- | `showTextBox` | `boolean` | `true` | Show/hide the floating text box above the toggle button. Default: true. |
135
- | `textBoxMessage` | `string` | `'Hi there! If you need any assistance, I am always here.'` | Main text message displayed in the floating text box above the toggle button. |
136
- | `textBoxSubMessage` | `string` | `'💬 24/7 Live Chat Support'` | Sub message displayed in the text box after the separator line. |
137
- | `showTextBoxCloseButton` | `boolean` | `true` | Show/hide the close button on the text box. Default: true. |
138
- | `toggleButtonAnimation` | `number` | `4` | Toggle button animation type: 0=none, 1=pulse, 2=bounce, 3=shake, 4=infinity(grow-shrink), 5=rotate. Default: 4 (infinity effect). |
139
- | `toggleButtonSize` | `number` | `60` | Toggle button size in pixels. Range: 40-80px. Default: 60px. |
140
- | `toggleButtonBottomMargin` | `number` | `50` | Bottom margin of toggle button in pixels. Range: 10-50px. Default: 50px. |
141
- | `toggleButtonRightMargin` | `number` | `30` | Right margin of toggle button in pixels. Range: 10-100px. Default: 30px. |
142
- | `websiteBottomSpacing` | `number` | `0` | Additional bottom spacing for website integration in pixels. Range: 0-100px. Default: 0px. |
143
- | `textBoxSpacingFromToggle` | `number` | `0` | Spacing between text box and toggle button in pixels. Range: 0-30px. Default: 0px (touching). |
144
- | `textBoxTextColor` | `string` | `'primary'` | Text color for text box content. Use 'primary' for primary color, 'default' for standard colors, or any CSS color value. |
145
-
146
-
147
-
148
- ### Key Features:
149
- - **Responsive Design**: Automatically adapts to different screen sizes and devices
150
- - **Smart Positioning**: Prevents text box cutoff with dynamic max-width calculations
151
- - **Z-Index Management**: Optimal layering for clean interface without overlapping elements
152
- - **Gradient Support**: Text box content supports CSS gradients when using gradient primary colors
153
- - **Click Outside to Close**: Chat window closes when clicking outside the widget
154
- - **Touch Positioning**: Text box can touch toggle button for seamless integration
155
-
156
- ## New Features (v2.5.0+)
157
-
158
- ### File Upload Support
159
- ChatNest now supports file uploads with the following capabilities:
160
- - **Supported Formats**: Images (JPG, PNG, GIF), PDFs, Word documents (DOC, DOCX), and text files (TXT)
161
- - **Multiple Files**: Select and upload multiple files simultaneously
162
- - **File Preview**: See selected files with size information before sending
163
- - **File Management**: Remove individual files from selection
164
- - **Configurable**: Enable/disable file upload functionality with `enableFileUpload` option
165
-
166
- ### Enhanced API Integration
167
- - **Multipart Form Data**: Full support for multipart/form-data format for file uploads
168
- - **422 Error Resolution**: Proper handling of API data format requirements to prevent 422 errors
169
- - **Flexible Data Format**: Choose between JSON and multipart form data with `apiDataFormat` option
170
- - **Request/Response Mapping**: Customize field names to match your API's expected format
171
-
172
- ### UI Improvements
173
- - **Black Action Icons**: Professional black 3-dot menu icons for better visibility
174
- - **Configurable Buttons**: Show/hide file upload and delete buttons as needed
175
- - **Better Error Handling**: Enhanced error messages and user feedback
176
- - **Fixed Typing Indicator**: Typing indicator now only shows when AI is actively processing, not on widget initialization
177
- - **Custom Toggle Button Icon**: Customize the opening chat window circle logo with emoji, image, or SVG
178
- - **Custom Chat Background**: Add custom background images or colors to the chat messages section for better branding and visual appeal
179
- - **AI Avatar System**: Customizable AI avatar with bot name display inside each bot message bubble, and optional subname in the header
180
- - **Customizable Send Button**: Adjust the size of the send button icon for better visibility and user experience
181
- - **Enhanced Mobile Input**: Improved mobile input handling with auto-focus, focus restoration, and better touch interaction
182
- - **HubSpot Form Integration**: Show form on chat open with Name, Email, Phone fields, save to HubSpot, and use email as user ID
183
- - **Typewriter Scroll Control**: Configure whether typewriter effect scrolls with text or remains static with `typewritewithscroll` option
184
- - **Auto Scroll to Bottom**: Chat window automatically scrolls to bottom when opened for better user experience
185
-
186
- ### Configuration Examples
187
-
188
- #### Basic Configuration Examples
189
- ```javascript
190
- // File upload with gradient text
191
- const chatWidget = new EasyChatWidget({
192
- enableFileUpload: true,
193
- showTextBox: true,
194
- textBoxTextColor: 'primary',
195
- primaryColor: 'linear-gradient(45deg, #2563eb, #9333ea)',
196
- apiEndpoint: 'https://your-api.com/chat'
43
+ ---
44
+
45
+ ## Configuration
46
+
47
+ ### Core
48
+
49
+ | Option | Type | Default | Description |
50
+ |--------|------|---------|-------------|
51
+ | `botName` | `string` | `'Chat Assistant'` | Name shown in the header |
52
+ | `botImage` | `string` | default avatar | Bot avatar URL |
53
+ | `botSubname` | `string` | `null` | Sub-label below the bot name |
54
+ | `showBotSubname` | `boolean` | `true` | Show/hide `botSubname` |
55
+ | `greeting` | `string` | `'Hello! How can I help you today?'` | Opening message |
56
+ | `placeholder` | `string` | `'Type your message here...'` | Input placeholder text |
57
+ | `primaryColor` | `string` | `'#0084ff'` | Accent color hex or CSS gradient |
58
+ | `fontSize` | `number\|string` | `14` | Message font size in px (14–25) |
59
+ | `width` | `string` | `'400px'` | Widget width (300–600px) |
60
+ | `height` | `string` | `'600px'` | Widget height (400–800px) |
61
+ | `position` | `string` | `'bottom-right'` | `bottom-right` `bottom-left` `bottom-center` `top-right` `top-left` |
62
+ | `theme` | `string` | `'light'` | `'light'` `'dark'` `'system'` |
63
+
64
+ ### API
65
+
66
+ | Option | Type | Default | Description |
67
+ |--------|------|---------|-------------|
68
+ | `apiEndpoint` | `string` | `'http://localhost:7000/chat'` | Chat endpoint URL |
69
+ | `apiKey` | `string` | `''` | Bearer token added to `Authorization` header |
70
+ | `apiHeaders` | `object` | `{ 'Content-Type': 'application/json' }` | Extra request headers |
71
+ | `apiMethod` | `string` | `'POST'` | HTTP method |
72
+ | `apiTimeout` | `number` | `30000` | Request timeout in ms |
73
+ | `apiRequestFormat` | `object` | `{ query, userId, domain }` | Map request field names to what your API expects |
74
+ | `apiResponseFormat` | `object` | `{ response, products, productItem }` | Map response field names from your API |
75
+ | `apiDataFormat` | `string` | `'json'` | `'json'` or `'form-data'` |
76
+ | `useMultipartFormData` | `boolean` | `true` | Use multipart encoding for file uploads |
77
+ | `userId` | `string\|function\|null` | `null` | Override the `user_id` sent on every API call. Pass a static string, a function `(userManager) => string`, or `null` to use the auto-generated ID. If `nativeForm.useEmailAsUserId` is `true` the submitted email takes over automatically after form submission. |
78
+ | `transformResponse` | `function` | `null` | Transform the raw API response before display |
79
+ | `productInjectionMarker` | `string\|array` | see below | Text marker(s) after which the product carousel is inserted |
80
+
81
+ ### Chat Behavior
82
+
83
+ | Option | Type | Default | Description |
84
+ |--------|------|---------|-------------|
85
+ | `enableHistory` | `boolean` | `true` | Persist chat in localStorage |
86
+ | `maxHistoryLength` | `number` | `100` | Max messages stored locally |
87
+ | `separateSubpageHistory` | `boolean` | `false` | Separate history per URL path |
88
+ | `enableMarkdown` | `boolean` | `true` | Render Markdown in bot replies |
89
+ | `enableTypewriter` | `boolean` | `true` | Typewriter animation for bot replies |
90
+ | `typewriterSpeed` | `object` | `{ min: 30, max: 70 }` | Typewriter speed range in ms per character |
91
+ | `typewritewithscroll` | `boolean` | `false` | Auto-scroll while typewriter is animating |
92
+ | `enableTypingIndicator` | `boolean` | `true` | Show "Thinking…" while waiting |
93
+ | `showTypingText` | `boolean` | `true` | Show text label next to typing dots |
94
+ | `typingIndicatorColor` | `string` | `'#666'` | Color of the typing dots |
95
+ | `showTimestamp` | `boolean` | `false` | Show time on each message |
96
+ | `chips` | `array` | `[]` | Suggestion chip buttons, e.g. `['Help', 'Pricing']` |
97
+
98
+ ### File Upload
99
+
100
+ | Option | Type | Default | Description |
101
+ |--------|------|---------|-------------|
102
+ | `enableFileUpload` | `boolean` | `true` | Enable file / image attachments |
103
+ | `fileAccept` | `string` | `'image/*,.pdf,.doc,.docx,.txt'` | Accepted MIME types or extensions |
104
+ | `maxFiles` | `number` | `null` | Max files per message (`null` = unlimited) |
105
+ | `enableEnhancedMobileInput` | `boolean` | `true` | Optimised input handling on mobile |
106
+
107
+ ### Backend History
108
+
109
+ | Option | Type | Default | Description |
110
+ |--------|------|---------|-------------|
111
+ | `enableBackendHistory` | `boolean` | `true` | Send conversation history to the API |
112
+ | `backendHistoryEndpoint` | `string` | `''` | Separate endpoint to fetch server-side history |
113
+ | `deleteEndpoint` | `string` | `{apiEndpoint}/delete-history` | Endpoint called when the user clears chat |
114
+ | `feedbackEndpoint` | `string` | `{apiEndpoint}/feedback` | Endpoint for like/dislike feedback |
115
+ | `enableServerHistoryDelete` | `boolean` | `false` | Call `deleteEndpoint` when erasing chat |
116
+
117
+ ### UI & Branding
118
+
119
+ | Option | Type | Default | Description |
120
+ |--------|------|---------|-------------|
121
+ | `showBranding` | `boolean` | `true` | "Powered by" footer link |
122
+ | `brandingText` | `string` | `'Powered by NeuroBrain'` | Footer brand label |
123
+ | `brandingUrl` | `string` | `'https://neurobrains.co/'` | Footer brand URL |
124
+ | `showMessageActions` | `boolean` | `true` | Like / dislike / copy / regenerate buttons |
125
+ | `enableDeleteButton` | `boolean` | `true` | Show clear-chat button in header |
126
+ | `aiAvatar` | `string` | `null` | URL, emoji, or inline SVG for the AI avatar |
127
+ | `showAiAvatar` | `boolean` | `true` | Show/hide the AI avatar next to messages |
128
+ | `chatBackgroundColor` | `string` | `'#ffffff'` | Chat panel background color |
129
+ | `chatBackgroundImage` | `string` | `null` | CSS background-image for the chat panel |
130
+ | `sendButtonIconSize` | `number` | `24` | Send button icon size in px |
131
+ | `showPrivacyNotice` | `boolean` | `true` | Show a small privacy notice below the input |
132
+ | `privacyNoticeText` | `string` | `'Messages may be stored to improve responses.'` | Privacy notice copy |
133
+
134
+ ### Toggle Button
135
+
136
+ | Option | Type | Default | Description |
137
+ |--------|------|---------|-------------|
138
+ | `toggleButtonIcon` | `string` | default chat icon | URL, emoji, or SVG for the toggle button |
139
+ | `toggleButtonSize` | `number` | `60` | Toggle button diameter in px (40–80) |
140
+ | `toggleButtonAnimation` | `number` | `4` | Animation style 0–5 (`0` = none) |
141
+ | `toggleButtonBottomMargin` | `number` | `50` | Distance from the bottom of the viewport in px |
142
+ | `toggleButtonRightMargin` | `number` | `30` | Distance from the right edge of the viewport in px |
143
+ | `websiteBottomSpacing` | `number` | `0` | Extra bottom spacing to avoid overlapping site elements |
144
+
145
+ ### Text Box Pop-up
146
+
147
+ The small speech-bubble pop-up that appears above the toggle button before the chat is opened.
148
+
149
+ | Option | Type | Default | Description |
150
+ |--------|------|---------|-------------|
151
+ | `showTextBox` | `boolean` | `true` | Show the pop-up text box |
152
+ | `textBoxMessage` | `string` | `'Hi there! If you need any assistance, I am always here.'` | Main message |
153
+ | `textBoxSubMessage` | `string` | `'24/7 Live Chat Support'` | Sub-message |
154
+ | `showTextBoxCloseButton` | `boolean` | `true` | Allow user to dismiss the pop-up |
155
+ | `textBoxTextColor` | `string` | `'primary'` | `'primary'` (uses `primaryColor`), `'default'`, or any hex |
156
+ | `textBoxSpacingFromToggle` | `number` | `0` | Gap between the pop-up and toggle button in px |
157
+
158
+ ### Native Lead Form
159
+
160
+ A fully built-in, no-dependency lead-capture form. Fields, labels, and validation are all customisable. Data is saved to `localStorage` and, optionally, the submitted email is used as the API `user_id` from that point on.
161
+
162
+ | Option | Type | Default | Description |
163
+ |--------|------|---------|-------------|
164
+ | `nativeForm.enabled` | `boolean` | `false` | Enable the native form |
165
+ | `nativeForm.trigger` | `string` | `'onOpen'` | When to show — `'onOpen'` (chat opens) or `'onFirstMessage'` (first send attempt) |
166
+ | `nativeForm.title` | `string` | `'Before we start'` | Modal heading |
167
+ | `nativeForm.subtitle` | `string` | `'Tell us a little about yourself.'` | Modal sub-heading |
168
+ | `nativeForm.submitLabel` | `string` | `'Start chatting'` | Submit button label |
169
+ | `nativeForm.useEmailAsUserId` | `boolean` | `true` | After submission, set the email field value as the persistent API `user_id` |
170
+ | `nativeForm.storageKey` | `string\|null` | `null` | localStorage key prefix. `null` → auto (`cnf_<hostname>`) |
171
+ | `nativeForm.fields` | `array` | name + email + phone | Array of field descriptors — see table below |
172
+ | `nativeForm.onSubmit` | `async function\|null` | `null` | Optional async callback `(formData) => void\|false`. Return `false` to block submission. |
173
+
174
+ **Field descriptor shape**
175
+
176
+ | Key | Type | Required | Description |
177
+ |-----|------|----------|-------------|
178
+ | `name` | `string` | yes | Field key, also used as the `localStorage` data property |
179
+ | `label` | `string` | yes | Label shown above the input |
180
+ | `type` | `string` | no | HTML input type — `'text'` `'email'` `'tel'` `'number'` etc. Default `'text'` |
181
+ | `required` | `boolean` | no | Mark field as required. Default `false` |
182
+ | `placeholder` | `string` | no | Input placeholder text |
183
+ | `validate` | `function` | no | Custom validator `(value: string) => errorMessage \| ''`. Overrides built-in type checks. |
184
+
185
+ **localStorage keys written on submit**
186
+
187
+ | Key | Value |
188
+ |-----|-------|
189
+ | `cnf_<hostname>_submitted` | `"true"` |
190
+ | `cnf_<hostname>_data` | JSON — all field values + `submittedAt` ISO timestamp |
191
+
192
+ ### HubSpot Lead Form
193
+
194
+ Displays a lead-capture form before or during chat. Requires HubSpot portal credentials.
195
+
196
+ | Option | Type | Default | Description |
197
+ |--------|------|---------|-------------|
198
+ | `hubspot.enabled` | `boolean` | `false` | Enable HubSpot form integration |
199
+ | `hubspot.portalId` | `string` | `''` | HubSpot portal ID |
200
+ | `hubspot.formGuid` | `string` | `''` | HubSpot form GUID |
201
+ | `hubspot.triggerKeywords` | `array` | `['pricing','demo','contact','quote','help','support']` | Keywords that trigger the form |
202
+ | `showFormOnStart` | `boolean` | `true` | Show form when chat opens for new users |
203
+ | `useEmailAsUserId` | `boolean` | `true` | Use submitted email as the persistent user ID (HubSpot form only) |
204
+ | `formTitle` | `string` | `'Give Your Details'` | Form modal title |
205
+ | `formSubtitle` | `string` | `'Please provide your information to start chatting.'` | Form modal subtitle |
206
+
207
+ ### Supabase Chat History
208
+
209
+ Persist chat history in Supabase so sessions survive across devices and browsers.
210
+
211
+ | Option | Type | Default | Description |
212
+ |--------|------|---------|-------------|
213
+ | `supabase.enabled` | `boolean` | `false` | Enable Supabase persistence |
214
+ | `supabase.url` | `string` | `''` | Supabase project URL |
215
+ | `supabase.anonKey` | `string` | `''` | Supabase anon/public API key |
216
+ | `supabase.tableName` | `string` | `'chat_history'` | Table to store messages |
217
+ | `supabase.historyLimit` | `number` | `50` | Max rows to load on widget open |
218
+ | `supabase.pollIntervalMs` | `number` | `5000` | Background refresh interval (ms); Realtime gives instant delivery |
219
+
220
+ ### Parlant Integration
221
+
222
+ | Option | Type | Default | Description |
223
+ |--------|------|---------|-------------|
224
+ | `parlant.enabled` | `boolean` | `false` | Enable Parlant agent integration |
225
+ | `parlant.apiBaseUrl` | `string` | `''` | Parlant API base URL |
226
+
227
+ ### Callbacks
228
+
229
+ | Option | Type | Description |
230
+ |--------|------|-------------|
231
+ | `onInit` | `function` | Called when the widget is ready |
232
+ | `onMessage` | `function` | Called on every message send / receive |
233
+ | `onError` | `function` | Called on API errors |
234
+
235
+ ---
236
+
237
+ ## Native Lead Form
238
+
239
+ Capture user details before or during chat — no HubSpot account needed. All data stays in the user's browser.
240
+
241
+ ### Minimal setup
242
+
243
+ ```js
244
+ new Chatnest({
245
+ apiEndpoint: 'https://your-api.com/chat',
246
+ nativeForm: {
247
+ enabled: true
248
+ }
197
249
  });
250
+ ```
198
251
 
199
- // Custom branding with gradient
200
- const chatWidget = new EasyChatWidget({
201
- showBranding: true,
202
- brandingText: 'Your Company',
203
- brandingUrl: 'https://yourcompany.com',
204
- primaryColor: 'linear-gradient(to right, #2563eb, #9333ea)',
205
- apiEndpoint: 'https://your-api.com/chat'
252
+ Shows a name + email + phone form when the chat opens. After submission the email becomes the persistent `user_id` on every API request.
253
+
254
+ ### Custom fields
255
+
256
+ ```js
257
+ new Chatnest({
258
+ apiEndpoint: 'https://your-api.com/chat',
259
+ nativeForm: {
260
+ enabled: true,
261
+ trigger: 'onFirstMessage', // intercept first send attempt
262
+ title: 'Quick intro',
263
+ subtitle: 'We use this to personalise your experience.',
264
+ submitLabel: 'Let\'s go',
265
+ fields: [
266
+ { name: 'fullname', label: 'Your name', type: 'text', required: true },
267
+ { name: 'email', label: 'Work email', type: 'email', required: true },
268
+ { name: 'company', label: 'Company', type: 'text', required: false,
269
+ validate: (v) => v.length >= 2 ? '' : 'Enter your company name.' }
270
+ ]
271
+ }
206
272
  });
273
+ ```
207
274
 
208
- // Text box with perfect positioning
209
- const chatWidget = new EasyChatWidget({
210
- showTextBox: true,
211
- textBoxMessage: 'Need help? We\'re here!',
212
- textBoxSubMessage: '💬 24/7 Support',
213
- toggleButtonBottomMargin: 50,
214
- textBoxSpacingFromToggle: 0, // Touching
215
- apiEndpoint: 'https://your-api.com/chat'
275
+ ### Custom submit hook
276
+
277
+ ```js
278
+ new Chatnest({
279
+ nativeForm: {
280
+ enabled: true,
281
+ onSubmit: async (formData) => {
282
+ // formData = { fullname, email, company, submittedAt }
283
+ const res = await fetch('/api/leads', {
284
+ method: 'POST',
285
+ headers: { 'Content-Type': 'application/json' },
286
+ body: JSON.stringify(formData)
287
+ });
288
+ if (!res.ok) return false; // returning false shows an error and keeps the form open
289
+ }
290
+ }
216
291
  });
217
292
  ```
218
293
 
219
- ## Complete Example
220
-
221
- ```javascript
222
- document.addEventListener('DOMContentLoaded', () => {
223
- const chatWidget = new EasyChatWidget({
224
- // Basic configuration
225
- botName: 'Customer Support Bot',
226
- greeting: 'Welcome! How can we assist you?',
227
- primaryColor: 'linear-gradient(45deg, #2563eb, #9333ea)',
228
-
229
- // Text box with gradient support
230
- showTextBox: true,
231
- textBoxMessage: 'Need help? We\'re here!',
232
- textBoxSubMessage: '💬 24/7 Support',
233
- textBoxTextColor: 'primary',
234
-
235
- // Perfect positioning
236
- toggleButtonBottomMargin: 50,
237
- textBoxSpacingFromToggle: 0,
238
-
239
- // API configuration
240
- apiEndpoint: 'https://your-api.com/chat',
241
- enableFileUpload: true,
242
-
243
- // Callbacks
244
- onInit: () => console.log('Chat widget initialized'),
245
- onMessage: (message) => console.log('Message received:', message),
246
- onError: (error) => console.error('An error occurred:', error),
247
- });
294
+ ### Reading stored data in your own code
295
+
296
+ ```js
297
+ // Check if the user already submitted
298
+ const submitted = localStorage.getItem('cnf_yourdomain.com_submitted') === 'true';
299
+
300
+ // Read field values
301
+ const data = JSON.parse(localStorage.getItem('cnf_yourdomain.com_data') || 'null');
302
+ // { fullname: 'Jane Doe', email: 'jane@co.com', submittedAt: '2025-04-03T...' }
303
+ ```
304
+
305
+ ---
306
+
307
+ ## User ID Control
308
+
309
+ By default ChatNest auto-generates a random `user_id` per browser and persists it in `localStorage`. You can override this at any level of precision:
310
+
311
+ ```js
312
+ // 1. Static — same ID for every visitor (useful for authenticated apps)
313
+ new Chatnest({ userId: 'user_42' });
314
+
315
+ // 2. Dynamic — evaluated on every API request
316
+ new Chatnest({
317
+ userId: (userManager) => {
318
+ // userManager.currentUser is the auto-generated or email-derived ID
319
+ return window.__myApp?.loggedInUserId || userManager.currentUser;
320
+ }
321
+ });
322
+
323
+ // 3. Email from nativeForm — no extra config needed
324
+ // When nativeForm.useEmailAsUserId is true (the default),
325
+ // the email the user submits automatically becomes userManager.currentUser
326
+ // and is used on all subsequent requests.
327
+ new Chatnest({
328
+ nativeForm: { enabled: true, useEmailAsUserId: true }
248
329
  });
249
330
  ```
250
331
 
251
- ## Dependencies
332
+ **Resolution order on each API call:**
333
+ 1. `config.userId` (string or function), if set
334
+ 2. `userManager.currentUser` — which is the submitted email after `nativeForm` or `hubspot` form submission (when `useEmailAsUserId: true`)
335
+ 3. Auto-generated `user_<domain><timestamp>_<random>` persisted in `localStorage`
252
336
 
253
- If you enable Markdown rendering (`enableMarkdown: true`), the widget will load [Marked.js](https://cdn.jsdelivr.net/npm/marked@14.1.3/lib/marked.umd.min.js) from a CDN by default.
337
+ ---
254
338
 
255
- ## Look of the chat widget
339
+ ## Supabase Setup
256
340
 
257
- ![ChatNest](https://i.ibb.co.com/HPJ7WVL/Screenshot-2024-11-06-090205.png)
341
+ ### 1. Create the table
258
342
 
259
- ## Troubleshooting
343
+ ```sql
344
+ CREATE TABLE IF NOT EXISTS chat_history (
345
+ id BIGSERIAL PRIMARY KEY,
346
+ user_id TEXT NOT NULL,
347
+ domain TEXT NOT NULL,
348
+ query TEXT NOT NULL,
349
+ response TEXT NOT NULL,
350
+ timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
351
+ );
260
352
 
261
- ### 422 Error (Unprocessable Entity)
262
- This usually occurs when the API expects different data format. Try:
353
+ CREATE INDEX IF NOT EXISTS idx_chat_history_user_domain ON chat_history (user_id, domain);
354
+ CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON chat_history (timestamp DESC);
263
355
 
264
- 1. Set `useMultipartFormData: true` for file uploads
265
- 2. Set `apiDataFormat: 'form-data'` for multipart requests
266
- 3. Check your `apiRequestFormat` mapping matches your API expectations
356
+ ALTER TABLE chat_history ENABLE ROW LEVEL SECURITY;
357
+ CREATE POLICY "chat_history_open" ON chat_history FOR ALL USING (true) WITH CHECK (true);
267
358
 
268
- ### File Upload Issues
269
- 1. Ensure `enableFileUpload: true`
270
- 2. Set `useMultipartFormData: true`
271
- 3. Set `apiDataFormat: 'form-data'`
272
- 4. Check file size limits on your server
359
+ -- Enable Realtime for instant Messenger-like delivery (optional but recommended)
360
+ ALTER PUBLICATION supabase_realtime ADD TABLE chat_history;
361
+ ```
273
362
 
274
- ### API Connection Issues
275
- 1. Verify `apiEndpoint` URL is correct
276
- 2. Check CORS settings on your server
277
- 3. Ensure `apiKey` is valid (if required)
278
- 4. Check network connectivity
363
+ ### 2. Configure
364
+
365
+ ```js
366
+ new Chatnest({
367
+ apiEndpoint: 'https://your-api.com/chat',
368
+ supabase: {
369
+ enabled: true,
370
+ url: 'https://xxxxxxxxxxxx.supabase.co',
371
+ anonKey: 'your-anon-key',
372
+ tableName: 'chat_history', // optional
373
+ historyLimit: 50 // optional
374
+ }
375
+ });
376
+ ```
279
377
 
280
- ### Common Configuration Fixes
378
+ > Find `url` and `anonKey` in **Supabase → Project Settings → API**.
281
379
 
282
- #### For APIs expecting multipart form data:
283
- ```javascript
284
- {
285
- useMultipartFormData: true,
286
- apiDataFormat: 'form-data',
287
- apiRequestFormat: {
288
- query: 'message', // Match your API's field name
289
- userId: 'user_id',
290
- domain: 'domain'
380
+ **Real-time sync** The widget polls for new rows every 3 seconds. When a human agent or backend adds a reply to `chat_history`, it appears live, like Messenger. Tune with `supabase.pollIntervalMs`.
381
+
382
+ **Multi-part responses (`,,,`)** — If your API returns multiple replies concatenated with three commas, ChatNest splits them into separate messages:
383
+ `"Hello!,,,How can I help?"` → two bot messages.
384
+
385
+ ---
386
+
387
+ ## Product Carousel
388
+
389
+ When your API returns a `products` array, ChatNest renders product cards with image, name, price, highlights, and a CTA button.
390
+
391
+ ```js
392
+ new Chatnest({
393
+ apiEndpoint: 'https://your-api.com/chat',
394
+ productInjectionMarker: 'Here are some recommendations:',
395
+ apiResponseFormat: {
396
+ response: 'response',
397
+ products: 'products',
398
+ productItem: {
399
+ name: 'name',
400
+ price: 'price',
401
+ image: 'image_url',
402
+ link: 'buy_link',
403
+ highlights: 'highlights',
404
+ ctaText: 'Buy now'
291
405
  }
292
- }
406
+ }
407
+ });
293
408
  ```
294
409
 
295
- #### For APIs expecting JSON:
296
- ```javascript
410
+ Expected API response shape:
411
+ ```json
297
412
  {
298
- useMultipartFormData: false,
299
- apiDataFormat: 'json',
300
- apiRequestFormat: {
301
- query: 'message',
302
- userId: 'user_id',
303
- domain: 'domain'
304
- }
413
+ "response": "Here are some recommendations:\n\n",
414
+ "products": [
415
+ { "name": "Product A", "price": "$29", "image_url": "...", "buy_link": "...", "highlights": "Lightweight" }
416
+ ]
305
417
  }
306
418
  ```
419
+
420
+ ---
421
+
422
+ ## File Upload
423
+
424
+ ```js
425
+ new Chatnest({
426
+ apiEndpoint: 'https://your-api.com/chat',
427
+ enableFileUpload: true,
428
+ useMultipartFormData: true,
429
+ apiDataFormat: 'form-data',
430
+ fileAccept: 'image/*',
431
+ maxFiles: 1
432
+ });
433
+ ```
434
+
435
+ Single file → sent as `image` field. Multiple files → `file_0`, `file_1`, etc.
436
+
437
+ ---
438
+
439
+ ## Troubleshooting
440
+
441
+ **Widget not loading**
442
+ Wrap init in `DOMContentLoaded`. Load the script before your init code.
443
+
444
+ **422 error from API**
445
+ Your API expects different field names:
446
+ ```js
447
+ apiRequestFormat: { query: 'message', userId: 'user_id', domain: 'domain' }
448
+ ```
449
+
450
+ **Products not showing**
451
+ Ensure your API returns a `products` array and `productInjectionMarker` matches text in the `response` field.
452
+
453
+ **Supabase history not loading**
454
+ - Confirm `supabase.enabled: true` and credentials are correct
455
+ - Check RLS policies allow reads with the anon key
456
+ - Check browser console for `[Supabase]` error messages
457
+
458
+ ---
459
+
460
+ ## License
461
+
462
+ MIT © [Sifat Hasan](https://github.com/Pro-Sifat-Hasan)