@adatechnology/conversations-ui 0.1.0-rc.2 → 0.1.0-rc.21

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.
Files changed (106) hide show
  1. package/dist/{chunk-ZDURDZTM.js → chunk-2AYDBWNE.js} +14 -0
  2. package/dist/chunk-TV4OQRGH.js +2187 -0
  3. package/dist/flows/index.d.ts +14 -2
  4. package/dist/flows/index.js +117 -39
  5. package/dist/index.d.ts +862 -136
  6. package/dist/index.js +1746 -1124
  7. package/dist/preview/index.d.ts +470 -0
  8. package/dist/preview/index.js +1329 -0
  9. package/dist/styles.css +228 -0
  10. package/dist/types-C6A_9edv.d.ts +456 -0
  11. package/package.json +10 -3
  12. package/src/AudioRecorderButton.test.tsx +30 -0
  13. package/src/AudioRecorderButton.tsx +248 -0
  14. package/src/AudioTranscription.test.tsx +115 -0
  15. package/src/AudioTranscription.tsx +249 -0
  16. package/src/Avatar.tsx +30 -4
  17. package/src/ChannelIcon.tsx +87 -0
  18. package/src/ConversationContextPanel.tsx +280 -0
  19. package/src/ConversationDocumentsPanel.tsx +425 -0
  20. package/src/ConversationHeader.tsx +257 -0
  21. package/src/ConversationListItem.tsx +54 -7
  22. package/src/ConversationLocalesProvider.tsx +44 -0
  23. package/src/ConversationRow.tsx +137 -0
  24. package/src/DateDivider.tsx +16 -3
  25. package/src/DocumentsLibrary.tsx +322 -0
  26. package/src/EmojiPicker.tsx +69 -55
  27. package/src/FileIcon.test.ts +83 -0
  28. package/src/FileIcon.tsx +88 -11
  29. package/src/InteractiveMessage.test.tsx +41 -0
  30. package/src/InteractiveMessage.tsx +143 -0
  31. package/src/Lightbox.tsx +18 -3
  32. package/src/MediaRenderer.tsx +96 -22
  33. package/src/MessageBubble.tsx +77 -5
  34. package/src/MessageComposer.test.tsx +35 -0
  35. package/src/MessageComposer.tsx +165 -19
  36. package/src/RichMessageComposer.test.tsx +83 -0
  37. package/src/RichMessageComposer.tsx +380 -0
  38. package/src/Wallpaper.test.tsx +21 -0
  39. package/src/Wallpaper.tsx +69 -7
  40. package/src/WhatsAppMessageEditor.tsx +28 -4
  41. package/src/WindowExpiredNotice.tsx +57 -0
  42. package/src/audioRecorderFormat.test.ts +67 -0
  43. package/src/conversationChannel.test.ts +53 -0
  44. package/src/conversationChannel.ts +146 -0
  45. package/src/conversationTranscript.test.ts +122 -0
  46. package/src/conversationTranscript.ts +89 -0
  47. package/src/conversationWindow.test.ts +90 -0
  48. package/src/conversationWindow.ts +78 -0
  49. package/src/documentTypeLabel.test.ts +57 -0
  50. package/src/emojiCatalog.test.ts +35 -0
  51. package/src/emojiCatalog.ts +189 -0
  52. package/src/flows/FlowGroupHeader.tsx +12 -2
  53. package/src/flows/FlowMapCanvas.tsx +17 -14
  54. package/src/flows/FlowMapNode.tsx +3 -1
  55. package/src/flows/FlowNodeCard.tsx +22 -4
  56. package/src/flows/FlowNodePanel.tsx +132 -35
  57. package/src/flows/FlowPalette.tsx +6 -2
  58. package/src/flows/FlowWhatsAppPreview.tsx +14 -3
  59. package/src/flows/flowGraph.ts +5 -5
  60. package/src/flows/labels.ts +5 -0
  61. package/src/hooks/useConversationActions.ts +56 -0
  62. package/src/hooks/useConversationDocuments.ts +15 -9
  63. package/src/hooks/useConversationList.ts +15 -9
  64. package/src/hooks/useConversationMessages.ts +2 -2
  65. package/src/hooks/useScrollToLatestMessage.ts +127 -0
  66. package/src/index.ts +140 -16
  67. package/src/lib/cn.test.ts +29 -0
  68. package/src/lib/cn.ts +15 -0
  69. package/src/lib/createMediaUrlResolver.ts +33 -0
  70. package/src/lib/paginated.test.ts +33 -0
  71. package/src/lib/paginated.ts +26 -0
  72. package/src/lib/phone.ts +34 -0
  73. package/src/preview/ConversationPreview.tsx +334 -0
  74. package/src/preview/MediaTypesPreview.tsx +87 -0
  75. package/src/preview/conversationPreviewFailures.test.ts +64 -0
  76. package/src/preview/createMockConversationsApi.ts +271 -0
  77. package/src/preview/createMockSSEProvider.ts +40 -0
  78. package/src/preview/createPreviewBridgeClient.test.ts +92 -0
  79. package/src/preview/createPreviewBridgeClient.ts +124 -0
  80. package/src/preview/createPreviewMediaUploader.ts +82 -0
  81. package/src/preview/createPreviewWebhookClient.test.ts +194 -0
  82. package/src/preview/createPreviewWebhookClient.ts +222 -0
  83. package/src/preview/index.ts +67 -0
  84. package/src/preview/mediaTypeOf.test.ts +15 -0
  85. package/src/preview/mockDocumentsSearch.test.ts +57 -0
  86. package/src/preview/mockEventSource.ts +53 -0
  87. package/src/preview/preview.test.ts +177 -0
  88. package/src/preview/previewFileSamples.test.ts +151 -0
  89. package/src/preview/previewFileSamples.ts +74 -0
  90. package/src/preview/previewFixtures.ts +440 -0
  91. package/src/preview/previewMediaSource.test.ts +62 -0
  92. package/src/preview/previewMediaSource.ts +91 -0
  93. package/src/preview/previewMediaUploader.test.ts +61 -0
  94. package/src/preview/previewStore.ts +193 -0
  95. package/src/preview/startPreviewScript.ts +60 -0
  96. package/src/providers/types.ts +175 -12
  97. package/src/quickReply.test.ts +58 -0
  98. package/src/settings/TranscriptionSettingsForm.test.tsx +81 -0
  99. package/src/settings/TranscriptionSettingsForm.tsx +189 -0
  100. package/src/settings/WhatsAppCreateTemplateForm.tsx +3 -1
  101. package/src/settings/WhatsAppTemplatesSettings.tsx +106 -0
  102. package/src/styles.css +173 -0
  103. package/src/types.ts +72 -1
  104. package/src/useDarkMode.ts +26 -0
  105. package/src/useIsNarrow.ts +29 -0
  106. package/src/useWaitingNotifications.ts +74 -29
@@ -0,0 +1,249 @@
1
+ import { useCallback, useState } from 'react'
2
+ import { Check, Copy, FileText, Loader2, RefreshCw } from 'lucide-react'
3
+ import { useConversationLocales } from './ConversationLocalesProvider'
4
+ import { cn } from './lib/cn'
5
+ import type { MessageTranscription } from './types'
6
+
7
+ export interface AudioTranscriptionProps {
8
+ transcription?: MessageTranscription | null
9
+ /**
10
+ * Pede a transcrição ao backend. Ausente, o bloco nunca oferece o botão — um host em modo
11
+ * automático não tem rota para isso, e desenhar um botão que estoura no clique é pior do que não
12
+ * desenhar nada.
13
+ *
14
+ * O que for devolvido é exibido na hora. Sem isso o texto só apareceria no próximo refetch da
15
+ * lista, e transcrição não emite evento de tempo real: o operador clicaria, veria o spinner
16
+ * terminar e continuaria sem o texto na tela.
17
+ */
18
+ onTranscribe?: () => Promise<MessageTranscription | void>
19
+ isMine?: boolean
20
+ }
21
+
22
+ /** Feedback de "copiado" some sozinho — confirmação que exige clique para fechar é ruído. */
23
+ const COPIED_FEEDBACK_MS = 2000
24
+
25
+ /**
26
+ * Acima disto a transcrição nasce recolhida.
27
+ *
28
+ * Medido: 1147 caracteres (cerca de um minuto de fala) produziram uma bolha de 854px — mais alta que
29
+ * a área visível da conversa, empurrando todo o resto para fora. Nota de voz de três minutos
30
+ * triplicaria. O limite é em caracteres, e não em linhas de CSS, porque a decisão precisa acontecer
31
+ * antes de renderizar: `line-clamp` sozinho esconde o texto mas ainda paga o layout inteiro.
32
+ */
33
+ const COLLAPSE_ABOVE_CHARS = 320
34
+
35
+ /** Linhas visíveis quando recolhido — o bastante para saber do que o cliente está falando. */
36
+ const COLLAPSED_LINE_CLAMP = 4
37
+
38
+ /**
39
+ * Transcrição sob a nota de voz, com botão de copiar.
40
+ *
41
+ * Copiar é o motivo de o bloco existir: o operador cola o pedido do cliente no sistema interno, no
42
+ * orçamento, na busca. Seleção manual de texto dentro de um balão de chat é exatamente onde o
43
+ * arrasto do mouse falha — pega o balão vizinho, o horário, o nome do remetente.
44
+ *
45
+ * `navigator.clipboard.writeText` com try/catch silencioso, mesmo padrão de `MessageText.tsx`: a API
46
+ * exige contexto seguro e permissão, e um host servindo em HTTP simples não a tem. Falhar sem alarme
47
+ * é o certo — o texto continua na tela para seleção manual.
48
+ */
49
+ export function AudioTranscription({ transcription, onTranscribe, isMine = false }: AudioTranscriptionProps) {
50
+ const { transcription: locales } = useConversationLocales()
51
+ const [hasCopied, setHasCopied] = useState(false)
52
+ const [isTranscribing, setIsTranscribing] = useState(false)
53
+ const [hasRequestFailed, setHasRequestFailed] = useState(false)
54
+ /**
55
+ * Resultado que acabou de voltar do backend, exibido antes de a lista ser refeita.
56
+ *
57
+ * Tem precedência sobre a prop porque é o dado mais novo: o refetch, quando vier, traz a mesma
58
+ * coisa. Sem isto o clique terminaria em nada visível.
59
+ */
60
+ const [justTranscribed, setJustTranscribed] = useState<MessageTranscription | undefined>()
61
+ const [isExpanded, setIsExpanded] = useState(false)
62
+
63
+ const effective = justTranscribed ?? transcription
64
+ const text = effective?.text?.trim() ?? ''
65
+ const status = effective?.status
66
+
67
+ // Nasce recolhido e o operador decide: abrir tudo por padrão faria a nota de voz longa esconder as
68
+ // mensagens seguintes, que é justamente o contexto de que ele precisa para responder.
69
+ const isLong = text.length > COLLAPSE_ABOVE_CHARS
70
+ const isTruncated = isLong && !isExpanded
71
+ const isDone = status === 'done'
72
+ const hasText = isDone && text.length > 0
73
+ // Silêncio já processado: dizer "sem fala detectada" evita o operador clicar em transcrever de novo
74
+ // atrás de um texto que não existe.
75
+ const isSilent = isDone && text.length === 0
76
+
77
+ const handleCopy = useCallback(async () => {
78
+ if (!text) return
79
+ try {
80
+ await navigator.clipboard.writeText(text)
81
+ setHasCopied(true)
82
+ setTimeout(() => setHasCopied(false), COPIED_FEEDBACK_MS)
83
+ } catch {
84
+ // Clipboard indisponível (contexto não seguro, permissão negada) — o texto segue selecionável.
85
+ }
86
+ }, [text])
87
+
88
+ const handleTranscribe = useCallback(async () => {
89
+ if (!onTranscribe || isTranscribing) return
90
+ setIsTranscribing(true)
91
+ setHasRequestFailed(false)
92
+ try {
93
+ const result = await onTranscribe()
94
+ if (result) setJustTranscribed(result)
95
+ } catch {
96
+ setHasRequestFailed(true)
97
+ } finally {
98
+ setIsTranscribing(false)
99
+ }
100
+ }, [onTranscribe, isTranscribing])
101
+
102
+ const dividerClass = isMine ? 'border-black/10 dark:border-white/10' : 'border-black/10 dark:border-white/10'
103
+
104
+ // Nada avaliado e sem rota para pedir: o balão fica como era antes da transcrição existir.
105
+ if (!status && !onTranscribe) return null
106
+
107
+ if (!status || status === 'pending' || status === 'failed') {
108
+ return (
109
+ <div className={`mt-1.5 border-t pt-1.5 ${dividerClass}`}>
110
+ <TranscribeButton
111
+ label={resolveActionLabel({ status, hasRequestFailed, isTranscribing, locales })}
112
+ isBusy={isTranscribing}
113
+ onClick={handleTranscribe}
114
+ isDisabled={!onTranscribe}
115
+ />
116
+ </div>
117
+ )
118
+ }
119
+
120
+ if (status === 'unsupported') {
121
+ return (
122
+ <div className={`mt-1.5 border-t pt-1.5 ${dividerClass}`}>
123
+ <p className="text-xs italic text-gray-500 dark:text-gray-400">{locales.unsupported}</p>
124
+ </div>
125
+ )
126
+ }
127
+
128
+ return (
129
+ <div className={`mt-1.5 border-t pt-1.5 ${dividerClass}`}>
130
+ <div className="mb-0.5 flex items-center gap-1.5">
131
+ <FileText size={11} className="flex-shrink-0 text-gray-500 dark:text-gray-400" aria-hidden />
132
+ <span className="text-[11px] font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">
133
+ {locales.label}
134
+ </span>
135
+
136
+ {hasText && (
137
+ <button
138
+ onClick={handleCopy}
139
+ title={locales.copy}
140
+ aria-label={hasCopied ? locales.copied : locales.copy}
141
+ className="ml-auto flex flex-shrink-0 items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-gray-500 transition-colors hover:bg-black/5 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/10 dark:hover:text-gray-200"
142
+ >
143
+ {hasCopied ? (
144
+ <>
145
+ <Check size={11} aria-hidden />
146
+ <span>{locales.copied}</span>
147
+ </>
148
+ ) : (
149
+ <>
150
+ <Copy size={11} aria-hidden />
151
+ <span>{locales.copy}</span>
152
+ </>
153
+ )}
154
+ </button>
155
+ )}
156
+ </div>
157
+
158
+ {isSilent ? (
159
+ <p className="text-xs italic text-gray-500 dark:text-gray-400">{locales.empty}</p>
160
+ ) : (
161
+ <>
162
+ {/* `select-all` para o clique único selecionar tudo: é o fallback quando o clipboard não
163
+ está disponível, e o caminho de quem prefere copiar com o teclado. */}
164
+ <p
165
+ className={cn(
166
+ 'select-all whitespace-pre-wrap break-words text-[13px] leading-[18px] text-gray-700 dark:text-gray-200',
167
+ isTruncated && 'overflow-hidden',
168
+ )}
169
+ style={
170
+ isTruncated
171
+ ? {
172
+ display: '-webkit-box',
173
+ WebkitBoxOrient: 'vertical',
174
+ WebkitLineClamp: COLLAPSED_LINE_CLAMP,
175
+ }
176
+ : undefined
177
+ }
178
+ >
179
+ {text}
180
+ </p>
181
+ {/* O botão de copiar leva o texto INTEIRO, recolhido ou não — recolher é sobre altura na
182
+ tela, não sobre o que o operador cola no sistema interno. */}
183
+ {isLong && (
184
+ <button
185
+ onClick={() => setIsExpanded((current) => !current)}
186
+ className="mt-1 text-[11px] font-medium text-gray-500 underline decoration-dotted hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
187
+ >
188
+ {isExpanded ? locales.showLess : locales.showMore}
189
+ </button>
190
+ )}
191
+ </>
192
+ )}
193
+
194
+ {/* Retranscrever fica escondido atrás do hover do balão: é ação rara e paga cota de engine. */}
195
+ {onTranscribe && (
196
+ <button
197
+ onClick={handleTranscribe}
198
+ disabled={isTranscribing}
199
+ className="mt-1 flex items-center gap-1 text-[11px] text-gray-400 opacity-0 transition-opacity hover:text-gray-600 focus:opacity-100 group-hover:opacity-100 disabled:opacity-50 dark:text-gray-500 dark:hover:text-gray-300"
200
+ >
201
+ {isTranscribing ? <Loader2 size={10} className="animate-spin" aria-hidden /> : <RefreshCw size={10} aria-hidden />}
202
+ <span>{isTranscribing ? locales.transcribing : locales.retry}</span>
203
+ </button>
204
+ )}
205
+ </div>
206
+ )
207
+ }
208
+
209
+ function resolveActionLabel(params: {
210
+ status?: MessageTranscription['status']
211
+ hasRequestFailed: boolean
212
+ isTranscribing: boolean
213
+ locales: { transcribe: string; transcribing: string; retry: string; failed: string }
214
+ }): string {
215
+ if (params.isTranscribing) return params.locales.transcribing
216
+ if (params.hasRequestFailed) return params.locales.retry
217
+ // `pending` é cota estourada ou falha transitória do lado do servidor: já foi tentado e vai sair,
218
+ // mas o operador que não quer esperar a retomada pode forçar agora.
219
+ if (params.status === 'pending') return params.locales.transcribing
220
+ if (params.status === 'failed') return params.locales.failed
221
+ return params.locales.transcribe
222
+ }
223
+
224
+ function TranscribeButton({
225
+ label,
226
+ isBusy,
227
+ isDisabled,
228
+ onClick,
229
+ }: {
230
+ label: string
231
+ isBusy: boolean
232
+ isDisabled: boolean
233
+ onClick: () => void
234
+ }) {
235
+ return (
236
+ <button
237
+ onClick={onClick}
238
+ disabled={isBusy || isDisabled}
239
+ className="flex items-center gap-1.5 rounded px-1.5 py-0.5 text-[11px] text-gray-500 transition-colors hover:bg-black/5 hover:text-gray-700 disabled:opacity-60 dark:text-gray-400 dark:hover:bg-white/10 dark:hover:text-gray-200"
240
+ >
241
+ {isBusy ? (
242
+ <Loader2 size={11} className="animate-spin" aria-hidden />
243
+ ) : (
244
+ <FileText size={11} aria-hidden />
245
+ )}
246
+ <span>{label}</span>
247
+ </button>
248
+ )
249
+ }
package/src/Avatar.tsx CHANGED
@@ -1,8 +1,18 @@
1
+ export interface AvatarLabels {
2
+ /** Lido por leitor de tela quando não há nome nem imagem — a silhueta genérica. */
3
+ unnamedContact: string
4
+ }
5
+
1
6
  export interface AvatarProps {
2
7
  name?: string | null
3
8
  avatarUrl?: string
4
9
  size?: 'sm' | 'md' | 'lg'
5
10
  className?: string
11
+ labels?: Partial<AvatarLabels>
12
+ }
13
+
14
+ export const DEFAULT_AVATAR_LABELS: AvatarLabels = {
15
+ unnamedContact: 'Contato sem nome',
6
16
  }
7
17
 
8
18
  const sizeClasses = {
@@ -36,8 +46,9 @@ function getBgColor(name: string | undefined | null): string {
36
46
 
37
47
  // Paridade com financiamento-imobiliario-bot/apps/web/src/components/Avatar.tsx —
38
48
  // mesmas iniciais (primeira+última letra), mesmo hash de cor, mesmas classes de tamanho.
39
- export function Avatar({ name, avatarUrl, size = 'md', className = '' }: AvatarProps) {
49
+ export function Avatar({ name, avatarUrl, size = 'md', className = '', labels }: AvatarProps) {
40
50
  const sizeClass = sizeClasses[size]
51
+ const unnamedContactLabel = labels?.unnamedContact ?? DEFAULT_AVATAR_LABELS.unnamedContact
41
52
 
42
53
  if (avatarUrl) {
43
54
  return (
@@ -49,15 +60,30 @@ export function Avatar({ name, avatarUrl, size = 'md', className = '' }: AvatarP
49
60
  )
50
61
  }
51
62
 
52
- const initials = getInitials(name)
53
63
  const bgColor = getBgColor(name)
54
64
 
65
+ // Sem nome e sem imagem, a silhueta genérica. Iniciais exigem nome — derivá-las de um telefone
66
+ // produz rótulo sem significado ("+9"), que é pior que assumir o anonimato.
67
+ if (!name) {
68
+ return (
69
+ <div
70
+ className={`${sizeClass} ${bgColor} rounded-full flex items-center justify-center text-white flex-shrink-0 ${className}`}
71
+ role="img"
72
+ aria-label={unnamedContactLabel}
73
+ >
74
+ <svg viewBox="0 0 24 24" fill="currentColor" className="h-[60%] w-[60%]" aria-hidden>
75
+ <path d="M12 12a5 5 0 1 0 0-10 5 5 0 0 0 0 10Zm0 2c-4.42 0-8 2.24-8 5v1h16v-1c0-2.76-3.58-5-8-5Z" />
76
+ </svg>
77
+ </div>
78
+ )
79
+ }
80
+
55
81
  return (
56
82
  <div
57
83
  className={`${sizeClass} ${bgColor} rounded-full flex items-center justify-center text-white font-semibold flex-shrink-0 ${className}`}
58
- title={name || undefined}
84
+ title={name}
59
85
  >
60
- {initials}
86
+ {getInitials(name)}
61
87
  </div>
62
88
  )
63
89
  }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Marca visual de cada canal.
3
+ *
4
+ * SVG em vez de emoji porque emoji não tem logo de marca: 💬 e 📨 não distinguem WhatsApp de
5
+ * Messenger para quem bate o olho numa fila de conversas. São marcas **simplificadas** desenhadas
6
+ * com primitivas — reconhecíveis pela forma e pela cor oficial, sem reproduzir o logotipo original.
7
+ *
8
+ * `currentColor` não serve aqui: a cor faz parte da identificação do canal.
9
+ */
10
+
11
+ import { CONVERSATION_CHANNEL, capabilitiesOf, type ConversationChannel } from './conversationChannel'
12
+
13
+ export const CHANNEL_BRAND_COLOR: Readonly<Record<ConversationChannel, string>> = {
14
+ [CONVERSATION_CHANNEL.WHATSAPP]: '#25D366',
15
+ [CONVERSATION_CHANNEL.MESSENGER]: '#0084FF',
16
+ [CONVERSATION_CHANNEL.INSTAGRAM]: '#E4405F',
17
+ [CONVERSATION_CHANNEL.WEBCHAT]: '#64748B',
18
+ }
19
+
20
+ export interface ChannelIconProps {
21
+ channel?: ConversationChannel | undefined
22
+ size?: number
23
+ className?: string
24
+ }
25
+
26
+ function Glyph({ channel }: { channel: ConversationChannel }) {
27
+ const color = CHANNEL_BRAND_COLOR[channel]
28
+
29
+ if (channel === CONVERSATION_CHANNEL.WHATSAPP) {
30
+ return (
31
+ <>
32
+ <circle cx="12" cy="12" r="11" fill={color} />
33
+ {/* Handset estilizado, o traço que identifica a marca à distância. */}
34
+ <path
35
+ d="M8.6 7.2c.3-.1.7 0 .9.3l1 1.6c.2.3.1.7-.1.9l-.7.7c.6 1.3 1.6 2.3 2.9 2.9l.7-.7c.2-.2.6-.3.9-.1l1.6 1c.3.2.4.6.3.9-.4 1-1.4 1.6-2.4 1.4-3-.5-5.4-2.9-5.9-5.9-.2-1 .4-2 1.4-2.4Z"
36
+ fill="#fff"
37
+ />
38
+ </>
39
+ )
40
+ }
41
+
42
+ if (channel === CONVERSATION_CHANNEL.MESSENGER) {
43
+ return (
44
+ <>
45
+ <circle cx="12" cy="12" r="11" fill={color} />
46
+ {/* Raio do Messenger. */}
47
+ <path d="M6.5 15.5 11 10.8l2.4 2.4L17.5 9l-4.6 4.9-2.4-2.4-4 4Z" fill="#fff" stroke="#fff" strokeWidth="1.4" strokeLinejoin="round" />
48
+ </>
49
+ )
50
+ }
51
+
52
+ if (channel === CONVERSATION_CHANNEL.INSTAGRAM) {
53
+ return (
54
+ <>
55
+ <rect x="2" y="2" width="20" height="20" rx="6" fill={color} />
56
+ <rect x="6.5" y="6.5" width="11" height="11" rx="3.5" fill="none" stroke="#fff" strokeWidth="1.6" />
57
+ <circle cx="12" cy="12" r="2.6" fill="none" stroke="#fff" strokeWidth="1.6" />
58
+ <circle cx="16.4" cy="7.6" r="1" fill="#fff" />
59
+ </>
60
+ )
61
+ }
62
+
63
+ return (
64
+ <>
65
+ <circle cx="12" cy="12" r="11" fill={color} />
66
+ <path d="M6.5 8.5h11v7h-5.5L8.5 18v-2.5h-2v-7Z" fill="#fff" />
67
+ </>
68
+ )
69
+ }
70
+
71
+ export function ChannelIcon({ channel, size = 14, className = '' }: ChannelIconProps) {
72
+ const resolved: ConversationChannel = channel ?? CONVERSATION_CHANNEL.WHATSAPP
73
+ const { label } = capabilitiesOf(resolved)
74
+
75
+ return (
76
+ <svg
77
+ viewBox="0 0 24 24"
78
+ width={size}
79
+ height={size}
80
+ className={`inline-block shrink-0 ${className}`.trim()}
81
+ role="img"
82
+ aria-label={label}
83
+ >
84
+ <Glyph channel={resolved} />
85
+ </svg>
86
+ )
87
+ }
@@ -0,0 +1,280 @@
1
+ /**
2
+ * "Suas Seleções": o que o bot já coletou na conversa. Para o atendente que assume no meio, é a
3
+ * diferença entre ler o transcript inteiro e ver o estado de relance.
4
+ *
5
+ * O pacote não interpreta o contexto — ele é `Record<string, unknown>` e cada produto nomeia as
6
+ * próprias chaves. O host traduz para `entries`; aqui só se decide como mostrar.
7
+ *
8
+ * Desenho em paridade com financiamento-imobiliario-bot/apps/web/src/components/SelectionsSummary.tsx:
9
+ * card com gradiente, badge de contagem, pills de status no cabeçalho e grid de cards com borda
10
+ * colorida por estado. O que ficou diferente de lá, e por quê, está comentado no ponto.
11
+ */
12
+
13
+ import { useState } from 'react'
14
+ import { Check, ChevronDown, ChevronUp, Clock, Pencil } from 'lucide-react'
15
+
16
+ import { cn } from './lib/cn'
17
+ import { useIsNarrow } from './useIsNarrow'
18
+
19
+ /**
20
+ * `completed` tem valor, `pending` ainda não foi coletado, `editing` é o cliente refazendo a
21
+ * resposta. O host só precisa mandar `status` para o terceiro caso — os dois primeiros saem do
22
+ * próprio `value`, e exigir o campo quebraria quem já usa o painel.
23
+ */
24
+ export type ConversationContextStatus = 'completed' | 'pending' | 'editing'
25
+
26
+ export interface ConversationContextEntry {
27
+ key: string
28
+ label: string
29
+ value?: string | undefined
30
+ icon?: string
31
+ status?: ConversationContextStatus
32
+ }
33
+
34
+ export interface ConversationContextPanelLabels {
35
+ title: string
36
+ empty: string
37
+ collapse: string
38
+ expand: string
39
+ /** Placeholder do card ainda não coletado. */
40
+ notCollected: string
41
+ }
42
+
43
+ export const DEFAULT_CONVERSATION_CONTEXT_LABELS: ConversationContextPanelLabels = {
44
+ title: 'Suas Seleções',
45
+ empty: 'Nada coletado ainda nesta conversa.',
46
+ collapse: 'fechar',
47
+ expand: 'abrir',
48
+ notCollected: 'a coletar',
49
+ }
50
+
51
+ export interface ConversationContextPanelClassNames {
52
+ root: string
53
+ toggle: string
54
+ counter: string
55
+ body: string
56
+ }
57
+
58
+ export interface ConversationContextPanelProps {
59
+ entries: readonly ConversationContextEntry[]
60
+ /**
61
+ * Estado inicial. Ausente, abre sozinho no desktop quando há algum dado preenchido.
62
+ *
63
+ * Existe porque "abre sozinho" nem sempre é o que o produto quer: com 1 de 6 campos preenchidos o
64
+ * painel ocupa altura mostrando quase só pendências, e empurra a conversa — que é o que se veio ver.
65
+ */
66
+ defaultOpen?: boolean
67
+ /**
68
+ * Rótulo do fluxo em curso, exibido em azul ao lado do título — no financiamento é o produto
69
+ * escolhido ("Consórcio", "MCMV"). Ausente, o cabeçalho fica só com título e contagens.
70
+ */
71
+ flowLabel?: string
72
+ labels?: Partial<ConversationContextPanelLabels>
73
+ className?: string
74
+ classNames?: Partial<ConversationContextPanelClassNames>
75
+ }
76
+
77
+ function statusOf(entry: ConversationContextEntry): ConversationContextStatus {
78
+ if (entry.status) return entry.status
79
+ return entry.value ? 'completed' : 'pending'
80
+ }
81
+
82
+ /** Borda e fundo do card por estado. Pendente é tracejado — ver o comentário no grid. */
83
+ const CARD_STYLE: Record<ConversationContextStatus, string> = {
84
+ completed: 'bg-white dark:bg-gray-800 border-2 border-green-200 dark:border-green-800 shadow-sm',
85
+ editing: 'bg-white dark:bg-gray-800 border-2 border-blue-200 dark:border-blue-800 shadow-sm',
86
+ pending: 'border-2 border-dashed border-gray-200 bg-white/40 dark:border-gray-700 dark:bg-gray-800/30',
87
+ }
88
+
89
+ const GLYPH_STYLE: Record<ConversationContextStatus, string> = {
90
+ completed: 'text-green-600 dark:text-green-400',
91
+ editing: 'text-blue-600 dark:text-blue-400',
92
+ pending: 'text-gray-400 dark:text-gray-500',
93
+ }
94
+
95
+ function StatusGlyph({ status }: { status: ConversationContextStatus }) {
96
+ const size = 11
97
+ if (status === 'completed') return <Check size={size} aria-hidden />
98
+ if (status === 'editing') return <Pencil size={size} aria-hidden />
99
+ return <Clock size={size} aria-hidden />
100
+ }
101
+
102
+ function CountPill({
103
+ status,
104
+ count,
105
+ className,
106
+ }: {
107
+ status: ConversationContextStatus
108
+ count: number
109
+ className: string
110
+ }) {
111
+ if (count === 0) return null
112
+
113
+ return (
114
+ <span className={cn('flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium', className)}>
115
+ <StatusGlyph status={status} />
116
+ {count}
117
+ </span>
118
+ )
119
+ }
120
+
121
+ export function ConversationContextPanel({
122
+ entries,
123
+ defaultOpen,
124
+ flowLabel,
125
+ labels: labelsOverride,
126
+ className,
127
+ classNames,
128
+ }: ConversationContextPanelProps) {
129
+ const labels = { ...DEFAULT_CONVERSATION_CONTEXT_LABELS, ...labelsOverride }
130
+
131
+ const counts = { completed: 0, pending: 0, editing: 0 }
132
+ for (const entry of entries) counts[statusOf(entry)] += 1
133
+
134
+ // Abre sozinho só quando há algo coletado: um painel de seis pendências ocupa a altura da conversa
135
+ // sem informar nada. As contagens continuam visíveis fechado, que é o dado útil de relance.
136
+ //
137
+ // `undefined` = usuário ainda não mexeu. Guardar só um booleano não serve: o contexto chega
138
+ // depois da montagem, então o estado inicial seria calculado com a lista vazia e o painel ficaria
139
+ // fechado mesmo com dados.
140
+ const isNarrow = useIsNarrow()
141
+ const [manualOpen, setManualOpen] = useState<boolean | undefined>(undefined)
142
+ // No celular nasce fechado mesmo com dados: aberto, o painel consome ~150px da conversa.
143
+ const open = manualOpen ?? defaultOpen ?? (!isNarrow && counts.completed > 0)
144
+
145
+ return (
146
+ // Faixa azul clara com separador, como o wrapper do financiamento: sem ela o card encostava
147
+ // direto no papel de parede da conversa e os dois blocos se misturavam.
148
+ <div className={cn('border-b bg-blue-50/60 px-3 py-3 dark:border-gray-700 dark:bg-blue-950/20', className)}>
149
+ <section
150
+ className={cn(
151
+ 'overflow-hidden rounded-lg border border-blue-200 bg-gradient-to-br from-blue-50 to-indigo-50 dark:border-blue-900 dark:from-blue-950/30 dark:to-indigo-950/30',
152
+ classNames?.root,
153
+ )}
154
+ >
155
+ <button
156
+ type="button"
157
+ onClick={() => setManualOpen(!open)}
158
+ aria-expanded={open}
159
+ title={open ? labels.collapse : labels.expand}
160
+ className={cn(
161
+ 'flex w-full cursor-pointer items-center justify-between gap-2 px-4 py-2.5 text-left transition-colors hover:bg-blue-100/40 dark:hover:bg-blue-900/20',
162
+ classNames?.toggle,
163
+ )}
164
+ >
165
+ <span className="flex min-w-0 items-center gap-2">
166
+ <span aria-hidden className="text-base leading-none">
167
+ 📋
168
+ </span>
169
+ <span className="truncate text-sm font-semibold text-gray-900 dark:text-gray-100">{labels.title}</span>
170
+ {flowLabel ? (
171
+ <span className="truncate text-xs font-medium text-blue-600 dark:text-blue-400">{flowLabel}</span>
172
+ ) : null}
173
+ <span
174
+ className={cn(
175
+ 'inline-flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full bg-blue-600 text-xs font-medium text-white',
176
+ classNames?.counter,
177
+ )}
178
+ >
179
+ {entries.length}
180
+ </span>
181
+ </span>
182
+
183
+ <span className="flex flex-shrink-0 items-center gap-2">
184
+ <CountPill
185
+ status="completed"
186
+ count={counts.completed}
187
+ className="bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"
188
+ />
189
+ <CountPill
190
+ status="editing"
191
+ count={counts.editing}
192
+ className="bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"
193
+ />
194
+ <CountPill
195
+ status="pending"
196
+ count={counts.pending}
197
+ className="bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400"
198
+ />
199
+ {open ? (
200
+ <ChevronUp size={15} className="flex-shrink-0 text-blue-500" aria-hidden />
201
+ ) : (
202
+ <ChevronDown size={15} className="flex-shrink-0 text-blue-500" aria-hidden />
203
+ )}
204
+ </span>
205
+ </button>
206
+
207
+ {open ? (
208
+ /**
209
+ * Teto de altura com rolagem interna, como no financiamento (`max-h-64 overflow-y-auto`).
210
+ * Sem isso o painel cresce sem limite — e cresce de verdade: o host anexa as chaves de
211
+ * contexto que ele não conhece ao fim da lista, então uma conversa com bastante estado
212
+ * empurrava a conversa inteira para fora da tela.
213
+ *
214
+ * A diferença: lá o teto envolve o cabeçalho também, então ele rola junto e sai de vista.
215
+ * Aqui só o corpo rola — o cabeçalho é o que fecha o painel, e perder o clique de fechar
216
+ * no meio da rolagem é pior do que a economia de uma linha de markup.
217
+ */
218
+ <div
219
+ className={cn(
220
+ 'cv-scrollbar-thin max-h-64 overflow-y-auto border-t border-blue-200 px-4 pb-4 pt-1 dark:border-blue-900',
221
+ classNames?.body,
222
+ )}
223
+ >
224
+ {entries.length === 0 ? (
225
+ <p className="pt-2 text-xs text-gray-500 dark:text-gray-400">{labels.empty}</p>
226
+ ) : (
227
+ /**
228
+ * Três colunas no desktop, como no financiamento — com duas, seis campos viravam uma
229
+ * coluna alta que empurrava a conversa.
230
+ *
231
+ * O que não fizemos igual: lá o painel FILTRA o que não foi coletado, porque a fonte
232
+ * só guarda o que o cliente respondeu. Aqui a lista de campos é conhecida de antemão,
233
+ * e "falta endereço" é justamente o que o atendente precisa ver ao assumir. Então o
234
+ * pendente aparece — tracejado e apagado, para ler como lacuna e não como dado.
235
+ */
236
+ <dl className="mt-2 grid grid-cols-2 gap-2 lg:grid-cols-3">
237
+ {entries.map((entry) => {
238
+ const status = statusOf(entry)
239
+
240
+ return (
241
+ <div
242
+ key={entry.key}
243
+ className={cn('min-w-0 rounded-lg p-2.5 transition-all', CARD_STYLE[status])}
244
+ >
245
+ <dt className="mb-1 flex items-center justify-center gap-1">
246
+ {entry.icon ? (
247
+ <span aria-hidden className="text-base leading-none">
248
+ {entry.icon}
249
+ </span>
250
+ ) : null}
251
+ <span className="truncate text-[10px] font-medium uppercase leading-none tracking-wide text-gray-500 dark:text-gray-400">
252
+ {entry.label}
253
+ </span>
254
+ <span className={cn('flex-shrink-0 leading-none', GLYPH_STYLE[status])}>
255
+ <StatusGlyph status={status} />
256
+ </span>
257
+ </dt>
258
+ {/* `title` no valor: truncado no card, o texto completo só existe no tooltip. */}
259
+ <dd
260
+ className={cn(
261
+ 'truncate text-center text-xs font-semibold',
262
+ entry.value
263
+ ? 'text-gray-900 dark:text-gray-100'
264
+ : 'italic font-normal text-gray-400 dark:text-gray-500',
265
+ )}
266
+ title={entry.value ?? labels.notCollected}
267
+ >
268
+ {entry.value ?? labels.notCollected}
269
+ </dd>
270
+ </div>
271
+ )
272
+ })}
273
+ </dl>
274
+ )}
275
+ </div>
276
+ ) : null}
277
+ </section>
278
+ </div>
279
+ )
280
+ }