@channelhub/widget 0.1.7 → 0.1.9

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.
@@ -0,0 +1,348 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import type { ReactNode } from 'react';
3
+ import { MessageCircle } from 'lucide-react';
4
+ import { ChannelHubClient } from './api.js';
5
+ import { Avatar as UiAvatar } from './components/ui/index.js';
6
+ import type { Conversation, Provider, WidgetTheme } from './types.js';
7
+
8
+ export type ChannelHubNotificationBellProps = {
9
+ apiUrl: string;
10
+ token: string;
11
+ theme?: WidgetTheme;
12
+ locale?: 'vi' | 'en';
13
+ /** Custom trigger icon — defaults to MessageCircle. Receives `{ size, color }` for convenience */
14
+ icon?: ReactNode | ((props: { size: number; color: string }) => ReactNode);
15
+ /** Fired when user clicks a conversation row */
16
+ onConversationSelect?: (conversationId: string, conversation: Conversation) => void;
17
+ };
18
+
19
+ function initials(name: string) {
20
+ return name.split(/\s+/).filter(Boolean).slice(-2).map(x => x[0]).join('').toUpperCase() || '?';
21
+ }
22
+
23
+ function formatTime(value?: string) {
24
+ if (!value) return '';
25
+ const d = new Date(value);
26
+ if (d.toDateString() === new Date().toDateString()) {
27
+ return d.toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' });
28
+ }
29
+ return d.toLocaleDateString('vi-VN', { day: '2-digit', month: '2-digit' });
30
+ }
31
+
32
+ const providerColor: Partial<Record<string, string>> = {
33
+ facebook: '#1877f2',
34
+ instagram: '#e1306c',
35
+ telegram: '#2aabee',
36
+ zalo: '#0068ff',
37
+ livechat: '#6366f1',
38
+ };
39
+
40
+ function ProviderDot({ provider, apiUrl }: { provider?: Provider; apiUrl: string }) {
41
+ if (!provider) return null;
42
+ return (
43
+ <img
44
+ src={`${apiUrl}/static/logos/${provider === 'livechat' ? 'web' : provider}.avif`}
45
+ alt={provider as string}
46
+ width={14}
47
+ height={14}
48
+ style={{ borderRadius: '50%', objectFit: 'cover', display: 'block', border: '1.5px solid #fff' }}
49
+ />
50
+ );
51
+ }
52
+
53
+ export function ChannelHubNotificationBell({
54
+ apiUrl,
55
+ token,
56
+ theme,
57
+ locale = 'vi',
58
+ icon,
59
+ onConversationSelect,
60
+ }: ChannelHubNotificationBellProps) {
61
+ const primary = theme?.primaryColor ?? '#2563eb';
62
+ const triggerIcon = typeof icon === 'function'
63
+ ? icon({ size: 20, color: 'currentColor' })
64
+ : (icon ?? <MessageCircle size={20} strokeWidth={1.8} />);
65
+ const client = useRef(new ChannelHubClient(apiUrl, token));
66
+
67
+ const [open, setOpen] = useState(false);
68
+ const [conversations, setConversations] = useState<Conversation[]>([]);
69
+ const bellRef = useRef<HTMLButtonElement>(null);
70
+ const panelRef = useRef<HTMLDivElement>(null);
71
+
72
+ const unread = conversations.filter(c => (c.unreadCount ?? 0) > 0);
73
+ const totalUnread = unread.reduce((s, c) => s + (c.unreadCount ?? 0), 0);
74
+
75
+ const load = useCallback(async () => {
76
+ try {
77
+ const page = await client.current.listConversations();
78
+ setConversations(page.items);
79
+ } catch {
80
+ // silent — bell degrades gracefully
81
+ }
82
+ }, []);
83
+
84
+ // Initial load + SSE refresh
85
+ useEffect(() => {
86
+ void load();
87
+ const stop = client.current.connectSSE((type) => {
88
+ if (type === 'message.new' || type === 'conversation.updated') {
89
+ void load();
90
+ }
91
+ });
92
+ return stop;
93
+ }, [load]);
94
+
95
+ // Close on outside click
96
+ useEffect(() => {
97
+ if (!open) return;
98
+ const handler = (e: MouseEvent) => {
99
+ if (bellRef.current?.contains(e.target as Node)) return;
100
+ if (panelRef.current?.contains(e.target as Node)) return;
101
+ setOpen(false);
102
+ };
103
+ document.addEventListener('mousedown', handler);
104
+ return () => document.removeEventListener('mousedown', handler);
105
+ }, [open]);
106
+
107
+ const handleSelect = async (conv: Conversation) => {
108
+ setOpen(false);
109
+ onConversationSelect?.(conv.id, conv);
110
+ if ((conv.unreadCount ?? 0) > 0) {
111
+ try {
112
+ await client.current.markRead(conv.id);
113
+ setConversations(prev =>
114
+ prev.map(c => c.id === conv.id ? { ...c, unreadCount: 0 } : c),
115
+ );
116
+ } catch {
117
+ // silent
118
+ }
119
+ }
120
+ };
121
+
122
+ const label = locale === 'en'
123
+ ? `${totalUnread} unread message${totalUnread !== 1 ? 's' : ''}`
124
+ : `${totalUnread} tin nhắn chưa đọc`;
125
+
126
+ const emptyLabel = locale === 'en' ? 'No unread messages' : 'Không có tin nhắn mới';
127
+ const headerLabel = locale === 'en' ? 'Messages' : 'Tin nhắn';
128
+
129
+ return (
130
+ <div style={{ position: 'relative', display: 'inline-block', fontFamily: theme?.fontFamily ?? 'Inter, ui-sans-serif, system-ui, sans-serif' }}>
131
+ {/* Bell button */}
132
+ <button
133
+ ref={bellRef}
134
+ aria-label={label}
135
+ aria-haspopup="true"
136
+ aria-expanded={open}
137
+ onClick={() => setOpen(o => !o)}
138
+ style={{
139
+ position: 'relative',
140
+ display: 'inline-grid',
141
+ placeItems: 'center',
142
+ width: 40,
143
+ height: 40,
144
+ border: 0,
145
+ borderRadius: '50%',
146
+ background: open ? `${primary}18` : 'transparent',
147
+ color: open ? primary : '#6b7280',
148
+ cursor: 'pointer',
149
+ transition: 'background 150ms ease, color 150ms ease',
150
+ }}
151
+ >
152
+ {triggerIcon}
153
+ {totalUnread > 0 && (
154
+ <span
155
+ aria-hidden="true"
156
+ style={{
157
+ position: 'absolute',
158
+ top: 4,
159
+ right: 4,
160
+ minWidth: 16,
161
+ height: 16,
162
+ borderRadius: 999,
163
+ background: '#ef4444',
164
+ color: '#fff',
165
+ fontSize: 10,
166
+ fontWeight: 800,
167
+ lineHeight: '16px',
168
+ textAlign: 'center',
169
+ padding: '0 4px',
170
+ border: '2px solid #fff',
171
+ boxSizing: 'border-box',
172
+ }}
173
+ >
174
+ {totalUnread > 99 ? '99+' : totalUnread}
175
+ </span>
176
+ )}
177
+ </button>
178
+
179
+ {/* Dropdown panel */}
180
+ {open && (
181
+ <div
182
+ ref={panelRef}
183
+ role="dialog"
184
+ aria-label={headerLabel}
185
+ style={{
186
+ position: 'absolute',
187
+ top: 'calc(100% + 8px)',
188
+ right: 0,
189
+ zIndex: 9999,
190
+ width: 360,
191
+ maxHeight: 480,
192
+ background: '#fff',
193
+ border: '1px solid #e7ebf2',
194
+ borderRadius: 14,
195
+ boxShadow: '0 12px 40px rgba(23,32,51,.14)',
196
+ overflow: 'hidden',
197
+ display: 'flex',
198
+ flexDirection: 'column',
199
+ }}
200
+ >
201
+ {/* Header */}
202
+ <div style={{
203
+ display: 'flex',
204
+ alignItems: 'center',
205
+ justifyContent: 'space-between',
206
+ padding: '14px 16px 10px',
207
+ borderBottom: '1px solid #e7ebf2',
208
+ }}>
209
+ <span style={{ fontSize: 16, fontWeight: 700, color: '#172033' }}>{headerLabel}</span>
210
+ {totalUnread > 0 && (
211
+ <span style={{
212
+ fontSize: 11, fontWeight: 600,
213
+ background: `${primary}14`, color: primary,
214
+ borderRadius: 999, padding: '2px 8px',
215
+ }}>
216
+ {totalUnread} {locale === 'en' ? 'unread' : 'chưa đọc'}
217
+ </span>
218
+ )}
219
+ </div>
220
+
221
+ {/* List */}
222
+ <div style={{ overflowY: 'auto', flex: 1 }}>
223
+ {unread.length === 0 ? (
224
+ <div style={{
225
+ display: 'flex', flexDirection: 'column', alignItems: 'center',
226
+ gap: 8, padding: '40px 24px', color: '#9aa5b5',
227
+ }}>
228
+ <MessageCircle size={28} strokeWidth={1.5} />
229
+ <span style={{ fontSize: 13 }}>{emptyLabel}</span>
230
+ </div>
231
+ ) : (
232
+ unread.map(conv => (
233
+ <ConversationNotifRow
234
+ key={conv.id}
235
+ conversation={conv}
236
+ primary={primary}
237
+ apiUrl={apiUrl}
238
+ onSelect={handleSelect}
239
+ />
240
+ ))
241
+ )}
242
+ </div>
243
+ </div>
244
+ )}
245
+ </div>
246
+ );
247
+ }
248
+
249
+ function ConversationNotifRow({
250
+ conversation,
251
+ primary,
252
+ apiUrl,
253
+ onSelect,
254
+ }: {
255
+ conversation: Conversation;
256
+ primary: string;
257
+ apiUrl: string;
258
+ onSelect: (conv: Conversation) => void;
259
+ }) {
260
+ const [hovered, setHovered] = useState(false);
261
+ const name = conversation.contactName ?? conversation.providerConversationKey;
262
+ const unread = conversation.unreadCount ?? 0;
263
+ const provider = undefined as Provider | undefined; // provider not in Conversation type, badge optional
264
+
265
+ return (
266
+ <button
267
+ onClick={() => onSelect(conversation)}
268
+ onMouseEnter={() => setHovered(true)}
269
+ onMouseLeave={() => setHovered(false)}
270
+ style={{
271
+ display: 'flex',
272
+ width: '100%',
273
+ gap: 12,
274
+ padding: '10px 16px',
275
+ border: 0,
276
+ borderBottom: '1px solid #f1f5f9',
277
+ background: hovered ? '#f7f9fc' : unread > 0 ? '#f0f4ff' : '#fff',
278
+ textAlign: 'left',
279
+ cursor: 'pointer',
280
+ transition: 'background 100ms ease',
281
+ alignItems: 'center',
282
+ }}
283
+ >
284
+ {/* Avatar */}
285
+ <span style={{ position: 'relative', flex: '0 0 auto', width: 42, height: 42 }}>
286
+ <UiAvatar
287
+ src={conversation.contactPictureUrl}
288
+ fallback={initials(name)}
289
+ style={{
290
+ width: 42, height: 42,
291
+ borderRadius: '50%',
292
+ objectFit: 'cover',
293
+ display: 'grid',
294
+ placeItems: 'center',
295
+ fontSize: 13,
296
+ fontWeight: 800,
297
+ background: `${primary}18`,
298
+ color: primary,
299
+ }}
300
+ />
301
+ {provider && (
302
+ <span style={{ position: 'absolute', bottom: -2, right: -2 }}>
303
+ <ProviderDot provider={provider} apiUrl={apiUrl} />
304
+ </span>
305
+ )}
306
+ </span>
307
+
308
+ {/* Text */}
309
+ <span style={{ flex: 1, minWidth: 0 }}>
310
+ <span style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6 }}>
311
+ <span style={{
312
+ fontSize: 13, fontWeight: unread > 0 ? 700 : 500,
313
+ color: '#172033',
314
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
315
+ }}>
316
+ {name}
317
+ </span>
318
+ <span style={{ display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0 }}>
319
+ <time style={{ fontSize: 11, color: '#9aa5b5', whiteSpace: 'nowrap' }}>
320
+ {formatTime(conversation.lastMessageAt)}
321
+ </time>
322
+ {unread > 0 && (
323
+ <span style={{
324
+ display: 'inline-grid', placeItems: 'center',
325
+ minWidth: 18, height: 18, borderRadius: 999,
326
+ background: '#ef4444', color: '#fff',
327
+ fontSize: 10, fontWeight: 800, padding: '0 4px',
328
+ }}>
329
+ {unread > 99 ? '99+' : unread}
330
+ </span>
331
+ )}
332
+ </span>
333
+ </span>
334
+ <span style={{
335
+ display: 'block', marginTop: 2,
336
+ fontSize: 12, color: unread > 0 ? '#374151' : '#9aa5b5',
337
+ fontWeight: unread > 0 ? 500 : 400,
338
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
339
+ }}>
340
+ {conversation.lastMessageDirection === 'outbound' && (
341
+ <span style={{ color: '#9aa5b5' }}>Bạn: </span>
342
+ )}
343
+ {conversation.lastMessageText || <span style={{ opacity: 0.5 }}>Chưa có tin nhắn</span>}
344
+ </span>
345
+ </span>
346
+ </button>
347
+ );
348
+ }
package/src/api.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Connection, Conversation, Message, MessageAttachment, Page } from './types.js';
1
+ import type { ChannelHubAgent, Connection, Conversation, Message, MessageAttachment, Page } from './types.js';
2
2
 
3
3
  export class ChannelHubClient {
4
4
  constructor(private readonly apiUrl: string, private readonly token: string) {}
@@ -18,6 +18,17 @@ export class ChannelHubClient {
18
18
  return body as T;
19
19
  }
20
20
 
21
+ getSessionMe(): Promise<{ tenantId: string; scopes: string[]; agent?: ChannelHubAgent | null }> {
22
+ return this.request('/v1/auth/session/me');
23
+ }
24
+
25
+ assignConversation(conversationId: string, agent: ChannelHubAgent | null): Promise<Conversation> {
26
+ return this.request(`/v1/conversations/${encodeURIComponent(conversationId)}/assignee`, {
27
+ method: 'PATCH',
28
+ body: JSON.stringify({ agent }),
29
+ });
30
+ }
31
+
21
32
  listConnections(): Promise<Connection[]> { return this.request('/v1/connections'); }
22
33
 
23
34
  listConversations(cursor?: string): Promise<Page<Conversation>> {
package/src/index.ts CHANGED
@@ -3,6 +3,8 @@ console.log(`[ChannelHub] widget v${__WIDGET_VERSION__} loaded`);
3
3
 
4
4
  export { ChannelHubInbox } from './ChannelHubInbox.js';
5
5
  export { ChannelHubChannels } from './ChannelHubChannels.js';
6
+ export { ChannelHubNotificationBell } from './ChannelHubNotificationBell.js';
6
7
  export { ChannelHubClient } from './api.js';
7
- export type { WidgetProps, WidgetTheme, Conversation, Message, ChannelHubInboxHandle } from './types.js';
8
+ export type { WidgetProps, WidgetTheme, Conversation, Message, ChannelHubInboxHandle, ChannelHubAgent } from './types.js';
8
9
  export type { ChannelHubChannelsProps, ChannelConnection } from './ChannelHubChannels.js';
10
+ export type { ChannelHubNotificationBellProps } from './ChannelHubNotificationBell.js';
package/src/types.ts CHANGED
@@ -4,6 +4,14 @@ export type Provider = 'facebook' | 'instagram' | 'telegram' | 'zalo' | string;
4
4
 
5
5
  export type Connection = { id: string; provider: Provider; type?: string; metadata?: Record<string, unknown> };
6
6
 
7
+ export interface ChannelHubAgent {
8
+ id: string;
9
+ name: string;
10
+ avatarUrl?: string;
11
+ title?: string;
12
+ metadata?: Record<string, unknown>;
13
+ }
14
+
7
15
  export type Conversation = {
8
16
  id: string;
9
17
  connectionId: string;
@@ -19,6 +27,7 @@ export type Conversation = {
19
27
  lastMessageDirection?: 'inbound' | 'outbound';
20
28
  messageCount?: number;
21
29
  unreadCount?: number;
30
+ assignedAgent?: ChannelHubAgent | null;
22
31
  };
23
32
 
24
33
  export type MessageAttachment = {
@@ -35,6 +44,7 @@ export type Message = {
35
44
  attachments?: MessageAttachment[];
36
45
  occurredAt: string;
37
46
  senderId?: string;
47
+ senderAgent?: ChannelHubAgent | null;
38
48
  };
39
49
 
40
50
  export type Page<T> = { items: T[]; nextCursor?: string };
@@ -126,6 +136,8 @@ export type WidgetProps = {
126
136
  hideKeyboardHint?: boolean;
127
137
  locale?: 'vi' | 'en';
128
138
  extensions?: Extension[];
139
+ currentAgent?: ChannelHubAgent | null;
140
+ teamAgents?: ChannelHubAgent[];
129
141
  onNewMessage?: (conversationId: string) => void;
130
142
  onConversationSelect?: (conversationId: string) => void;
131
143
  };