@data-netmonk/mona-chat-widget 2.5.1 → 2.6.0

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,760 +1,822 @@
1
- # Mona Chat Widget
2
-
3
- Chat widget package developed by Netmonk data & solution team to be imported in Netmonk products
4
-
5
- ---
6
-
7
- ### Recent Updates & Breaking Changes
8
-
9
- ---
10
-
11
- **Latest Version Changes:**
12
-
13
- ⚠️ **Breaking Changes:**
14
- 1. **Removed `type` and `agentType` props** - These parameters are no longer used and have been removed from all components
15
- 2. **Renamed `botServerUrl` to `webhookUrl`** - For better clarity and consistency
16
- 3. **`webhookUrl` is now required** - Must be provided as a prop
17
- 4. **`authUrl` and `username` are now direct props** - No longer part of `data` prop for better clarity and type safety
18
- 5. **`userId` is now optional** - Widget automatically generates visitor ID for guest users via browser fingerprinting when `userId` is not provided
19
-
20
- **New Features:**
21
- 1. **Guest user support** - Users can chat without logging in
22
- - Automatic visitor ID generation using browser fingerprinting (FingerprintJS + SHA256)
23
- - `auth: false` flag automatically added to API requests for guest users
24
- - Persistent sessions across page reloads for anonymous visitors
25
- 2. **Authentication support** - Automatic token management with refresh on 401 errors
26
- - Pass `authUrl` as a direct prop
27
- - Widget handles token lifecycle automatically
28
- 3. **Enhanced user authentication handling** - Smart detection of authenticated vs guest users
29
- - Compares `userId` with visitor ID to determine authentication status
30
- - Automatic `auth` flag management in all API requests
31
- 4. **Enhanced data prop** - Support for custom variables passed to backend via `data` prop
32
- 5. **Improved error handling** - Better fallback mechanisms and error messages
33
- 6. **Direct `username` prop** - Pass username as a top-level prop instead of in data string
34
-
35
- 📝 **Migration Guide:**
36
- ```jsx
37
- // Old usage (deprecated)
38
- <ChatWidget
39
- userId="user123"
40
- sourceId="source456"
41
- type="prime"
42
- botServerUrl="https://api.example.com"
43
- />
44
-
45
- // Previous version (with data prop)
46
- <ChatWidget
47
- userId="user123"
48
- sourceId="source456"
49
- webhookUrl="https://api.example.com/webhook"
50
- data="authUrl=https://api.example.com/login/chatwidget~username=John"
51
- />
52
-
53
- // New usage - Authenticated user (current - recommended)
54
- <ChatWidget
55
- userId="user123"
56
- sourceId="source456"
57
- webhookUrl="https://api.example.com/webhook"
58
- authUrl="https://api.example.com/login/chatwidget"
59
- username="John"
60
- data="email=john@example.com~phone=+1234567890"
61
- />
62
-
63
- // New usage - Guest user (without login)
64
- <ChatWidget
65
- sourceId="source456"
66
- webhookUrl="https://api.example.com/webhook"
67
- username="Guest"
68
- />
69
- // Widget automatically generates visitor ID and adds auth: false flag
70
-
71
- // New usage - Conditional (handles both logged-in and guest users)
72
- <ChatWidget
73
- userId={currentUser?.id} // undefined for guests
74
- sourceId="source456"
75
- webhookUrl="https://api.example.com/webhook"
76
- username={currentUser?.name || "Guest"}
77
- />
78
- ```
79
-
80
- ---
81
-
82
- ## 🚅 Quick start
83
-
84
- ### Prerequisites
85
-
86
- ---
87
-
88
- 1. Install dependencies
89
- ```
90
- npm install --legacy-peer-deps
91
- ```
92
- 2. Copy .env.example
93
- ```
94
- cp .env.example .env
95
- ```
96
- 3. Populate .env
97
- 4. Enable mock mode (optional)
98
-
99
- To test the chat widget without a backend server, set `VITE_USE_MOCK_RESPONSES=true` in your `.env` file. The widget will respond to messages like:
100
- - "start", "hello", "hi", "halo" - Greeting messages
101
- - "help", "bantuan" - Help information
102
- - "terima kasih", "thank you" - Acknowledgments
103
- - "bye", "goodbye" - Farewell messages
104
- - And more! Check `src/components/ChatWidget/utils/helpers.js` for full list
105
-
106
- ---
107
-
108
- ### Mock Mode (Demo without Backend)
109
-
110
- ---
111
-
112
- The chat widget includes a built-in mock mode for testing and demonstrations without requiring a backend server.
113
-
114
- **To enable mock mode:**
115
- 1. Set `VITE_USE_MOCK_RESPONSES=true` in your `.env` file
116
- 2. Run the app normally with `npm run dev`
117
-
118
- **Mock responses include:**
119
- - Greetings (hello, hi, halo, start) - with interactive buttons
120
- - Help commands
121
- - Device list with clickable buttons (type "devices" or "show devices")
122
- - Thank you acknowledgments
123
- - Farewells
124
- - Time-based greetings (good morning, etc.)
125
- - And automatically falls back to mock mode if backend fails
126
-
127
- **Interactive Buttons Demo:**
128
- Type these messages to see button responses:
129
- - "start" - Welcome message with action buttons
130
- - "show devices" or "devices" - List of devices as clickable buttons
131
- - Click any button to trigger the next action
132
-
133
- **To add custom mock responses:**
134
- Edit the `mockBotResponses` object in `src/components/ChatWidget/utils/mockBotResponses.js`
135
-
136
- For text-only responses:
137
- ```javascript
138
- "trigger": "Response text"
139
- ```
140
-
141
- For responses with buttons:
142
- ```javascript
143
- "trigger": {
144
- text: "Your message here",
145
- buttons: [
146
- { title: "Button 1", payload: "action_1" },
147
- { title: "Button 2", payload: "action_2" },
148
- { title: "Link Button", url: "https://example.com" }
149
- ]
150
- }
151
- ```
152
-
153
- ---
154
-
155
- ### Storybook
156
-
157
- ---
158
-
159
- 1. **How to run Storybook locally** (access at http://localhost:5177)
160
-
161
- ```
162
- npm run storybook
163
- ```
164
-
165
- 2. **How to build Storybook**
166
-
167
- ```
168
- npm run build-storybook
169
- ```
170
-
171
- 3. **How to serve Storybook**
172
-
173
- ```
174
- npm run serve-storybook
175
- ```
176
-
177
- ---
178
-
179
- ### Library (how to update and publish)
180
-
181
- ---
182
-
183
- 1. **Commit changes**
184
- ```
185
- git add .
186
- git commit -m "Your commit message"
187
- ```
188
- 2. **Update version**
189
-
190
- ```bash
191
- npm version patch # for bug fixes (1.0.0 -> 1.0.1)
192
- ```
193
-
194
- ```bash
195
- npm version minor # for new features (1.0.0 -> 1.1.0)
196
- ```
197
-
198
- ```bash
199
- npm version major # for breaking changes (1.0.0 -> 2.0.0)
200
- ```
201
-
202
- 3. **Build as a library** (build file at `/dist` directory)
203
-
204
- ```
205
- npm run build
206
- ```
207
-
208
- 4. **Copy declaration file to `/dist`**
209
-
210
- ```
211
- cp ./src/declarations/index.d.ts ./dist/index.d.ts
212
- ```
213
-
214
- 5. **Publish**
215
-
216
- ```
217
- npm publish
218
- ```
219
-
220
- ---
221
-
222
- ### Library (how to import on your project)
223
-
224
- ---
225
-
226
- 1. **Install package**
227
- ```bash
228
- npm install @data-netmonk/mona-chat-widget
229
- ```
230
-
231
- 2. **Import styles on your `App.jsx` or `index.jsx`**
232
-
233
- ```jsx
234
- import "@data-netmonk/mona-chat-widget/dist/style.css";
235
- ```
236
-
237
- 3. **Import & use component**
238
-
239
- ```jsx
240
- import { ChatWidget } from "@data-netmonk/mona-chat-widget";
241
-
242
- function App() {
243
- return (
244
- <ChatWidget
245
- userId="user123"
246
- sourceId="691e1b5952068ff7aaeccffc9"
247
- webhookUrl="https://your-backend-url.com"
248
- />
249
- );
250
- }
251
- ```
252
-
253
- ---
254
-
255
- ### Component Props
256
-
257
- ---
258
-
259
- #### Required Props
260
-
261
- | Prop | Type | Description |
262
- |------|------|-------------|
263
- | `sourceId` | `string` | **Required.** Source/channel identifier for the chat |
264
- | `webhookUrl` | `string` | **Required.** Backend webhook URL |
265
-
266
- #### Optional Props
267
-
268
- | Prop | Type | Default | Description |
269
- |------|------|---------|-------------|
270
- | `userId` | `string` | Generated visitor ID | Unique identifier for the user. **Optional** - if not provided, a unique visitor ID is automatically generated using browser fingerprinting for guest users |
271
- | `authUrl` | `string` | - | Authentication endpoint URL for token-based authentication |
272
- | `username` | `string` | - | Username for the session (sent to backend in variables) |
273
- | `data` | `string` | - | Additional custom variables in format `key1=value1~key2=value2` |
274
- | `width` | `string` | `"25vw"` | Widget width (CSS value) |
275
- | `height` | `string` | `"90vh"` | Widget height (CSS value) |
276
- | `right` | `string` | `"1.25rem"` | Distance from right edge |
277
- | `bottom` | `string` | `"1.25rem"` | Distance from bottom edge |
278
- | `zIndex` | `number` | `2000` | CSS z-index for widget positioning |
279
- | `position` | `string` | `"fixed"` | CSS position (`"fixed"` or `"relative"`) |
280
- | `onToggle` | `function` | - | Callback when widget opens/closes: `(isOpen: boolean) => void` |
281
-
282
- ---
283
-
284
- ### Guest User Support
285
-
286
- ---
287
-
288
- The widget now supports **guest users** (users who haven't logged in or before logging in). When `userId` is not provided, the widget automatically generates a unique visitor ID using browser fingerprinting.
289
-
290
- **How it works:**
291
-
292
- 1. **Browser Fingerprinting**: Uses FingerprintJS to generate a unique identifier based on:
293
- - Browser characteristics (user agent, screen resolution, timezone, etc.)
294
- - Incognito/private browsing detection
295
- - Combined into a SHA256 hash for consistency
296
-
297
- 2. **Automatic Guest Detection**: The widget automatically detects guest users and:
298
- - Generates a visitor ID if `userId` is not provided
299
- - Adds `auth: false` flag to all API requests for guest users
300
- - Uses the visitor ID as the effective user ID throughout the session
301
-
302
- 3. **Persistent Sessions**: The visitor ID remains consistent across page reloads (unless browser fingerprint changes or user clears data)
303
-
304
- **When to use guest mode:**
305
- - Public-facing websites where users can chat without logging in
306
- - Support widgets for anonymous visitors
307
- - Pre-login customer service interactions
308
- - Any scenario where user authentication is optional
309
-
310
- **When to provide userId:**
311
- - Users who are logged into your application
312
- - When you need to track chat history across devices
313
- - When authentication is required for personalized responses
314
- - Enterprise or internal applications
315
-
316
- ---
317
-
318
- ### Usage Examples
319
-
320
- ---
321
-
322
- #### Basic Usage (Authenticated User)
323
-
324
- ```jsx
325
- import { ChatWidget } from "@data-netmonk/mona-chat-widget";
326
- import "@data-netmonk/mona-chat-widget/dist/style.css";
327
-
328
- function App() {
329
- return (
330
- <ChatWidget
331
- userId="user123"
332
- sourceId="691e1b5952068ff7aaeccffc9"
333
- webhookUrl="https://api.example.com/webhook"
334
- />
335
- );
336
- }
337
- ```
338
-
339
- #### Guest User (Without Login)
340
-
341
- For anonymous visitors or users who haven't logged in:
342
-
343
- ```jsx
344
- import { ChatWidget } from "@data-netmonk/mona-chat-widget";
345
- import "@data-netmonk/mona-chat-widget/dist/style.css";
346
-
347
- function App() {
348
- return (
349
- <ChatWidget
350
- sourceId="691e1b5952068ff7aaeccffc9"
351
- webhookUrl="https://api.example.com/webhook"
352
- />
353
- );
354
- }
355
- ```
356
-
357
- **What happens:**
358
- - Widget automatically generates a visitor ID using browser fingerprinting
359
- - All API requests include `auth: false` in variables to indicate guest user
360
- - No login required - users can start chatting immediately
361
-
362
- #### Conditional userId (Logged in or Guest)
363
-
364
- Handle both logged-in users and guests dynamically:
365
-
366
- ```jsx
367
- import { ChatWidget } from "@data-netmonk/mona-chat-widget";
368
- import "@data-netmonk/mona-chat-widget/dist/style.css";
369
-
370
- function App() {
371
- const currentUser = getCurrentUser(); // Your auth function
372
-
373
- return (
374
- <ChatWidget
375
- userId={currentUser?.id} // Provide userId if logged in, undefined if not
376
- sourceId="691e1b5952068ff7aaeccffc9"
377
- webhookUrl="https://api.example.com/webhook"
378
- username={currentUser?.name}
379
- />
380
- );
381
- }
382
- ```
383
-
384
- **Behavior:**
385
- - If `currentUser.id` exists → Uses provided userId (authenticated user)
386
- - If `currentUser.id` is `null`/`undefined` → Generates visitor ID (guest user)
387
- - Backend receives `auth: false` flag only for guest users
388
-
389
- #### With Custom Variables
390
-
391
- Pass custom user data like email, phone number, etc. to the backend:
392
-
393
- ```jsx
394
- <ChatWidget
395
- userId="user123"
396
- sourceId="691e1b5952068ff7aaeccffc9"
397
- webhookUrl="https://api.example.com/webhook"
398
- username="John Doe"
399
- data="telephone_number=+628123456789~email=john@example.com"
400
- />
401
- ```
402
-
403
- **Variables sent to backend:**
404
- ```json
405
- {
406
- "chat_id": "...",
407
- "session_id": "...",
408
- "user_id": "user123",
409
- "message": "Hello",
410
- "type": "text",
411
- "variables": {
412
- "username": "John Doe",
413
- "telephone_number": "+628123456789",
414
- "email": "john@example.com"
415
- }
416
- }
417
- ```
418
- }
419
- ```
420
- #### With Authentication (NEW!)
421
-
422
- The widget supports automatic authentication with token refresh on expiry:
423
-
424
- ```jsx
425
- <ChatWidget
426
- userId="user123"
427
- sourceId="691e1b5952068ff7aaeccffc9"
428
- webhookUrl="https://api.example.com/webhook"
429
- authUrl="https://api.example.com/login/chatwidget"
430
- username="John Doe"
431
- />
432
- ```
433
-
434
- **How authentication works:**
435
-
436
- 1. **Initial Authentication**: When the widget loads (on Launcher mount), if `authUrl` is provided as a prop, it automatically calls the auth API:
437
- ```
438
- POST {authUrl}
439
- Body: { "user_id": "user123" }
440
- Response: { "token": "eyJ..." }
441
- ```
442
-
443
- 2. **Session Initialization**: After getting the token, the widget calls the init endpoint to establish the session:
444
- ```
445
- POST {webhookUrl}/{sourceId}/init
446
- Body: {
447
- "session_id": "...",
448
- "user_id": "user123",
449
- "token": "eyJ...",
450
- "username": "John Doe"
451
- }
452
- ```
453
-
454
- 3. **Automatic Token Refresh**: If the webhook returns **401 Unauthorized** (token expired/revoked), the widget automatically:
455
- - Calls the `authUrl` again to get a fresh token
456
- - Re-initializes the session with the new token
457
- - Updates the `authToken` in variables
458
- - Retries the failed request with the new token
459
- - This happens transparently without user interaction
460
-
461
- **Combined example with auth and custom variables:**
462
- ```jsx
463
- <ChatWidget
464
- userId="user123"
465
- sourceId="691e1b5952068ff7aaeccffc9"
466
- webhookUrl="https://api.example.com/webhook"
467
- authUrl="https://api.example.com/login/chatwidget"
468
- username="John"
469
- data="email=john@example.com~phone=+628123456789"
470
- />
471
- ```
472
-
473
- **Auth Flag (`auth` variable):**
474
- The widget automatically adds an `auth: false` flag to the `variables` object when the user is a guest (not authenticated):
475
- - When `userId === visitorId` (browser fingerprint), the widget adds `auth: false` to variables
476
- - When `userId !== visitorId` (authenticated user), no `auth` flag is added to variables
477
-
478
- **Guest user example** (userId equals browser fingerprint):
479
- ```json
480
- {
481
- "chat_id": "...",
482
- "session_id": "...",
483
- "user_id": "visitor_abc123",
484
- "message": "Hello",
485
- "type": "text",
486
- "variables": {
487
- "username": "Guest",
488
- "auth": false
489
- }
490
- }
491
- ```
492
-
493
- **Authenticated user example** (userId is different from browser fingerprint):
494
- ```json
495
- {
496
- "chat_id": "...",
497
- "session_id": "...",
498
- "user_id": "user123",
499
- "message": "Hello",
500
- "type": "text",
501
- "variables": {
502
- "username": "John Doe",
503
- "email": "john@example.com"
504
- }
505
- }
506
- ```
507
-
508
- This `auth: false` flag is automatically added in:
509
- - Session initialization payload (when guest)
510
- - All message requests (when guest)
511
- - Button postback requests (when guest)
512
-
513
- **Note:** The `data` prop is for additional custom variables only. Required parameters (`userId`, `sourceId`, `webhookUrl`) and common optional parameters (`authUrl`, `username`) should be passed as direct props for better type safety and clarity.
514
-
515
- #### Custom Styling
516
-
517
- ```jsx
518
- <ChatWidget
519
- userId="user123" // Optional
520
- sourceId="691e1b5952068ff7aaeccffc9"
521
- webhookUrl="https://api.example.com/webhook"
522
- width="400px"
523
- height="600px"
524
- right="20px"
525
- bottom="20px"
526
- zIndex={9999}
527
- />
528
- ```
529
-
530
- #### Embedded in Layout (Relative Positioning)
531
-
532
- ```jsx
533
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 400px' }}>
534
- <div>Main content</div>
535
- <ChatWidget
536
- userId="user123" // Optional
537
- sourceId="691e1b5952068ff7aaeccffc9"
538
- webhookUrl="https://api.example.com/webhook"
539
- position="relative"
540
- width="100%"
541
- height="100vh"
542
- />
543
- </div>
544
- ```
545
-
546
- #### With Toggle Callback
547
-
548
- ```jsx
549
- function App() {
550
- const handleToggle = (isOpen) => {
551
- console.log('Chat widget is', isOpen ? 'open' : 'closed');
552
- // Track analytics, update UI, etc.
553
- };
554
-
555
- return (
556
- <ChatWidget
557
- userId="user123" // Optional
558
- sourceId="691e1b5952068ff7aaeccffc9"
559
- webhookUrl="https://api.example.com/webhook"
560
- onToggle={handleToggle}
561
- />
562
- );
563
- }
564
- ```
565
-
566
- #### Full-Screen Widget
567
-
568
- ```jsx
569
- <ChatWidget
570
- userId="user123" // Optional - supports guest users
571
- sourceId="691e1b5952068ff7aaeccffc9"
572
- webhookUrl="https://api.example.com/webhook"
573
- width="100vw"
574
- height="100vh"
575
- right="0"
576
- bottom="0"
577
- />
578
- ```
579
-
580
- ---
581
-
582
- ### Data Prop Format & Helper Function
583
-
584
- ---
585
-
586
- The `data` prop allows you to pass additional custom variables via a single string. This is especially useful when you need to dynamically pass user-specific data or pass it through URL parameters.
587
-
588
- **Format:** `key=value` pairs separated by `~`
589
-
590
- **Example data string:**
591
- ```
592
- email=john@example.com~phone=+1234567890~department=Engineering
593
- ```
594
-
595
- **Note:** `authUrl` and `username` are now **direct props** and should not be included in the `data` string.
596
-
597
- #### Building Data String Programmatically
598
-
599
- Instead of manually constructing the data string, you can create a helper function to build it dynamically. This approach is recommended for production applications as it:
600
- - Prevents syntax errors in the data string format
601
- - Makes the code more maintainable and readable
602
- - Allows for conditional inclusion of parameters
603
- - Handles URL encoding automatically if needed
604
-
605
- **Create a helper function** (`src/helpers/chatWidget.js` or similar):
606
-
607
- ```jsx
608
- /**
609
- * Builds the data string for ChatWidget component
610
- * @param {Object} params - Object containing all parameters
611
- * @param {string} params.email - Optional: User's email address
612
- * @param {string} params.phone - Optional: User's phone number
613
- * @param {Object} params.customFields - Optional: Any additional custom fields as key-value pairs
614
- * @returns {string} Formatted data string for ChatWidget (always returns a string)
615
- *
616
- * @example
617
- * // Returns: "email=john@example.com~phone=+1234567890~department=Engineering"
618
- * buildChatWidgetData({
619
- * email: "john@example.com",
620
- * phone: "+1234567890",
621
- * customFields: { department: "Engineering" }
622
- * });
623
- */
624
- export const buildChatWidgetData = ({
625
- email,
626
- phone,
627
- customFields = {}
628
- }) => {
629
- const parts = [];
630
-
631
- // Add standard fields
632
- if (email) {
633
- parts.push(`email=${encodeURIComponent(email)}`);
634
- }
635
-
636
- if (phone) {
637
- parts.push(`phone=${encodeURIComponent(phone)}`);
638
- }
639
-
640
- // Add any custom fields dynamically
641
- // Note: customFields is just a convenience parameter for the helper function
642
- // Each field will be flattened into the string format: key=value~key2=value2
643
- Object.entries(customFields).forEach(([key, value]) => {
644
- if (value) {
645
- parts.push(`${key}=${encodeURIComponent(String(value))}`);
646
- }
647
- });
648
-
649
- // Returns a string like: "email=john@example.com~phone=+1234567890~department=Engineering"
650
- return parts.join("~");
651
- };
652
- ```
653
-
654
- **Important:** The `customFields` parameter is **NOT** passed as an object to the widget. It's just a convenient way to pass multiple additional fields to the helper function. The function flattens everything into a single string format.
655
-
656
- **Usage in your application:**
657
-
658
- ```jsx
659
- import { ChatWidget } from "@data-netmonk/mona-chat-widget";
660
- import "@data-netmonk/mona-chat-widget/dist/style.css";
661
- import { buildChatWidgetData } from "./helpers/chatWidget";
662
-
663
- function App() {
664
- // Get user data from your auth system, state, or props
665
- const user = {
666
- id: "user123",
667
- name: "John Doe",
668
- email: "john@example.com",
669
- phone: "+628123456789"
670
- };
671
-
672
- // Build the data string with custom variables only
673
- const customData = buildChatWidgetData({
674
- email: user.email,
675
- phone: user.phone,
676
- customFields: {
677
- department: "Engineering",
678
- role: "Developer",
679
- company: "Acme Corp"
680
- }
681
- });
682
-
683
- // customData is now a STRING like:
684
- // "email=john@example.com~phone=%2B628123456789~department=Engineering~role=Developer~company=Acme%20Corp"
685
-
686
- return (
687
- <ChatWidget
688
- userId={user.id}
689
- sourceId="691e1b5952068ff7aaeccffc9"
690
- webhookUrl="https://api.example.com/webhook"
691
- authUrl="https://api.example.com/login/chatwidget" // Direct prop
692
- username={user.name} // Direct prop
693
- data={customData} // Only additional variables
694
- />
695
- );
696
- }
697
- ```
698
-
699
- **With conditional authentication:**
700
-
701
- ```jsx
702
- function App() {
703
- const authUrl = import.meta.env.VITE_CHAT_AUTH_ENABLED === "true"
704
- ? import.meta.env.VITE_CHAT_AUTH_URL
705
- : null;
706
-
707
- const customData = buildChatWidgetData({
708
- email: getCurrentUser().email,
709
- customFields: {
710
- department: "Sales"
711
- }
712
- });
713
-
714
- return (
715
- <ChatWidget
716
- userId={getCurrentUser().id}
717
- sourceId="691e1b5952068ff7aaeccffc9"
718
- webhookUrl={import.meta.env.VITE_WEBHOOK_URL}
719
- authUrl={authUrl} // Direct prop (conditionally set)
720
- username={getCurrentUser().name} // Direct prop
721
- data={customData} // Only additional variables
722
- />
723
- );
724
- }
725
- ```
726
-
727
- **The helper function handles:**
728
- - ✅ Proper formatting with `~` separators
729
- - URL encoding for special characters
730
- - ✅ Conditional parameter inclusion (only adds if value exists)
731
- - ✅ Support for dynamic custom fields
732
- - ✅ Type safety and documentation via JSDoc comments
733
-
734
- ### Standalone app (for demonstration)
735
-
736
- 1. **How to run locally** (access at `http://localhost:${PORT}/${APP_PREFIX}`)
737
-
738
- ```
739
- npm run dev
740
- ```
741
-
742
- 2. **How to build as a standalone app** (build file at `/dist-app` directory)
743
-
744
- ```
745
- npm run build-app
746
- ```
747
-
748
- 3. **How to serve standalone app** (access at `http://localhost:${PORT}/${APP_PREFIX}`)
749
-
750
- ```
751
- npm run serve
752
- ```
753
-
754
- 4. **How to run on docker** (access at `http://localhost:${PORT}/${APP_PREFIX}`)
755
-
756
- ```
757
- docker-compose up --build
758
- ```
759
-
760
- ---
1
+ # Mona Chat Widget
2
+
3
+ Chat widget package developed by Netmonk data & solution team to be imported in Netmonk products
4
+
5
+ ---
6
+
7
+ ### Recent Updates & Breaking Changes
8
+
9
+ ---
10
+
11
+ **Latest Version Changes (`v2.6.0`):**
12
+
13
+ **Non-breaking Changes:**
14
+ 1. **Built-in voice mode button** - Chat widget now includes a microphone button to toggle voice mode directly from the input area
15
+ 2. **Speech-to-text flow for voice mode** - Recorded user audio is sent to the configured `VITE_STT_ENDPOINT`, then the transcription is forwarded as a normal chat message
16
+ 3. **Phoneme-driven avatar animation** - The widget can animate Mona's avatar during TTS playback based on phoneme/viseme IDs returned by the backend
17
+ 4. **Supported phoneme IDs** - `A`, `BP`, `ChJ`, `E`, `FV`, `I`, `KG`, `L`, `M`, `O`, `SZ`, `U`
18
+
19
+ ⚠️ **Previous Breaking Changes:**
20
+ 1. **Removed `type` and `agentType` props** - These parameters are no longer used and have been removed from all components
21
+ 2. **Renamed `botServerUrl` to `webhookUrl`** - For better clarity and consistency
22
+ 3. **`webhookUrl` is now required** - Must be provided as a prop
23
+ 4. **`authUrl` and `username` are now direct props** - No longer part of `data` prop for better clarity and type safety
24
+ 5. **`userId` is now optional** - Widget automatically generates visitor ID for guest users via browser fingerprinting when `userId` is not provided
25
+
26
+ **New Features:**
27
+ 1. **Guest user support** - Users can chat without logging in
28
+ - Automatic visitor ID generation using browser fingerprinting (FingerprintJS + SHA256)
29
+ - `auth: false` flag automatically added to API requests for guest users
30
+ - Persistent sessions across page reloads for anonymous visitors
31
+ 2. **Authentication support** - Automatic token management with refresh on 401 errors
32
+ - Pass `authUrl` as a direct prop
33
+ - Widget handles token lifecycle automatically
34
+ 3. **Enhanced user authentication handling** - Smart detection of authenticated vs guest users
35
+ - Compares `userId` with visitor ID to determine authentication status
36
+ - Automatic `auth` flag management in all API requests
37
+ 4. **Enhanced data prop** - Support for custom variables passed to backend via `data` prop
38
+ 5. **Improved error handling** - Better fallback mechanisms and error messages
39
+ 6. **Direct `username` prop** - Pass username as a top-level prop instead of in data string
40
+
41
+ 📝 **Migration Guide:**
42
+ ```jsx
43
+ // Old usage (deprecated)
44
+ <ChatWidget
45
+ userId="user123"
46
+ sourceId="source456"
47
+ type="prime"
48
+ botServerUrl="https://api.example.com"
49
+ />
50
+
51
+ // Previous version (with data prop)
52
+ <ChatWidget
53
+ userId="user123"
54
+ sourceId="source456"
55
+ webhookUrl="https://api.example.com/webhook"
56
+ data="authUrl=https://api.example.com/login/chatwidget~username=John"
57
+ />
58
+
59
+ // New usage - Authenticated user (current - recommended)
60
+ <ChatWidget
61
+ userId="user123"
62
+ sourceId="source456"
63
+ webhookUrl="https://api.example.com/webhook"
64
+ authUrl="https://api.example.com/login/chatwidget"
65
+ username="John"
66
+ data="email=john@example.com~phone=+1234567890"
67
+ />
68
+
69
+ // New usage - Guest user (without login)
70
+ <ChatWidget
71
+ sourceId="source456"
72
+ webhookUrl="https://api.example.com/webhook"
73
+ username="Guest"
74
+ />
75
+ // Widget automatically generates visitor ID and adds auth: false flag
76
+
77
+ // New usage - Conditional (handles both logged-in and guest users)
78
+ <ChatWidget
79
+ userId={currentUser?.id} // undefined for guests
80
+ sourceId="source456"
81
+ webhookUrl="https://api.example.com/webhook"
82
+ username={currentUser?.name || "Guest"}
83
+ />
84
+ ```
85
+
86
+ ---
87
+
88
+ ## 🚅 Quick start
89
+
90
+ ### Prerequisites
91
+
92
+ ---
93
+
94
+ 1. Install dependencies
95
+ ```
96
+ npm install --legacy-peer-deps
97
+ ```
98
+ 2. Copy .env.example
99
+ ```
100
+ cp .env.example .env
101
+ ```
102
+ 3. Populate .env
103
+ 4. Optional speech endpoints
104
+
105
+ To enable voice mode and phoneme-based avatar animation, set these environment variables in your `.env` file:
106
+ ```
107
+ VITE_STT_ENDPOINT=https://your-stt-service.example.com/transcribe
108
+ VITE_TTS_ENDPOINT=https://your-tts-service.example.com/synthesize
109
+ ```
110
+
111
+ `VITE_STT_ENDPOINT` is used by the built-in mic button to transcribe recorded audio.
112
+ `VITE_TTS_ENDPOINT` is used for TTS playback and to consume `visemes` data for avatar lip-sync.
113
+ 5. Optional TTS debug logging
114
+
115
+ To inspect TTS queue and playback lifecycle in browser console, set `VITE_DEBUG_TTS=true` in your `.env` file.
116
+ Keep this disabled in production to avoid noisy logs.
117
+ 6. Enable mock mode (optional)
118
+
119
+ To test the chat widget without a backend server, set `VITE_USE_MOCK_RESPONSES=true` in your `.env` file. The widget will respond to messages like:
120
+ - "start", "hello", "hi", "halo" - Greeting messages
121
+ - "help", "bantuan" - Help information
122
+ - "terima kasih", "thank you" - Acknowledgments
123
+ - "bye", "goodbye" - Farewell messages
124
+ - And more! Check `src/components/ChatWidget/utils/helpers.js` for full list
125
+
126
+ ---
127
+
128
+ ### Mock Mode (Demo without Backend)
129
+
130
+ ---
131
+
132
+ The chat widget includes a built-in mock mode for testing and demonstrations without requiring a backend server.
133
+
134
+ **To enable mock mode:**
135
+ 1. Set `VITE_USE_MOCK_RESPONSES=true` in your `.env` file
136
+ 2. Run the app normally with `npm run dev`
137
+
138
+ **Mock responses include:**
139
+ - Greetings (hello, hi, halo, start) - with interactive buttons
140
+ - Help commands
141
+ - Device list with clickable buttons (type "devices" or "show devices")
142
+ - Thank you acknowledgments
143
+ - Farewells
144
+ - Time-based greetings (good morning, etc.)
145
+ - And automatically falls back to mock mode if backend fails
146
+
147
+ **Interactive Buttons Demo:**
148
+ Type these messages to see button responses:
149
+ - "start" - Welcome message with action buttons
150
+ - "show devices" or "devices" - List of devices as clickable buttons
151
+ - Click any button to trigger the next action
152
+
153
+ **To add custom mock responses:**
154
+ Edit the `mockBotResponses` object in `src/components/ChatWidget/utils/mockBotResponses.js`
155
+
156
+ For text-only responses:
157
+ ```javascript
158
+ "trigger": "Response text"
159
+ ```
160
+
161
+ For responses with buttons:
162
+ ```javascript
163
+ "trigger": {
164
+ text: "Your message here",
165
+ buttons: [
166
+ { title: "Button 1", payload: "action_1" },
167
+ { title: "Button 2", payload: "action_2" },
168
+ { title: "Link Button", url: "https://example.com" }
169
+ ]
170
+ }
171
+ ```
172
+
173
+ ---
174
+
175
+ ### Storybook
176
+
177
+ ---
178
+
179
+ 1. **How to run Storybook locally** (access at http://localhost:5177)
180
+
181
+ ```
182
+ npm run storybook
183
+ ```
184
+
185
+ 2. **How to build Storybook**
186
+
187
+ ```
188
+ npm run build-storybook
189
+ ```
190
+
191
+ 3. **How to serve Storybook**
192
+
193
+ ```
194
+ npm run serve-storybook
195
+ ```
196
+
197
+ ---
198
+
199
+ ### Library (how to update and publish)
200
+
201
+ ---
202
+
203
+ 1. **Commit changes**
204
+ ```
205
+ git add .
206
+ git commit -m "Your commit message"
207
+ ```
208
+ 2. **Update version**
209
+
210
+ ```bash
211
+ npm version patch # for bug fixes (1.0.0 -> 1.0.1)
212
+ ```
213
+
214
+ ```bash
215
+ npm version minor # for new features (1.0.0 -> 1.1.0)
216
+ ```
217
+
218
+ ```bash
219
+ npm version major # for breaking changes (1.0.0 -> 2.0.0)
220
+ ```
221
+
222
+ 3. **Build as a library** (build file at `/dist` directory)
223
+
224
+ ```
225
+ npm run build
226
+ ```
227
+
228
+ 4. **Copy declaration file to `/dist`**
229
+
230
+ ```
231
+ cp ./src/declarations/index.d.ts ./dist/index.d.ts
232
+ ```
233
+
234
+ 5. **Publish**
235
+
236
+ ```
237
+ npm publish
238
+ ```
239
+
240
+ ---
241
+
242
+ ### Library (how to import on your project)
243
+
244
+ ---
245
+
246
+ 1. **Install package**
247
+ ```bash
248
+ npm install @data-netmonk/mona-chat-widget
249
+ ```
250
+
251
+ 2. **Import styles on your `App.jsx` or `index.jsx`**
252
+
253
+ ```jsx
254
+ import "@data-netmonk/mona-chat-widget/dist/style.css";
255
+ ```
256
+
257
+ 3. **Import & use component**
258
+
259
+ ```jsx
260
+ import { ChatWidget } from "@data-netmonk/mona-chat-widget";
261
+
262
+ function App() {
263
+ return (
264
+ <ChatWidget
265
+ userId="user123"
266
+ sourceId="691e1b5952068ff7aaeccffc9"
267
+ webhookUrl="https://your-backend-url.com"
268
+ />
269
+ );
270
+ }
271
+ ```
272
+
273
+ ---
274
+
275
+ ### Component Props
276
+
277
+ ---
278
+
279
+ #### Required Props
280
+
281
+ | Prop | Type | Description |
282
+ |------|------|-------------|
283
+ | `sourceId` | `string` | **Required.** Source/channel identifier for the chat |
284
+ | `webhookUrl` | `string` | **Required.** Backend webhook URL |
285
+
286
+ #### Optional Props
287
+
288
+ | Prop | Type | Default | Description |
289
+ |------|------|---------|-------------|
290
+ | `userId` | `string` | Generated visitor ID | Unique identifier for the user. **Optional** - if not provided, a unique visitor ID is automatically generated using browser fingerprinting for guest users |
291
+ | `authUrl` | `string` | - | Authentication endpoint URL for token-based authentication |
292
+ | `username` | `string` | - | Username for the session (sent to backend in variables) |
293
+ | `data` | `string` | - | Additional custom variables in format `key1=value1~key2=value2` |
294
+ | `width` | `string` | `"25vw"` | Widget width (CSS value) |
295
+ | `height` | `string` | `"90vh"` | Widget height (CSS value) |
296
+ | `right` | `string` | `"1.25rem"` | Distance from right edge |
297
+ | `bottom` | `string` | `"1.25rem"` | Distance from bottom edge |
298
+ | `zIndex` | `number` | `2000` | CSS z-index for widget positioning |
299
+ | `position` | `string` | `"fixed"` | CSS position (`"fixed"` or `"relative"`) |
300
+ | `onToggle` | `function` | - | Callback when widget opens/closes: `(isOpen: boolean) => void` |
301
+
302
+ ---
303
+
304
+ ### Voice Mode & Phoneme Support
305
+
306
+ ---
307
+
308
+ The widget now includes a built-in microphone button in the input area. Clicking the button toggles voice mode, requests microphone access, records speech, sends the recorded audio to `VITE_STT_ENDPOINT`, and forwards the returned transcription as a regular user message.
309
+
310
+ During TTS playback, the header avatar can switch between phoneme images using the `visemes` payload returned by the TTS service. The widget currently supports these phoneme IDs:
311
+
312
+ - `A`
313
+ - `BP`
314
+ - `ChJ`
315
+ - `E`
316
+ - `FV`
317
+ - `I`
318
+ - `KG`
319
+ - `L`
320
+ - `M`
321
+ - `O`
322
+ - `SZ`
323
+ - `U`
324
+
325
+ Phoneme IDs are normalized case-insensitively in the widget, so values such as `ChJ` and `CHJ` resolve to the same avatar image.
326
+
327
+ **Expected TTS response shape:**
328
+
329
+ ```json
330
+ {
331
+ "audioBase64": "<base64-audio>",
332
+ "contentType": "audio/mpeg",
333
+ "durationMs": 1450,
334
+ "visemes": [
335
+ { "id": "M", "startMs": 0, "endMs": 120 },
336
+ { "id": "A", "startMs": 121, "endMs": 260 },
337
+ { "id": "SZ", "startMs": 261, "endMs": 420 }
338
+ ]
339
+ }
340
+ ```
341
+
342
+ If `visemes` are omitted, TTS audio can still play normally, but the avatar will not switch phoneme frames dynamically.
343
+
344
+ ---
345
+
346
+ ### Guest User Support
347
+
348
+ ---
349
+
350
+ The widget now supports **guest users** (users who haven't logged in or before logging in). When `userId` is not provided, the widget automatically generates a unique visitor ID using browser fingerprinting.
351
+
352
+ **How it works:**
353
+
354
+ 1. **Browser Fingerprinting**: Uses FingerprintJS to generate a unique identifier based on:
355
+ - Browser characteristics (user agent, screen resolution, timezone, etc.)
356
+ - Incognito/private browsing detection
357
+ - Combined into a SHA256 hash for consistency
358
+
359
+ 2. **Automatic Guest Detection**: The widget automatically detects guest users and:
360
+ - Generates a visitor ID if `userId` is not provided
361
+ - Adds `auth: false` flag to all API requests for guest users
362
+ - Uses the visitor ID as the effective user ID throughout the session
363
+
364
+ 3. **Persistent Sessions**: The visitor ID remains consistent across page reloads (unless browser fingerprint changes or user clears data)
365
+
366
+ **When to use guest mode:**
367
+ - Public-facing websites where users can chat without logging in
368
+ - Support widgets for anonymous visitors
369
+ - Pre-login customer service interactions
370
+ - Any scenario where user authentication is optional
371
+
372
+ **When to provide userId:**
373
+ - Users who are logged into your application
374
+ - When you need to track chat history across devices
375
+ - When authentication is required for personalized responses
376
+ - Enterprise or internal applications
377
+
378
+ ---
379
+
380
+ ### Usage Examples
381
+
382
+ ---
383
+
384
+ #### Basic Usage (Authenticated User)
385
+
386
+ ```jsx
387
+ import { ChatWidget } from "@data-netmonk/mona-chat-widget";
388
+ import "@data-netmonk/mona-chat-widget/dist/style.css";
389
+
390
+ function App() {
391
+ return (
392
+ <ChatWidget
393
+ userId="user123"
394
+ sourceId="691e1b5952068ff7aaeccffc9"
395
+ webhookUrl="https://api.example.com/webhook"
396
+ />
397
+ );
398
+ }
399
+ ```
400
+
401
+ #### Guest User (Without Login)
402
+
403
+ For anonymous visitors or users who haven't logged in:
404
+
405
+ ```jsx
406
+ import { ChatWidget } from "@data-netmonk/mona-chat-widget";
407
+ import "@data-netmonk/mona-chat-widget/dist/style.css";
408
+
409
+ function App() {
410
+ return (
411
+ <ChatWidget
412
+ sourceId="691e1b5952068ff7aaeccffc9"
413
+ webhookUrl="https://api.example.com/webhook"
414
+ />
415
+ );
416
+ }
417
+ ```
418
+
419
+ **What happens:**
420
+ - Widget automatically generates a visitor ID using browser fingerprinting
421
+ - All API requests include `auth: false` in variables to indicate guest user
422
+ - No login required - users can start chatting immediately
423
+
424
+ #### Conditional userId (Logged in or Guest)
425
+
426
+ Handle both logged-in users and guests dynamically:
427
+
428
+ ```jsx
429
+ import { ChatWidget } from "@data-netmonk/mona-chat-widget";
430
+ import "@data-netmonk/mona-chat-widget/dist/style.css";
431
+
432
+ function App() {
433
+ const currentUser = getCurrentUser(); // Your auth function
434
+
435
+ return (
436
+ <ChatWidget
437
+ userId={currentUser?.id} // Provide userId if logged in, undefined if not
438
+ sourceId="691e1b5952068ff7aaeccffc9"
439
+ webhookUrl="https://api.example.com/webhook"
440
+ username={currentUser?.name}
441
+ />
442
+ );
443
+ }
444
+ ```
445
+
446
+ **Behavior:**
447
+ - If `currentUser.id` exists → Uses provided userId (authenticated user)
448
+ - If `currentUser.id` is `null`/`undefined` → Generates visitor ID (guest user)
449
+ - Backend receives `auth: false` flag only for guest users
450
+
451
+ #### With Custom Variables
452
+
453
+ Pass custom user data like email, phone number, etc. to the backend:
454
+
455
+ ```jsx
456
+ <ChatWidget
457
+ userId="user123"
458
+ sourceId="691e1b5952068ff7aaeccffc9"
459
+ webhookUrl="https://api.example.com/webhook"
460
+ username="John Doe"
461
+ data="telephone_number=+628123456789~email=john@example.com"
462
+ />
463
+ ```
464
+
465
+ **Variables sent to backend:**
466
+ ```json
467
+ {
468
+ "chat_id": "...",
469
+ "session_id": "...",
470
+ "user_id": "user123",
471
+ "message": "Hello",
472
+ "type": "text",
473
+ "variables": {
474
+ "username": "John Doe",
475
+ "telephone_number": "+628123456789",
476
+ "email": "john@example.com"
477
+ }
478
+ }
479
+ ```
480
+ }
481
+ ```
482
+ #### With Authentication (NEW!)
483
+
484
+ The widget supports automatic authentication with token refresh on expiry:
485
+
486
+ ```jsx
487
+ <ChatWidget
488
+ userId="user123"
489
+ sourceId="691e1b5952068ff7aaeccffc9"
490
+ webhookUrl="https://api.example.com/webhook"
491
+ authUrl="https://api.example.com/login/chatwidget"
492
+ username="John Doe"
493
+ />
494
+ ```
495
+
496
+ **How authentication works:**
497
+
498
+ 1. **Initial Authentication**: When the widget loads (on Launcher mount), if `authUrl` is provided as a prop, it automatically calls the auth API:
499
+ ```
500
+ POST {authUrl}
501
+ Body: { "user_id": "user123" }
502
+ Response: { "token": "eyJ..." }
503
+ ```
504
+
505
+ 2. **Session Initialization**: After getting the token, the widget calls the init endpoint to establish the session:
506
+ ```
507
+ POST {webhookUrl}/{sourceId}/init
508
+ Body: {
509
+ "session_id": "...",
510
+ "user_id": "user123",
511
+ "token": "eyJ...",
512
+ "username": "John Doe"
513
+ }
514
+ ```
515
+
516
+ 3. **Automatic Token Refresh**: If the webhook returns **401 Unauthorized** (token expired/revoked), the widget automatically:
517
+ - Calls the `authUrl` again to get a fresh token
518
+ - Re-initializes the session with the new token
519
+ - Updates the `authToken` in variables
520
+ - Retries the failed request with the new token
521
+ - This happens transparently without user interaction
522
+
523
+ **Combined example with auth and custom variables:**
524
+ ```jsx
525
+ <ChatWidget
526
+ userId="user123"
527
+ sourceId="691e1b5952068ff7aaeccffc9"
528
+ webhookUrl="https://api.example.com/webhook"
529
+ authUrl="https://api.example.com/login/chatwidget"
530
+ username="John"
531
+ data="email=john@example.com~phone=+628123456789"
532
+ />
533
+ ```
534
+
535
+ **Auth Flag (`auth` variable):**
536
+ The widget automatically adds an `auth: false` flag to the `variables` object when the user is a guest (not authenticated):
537
+ - When `userId === visitorId` (browser fingerprint), the widget adds `auth: false` to variables
538
+ - When `userId !== visitorId` (authenticated user), no `auth` flag is added to variables
539
+
540
+ **Guest user example** (userId equals browser fingerprint):
541
+ ```json
542
+ {
543
+ "chat_id": "...",
544
+ "session_id": "...",
545
+ "user_id": "visitor_abc123",
546
+ "message": "Hello",
547
+ "type": "text",
548
+ "variables": {
549
+ "username": "Guest",
550
+ "auth": false
551
+ }
552
+ }
553
+ ```
554
+
555
+ **Authenticated user example** (userId is different from browser fingerprint):
556
+ ```json
557
+ {
558
+ "chat_id": "...",
559
+ "session_id": "...",
560
+ "user_id": "user123",
561
+ "message": "Hello",
562
+ "type": "text",
563
+ "variables": {
564
+ "username": "John Doe",
565
+ "email": "john@example.com"
566
+ }
567
+ }
568
+ ```
569
+
570
+ This `auth: false` flag is automatically added in:
571
+ - Session initialization payload (when guest)
572
+ - All message requests (when guest)
573
+ - Button postback requests (when guest)
574
+
575
+ **Note:** The `data` prop is for additional custom variables only. Required parameters (`userId`, `sourceId`, `webhookUrl`) and common optional parameters (`authUrl`, `username`) should be passed as direct props for better type safety and clarity.
576
+
577
+ #### Custom Styling
578
+
579
+ ```jsx
580
+ <ChatWidget
581
+ userId="user123" // Optional
582
+ sourceId="691e1b5952068ff7aaeccffc9"
583
+ webhookUrl="https://api.example.com/webhook"
584
+ width="400px"
585
+ height="600px"
586
+ right="20px"
587
+ bottom="20px"
588
+ zIndex={9999}
589
+ />
590
+ ```
591
+
592
+ #### Embedded in Layout (Relative Positioning)
593
+
594
+ ```jsx
595
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 400px' }}>
596
+ <div>Main content</div>
597
+ <ChatWidget
598
+ userId="user123" // Optional
599
+ sourceId="691e1b5952068ff7aaeccffc9"
600
+ webhookUrl="https://api.example.com/webhook"
601
+ position="relative"
602
+ width="100%"
603
+ height="100vh"
604
+ />
605
+ </div>
606
+ ```
607
+
608
+ #### With Toggle Callback
609
+
610
+ ```jsx
611
+ function App() {
612
+ const handleToggle = (isOpen) => {
613
+ console.log('Chat widget is', isOpen ? 'open' : 'closed');
614
+ // Track analytics, update UI, etc.
615
+ };
616
+
617
+ return (
618
+ <ChatWidget
619
+ userId="user123" // Optional
620
+ sourceId="691e1b5952068ff7aaeccffc9"
621
+ webhookUrl="https://api.example.com/webhook"
622
+ onToggle={handleToggle}
623
+ />
624
+ );
625
+ }
626
+ ```
627
+
628
+ #### Full-Screen Widget
629
+
630
+ ```jsx
631
+ <ChatWidget
632
+ userId="user123" // Optional - supports guest users
633
+ sourceId="691e1b5952068ff7aaeccffc9"
634
+ webhookUrl="https://api.example.com/webhook"
635
+ width="100vw"
636
+ height="100vh"
637
+ right="0"
638
+ bottom="0"
639
+ />
640
+ ```
641
+
642
+ ---
643
+
644
+ ### Data Prop Format & Helper Function
645
+
646
+ ---
647
+
648
+ The `data` prop allows you to pass additional custom variables via a single string. This is especially useful when you need to dynamically pass user-specific data or pass it through URL parameters.
649
+
650
+ **Format:** `key=value` pairs separated by `~`
651
+
652
+ **Example data string:**
653
+ ```
654
+ email=john@example.com~phone=+1234567890~department=Engineering
655
+ ```
656
+
657
+ **Note:** `authUrl` and `username` are now **direct props** and should not be included in the `data` string.
658
+
659
+ #### Building Data String Programmatically
660
+
661
+ Instead of manually constructing the data string, you can create a helper function to build it dynamically. This approach is recommended for production applications as it:
662
+ - Prevents syntax errors in the data string format
663
+ - Makes the code more maintainable and readable
664
+ - Allows for conditional inclusion of parameters
665
+ - Handles URL encoding automatically if needed
666
+
667
+ **Create a helper function** (`src/helpers/chatWidget.js` or similar):
668
+
669
+ ```jsx
670
+ /**
671
+ * Builds the data string for ChatWidget component
672
+ * @param {Object} params - Object containing all parameters
673
+ * @param {string} params.email - Optional: User's email address
674
+ * @param {string} params.phone - Optional: User's phone number
675
+ * @param {Object} params.customFields - Optional: Any additional custom fields as key-value pairs
676
+ * @returns {string} Formatted data string for ChatWidget (always returns a string)
677
+ *
678
+ * @example
679
+ * // Returns: "email=john@example.com~phone=+1234567890~department=Engineering"
680
+ * buildChatWidgetData({
681
+ * email: "john@example.com",
682
+ * phone: "+1234567890",
683
+ * customFields: { department: "Engineering" }
684
+ * });
685
+ */
686
+ export const buildChatWidgetData = ({
687
+ email,
688
+ phone,
689
+ customFields = {}
690
+ }) => {
691
+ const parts = [];
692
+
693
+ // Add standard fields
694
+ if (email) {
695
+ parts.push(`email=${encodeURIComponent(email)}`);
696
+ }
697
+
698
+ if (phone) {
699
+ parts.push(`phone=${encodeURIComponent(phone)}`);
700
+ }
701
+
702
+ // Add any custom fields dynamically
703
+ // Note: customFields is just a convenience parameter for the helper function
704
+ // Each field will be flattened into the string format: key=value~key2=value2
705
+ Object.entries(customFields).forEach(([key, value]) => {
706
+ if (value) {
707
+ parts.push(`${key}=${encodeURIComponent(String(value))}`);
708
+ }
709
+ });
710
+
711
+ // Returns a string like: "email=john@example.com~phone=+1234567890~department=Engineering"
712
+ return parts.join("~");
713
+ };
714
+ ```
715
+
716
+ **Important:** The `customFields` parameter is **NOT** passed as an object to the widget. It's just a convenient way to pass multiple additional fields to the helper function. The function flattens everything into a single string format.
717
+
718
+ **Usage in your application:**
719
+
720
+ ```jsx
721
+ import { ChatWidget } from "@data-netmonk/mona-chat-widget";
722
+ import "@data-netmonk/mona-chat-widget/dist/style.css";
723
+ import { buildChatWidgetData } from "./helpers/chatWidget";
724
+
725
+ function App() {
726
+ // Get user data from your auth system, state, or props
727
+ const user = {
728
+ id: "user123",
729
+ name: "John Doe",
730
+ email: "john@example.com",
731
+ phone: "+628123456789"
732
+ };
733
+
734
+ // Build the data string with custom variables only
735
+ const customData = buildChatWidgetData({
736
+ email: user.email,
737
+ phone: user.phone,
738
+ customFields: {
739
+ department: "Engineering",
740
+ role: "Developer",
741
+ company: "Acme Corp"
742
+ }
743
+ });
744
+
745
+ // customData is now a STRING like:
746
+ // "email=john@example.com~phone=%2B628123456789~department=Engineering~role=Developer~company=Acme%20Corp"
747
+
748
+ return (
749
+ <ChatWidget
750
+ userId={user.id}
751
+ sourceId="691e1b5952068ff7aaeccffc9"
752
+ webhookUrl="https://api.example.com/webhook"
753
+ authUrl="https://api.example.com/login/chatwidget" // Direct prop
754
+ username={user.name} // Direct prop
755
+ data={customData} // Only additional variables
756
+ />
757
+ );
758
+ }
759
+ ```
760
+
761
+ **With conditional authentication:**
762
+
763
+ ```jsx
764
+ function App() {
765
+ const authUrl = import.meta.env.VITE_CHAT_AUTH_ENABLED === "true"
766
+ ? import.meta.env.VITE_CHAT_AUTH_URL
767
+ : null;
768
+
769
+ const customData = buildChatWidgetData({
770
+ email: getCurrentUser().email,
771
+ customFields: {
772
+ department: "Sales"
773
+ }
774
+ });
775
+
776
+ return (
777
+ <ChatWidget
778
+ userId={getCurrentUser().id}
779
+ sourceId="691e1b5952068ff7aaeccffc9"
780
+ webhookUrl={import.meta.env.VITE_WEBHOOK_URL}
781
+ authUrl={authUrl} // Direct prop (conditionally set)
782
+ username={getCurrentUser().name} // Direct prop
783
+ data={customData} // Only additional variables
784
+ />
785
+ );
786
+ }
787
+ ```
788
+
789
+ **The helper function handles:**
790
+ - ✅ Proper formatting with `~` separators
791
+ - ✅ URL encoding for special characters
792
+ - ✅ Conditional parameter inclusion (only adds if value exists)
793
+ - ✅ Support for dynamic custom fields
794
+ - ✅ Type safety and documentation via JSDoc comments
795
+
796
+ ### Standalone app (for demonstration)
797
+
798
+ 1. **How to run locally** (access at `http://localhost:${PORT}/${APP_PREFIX}`)
799
+
800
+ ```
801
+ npm run dev
802
+ ```
803
+
804
+ 2. **How to build as a standalone app** (build file at `/dist-app` directory)
805
+
806
+ ```
807
+ npm run build-app
808
+ ```
809
+
810
+ 3. **How to serve standalone app** (access at `http://localhost:${PORT}/${APP_PREFIX}`)
811
+
812
+ ```
813
+ npm run serve
814
+ ```
815
+
816
+ 4. **How to run on docker** (access at `http://localhost:${PORT}/${APP_PREFIX}`)
817
+
818
+ ```
819
+ docker-compose up --build
820
+ ```
821
+
822
+ ---