SupportBubble.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. 'use client'
  2. import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
  3. import { useTranslations } from 'next-intl'
  4. import {
  5. Camera,
  6. ChevronLeft,
  7. GripVertical,
  8. Headset,
  9. Loader2,
  10. Paperclip,
  11. Send,
  12. X,
  13. } from 'lucide-react'
  14. import { Button } from '@/components/ui/button'
  15. import { Input } from '@/components/ui/input'
  16. import { Textarea } from '@/components/ui/textarea'
  17. import { Label } from '@/components/ui/label'
  18. import { compressImage } from '@/lib/compress-image'
  19. import {
  20. ATTACHMENT_ACCEPT,
  21. MAX_ATTACHMENTS,
  22. MAX_MESSAGE_LENGTH,
  23. MAX_SUBJECT_LENGTH,
  24. MAX_TOTAL_ATTACHMENT_BYTES,
  25. } from '@/features/support/Lib/supportRequest'
  26. import {
  27. clearSupportDraft,
  28. readSupportDraft,
  29. writeSupportDraft,
  30. } from '@/features/support/Lib/supportDraft'
  31. import {
  32. SUPPORT_OPEN_EVENT,
  33. SUPPORT_VISIBILITY_EVENT,
  34. type SupportOpenDetail,
  35. isSupportBubbleHidden,
  36. setSupportBubbleHidden,
  37. } from '@/features/support/Lib/supportVisibility'
  38. import { useDraggablePosition } from '@/features/support/Lib/useDraggablePosition'
  39. import { useTouchScreen } from '@/features/support/Lib/useTouchScreen'
  40. type Status = 'idle' | 'sending' | 'sent'
  41. const TRIGGER_SIZE = 48
  42. const PANEL_WIDTH = 380
  43. const GAP = 12
  44. /**
  45. * Error codes the endpoint can return that have their own copy. Anything
  46. * outside this list falls back to the generic message: next-intl throws on a
  47. * missing key, so an unrecognised code must never reach `t()` directly.
  48. */
  49. const KNOWN_ERROR_CODES = [
  50. 'subject-required',
  51. 'subject-too-long',
  52. 'message-required',
  53. 'message-too-long',
  54. 'too-many-attachments',
  55. 'attachment-type-not-allowed',
  56. 'attachments-too-large',
  57. ] as const
  58. function errorKey(code: unknown): string {
  59. return (KNOWN_ERROR_CODES as readonly string[]).includes(String(code))
  60. ? `errors.${code}`
  61. : 'errors.sendFailed'
  62. }
  63. export function SupportBubble({ userId }: { userId: string }) {
  64. const t = useTranslations('support')
  65. const [isOpen, setIsOpen] = useState(false)
  66. // Assume hidden until localStorage has been read. Rendering the button and
  67. // then pulling it away is worse than a frame without it.
  68. const [hidden, setHidden] = useState(true)
  69. const [status, setStatus] = useState<Status>('idle')
  70. const [error, setError] = useState<string | null>(null)
  71. const [subject, setSubject] = useState('')
  72. const [message, setMessage] = useState('')
  73. const [files, setFiles] = useState<File[]>([])
  74. const [capturing, setCapturing] = useState(false)
  75. const fileInputRef = useRef<HTMLInputElement>(null)
  76. const { position, dragging, consumeDrag, dragHandlers } = useDraggablePosition(TRIGGER_SIZE)
  77. useEffect(() => {
  78. const sync = () => setHidden(isSupportBubbleHidden())
  79. sync()
  80. // The settings page toggles the same key. `storage` covers other tabs; the
  81. // custom event covers this one, which `storage` does not fire for.
  82. window.addEventListener('storage', sync)
  83. window.addEventListener(SUPPORT_VISIBILITY_EVENT, sync)
  84. return () => {
  85. window.removeEventListener('storage', sync)
  86. window.removeEventListener(SUPPORT_VISIBILITY_EVENT, sync)
  87. }
  88. }, [])
  89. // On a phone or tablet the floating button sits on top of what is being
  90. // tapped, so neither it nor its edge tab is drawn there. Support is still a
  91. // tap away in Settings, and the form opens as usual when a page asks for it.
  92. // Unknown for the first render: nothing is drawn until it is known, so the
  93. // button never shows for a frame on a phone.
  94. const touchScreen = useTouchScreen()
  95. /**
  96. * The panel follows the button. It is right-aligned to the button and opens
  97. * upward when the button sits low, which is where it usually will after being
  98. * dragged clear of a save button.
  99. */
  100. const panelStyle = useMemo((): React.CSSProperties | undefined => {
  101. if (!position || typeof window === 'undefined') return undefined
  102. const viewportWidth = window.innerWidth
  103. const viewportHeight = window.innerHeight
  104. const width = Math.min(PANEL_WIDTH, viewportWidth - 2 * GAP)
  105. const left = Math.max(
  106. GAP,
  107. Math.min(position.x + TRIGGER_SIZE - width, viewportWidth - width - GAP)
  108. )
  109. return position.y > viewportHeight / 2
  110. ? { left, bottom: viewportHeight - position.y + GAP, width }
  111. : { left, top: position.y + TRIGGER_SIZE + GAP, width }
  112. }, [position])
  113. const totalBytes = files.reduce((sum, f) => sum + f.size, 0)
  114. // What was being written when the page was last replaced under the form: a
  115. // tab that lost its session comes back from the sign-in page, and a new
  116. // build asks for a reload. Read after mount, like the visibility above, so
  117. // the server and the first client render agree.
  118. const [draftRestored, setDraftRestored] = useState(false)
  119. useEffect(() => {
  120. const draft = readSupportDraft(userId)
  121. if (draft) {
  122. setSubject((current) => current || draft.subject)
  123. setMessage((current) => current || draft.message)
  124. }
  125. setDraftRestored(true)
  126. }, [userId])
  127. // Kept whenever the fields change, whether typed or handed over by a page
  128. // that opened the form. Not before the stored draft has been read back, or
  129. // the empty first render would wipe it.
  130. useEffect(() => {
  131. if (draftRestored) writeSupportDraft(userId, { subject, message })
  132. }, [draftRestored, userId, subject, message])
  133. const reset = useCallback(() => {
  134. setSubject('')
  135. setMessage('')
  136. setFiles([])
  137. setError(null)
  138. setStatus('idle')
  139. clearSupportDraft()
  140. }, [])
  141. // The settings page opens the widget for someone who cannot find it, and
  142. // other pages open it with a subject, and sometimes a message, already
  143. // filled in. Each only lands on an empty field: someone halfway through
  144. // describing a problem does not lose their words because they clicked
  145. // another button.
  146. useEffect(() => {
  147. const open = (event: Event) => {
  148. const detail = (event as CustomEvent<SupportOpenDetail>).detail
  149. const subject = detail?.subject
  150. const body = detail?.message
  151. if (subject || body) {
  152. if (status === 'sent') reset()
  153. if (subject) setSubject((current) => current || subject)
  154. if (body) setMessage((current) => current || body)
  155. }
  156. setIsOpen(true)
  157. }
  158. window.addEventListener(SUPPORT_OPEN_EVENT, open)
  159. return () => window.removeEventListener(SUPPORT_OPEN_EVENT, open)
  160. }, [status, reset])
  161. const handleClose = useCallback(() => {
  162. setIsOpen(false)
  163. if (status !== 'sent') setError(null)
  164. }, [status])
  165. const handleDismiss = useCallback(() => {
  166. setSupportBubbleHidden(true)
  167. setIsOpen(false)
  168. }, [])
  169. const addFiles = useCallback(
  170. async (incoming: File[]) => {
  171. setError(null)
  172. const room = MAX_ATTACHMENTS - files.length
  173. if (room <= 0) {
  174. setError(t('errors.too-many-attachments', { max: MAX_ATTACHMENTS }))
  175. return
  176. }
  177. // Images are shrunk before they are counted, so a phone photo does not
  178. // eat the whole budget on its own.
  179. const processed = await Promise.all(
  180. incoming
  181. .slice(0, room)
  182. .map((file) =>
  183. file.type.startsWith('image/') ? compressImage(file) : Promise.resolve(file)
  184. )
  185. )
  186. const next = [...files, ...processed]
  187. if (next.reduce((sum, f) => sum + f.size, 0) > MAX_TOTAL_ATTACHMENT_BYTES) {
  188. setError(t('errors.attachments-too-large'))
  189. return
  190. }
  191. setFiles(next)
  192. },
  193. [files, t]
  194. )
  195. const handleScreenshot = useCallback(async () => {
  196. setCapturing(true)
  197. setError(null)
  198. // Close the panel so the capture shows the page the user is reporting on,
  199. // not the form covering it.
  200. setIsOpen(false)
  201. try {
  202. // Loaded on demand: this is a large dependency and most sessions never
  203. // open the widget, let alone take a screenshot.
  204. const { snapdom } = await import('@zumer/snapdom')
  205. // Two frames, so the panel has actually left the screen before capture.
  206. await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))
  207. const blob = await snapdom.toBlob(document.body, {
  208. type: 'jpeg',
  209. quality: 0.7,
  210. backgroundColor: '#ffffff',
  211. })
  212. const file = new File([blob], `screenshot-${Date.now()}.jpg`, { type: 'image/jpeg' })
  213. await addFiles([file])
  214. } catch {
  215. setError(t('errors.screenshotFailed'))
  216. } finally {
  217. setCapturing(false)
  218. setIsOpen(true)
  219. }
  220. }, [addFiles, t])
  221. const handleSubmit = useCallback(
  222. async (event: React.FormEvent) => {
  223. event.preventDefault()
  224. setStatus('sending')
  225. setError(null)
  226. const body = new FormData()
  227. body.set('subject', subject)
  228. body.set('message', message)
  229. body.set('pageUrl', window.location.href)
  230. for (const file of files) body.append('files', file)
  231. try {
  232. const response = await fetch('/api/protected/support', { method: 'POST', body })
  233. if (!response.ok) {
  234. const payload = await response.json().catch(() => ({}))
  235. setError(t(errorKey(payload.error), { max: MAX_ATTACHMENTS }))
  236. setStatus('idle')
  237. return
  238. }
  239. setStatus('sent')
  240. setSubject('')
  241. setMessage('')
  242. setFiles([])
  243. // Sent, so it must not come back as a draft on the next page load.
  244. clearSupportDraft()
  245. } catch {
  246. setError(t('errors.sendFailed'))
  247. setStatus('idle')
  248. }
  249. },
  250. [subject, message, files, t]
  251. )
  252. // position is null until localStorage and the viewport have been read.
  253. if (!position || touchScreen === null) return null
  254. // Only the form, and only while it is open. The dismissal below is about
  255. // the button, so it has no say here.
  256. if (touchScreen && !isOpen) return null
  257. // Dismissed collapses to a tab tucked against the right edge rather than
  258. // disappearing. Removing the button outright leaves no way back except the
  259. // settings page, which is not somewhere you look when you want support.
  260. if (hidden && !touchScreen) {
  261. return (
  262. <button
  263. type="button"
  264. onClick={() => {
  265. setSupportBubbleHidden(false)
  266. setIsOpen(true)
  267. }}
  268. className="group fixed right-0 bottom-24 z-50 flex h-9 items-center gap-0 rounded-l-md border border-r-0 border-border/60 bg-background/80 pl-1.5 pr-1 text-muted-foreground/60 shadow-sm backdrop-blur transition-colors hover:bg-background hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring md:bottom-8"
  269. aria-label={t('restore')}
  270. >
  271. <ChevronLeft className="h-3.5 w-3.5 shrink-0" />
  272. {/* Collapsed to an arrow until pointed at, so it stays out of the way
  273. but still says what it does rather than relying on a tooltip. */}
  274. <span className="max-w-0 overflow-hidden whitespace-nowrap text-xs font-medium opacity-0 transition-all duration-200 group-hover:max-w-[12rem] group-hover:pr-1 group-hover:opacity-100 group-focus-visible:max-w-[12rem] group-focus-visible:pr-1 group-focus-visible:opacity-100">
  275. {t('restore')}
  276. </span>
  277. </button>
  278. )
  279. }
  280. return (
  281. <>
  282. {!isOpen && (
  283. <button
  284. type="button"
  285. {...dragHandlers}
  286. onClick={() => {
  287. // Swallow the click that ends a drag, so moving the button out of
  288. // the way does not also open the form.
  289. if (consumeDrag()) return
  290. setIsOpen(true)
  291. }}
  292. style={{ left: position.x, top: position.y, width: TRIGGER_SIZE, height: TRIGGER_SIZE }}
  293. className={`fixed z-50 flex touch-none items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg shadow-primary/25 ring-1 ring-inset ring-white/15 transition-[box-shadow,transform] hover:shadow-xl hover:shadow-primary/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${
  294. dragging ? 'scale-105 cursor-grabbing' : 'cursor-grab hover:-translate-y-0.5'
  295. }`}
  296. aria-label={t('open')}
  297. title={t('dragHint')}
  298. >
  299. <Headset className="h-[22px] w-[22px]" strokeWidth={1.75} />
  300. </button>
  301. )}
  302. {isOpen && (
  303. <div
  304. // With no button to follow, the form sits at the top of the screen:
  305. // clear of the bottom navigation, and of the on-screen keyboard that
  306. // covers the lower half as soon as a field is tapped. Below a
  307. // laptop's width it hangs from the left edge: a page that is a few
  308. // pixels too wide pushes the right edge, and the close button with
  309. // it, off a phone or small tablet.
  310. style={touchScreen ? undefined : panelStyle}
  311. className={`fixed z-50 overflow-hidden rounded-xl border bg-popover shadow-2xl ring-1 ring-black/5 dark:ring-white/10 ${
  312. touchScreen
  313. ? 'top-[calc(0.75rem+env(safe-area-inset-top))] left-3 w-[min(380px,calc(100vw-1.5rem))] lg:right-3 lg:left-auto'
  314. : ''
  315. }`}
  316. >
  317. <div
  318. className={`flex items-center gap-1 border-b bg-muted/40 py-2 pr-2 ${
  319. touchScreen ? 'pl-3' : 'pl-1'
  320. }`}
  321. >
  322. {/* Hidden from assistive tech rather than announced as a button.
  323. Dragging is pointer-only, so exposing it as a control would
  324. advertise something a keyboard user cannot operate. Nothing is
  325. lost: every control in the panel is reachable regardless of
  326. where it sits, and the position is only a convenience. */}
  327. {!touchScreen && (
  328. <span
  329. {...dragHandlers}
  330. aria-hidden="true"
  331. title={t('move')}
  332. className={`flex h-7 w-6 shrink-0 touch-none items-center justify-center text-muted-foreground/60 hover:text-muted-foreground ${
  333. dragging ? 'cursor-grabbing' : 'cursor-grab'
  334. }`}
  335. >
  336. <GripVertical className="h-4 w-4" />
  337. </span>
  338. )}
  339. <Headset className="h-4 w-4 shrink-0 text-primary" strokeWidth={1.75} />
  340. <span className="flex-1 truncate text-sm font-medium">{t('title')}</span>
  341. <button
  342. type="button"
  343. onClick={handleClose}
  344. className="rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
  345. aria-label={t('close')}
  346. >
  347. <X className="h-4 w-4" />
  348. </button>
  349. </div>
  350. <div className="max-h-[min(70vh,32rem)] overflow-y-auto p-4">
  351. {status === 'sent' ? (
  352. <div className="py-6 text-center">
  353. <p className="font-medium">{t('sentTitle')}</p>
  354. <p className="mt-1 text-sm text-muted-foreground">{t('sentDescription')}</p>
  355. <div className="mt-4 flex justify-center gap-2">
  356. <Button type="button" variant="outline" size="sm" onClick={reset}>
  357. {t('sendAnother')}
  358. </Button>
  359. <Button type="button" size="sm" onClick={handleClose}>
  360. {t('close')}
  361. </Button>
  362. </div>
  363. </div>
  364. ) : (
  365. <form onSubmit={handleSubmit} className="space-y-3">
  366. <div className="space-y-1.5">
  367. <Label htmlFor="support-subject" className="text-xs text-muted-foreground">
  368. {t('subjectLabel')}
  369. </Label>
  370. <Input
  371. id="support-subject"
  372. value={subject}
  373. onChange={(e) => setSubject(e.target.value)}
  374. maxLength={MAX_SUBJECT_LENGTH}
  375. required
  376. placeholder={t('subjectPlaceholder')}
  377. />
  378. </div>
  379. <div className="space-y-1.5">
  380. <Label htmlFor="support-message" className="text-xs text-muted-foreground">
  381. {t('messageLabel')}
  382. </Label>
  383. <Textarea
  384. id="support-message"
  385. value={message}
  386. onChange={(e) => setMessage(e.target.value)}
  387. maxLength={MAX_MESSAGE_LENGTH}
  388. required
  389. rows={4}
  390. className="resize-none"
  391. placeholder={t('messagePlaceholder')}
  392. />
  393. </div>
  394. <div className="flex gap-2">
  395. <Button
  396. type="button"
  397. variant="outline"
  398. size="sm"
  399. className="flex-1"
  400. onClick={handleScreenshot}
  401. disabled={capturing || files.length >= MAX_ATTACHMENTS}
  402. >
  403. {capturing ? (
  404. <Loader2 className="mr-1 h-4 w-4 animate-spin" />
  405. ) : (
  406. <Camera className="mr-1 h-4 w-4" />
  407. )}
  408. {t('takeScreenshot')}
  409. </Button>
  410. <Button
  411. type="button"
  412. variant="outline"
  413. size="sm"
  414. className="flex-1"
  415. onClick={() => fileInputRef.current?.click()}
  416. disabled={files.length >= MAX_ATTACHMENTS}
  417. >
  418. <Paperclip className="mr-1 h-4 w-4" />
  419. {t('addFiles')}
  420. </Button>
  421. <input
  422. ref={fileInputRef}
  423. type="file"
  424. multiple
  425. accept={ATTACHMENT_ACCEPT}
  426. className="hidden"
  427. onChange={(e) => {
  428. void addFiles(Array.from(e.target.files ?? []))
  429. e.target.value = ''
  430. }}
  431. />
  432. </div>
  433. {files.length > 0 && (
  434. <ul className="space-y-1">
  435. {files.map((file, index) => (
  436. <li
  437. key={`${file.name}-${index}`}
  438. className="flex items-center justify-between gap-2 rounded-md border bg-muted/30 px-2 py-1 text-xs"
  439. >
  440. <span className="truncate" title={file.name}>
  441. {file.name}
  442. </span>
  443. <button
  444. type="button"
  445. className="shrink-0 text-muted-foreground hover:text-destructive"
  446. onClick={() => setFiles(files.filter((_, i) => i !== index))}
  447. aria-label={t('removeAttachment')}
  448. >
  449. <X className="h-3.5 w-3.5" />
  450. </button>
  451. </li>
  452. ))}
  453. <li className="px-0.5 pt-0.5 text-[11px] text-muted-foreground">
  454. {t('attachmentSummary', {
  455. count: files.length,
  456. max: MAX_ATTACHMENTS,
  457. size: (totalBytes / (1024 * 1024)).toFixed(1),
  458. })}
  459. </li>
  460. </ul>
  461. )}
  462. {error && <p className="text-sm text-destructive">{error}</p>}
  463. <Button type="submit" className="w-full" disabled={status === 'sending'}>
  464. {status === 'sending' ? (
  465. <Loader2 className="mr-1 h-4 w-4 animate-spin" />
  466. ) : (
  467. <Send className="mr-1 h-4 w-4" />
  468. )}
  469. {status === 'sending' ? t('sending') : t('send')}
  470. </Button>
  471. {/* There is no button to hide on a phone or tablet. */}
  472. {!touchScreen && (
  473. <button
  474. type="button"
  475. onClick={handleDismiss}
  476. className="w-full text-center text-xs text-muted-foreground transition-colors hover:text-foreground hover:underline"
  477. >
  478. {t('hideButton')}
  479. </button>
  480. )}
  481. </form>
  482. )}
  483. </div>
  484. </div>
  485. )}
  486. </>
  487. )
  488. }