@channelhub/widget 0.0.0-stage → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ChannelHubChannels.d.ts +15 -0
- package/dist/ChannelHubChannels.d.ts.map +1 -0
- package/dist/ChannelHubInbox.d.ts +3 -0
- package/dist/ChannelHubInbox.d.ts.map +1 -0
- package/dist/LiveChatWidget.d.ts +12 -0
- package/dist/LiveChatWidget.d.ts.map +1 -0
- package/dist/api.d.ts +20 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/channels/ProviderLogo.d.ts +8 -0
- package/dist/channels/ProviderLogo.d.ts.map +1 -0
- package/dist/components/ui/avatar.d.ts +8 -0
- package/dist/components/ui/avatar.d.ts.map +1 -0
- package/dist/components/ui/button.d.ts +5 -0
- package/dist/components/ui/button.d.ts.map +1 -0
- package/dist/components/ui/index.d.ts +6 -0
- package/dist/components/ui/index.d.ts.map +1 -0
- package/dist/components/ui/input.d.ts +3 -0
- package/dist/components/ui/input.d.ts.map +1 -0
- package/dist/components/ui/scroll-area.d.ts +6 -0
- package/dist/components/ui/scroll-area.d.ts.map +1 -0
- package/dist/components/ui/textarea.d.ts +3 -0
- package/dist/components/ui/textarea.d.ts.map +1 -0
- package/dist/facebook_icon.avif +0 -0
- package/dist/index.cjs +99 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1975 -0
- package/dist/instagram_icon.avif +0 -0
- package/dist/livechat-standalone.d.ts +23 -0
- package/dist/livechat-standalone.d.ts.map +1 -0
- package/dist/standalone.d.ts +22 -0
- package/dist/standalone.d.ts.map +1 -0
- package/dist/telegram_icon.avif +0 -0
- package/dist/types.d.ts +66 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/web.avif +0 -0
- package/dist/zalo_icon.avif +0 -0
- package/package.json +45 -3
- package/public/facebook_icon.avif +0 -0
- package/public/instagram_icon.avif +0 -0
- package/public/telegram_icon.avif +0 -0
- package/public/web.avif +0 -0
- package/public/zalo_icon.avif +0 -0
- package/src/ChannelHubChannels.tsx +941 -0
- package/src/ChannelHubInbox.tsx +769 -0
- package/src/LiveChatWidget.tsx +380 -0
- package/src/api.ts +84 -0
- package/src/assets/facebook_icon.avif +0 -0
- package/src/assets/instagram_icon.avif +0 -0
- package/src/assets/telegram_icon.avif +0 -0
- package/src/assets/web.avif +0 -0
- package/src/assets/zalo_icon.avif +0 -0
- package/src/assets.d.ts +4 -0
- package/src/channels/ProviderLogo.tsx +59 -0
- package/src/components/ui/avatar.tsx +2 -0
- package/src/components/ui/button.tsx +4 -0
- package/src/components/ui/index.ts +5 -0
- package/src/components/ui/input.tsx +2 -0
- package/src/components/ui/scroll-area.tsx +5 -0
- package/src/components/ui/textarea.tsx +2 -0
- package/src/index.ts +8 -0
- package/src/livechat-standalone.tsx +75 -0
- package/src/standalone.tsx +68 -0
- package/src/types.ts +65 -0
- package/tsconfig.json +14 -0
- package/vite.config.ts +76 -0
- package/README.md +0 -3
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
2
|
+
|
|
3
|
+
interface LiveChatWidgetProps {
|
|
4
|
+
apiUrl: string;
|
|
5
|
+
widgetId: string;
|
|
6
|
+
primaryColor?: string;
|
|
7
|
+
greeting?: string;
|
|
8
|
+
title?: string;
|
|
9
|
+
identifier?: string;
|
|
10
|
+
hmac?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface ChatMessage {
|
|
14
|
+
id: string;
|
|
15
|
+
direction: 'inbound' | 'outbound';
|
|
16
|
+
text: string | null;
|
|
17
|
+
occurredAt: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Fallback for sandboxed iframes where localStorage is unavailable
|
|
21
|
+
const _memoryTokens: Record<string, string> = {};
|
|
22
|
+
|
|
23
|
+
function tokenKey(widgetId: string): string {
|
|
24
|
+
return `channelhub_visitor_token_${widgetId}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function getStoredVisitorToken(widgetId: string): string | null {
|
|
28
|
+
try {
|
|
29
|
+
return localStorage.getItem(tokenKey(widgetId));
|
|
30
|
+
} catch {
|
|
31
|
+
return _memoryTokens[widgetId] ?? null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function storeVisitorToken(widgetId: string, token: string): void {
|
|
36
|
+
try {
|
|
37
|
+
localStorage.setItem(tokenKey(widgetId), token);
|
|
38
|
+
} catch {
|
|
39
|
+
_memoryTokens[widgetId] = token;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function LiveChatWidget({ apiUrl, widgetId, primaryColor = '#2563eb', greeting = 'Xin chào! Chúng tôi có thể giúp gì cho bạn?', title = 'Chat với chúng tôi', identifier, hmac }: LiveChatWidgetProps) {
|
|
44
|
+
const [open, setOpen] = useState(false);
|
|
45
|
+
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
|
46
|
+
const [inputText, setInputText] = useState('');
|
|
47
|
+
const [sending, setSending] = useState(false);
|
|
48
|
+
const [initialized, setInitialized] = useState(false);
|
|
49
|
+
const [visitorToken, setVisitorToken] = useState<string | null>(null);
|
|
50
|
+
const [conversationId, setConversationId] = useState<string | null>(null);
|
|
51
|
+
const [unread, setUnread] = useState(0);
|
|
52
|
+
const afterRef = useRef<string | undefined>(undefined);
|
|
53
|
+
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
|
54
|
+
const messagesEndRef = useRef<HTMLDivElement>(null);
|
|
55
|
+
|
|
56
|
+
const base = apiUrl.replace(/\/$/, '');
|
|
57
|
+
|
|
58
|
+
const initSession = useCallback(async () => {
|
|
59
|
+
try {
|
|
60
|
+
const storedToken = getStoredVisitorToken(widgetId);
|
|
61
|
+
const bodyPayload: Record<string, unknown> = { widgetId };
|
|
62
|
+
if (storedToken) bodyPayload['visitorToken'] = storedToken;
|
|
63
|
+
if (identifier) bodyPayload['identifier'] = identifier;
|
|
64
|
+
if (hmac) bodyPayload['hmac'] = hmac;
|
|
65
|
+
|
|
66
|
+
const res = await fetch(`${base}/v1/livechat/visitor/session`, {
|
|
67
|
+
method: 'POST',
|
|
68
|
+
headers: { 'content-type': 'application/json' },
|
|
69
|
+
body: JSON.stringify(bodyPayload),
|
|
70
|
+
});
|
|
71
|
+
if (!res.ok) return;
|
|
72
|
+
const data = await res.json() as { visitorToken: string; conversationId: string | null };
|
|
73
|
+
storeVisitorToken(widgetId, data.visitorToken);
|
|
74
|
+
setVisitorToken(data.visitorToken);
|
|
75
|
+
setConversationId(data.conversationId);
|
|
76
|
+
setInitialized(true);
|
|
77
|
+
} catch {
|
|
78
|
+
// silent — will retry on next open
|
|
79
|
+
}
|
|
80
|
+
}, [base, widgetId, identifier, hmac]);
|
|
81
|
+
|
|
82
|
+
const pollMessages = useCallback(async (vid: string) => {
|
|
83
|
+
try {
|
|
84
|
+
const params = new URLSearchParams({ widgetId, visitorToken: vid });
|
|
85
|
+
if (afterRef.current) params.set('after', afterRef.current);
|
|
86
|
+
const res = await fetch(`${base}/v1/livechat/visitor/messages?${params}`);
|
|
87
|
+
if (!res.ok) return;
|
|
88
|
+
const data = await res.json() as { messages: ChatMessage[]; nextAfter: string };
|
|
89
|
+
if (data.messages.length > 0) {
|
|
90
|
+
setMessages(prev => {
|
|
91
|
+
const existingIds = new Set(prev.map(m => m.id));
|
|
92
|
+
const newMsgs = data.messages.filter(m => !existingIds.has(m.id));
|
|
93
|
+
if (newMsgs.length === 0) return prev;
|
|
94
|
+
const outboundNew = newMsgs.filter(m => m.direction === 'outbound').length;
|
|
95
|
+
if (outboundNew > 0) {
|
|
96
|
+
setUnread(u => u + outboundNew);
|
|
97
|
+
}
|
|
98
|
+
return [...prev, ...newMsgs];
|
|
99
|
+
});
|
|
100
|
+
afterRef.current = data.nextAfter;
|
|
101
|
+
}
|
|
102
|
+
} catch {
|
|
103
|
+
// silent
|
|
104
|
+
}
|
|
105
|
+
}, [base, widgetId]);
|
|
106
|
+
|
|
107
|
+
useEffect(() => {
|
|
108
|
+
if (!open) return;
|
|
109
|
+
setUnread(0);
|
|
110
|
+
if (!initialized) {
|
|
111
|
+
void initSession();
|
|
112
|
+
}
|
|
113
|
+
}, [open, initialized, initSession]);
|
|
114
|
+
|
|
115
|
+
useEffect(() => {
|
|
116
|
+
if (!open || !visitorToken) return;
|
|
117
|
+
void pollMessages(visitorToken);
|
|
118
|
+
pollRef.current = setInterval(() => { void pollMessages(visitorToken); }, 3000);
|
|
119
|
+
return () => {
|
|
120
|
+
if (pollRef.current) clearInterval(pollRef.current);
|
|
121
|
+
};
|
|
122
|
+
}, [open, visitorToken, pollMessages]);
|
|
123
|
+
|
|
124
|
+
useEffect(() => {
|
|
125
|
+
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
|
126
|
+
}, [messages]);
|
|
127
|
+
|
|
128
|
+
const handleSend = async () => {
|
|
129
|
+
const text = inputText.trim();
|
|
130
|
+
if (!text || sending || !visitorToken) return;
|
|
131
|
+
setSending(true);
|
|
132
|
+
setInputText('');
|
|
133
|
+
const tempId = crypto.randomUUID();
|
|
134
|
+
const optimistic: ChatMessage = { id: tempId, direction: 'inbound', text, occurredAt: new Date().toISOString() };
|
|
135
|
+
setMessages(prev => [...prev, optimistic]);
|
|
136
|
+
try {
|
|
137
|
+
const res = await fetch(`${base}/v1/livechat/visitor/message`, {
|
|
138
|
+
method: 'POST',
|
|
139
|
+
headers: { 'content-type': 'application/json' },
|
|
140
|
+
body: JSON.stringify({ widgetId, visitorToken, text }),
|
|
141
|
+
});
|
|
142
|
+
if (res.ok) {
|
|
143
|
+
const data = await res.json() as { messageId: string; conversationId: string };
|
|
144
|
+
setConversationId(data.conversationId);
|
|
145
|
+
setMessages(prev => prev.map(m => m.id === tempId ? { ...m, id: data.messageId } : m));
|
|
146
|
+
afterRef.current = new Date().toISOString();
|
|
147
|
+
}
|
|
148
|
+
} catch {
|
|
149
|
+
// keep optimistic message
|
|
150
|
+
} finally {
|
|
151
|
+
setSending(false);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
|
156
|
+
if (e.key === 'Enter' && !e.shiftKey) {
|
|
157
|
+
e.preventDefault();
|
|
158
|
+
void handleSend();
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const s = styles(primaryColor);
|
|
163
|
+
|
|
164
|
+
return (
|
|
165
|
+
<div style={s.root}>
|
|
166
|
+
{open && (
|
|
167
|
+
<div style={s.window}>
|
|
168
|
+
<div style={s.header}>
|
|
169
|
+
<span style={s.headerTitle}>{title}</span>
|
|
170
|
+
<button style={s.closeBtn} onClick={() => setOpen(false)} aria-label="Đóng chat">✕</button>
|
|
171
|
+
</div>
|
|
172
|
+
<div style={s.messages}>
|
|
173
|
+
{messages.length === 0 && (
|
|
174
|
+
<div style={s.greeting}>{greeting}</div>
|
|
175
|
+
)}
|
|
176
|
+
{messages.map(msg => (
|
|
177
|
+
<div key={msg.id} style={msg.direction === 'inbound' ? s.msgOut : s.msgIn}>
|
|
178
|
+
<div style={msg.direction === 'inbound' ? s.bubbleOut(primaryColor) : s.bubbleIn}>
|
|
179
|
+
{msg.text}
|
|
180
|
+
</div>
|
|
181
|
+
</div>
|
|
182
|
+
))}
|
|
183
|
+
<div ref={messagesEndRef} />
|
|
184
|
+
</div>
|
|
185
|
+
<div style={s.inputRow}>
|
|
186
|
+
<textarea
|
|
187
|
+
style={s.textarea}
|
|
188
|
+
value={inputText}
|
|
189
|
+
onChange={e => setInputText(e.target.value)}
|
|
190
|
+
onKeyDown={handleKeyDown}
|
|
191
|
+
placeholder="Nhập tin nhắn..."
|
|
192
|
+
rows={1}
|
|
193
|
+
disabled={sending}
|
|
194
|
+
/>
|
|
195
|
+
<button style={s.sendBtn(primaryColor)} onClick={() => { void handleSend(); }} disabled={sending || !inputText.trim()} aria-label="Gửi">
|
|
196
|
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
|
|
197
|
+
</button>
|
|
198
|
+
</div>
|
|
199
|
+
{!conversationId && initialized && (
|
|
200
|
+
<div style={s.poweredBy}>Powered by <a href="https://channelhub.io" target="_blank" rel="noopener noreferrer" style={s.poweredLink}>ChannelHub</a></div>
|
|
201
|
+
)}
|
|
202
|
+
</div>
|
|
203
|
+
)}
|
|
204
|
+
<button style={s.bubble(primaryColor)} onClick={() => setOpen(o => !o)} aria-label={open ? 'Đóng chat' : 'Mở chat'}>
|
|
205
|
+
{open ? (
|
|
206
|
+
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
|
207
|
+
) : (
|
|
208
|
+
<>
|
|
209
|
+
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
|
210
|
+
{unread > 0 && <span style={s.badge}>{unread > 9 ? '9+' : unread}</span>}
|
|
211
|
+
</>
|
|
212
|
+
)}
|
|
213
|
+
</button>
|
|
214
|
+
</div>
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function styles(primaryColor: string) {
|
|
219
|
+
return {
|
|
220
|
+
root: {
|
|
221
|
+
position: 'fixed' as const,
|
|
222
|
+
bottom: '24px',
|
|
223
|
+
right: '24px',
|
|
224
|
+
zIndex: 999999,
|
|
225
|
+
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
|
|
226
|
+
},
|
|
227
|
+
bubble: (color: string) => ({
|
|
228
|
+
width: '56px',
|
|
229
|
+
height: '56px',
|
|
230
|
+
borderRadius: '50%',
|
|
231
|
+
background: color,
|
|
232
|
+
border: 'none',
|
|
233
|
+
cursor: 'pointer',
|
|
234
|
+
display: 'flex',
|
|
235
|
+
alignItems: 'center',
|
|
236
|
+
justifyContent: 'center',
|
|
237
|
+
color: '#fff',
|
|
238
|
+
boxShadow: '0 4px 16px rgba(0,0,0,0.18)',
|
|
239
|
+
position: 'relative' as const,
|
|
240
|
+
transition: 'transform 0.15s',
|
|
241
|
+
marginLeft: 'auto',
|
|
242
|
+
}),
|
|
243
|
+
badge: {
|
|
244
|
+
position: 'absolute' as const,
|
|
245
|
+
top: '-4px',
|
|
246
|
+
right: '-4px',
|
|
247
|
+
background: '#ef4444',
|
|
248
|
+
color: '#fff',
|
|
249
|
+
borderRadius: '999px',
|
|
250
|
+
fontSize: '11px',
|
|
251
|
+
fontWeight: 700,
|
|
252
|
+
minWidth: '18px',
|
|
253
|
+
height: '18px',
|
|
254
|
+
display: 'flex',
|
|
255
|
+
alignItems: 'center',
|
|
256
|
+
justifyContent: 'center',
|
|
257
|
+
padding: '0 4px',
|
|
258
|
+
border: '2px solid #fff',
|
|
259
|
+
},
|
|
260
|
+
window: {
|
|
261
|
+
width: '340px',
|
|
262
|
+
maxHeight: '480px',
|
|
263
|
+
background: '#fff',
|
|
264
|
+
borderRadius: '16px',
|
|
265
|
+
boxShadow: '0 8px 32px rgba(0,0,0,0.16)',
|
|
266
|
+
display: 'flex',
|
|
267
|
+
flexDirection: 'column' as const,
|
|
268
|
+
overflow: 'hidden',
|
|
269
|
+
marginBottom: '12px',
|
|
270
|
+
},
|
|
271
|
+
header: {
|
|
272
|
+
background: primaryColor,
|
|
273
|
+
color: '#fff',
|
|
274
|
+
padding: '14px 16px',
|
|
275
|
+
display: 'flex',
|
|
276
|
+
alignItems: 'center',
|
|
277
|
+
justifyContent: 'space-between',
|
|
278
|
+
},
|
|
279
|
+
headerTitle: {
|
|
280
|
+
fontWeight: 600,
|
|
281
|
+
fontSize: '15px',
|
|
282
|
+
},
|
|
283
|
+
closeBtn: {
|
|
284
|
+
background: 'none',
|
|
285
|
+
border: 'none',
|
|
286
|
+
color: '#fff',
|
|
287
|
+
cursor: 'pointer',
|
|
288
|
+
fontSize: '16px',
|
|
289
|
+
padding: '0 4px',
|
|
290
|
+
opacity: 0.8,
|
|
291
|
+
},
|
|
292
|
+
messages: {
|
|
293
|
+
flex: 1,
|
|
294
|
+
overflowY: 'auto' as const,
|
|
295
|
+
padding: '12px 14px',
|
|
296
|
+
display: 'flex',
|
|
297
|
+
flexDirection: 'column' as const,
|
|
298
|
+
gap: '6px',
|
|
299
|
+
minHeight: '200px',
|
|
300
|
+
},
|
|
301
|
+
greeting: {
|
|
302
|
+
color: '#6b7280',
|
|
303
|
+
fontSize: '13px',
|
|
304
|
+
textAlign: 'center' as const,
|
|
305
|
+
padding: '24px 8px',
|
|
306
|
+
},
|
|
307
|
+
msgOut: {
|
|
308
|
+
display: 'flex',
|
|
309
|
+
justifyContent: 'flex-end',
|
|
310
|
+
},
|
|
311
|
+
msgIn: {
|
|
312
|
+
display: 'flex',
|
|
313
|
+
justifyContent: 'flex-start',
|
|
314
|
+
},
|
|
315
|
+
bubbleOut: (color: string) => ({
|
|
316
|
+
background: color,
|
|
317
|
+
color: '#fff',
|
|
318
|
+
borderRadius: '14px 14px 2px 14px',
|
|
319
|
+
padding: '8px 12px',
|
|
320
|
+
maxWidth: '80%',
|
|
321
|
+
fontSize: '14px',
|
|
322
|
+
lineHeight: 1.4,
|
|
323
|
+
wordBreak: 'break-word' as const,
|
|
324
|
+
}),
|
|
325
|
+
bubbleIn: {
|
|
326
|
+
background: '#f3f4f6',
|
|
327
|
+
color: '#111827',
|
|
328
|
+
borderRadius: '14px 14px 14px 2px',
|
|
329
|
+
padding: '8px 12px',
|
|
330
|
+
maxWidth: '80%',
|
|
331
|
+
fontSize: '14px',
|
|
332
|
+
lineHeight: 1.4,
|
|
333
|
+
wordBreak: 'break-word' as const,
|
|
334
|
+
},
|
|
335
|
+
inputRow: {
|
|
336
|
+
display: 'flex',
|
|
337
|
+
alignItems: 'flex-end',
|
|
338
|
+
gap: '8px',
|
|
339
|
+
padding: '10px 12px',
|
|
340
|
+
borderTop: '1px solid #f3f4f6',
|
|
341
|
+
},
|
|
342
|
+
textarea: {
|
|
343
|
+
flex: 1,
|
|
344
|
+
border: '1px solid #e5e7eb',
|
|
345
|
+
borderRadius: '10px',
|
|
346
|
+
padding: '8px 10px',
|
|
347
|
+
fontSize: '14px',
|
|
348
|
+
resize: 'none' as const,
|
|
349
|
+
outline: 'none',
|
|
350
|
+
fontFamily: 'inherit',
|
|
351
|
+
lineHeight: 1.4,
|
|
352
|
+
maxHeight: '80px',
|
|
353
|
+
overflowY: 'auto' as const,
|
|
354
|
+
},
|
|
355
|
+
sendBtn: (color: string) => ({
|
|
356
|
+
background: color,
|
|
357
|
+
border: 'none',
|
|
358
|
+
borderRadius: '10px',
|
|
359
|
+
color: '#fff',
|
|
360
|
+
cursor: 'pointer',
|
|
361
|
+
display: 'flex',
|
|
362
|
+
alignItems: 'center',
|
|
363
|
+
justifyContent: 'center',
|
|
364
|
+
width: '36px',
|
|
365
|
+
height: '36px',
|
|
366
|
+
flexShrink: 0,
|
|
367
|
+
opacity: 1,
|
|
368
|
+
}),
|
|
369
|
+
poweredBy: {
|
|
370
|
+
textAlign: 'center' as const,
|
|
371
|
+
fontSize: '11px',
|
|
372
|
+
color: '#9ca3af',
|
|
373
|
+
padding: '6px 0 8px',
|
|
374
|
+
},
|
|
375
|
+
poweredLink: {
|
|
376
|
+
color: '#6b7280',
|
|
377
|
+
textDecoration: 'none',
|
|
378
|
+
},
|
|
379
|
+
};
|
|
380
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { Connection, Conversation, Message, MessageAttachment, Page } from './types.js';
|
|
2
|
+
|
|
3
|
+
export class ChannelHubClient {
|
|
4
|
+
constructor(private readonly apiUrl: string, private readonly token: string) {}
|
|
5
|
+
|
|
6
|
+
private async request<T>(path: string, init?: RequestInit, isFormData?: boolean): Promise<T> {
|
|
7
|
+
const headers: Record<string, string> = {
|
|
8
|
+
authorization: `Bearer ${this.token}`,
|
|
9
|
+
...(isFormData ? {} : { 'content-type': 'application/json' }),
|
|
10
|
+
...(init?.headers as Record<string, string> | undefined),
|
|
11
|
+
};
|
|
12
|
+
const response = await fetch(`${this.apiUrl}${path}`, {
|
|
13
|
+
...init,
|
|
14
|
+
headers,
|
|
15
|
+
});
|
|
16
|
+
const body = await response.json().catch(() => null) as { message?: string } | null;
|
|
17
|
+
if (!response.ok) throw new Error(body?.message ?? `Request failed (${response.status})`);
|
|
18
|
+
return body as T;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
listConnections(): Promise<Connection[]> { return this.request('/v1/connections'); }
|
|
22
|
+
|
|
23
|
+
listConversations(cursor?: string): Promise<Page<Conversation>> {
|
|
24
|
+
return this.request(`/v1/conversations${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
listMessages(conversationId: string, cursor?: string): Promise<Page<Message>> {
|
|
28
|
+
return this.request(`/v1/conversations/${encodeURIComponent(conversationId)}/messages${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
getMessage(messageId: string): Promise<Message> {
|
|
32
|
+
return this.request<Message>(`/v1/messages/${encodeURIComponent(messageId)}`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
sendMessage(conversationId: string, text?: string, attachments?: MessageAttachment[]): Promise<unknown> {
|
|
36
|
+
return this.request(`/v1/conversations/${encodeURIComponent(conversationId)}/messages`, {
|
|
37
|
+
method: 'POST',
|
|
38
|
+
headers: { 'idempotency-key': crypto.randomUUID() },
|
|
39
|
+
body: JSON.stringify({ text, attachments }),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async markRead(conversationId: string): Promise<void> {
|
|
44
|
+
const response = await fetch(`${this.apiUrl}/v1/conversations/${encodeURIComponent(conversationId)}/mark-read`, {
|
|
45
|
+
method: 'POST',
|
|
46
|
+
headers: { authorization: `Bearer ${this.token}` },
|
|
47
|
+
});
|
|
48
|
+
if (!response.ok && response.status !== 204) throw new Error(`markRead failed (${response.status})`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async uploadAttachment(file: File): Promise<{ url: string; mimeType: string; attachmentType: string }> {
|
|
52
|
+
const form = new FormData();
|
|
53
|
+
form.append('file', file);
|
|
54
|
+
return this.request<{ url: string; mimeType: string; attachmentType: string }>(
|
|
55
|
+
'/v1/attachments',
|
|
56
|
+
{ method: 'POST', body: form },
|
|
57
|
+
true,
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
connectSSE(onEvent: (type: string, data: unknown) => void): () => void {
|
|
62
|
+
const url = `${this.apiUrl}/v1/events?token=${encodeURIComponent(this.token)}`;
|
|
63
|
+
let source: EventSource;
|
|
64
|
+
let retryTimer: ReturnType<typeof setTimeout>;
|
|
65
|
+
let stopped = false;
|
|
66
|
+
|
|
67
|
+
const connect = () => {
|
|
68
|
+
source = new EventSource(url);
|
|
69
|
+
source.addEventListener('message.new', (e: MessageEvent<string>) => {
|
|
70
|
+
onEvent('message.new', JSON.parse(e.data));
|
|
71
|
+
});
|
|
72
|
+
source.addEventListener('conversation.updated', (e: MessageEvent<string>) => {
|
|
73
|
+
onEvent('conversation.updated', JSON.parse(e.data));
|
|
74
|
+
});
|
|
75
|
+
source.onerror = () => {
|
|
76
|
+
source.close();
|
|
77
|
+
if (!stopped) retryTimer = setTimeout(connect, 5_000);
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
connect();
|
|
82
|
+
return () => { stopped = true; clearTimeout(retryTimer); source?.close(); };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/src/assets.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
interface ProviderLogoProps {
|
|
2
|
+
provider: string;
|
|
3
|
+
apiUrl: string;
|
|
4
|
+
size?: number;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
const BG: Record<string, string> = {
|
|
8
|
+
facebook: '#dbeafe',
|
|
9
|
+
zalo: '#e0f2fe',
|
|
10
|
+
instagram: '#fce7f3',
|
|
11
|
+
telegram: '#cffafe',
|
|
12
|
+
livechat: '#ede9fe',
|
|
13
|
+
whatsapp: '#dcfce7',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const LOGO_KEY: Record<string, string> = {
|
|
17
|
+
facebook: 'facebook',
|
|
18
|
+
instagram: 'instagram',
|
|
19
|
+
telegram: 'telegram',
|
|
20
|
+
zalo: 'zalo',
|
|
21
|
+
livechat: 'web',
|
|
22
|
+
whatsapp: 'web',
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export function ProviderLogo({ provider, apiUrl, size = 40 }: ProviderLogoProps) {
|
|
26
|
+
const bg = BG[provider] ?? '#f1f5f9';
|
|
27
|
+
const logoKey = LOGO_KEY[provider];
|
|
28
|
+
const base = apiUrl.replace(/\/$/, '');
|
|
29
|
+
|
|
30
|
+
return (
|
|
31
|
+
<div
|
|
32
|
+
style={{
|
|
33
|
+
width: size,
|
|
34
|
+
height: size,
|
|
35
|
+
borderRadius: Math.round(size * 0.28),
|
|
36
|
+
background: bg,
|
|
37
|
+
display: 'flex',
|
|
38
|
+
alignItems: 'center',
|
|
39
|
+
justifyContent: 'center',
|
|
40
|
+
flexShrink: 0,
|
|
41
|
+
overflow: 'hidden',
|
|
42
|
+
}}
|
|
43
|
+
>
|
|
44
|
+
{logoKey ? (
|
|
45
|
+
<img
|
|
46
|
+
src={`${base}/static/logos/${logoKey}.avif`}
|
|
47
|
+
alt={provider}
|
|
48
|
+
width={Math.round(size * 0.65)}
|
|
49
|
+
height={Math.round(size * 0.65)}
|
|
50
|
+
style={{ objectFit: 'contain', display: 'block' }}
|
|
51
|
+
/>
|
|
52
|
+
) : (
|
|
53
|
+
<span style={{ fontSize: Math.round(size * 0.45), fontWeight: 700, color: '#64748b', textTransform: 'uppercase' }}>
|
|
54
|
+
{provider.slice(0, 1)}
|
|
55
|
+
</span>
|
|
56
|
+
)}
|
|
57
|
+
</div>
|
|
58
|
+
);
|
|
59
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
export function Avatar({ src, alt = '', fallback, style }: { src?: string; alt?: string; fallback: ReactNode; style?: React.CSSProperties }) { return src ? <img src={src} alt={alt} style={{ width: 38, height: 38, borderRadius: '50%', objectFit: 'cover', ...style }} /> : <span style={{ display: 'grid', placeItems: 'center', width: 38, height: 38, borderRadius: '50%', ...style }}>{fallback}</span>; }
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ButtonHTMLAttributes } from 'react';
|
|
2
|
+
export function Button({ variant = 'ghost', style, ...props }: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: 'default' | 'ghost' | 'outline' }) {
|
|
3
|
+
return <button {...props} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', border: variant === 'outline' ? '1px solid #e7ebf2' : 0, borderRadius: 8, cursor: 'pointer', font: 'inherit', background: variant === 'default' ? '#2563eb' : 'transparent', ...style }} />;
|
|
4
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { InputHTMLAttributes } from 'react';
|
|
2
|
+
export function Input({ style, ...props }: InputHTMLAttributes<HTMLInputElement>) { return <input {...props} style={{ width: '100%', minWidth: 0, border: 0, outline: 0, background: 'transparent', font: 'inherit', ...style }} />; }
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { forwardRef } from 'react';
|
|
2
|
+
import type { ReactNode } from 'react';
|
|
3
|
+
export const ScrollArea = forwardRef<HTMLDivElement, { children: ReactNode; style?: React.CSSProperties }>(
|
|
4
|
+
({ children, style }, ref) => <div ref={ref} style={{ minHeight: 0, overflowY: 'auto', overscrollBehavior: 'contain', ...style }}>{children}</div>,
|
|
5
|
+
);
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type { TextareaHTMLAttributes } from 'react';
|
|
2
|
+
export function Textarea({ style, ...props }: TextareaHTMLAttributes<HTMLTextAreaElement>) { return <textarea {...props} style={{ display: 'block', width: '100%', minWidth: 0, boxSizing: 'border-box', resize: 'vertical', border: 0, outline: 0, background: 'transparent', font: 'inherit', ...style }} />; }
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
declare const __WIDGET_VERSION__: string;
|
|
2
|
+
console.log(`[ChannelHub] widget v${__WIDGET_VERSION__} loaded`);
|
|
3
|
+
|
|
4
|
+
export { ChannelHubInbox } from './ChannelHubInbox.js';
|
|
5
|
+
export { ChannelHubChannels } from './ChannelHubChannels.js';
|
|
6
|
+
export { ChannelHubClient } from './api.js';
|
|
7
|
+
export type { WidgetProps, WidgetTheme, Conversation, Message, ChannelHubInboxHandle } from './types.js';
|
|
8
|
+
export type { ChannelHubChannelsProps, ChannelConnection } from './ChannelHubChannels.js';
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { createRoot } from 'react-dom/client';
|
|
2
|
+
import { LiveChatWidget } from './LiveChatWidget.js';
|
|
3
|
+
|
|
4
|
+
interface LiveChatOptions {
|
|
5
|
+
apiUrl: string;
|
|
6
|
+
widgetId: string;
|
|
7
|
+
primaryColor?: string;
|
|
8
|
+
greeting?: string;
|
|
9
|
+
title?: string;
|
|
10
|
+
identifier?: string;
|
|
11
|
+
hmac?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function init(options: LiveChatOptions): void {
|
|
15
|
+
const container = document.createElement('div');
|
|
16
|
+
document.body.appendChild(container);
|
|
17
|
+
createRoot(container).render(
|
|
18
|
+
<LiveChatWidget
|
|
19
|
+
apiUrl={options.apiUrl}
|
|
20
|
+
widgetId={options.widgetId}
|
|
21
|
+
primaryColor={options.primaryColor}
|
|
22
|
+
greeting={options.greeting}
|
|
23
|
+
title={options.title}
|
|
24
|
+
identifier={options.identifier}
|
|
25
|
+
hmac={options.hmac}
|
|
26
|
+
/>,
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
declare global {
|
|
31
|
+
interface Window {
|
|
32
|
+
ChannelHubLiveChat: { init: typeof init };
|
|
33
|
+
// Optional window global for server-rendered identity injection:
|
|
34
|
+
// Set BEFORE the script tag loads: window.__channelhub_identity = { identifier, hmac }
|
|
35
|
+
__channelhub_identity?: { identifier: string; hmac: string };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
declare const __WIDGET_VERSION__: string;
|
|
40
|
+
console.log(`[ChannelHub] livechat v${__WIDGET_VERSION__} loaded`);
|
|
41
|
+
|
|
42
|
+
window.ChannelHubLiveChat = { init };
|
|
43
|
+
|
|
44
|
+
// Auto-initialize from script tag data attributes + optional window identity global
|
|
45
|
+
function autoInit(): void {
|
|
46
|
+
const script = document.currentScript as HTMLScriptElement | null
|
|
47
|
+
?? document.querySelector<HTMLScriptElement>('script[data-widget-id]');
|
|
48
|
+
if (!script) return;
|
|
49
|
+
// data-manual-init suppresses autoInit — caller will invoke init() themselves
|
|
50
|
+
if ('manualInit' in script.dataset) return;
|
|
51
|
+
const widgetId = script.dataset['widgetId'];
|
|
52
|
+
const apiUrl = script.dataset['apiUrl'] ?? script.src.replace(/\/static\/livechat\.js.*$/, '');
|
|
53
|
+
if (!widgetId || !apiUrl) return;
|
|
54
|
+
|
|
55
|
+
// Identity: data attributes take priority, then window global
|
|
56
|
+
const identity = window.__channelhub_identity;
|
|
57
|
+
const identifier = script.dataset['identifier'] ?? identity?.identifier;
|
|
58
|
+
const hmac = script.dataset['hmac'] ?? identity?.hmac;
|
|
59
|
+
|
|
60
|
+
init({
|
|
61
|
+
apiUrl,
|
|
62
|
+
widgetId,
|
|
63
|
+
primaryColor: script.dataset['primaryColor'],
|
|
64
|
+
greeting: script.dataset['greeting'],
|
|
65
|
+
title: script.dataset['title'],
|
|
66
|
+
identifier,
|
|
67
|
+
hmac,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (document.readyState === 'loading') {
|
|
72
|
+
document.addEventListener('DOMContentLoaded', autoInit);
|
|
73
|
+
} else {
|
|
74
|
+
autoInit();
|
|
75
|
+
}
|