'use client' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useTranslations } from 'next-intl' import { Camera, ChevronLeft, GripVertical, Headset, Loader2, Paperclip, Send, X, } from 'lucide-react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Textarea } from '@/components/ui/textarea' import { Label } from '@/components/ui/label' import { compressImage } from '@/lib/compress-image' import { ATTACHMENT_ACCEPT, MAX_ATTACHMENTS, MAX_MESSAGE_LENGTH, MAX_SUBJECT_LENGTH, MAX_TOTAL_ATTACHMENT_BYTES, } from '@/features/support/Lib/supportRequest' import { clearSupportDraft, readSupportDraft, writeSupportDraft, } from '@/features/support/Lib/supportDraft' import { SUPPORT_OPEN_EVENT, SUPPORT_VISIBILITY_EVENT, type SupportOpenDetail, isSupportBubbleHidden, setSupportBubbleHidden, } from '@/features/support/Lib/supportVisibility' import { useDraggablePosition } from '@/features/support/Lib/useDraggablePosition' import { useTouchScreen } from '@/features/support/Lib/useTouchScreen' type Status = 'idle' | 'sending' | 'sent' const TRIGGER_SIZE = 48 const PANEL_WIDTH = 380 const GAP = 12 /** * Error codes the endpoint can return that have their own copy. Anything * outside this list falls back to the generic message: next-intl throws on a * missing key, so an unrecognised code must never reach `t()` directly. */ const KNOWN_ERROR_CODES = [ 'subject-required', 'subject-too-long', 'message-required', 'message-too-long', 'too-many-attachments', 'attachment-type-not-allowed', 'attachments-too-large', ] as const function errorKey(code: unknown): string { return (KNOWN_ERROR_CODES as readonly string[]).includes(String(code)) ? `errors.${code}` : 'errors.sendFailed' } export function SupportBubble({ userId }: { userId: string }) { const t = useTranslations('support') const [isOpen, setIsOpen] = useState(false) // Assume hidden until localStorage has been read. Rendering the button and // then pulling it away is worse than a frame without it. const [hidden, setHidden] = useState(true) const [status, setStatus] = useState('idle') const [error, setError] = useState(null) const [subject, setSubject] = useState('') const [message, setMessage] = useState('') const [files, setFiles] = useState([]) const [capturing, setCapturing] = useState(false) const fileInputRef = useRef(null) const { position, dragging, consumeDrag, dragHandlers } = useDraggablePosition(TRIGGER_SIZE) useEffect(() => { const sync = () => setHidden(isSupportBubbleHidden()) sync() // The settings page toggles the same key. `storage` covers other tabs; the // custom event covers this one, which `storage` does not fire for. window.addEventListener('storage', sync) window.addEventListener(SUPPORT_VISIBILITY_EVENT, sync) return () => { window.removeEventListener('storage', sync) window.removeEventListener(SUPPORT_VISIBILITY_EVENT, sync) } }, []) // On a phone or tablet the floating button sits on top of what is being // tapped, so neither it nor its edge tab is drawn there. Support is still a // tap away in Settings, and the form opens as usual when a page asks for it. // Unknown for the first render: nothing is drawn until it is known, so the // button never shows for a frame on a phone. const touchScreen = useTouchScreen() /** * The panel follows the button. It is right-aligned to the button and opens * upward when the button sits low, which is where it usually will after being * dragged clear of a save button. */ const panelStyle = useMemo((): React.CSSProperties | undefined => { if (!position || typeof window === 'undefined') return undefined const viewportWidth = window.innerWidth const viewportHeight = window.innerHeight const width = Math.min(PANEL_WIDTH, viewportWidth - 2 * GAP) const left = Math.max( GAP, Math.min(position.x + TRIGGER_SIZE - width, viewportWidth - width - GAP) ) return position.y > viewportHeight / 2 ? { left, bottom: viewportHeight - position.y + GAP, width } : { left, top: position.y + TRIGGER_SIZE + GAP, width } }, [position]) const totalBytes = files.reduce((sum, f) => sum + f.size, 0) // What was being written when the page was last replaced under the form: a // tab that lost its session comes back from the sign-in page, and a new // build asks for a reload. Read after mount, like the visibility above, so // the server and the first client render agree. const [draftRestored, setDraftRestored] = useState(false) useEffect(() => { const draft = readSupportDraft(userId) if (draft) { setSubject((current) => current || draft.subject) setMessage((current) => current || draft.message) } setDraftRestored(true) }, [userId]) // Kept whenever the fields change, whether typed or handed over by a page // that opened the form. Not before the stored draft has been read back, or // the empty first render would wipe it. useEffect(() => { if (draftRestored) writeSupportDraft(userId, { subject, message }) }, [draftRestored, userId, subject, message]) const reset = useCallback(() => { setSubject('') setMessage('') setFiles([]) setError(null) setStatus('idle') clearSupportDraft() }, []) // The settings page opens the widget for someone who cannot find it, and // other pages open it with a subject, and sometimes a message, already // filled in. Each only lands on an empty field: someone halfway through // describing a problem does not lose their words because they clicked // another button. useEffect(() => { const open = (event: Event) => { const detail = (event as CustomEvent).detail const subject = detail?.subject const body = detail?.message if (subject || body) { if (status === 'sent') reset() if (subject) setSubject((current) => current || subject) if (body) setMessage((current) => current || body) } setIsOpen(true) } window.addEventListener(SUPPORT_OPEN_EVENT, open) return () => window.removeEventListener(SUPPORT_OPEN_EVENT, open) }, [status, reset]) const handleClose = useCallback(() => { setIsOpen(false) if (status !== 'sent') setError(null) }, [status]) const handleDismiss = useCallback(() => { setSupportBubbleHidden(true) setIsOpen(false) }, []) const addFiles = useCallback( async (incoming: File[]) => { setError(null) const room = MAX_ATTACHMENTS - files.length if (room <= 0) { setError(t('errors.too-many-attachments', { max: MAX_ATTACHMENTS })) return } // Images are shrunk before they are counted, so a phone photo does not // eat the whole budget on its own. const processed = await Promise.all( incoming .slice(0, room) .map((file) => file.type.startsWith('image/') ? compressImage(file) : Promise.resolve(file) ) ) const next = [...files, ...processed] if (next.reduce((sum, f) => sum + f.size, 0) > MAX_TOTAL_ATTACHMENT_BYTES) { setError(t('errors.attachments-too-large')) return } setFiles(next) }, [files, t] ) const handleScreenshot = useCallback(async () => { setCapturing(true) setError(null) // Close the panel so the capture shows the page the user is reporting on, // not the form covering it. setIsOpen(false) try { // Loaded on demand: this is a large dependency and most sessions never // open the widget, let alone take a screenshot. const { snapdom } = await import('@zumer/snapdom') // Two frames, so the panel has actually left the screen before capture. await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))) const blob = await snapdom.toBlob(document.body, { type: 'jpeg', quality: 0.7, backgroundColor: '#ffffff', }) const file = new File([blob], `screenshot-${Date.now()}.jpg`, { type: 'image/jpeg' }) await addFiles([file]) } catch { setError(t('errors.screenshotFailed')) } finally { setCapturing(false) setIsOpen(true) } }, [addFiles, t]) const handleSubmit = useCallback( async (event: React.FormEvent) => { event.preventDefault() setStatus('sending') setError(null) const body = new FormData() body.set('subject', subject) body.set('message', message) body.set('pageUrl', window.location.href) for (const file of files) body.append('files', file) try { const response = await fetch('/api/protected/support', { method: 'POST', body }) if (!response.ok) { const payload = await response.json().catch(() => ({})) setError(t(errorKey(payload.error), { max: MAX_ATTACHMENTS })) setStatus('idle') return } setStatus('sent') setSubject('') setMessage('') setFiles([]) // Sent, so it must not come back as a draft on the next page load. clearSupportDraft() } catch { setError(t('errors.sendFailed')) setStatus('idle') } }, [subject, message, files, t] ) // position is null until localStorage and the viewport have been read. if (!position || touchScreen === null) return null // Only the form, and only while it is open. The dismissal below is about // the button, so it has no say here. if (touchScreen && !isOpen) return null // Dismissed collapses to a tab tucked against the right edge rather than // disappearing. Removing the button outright leaves no way back except the // settings page, which is not somewhere you look when you want support. if (hidden && !touchScreen) { return ( ) } return ( <> {!isOpen && ( )} {isOpen && (
{/* Hidden from assistive tech rather than announced as a button. Dragging is pointer-only, so exposing it as a control would advertise something a keyboard user cannot operate. Nothing is lost: every control in the panel is reachable regardless of where it sits, and the position is only a convenience. */} {!touchScreen && ( )} {t('title')}
{status === 'sent' ? (

{t('sentTitle')}

{t('sentDescription')}

) : (
setSubject(e.target.value)} maxLength={MAX_SUBJECT_LENGTH} required placeholder={t('subjectPlaceholder')} />