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

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 (99) hide show
  1. package/dist/{chunk-ZDURDZTM.js → chunk-2AYDBWNE.js} +14 -0
  2. package/dist/chunk-OIDAIVCH.js +1985 -0
  3. package/dist/flows/index.d.ts +14 -2
  4. package/dist/flows/index.js +117 -39
  5. package/dist/index.d.ts +729 -136
  6. package/dist/index.js +1418 -1104
  7. package/dist/preview/index.d.ts +373 -0
  8. package/dist/preview/index.js +1247 -0
  9. package/dist/styles.css +198 -0
  10. package/dist/types-O7kMP1Yn.d.ts +416 -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/Avatar.tsx +30 -4
  15. package/src/ChannelIcon.tsx +87 -0
  16. package/src/ConversationContextPanel.tsx +127 -0
  17. package/src/ConversationDocumentsPanel.tsx +425 -0
  18. package/src/ConversationHeader.tsx +257 -0
  19. package/src/ConversationListItem.tsx +54 -7
  20. package/src/ConversationLocalesProvider.tsx +16 -0
  21. package/src/ConversationRow.tsx +137 -0
  22. package/src/DateDivider.tsx +16 -3
  23. package/src/DocumentsLibrary.tsx +322 -0
  24. package/src/EmojiPicker.tsx +69 -55
  25. package/src/FileIcon.test.ts +83 -0
  26. package/src/FileIcon.tsx +88 -11
  27. package/src/InteractiveMessage.test.tsx +41 -0
  28. package/src/InteractiveMessage.tsx +143 -0
  29. package/src/Lightbox.tsx +18 -3
  30. package/src/MediaRenderer.tsx +64 -21
  31. package/src/MessageBubble.tsx +54 -5
  32. package/src/MessageComposer.test.tsx +35 -0
  33. package/src/MessageComposer.tsx +146 -19
  34. package/src/RichMessageComposer.test.tsx +83 -0
  35. package/src/RichMessageComposer.tsx +380 -0
  36. package/src/Wallpaper.test.tsx +21 -0
  37. package/src/Wallpaper.tsx +54 -6
  38. package/src/WhatsAppMessageEditor.tsx +28 -4
  39. package/src/WindowExpiredNotice.tsx +57 -0
  40. package/src/audioRecorderFormat.test.ts +67 -0
  41. package/src/conversationChannel.test.ts +53 -0
  42. package/src/conversationChannel.ts +146 -0
  43. package/src/conversationTranscript.test.ts +65 -0
  44. package/src/conversationTranscript.ts +64 -0
  45. package/src/conversationWindow.test.ts +90 -0
  46. package/src/conversationWindow.ts +78 -0
  47. package/src/documentTypeLabel.test.ts +57 -0
  48. package/src/emojiCatalog.test.ts +35 -0
  49. package/src/emojiCatalog.ts +189 -0
  50. package/src/flows/FlowGroupHeader.tsx +12 -2
  51. package/src/flows/FlowMapCanvas.tsx +17 -14
  52. package/src/flows/FlowMapNode.tsx +3 -1
  53. package/src/flows/FlowNodeCard.tsx +22 -4
  54. package/src/flows/FlowNodePanel.tsx +132 -35
  55. package/src/flows/FlowPalette.tsx +6 -2
  56. package/src/flows/FlowWhatsAppPreview.tsx +14 -3
  57. package/src/flows/flowGraph.ts +5 -5
  58. package/src/flows/labels.ts +5 -0
  59. package/src/hooks/useConversationActions.ts +56 -0
  60. package/src/hooks/useConversationDocuments.ts +15 -9
  61. package/src/hooks/useConversationList.ts +15 -9
  62. package/src/hooks/useConversationMessages.ts +2 -2
  63. package/src/index.ts +129 -16
  64. package/src/lib/cn.test.ts +29 -0
  65. package/src/lib/cn.ts +15 -0
  66. package/src/lib/createMediaUrlResolver.ts +33 -0
  67. package/src/lib/paginated.test.ts +33 -0
  68. package/src/lib/paginated.ts +26 -0
  69. package/src/lib/phone.ts +34 -0
  70. package/src/preview/ConversationPreview.tsx +325 -0
  71. package/src/preview/MediaTypesPreview.tsx +87 -0
  72. package/src/preview/conversationPreviewFailures.test.ts +64 -0
  73. package/src/preview/createMockConversationsApi.ts +271 -0
  74. package/src/preview/createMockSSEProvider.ts +40 -0
  75. package/src/preview/createPreviewBridgeClient.test.ts +92 -0
  76. package/src/preview/createPreviewBridgeClient.ts +88 -0
  77. package/src/preview/createPreviewWebhookClient.test.ts +105 -0
  78. package/src/preview/createPreviewWebhookClient.ts +131 -0
  79. package/src/preview/index.ts +61 -0
  80. package/src/preview/mediaTypeOf.test.ts +15 -0
  81. package/src/preview/mockDocumentsSearch.test.ts +57 -0
  82. package/src/preview/mockEventSource.ts +53 -0
  83. package/src/preview/preview.test.ts +177 -0
  84. package/src/preview/previewFileSamples.test.ts +151 -0
  85. package/src/preview/previewFileSamples.ts +74 -0
  86. package/src/preview/previewFixtures.ts +440 -0
  87. package/src/preview/previewMediaSource.test.ts +62 -0
  88. package/src/preview/previewMediaSource.ts +91 -0
  89. package/src/preview/previewStore.ts +193 -0
  90. package/src/preview/startPreviewScript.ts +60 -0
  91. package/src/providers/types.ts +163 -11
  92. package/src/quickReply.test.ts +58 -0
  93. package/src/settings/WhatsAppCreateTemplateForm.tsx +3 -1
  94. package/src/settings/WhatsAppTemplatesSettings.tsx +106 -0
  95. package/src/styles.css +136 -0
  96. package/src/types.ts +46 -1
  97. package/src/useDarkMode.ts +26 -0
  98. package/src/useIsNarrow.ts +29 -0
  99. package/src/useWaitingNotifications.ts +74 -29
package/dist/styles.css CHANGED
@@ -9,3 +9,201 @@
9
9
  background-color: #0b141a;
10
10
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100' viewBox='0 0 100 100'%3E%3Cg fill='none' stroke='%2319232a' stroke-width='1.2' opacity='0.9'%3E%3Ccircle cx='15' cy='15' r='3'/%3E%3Cpath d='M40 10 q5 8 0 16 q-5 -8 0 -16z'/%3E%3Ccircle cx='70' cy='28' r='2'/%3E%3Cpath d='M18 55 l6 6 m-6 0 l6 -6'/%3E%3Ccircle cx='55' cy='68' r='2.5'/%3E%3Cpath d='M85 58 q6 6 0 12 q-6 -6 0 -12z'/%3E%3Ccircle cx='8' cy='85' r='2'/%3E%3Cpath d='M65 90 l5 5 m-5 0 l5 -5'/%3E%3C/g%3E%3C/svg%3E");
11
11
  }
12
+ .cv-header-action {
13
+ border: 1px solid rgb(203 213 225);
14
+ border-radius: 0.375rem;
15
+ padding: 0.375rem 0.75rem;
16
+ font-size: 0.8125rem;
17
+ background: transparent;
18
+ cursor: pointer;
19
+ }
20
+ .cv-header-action:disabled {
21
+ opacity: 0.5;
22
+ cursor: not-allowed;
23
+ }
24
+ .dark .cv-header-action {
25
+ border-color: rgb(71 85 105);
26
+ color: rgb(226 232 240);
27
+ }
28
+ .cv-header-icon {
29
+ border: 1px solid rgb(203 213 225);
30
+ border-radius: 0.5rem;
31
+ padding: 0.375rem 0.5rem;
32
+ background: transparent;
33
+ cursor: pointer;
34
+ line-height: 1;
35
+ }
36
+ .cv-header-icon--active {
37
+ background: rgb(241 245 249);
38
+ border-color: rgb(148 163 184);
39
+ }
40
+ .cv-header-icon:disabled {
41
+ opacity: 0.5;
42
+ cursor: not-allowed;
43
+ }
44
+ .dark .cv-header-icon {
45
+ border-color: rgb(71 85 105);
46
+ }
47
+ .dark .cv-header-icon--active {
48
+ background: rgb(51 65 85);
49
+ }
50
+ .cv-header-action--primary {
51
+ background: rgb(37 99 235);
52
+ border-color: rgb(37 99 235);
53
+ color: white;
54
+ font-weight: 500;
55
+ }
56
+ .cv-header-action--danger {
57
+ background: rgb(239 68 68);
58
+ border-color: rgb(239 68 68);
59
+ color: white;
60
+ font-weight: 500;
61
+ }
62
+ .cv-subtab {
63
+ padding: 0.5rem 0.75rem;
64
+ font-size: 0.8125rem;
65
+ color: rgb(100 116 139);
66
+ background: transparent;
67
+ border: 0;
68
+ border-bottom: 2px solid transparent;
69
+ cursor: pointer;
70
+ }
71
+ .cv-subtab--active {
72
+ color: inherit;
73
+ font-weight: 500;
74
+ border-bottom-color: rgb(37 99 235);
75
+ }
76
+ .cv-pill {
77
+ display: inline-flex;
78
+ align-items: center;
79
+ gap: 0.25rem;
80
+ font-size: 0.6875rem;
81
+ font-weight: 500;
82
+ line-height: 1;
83
+ padding: 0.25rem 0.5rem;
84
+ border-radius: 9999px;
85
+ background: rgb(241 245 249);
86
+ color: rgb(71 85 105);
87
+ }
88
+ .cv-pill--success {
89
+ background: rgb(220 252 231);
90
+ color: rgb(21 128 61);
91
+ }
92
+ .cv-pill--warning {
93
+ background: rgb(254 243 199);
94
+ color: rgb(146 64 14);
95
+ }
96
+ .cv-pill--danger {
97
+ background: rgb(255 237 213);
98
+ color: rgb(194 65 12);
99
+ }
100
+ .dark .cv-pill {
101
+ background: rgb(51 65 85);
102
+ color: rgb(203 213 225);
103
+ }
104
+ .dark .cv-pill--success {
105
+ background: rgb(20 83 45);
106
+ color: rgb(187 247 208);
107
+ }
108
+ .dark .cv-pill--warning {
109
+ background: rgb(120 53 15);
110
+ color: rgb(253 230 138);
111
+ }
112
+ .dark .cv-pill--danger {
113
+ background: rgb(124 45 18);
114
+ color: rgb(254 215 170);
115
+ }
116
+ .cv-row:hover {
117
+ background: #f0f2f5;
118
+ }
119
+ .cv-row--active,
120
+ .cv-row--active:hover {
121
+ background: #f0f2f5;
122
+ }
123
+ .dark .cv-row:hover {
124
+ background: rgb(30 41 59);
125
+ }
126
+ .dark .cv-row--active,
127
+ .dark .cv-row--active:hover {
128
+ background: rgb(30 41 59);
129
+ }
130
+ .cv-back {
131
+ border: 1px solid rgb(203 213 225);
132
+ border-radius: 0.5rem;
133
+ padding: 0.25rem 0.5rem;
134
+ background: transparent;
135
+ cursor: pointer;
136
+ line-height: 1;
137
+ }
138
+ @media (min-width: 1024px) {
139
+ .cv-back {
140
+ display: none;
141
+ }
142
+ }
143
+ .dark .cv-back {
144
+ border-color: rgb(71 85 105);
145
+ color: rgb(226 232 240);
146
+ }
147
+ .cv-only-wide {
148
+ display: none;
149
+ }
150
+ @media (min-width: 1024px) {
151
+ .cv-only-wide {
152
+ display: inline;
153
+ }
154
+ }
155
+ .cv-only-narrow {
156
+ display: inline-flex;
157
+ }
158
+ @media (min-width: 1024px) {
159
+ .cv-only-narrow {
160
+ display: none;
161
+ }
162
+ }
163
+ .cv-menu {
164
+ position: relative;
165
+ }
166
+ .cv-menu-panel {
167
+ position: absolute;
168
+ right: 0;
169
+ top: calc(100% + 0.25rem);
170
+ z-index: 20;
171
+ min-width: 12rem;
172
+ display: flex;
173
+ flex-direction: column;
174
+ gap: 0.25rem;
175
+ padding: 0.375rem;
176
+ border: 1px solid rgb(203 213 225);
177
+ border-radius: 0.5rem;
178
+ background: #fff;
179
+ box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1);
180
+ }
181
+ .dark .cv-menu-panel {
182
+ background: rgb(30 41 59);
183
+ border-color: rgb(71 85 105);
184
+ }
185
+ .cv-menu-panel .cv-header-action {
186
+ text-align: left;
187
+ }
188
+ @media (max-width: 1023px) {
189
+ .cv-touch {
190
+ min-width: 44px;
191
+ min-height: 44px;
192
+ }
193
+ .cv-back {
194
+ min-width: 44px;
195
+ min-height: 44px;
196
+ }
197
+ .cv-menu-panel .cv-touch {
198
+ min-height: 44px;
199
+ }
200
+ }
201
+ @media (max-width: 1023px) {
202
+ .cv-menu-panel {
203
+ position: fixed;
204
+ right: 0.75rem;
205
+ left: auto;
206
+ top: auto;
207
+ max-width: calc(100vw - 1.5rem);
208
+ }
209
+ }
@@ -0,0 +1,416 @@
1
+ import * as react from 'react';
2
+
3
+ interface ConversationsUIConfig {
4
+ apiBaseUrl: string;
5
+ theme?: ConversationsTheme;
6
+ features?: ConversationsFeatures;
7
+ }
8
+ interface ConversationsTheme {
9
+ primaryColor?: string;
10
+ backgroundColor?: string;
11
+ bubbleSent?: string;
12
+ bubbleReceived?: string;
13
+ textPrimary?: string;
14
+ textSecondary?: string;
15
+ }
16
+ interface ConversationsFeatures {
17
+ audio?: boolean;
18
+ documents?: boolean;
19
+ emoji?: boolean;
20
+ darkMode?: boolean;
21
+ }
22
+ /**
23
+ * Recorte do bloco `interactive` da Meta que a UI precisa para desenhar o menu. Fica solto (e não
24
+ * espelhando o contrato inteiro) porque o que chega do banco é o payload cru já enviado ao
25
+ * WhatsApp: qualquer campo que a UI não conheça é ignorado, nunca causa erro de render.
26
+ */
27
+ interface InteractiveOption {
28
+ id: string;
29
+ title: string;
30
+ description?: string;
31
+ }
32
+ interface InteractiveSection {
33
+ title?: string;
34
+ rows?: InteractiveOption[];
35
+ }
36
+ interface InteractivePayload {
37
+ type?: 'button' | 'list' | string;
38
+ header?: {
39
+ text?: string;
40
+ };
41
+ body?: {
42
+ text?: string;
43
+ };
44
+ footer?: {
45
+ text?: string;
46
+ };
47
+ action?: {
48
+ /** Rótulo do botão que abre a lista — só existe em `type: 'list'`. */
49
+ button?: string;
50
+ sections?: InteractiveSection[];
51
+ buttons?: {
52
+ reply?: InteractiveOption;
53
+ }[];
54
+ };
55
+ }
56
+ /** Como o cliente respondeu a um menu: por botão ou por item de lista. */
57
+ type InteractiveSelection = {
58
+ readonly kind: 'button' | 'list';
59
+ readonly option: InteractiveOption;
60
+ };
61
+ interface MessagePayload {
62
+ id: string;
63
+ type: 'text' | 'image' | 'video' | 'audio' | 'document' | 'sticker' | 'template' | 'interactive';
64
+ /** Payload cru da mensagem. Em `type: 'interactive'`, carrega o menu que o cliente vê. */
65
+ payload?: InteractivePayload | null;
66
+ content?: string;
67
+ caption?: string;
68
+ mediaUrl?: string;
69
+ base64?: string;
70
+ uploadId?: string;
71
+ mediaId?: string;
72
+ mimeType?: string;
73
+ filename?: string;
74
+ sizeBytes?: number;
75
+ direction: 'inbound' | 'outbound';
76
+ sender: 'bot' | 'customer' | 'agent';
77
+ timestamp: string;
78
+ status?: 'sent' | 'delivered' | 'read' | 'failed';
79
+ readAt?: string;
80
+ agentName?: string | null;
81
+ templateName?: string;
82
+ /**
83
+ * Veredito de moderação vindo do backend — a UI só exibe, nunca calcula. Dicionário no browser
84
+ * seria peso morto e daria veredito diferente por versão de cliente.
85
+ *
86
+ * `null`/ausente = não avaliado (moderação desligada, ou mensagem anterior ao recurso), que é
87
+ * diferente de avaliado e limpo.
88
+ */
89
+ moderation?: {
90
+ isOffensive: boolean;
91
+ terms: string[];
92
+ } | null;
93
+ isFirstInGroup?: boolean;
94
+ isLastInGroup?: boolean;
95
+ }
96
+
97
+ type ResolveMediaUrl = (message: MessagePayload) => Promise<string | null>;
98
+ interface MediaRendererProps {
99
+ message: MessagePayload;
100
+ onLightbox: (src: string) => void;
101
+ onResolveUrl?: ResolveMediaUrl;
102
+ /** Aplicado no wrapper de cada tipo de mídia — imagem, vídeo, áudio e documento. */
103
+ className?: string;
104
+ }
105
+ declare function MediaRenderer({ message, onLightbox, onResolveUrl, className }: MediaRendererProps): react.JSX.Element | null;
106
+
107
+ /**
108
+ * Gravação de áudio no simulador, pelo microfone do próprio navegador.
109
+ *
110
+ * Existe porque áudio é o formato que mais chega de cliente real e o que mais quebra fluxo: sem
111
+ * poder gravar aqui, testar o caminho de transcrição exigia mandar mensagem do celular de alguém.
112
+ *
113
+ * O arquivo gravado sai daqui como `File` e segue exatamente o mesmo caminho de um anexo — quem
114
+ * hospeda e devolve o `mediaId` é o host, via `uploadMedia`.
115
+ */
116
+ interface AudioRecorderButtonLabels {
117
+ start: string;
118
+ stop: string;
119
+ unsupported: string;
120
+ denied: string;
121
+ review: string;
122
+ send: string;
123
+ discard: string;
124
+ empty: string;
125
+ }
126
+ declare const DEFAULT_AUDIO_RECORDER_BUTTON_LABELS: AudioRecorderButtonLabels;
127
+ interface AudioRecorderButtonProps {
128
+ onRecorded: (file: File) => void | Promise<void>;
129
+ onFailure?: (message: string) => void;
130
+ /**
131
+ * Avisa quando a gravação começa e termina. O botão é um interruptor — o segundo toque é que
132
+ * envia — e sem um aviso fora dele o operador grava, não vê nada acontecer e desiste achando
133
+ * que o microfone está quebrado.
134
+ */
135
+ onRecordingChange?: (isRecording: boolean) => void;
136
+ /**
137
+ * Abre uma etapa de revisão quando a gravação para: o áudio toca ali mesmo e só sai depois de
138
+ * confirmado. Ligado por padrão — voz é o único anexo que quem envia não viu antes de mandar, e
139
+ * sem ouvir não há como saber se o microfone captou alguma coisa. Desligar volta ao envio direto.
140
+ */
141
+ reviewBeforeSend?: boolean;
142
+ /**
143
+ * Teto de duração da gravação, em milissegundos. Passado o tempo, o gravador para e envia o que
144
+ * tem. Produto com limite próprio sobrescreve.
145
+ */
146
+ maxDurationMilliseconds?: number;
147
+ labels?: Partial<AudioRecorderButtonLabels>;
148
+ disabled?: boolean;
149
+ }
150
+ /**
151
+ * Cinco minutos: com o codec de voz do WhatsApp isso dá menos de 3MB, folgado dentro do teto de
152
+ * 16MB que a Meta impõe a áudio, e é mais do que qualquer recado de cliente. O corte automático
153
+ * existe porque gravação esquecida aberta só se descobre no envio, com o arquivo inteiro perdido.
154
+ */
155
+ declare const DEFAULT_MAX_RECORDING_MILLISECONDS: number;
156
+ declare function AudioRecorderButton({ onRecorded, onFailure, onRecordingChange, reviewBeforeSend, maxDurationMilliseconds, labels, disabled, }: AudioRecorderButtonProps): react.JSX.Element;
157
+
158
+ /**
159
+ * Canal de origem da conversa e o que cada um permite.
160
+ *
161
+ * Existe porque as regras que a inbox precisa respeitar não são do WhatsApp, são **de cada canal**:
162
+ * a janela de sessão, o jeito de reabrir a conversa e o formato do identificador do contato mudam
163
+ * entre WhatsApp, Messenger, Instagram e chat de site. Tratar a regra do WhatsApp como universal
164
+ * faria a UI bloquear o composer num chat de site, onde janela nenhuma existe.
165
+ *
166
+ * `whatsapp` é o padrão em todo lugar: instalações que ainda não informam canal continuam
167
+ * funcionando exatamente como antes.
168
+ */
169
+ declare const CONVERSATION_CHANNEL: {
170
+ readonly WHATSAPP: "whatsapp";
171
+ readonly MESSENGER: "messenger";
172
+ readonly INSTAGRAM: "instagram";
173
+ readonly WEBCHAT: "webchat";
174
+ };
175
+ type ConversationChannel = (typeof CONVERSATION_CHANNEL)[keyof typeof CONVERSATION_CHANNEL];
176
+ declare const DEFAULT_CONVERSATION_CHANNEL: ConversationChannel;
177
+ /** Como o canal reabre uma conversa fora da janela de sessão. */
178
+ declare const REOPEN_MECHANISM: {
179
+ readonly TEMPLATE: "template";
180
+ readonly TAG: "tag";
181
+ readonly NONE: "none";
182
+ };
183
+ type ReopenMechanism = (typeof REOPEN_MECHANISM)[keyof typeof REOPEN_MECHANISM];
184
+ /** Natureza do identificador do contato — decide como exibi-lo. */
185
+ declare const HANDLE_KIND: {
186
+ readonly PHONE: "phone";
187
+ readonly USERNAME: "username";
188
+ readonly SESSION: "session";
189
+ };
190
+ type HandleKind = (typeof HANDLE_KIND)[keyof typeof HANDLE_KIND];
191
+ type ChannelCapabilities = {
192
+ readonly label: string;
193
+ readonly icon: string;
194
+ readonly hasSessionWindow: boolean;
195
+ readonly windowHours: number;
196
+ readonly reopenMechanism: ReopenMechanism;
197
+ readonly handleKind: HandleKind;
198
+ };
199
+ declare const CHANNEL_CAPABILITIES: Readonly<Record<ConversationChannel, ChannelCapabilities>>;
200
+ declare function capabilitiesOf(channel: ConversationChannel | undefined): ChannelCapabilities;
201
+ declare const CHANNEL_FILTER_ALL = "all";
202
+ type ChannelFilter = ConversationChannel | typeof CHANNEL_FILTER_ALL;
203
+ type ChannelFilterOption = {
204
+ readonly value: ChannelFilter;
205
+ readonly label: string;
206
+ };
207
+ /**
208
+ * Opções derivadas do que existe na lista, não do catálogo inteiro: oferecer Instagram numa conta
209
+ * que só tem WhatsApp promete um recorte que nunca traz resultado.
210
+ *
211
+ * Devolve vazio com menos de dois canais — um filtro de opção única não filtra nada, e a barra só
212
+ * ocuparia espaço. O host usa isso para esconder a seção.
213
+ */
214
+ declare function channelFiltersFor(conversations: readonly {
215
+ readonly channel?: ConversationChannel | undefined;
216
+ }[]): ChannelFilterOption[];
217
+ type FormatContactHandleParams = {
218
+ readonly handle: string;
219
+ readonly channel?: ConversationChannel | undefined;
220
+ };
221
+ /**
222
+ * Exibição do identificador conforme a natureza dele. Formatar tudo como telefone — o que a UI
223
+ * fazia — transforma um `@perfil` do Instagram em dígitos sem sentido.
224
+ */
225
+ declare function formatContactHandle(params: FormatContactHandleParams): string;
226
+ /** Bandeira só faz sentido quando o identificador é telefone. */
227
+ declare function contactFlag(params: FormatContactHandleParams): string;
228
+
229
+ interface ListConversationsParams {
230
+ page?: number;
231
+ limit?: number;
232
+ waitingHuman?: boolean;
233
+ search?: string;
234
+ /**
235
+ * Recortes que só o produto conhece (tipo de financiamento, carteira, campanha) repassados
236
+ * crus ao backend dele. É o que evita o vocabulário de uma vertical virar campo fixo aqui:
237
+ * o pacote transporta o filtro sem saber o que ele significa.
238
+ */
239
+ filters?: Record<string, string | undefined>;
240
+ }
241
+ /**
242
+ * Página com o total, para a UI conseguir desenhar controles de paginação.
243
+ *
244
+ * `fetchConversations` devolve isto **ou** o array puro de antes: implementações existentes
245
+ * continuam válidas sem mudar uma linha, e quem precisa paginar passa a ter o total. Sem a união
246
+ * seria impossível saber se um retorno curto é a última página ou uma página cheia por acaso.
247
+ */
248
+ interface ConversationPage {
249
+ conversations: ConversationSummary[];
250
+ total: number;
251
+ }
252
+ interface ListDocumentsParams {
253
+ search?: string;
254
+ page?: number;
255
+ /** Tamanho da página. Sem ele, `page` sozinho não define fatia nenhuma. */
256
+ limit?: number;
257
+ /** Origem do arquivo (`customer`, `agent`, `bot`…). O vocabulário é do host. */
258
+ source?: string;
259
+ sortDirection?: 'asc' | 'desc';
260
+ }
261
+ /** Arquivo na biblioteca da empresa: o mesmo da conversa, mais de qual conversa veio. */
262
+ interface CompanyDocument extends ConversationDocument {
263
+ conversationId: string;
264
+ }
265
+ interface CompanyDocumentPage {
266
+ documents: CompanyDocument[];
267
+ total: number;
268
+ }
269
+ interface ConversationDocumentPage {
270
+ documents: ConversationDocument[];
271
+ total: number;
272
+ }
273
+ /**
274
+ * Template disponível para envio a partir da inbox. Distinto do `WhatsAppTemplateSummary` de
275
+ * `settings/`, e de propósito: aquele serve ao formulário que **edita** template e carrega o que
276
+ * a edição precisa (`shortId`, `variableCount`); este serve a quem só vai **escolher um para
277
+ * enviar**, e pedir os campos de edição obrigaria todo host a produzi-los sem uso.
278
+ */
279
+ interface ConversationTemplate {
280
+ name: string;
281
+ language: string;
282
+ status: string;
283
+ category?: string;
284
+ bodyText?: string | null;
285
+ }
286
+ interface ConversationsApi {
287
+ fetchMessages(conversationId: string, params?: {
288
+ limit?: number;
289
+ before?: string;
290
+ }): Promise<MessagePayload[]>;
291
+ fetchConversations(params?: ListConversationsParams): Promise<ConversationSummary[] | ConversationPage>;
292
+ sendMessage(conversationId: string, text: string): Promise<MessagePayload>;
293
+ sendMedia(conversationId: string, data: {
294
+ base64: string;
295
+ mimeType: string;
296
+ filename: string;
297
+ caption?: string;
298
+ }): Promise<MessagePayload>;
299
+ /**
300
+ * `templateName` é opcional porque reabrir a janela é a operação, e escolher *qual* template a
301
+ * usa nem sempre é decisão da UI: backends que guardam um template padrão configurado só
302
+ * precisam do "reabra". Exigir o nome obrigaria toda inbox a listar templates antes de poder
303
+ * mandar o primeiro — e a listagem é `listTemplates?`, opcional.
304
+ */
305
+ sendTemplate(conversationId: string, data: {
306
+ templateName?: string;
307
+ languageCode?: string;
308
+ bodyParams?: string[];
309
+ }): Promise<void>;
310
+ markRead(conversationId: string): Promise<void>;
311
+ getContext(conversationId: string): Promise<Record<string, unknown>>;
312
+ getDocuments(conversationId: string, params?: ListDocumentsParams): Promise<ConversationDocument[] | ConversationDocumentPage>;
313
+ /**
314
+ * `disposition` decide entre abrir no navegador e baixar. É o backend que assina a URL e grava
315
+ * o `Content-Disposition` nela, então a escolha precisa viajar na chamada — depois de assinada
316
+ * não há como o cliente mudá-la. Ausente = o padrão do host.
317
+ */
318
+ getDocumentUrl(uploadId: string, disposition?: 'inline' | 'attachment'): Promise<string>;
319
+ /**
320
+ * Baixa vários arquivos num zip único.
321
+ *
322
+ * **Opcional por capacidade:** montar zip exige o host LER os bytes do storage, o que nem toda
323
+ * instalação faz — as que só assinam URL não conseguem. Ausente, o painel esconde a seleção em
324
+ * lote em vez de oferecer um botão que falha.
325
+ */
326
+ downloadDocumentsArchive?(conversationId: string, uploadIds: readonly string[]): Promise<Blob>;
327
+ /**
328
+ * Biblioteca de TODAS as conversas, para uma tela de Documentos fora do atendimento.
329
+ *
330
+ * Opcional por capacidade: host que só expõe anexo dentro da conversa não implementa, e o
331
+ * componente de biblioteca simplesmente não é usável — melhor que uma tela que sempre erra.
332
+ */
333
+ getAllDocuments?(params?: ListDocumentsParams): Promise<CompanyDocumentPage>;
334
+ getMediaProxyUrl(mediaId: string): Promise<{
335
+ mimeType: string;
336
+ data: string;
337
+ }>;
338
+ /**
339
+ * Operações de atendimento humano. **Opcionais por capacidade, não por descuido:** nem toda
340
+ * inbox tem fila humana — um canal só-bot, ou um chat de site sem operador, não sabe o que é
341
+ * assumir conversa. Quem não implementa não ganha o botão, em vez de ganhar um botão que
342
+ * estoura no clique. Os hooks devolvem `undefined` para a ação ausente, e é isso que a UI
343
+ * consulta para decidir se desenha a afordância.
344
+ */
345
+ takeover?(conversationId: string): Promise<void>;
346
+ release?(conversationId: string): Promise<void>;
347
+ /** Encerra o atendimento. Despedida, se houver, é decisão do host — o pacote não a inventa. */
348
+ finalize?(conversationId: string): Promise<void>;
349
+ markAllRead?(): Promise<void>;
350
+ listTemplates?(): Promise<ConversationTemplate[]>;
351
+ /**
352
+ * Transcrição completa gerada pelo servidor. Existe ao lado de `buildTranscriptText`, que monta
353
+ * a partir das mensagens já em memória: a tela costuma ter só a última página carregada, e
354
+ * exportar dali entregaria um recorte parcial com cara de histórico inteiro. Opcional porque
355
+ * nem todo backend expõe a rota — quem não tem continua usando o builder local.
356
+ */
357
+ exportTranscript?(conversationId: string): Promise<{
358
+ transcript: string;
359
+ filename: string;
360
+ }>;
361
+ }
362
+ /**
363
+ * Superfície mínima de stream que o pacote consome — exatamente o que `useConversationRealtime`
364
+ * usa: assinar 'message', desassinar e fechar. Deliberadamente estrutural em vez de
365
+ * `EventSource`: sem servidor HTTP não existe `EventSource`, e é isso que impediria alimentar a
366
+ * inbox com dados mockados em desenvolvimento. Um `EventSource` nativo satisfaz este tipo, então
367
+ * quem já implementa `SSEProvider` continua válido sem mudança.
368
+ */
369
+ interface ConversationEventSource {
370
+ addEventListener(type: string, listener: (event: MessageEvent) => void): void;
371
+ removeEventListener(type: string, listener: (event: MessageEvent) => void): void;
372
+ close(): void;
373
+ }
374
+ interface SSEProvider {
375
+ connectConversationStream(conversationId: string): ConversationEventSource;
376
+ connectGlobalStream(): ConversationEventSource;
377
+ }
378
+ interface ConversationSummary {
379
+ id: string;
380
+ /**
381
+ * @deprecated Use `contactId` com `channel`. Mantido obrigatório para não quebrar quem já
382
+ * consome; some quando o segundo canal entrar em produção.
383
+ */
384
+ whatsappNumber: string;
385
+ /** Identificador neutro do contato. Ausente = usa `whatsappNumber`. */
386
+ contactId?: string;
387
+ /** Ausente = `whatsapp`, o comportamento de antes desta mudança. */
388
+ channel?: ConversationChannel;
389
+ clientName?: string;
390
+ lastContent?: string;
391
+ lastDirection?: 'inbound' | 'outbound';
392
+ lastAt: string;
393
+ lastInboundAt: string | null;
394
+ mode: 'bot' | 'human';
395
+ assignedUserId: string | null;
396
+ waitingHuman: boolean;
397
+ unread: number;
398
+ currentState: string;
399
+ /**
400
+ * Atributos que só o produto conhece e desenha (tipo de financiamento, carteira, campanha). É a
401
+ * contraparte de leitura do `filters` de `ListConversationsParams`: o pacote transporta e nunca
402
+ * interpreta. Sem isto, exibir um selo próprio na linha exigiria o host manter uma segunda
403
+ * consulta paralela à mesma listagem — a implementação duplicada que o pacote existe para evitar.
404
+ */
405
+ attributes?: Record<string, string | undefined>;
406
+ }
407
+ interface ConversationDocument {
408
+ id: string;
409
+ filename: string;
410
+ mimeType: string;
411
+ sizeBytes: number;
412
+ source: string;
413
+ linkedAt: string;
414
+ }
415
+
416
+ export { AudioRecorderButton as A, type ListDocumentsParams as B, CHANNEL_CAPABILITIES as C, DEFAULT_AUDIO_RECORDER_BUTTON_LABELS as D, type MediaRendererProps as E, type FormatContactHandleParams as F, type MessagePayload as G, HANDLE_KIND as H, type InteractiveOption as I, type ReopenMechanism as J, type ResolveMediaUrl as K, type ListConversationsParams as L, MediaRenderer as M, capabilitiesOf as N, channelFiltersFor as O, contactFlag as P, formatContactHandle as Q, REOPEN_MECHANISM as R, type SSEProvider as S, type AudioRecorderButtonLabels as a, type AudioRecorderButtonProps as b, CHANNEL_FILTER_ALL as c, CONVERSATION_CHANNEL as d, type ChannelCapabilities as e, type ChannelFilter as f, type ChannelFilterOption as g, type CompanyDocument as h, type CompanyDocumentPage as i, type ConversationChannel as j, type ConversationDocument as k, type ConversationDocumentPage as l, type ConversationEventSource as m, type ConversationPage as n, type ConversationSummary as o, type ConversationTemplate as p, type ConversationsApi as q, type ConversationsFeatures as r, type ConversationsTheme as s, type ConversationsUIConfig as t, DEFAULT_CONVERSATION_CHANNEL as u, DEFAULT_MAX_RECORDING_MILLISECONDS as v, type HandleKind as w, type InteractivePayload as x, type InteractiveSection as y, type InteractiveSelection as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adatechnology/conversations-ui",
3
- "version": "0.1.0-rc.2",
3
+ "version": "0.1.0-rc.20",
4
4
  "description": "WhatsApp conversation UI components — parametrizável por endpoint, tema e feature flags",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -19,13 +19,19 @@
19
19
  "import": "./dist/channel/index.js",
20
20
  "types": "./dist/channel/index.d.ts"
21
21
  },
22
+ "./preview": {
23
+ "import": "./dist/preview/index.js",
24
+ "types": "./dist/preview/index.d.ts"
25
+ },
22
26
  "./styles.css": "./dist/styles.css"
23
27
  },
24
28
  "main": "dist/index.js",
25
29
  "types": "dist/index.d.ts",
26
30
  "dependencies": {
31
+ "clsx": "^2.1.1",
27
32
  "lucide-react": "^1.21.0",
28
- "@adatechnology/meta-whatsapp-contracts": "0.2.0-rc.2"
33
+ "tailwind-merge": "^3.6.0",
34
+ "@adatechnology/meta-whatsapp-contracts": "0.2.0-rc.8"
29
35
  },
30
36
  "peerDependencies": {
31
37
  "react": "^18 || ^19",
@@ -38,13 +44,14 @@
38
44
  }
39
45
  },
40
46
  "devDependencies": {
47
+ "@types/bun": "1.3.14",
41
48
  "tsup": "^8.5.1",
42
49
  "typescript": "^5.9.3",
43
50
  "@types/react": "^18 || ^19",
44
51
  "@types/react-dom": "^18 || ^19"
45
52
  },
46
53
  "scripts": {
47
- "build": "tsup src/index.ts src/flows/index.ts src/channel/index.ts src/styles.css --dts --format esm --external react --external react-dom --external @xyflow/react",
54
+ "build": "tsup src/index.ts src/flows/index.ts src/channel/index.ts src/preview/index.ts src/styles.css --dts --format esm --external react --external react-dom --external @xyflow/react",
48
55
  "build:watch": "tsup src/index.ts src/flows/index.ts src/channel/index.ts src/styles.css --watch --dts --format esm --external react --external react-dom --external @xyflow/react",
49
56
  "check": "tsc -p tsconfig.json --noEmit",
50
57
  "test": "bun test"
@@ -0,0 +1,30 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+ import { renderToStaticMarkup } from 'react-dom/server'
3
+
4
+ import { AudioRecorderButton, DEFAULT_AUDIO_RECORDER_BUTTON_LABELS } from './AudioRecorderButton'
5
+
6
+ const noop = () => {}
7
+
8
+ describe('AudioRecorderButton', () => {
9
+ it('começa oferecendo gravar, sem painel de revisão à vista', () => {
10
+ const markup = renderToStaticMarkup(<AudioRecorderButton onRecorded={noop} />)
11
+
12
+ expect(markup).toContain(`title="${DEFAULT_AUDIO_RECORDER_BUTTON_LABELS.start}"`)
13
+ expect(markup).not.toContain(`title="${DEFAULT_AUDIO_RECORDER_BUTTON_LABELS.send}"`)
14
+ expect(markup).not.toContain('<audio')
15
+ })
16
+
17
+ it('deixa o host trocar o texto de um rótulo sem perder os outros', () => {
18
+ const markup = renderToStaticMarkup(
19
+ <AudioRecorderButton onRecorded={noop} labels={{ start: 'Gravar recado' }} />,
20
+ )
21
+
22
+ expect(markup).toContain('title="Gravar recado"')
23
+ })
24
+
25
+ it('mantém a caixa de 40px do botão de enviar para a barra não pular', () => {
26
+ const markup = renderToStaticMarkup(<AudioRecorderButton onRecorded={noop} />)
27
+
28
+ expect(markup).toContain('h-10 w-10')
29
+ })
30
+ })