@adatechnology/conversations-ui 0.16.0 → 0.18.0

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.
@@ -17,10 +17,10 @@
17
17
  */
18
18
 
19
19
  import { useEffect, useMemo, useState, type ReactNode } from 'react'
20
- import { Check, CheckCheck, FlaskConical, Hourglass, Mail, MessagesSquare } from 'lucide-react'
20
+ import { Check, CheckCheck, FlaskConical, Hourglass, Mail, MessagesSquare, UserPlus } from 'lucide-react'
21
21
 
22
22
  import { ICON_SIZE_ACTION, ICON_SIZE_INLINE } from '../icon.constant'
23
- import type { ConversationContextEntry } from '../ConversationContextPanel'
23
+ import type { ConversationContextEntry, ConversationContextPanelLabels } from '../ConversationContextPanel'
24
24
  import type { ConversationHeaderUtility } from '../ConversationHeader'
25
25
  import type { QuickReply } from '../MessageComposer'
26
26
  import type { RichComposerVariable } from '../RichMessageComposer'
@@ -57,6 +57,18 @@ export type SimulatorTransportParams = {
57
57
  */
58
58
  export type SimulatorTransportFactory = (params: SimulatorTransportParams) => ConversationSimulatorClient
59
59
 
60
+ /**
61
+ * Contato de teste que o host cria para abrir o simulador sem conversa selecionada. `handle` é o
62
+ * identificador no canal (no WhatsApp, um número de teste começando com `0`, que nenhum país usa).
63
+ */
64
+ export type SimulatorTestContact = {
65
+ readonly handle: string
66
+ /** Ausente = WhatsApp. */
67
+ readonly channel?: ConversationChannel
68
+ /** Id da conversa quando o host já o conhece. Ausente, usa `handle` e o transcript começa vazio. */
69
+ readonly conversationId?: string
70
+ }
71
+
60
72
  export interface ConversationsWorkspaceSimulator {
61
73
  /**
62
74
  * Um transporte por canal — o workspace monta o painel com o da conversa selecionada.
@@ -84,6 +96,27 @@ export interface ConversationsWorkspaceSimulator {
84
96
  readonly uploadMedia?: (file: File) => Promise<PreviewUploadedMedia>
85
97
  /** Recarrega o transcript a cada N ms. Serve a host sem stream. */
86
98
  readonly pollIntervalMs?: number
99
+ /**
100
+ * Liga "Novo contato de teste" no cabeçalho da página: o host devolve o contato e o simulador
101
+ * abre sem conversa selecionada. Quando a conversa dele aparece na lista, ela é selecionada.
102
+ * Ausente, o simulador só abre sobre uma conversa existente.
103
+ */
104
+ readonly createTestContact?: () => SimulatorTestContact | Promise<SimulatorTestContact>
105
+ /** Rótulo do botão de novo contato. Padrão: "Novo contato de teste". */
106
+ readonly newContactLabel?: string
107
+ }
108
+
109
+ type SimulatorTarget = {
110
+ readonly key: string
111
+ readonly conversationId: string
112
+ readonly channel: ConversationChannel
113
+ readonly handle: string
114
+ /** `false` enquanto a conversa do contato de teste ainda não existe no servidor. */
115
+ readonly persisted: boolean
116
+ }
117
+
118
+ function handleOf(conversation: ConversationSummary): string {
119
+ return conversation.contactId ?? conversation.whatsappNumber
87
120
  }
88
121
 
89
122
  export interface ConversationsWorkspaceProps {
@@ -141,6 +174,8 @@ export interface ConversationsWorkspaceProps {
141
174
  /** Nota de voz. Ausente, o microfone não aparece. */
142
175
  readonly onRecordAudio?: (conversation: ConversationSummary, file: File) => Promise<void>
143
176
  readonly contextEntriesOf?: (context: Record<string, unknown> | undefined) => readonly ConversationContextEntry[]
177
+ /** Vocabulário do painel de contexto (`title`, `empty`, `notCollected`...). */
178
+ readonly contextLabels?: Partial<ConversationContextPanelLabels>
144
179
  readonly onAttach?: (conversation: ConversationSummary, file: File) => Promise<void>
145
180
  readonly extraUtilitiesFor?: (conversation: ConversationSummary) => readonly ConversationHeaderUtility[]
146
181
  readonly renderFilters?: (inbox: UseConversationsInboxResult) => ReactNode
@@ -179,6 +214,7 @@ export function ConversationsWorkspace({
179
214
  onSendAttachments,
180
215
  onRecordAudio,
181
216
  contextEntriesOf,
217
+ contextLabels,
182
218
  onAttach,
183
219
  extraUtilitiesFor,
184
220
  renderFilters,
@@ -198,6 +234,7 @@ export function ConversationsWorkspace({
198
234
  ...(serverPaginated ? { serverPaginated } : {}),
199
235
  })
200
236
  const [simulatorOpen, setSimulatorOpen] = useState(false)
237
+ const [testContact, setTestContact] = useState<SimulatorTestContact | undefined>(undefined)
201
238
  const [templateModalOpen, setTemplateModalOpen] = useState(false)
202
239
  const [openedFromLink, setOpenedFromLink] = useState<string | undefined>(undefined)
203
240
 
@@ -216,23 +253,68 @@ export function ConversationsWorkspace({
216
253
  }, [initialConversationId, initialWhatsappNumber, openedFromLink, inbox])
217
254
 
218
255
  const selected = inbox.selectedConversation
256
+
257
+ // O contato de teste vira conversa de verdade no primeiro envio; achando-a na lista, ela passa a
258
+ // ser a selecionada e o painel segue sobre ela.
259
+ useEffect(() => {
260
+ if (!testContact) return
261
+ const created = inbox.conversations.find((conversation) => handleOf(conversation) === testContact.handle)
262
+ if (!created) return
263
+ inbox.selectConversation(created.id)
264
+ setTestContact(undefined)
265
+ }, [testContact, inbox])
266
+
219
267
  const conversations = useConversations()
220
- const selectedId = selected?.id
221
- const channel = selected?.channel ?? DEFAULT_CONVERSATION_CHANNEL
222
- const handle = selected ? (selected.contactId ?? selected.whatsappNumber) : ''
268
+ const target: SimulatorTarget | undefined = selected
269
+ ? {
270
+ key: selected.id,
271
+ conversationId: selected.id,
272
+ channel: selected.channel ?? DEFAULT_CONVERSATION_CHANNEL,
273
+ handle: handleOf(selected),
274
+ persisted: true,
275
+ }
276
+ : testContact
277
+ ? {
278
+ key: `test-contact:${testContact.handle}`,
279
+ // Sem id conhecido, o próprio identificador: é a chave do stream por conversa (`conv:<número>`).
280
+ conversationId: testContact.conversationId ?? testContact.handle,
281
+ channel: testContact.channel ?? DEFAULT_CONVERSATION_CHANNEL,
282
+ handle: testContact.handle,
283
+ persisted: testContact.conversationId !== undefined,
284
+ }
285
+ : undefined
286
+ const channel = target?.channel ?? DEFAULT_CONVERSATION_CHANNEL
287
+ const targetConversationId = target?.conversationId
288
+ const handle = target?.handle ?? ''
223
289
  const transport = simulator?.transports?.[channel]
224
- const simulatorEnabled = Boolean(
225
- simulator && (simulator.enabled ?? true) && (simulator.render ?? transport),
226
- )
227
- const showSimulator = simulatorEnabled && simulatorOpen && Boolean(selected)
290
+ const simulatorAvailable = Boolean(simulator && (simulator.enabled ?? true))
291
+ const simulatorEnabled = simulatorAvailable && Boolean(simulator?.render ?? transport)
292
+ const showSimulator = simulatorEnabled && simulatorOpen && Boolean(target)
293
+ const canCreateTestContact = simulatorAvailable && Boolean(simulator?.createTestContact)
228
294
 
229
295
  // O transporte é recriado só quando a conversa (ou o canal dela) muda: identidade nova a cada
230
296
  // render reiniciaria a leitura do transcript dentro do painel a cada digitação.
231
297
  const simulatorClient = useMemo(
232
- () => (transport && selectedId ? transport({ conversationId: selectedId, channel, handle }) : undefined),
233
- [transport, selectedId, channel, handle],
298
+ () =>
299
+ transport && targetConversationId !== undefined
300
+ ? transport({ conversationId: targetConversationId, channel, handle })
301
+ : undefined,
302
+ [transport, targetConversationId, channel, handle],
234
303
  )
235
304
 
305
+ async function handleCreateTestContact(): Promise<void> {
306
+ const contact = await simulator?.createTestContact?.()
307
+ if (!contact) return
308
+ inbox.clearSelection()
309
+ setTestContact(contact)
310
+ setSimulatorOpen(true)
311
+ }
312
+
313
+ function closeSimulator(): void {
314
+ setSimulatorOpen(false)
315
+ setTestContact(undefined)
316
+ }
317
+
236
318
  const paneUtilities = useMemo(() => {
237
319
  if (!selected) return undefined
238
320
  const fromProduct = extraUtilitiesFor?.(selected) ?? []
@@ -313,6 +395,18 @@ export function ConversationsWorkspace({
313
395
  <span className="cv-only-wide">{labels.markAllAsRead}</span>
314
396
  </button>
315
397
  ) : null}
398
+ {canCreateTestContact ? (
399
+ <button
400
+ type="button"
401
+ onClick={() => void handleCreateTestContact()}
402
+ data-cv-tooltip={simulator?.newContactLabel ?? labels.newTestContact}
403
+ aria-label={simulator?.newContactLabel ?? labels.newTestContact}
404
+ className="cv-workspace-toggle"
405
+ >
406
+ <UserPlus size={ICON_SIZE_ACTION} aria-hidden="true" />
407
+ <span className="cv-only-wide">{simulator?.newContactLabel ?? labels.newTestContact}</span>
408
+ </button>
409
+ ) : null}
316
410
  {renderHeaderActions?.(inbox)}
317
411
  </div>
318
412
  </header>
@@ -340,7 +434,7 @@ export function ConversationsWorkspace({
340
434
  separação por espaço lê mais rápido que por borda. */}
341
435
  <div
342
436
  className={`cv-workspace-grid${showSimulator ? ' cv-workspace-grid--with-simulator' : ''}`}
343
- data-detail={selected ? 'open' : 'closed'}
437
+ data-detail={selected || showSimulator ? 'open' : 'closed'}
344
438
  >
345
439
  <ConversationsInboxList
346
440
  inbox={inbox}
@@ -385,6 +479,7 @@ export function ConversationsWorkspace({
385
479
  onBack={inbox.clearSelection}
386
480
  {...(paneUtilities ? { extraUtilities: paneUtilities } : {})}
387
481
  {...(contextEntriesOf ? { contextEntriesOf } : {})}
482
+ {...(contextLabels ? { contextLabels } : {})}
388
483
  {...(quickReplies ? { quickReplies } : {})}
389
484
  {...(quickReplyVariablesFor ? { quickReplyVariablesFor } : {})}
390
485
  {...(renderAboveTranscript ? { renderAboveTranscript } : {})}
@@ -395,24 +490,28 @@ export function ConversationsWorkspace({
395
490
  )}
396
491
  </section>
397
492
 
398
- {showSimulator && selected ? (
493
+ {showSimulator && target ? (
399
494
  // `min-height:0` junto do `min-width:0`: sem isso a linha do grid cresce com o conteúdo do
400
495
  // painel, o scroll interno nunca ativa e quem rola passa a ser a página inteira.
401
496
  <div className="cv-workspace-simulator">
402
497
  {simulator?.render ? (
403
- simulator.render({ conversationId: selected.id, channel, close: () => setSimulatorOpen(false) })
498
+ simulator.render({ conversationId: target.conversationId, channel, close: closeSimulator })
404
499
  ) : simulatorClient && conversations ? (
405
500
  // `key` pela conversa: trocar de contato sem remontar deixaria o transcript e o campo
406
501
  // de texto do contato anterior na tela.
407
502
  <ConversationSimulatorPanel
408
- key={selected.id}
503
+ key={target.key}
409
504
  client={simulatorClient}
410
505
  sse={conversations.sse}
411
- conversationId={selected.id}
506
+ conversationId={target.conversationId}
412
507
  channel={channel}
413
508
  displayHandle={formatContactHandle({ handle, channel })}
414
- loadMessages={(conversationId) => conversations.api.fetchMessages(conversationId)}
415
- onClose={() => setSimulatorOpen(false)}
509
+ // Contato de teste sem conversa ainda: nada a ler. O eco local mostra o que foi
510
+ // enviado até a conversa aparecer na lista e o painel passar para ela.
511
+ loadMessages={(conversationId) =>
512
+ target.persisted ? conversations.api.fetchMessages(conversationId) : Promise.resolve([])
513
+ }
514
+ onClose={closeSimulator}
416
515
  {...(simulator?.labels ? { labels: simulator.labels } : {})}
417
516
  {...(simulator?.uploadMedia ? { uploadMedia: simulator.uploadMedia } : {})}
418
517
  {...(simulator?.pollIntervalMs ? { pollIntervalMs: simulator.pollIntervalMs } : {})}
@@ -4,6 +4,7 @@ export type {
4
4
  ConversationsWorkspaceSimulator,
5
5
  SimulatorTransportFactory,
6
6
  SimulatorTransportParams,
7
+ SimulatorTestContact,
7
8
  } from './ConversationsWorkspace'
8
9
  export { ConversationPane } from './ConversationPane'
9
10
  export type { ConversationPaneProps } from './ConversationPane'
@@ -16,6 +16,7 @@ export interface ConversationsWorkspaceLabels {
16
16
  readonly selectAll: string
17
17
  readonly emptyList: string
18
18
  readonly emptyDetail: string
19
+ readonly newTestContact: string
19
20
  readonly bulkSelected: (count: number) => string
20
21
  readonly bulkClear: string
21
22
  readonly bulkFinalize: string
@@ -67,6 +68,7 @@ export const DEFAULT_CONVERSATIONS_WORKSPACE_LABELS: ConversationsWorkspaceLabel
67
68
  selectAll: 'Selecionar todas',
68
69
  emptyList: 'Nenhuma conversa encontrada.',
69
70
  emptyDetail: 'Selecione uma conversa.',
71
+ newTestContact: 'Novo contato de teste',
70
72
  bulkSelected: (count) => `${count} selecionada${count === 1 ? '' : 's'}`,
71
73
  bulkClear: 'Limpar seleção',
72
74
  bulkFinalize: 'Finalizar',
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Copyright (c) 2026 Ada Technology. MIT License.
3
+ *
4
+ * Simulador sem conversa selecionada: o host cria um contato de teste e o painel abre direto.
5
+ */
6
+
7
+ import { act } from 'react'
8
+
9
+ import { afterAll, beforeAll, describe, expect, it } from 'bun:test'
10
+
11
+ import { setupDom, wait, type DomHarness } from '../domHarness.test-helper'
12
+ import { ConversationsProvider } from '../providers/ConversationsProvider'
13
+ import { createMockConversationsApi } from '../preview/createMockConversationsApi'
14
+ import { createMockSSEProvider } from '../preview/createMockSSEProvider'
15
+ import { createPreviewStore } from '../preview/previewStore'
16
+ import { PREVIEW_CONVERSATIONS, PREVIEW_MESSAGES } from '../preview/previewFixtures'
17
+ import { ConversationsWorkspace, type ConversationsWorkspaceSimulator } from './ConversationsWorkspace'
18
+
19
+ let harness: DomHarness
20
+
21
+ beforeAll(async () => {
22
+ harness = await setupDom()
23
+ })
24
+
25
+ afterAll(() => harness.teardown())
26
+
27
+ function mountWorkspace(simulator: ConversationsWorkspaceSimulator) {
28
+ const store = createPreviewStore({ conversations: [], messages: {} })
29
+ return harness.mount(
30
+ <ConversationsProvider api={createMockConversationsApi({ store, latencyMs: 0 })} sse={createMockSSEProvider({ store })}>
31
+ <ConversationsWorkspace simulator={simulator} />
32
+ </ConversationsProvider>,
33
+ )
34
+ }
35
+
36
+ function newContactButton(container: HTMLElement): HTMLButtonElement | undefined {
37
+ return Array.from(container.querySelectorAll('button')).find(
38
+ (button) => button.getAttribute('aria-label') === 'Novo contato de teste',
39
+ )
40
+ }
41
+
42
+ describe('novo contato de teste', () => {
43
+ it('sem createTestContact o botão não existe', async () => {
44
+ const { container, unmount } = mountWorkspace({ transports: { whatsapp: () => ({ sendText: async () => {}, sendReply: async () => {} }) } })
45
+ await wait(5)
46
+
47
+ expect(newContactButton(container)).toBeUndefined()
48
+ unmount()
49
+ })
50
+
51
+ it('abre o simulador sem conversa selecionada, com o contato do host', async () => {
52
+ const sent: string[] = []
53
+ const handles: string[] = []
54
+ const { container, unmount } = mountWorkspace({
55
+ createTestContact: () => ({ handle: '05511900001234' }),
56
+ transports: {
57
+ whatsapp: ({ handle }) => {
58
+ handles.push(handle)
59
+ return { sendText: async (text) => void sent.push(text), sendReply: async () => {} }
60
+ },
61
+ },
62
+ })
63
+ await wait(5)
64
+
65
+ await act(async () => {
66
+ newContactButton(container)?.click()
67
+ })
68
+ await wait(5)
69
+
70
+ const panel = container.querySelector('.cv-simulator-panel')
71
+ expect(panel).not.toBeNull()
72
+ expect(panel?.textContent).toContain('Contato de teste 1234')
73
+ expect(handles).toContain('05511900001234')
74
+ unmount()
75
+ })
76
+ })
77
+
78
+ describe('rótulos do painel de contexto', () => {
79
+ it('o workspace repassa contextLabels ao painel', async () => {
80
+ const store = createPreviewStore({ conversations: PREVIEW_CONVERSATIONS, messages: PREVIEW_MESSAGES })
81
+ const first = PREVIEW_CONVERSATIONS[0]
82
+ const { container, unmount } = harness.mount(
83
+ <ConversationsProvider api={createMockConversationsApi({ store, latencyMs: 0 })} sse={createMockSSEProvider({ store })}>
84
+ <ConversationsWorkspace
85
+ initialConversationId={first?.id}
86
+ contextEntriesOf={() => [{ key: 'date', label: 'Data', value: undefined, status: 'pending' }]}
87
+ contextLabels={{ title: 'Dados da reserva', notCollected: 'ainda não informado' }}
88
+ />
89
+ </ConversationsProvider>,
90
+ )
91
+ await wait(20)
92
+
93
+ expect(container.textContent).toContain('Dados da reserva')
94
+ unmount()
95
+ })
96
+ })