@channelhub/widget 0.1.10 → 0.1.12

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.
@@ -57,6 +57,9 @@ export function LiveChatWidget({ apiUrl, widgetId, primaryColor = '#2563eb', gre
57
57
  const [conversationId, setConversationId] = useState<string | null>(null);
58
58
  const [unread, setUnread] = useState(0);
59
59
  const [lightbox, setLightbox] = useState<{ url: string; kind: 'image' | 'video' } | null>(null);
60
+ const [pendingFiles, setPendingFiles] = useState<Array<{ file: File; previewUrl: string | null }>>([]);
61
+ const mediaInputRef = useRef<HTMLInputElement>(null);
62
+ const fileInputRef = useRef<HTMLInputElement>(null);
60
63
  const afterRef = useRef<string | undefined>(undefined);
61
64
  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
62
65
  const messagesEndRef = useRef<HTMLDivElement>(null);
@@ -136,19 +139,63 @@ export function LiveChatWidget({ apiUrl, widgetId, primaryColor = '#2563eb', gre
136
139
  messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
137
140
  }, [messages]);
138
141
 
142
+ const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
143
+ const files = Array.from(e.target.files ?? []);
144
+ const items = files.map(f => ({
145
+ file: f,
146
+ previewUrl: f.type.startsWith('image/') ? URL.createObjectURL(f) : null,
147
+ }));
148
+ setPendingFiles(prev => [...prev, ...items].slice(0, 5));
149
+ if (fileInputRef.current) fileInputRef.current.value = '';
150
+ };
151
+
152
+ const removePendingFile = (idx: number) => {
153
+ setPendingFiles(prev => {
154
+ const item = prev[idx];
155
+ if (item?.previewUrl) URL.revokeObjectURL(item.previewUrl);
156
+ return prev.filter((_, i) => i !== idx);
157
+ });
158
+ };
159
+
139
160
  const handleSend = async () => {
140
161
  const text = inputText.trim();
141
- if (!text || sending || !visitorToken) return;
162
+ if ((!text && pendingFiles.length === 0) || sending || !visitorToken) return;
142
163
  setSending(true);
143
164
  setInputText('');
165
+ const filesToSend = [...pendingFiles];
166
+ setPendingFiles([]);
167
+
168
+ // Upload files first
169
+ const attachments: Array<{ url: string; mimeType: string; type: string }> = [];
170
+ for (const { file } of filesToSend) {
171
+ try {
172
+ const form = new FormData();
173
+ form.append('widgetId', widgetId);
174
+ form.append('visitorToken', visitorToken);
175
+ form.append('file', file);
176
+ const up = await fetch(`${base}/v1/livechat/visitor/upload`, { method: 'POST', body: form });
177
+ if (up.ok) {
178
+ const d = await up.json() as { url: string; mimeType: string; type: string };
179
+ attachments.push(d);
180
+ }
181
+ } catch { /* skip failed upload */ }
182
+ }
183
+
144
184
  const tempId = crypto.randomUUID();
145
- const optimistic: ChatMessage = { id: tempId, direction: 'inbound', text, occurredAt: new Date().toISOString() };
185
+ const optimistic: ChatMessage = {
186
+ id: tempId,
187
+ direction: 'inbound',
188
+ text: text || null,
189
+ attachments: attachments.map(a => ({ type: a.type as MessageAttachment['type'], url: a.url, mimeType: a.mimeType })),
190
+ occurredAt: new Date().toISOString(),
191
+ };
146
192
  setMessages(prev => [...prev, optimistic]);
193
+
147
194
  try {
148
195
  const res = await fetch(`${base}/v1/livechat/visitor/message`, {
149
196
  method: 'POST',
150
197
  headers: { 'content-type': 'application/json' },
151
- body: JSON.stringify({ widgetId, visitorToken, text }),
198
+ body: JSON.stringify({ widgetId, visitorToken, ...(text ? { text } : {}), attachments }),
152
199
  });
153
200
  if (res.ok) {
154
201
  const data = await res.json() as { messageId: string; conversationId: string };
@@ -230,7 +277,56 @@ export function LiveChatWidget({ apiUrl, widgetId, primaryColor = '#2563eb', gre
230
277
  })}
231
278
  <div ref={messagesEndRef} />
232
279
  </div>
280
+ {pendingFiles.length > 0 && (
281
+ <div style={{ display: 'flex', gap: 6, padding: '6px 12px 0', flexWrap: 'wrap' as const }}>
282
+ {pendingFiles.map((item, idx) => (
283
+ <div key={idx} style={{ position: 'relative', width: 52, height: 52, borderRadius: 8, overflow: 'hidden', border: '1px solid #e5e7eb', flexShrink: 0 }}>
284
+ {item.previewUrl
285
+ ? <img src={item.previewUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
286
+ : <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f3f4f6', fontSize: 20 }}>📎</div>
287
+ }
288
+ <button
289
+ onClick={() => removePendingFile(idx)}
290
+ style={{ position: 'absolute', top: 2, right: 2, width: 16, height: 16, borderRadius: '50%', background: 'rgba(0,0,0,.55)', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 9, lineHeight: 1 }}
291
+ aria-label="Xóa"
292
+ >✕</button>
293
+ </div>
294
+ ))}
295
+ </div>
296
+ )}
233
297
  <div style={s.inputRow}>
298
+ <input
299
+ ref={mediaInputRef}
300
+ type="file"
301
+ accept="image/*,video/mp4"
302
+ multiple
303
+ style={{ display: 'none' }}
304
+ onChange={handleFileChange}
305
+ />
306
+ <input
307
+ ref={fileInputRef}
308
+ type="file"
309
+ accept="audio/mpeg,audio/ogg,application/pdf"
310
+ multiple
311
+ style={{ display: 'none' }}
312
+ onChange={handleFileChange}
313
+ />
314
+ <button
315
+ style={s.attachBtn}
316
+ onClick={() => mediaInputRef.current?.click()}
317
+ disabled={sending || pendingFiles.length >= 5}
318
+ aria-label="Gửi ảnh/video"
319
+ >
320
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
321
+ </button>
322
+ <button
323
+ style={s.attachBtn}
324
+ onClick={() => fileInputRef.current?.click()}
325
+ disabled={sending || pendingFiles.length >= 5}
326
+ aria-label="Đính kèm tệp"
327
+ >
328
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
329
+ </button>
234
330
  <textarea
235
331
  style={s.textarea}
236
332
  value={inputText}
@@ -240,7 +336,7 @@ export function LiveChatWidget({ apiUrl, widgetId, primaryColor = '#2563eb', gre
240
336
  rows={1}
241
337
  disabled={sending}
242
338
  />
243
- <button style={s.sendBtn(primaryColor)} onClick={() => { void handleSend(); }} disabled={sending || !inputText.trim()} aria-label="Gửi">
339
+ <button style={s.sendBtn(primaryColor)} onClick={() => { void handleSend(); }} disabled={sending || (!inputText.trim() && pendingFiles.length === 0)} aria-label="Gửi">
244
340
  <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
341
  </button>
246
342
  </div>
@@ -413,6 +509,19 @@ function styles(primaryColor: string) {
413
509
  maxHeight: '80px',
414
510
  overflowY: 'auto' as const,
415
511
  },
512
+ attachBtn: {
513
+ background: 'none',
514
+ border: 'none',
515
+ cursor: 'pointer',
516
+ color: '#9ca3af',
517
+ display: 'flex',
518
+ alignItems: 'center',
519
+ justifyContent: 'center',
520
+ width: '32px',
521
+ height: '36px',
522
+ flexShrink: 0,
523
+ padding: 0,
524
+ },
416
525
  sendBtn: (color: string) => ({
417
526
  background: color,
418
527
  border: 'none',