@adatechnology/conversations-ui 0.1.0-rc.8 → 0.1.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.
Files changed (132) hide show
  1. package/dist/ConversationSimulatorPanel--5fIzXWY.d.ts +804 -0
  2. package/dist/chunk-BJNRLLDO.js +2708 -0
  3. package/dist/chunk-DKPXKQGC.js +110 -0
  4. package/dist/{chunk-OGRRHQQW.js → chunk-WCBDXZ3X.js} +68 -4
  5. package/dist/flows/index.d.ts +422 -5
  6. package/dist/flows/index.js +2502 -678
  7. package/dist/index.d.ts +921 -17
  8. package/dist/index.js +3677 -678
  9. package/dist/preview/index.d.ts +62 -105
  10. package/dist/preview/index.js +162 -284
  11. package/dist/styles.css +893 -0
  12. package/package.json +9 -8
  13. package/src/AudioPlayer.tsx +8 -0
  14. package/src/AudioRecorderButton.test.tsx +30 -0
  15. package/src/AudioRecorderButton.tsx +248 -0
  16. package/src/AudioTranscription.test.tsx +115 -0
  17. package/src/AudioTranscription.tsx +252 -0
  18. package/src/Avatar.tsx +1 -1
  19. package/src/ConversationContextPanel.tsx +218 -44
  20. package/src/ConversationDocumentsPanel.tsx +11 -6
  21. package/src/ConversationHeader.test.tsx +66 -0
  22. package/src/ConversationHeader.tsx +147 -47
  23. package/src/ConversationListItem.tsx +8 -6
  24. package/src/ConversationLocalesProvider.tsx +28 -0
  25. package/src/ConversationRow.tsx +53 -7
  26. package/src/DarkModeToggle.test.tsx +76 -0
  27. package/src/DarkModeToggle.tsx +92 -0
  28. package/src/DocumentsLibrary.tsx +67 -7
  29. package/src/EmojiPicker.tsx +2 -1
  30. package/src/InteractiveMessage.tsx +3 -0
  31. package/src/Lightbox.tsx +1 -1
  32. package/src/MediaRenderer.tsx +88 -15
  33. package/src/MessageBubble.test.tsx +41 -0
  34. package/src/MessageBubble.tsx +47 -5
  35. package/src/MessageComposer.test.tsx +35 -0
  36. package/src/MessageComposer.tsx +122 -17
  37. package/src/MessageText.tsx +2 -1
  38. package/src/MessageTimestamp.tsx +2 -1
  39. package/src/RichMessageComposer.test.tsx +113 -0
  40. package/src/RichMessageComposer.tsx +551 -0
  41. package/src/SimpleEmojiPicker.tsx +5 -3
  42. package/src/StatusTicks.tsx +1 -1
  43. package/src/Toast.tsx +4 -0
  44. package/src/Tooltip.test.ts +42 -0
  45. package/src/Tooltip.tsx +167 -0
  46. package/src/Wallpaper.test.tsx +21 -0
  47. package/src/Wallpaper.tsx +67 -7
  48. package/src/WhatsAppMessageEditor.tsx +10 -7
  49. package/src/WindowExpiredNotice.tsx +12 -4
  50. package/src/{preview/audioRecorderFormat.test.ts → audioRecorderFormat.test.ts} +1 -1
  51. package/src/buildOutput.test.ts +79 -0
  52. package/src/composer.constant.ts +33 -0
  53. package/src/conversationTranscript.test.ts +57 -0
  54. package/src/conversationTranscript.ts +29 -4
  55. package/src/conversationWindow.ts +7 -5
  56. package/src/documentTypeLabel.test.ts +57 -0
  57. package/src/documents/DocumentsWorkspace.tsx +550 -0
  58. package/src/documents/index.ts +8 -0
  59. package/src/documents/labels.ts +92 -0
  60. package/src/flows/FlowConnectionEdge.tsx +104 -0
  61. package/src/flows/FlowGroupHeader.tsx +12 -2
  62. package/src/flows/FlowLegend.tsx +125 -0
  63. package/src/flows/FlowMapCanvas.tsx +15 -12
  64. package/src/flows/FlowMapNode.tsx +4 -1
  65. package/src/flows/FlowNodeCard.tsx +219 -34
  66. package/src/flows/FlowNodePanel.tsx +153 -39
  67. package/src/flows/FlowPalette.tsx +156 -70
  68. package/src/flows/FlowPortalNode.tsx +1 -1
  69. package/src/flows/FlowWhatsAppPreview.tsx +14 -3
  70. package/src/flows/FlowsWorkspace.tsx +1255 -0
  71. package/src/flows/flowCanvasModel.test.ts +456 -0
  72. package/src/flows/flowCanvasModel.ts +378 -0
  73. package/src/flows/flowEditorOps.test.ts +276 -0
  74. package/src/flows/flowEditorOps.ts +202 -0
  75. package/src/flows/flowGraph.ts +78 -53
  76. package/src/flows/flowMenuPlacement.test.ts +130 -0
  77. package/src/flows/flowMenuPlacement.ts +86 -0
  78. package/src/flows/index.ts +51 -2
  79. package/src/flows/labels.ts +180 -0
  80. package/src/flows/workspaceContract.test.ts +126 -0
  81. package/src/hooks/useContainerWidth.ts +35 -0
  82. package/src/hooks/useConversationRealtime.ts +10 -8
  83. package/src/hooks/useScrollToLatestMessage.ts +127 -0
  84. package/src/hooks/useUrlFilterState.ts +107 -0
  85. package/src/icon.constant.ts +12 -0
  86. package/src/index.ts +100 -0
  87. package/src/lib/composer-formatting.test.ts +78 -0
  88. package/src/lib/composer-formatting.ts +145 -0
  89. package/src/lib/whatsapp-formatting.test.tsx +37 -0
  90. package/src/lib/whatsapp-formatting.tsx +28 -3
  91. package/src/listing/index.tsx +202 -0
  92. package/src/pagination.constant.ts +10 -0
  93. package/src/preview/ConversationPreview.tsx +84 -45
  94. package/src/preview/ConversationSimulatorClient.ts +143 -0
  95. package/src/preview/ConversationSimulatorPanel.test.tsx +55 -0
  96. package/src/preview/ConversationSimulatorPanel.tsx +131 -0
  97. package/src/preview/createPreviewBridgeClient.test.ts +92 -0
  98. package/src/preview/createPreviewBridgeClient.ts +124 -0
  99. package/src/preview/createPreviewMediaUploader.ts +82 -0
  100. package/src/preview/createPreviewWebhookClient.test.ts +96 -0
  101. package/src/preview/createPreviewWebhookClient.ts +99 -3
  102. package/src/preview/index.ts +36 -2
  103. package/src/preview/previewMediaUploader.test.ts +61 -0
  104. package/src/providers/ConversationsProvider.tsx +8 -6
  105. package/src/providers/types.ts +59 -2
  106. package/src/quickReply.test.ts +58 -0
  107. package/src/replyLatency.test.ts +71 -0
  108. package/src/replyLatency.ts +57 -0
  109. package/src/settings/MessagesWorkspace.tsx +571 -0
  110. package/src/settings/TopicsForm.tsx +2 -0
  111. package/src/settings/TranscriptionSettingsForm.test.tsx +81 -0
  112. package/src/settings/TranscriptionSettingsForm.tsx +190 -0
  113. package/src/settings/WelcomeFarewellForm.tsx +1 -0
  114. package/src/settings/WhatsAppCreateTemplateForm.tsx +1 -0
  115. package/src/settings/WhatsAppTemplateSettingsForm.tsx +5 -2
  116. package/src/settings/WhatsAppTemplatesSettings.test.tsx +61 -0
  117. package/src/settings/WhatsAppTemplatesSettings.tsx +22 -2
  118. package/src/styles.css +858 -0
  119. package/src/theme.ts +13 -0
  120. package/src/types.ts +26 -0
  121. package/src/workspace/BulkTemplateModal.tsx +132 -0
  122. package/src/workspace/ConversationPane.tsx +432 -0
  123. package/src/workspace/ConversationsInboxList.tsx +194 -0
  124. package/src/workspace/ConversationsWorkspace.tsx +423 -0
  125. package/src/workspace/index.ts +17 -0
  126. package/src/workspace/labels.test.ts +17 -0
  127. package/src/workspace/labels.ts +85 -0
  128. package/src/workspace/useConversationsInbox.ts +332 -0
  129. package/dist/chunk-73MW5HNT.js +0 -1717
  130. package/dist/chunk-NV2RZ5KT.js +0 -56
  131. package/dist/types-B5C1DLu1.d.ts +0 -365
  132. package/src/preview/AudioRecorderButton.tsx +0 -117
@@ -1,56 +0,0 @@
1
- // src/useDarkMode.ts
2
- import { useState, useEffect, useCallback } from "react";
3
- var STORAGE_KEY = "conversations-ui-dark-mode";
4
- function getInitialDark() {
5
- if (typeof window === "undefined") return false;
6
- const stored = localStorage.getItem(STORAGE_KEY);
7
- if (stored !== null) {
8
- return stored === "true";
9
- }
10
- return window.matchMedia("(prefers-color-scheme: dark)").matches;
11
- }
12
- function useIsDarkTheme() {
13
- const [isDark, setIsDark] = useState(
14
- () => typeof document !== "undefined" && document.documentElement.classList.contains("dark")
15
- );
16
- useEffect(() => {
17
- const root = document.documentElement;
18
- const observer = new MutationObserver(() => setIsDark(root.classList.contains("dark")));
19
- observer.observe(root, { attributes: true, attributeFilter: ["class"] });
20
- setIsDark(root.classList.contains("dark"));
21
- return () => observer.disconnect();
22
- }, []);
23
- return isDark;
24
- }
25
- function useDarkMode() {
26
- const [isDark, setIsDark] = useState(getInitialDark);
27
- useEffect(() => {
28
- const root = document.documentElement;
29
- if (isDark) {
30
- root.classList.add("dark");
31
- } else {
32
- root.classList.remove("dark");
33
- }
34
- localStorage.setItem(STORAGE_KEY, String(isDark));
35
- }, [isDark]);
36
- useEffect(() => {
37
- const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
38
- const handleChange = (event) => {
39
- const stored = localStorage.getItem(STORAGE_KEY);
40
- if (stored === null) {
41
- setIsDark(event.matches);
42
- }
43
- };
44
- mediaQuery.addEventListener("change", handleChange);
45
- return () => mediaQuery.removeEventListener("change", handleChange);
46
- }, []);
47
- const toggle = useCallback(() => {
48
- setIsDark((prev) => !prev);
49
- }, []);
50
- return { isDark, toggle };
51
- }
52
-
53
- export {
54
- useIsDarkTheme,
55
- useDarkMode
56
- };
@@ -1,365 +0,0 @@
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
- * Canal de origem da conversa e o que cada um permite.
109
- *
110
- * Existe porque as regras que a inbox precisa respeitar não são do WhatsApp, são **de cada canal**:
111
- * a janela de sessão, o jeito de reabrir a conversa e o formato do identificador do contato mudam
112
- * entre WhatsApp, Messenger, Instagram e chat de site. Tratar a regra do WhatsApp como universal
113
- * faria a UI bloquear o composer num chat de site, onde janela nenhuma existe.
114
- *
115
- * `whatsapp` é o padrão em todo lugar: instalações que ainda não informam canal continuam
116
- * funcionando exatamente como antes.
117
- */
118
- declare const CONVERSATION_CHANNEL: {
119
- readonly WHATSAPP: "whatsapp";
120
- readonly MESSENGER: "messenger";
121
- readonly INSTAGRAM: "instagram";
122
- readonly WEBCHAT: "webchat";
123
- };
124
- type ConversationChannel = (typeof CONVERSATION_CHANNEL)[keyof typeof CONVERSATION_CHANNEL];
125
- declare const DEFAULT_CONVERSATION_CHANNEL: ConversationChannel;
126
- /** Como o canal reabre uma conversa fora da janela de sessão. */
127
- declare const REOPEN_MECHANISM: {
128
- readonly TEMPLATE: "template";
129
- readonly TAG: "tag";
130
- readonly NONE: "none";
131
- };
132
- type ReopenMechanism = (typeof REOPEN_MECHANISM)[keyof typeof REOPEN_MECHANISM];
133
- /** Natureza do identificador do contato — decide como exibi-lo. */
134
- declare const HANDLE_KIND: {
135
- readonly PHONE: "phone";
136
- readonly USERNAME: "username";
137
- readonly SESSION: "session";
138
- };
139
- type HandleKind = (typeof HANDLE_KIND)[keyof typeof HANDLE_KIND];
140
- type ChannelCapabilities = {
141
- readonly label: string;
142
- readonly icon: string;
143
- readonly hasSessionWindow: boolean;
144
- readonly windowHours: number;
145
- readonly reopenMechanism: ReopenMechanism;
146
- readonly handleKind: HandleKind;
147
- };
148
- declare const CHANNEL_CAPABILITIES: Readonly<Record<ConversationChannel, ChannelCapabilities>>;
149
- declare function capabilitiesOf(channel: ConversationChannel | undefined): ChannelCapabilities;
150
- declare const CHANNEL_FILTER_ALL = "all";
151
- type ChannelFilter = ConversationChannel | typeof CHANNEL_FILTER_ALL;
152
- type ChannelFilterOption = {
153
- readonly value: ChannelFilter;
154
- readonly label: string;
155
- };
156
- /**
157
- * Opções derivadas do que existe na lista, não do catálogo inteiro: oferecer Instagram numa conta
158
- * que só tem WhatsApp promete um recorte que nunca traz resultado.
159
- *
160
- * Devolve vazio com menos de dois canais — um filtro de opção única não filtra nada, e a barra só
161
- * ocuparia espaço. O host usa isso para esconder a seção.
162
- */
163
- declare function channelFiltersFor(conversations: readonly {
164
- readonly channel?: ConversationChannel | undefined;
165
- }[]): ChannelFilterOption[];
166
- type FormatContactHandleParams = {
167
- readonly handle: string;
168
- readonly channel?: ConversationChannel | undefined;
169
- };
170
- /**
171
- * Exibição do identificador conforme a natureza dele. Formatar tudo como telefone — o que a UI
172
- * fazia — transforma um `@perfil` do Instagram em dígitos sem sentido.
173
- */
174
- declare function formatContactHandle(params: FormatContactHandleParams): string;
175
- /** Bandeira só faz sentido quando o identificador é telefone. */
176
- declare function contactFlag(params: FormatContactHandleParams): string;
177
-
178
- interface ListConversationsParams {
179
- page?: number;
180
- limit?: number;
181
- waitingHuman?: boolean;
182
- search?: string;
183
- /**
184
- * Recortes que só o produto conhece (tipo de financiamento, carteira, campanha) repassados
185
- * crus ao backend dele. É o que evita o vocabulário de uma vertical virar campo fixo aqui:
186
- * o pacote transporta o filtro sem saber o que ele significa.
187
- */
188
- filters?: Record<string, string | undefined>;
189
- }
190
- /**
191
- * Página com o total, para a UI conseguir desenhar controles de paginação.
192
- *
193
- * `fetchConversations` devolve isto **ou** o array puro de antes: implementações existentes
194
- * continuam válidas sem mudar uma linha, e quem precisa paginar passa a ter o total. Sem a união
195
- * seria impossível saber se um retorno curto é a última página ou uma página cheia por acaso.
196
- */
197
- interface ConversationPage {
198
- conversations: ConversationSummary[];
199
- total: number;
200
- }
201
- interface ListDocumentsParams {
202
- search?: string;
203
- page?: number;
204
- /** Tamanho da página. Sem ele, `page` sozinho não define fatia nenhuma. */
205
- limit?: number;
206
- /** Origem do arquivo (`customer`, `agent`, `bot`…). O vocabulário é do host. */
207
- source?: string;
208
- sortDirection?: 'asc' | 'desc';
209
- }
210
- /** Arquivo na biblioteca da empresa: o mesmo da conversa, mais de qual conversa veio. */
211
- interface CompanyDocument extends ConversationDocument {
212
- conversationId: string;
213
- }
214
- interface CompanyDocumentPage {
215
- documents: CompanyDocument[];
216
- total: number;
217
- }
218
- interface ConversationDocumentPage {
219
- documents: ConversationDocument[];
220
- total: number;
221
- }
222
- /**
223
- * Template disponível para envio a partir da inbox. Distinto do `WhatsAppTemplateSummary` de
224
- * `settings/`, e de propósito: aquele serve ao formulário que **edita** template e carrega o que
225
- * a edição precisa (`shortId`, `variableCount`); este serve a quem só vai **escolher um para
226
- * enviar**, e pedir os campos de edição obrigaria todo host a produzi-los sem uso.
227
- */
228
- interface ConversationTemplate {
229
- name: string;
230
- language: string;
231
- status: string;
232
- category?: string;
233
- bodyText?: string | null;
234
- }
235
- interface ConversationsApi {
236
- fetchMessages(conversationId: string, params?: {
237
- limit?: number;
238
- before?: string;
239
- }): Promise<MessagePayload[]>;
240
- fetchConversations(params?: ListConversationsParams): Promise<ConversationSummary[] | ConversationPage>;
241
- sendMessage(conversationId: string, text: string): Promise<MessagePayload>;
242
- sendMedia(conversationId: string, data: {
243
- base64: string;
244
- mimeType: string;
245
- filename: string;
246
- caption?: string;
247
- }): Promise<MessagePayload>;
248
- /**
249
- * `templateName` é opcional porque reabrir a janela é a operação, e escolher *qual* template a
250
- * usa nem sempre é decisão da UI: backends que guardam um template padrão configurado só
251
- * precisam do "reabra". Exigir o nome obrigaria toda inbox a listar templates antes de poder
252
- * mandar o primeiro — e a listagem é `listTemplates?`, opcional.
253
- */
254
- sendTemplate(conversationId: string, data: {
255
- templateName?: string;
256
- languageCode?: string;
257
- bodyParams?: string[];
258
- }): Promise<void>;
259
- markRead(conversationId: string): Promise<void>;
260
- getContext(conversationId: string): Promise<Record<string, unknown>>;
261
- getDocuments(conversationId: string, params?: ListDocumentsParams): Promise<ConversationDocument[] | ConversationDocumentPage>;
262
- /**
263
- * `disposition` decide entre abrir no navegador e baixar. É o backend que assina a URL e grava
264
- * o `Content-Disposition` nela, então a escolha precisa viajar na chamada — depois de assinada
265
- * não há como o cliente mudá-la. Ausente = o padrão do host.
266
- */
267
- getDocumentUrl(uploadId: string, disposition?: 'inline' | 'attachment'): Promise<string>;
268
- /**
269
- * Baixa vários arquivos num zip único.
270
- *
271
- * **Opcional por capacidade:** montar zip exige o host LER os bytes do storage, o que nem toda
272
- * instalação faz — as que só assinam URL não conseguem. Ausente, o painel esconde a seleção em
273
- * lote em vez de oferecer um botão que falha.
274
- */
275
- downloadDocumentsArchive?(conversationId: string, uploadIds: readonly string[]): Promise<Blob>;
276
- /**
277
- * Biblioteca de TODAS as conversas, para uma tela de Documentos fora do atendimento.
278
- *
279
- * Opcional por capacidade: host que só expõe anexo dentro da conversa não implementa, e o
280
- * componente de biblioteca simplesmente não é usável — melhor que uma tela que sempre erra.
281
- */
282
- getAllDocuments?(params?: ListDocumentsParams): Promise<CompanyDocumentPage>;
283
- getMediaProxyUrl(mediaId: string): Promise<{
284
- mimeType: string;
285
- data: string;
286
- }>;
287
- /**
288
- * Operações de atendimento humano. **Opcionais por capacidade, não por descuido:** nem toda
289
- * inbox tem fila humana — um canal só-bot, ou um chat de site sem operador, não sabe o que é
290
- * assumir conversa. Quem não implementa não ganha o botão, em vez de ganhar um botão que
291
- * estoura no clique. Os hooks devolvem `undefined` para a ação ausente, e é isso que a UI
292
- * consulta para decidir se desenha a afordância.
293
- */
294
- takeover?(conversationId: string): Promise<void>;
295
- release?(conversationId: string): Promise<void>;
296
- /** Encerra o atendimento. Despedida, se houver, é decisão do host — o pacote não a inventa. */
297
- finalize?(conversationId: string): Promise<void>;
298
- markAllRead?(): Promise<void>;
299
- listTemplates?(): Promise<ConversationTemplate[]>;
300
- /**
301
- * Transcrição completa gerada pelo servidor. Existe ao lado de `buildTranscriptText`, que monta
302
- * a partir das mensagens já em memória: a tela costuma ter só a última página carregada, e
303
- * exportar dali entregaria um recorte parcial com cara de histórico inteiro. Opcional porque
304
- * nem todo backend expõe a rota — quem não tem continua usando o builder local.
305
- */
306
- exportTranscript?(conversationId: string): Promise<{
307
- transcript: string;
308
- filename: string;
309
- }>;
310
- }
311
- /**
312
- * Superfície mínima de stream que o pacote consome — exatamente o que `useConversationRealtime`
313
- * usa: assinar 'message', desassinar e fechar. Deliberadamente estrutural em vez de
314
- * `EventSource`: sem servidor HTTP não existe `EventSource`, e é isso que impediria alimentar a
315
- * inbox com dados mockados em desenvolvimento. Um `EventSource` nativo satisfaz este tipo, então
316
- * quem já implementa `SSEProvider` continua válido sem mudança.
317
- */
318
- interface ConversationEventSource {
319
- addEventListener(type: string, listener: (event: MessageEvent) => void): void;
320
- removeEventListener(type: string, listener: (event: MessageEvent) => void): void;
321
- close(): void;
322
- }
323
- interface SSEProvider {
324
- connectConversationStream(conversationId: string): ConversationEventSource;
325
- connectGlobalStream(): ConversationEventSource;
326
- }
327
- interface ConversationSummary {
328
- id: string;
329
- /**
330
- * @deprecated Use `contactId` com `channel`. Mantido obrigatório para não quebrar quem já
331
- * consome; some quando o segundo canal entrar em produção.
332
- */
333
- whatsappNumber: string;
334
- /** Identificador neutro do contato. Ausente = usa `whatsappNumber`. */
335
- contactId?: string;
336
- /** Ausente = `whatsapp`, o comportamento de antes desta mudança. */
337
- channel?: ConversationChannel;
338
- clientName?: string;
339
- lastContent?: string;
340
- lastDirection?: 'inbound' | 'outbound';
341
- lastAt: string;
342
- lastInboundAt: string | null;
343
- mode: 'bot' | 'human';
344
- assignedUserId: string | null;
345
- waitingHuman: boolean;
346
- unread: number;
347
- currentState: string;
348
- /**
349
- * Atributos que só o produto conhece e desenha (tipo de financiamento, carteira, campanha). É a
350
- * contraparte de leitura do `filters` de `ListConversationsParams`: o pacote transporta e nunca
351
- * interpreta. Sem isto, exibir um selo próprio na linha exigiria o host manter uma segunda
352
- * consulta paralela à mesma listagem — a implementação duplicada que o pacote existe para evitar.
353
- */
354
- attributes?: Record<string, string | undefined>;
355
- }
356
- interface ConversationDocument {
357
- id: string;
358
- filename: string;
359
- mimeType: string;
360
- sizeBytes: number;
361
- source: string;
362
- linkedAt: string;
363
- }
364
-
365
- export { type ResolveMediaUrl as A, capabilitiesOf as B, CHANNEL_CAPABILITIES as C, DEFAULT_CONVERSATION_CHANNEL as D, channelFiltersFor as E, type FormatContactHandleParams as F, contactFlag as G, HANDLE_KIND as H, type InteractiveOption as I, formatContactHandle as J, type ListConversationsParams as L, MediaRenderer as M, REOPEN_MECHANISM as R, type SSEProvider as S, CHANNEL_FILTER_ALL as a, CONVERSATION_CHANNEL as b, type ChannelCapabilities as c, type ChannelFilter as d, type ChannelFilterOption as e, type CompanyDocument as f, type CompanyDocumentPage as g, type ConversationChannel as h, type ConversationDocument as i, type ConversationDocumentPage as j, type ConversationEventSource as k, type ConversationPage as l, type ConversationSummary as m, type ConversationTemplate as n, type ConversationsApi as o, type ConversationsFeatures as p, type ConversationsTheme as q, type ConversationsUIConfig as r, type HandleKind as s, type InteractivePayload as t, type InteractiveSection as u, type InteractiveSelection as v, type ListDocumentsParams as w, type MediaRendererProps as x, type MessagePayload as y, type ReopenMechanism as z };
@@ -1,117 +0,0 @@
1
- /**
2
- * Gravação de áudio no simulador, pelo microfone do próprio navegador.
3
- *
4
- * Existe porque áudio é o formato que mais chega de cliente real e o que mais quebra fluxo: sem
5
- * poder gravar aqui, testar o caminho de transcrição exigia mandar mensagem do celular de alguém.
6
- *
7
- * O arquivo gravado sai daqui como `File` e segue exatamente o mesmo caminho de um anexo — quem
8
- * hospeda e devolve o `mediaId` é o host, via `uploadMedia`.
9
- */
10
-
11
- import { useCallback, useRef, useState } from 'react'
12
-
13
- export interface AudioRecorderButtonLabels {
14
- start: string
15
- stop: string
16
- unsupported: string
17
- denied: string
18
- }
19
-
20
- export const DEFAULT_AUDIO_RECORDER_BUTTON_LABELS: AudioRecorderButtonLabels = {
21
- start: 'Gravar áudio',
22
- stop: 'Parar gravação',
23
- unsupported: 'Este navegador não grava áudio.',
24
- denied: 'Sem permissão para usar o microfone.',
25
- }
26
-
27
- export interface AudioRecorderButtonProps {
28
- onRecorded: (file: File) => void | Promise<void>
29
- onFailure?: (message: string) => void
30
- labels?: Partial<AudioRecorderButtonLabels>
31
- disabled?: boolean
32
- }
33
-
34
- /**
35
- * Ordem de preferência de formato: os dois primeiros o WhatsApp aceita como áudio; `webm` é só
36
- * saída de emergência para navegador que não grava mais nada — gravar em webm e descobrir na hora
37
- * do envio que o formato é inválido é pior do que gravar já no formato certo.
38
- */
39
- const RECORDING_FORMATS = [
40
- { mimeType: 'audio/ogg;codecs=opus', uploadMimeType: 'audio/ogg', extension: 'ogg' },
41
- { mimeType: 'audio/mp4', uploadMimeType: 'audio/mp4', extension: 'm4a' },
42
- { mimeType: 'audio/webm', uploadMimeType: 'audio/webm', extension: 'webm' },
43
- ] as const
44
-
45
- export type RecordingFormat = (typeof RECORDING_FORMATS)[number]
46
-
47
- /** Primeiro formato que o navegador sabe gravar, ou `undefined` se não souber gravar nenhum. */
48
- export function resolveRecordingFormat(): RecordingFormat | undefined {
49
- if (typeof MediaRecorder === 'undefined') return undefined
50
- // `isTypeSupported` não existe em toda implementação; onde falta, o primeiro da lista é o palpite.
51
- if (typeof MediaRecorder.isTypeSupported !== 'function') return RECORDING_FORMATS[0]
52
- return RECORDING_FORMATS.find((format) => MediaRecorder.isTypeSupported(format.mimeType))
53
- }
54
-
55
- export function AudioRecorderButton({ onRecorded, onFailure, labels, disabled }: AudioRecorderButtonProps) {
56
- const startLabel = labels?.start ?? DEFAULT_AUDIO_RECORDER_BUTTON_LABELS.start
57
- const stopLabel = labels?.stop ?? DEFAULT_AUDIO_RECORDER_BUTTON_LABELS.stop
58
- const [isRecording, setIsRecording] = useState(false)
59
- const recorderRef = useRef<MediaRecorder | null>(null)
60
-
61
- const stop = useCallback(() => {
62
- recorderRef.current?.stop()
63
- }, [])
64
-
65
- const start = useCallback(async () => {
66
- const format = resolveRecordingFormat()
67
- if (!format || !navigator.mediaDevices?.getUserMedia) {
68
- onFailure?.(labels?.unsupported ?? DEFAULT_AUDIO_RECORDER_BUTTON_LABELS.unsupported)
69
- return
70
- }
71
-
72
- try {
73
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
74
- const recorder = new MediaRecorder(stream, { mimeType: format.mimeType })
75
- const chunks: Blob[] = []
76
-
77
- recorder.addEventListener('dataavailable', (event) => {
78
- if (event.data.size > 0) chunks.push(event.data)
79
- })
80
- recorder.addEventListener('stop', () => {
81
- // Solta o microfone assim que para: sem isto o indicador de gravação do navegador fica
82
- // aceso depois do envio, e o operador acha que o simulador continua ouvindo.
83
- stream.getTracks().forEach((track) => track.stop())
84
- setIsRecording(false)
85
- recorderRef.current = null
86
- // O `File` sai com o MIME sem os parâmetros de codec: `audio/ogg;codecs=opus` serve ao
87
- // gravador, mas quem valida upload compara com `audio/ogg` puro.
88
- const blob = new Blob(chunks, { type: format.uploadMimeType })
89
- void onRecorded(
90
- new File([blob], `audio-${Date.now()}.${format.extension}`, { type: format.uploadMimeType }),
91
- )
92
- })
93
-
94
- recorderRef.current = recorder
95
- recorder.start()
96
- setIsRecording(true)
97
- } catch {
98
- onFailure?.(labels?.denied ?? DEFAULT_AUDIO_RECORDER_BUTTON_LABELS.denied)
99
- }
100
- }, [labels?.denied, labels?.unsupported, onFailure, onRecorded])
101
-
102
- return (
103
- <button
104
- type="button"
105
- disabled={disabled}
106
- onClick={() => (isRecording ? stop() : void start())}
107
- title={isRecording ? stopLabel : startLabel}
108
- aria-label={isRecording ? stopLabel : startLabel}
109
- aria-pressed={isRecording}
110
- className={`flex h-9 w-9 items-center justify-center rounded-full transition-colors ${
111
- isRecording ? 'bg-red-100 text-red-600 dark:bg-red-900/40' : 'text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700'
112
- }`}
113
- >
114
- {isRecording ? '■' : '🎤'}
115
- </button>
116
- )
117
- }