@channelhub/widget 0.0.0-stage → 0.1.4
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 +36 -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 +114 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2376 -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 +1133 -0
- package/src/LiveChatWidget.tsx +441 -0
- package/src/api.ts +100 -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 +7 -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,441 @@
|
|
|
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 MessageAttachment {
|
|
14
|
+
type: 'image' | 'video' | 'audio' | 'file' | 'sticker';
|
|
15
|
+
url: string;
|
|
16
|
+
mimeType?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface ChatMessage {
|
|
20
|
+
id: string;
|
|
21
|
+
direction: 'inbound' | 'outbound';
|
|
22
|
+
text: string | null;
|
|
23
|
+
attachments?: MessageAttachment[];
|
|
24
|
+
occurredAt: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Fallback for sandboxed iframes where localStorage is unavailable
|
|
28
|
+
const _memoryTokens: Record<string, string> = {};
|
|
29
|
+
|
|
30
|
+
function tokenKey(widgetId: string): string {
|
|
31
|
+
return `channelhub_visitor_token_${widgetId}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function getStoredVisitorToken(widgetId: string): string | null {
|
|
35
|
+
try {
|
|
36
|
+
return localStorage.getItem(tokenKey(widgetId));
|
|
37
|
+
} catch {
|
|
38
|
+
return _memoryTokens[widgetId] ?? null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function storeVisitorToken(widgetId: string, token: string): void {
|
|
43
|
+
try {
|
|
44
|
+
localStorage.setItem(tokenKey(widgetId), token);
|
|
45
|
+
} catch {
|
|
46
|
+
_memoryTokens[widgetId] = token;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
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) {
|
|
51
|
+
const [open, setOpen] = useState(false);
|
|
52
|
+
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
|
53
|
+
const [inputText, setInputText] = useState('');
|
|
54
|
+
const [sending, setSending] = useState(false);
|
|
55
|
+
const [initialized, setInitialized] = useState(false);
|
|
56
|
+
const [visitorToken, setVisitorToken] = useState<string | null>(null);
|
|
57
|
+
const [conversationId, setConversationId] = useState<string | null>(null);
|
|
58
|
+
const [unread, setUnread] = useState(0);
|
|
59
|
+
const [lightbox, setLightbox] = useState<{ url: string; kind: 'image' | 'video' } | null>(null);
|
|
60
|
+
const afterRef = useRef<string | undefined>(undefined);
|
|
61
|
+
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
|
62
|
+
const messagesEndRef = useRef<HTMLDivElement>(null);
|
|
63
|
+
|
|
64
|
+
const base = apiUrl.replace(/\/$/, '');
|
|
65
|
+
|
|
66
|
+
const resolveUrl = (url: string): string =>
|
|
67
|
+
url.startsWith('/v1/media/proxy') ? `${base}${url}&tok=${encodeURIComponent(visitorToken ?? '')}` : url;
|
|
68
|
+
|
|
69
|
+
const initSession = useCallback(async () => {
|
|
70
|
+
try {
|
|
71
|
+
const storedToken = getStoredVisitorToken(widgetId);
|
|
72
|
+
const bodyPayload: Record<string, unknown> = { widgetId };
|
|
73
|
+
if (storedToken) bodyPayload['visitorToken'] = storedToken;
|
|
74
|
+
if (identifier) bodyPayload['identifier'] = identifier;
|
|
75
|
+
if (hmac) bodyPayload['hmac'] = hmac;
|
|
76
|
+
|
|
77
|
+
const res = await fetch(`${base}/v1/livechat/visitor/session`, {
|
|
78
|
+
method: 'POST',
|
|
79
|
+
headers: { 'content-type': 'application/json' },
|
|
80
|
+
body: JSON.stringify(bodyPayload),
|
|
81
|
+
});
|
|
82
|
+
if (!res.ok) return;
|
|
83
|
+
const data = await res.json() as { visitorToken: string; conversationId: string | null };
|
|
84
|
+
storeVisitorToken(widgetId, data.visitorToken);
|
|
85
|
+
setVisitorToken(data.visitorToken);
|
|
86
|
+
setConversationId(data.conversationId);
|
|
87
|
+
setInitialized(true);
|
|
88
|
+
} catch {
|
|
89
|
+
// silent — will retry on next open
|
|
90
|
+
}
|
|
91
|
+
}, [base, widgetId, identifier, hmac]);
|
|
92
|
+
|
|
93
|
+
const pollMessages = useCallback(async (vid: string) => {
|
|
94
|
+
try {
|
|
95
|
+
const params = new URLSearchParams({ widgetId, visitorToken: vid });
|
|
96
|
+
if (afterRef.current) params.set('after', afterRef.current);
|
|
97
|
+
const res = await fetch(`${base}/v1/livechat/visitor/messages?${params}`);
|
|
98
|
+
if (!res.ok) return;
|
|
99
|
+
const data = await res.json() as { messages: ChatMessage[]; nextAfter: string };
|
|
100
|
+
if (data.messages.length > 0) {
|
|
101
|
+
setMessages(prev => {
|
|
102
|
+
const existingIds = new Set(prev.map(m => m.id));
|
|
103
|
+
const newMsgs = data.messages.filter(m => !existingIds.has(m.id));
|
|
104
|
+
if (newMsgs.length === 0) return prev;
|
|
105
|
+
const outboundNew = newMsgs.filter(m => m.direction === 'outbound').length;
|
|
106
|
+
if (outboundNew > 0) {
|
|
107
|
+
setUnread(u => u + outboundNew);
|
|
108
|
+
}
|
|
109
|
+
return [...prev, ...newMsgs];
|
|
110
|
+
});
|
|
111
|
+
afterRef.current = data.nextAfter;
|
|
112
|
+
}
|
|
113
|
+
} catch {
|
|
114
|
+
// silent
|
|
115
|
+
}
|
|
116
|
+
}, [base, widgetId]);
|
|
117
|
+
|
|
118
|
+
useEffect(() => {
|
|
119
|
+
if (!open) return;
|
|
120
|
+
setUnread(0);
|
|
121
|
+
if (!initialized) {
|
|
122
|
+
void initSession();
|
|
123
|
+
}
|
|
124
|
+
}, [open, initialized, initSession]);
|
|
125
|
+
|
|
126
|
+
useEffect(() => {
|
|
127
|
+
if (!open || !visitorToken) return;
|
|
128
|
+
void pollMessages(visitorToken);
|
|
129
|
+
pollRef.current = setInterval(() => { void pollMessages(visitorToken); }, 3000);
|
|
130
|
+
return () => {
|
|
131
|
+
if (pollRef.current) clearInterval(pollRef.current);
|
|
132
|
+
};
|
|
133
|
+
}, [open, visitorToken, pollMessages]);
|
|
134
|
+
|
|
135
|
+
useEffect(() => {
|
|
136
|
+
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
|
137
|
+
}, [messages]);
|
|
138
|
+
|
|
139
|
+
const handleSend = async () => {
|
|
140
|
+
const text = inputText.trim();
|
|
141
|
+
if (!text || sending || !visitorToken) return;
|
|
142
|
+
setSending(true);
|
|
143
|
+
setInputText('');
|
|
144
|
+
const tempId = crypto.randomUUID();
|
|
145
|
+
const optimistic: ChatMessage = { id: tempId, direction: 'inbound', text, occurredAt: new Date().toISOString() };
|
|
146
|
+
setMessages(prev => [...prev, optimistic]);
|
|
147
|
+
try {
|
|
148
|
+
const res = await fetch(`${base}/v1/livechat/visitor/message`, {
|
|
149
|
+
method: 'POST',
|
|
150
|
+
headers: { 'content-type': 'application/json' },
|
|
151
|
+
body: JSON.stringify({ widgetId, visitorToken, text }),
|
|
152
|
+
});
|
|
153
|
+
if (res.ok) {
|
|
154
|
+
const data = await res.json() as { messageId: string; conversationId: string };
|
|
155
|
+
setConversationId(data.conversationId);
|
|
156
|
+
setMessages(prev => prev.map(m => m.id === tempId ? { ...m, id: data.messageId } : m));
|
|
157
|
+
afterRef.current = new Date().toISOString();
|
|
158
|
+
}
|
|
159
|
+
} catch {
|
|
160
|
+
// keep optimistic message
|
|
161
|
+
} finally {
|
|
162
|
+
setSending(false);
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
|
167
|
+
if (e.key === 'Enter' && !e.shiftKey) {
|
|
168
|
+
e.preventDefault();
|
|
169
|
+
void handleSend();
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const s = styles(primaryColor);
|
|
174
|
+
|
|
175
|
+
return (
|
|
176
|
+
<div style={s.root}>
|
|
177
|
+
{open && (
|
|
178
|
+
<div style={s.window}>
|
|
179
|
+
<div style={s.header}>
|
|
180
|
+
<span style={s.headerTitle}>{title}</span>
|
|
181
|
+
<button style={s.closeBtn} onClick={() => setOpen(false)} aria-label="Đóng chat">✕</button>
|
|
182
|
+
</div>
|
|
183
|
+
<div style={s.messages}>
|
|
184
|
+
{messages.length === 0 && (
|
|
185
|
+
<div style={s.greeting}>{greeting}</div>
|
|
186
|
+
)}
|
|
187
|
+
{messages.map(msg => {
|
|
188
|
+
const isOut = msg.direction === 'inbound';
|
|
189
|
+
const align = isOut ? 'flex-end' : 'flex-start';
|
|
190
|
+
const images = msg.attachments?.filter(a => a.type === 'image') ?? [];
|
|
191
|
+
const stickers = msg.attachments?.filter(a => a.type === 'sticker') ?? [];
|
|
192
|
+
const videos = msg.attachments?.filter(a => a.type === 'video') ?? [];
|
|
193
|
+
const audios = msg.attachments?.filter(a => a.type === 'audio') ?? [];
|
|
194
|
+
const files = msg.attachments?.filter(a => a.type === 'file') ?? [];
|
|
195
|
+
const hasBubble = !!(msg.text || audios.length || files.length);
|
|
196
|
+
return (
|
|
197
|
+
<div key={msg.id} style={{ display: 'flex', flexDirection: 'column', alignItems: align, gap: 2 }}>
|
|
198
|
+
{stickers.map((a, i) => (
|
|
199
|
+
<img key={`st${i}`} src={resolveUrl(a.url)} alt="sticker" style={{ maxWidth: 100, maxHeight: 100, objectFit: 'contain' }} />
|
|
200
|
+
))}
|
|
201
|
+
{images.map((a, i) => (
|
|
202
|
+
<img key={`img${i}`} src={resolveUrl(a.url)} alt="" onClick={() => setLightbox({ url: resolveUrl(a.url), kind: 'image' })}
|
|
203
|
+
style={{ display: 'block', maxWidth: 220, maxHeight: 220, borderRadius: 10, objectFit: 'cover', cursor: 'zoom-in' }} />
|
|
204
|
+
))}
|
|
205
|
+
{videos.map((a, i) => (
|
|
206
|
+
<div key={`vid${i}`} onClick={() => setLightbox({ url: resolveUrl(a.url), kind: 'video' })}
|
|
207
|
+
style={{ position: 'relative', cursor: 'pointer', borderRadius: 10, overflow: 'hidden', maxWidth: 220 }}>
|
|
208
|
+
<video src={resolveUrl(a.url)} style={{ display: 'block', maxWidth: 220, maxHeight: 160, objectFit: 'cover' }} />
|
|
209
|
+
<div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,.25)' }}>
|
|
210
|
+
<div style={{ width: 36, height: 36, borderRadius: '50%', background: 'rgba(255,255,255,.9)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
|
211
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="#172033"><polygon points="5 3 19 12 5 21 5 3"/></svg>
|
|
212
|
+
</div>
|
|
213
|
+
</div>
|
|
214
|
+
</div>
|
|
215
|
+
))}
|
|
216
|
+
{hasBubble && (
|
|
217
|
+
<div style={isOut ? s.bubbleOut(primaryColor) : s.bubbleIn}>
|
|
218
|
+
{audios.map((a, i) => <audio key={i} src={resolveUrl(a.url)} controls style={{ display: 'block', width: '100%', marginBottom: 4 }} />)}
|
|
219
|
+
{files.map((a, i) => (
|
|
220
|
+
<a key={i} href={resolveUrl(a.url)} target="_blank" rel="noreferrer"
|
|
221
|
+
style={{ display: 'block', fontSize: 12, color: isOut ? '#fff' : '#2563eb', textDecoration: 'underline', marginBottom: 4 }}>
|
|
222
|
+
📎 {a.mimeType ?? 'file'}
|
|
223
|
+
</a>
|
|
224
|
+
))}
|
|
225
|
+
{msg.text}
|
|
226
|
+
</div>
|
|
227
|
+
)}
|
|
228
|
+
</div>
|
|
229
|
+
);
|
|
230
|
+
})}
|
|
231
|
+
<div ref={messagesEndRef} />
|
|
232
|
+
</div>
|
|
233
|
+
<div style={s.inputRow}>
|
|
234
|
+
<textarea
|
|
235
|
+
style={s.textarea}
|
|
236
|
+
value={inputText}
|
|
237
|
+
onChange={e => setInputText(e.target.value)}
|
|
238
|
+
onKeyDown={handleKeyDown}
|
|
239
|
+
placeholder="Nhập tin nhắn..."
|
|
240
|
+
rows={1}
|
|
241
|
+
disabled={sending}
|
|
242
|
+
/>
|
|
243
|
+
<button style={s.sendBtn(primaryColor)} onClick={() => { void handleSend(); }} disabled={sending || !inputText.trim()} aria-label="Gửi">
|
|
244
|
+
<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>
|
|
245
|
+
</button>
|
|
246
|
+
</div>
|
|
247
|
+
{!conversationId && initialized && (
|
|
248
|
+
<div style={s.poweredBy}>Powered by <a href="https://channelhub.io" target="_blank" rel="noopener noreferrer" style={s.poweredLink}>ChannelHub</a></div>
|
|
249
|
+
)}
|
|
250
|
+
{lightbox && (
|
|
251
|
+
<div onClick={() => setLightbox(null)}
|
|
252
|
+
style={{ position: 'fixed', inset: 0, zIndex: 1000000, background: 'rgba(0,0,0,.88)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'zoom-out' }}>
|
|
253
|
+
{lightbox.kind === 'image'
|
|
254
|
+
? <img src={lightbox.url} alt="" onClick={e => e.stopPropagation()} style={{ maxWidth: '90vw', maxHeight: '90vh', borderRadius: 8, objectFit: 'contain', boxShadow: '0 8px 40px rgba(0,0,0,.5)', cursor: 'default' }} />
|
|
255
|
+
: <video src={lightbox.url} controls autoPlay onClick={e => e.stopPropagation()} style={{ maxWidth: '90vw', maxHeight: '90vh', borderRadius: 8, boxShadow: '0 8px 40px rgba(0,0,0,.5)', cursor: 'default' }} />
|
|
256
|
+
}
|
|
257
|
+
<button onClick={() => setLightbox(null)}
|
|
258
|
+
style={{ position: 'absolute', top: 16, right: 16, background: 'rgba(255,255,255,.15)', border: 'none', borderRadius: '50%', width: 36, height: 36, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 18 }}>
|
|
259
|
+
✕
|
|
260
|
+
</button>
|
|
261
|
+
</div>
|
|
262
|
+
)}
|
|
263
|
+
</div>
|
|
264
|
+
)}
|
|
265
|
+
<button style={s.bubble(primaryColor)} onClick={() => setOpen(o => !o)} aria-label={open ? 'Đóng chat' : 'Mở chat'}>
|
|
266
|
+
{open ? (
|
|
267
|
+
<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>
|
|
268
|
+
) : (
|
|
269
|
+
<>
|
|
270
|
+
<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>
|
|
271
|
+
{unread > 0 && <span style={s.badge}>{unread > 9 ? '9+' : unread}</span>}
|
|
272
|
+
</>
|
|
273
|
+
)}
|
|
274
|
+
</button>
|
|
275
|
+
</div>
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function styles(primaryColor: string) {
|
|
280
|
+
return {
|
|
281
|
+
root: {
|
|
282
|
+
position: 'fixed' as const,
|
|
283
|
+
bottom: '24px',
|
|
284
|
+
right: '24px',
|
|
285
|
+
zIndex: 999999,
|
|
286
|
+
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
|
|
287
|
+
},
|
|
288
|
+
bubble: (color: string) => ({
|
|
289
|
+
width: '56px',
|
|
290
|
+
height: '56px',
|
|
291
|
+
borderRadius: '50%',
|
|
292
|
+
background: color,
|
|
293
|
+
border: 'none',
|
|
294
|
+
cursor: 'pointer',
|
|
295
|
+
display: 'flex',
|
|
296
|
+
alignItems: 'center',
|
|
297
|
+
justifyContent: 'center',
|
|
298
|
+
color: '#fff',
|
|
299
|
+
boxShadow: '0 4px 16px rgba(0,0,0,0.18)',
|
|
300
|
+
position: 'relative' as const,
|
|
301
|
+
transition: 'transform 0.15s',
|
|
302
|
+
marginLeft: 'auto',
|
|
303
|
+
}),
|
|
304
|
+
badge: {
|
|
305
|
+
position: 'absolute' as const,
|
|
306
|
+
top: '-4px',
|
|
307
|
+
right: '-4px',
|
|
308
|
+
background: '#ef4444',
|
|
309
|
+
color: '#fff',
|
|
310
|
+
borderRadius: '999px',
|
|
311
|
+
fontSize: '11px',
|
|
312
|
+
fontWeight: 700,
|
|
313
|
+
minWidth: '18px',
|
|
314
|
+
height: '18px',
|
|
315
|
+
display: 'flex',
|
|
316
|
+
alignItems: 'center',
|
|
317
|
+
justifyContent: 'center',
|
|
318
|
+
padding: '0 4px',
|
|
319
|
+
border: '2px solid #fff',
|
|
320
|
+
},
|
|
321
|
+
window: {
|
|
322
|
+
width: '340px',
|
|
323
|
+
maxHeight: '480px',
|
|
324
|
+
background: '#fff',
|
|
325
|
+
borderRadius: '16px',
|
|
326
|
+
boxShadow: '0 8px 32px rgba(0,0,0,0.16)',
|
|
327
|
+
display: 'flex',
|
|
328
|
+
flexDirection: 'column' as const,
|
|
329
|
+
overflow: 'hidden',
|
|
330
|
+
marginBottom: '12px',
|
|
331
|
+
},
|
|
332
|
+
header: {
|
|
333
|
+
background: primaryColor,
|
|
334
|
+
color: '#fff',
|
|
335
|
+
padding: '14px 16px',
|
|
336
|
+
display: 'flex',
|
|
337
|
+
alignItems: 'center',
|
|
338
|
+
justifyContent: 'space-between',
|
|
339
|
+
},
|
|
340
|
+
headerTitle: {
|
|
341
|
+
fontWeight: 600,
|
|
342
|
+
fontSize: '15px',
|
|
343
|
+
},
|
|
344
|
+
closeBtn: {
|
|
345
|
+
background: 'none',
|
|
346
|
+
border: 'none',
|
|
347
|
+
color: '#fff',
|
|
348
|
+
cursor: 'pointer',
|
|
349
|
+
fontSize: '16px',
|
|
350
|
+
padding: '0 4px',
|
|
351
|
+
opacity: 0.8,
|
|
352
|
+
},
|
|
353
|
+
messages: {
|
|
354
|
+
flex: 1,
|
|
355
|
+
overflowY: 'auto' as const,
|
|
356
|
+
padding: '12px 14px',
|
|
357
|
+
display: 'flex',
|
|
358
|
+
flexDirection: 'column' as const,
|
|
359
|
+
gap: '6px',
|
|
360
|
+
minHeight: '200px',
|
|
361
|
+
},
|
|
362
|
+
greeting: {
|
|
363
|
+
color: '#6b7280',
|
|
364
|
+
fontSize: '13px',
|
|
365
|
+
textAlign: 'center' as const,
|
|
366
|
+
padding: '24px 8px',
|
|
367
|
+
},
|
|
368
|
+
msgOut: {
|
|
369
|
+
display: 'flex',
|
|
370
|
+
justifyContent: 'flex-end',
|
|
371
|
+
},
|
|
372
|
+
msgIn: {
|
|
373
|
+
display: 'flex',
|
|
374
|
+
justifyContent: 'flex-start',
|
|
375
|
+
},
|
|
376
|
+
bubbleOut: (color: string) => ({
|
|
377
|
+
background: color,
|
|
378
|
+
color: '#fff',
|
|
379
|
+
borderRadius: '14px 14px 2px 14px',
|
|
380
|
+
padding: '8px 12px',
|
|
381
|
+
maxWidth: '80%',
|
|
382
|
+
fontSize: '14px',
|
|
383
|
+
lineHeight: 1.4,
|
|
384
|
+
wordBreak: 'break-word' as const,
|
|
385
|
+
}),
|
|
386
|
+
bubbleIn: {
|
|
387
|
+
background: '#f3f4f6',
|
|
388
|
+
color: '#111827',
|
|
389
|
+
borderRadius: '14px 14px 14px 2px',
|
|
390
|
+
padding: '8px 12px',
|
|
391
|
+
maxWidth: '80%',
|
|
392
|
+
fontSize: '14px',
|
|
393
|
+
lineHeight: 1.4,
|
|
394
|
+
wordBreak: 'break-word' as const,
|
|
395
|
+
},
|
|
396
|
+
inputRow: {
|
|
397
|
+
display: 'flex',
|
|
398
|
+
alignItems: 'flex-end',
|
|
399
|
+
gap: '8px',
|
|
400
|
+
padding: '10px 12px',
|
|
401
|
+
borderTop: '1px solid #f3f4f6',
|
|
402
|
+
},
|
|
403
|
+
textarea: {
|
|
404
|
+
flex: 1,
|
|
405
|
+
border: '1px solid #e5e7eb',
|
|
406
|
+
borderRadius: '10px',
|
|
407
|
+
padding: '8px 10px',
|
|
408
|
+
fontSize: '14px',
|
|
409
|
+
resize: 'none' as const,
|
|
410
|
+
outline: 'none',
|
|
411
|
+
fontFamily: 'inherit',
|
|
412
|
+
lineHeight: 1.4,
|
|
413
|
+
maxHeight: '80px',
|
|
414
|
+
overflowY: 'auto' as const,
|
|
415
|
+
},
|
|
416
|
+
sendBtn: (color: string) => ({
|
|
417
|
+
background: color,
|
|
418
|
+
border: 'none',
|
|
419
|
+
borderRadius: '10px',
|
|
420
|
+
color: '#fff',
|
|
421
|
+
cursor: 'pointer',
|
|
422
|
+
display: 'flex',
|
|
423
|
+
alignItems: 'center',
|
|
424
|
+
justifyContent: 'center',
|
|
425
|
+
width: '36px',
|
|
426
|
+
height: '36px',
|
|
427
|
+
flexShrink: 0,
|
|
428
|
+
opacity: 1,
|
|
429
|
+
}),
|
|
430
|
+
poweredBy: {
|
|
431
|
+
textAlign: 'center' as const,
|
|
432
|
+
fontSize: '11px',
|
|
433
|
+
color: '#9ca3af',
|
|
434
|
+
padding: '6px 0 8px',
|
|
435
|
+
},
|
|
436
|
+
poweredLink: {
|
|
437
|
+
color: '#6b7280',
|
|
438
|
+
textDecoration: 'none',
|
|
439
|
+
},
|
|
440
|
+
};
|
|
441
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
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
|
+
listCannedResponses(search?: string): Promise<{ id: string; title: string; content: string; shortcut: string | null }[]> {
|
|
52
|
+
const q = search?.trim() ? `?search=${encodeURIComponent(search)}` : '';
|
|
53
|
+
return this.request(`/v1/canned-responses${q}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
getNote(conversationId: string): Promise<{ id: string; content: string; updatedAt: string } | null> {
|
|
57
|
+
return this.request(`/v1/conversations/${encodeURIComponent(conversationId)}/note`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
upsertNote(conversationId: string, content: string): Promise<{ id: string; content: string; updatedAt: string }> {
|
|
61
|
+
return this.request(`/v1/conversations/${encodeURIComponent(conversationId)}/note`, {
|
|
62
|
+
method: 'PUT',
|
|
63
|
+
body: JSON.stringify({ content }),
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async uploadAttachment(file: File): Promise<{ url: string; mimeType: string; attachmentType: string }> {
|
|
68
|
+
const form = new FormData();
|
|
69
|
+
form.append('file', file);
|
|
70
|
+
return this.request<{ url: string; mimeType: string; attachmentType: string }>(
|
|
71
|
+
'/v1/attachments',
|
|
72
|
+
{ method: 'POST', body: form },
|
|
73
|
+
true,
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
connectSSE(onEvent: (type: string, data: unknown) => void): () => void {
|
|
78
|
+
const url = `${this.apiUrl}/v1/events?token=${encodeURIComponent(this.token)}`;
|
|
79
|
+
let source: EventSource;
|
|
80
|
+
let retryTimer: ReturnType<typeof setTimeout>;
|
|
81
|
+
let stopped = false;
|
|
82
|
+
|
|
83
|
+
const connect = () => {
|
|
84
|
+
source = new EventSource(url);
|
|
85
|
+
source.addEventListener('message.new', (e: MessageEvent<string>) => {
|
|
86
|
+
onEvent('message.new', JSON.parse(e.data));
|
|
87
|
+
});
|
|
88
|
+
source.addEventListener('conversation.updated', (e: MessageEvent<string>) => {
|
|
89
|
+
onEvent('conversation.updated', JSON.parse(e.data));
|
|
90
|
+
});
|
|
91
|
+
source.onerror = () => {
|
|
92
|
+
source.close();
|
|
93
|
+
if (!stopped) retryTimer = setTimeout(connect, 5_000);
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
connect();
|
|
98
|
+
return () => { stopped = true; clearTimeout(retryTimer); source?.close(); };
|
|
99
|
+
}
|
|
100
|
+
}
|
|
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,7 @@
|
|
|
1
|
+
import { forwardRef } from 'react';
|
|
2
|
+
import type { TextareaHTMLAttributes } from 'react';
|
|
3
|
+
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLTextAreaElement>>(
|
|
4
|
+
function Textarea({ style, ...props }, ref) {
|
|
5
|
+
return <textarea ref={ref} {...props} style={{ display: 'block', width: '100%', minWidth: 0, boxSizing: 'border-box', resize: 'vertical', border: 0, outline: 0, background: 'transparent', font: 'inherit', ...style }} />;
|
|
6
|
+
}
|
|
7
|
+
);
|
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';
|