@channelhub/widget 0.1.3 โ†’ 0.1.5

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.
@@ -1,13 +1,44 @@
1
- import { FormEvent, createContext, forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
1
+ import { Component, FormEvent, createContext, forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
2
+ import type { ReactNode } from 'react';
2
3
  import { createPortal } from 'react-dom';
3
- import { AlertCircle, Check, CheckCheck, ChevronDown, ChevronRight, Inbox, Info, Loader2, MoreHorizontal, Paperclip, Play, Search, Send, SlidersHorizontal, X } from 'lucide-react';
4
+ import { AlertCircle, Check, CheckCheck, ChevronDown, ChevronRight, Image, Inbox, Info, Loader2, MoreHorizontal, Paperclip, Play, Search, Send, SlidersHorizontal, Smile, X, Zap } from 'lucide-react';
4
5
  import { ChannelHubClient } from './api.js';
5
- import type { ChannelHubInboxHandle, Connection, Conversation, Message, MessageAttachment, Page, Provider, WidgetProps } from './types.js';
6
+ import type { ChannelHubInboxHandle, Connection, Conversation, ContactInfoRow, Extension, ExtensionContact, ExtensionContext, Message, MessageAttachment, Page, Provider, WidgetProps } from './types.js';
6
7
 
7
8
  type WidgetTranslations = { today: string; loadOlder: string; loading: string; noMessages: string; searchPlaceholder: string; unreadOnly: string; sendPlaceholder: string; send: string; all: string };
8
9
  import { Avatar as UiAvatar, Button, Input, ScrollArea, Textarea } from './components/ui/index.js';
9
10
 
11
+ function buildContact(conv: Conversation): ExtensionContact {
12
+ return {
13
+ id: conv.contactId ?? conv.providerConversationKey,
14
+ name: conv.contactName,
15
+ pictureUrl: conv.contactPictureUrl,
16
+ providerUserId: conv.contactProviderUserId ?? conv.providerConversationKey,
17
+ ...(conv.contactExternalId ? { externalId: conv.contactExternalId } : {}),
18
+ };
19
+ }
20
+
21
+ function buildCtx(conv: Conversation): ExtensionContext {
22
+ return { conversation: conv, contact: buildContact(conv) };
23
+ }
24
+
25
+ class ExtErrorBoundary extends Component<{ children: ReactNode }, { caught: boolean }> {
26
+ state = { caught: false };
27
+ static getDerivedStateFromError() { return { caught: true }; }
28
+ render() { return this.state.caught ? null : this.props.children; }
29
+ }
30
+
10
31
  const c = { ink: '#172033', muted: '#718096', line: '#e7ebf2', surface: '#f7f9fc', white: '#fff' };
32
+
33
+ const EMOJI_CATEGORIES: { icon: string; emojis: string[] }[] = [
34
+ { icon: '๐Ÿ˜Š', emojis: ['๐Ÿ˜€','๐Ÿ˜','๐Ÿ˜‚','๐Ÿคฃ','๐Ÿ˜Š','๐Ÿ˜‡','๐Ÿ™‚','๐Ÿ˜‰','๐Ÿ˜','๐Ÿฅฐ','๐Ÿ˜˜','๐Ÿ˜‹','๐Ÿ˜Ž','๐Ÿคฉ','๐Ÿ˜','๐Ÿ˜’','๐Ÿ˜”','๐Ÿ˜ข','๐Ÿ˜ญ','๐Ÿ˜ค','๐Ÿ˜ ','๐Ÿคฏ','๐Ÿ˜ฑ','๐Ÿฅณ','๐Ÿ˜ด','๐Ÿค”','๐Ÿค—','๐Ÿซก','๐Ÿ˜ฎ','๐Ÿคง','๐Ÿฅบ','๐Ÿ˜ถ','๐Ÿซ ','๐Ÿคญ','๐Ÿคซ'] },
35
+ { icon: '๐Ÿ‘‹', emojis: ['๐Ÿ‘','๐Ÿ‘Ž','๐Ÿ‘','๐Ÿ™','๐Ÿค','โœŒ๏ธ','๐Ÿคž','๐Ÿซก','๐Ÿ’ช','๐Ÿคœ','๐Ÿ‘Š','โœŠ','๐Ÿ–','๐Ÿ‘Œ','๐ŸคŒ','๐Ÿค','โ˜๏ธ','๐Ÿ‘†','๐Ÿ‘‡','๐Ÿ‘‰','๐Ÿ‘ˆ','๐Ÿค™','๐Ÿ’…','๐Ÿซถ','โค๏ธ','๐Ÿงก','๐Ÿ’›','๐Ÿ’š','๐Ÿ’™','๐Ÿ’œ','๐Ÿ–ค','๐Ÿ’”','โฃ๏ธ','๐Ÿ’•','๐Ÿ’ฏ'] },
36
+ { icon: '๐Ÿฑ', emojis: ['๐Ÿถ','๐Ÿฑ','๐Ÿญ','๐Ÿน','๐Ÿฐ','๐ŸฆŠ','๐Ÿป','๐Ÿผ','๐Ÿจ','๐Ÿฏ','๐Ÿฆ','๐Ÿฎ','๐Ÿท','๐Ÿธ','๐Ÿต','๐Ÿ™ˆ','๐Ÿ”','๐Ÿง','๐Ÿฆ','๐Ÿฆ†','๐Ÿฆ…','๐Ÿฆ‰','๐Ÿฆ‹','๐Ÿ','๐Ÿ›','๐Ÿข','๐ŸฆŽ','๐Ÿฌ','๐Ÿฆˆ','๐Ÿณ','๐Ÿ™','๐Ÿฆ‘'] },
37
+ { icon: '๐Ÿ•', emojis: ['๐ŸŽ','๐ŸŠ','๐Ÿ‹','๐Ÿ‡','๐Ÿ“','๐Ÿ’','๐Ÿฅ','๐Ÿฅ‘','๐Ÿ”','๐Ÿ•','๐ŸŒฎ','๐Ÿœ','๐Ÿฃ','๐Ÿฆ','๐ŸŽ‚','๐Ÿฐ','๐Ÿง','โ˜•','๐Ÿง‹','๐Ÿฅค','๐Ÿบ','๐Ÿฅ‚','๐Ÿพ','๐Ÿงƒ','๐ŸงŠ'] },
38
+ { icon: 'โšฝ', emojis: ['โšฝ','๐Ÿ€','๐Ÿˆ','โšพ','๐ŸŽพ','๐Ÿ','๐Ÿ“','๐ŸŽฎ','๐ŸŽฒ','๐ŸŽฏ','๐ŸŽณ','๐Ÿ†','๐Ÿฅ‡','๐ŸŽ–','๐ŸŽ','๐ŸŽ‰','๐ŸŽŠ','๐ŸŽˆ','๐ŸŽญ','๐ŸŽจ','๐ŸŽฌ','๐ŸŽต','๐ŸŽธ','๐ŸŽน','๐ŸŽบ','๐Ÿช—','๐ŸŽป'] },
39
+ { icon: '๐ŸŒ', emojis: ['๐ŸŒ','๐ŸŒˆ','โญ','๐ŸŒ™','โ˜€๏ธ','โ›…','๐ŸŒŠ','๐Ÿ”ฅ','๐Ÿ’ง','๐ŸŒฟ','๐ŸŒธ','๐ŸŒบ','๐ŸŒป','๐Ÿ€','๐ŸŒด','๐Ÿ”','๐Ÿ–','๐Ÿ•','๐ŸŒƒ','๐Ÿ™','๐ŸŒ…','๐ŸŒ„','๐ŸŒ ','๐ŸŒŒ','๐ŸŒ‹','๐Ÿ'] },
40
+ ];
41
+
11
42
  const ApiUrlCtx = createContext('');
12
43
  const TokenCtx = createContext('');
13
44
 
@@ -42,6 +73,7 @@ function providerLabel(p?: Provider): string {
42
73
  if (p === 'instagram') return 'Instagram';
43
74
  if (p === 'telegram') return 'Telegram';
44
75
  if (p === 'zalo') return 'Zalo OA';
76
+ if (p === 'livechat') return 'Live Chat';
45
77
  return 'Channel';
46
78
  }
47
79
 
@@ -50,6 +82,7 @@ function providerShortLabel(p?: Provider): string {
50
82
  if (p === 'instagram') return 'Instagram';
51
83
  if (p === 'telegram') return 'Telegram';
52
84
  if (p === 'zalo') return 'Zalo';
85
+ if (p === 'livechat') return 'Live Chat';
53
86
  return String(p ?? '');
54
87
  }
55
88
 
@@ -73,7 +106,7 @@ function StatusIcon({ status }: { status?: Message['status'] }) {
73
106
  type ActiveFilters = { provider: Provider | 'all'; unreadOnly: boolean };
74
107
 
75
108
  export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(function ChannelHubInbox(
76
- { apiUrl, token, theme, height, defaultConversationId, disableAttachments, disableNotificationSound, hideKeyboardHint, locale = 'vi', onNewMessage, onConversationSelect },
109
+ { apiUrl, token, theme, height, defaultConversationId, disableAttachments, disableNotificationSound, hideKeyboardHint, locale = 'vi', extensions, onNewMessage, onConversationSelect },
77
110
  ref
78
111
  ) {
79
112
  const client = useRef(new ChannelHubClient(apiUrl, token));
@@ -87,13 +120,15 @@ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(fu
87
120
  const [popoverAnchor, setPopoverAnchor] = useState<{ top: number; left: number } | null>(null);
88
121
  const [loading, setLoading] = useState(true); const [error, setError] = useState('');
89
122
  const [infoOpen, setInfoOpen] = useState(false);
123
+ const [infoPanelWidth, setInfoPanelWidth] = useState(260);
124
+ const [isResizing, setIsResizing] = useState(false);
90
125
  const primary = theme?.primaryColor ?? '#2563eb';
91
126
  const connectionById = useMemo(() => new Map(connections.map(connection => [connection.id, connection])), [connections]);
92
127
  const appendMessageRef = useRef<((msg: Message) => void) | null>(null);
93
128
  const [msgRefreshKey, setMsgRefreshKey] = useState(0);
94
129
  const availableProviders = useMemo(() => {
95
130
  const ps = new Set(connections.map(cn => cn.provider));
96
- return (['facebook', 'instagram', 'telegram', 'zalo'] as const).filter(p => ps.has(p));
131
+ return (['facebook', 'instagram', 'telegram', 'zalo', 'livechat'] as const).filter(p => ps.has(p));
97
132
  }, [connections]);
98
133
  const countByProvider = useMemo(() => {
99
134
  const counts: Record<string, number> = {};
@@ -103,6 +138,26 @@ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(fu
103
138
  }
104
139
  return counts;
105
140
  }, [items, connectionById]);
141
+ function startInfoResize(e: React.MouseEvent) {
142
+ const startX = e.clientX;
143
+ const startWidth = infoPanelWidth;
144
+ setIsResizing(true);
145
+ document.body.style.cursor = 'col-resize';
146
+ document.body.style.userSelect = 'none';
147
+ function onMove(ev: MouseEvent) {
148
+ const newWidth = Math.max(200, Math.min(480, startWidth + (startX - ev.clientX)));
149
+ setInfoPanelWidth(newWidth);
150
+ }
151
+ function onUp() {
152
+ setIsResizing(false);
153
+ document.body.style.cursor = '';
154
+ document.body.style.userSelect = '';
155
+ document.removeEventListener('mousemove', onMove);
156
+ document.removeEventListener('mouseup', onUp);
157
+ }
158
+ document.addEventListener('mousemove', onMove);
159
+ document.addEventListener('mouseup', onUp);
160
+ }
106
161
  const load = useCallback(async (next?: string) => { try { const page: Page<Conversation> = await client.current.listConversations(next); setItems(old => next ? [...old, ...page.items] : page.items); setCursor(page.nextCursor); if (!next && page.items.length) setSelected(old => old ?? (defaultConversationId ? (page.items.find(c => c.id === defaultConversationId) ?? page.items[0]) : page.items[0])); setError(''); } catch (e) { setError(e instanceof Error ? e.message : 'Khรดng tแบฃi ฤ‘ฦฐแปฃc hแป™i thoแบกi'); } finally { setLoading(false); } }, [defaultConversationId]);
107
162
  useEffect(() => { void client.current.listConnections().then(setConnections).catch(() => undefined); void load(); const stop = client.current.connectSSE((type, data) => { if (type === 'message.new' || type === 'conversation.updated') { void load(); if (type === 'message.new') { const evtData = typeof data === 'object' && data ? data as Record<string, unknown> : {}; const evtConvId = evtData['conversationId'] ? String(evtData['conversationId']) : ''; const evtMsgId = evtData['messageId'] ? String(evtData['messageId']) : ''; const evtDirection = evtData['direction'] ? String(evtData['direction']) : ''; if (evtDirection === 'inbound' && !disableNotificationSound) playNotificationSound(); if (evtConvId && evtConvId === selectedId.current && evtMsgId && appendMessageRef.current) { const appendFn = appendMessageRef.current; void client.current.getMessage(evtMsgId).then(msg => { appendFn(msg); }).catch(() => undefined); } onNewMessage?.(evtConvId || selectedId.current || ''); } } else if (type === 'message.status_updated') { setMsgRefreshKey(k => k + 1); } }); return stop; }, [load, onNewMessage]);
108
163
  useEffect(() => { selectedId.current = selected?.id; }, [selected]);
@@ -152,9 +207,9 @@ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(fu
152
207
  fontFamily: theme?.fontFamily ?? 'Inter, ui-sans-serif, system-ui, sans-serif',
153
208
  borderRadius: theme?.borderRadius ?? '16px',
154
209
  gridTemplateColumns: infoOpen
155
- ? 'minmax(260px, 300px) minmax(0, 1fr) 260px'
210
+ ? `minmax(260px, 300px) minmax(0, 1fr) ${infoPanelWidth}px`
156
211
  : 'minmax(260px, 300px) minmax(0, 1fr)',
157
- transition: 'grid-template-columns 220ms ease',
212
+ transition: isResizing ? 'none' : 'grid-template-columns 220ms ease',
158
213
  };
159
214
  if (loading) return <div style={{ ...css.state, borderRadius: theme?.borderRadius ?? '16px' }}><Spinner /> ฤang tแบฃi hแป™p thฦฐโ€ฆ</div>;
160
215
  if (error && !items.length) return <div style={{ ...css.state, color: '#b42318', borderRadius: theme?.borderRadius ?? '16px' }}><AlertCircle size={16} strokeWidth={2} /> {error}<button style={css.retry} onClick={() => { setLoading(true); void load(); }}>Thแปญ lแบกi</button></div>;
@@ -262,6 +317,7 @@ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(fu
262
317
  t={t}
263
318
  disableAttachments={disableAttachments}
264
319
  hideKeyboardHint={hideKeyboardHint}
320
+ extensions={extensions}
265
321
  />
266
322
  ) : <EmptyConversation />}
267
323
  </main>
@@ -271,6 +327,9 @@ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(fu
271
327
  connection={connectionById.get(selected.connectionId)}
272
328
  primary={primary}
273
329
  onClose={() => setInfoOpen(false)}
330
+ client={client.current}
331
+ onStartResize={startInfoResize}
332
+ extensions={extensions}
274
333
  />
275
334
  )}
276
335
  </div>
@@ -331,15 +390,55 @@ function ConversationRow({ conversation, provider, selected, primary, onSelect }
331
390
 
332
391
  type PendingAttachment = { file: File; uploading: boolean; url?: string; mimeType?: string; attachmentType?: string; objectUrl?: string };
333
392
 
334
- function MessagePanel({ conversation, provider, connection, client, primary, error, onRegisterAppend, refreshKey, infoOpen, onToggleInfo, t, disableAttachments, hideKeyboardHint }: { conversation: Conversation; provider?: Provider; connection?: Connection; client: ChannelHubClient; primary: string; error: string; onRegisterAppend?: (fn: ((msg: Message) => void) | null) => void; refreshKey?: number; infoOpen: boolean; onToggleInfo: () => void; t: WidgetTranslations; disableAttachments?: boolean; hideKeyboardHint?: boolean }) {
393
+ function MessagePanel({ conversation, provider, connection, client, primary, error, onRegisterAppend, refreshKey, infoOpen, onToggleInfo, t, disableAttachments, hideKeyboardHint, extensions }: { conversation: Conversation; provider?: Provider; connection?: Connection; client: ChannelHubClient; primary: string; error: string; onRegisterAppend?: (fn: ((msg: Message) => void) | null) => void; refreshKey?: number; infoOpen: boolean; onToggleInfo: () => void; t: WidgetTranslations; disableAttachments?: boolean; hideKeyboardHint?: boolean; extensions?: Extension[] }) {
335
394
  const [messages, setMessages] = useState<Message[]>([]); const [cursor, setCursor] = useState<string>(); const [text, setText] = useState(''); const [loading, setLoading] = useState(true); const [sending, setSending] = useState(false); const [sendError, setSendError] = useState(''); const messageAreaRef = useRef<HTMLDivElement>(null); const name = conversation.contactName ?? conversation.subject ?? conversation.providerConversationKey;
336
- const fileRef = useRef<HTMLInputElement>(null);
395
+ const fileImageRef = useRef<HTMLInputElement>(null);
396
+ const fileDocRef = useRef<HTMLInputElement>(null);
337
397
  const [pendingAttachment, setPendingAttachment] = useState<PendingAttachment | null>(null);
398
+ const [boldActive, setBoldActive] = useState(false);
399
+ const [italicActive, setItalicActive] = useState(false);
400
+ const [emojiOpen, setEmojiOpen] = useState(false);
401
+ const [emojiCategory, setEmojiCategory] = useState(0);
402
+ const emojiPickerRef = useRef<HTMLDivElement>(null);
403
+ const emojiBtnRef = useRef<HTMLButtonElement>(null);
404
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
405
+ const [templateOpen, setTemplateOpen] = useState(false);
406
+ const [templateSearch, setTemplateSearch] = useState('');
407
+ const [templates, setTemplates] = useState<{ id: string; title: string; content: string; shortcut: string | null }[]>([]);
408
+ const templatePickerRef = useRef<HTMLDivElement>(null);
409
+ const templateBtnRef = useRef<HTMLButtonElement>(null);
338
410
 
339
411
  useEffect(() => {
340
412
  return () => { if (pendingAttachment?.objectUrl) URL.revokeObjectURL(pendingAttachment.objectUrl); };
341
413
  }, [pendingAttachment?.objectUrl]);
342
414
 
415
+ useEffect(() => {
416
+ if (!emojiOpen) return;
417
+ function handleOutside(e: MouseEvent) {
418
+ if (emojiBtnRef.current?.contains(e.target as Node)) return;
419
+ if (emojiPickerRef.current?.contains(e.target as Node)) return;
420
+ setEmojiOpen(false);
421
+ }
422
+ document.addEventListener('mousedown', handleOutside);
423
+ return () => document.removeEventListener('mousedown', handleOutside);
424
+ }, [emojiOpen]);
425
+
426
+ useEffect(() => {
427
+ void client.listCannedResponses().then(setTemplates).catch(() => undefined);
428
+ }, [client]);
429
+
430
+ useEffect(() => {
431
+ if (!templateOpen) return;
432
+ function handleOutside(e: MouseEvent) {
433
+ if (templateBtnRef.current?.contains(e.target as Node)) return;
434
+ if (templatePickerRef.current?.contains(e.target as Node)) return;
435
+ setTemplateOpen(false);
436
+ }
437
+ document.addEventListener('mousedown', handleOutside);
438
+ return () => document.removeEventListener('mousedown', handleOutside);
439
+ }, [templateOpen]);
440
+
441
+
343
442
  const shouldScrollToBottom = useRef(true);
344
443
 
345
444
  const load = useCallback(async (next?: string, silent?: boolean) => {
@@ -403,6 +502,32 @@ function MessagePanel({ conversation, provider, connection, client, primary, err
403
502
  } catch (e) { setSendError(e instanceof Error ? e.message : 'Khรดng gแปญi ฤ‘ฦฐแปฃc tin nhแบฏn'); } finally { setSending(false); }
404
503
  }
405
504
 
505
+ function insertEmoji(emoji: string) {
506
+ const ta = textareaRef.current;
507
+ if (!ta) { setText(t => t + emoji); setEmojiOpen(false); return; }
508
+ const start = ta.selectionStart ?? text.length;
509
+ const end = ta.selectionEnd ?? text.length;
510
+ const newText = text.slice(0, start) + emoji + text.slice(end);
511
+ setText(newText);
512
+ setEmojiOpen(false);
513
+ requestAnimationFrame(() => {
514
+ ta.focus();
515
+ ta.selectionStart = ta.selectionEnd = start + emoji.length;
516
+ });
517
+ }
518
+
519
+ function insertTemplate(content: string) {
520
+ setText(content);
521
+ setTemplateOpen(false);
522
+ setTemplateSearch('');
523
+ requestAnimationFrame(() => {
524
+ const ta = textareaRef.current;
525
+ if (!ta) return;
526
+ ta.focus();
527
+ ta.selectionStart = ta.selectionEnd = content.length;
528
+ });
529
+ }
530
+
406
531
  const canSend = !sending && (text.trim().length > 0 || (pendingAttachment?.url != null && !pendingAttachment.uploading));
407
532
 
408
533
  return (
@@ -435,10 +560,157 @@ function MessagePanel({ conversation, provider, connection, client, primary, err
435
560
  {cursor && <button onClick={() => void load(cursor)} style={css.historyButton}>{t.loadOlder}</button>}
436
561
  {loading && <div style={css.messageHint}><Spinner /> {t.loading}</div>}
437
562
  {!loading && !messages.length && <div style={css.messageHint}>{t.noMessages}</div>}
438
- {messages.map(m => <MessageBubble key={m.id} message={m} primary={primary} />)}
563
+ {messages.map((m, idx) => {
564
+ const enrichments = extensions?.flatMap(e => e.messageEnrichments ?? []) ?? [];
565
+ const shouldEnrich = m.direction === 'inbound' && enrichments.length > 0 && idx >= messages.length - 15;
566
+ return (
567
+ <div key={m.id}>
568
+ <MessageBubble message={m} primary={primary} />
569
+ {shouldEnrich && enrichments.map((enrich, i) => {
570
+ const match = m.text?.match(enrich.pattern);
571
+ if (!match) return null;
572
+ return <ExtErrorBoundary key={i}>{enrich.render(match, buildCtx(conversation))}</ExtErrorBoundary>;
573
+ })}
574
+ </div>
575
+ );
576
+ })}
439
577
  </ScrollArea>
440
- <form onSubmit={send} style={css.composer}>
441
- <div style={css.composerBox}>
578
+ {/* Quick reply chips */}
579
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', padding: '6px 14px 2px', borderTop: `1px solid ${c.line}` }}>
580
+ {['Cแบฃm ฦกn bแบกn ฤ‘รฃ liรชn hแป‡ ๐Ÿ™', 'Mรฌnh sแบฝ kiแปƒm tra ngay', 'Vui lรฒng chแป 1-2 phรบt'].map(chip => (
581
+ <button
582
+ key={chip}
583
+ type="button"
584
+ onClick={() => setText(chip)}
585
+ style={{
586
+ fontSize: 11, padding: '3px 10px', borderRadius: 999,
587
+ background: `${primary}0f`, color: primary,
588
+ border: `1px solid ${primary}33`,
589
+ cursor: 'pointer', whiteSpace: 'nowrap' as const,
590
+ }}
591
+ >
592
+ {chip}
593
+ </button>
594
+ ))}
595
+ </div>
596
+ <form onSubmit={send} style={{ flex: '0 0 auto', padding: '8px 14px 12px', borderTop: `1px solid ${c.line}`, background: c.white, position: 'relative' }}>
597
+ {/* Emoji picker popover โ€” absolute positioned above composer */}
598
+ {emojiOpen && (
599
+ <div
600
+ ref={emojiPickerRef}
601
+ style={{
602
+ position: 'absolute',
603
+ bottom: 'calc(100% + 6px)',
604
+ left: 0,
605
+ zIndex: 100,
606
+ background: c.white,
607
+ border: `1px solid ${c.line}`,
608
+ borderRadius: 12,
609
+ boxShadow: '0 8px 24px rgba(23,32,51,.14)',
610
+ width: 280,
611
+ overflow: 'hidden',
612
+ fontFamily: 'inherit',
613
+ }}
614
+ >
615
+ {/* Category tabs */}
616
+ <div style={{ display: 'flex', borderBottom: `1px solid ${c.line}`, background: '#f9fafb' }}>
617
+ {EMOJI_CATEGORIES.map((cat, i) => (
618
+ <button
619
+ key={i}
620
+ type="button"
621
+ onClick={() => setEmojiCategory(i)}
622
+ style={{
623
+ flex: 1, border: 0, background: 'transparent', padding: '7px 2px',
624
+ fontSize: 16, cursor: 'pointer', lineHeight: 1,
625
+ borderBottom: emojiCategory === i ? `2px solid ${primary}` : '2px solid transparent',
626
+ opacity: emojiCategory === i ? 1 : 0.5,
627
+ transition: 'opacity 100ms ease',
628
+ }}
629
+ >
630
+ {cat.icon}
631
+ </button>
632
+ ))}
633
+ </div>
634
+ {/* Emoji grid */}
635
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: 2, padding: 8, maxHeight: 180, overflowY: 'auto' }}>
636
+ {EMOJI_CATEGORIES[emojiCategory]?.emojis.map((emoji, i) => (
637
+ <button
638
+ key={i}
639
+ type="button"
640
+ onClick={() => insertEmoji(emoji)}
641
+ style={{
642
+ border: 0, background: 'transparent', padding: '5px 2px',
643
+ fontSize: 18, cursor: 'pointer', borderRadius: 6, lineHeight: 1,
644
+ transition: 'background 80ms ease',
645
+ }}
646
+ onMouseEnter={e => { (e.target as HTMLElement).style.background = '#f3f4f6'; }}
647
+ onMouseLeave={e => { (e.target as HTMLElement).style.background = 'transparent'; }}
648
+ >
649
+ {emoji}
650
+ </button>
651
+ ))}
652
+ </div>
653
+ </div>
654
+ )}
655
+ {templateOpen && (
656
+ <div
657
+ ref={templatePickerRef}
658
+ style={{
659
+ position: 'absolute',
660
+ bottom: 'calc(100% + 6px)',
661
+ left: 0,
662
+ zIndex: 100,
663
+ background: c.white,
664
+ border: `1px solid ${c.line}`,
665
+ borderRadius: 12,
666
+ boxShadow: '0 8px 24px rgba(23,32,51,.14)',
667
+ width: 300,
668
+ overflow: 'hidden',
669
+ fontFamily: 'inherit',
670
+ }}
671
+ >
672
+ <div style={{ padding: '8px 10px', borderBottom: `1px solid ${c.line}` }}>
673
+ <input
674
+ autoFocus
675
+ type="text"
676
+ placeholder="Tรฌm templateโ€ฆ"
677
+ value={templateSearch}
678
+ onChange={e => setTemplateSearch(e.target.value)}
679
+ style={{ width: '100%', boxSizing: 'border-box' as const, border: `1px solid ${c.line}`, borderRadius: 7, padding: '5px 8px', fontSize: 12, outline: 'none', fontFamily: 'inherit', color: c.ink }}
680
+ />
681
+ </div>
682
+ <div style={{ maxHeight: 220, overflowY: 'auto' }}>
683
+ {(() => {
684
+ const q = templateSearch.trim().toLowerCase();
685
+ const filtered = q ? templates.filter(t => t.title.toLowerCase().includes(q) || t.content.toLowerCase().includes(q) || (t.shortcut ?? '').toLowerCase().includes(q)) : templates;
686
+ if (!filtered.length) return (
687
+ <div style={{ padding: '24px 16px', textAlign: 'center' as const, color: c.muted, fontSize: 12 }}>
688
+ {templates.length === 0 ? 'Chฦฐa cรณ template nร o' : 'Khรดng tรฌm thแบฅy'}
689
+ </div>
690
+ );
691
+ return filtered.map(tpl => (
692
+ <button
693
+ key={tpl.id}
694
+ type="button"
695
+ onClick={() => insertTemplate(tpl.content)}
696
+ style={{ display: 'block', width: '100%', textAlign: 'left' as const, border: 0, borderBottom: `1px solid ${c.line}`, background: 'transparent', padding: '9px 12px', cursor: 'pointer', fontFamily: 'inherit' }}
697
+ onMouseEnter={e => { (e.currentTarget as HTMLElement).style.background = '#f7f9fc'; }}
698
+ onMouseLeave={e => { (e.currentTarget as HTMLElement).style.background = 'transparent'; }}
699
+ >
700
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
701
+ <span style={{ fontSize: 12, fontWeight: 600, color: c.ink }}>{tpl.title}</span>
702
+ {tpl.shortcut && <span style={{ fontSize: 10, color: primary, background: `${primary}18`, borderRadius: 4, padding: '1px 5px' }}>{tpl.shortcut}</span>}
703
+ </div>
704
+ <div style={{ fontSize: 11, color: c.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' as const }}>{tpl.content}</div>
705
+ </button>
706
+ ));
707
+ })()}
708
+ </div>
709
+ </div>
710
+ )}
711
+ <div style={{ border: `1.5px solid ${c.line}`, borderRadius: 12, background: c.white, overflow: 'hidden' }}>
712
+
713
+ {/* Attachment preview */}
442
714
  {pendingAttachment && (
443
715
  <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', borderBottom: `1px solid ${c.line}`, fontSize: 12 }}>
444
716
  {pendingAttachment.uploading
@@ -452,14 +724,120 @@ function MessagePanel({ conversation, provider, connection, client, primary, err
452
724
  )}
453
725
  </div>
454
726
  )}
455
- <Textarea aria-label="Soแบกn tin nhแบฏn" rows={1} value={text} onChange={e => setText(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send(e); } }} placeholder={t.sendPlaceholder} style={css.textarea} />
456
- <div style={css.composerTools}>
457
- {!hideKeyboardHint && <span>โ†ต Gแปญi ยท โ‡งโ†ต Xuแป‘ng dรฒng</span>}
458
- {!disableAttachments && <button type="button" style={css.iconButton} aria-label="ฤรญnh kรจm tแป‡p" onClick={() => fileRef.current?.click()}><Paperclip size={16} strokeWidth={2} /></button>}
459
- {!disableAttachments && <input ref={fileRef} type="file" style={{ display: 'none' }} onChange={handleFileSelect} accept="image/jpeg,image/png,image/gif,image/webp,application/pdf,video/mp4,audio/mpeg,audio/ogg" />}
727
+
728
+ {/* Toolbar */}
729
+ <div style={{ display: 'flex', alignItems: 'center', gap: 2, padding: '4px 8px', borderBottom: `1px solid #f3f4f6` }}>
730
+ {/* Emoji */}
731
+ <button
732
+ ref={emojiBtnRef}
733
+ type="button"
734
+ title="Chรจn emoji"
735
+ onClick={() => setEmojiOpen(o => !o)}
736
+ style={{ ...css.toolbarBtn, background: emojiOpen ? `${primary}18` : 'transparent', color: emojiOpen ? primary : '#9ca3af' }}
737
+ >
738
+ <Smile size={13} strokeWidth={2} />
739
+ </button>
740
+ {/* Image/Video button */}
741
+ {!disableAttachments && (
742
+ <button type="button" title="Gแปญi แบฃnh / video" aria-label="Gแปญi แบฃnh hoแบทc video" style={css.toolbarBtn} onClick={() => fileImageRef.current?.click()}>
743
+ <Image size={13} strokeWidth={2} />
744
+ </button>
745
+ )}
746
+ {/* File button */}
747
+ {!disableAttachments && (
748
+ <button type="button" title="Gแปญi tแป‡p ฤ‘รญnh kรจm" aria-label="Gแปญi tแป‡p ฤ‘รญnh kรจm" style={css.toolbarBtn} onClick={() => fileDocRef.current?.click()}>
749
+ <Paperclip size={13} strokeWidth={2} />
750
+ </button>
751
+ )}
752
+ {!disableAttachments && (
753
+ <>
754
+ <input ref={fileImageRef} type="file" style={{ display: 'none' }} onChange={handleFileSelect} accept="image/*,video/mp4" />
755
+ <input ref={fileDocRef} type="file" style={{ display: 'none' }} onChange={handleFileSelect} accept=".pdf,audio/mpeg,audio/ogg,application/octet-stream,application/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" />
756
+ </>
757
+ )}
758
+ {/* Template */}
759
+ <button
760
+ ref={templateBtnRef}
761
+ type="button"
762
+ title="Template nhanh"
763
+ onClick={() => { setTemplateOpen(o => !o); setTemplateSearch(''); }}
764
+ style={{ ...css.toolbarBtn, background: templateOpen ? `${primary}18` : 'transparent', color: templateOpen ? primary : '#9ca3af' }}
765
+ >
766
+ <Zap size={13} strokeWidth={2} />
767
+ </button>
768
+ {/* Separator */}
769
+ <span style={{ width: 1, height: 14, background: '#e5e7eb', margin: '0 2px' }} />
770
+ {/* Bold */}
771
+ <button type="button" title="In ฤ‘แบญm" onClick={() => setBoldActive(b => !b)}
772
+ style={{ ...css.toolbarBtn, fontWeight: 700, fontSize: 12, background: boldActive ? `${primary}18` : 'transparent', color: boldActive ? primary : '#9ca3af', border: boldActive ? `1px solid ${primary}33` : '1px solid transparent' }}>
773
+ B
774
+ </button>
775
+ {/* Italic */}
776
+ <button type="button" title="Nghiรชng" onClick={() => setItalicActive(i => !i)}
777
+ style={{ ...css.toolbarBtn, fontStyle: 'italic', fontSize: 12, background: italicActive ? `${primary}18` : 'transparent', color: italicActive ? primary : '#9ca3af', border: italicActive ? `1px solid ${primary}33` : '1px solid transparent' }}>
778
+ I
779
+ </button>
780
+ {extensions?.flatMap(e => e.toolbarActions ?? []).map((action, i) => (
781
+ <button key={i} type="button" title={action.tooltip} style={css.toolbarBtn}
782
+ onClick={() => { const insertText = (t: string) => setText(prev => prev + t); void action.onClick({ ...buildCtx(conversation), insertText }); }}>
783
+ {action.icon}
784
+ </button>
785
+ ))}
786
+ </div>
787
+
788
+ {/* Textarea */}
789
+ <Textarea
790
+ ref={textareaRef}
791
+ aria-label="Soแบกn tin nhแบฏn"
792
+ rows={2}
793
+ value={text}
794
+ onChange={e => setText(e.target.value)}
795
+ onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send(e); } }}
796
+ placeholder={t.sendPlaceholder}
797
+ style={{
798
+ display: 'block', width: '100%', minWidth: 0, boxSizing: 'border-box' as const,
799
+ minHeight: 52, maxHeight: 120, resize: 'none' as const,
800
+ border: 0, outline: 0,
801
+ background: 'transparent',
802
+ color: c.ink,
803
+ padding: '8px 12px 4px',
804
+ font: 'inherit', fontSize: 13, lineHeight: 1.45,
805
+ fontStyle: italicActive ? 'italic' : 'normal',
806
+ fontWeight: boldActive ? 700 : 400,
807
+ }}
808
+ />
809
+
810
+ {/* Bottom bar */}
811
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 8px 6px 12px' }}>
812
+ <span style={{
813
+ fontSize: 11,
814
+ color: text.length > 1000 ? '#ef4444' : text.length > 900 ? '#f59e0b' : '#9ca3af',
815
+ fontWeight: text.length > 1000 ? 600 : 400,
816
+ }}>
817
+ {text.length}/1000
818
+ </span>
819
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
820
+ {!hideKeyboardHint && <span style={{ fontSize: 10, color: '#9ca3af' }}>โ†ต Gแปญi ยท โ‡งโ†ต Xuแป‘ng dรฒng</span>}
821
+ <button
822
+ disabled={!canSend}
823
+ aria-label="Gแปญi tin nhแบฏn"
824
+ style={{
825
+ display: 'flex', alignItems: 'center', gap: 5,
826
+ padding: '5px 12px', border: 0, borderRadius: 999,
827
+ fontSize: 12, fontWeight: 600,
828
+ background: !canSend ? '#e5e7eb' : `linear-gradient(135deg,${primary},#0ea5e9)`,
829
+ color: !canSend ? '#9ca3af' : '#fff',
830
+ cursor: !canSend ? 'not-allowed' : 'pointer',
831
+ boxShadow: canSend ? '0 2px 8px rgba(37,99,235,0.25)' : 'none',
832
+ transition: 'all 150ms ease',
833
+ }}
834
+ >
835
+ {sending ? <Loader2 size={12} style={{ animation: 'channelhub-spin .7s linear infinite' }} /> : <Send size={12} strokeWidth={2} />}
836
+ {t.send}
837
+ </button>
838
+ </div>
460
839
  </div>
461
840
  </div>
462
- <button disabled={!canSend} aria-label="Gแปญi tin nhแบฏn" style={{ ...css.send, background: primary, opacity: !canSend ? .5 : 1, cursor: !canSend ? 'not-allowed' : 'pointer' }}><Send size={16} strokeWidth={2} /></button>
463
841
  </form>
464
842
  {(sendError || error) && <div role="alert" style={css.error}>{sendError || error}</div>}
465
843
  </section>
@@ -561,19 +939,74 @@ function ContactInfoPanel({
561
939
  connection,
562
940
  primary,
563
941
  onClose,
942
+ client,
943
+ onStartResize,
944
+ extensions,
564
945
  }: {
565
946
  conversation: Conversation;
566
947
  connection?: Connection;
567
948
  primary: string;
568
949
  onClose: () => void;
950
+ client: ChannelHubClient;
951
+ onStartResize?: (e: React.MouseEvent) => void;
952
+ extensions?: Extension[];
569
953
  }) {
570
954
  const name = conversation.contactName ?? conversation.subject ?? conversation.providerConversationKey;
571
955
  const provider = connection?.provider;
572
956
  const [expanded, setExpanded] = useState<Record<string, boolean>>({ channel: true, stats: false, extra: false });
573
957
  const toggle = (key: string) => setExpanded(e => ({ ...e, [key]: !e[key] }));
958
+ const [noteText, setNoteText] = useState('');
959
+ const [noteSaving, setNoteSaving] = useState(false);
960
+ const [noteSaved, setNoteSaved] = useState(false);
961
+ const [noteError, setNoteError] = useState('');
962
+ const [extRows, setExtRows] = useState<ContactInfoRow[]>([]);
963
+
964
+ useEffect(() => {
965
+ setNoteText('');
966
+ setNoteSaved(false);
967
+ setNoteError('');
968
+ client.getNote(conversation.id)
969
+ .then(note => { if (note) setNoteText(note.content); })
970
+ .catch(() => undefined);
971
+ }, [conversation.id, client]);
972
+
973
+ useEffect(() => {
974
+ if (!extensions?.some(e => e.contactInfoRows)) return;
975
+ const ctx = buildCtx(conversation);
976
+ setExtRows([]);
977
+ void Promise.allSettled(
978
+ extensions.filter(e => e.contactInfoRows).map(e => e.contactInfoRows!(ctx))
979
+ ).then(results => {
980
+ const rows = results
981
+ .filter((r): r is PromiseFulfilledResult<ContactInfoRow[]> => r.status === 'fulfilled')
982
+ .flatMap(r => r.value);
983
+ setExtRows(rows);
984
+ });
985
+ }, [conversation.id, extensions]);
986
+
987
+ async function saveNote() {
988
+ if (!noteText.trim() || noteSaving) return;
989
+ setNoteSaving(true);
990
+ setNoteError('');
991
+ try {
992
+ await client.upsertNote(conversation.id, noteText.trim());
993
+ setNoteSaved(true);
994
+ setTimeout(() => setNoteSaved(false), 2000);
995
+ } catch {
996
+ setNoteError('Lฦฐu thแบฅt bแบกi');
997
+ } finally {
998
+ setNoteSaving(false);
999
+ }
1000
+ }
574
1001
 
575
1002
  return (
576
- <aside style={css.infoPanel}>
1003
+ <aside style={{ ...css.infoPanel, position: 'relative' }}>
1004
+ <div
1005
+ onMouseDown={onStartResize}
1006
+ style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 4, cursor: 'col-resize', zIndex: 1 }}
1007
+ onMouseEnter={e => { (e.currentTarget as HTMLElement).style.background = 'rgba(0,0,0,0.07)'; }}
1008
+ onMouseLeave={e => { (e.currentTarget as HTMLElement).style.background = ''; }}
1009
+ />
577
1010
  <div style={css.infoPanelHeader}>
578
1011
  <span style={{ fontWeight: 600, fontSize: 13, color: c.ink }}>Thรดng tin liรชn hแป‡</span>
579
1012
  <button style={css.iconButton} onClick={onClose} aria-label="ฤรณng">
@@ -632,11 +1065,49 @@ function ContactInfoPanel({
632
1065
  <InfoRow label="ฤiแป‡n thoแบกi" value="โ€” chฦฐa cรณ" valueMuted />
633
1066
  <InfoRow label="Email" value="โ€” chฦฐa cรณ" valueMuted />
634
1067
  <InfoRow label="Nhรฃn" value="โ€” chฦฐa cรณ" valueMuted />
1068
+ {extRows.map(row => (
1069
+ <InfoRow key={row.label} label={row.label}>
1070
+ {row.href
1071
+ ? <a href={row.href} target="_blank" rel="noopener noreferrer" style={{ color: primary, fontSize: 12 }}>{row.value}</a>
1072
+ : <span style={{ fontSize: 12 }}>{row.value}</span>
1073
+ }
1074
+ </InfoRow>
1075
+ ))}
635
1076
  </InfoSection>
636
1077
 
637
1078
  <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
638
1079
  <button style={{ ...css.ghostButton, color: primary, borderColor: `${primary}33` }}>Xem lแป‹ch sแปญ</button>
639
- <button style={{ ...css.ghostButton, color: primary, borderColor: `${primary}33` }}>Thรชm ghi chรบ</button>
1080
+ {extensions?.flatMap(e => e.sidebarActions ?? []).map((action, i) => (
1081
+ <button key={i} style={{ ...css.ghostButton, color: c.ink, borderColor: c.line, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}
1082
+ onClick={() => { void action.onClick(buildCtx(conversation)); }}>
1083
+ {action.icon}
1084
+ {action.label}
1085
+ </button>
1086
+ ))}
1087
+ <div style={{ border: '1.5px solid #000', borderRadius: 10, background: '#fff', overflow: 'hidden' }}>
1088
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '7px 10px', borderBottom: '1px solid #fde68a', fontSize: 11, fontWeight: 600, color: '#92400e' }}>
1089
+ Ghi chรบ nแป™i bแป™
1090
+ </div>
1091
+ <textarea
1092
+ value={noteText}
1093
+ onChange={e => setNoteText(e.target.value)}
1094
+ placeholder="Nhแบญp ghi chรบ..."
1095
+ rows={3}
1096
+ style={{ display: 'block', width: '100%', boxSizing: 'border-box' as const, border: 0, outline: 0, background: 'transparent', resize: 'none' as const, padding: '8px 10px', font: 'inherit', fontSize: 12, color: c.ink, lineHeight: 1.5 }}
1097
+ />
1098
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 10px 6px' }}>
1099
+ {noteSaved
1100
+ ? <span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: '#16a34a' }}><Check size={11} strokeWidth={2.5} /> ฤรฃ lฦฐu</span>
1101
+ : noteError
1102
+ ? <span style={{ fontSize: 11, color: '#ef4444' }}>{noteError}</span>
1103
+ : <span />
1104
+ }
1105
+ <button type="button" onClick={() => { void saveNote(); }} disabled={!noteText.trim() || noteSaving}
1106
+ style={{ padding: '4px 12px', border: 0, borderRadius: 7, fontSize: 12, fontWeight: 600, background: noteText.trim() && !noteSaving ? 'linear-gradient(135deg,#f59e0b,#fbbf24)' : '#e5e7eb', color: noteText.trim() && !noteSaving ? '#fff' : '#9ca3af', cursor: noteText.trim() && !noteSaving ? 'pointer' : 'not-allowed' }}>
1107
+ {noteSaving ? 'ฤang lฦฐuโ€ฆ' : 'Lฦฐu ghi chรบ'}
1108
+ </button>
1109
+ </div>
1110
+ </div>
640
1111
  </div>
641
1112
  </div>
642
1113
  </aside>
@@ -761,7 +1232,7 @@ const css: Record<string, React.CSSProperties> = {
761
1232
  state: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, minHeight: 180, border: `1px solid ${c.line}`, background: c.white, color: c.muted, fontSize: 13 },
762
1233
  retry: { border: 0, borderRadius: 7, padding: '7px 10px', background: '#eff4ff', color: '#315dbb', cursor: 'pointer' },
763
1234
  spinner: { display: 'inline-block', width: 14, height: 14, border: '2px solid #dbe3f3', borderTopColor: '#5277d7', borderRadius: '50%', animation: 'channelhub-spin .7s linear infinite' },
764
- composerTools: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 8px 4px 12px', color: '#a0aabd', fontSize: 12 },
1235
+ toolbarBtn: { display: 'inline-grid', placeItems: 'center', width: 26, height: 26, border: '1px solid transparent', borderRadius: 6, background: 'transparent', color: '#9ca3af', cursor: 'pointer', padding: 0, lineHeight: 1 } as React.CSSProperties,
765
1236
  infoPanel: { display: 'flex', flexDirection: 'column', borderLeft: `1px solid ${c.line}`, background: c.white, minHeight: 0, overflow: 'hidden' },
766
1237
  infoPanelHeader: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 16px 12px', borderBottom: `1px solid ${c.line}`, flex: '0 0 auto' },
767
1238
  infoPanelIdentity: { display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '20px 16px 16px', gap: 4 },