@menuia/react 1.5.1 → 1.7.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.
package/README.md ADDED
@@ -0,0 +1,29 @@
1
+ # @menuia/react
2
+
3
+ Componente e hook React do chat da MenuIA (usa o `@menuia/core`).
4
+
5
+ ```tsx
6
+ import { useMenuIA } from '@menuia/react';
7
+
8
+ const chat = useMenuIA({ widgetId: 'SEU_WIDGET_ID' });
9
+ // chat.messages, chat.sendMessage(texto), chat.retryMessage(msg), ...
10
+ ```
11
+
12
+ ## Notificação quando a equipe ou a IA responde
13
+
14
+ O hook expõe os mesmos métodos do `MenuIAClient`:
15
+
16
+ ```tsx
17
+ // Aviso do navegador com a aba escondida — chame dentro de um clique
18
+ <button onClick={() => chat.ativarNotificacaoNoNavegador({ titulo: 'Minha Loja' })}>
19
+ Avisar quando responderem
20
+ </button>
21
+
22
+ // App (React Native/Expo, ou web com Firebase): registre o token do aparelho
23
+ await chat.registrarPush({ tipo: 'expo', token });
24
+ // ao sair da conta
25
+ await chat.removerPush(token);
26
+ ```
27
+
28
+ Credenciais, quem recebe, contagem de mensagens e limites: veja o README do `@menuia/core`
29
+ (seção "Notificação quando a equipe ou a IA responde").
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { MenuIAConfig, ChatMessage, ConnectionStatus, MessageAttachment } from '@menuia/core';
3
- export { ChatMessage, ConnectionStatus, MenuIAClient, MenuIAConfig, MessageAttachment, SendMessageOptions } from '@menuia/core';
2
+ import { MenuIAConfig, ChatMessage, ConnectionStatus, MessageAttachment, RegistrarPushOptions, RegistrarPushResult, NotificacaoNavegadorOptions } from '@menuia/core';
3
+ export { ChatMessage, ConnectionStatus, InteractiveButton, InteractivePayload, MenuIAClient, MenuIAConfig, MessageAttachment, NotificacaoNavegadorOptions, RegistrarPushOptions, RegistrarPushResult, SendMessageOptions } from '@menuia/core';
4
4
 
5
5
  interface MenuIAChatProps extends Omit<MenuIAConfig, 'widgetId' | 'agentId'> {
6
6
  /** Widget ID (from /dashboard/channels) - preferred */
@@ -34,7 +34,7 @@ interface MenuIAChatProps extends Omit<MenuIAConfig, 'widgetId' | 'agentId'> {
34
34
  /** Show powered by MenuIA */
35
35
  showPoweredBy?: boolean;
36
36
  }
37
- declare function MenuIAChat({ title, subtitle, avatar, primaryColor, theme, position, welcomeMessage, placeholder, defaultOpen, inline, width, height, showPoweredBy, widgetId, agentId, apiUrl, sessionId, customFields, metadata, channel, onMessage, onStatusChange, onTicketCreated, onError, }: MenuIAChatProps): react_jsx_runtime.JSX.Element;
37
+ declare function MenuIAChat({ title, subtitle, avatar, primaryColor, theme, position, welcomeMessage, placeholder, defaultOpen, inline, width, height, showPoweredBy, widgetId, agentId, apiUrl, sessionId, customFields, metadata, channel, sessionToken, visitorName, visitorEmail, visitorPhone, onMessage, onStatusChange, onTicketCreated, onError, }: MenuIAChatProps): react_jsx_runtime.JSX.Element;
38
38
 
39
39
  interface UseMenuIAReturn {
40
40
  messages: ChatMessage[];
@@ -46,8 +46,25 @@ interface UseMenuIAReturn {
46
46
  aiPaused: boolean;
47
47
  error: string | null;
48
48
  sendMessage: (content: string, attachments?: MessageAttachment[]) => Promise<void>;
49
+ /**
50
+ * Reenvia uma mensagem marcada com `failed` (ver `ChatMessage.failed`), sem criar outra bolha.
51
+ * Reenvia tambem o anexo original, quando havia um.
52
+ */
53
+ retryMessage: (message: ChatMessage) => Promise<void>;
49
54
  clearChat: () => void;
50
55
  ticketId: string | null;
56
+ /**
57
+ * Registra o aparelho para receber notificacao quando a equipe/IA responder, com o app fechado
58
+ * (token do FCM ou do Expo). Ver `MenuIAClient.registrarPush`.
59
+ */
60
+ registrarPush: (opcoes: RegistrarPushOptions) => Promise<RegistrarPushResult>;
61
+ /** Desliga a notificacao neste aparelho (ex.: ao sair da conta). */
62
+ removerPush: (token: string) => Promise<RegistrarPushResult>;
63
+ /**
64
+ * Aviso do navegador com a aba escondida. ⚠️ Chame dentro de um clique (o navegador so pede
65
+ * permissao em resposta a um gesto). Ver `MenuIAClient.ativarNotificacaoNoNavegador`.
66
+ */
67
+ ativarNotificacaoNoNavegador: (opcoes?: NotificacaoNavegadorOptions) => Promise<NotificationPermission | 'indisponivel'>;
51
68
  }
52
69
  declare function useMenuIA(config: MenuIAConfig): UseMenuIAReturn;
53
70
 
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { MenuIAConfig, ChatMessage, ConnectionStatus, MessageAttachment } from '@menuia/core';
3
- export { ChatMessage, ConnectionStatus, MenuIAClient, MenuIAConfig, MessageAttachment, SendMessageOptions } from '@menuia/core';
2
+ import { MenuIAConfig, ChatMessage, ConnectionStatus, MessageAttachment, RegistrarPushOptions, RegistrarPushResult, NotificacaoNavegadorOptions } from '@menuia/core';
3
+ export { ChatMessage, ConnectionStatus, InteractiveButton, InteractivePayload, MenuIAClient, MenuIAConfig, MessageAttachment, NotificacaoNavegadorOptions, RegistrarPushOptions, RegistrarPushResult, SendMessageOptions } from '@menuia/core';
4
4
 
5
5
  interface MenuIAChatProps extends Omit<MenuIAConfig, 'widgetId' | 'agentId'> {
6
6
  /** Widget ID (from /dashboard/channels) - preferred */
@@ -34,7 +34,7 @@ interface MenuIAChatProps extends Omit<MenuIAConfig, 'widgetId' | 'agentId'> {
34
34
  /** Show powered by MenuIA */
35
35
  showPoweredBy?: boolean;
36
36
  }
37
- declare function MenuIAChat({ title, subtitle, avatar, primaryColor, theme, position, welcomeMessage, placeholder, defaultOpen, inline, width, height, showPoweredBy, widgetId, agentId, apiUrl, sessionId, customFields, metadata, channel, onMessage, onStatusChange, onTicketCreated, onError, }: MenuIAChatProps): react_jsx_runtime.JSX.Element;
37
+ declare function MenuIAChat({ title, subtitle, avatar, primaryColor, theme, position, welcomeMessage, placeholder, defaultOpen, inline, width, height, showPoweredBy, widgetId, agentId, apiUrl, sessionId, customFields, metadata, channel, sessionToken, visitorName, visitorEmail, visitorPhone, onMessage, onStatusChange, onTicketCreated, onError, }: MenuIAChatProps): react_jsx_runtime.JSX.Element;
38
38
 
39
39
  interface UseMenuIAReturn {
40
40
  messages: ChatMessage[];
@@ -46,8 +46,25 @@ interface UseMenuIAReturn {
46
46
  aiPaused: boolean;
47
47
  error: string | null;
48
48
  sendMessage: (content: string, attachments?: MessageAttachment[]) => Promise<void>;
49
+ /**
50
+ * Reenvia uma mensagem marcada com `failed` (ver `ChatMessage.failed`), sem criar outra bolha.
51
+ * Reenvia tambem o anexo original, quando havia um.
52
+ */
53
+ retryMessage: (message: ChatMessage) => Promise<void>;
49
54
  clearChat: () => void;
50
55
  ticketId: string | null;
56
+ /**
57
+ * Registra o aparelho para receber notificacao quando a equipe/IA responder, com o app fechado
58
+ * (token do FCM ou do Expo). Ver `MenuIAClient.registrarPush`.
59
+ */
60
+ registrarPush: (opcoes: RegistrarPushOptions) => Promise<RegistrarPushResult>;
61
+ /** Desliga a notificacao neste aparelho (ex.: ao sair da conta). */
62
+ removerPush: (token: string) => Promise<RegistrarPushResult>;
63
+ /**
64
+ * Aviso do navegador com a aba escondida. ⚠️ Chame dentro de um clique (o navegador so pede
65
+ * permissao em resposta a um gesto). Ver `MenuIAClient.ativarNotificacaoNoNavegador`.
66
+ */
67
+ ativarNotificacaoNoNavegador: (opcoes?: NotificacaoNavegadorOptions) => Promise<NotificationPermission | 'indisponivel'>;
51
68
  }
52
69
  declare function useMenuIA(config: MenuIAConfig): UseMenuIAReturn;
53
70
 
package/dist/index.js CHANGED
@@ -43,9 +43,15 @@ var import_react2 = __toESM(require("react"));
43
43
  var import_react = require("react");
44
44
  var import_core = require("@menuia/core");
45
45
  var normalizar = (s) => (s || "").trim().replace(/\s+/g, " ").toLowerCase();
46
+ var ehIdLocal = (id) => /^(user|assistant)_\d/.test(id || "");
46
47
  function mesmaMensagem(lista, msg) {
47
48
  const alvo = normalizar(msg.content);
48
- return lista.some((m) => m.id === msg.id || !!alvo && m.role === msg.role && normalizar(m.content) === alvo);
49
+ return lista.some((m) => {
50
+ if (m.id === msg.id) return true;
51
+ if (!alvo || m.role !== msg.role) return false;
52
+ if (normalizar(m.content) !== alvo) return false;
53
+ return ehIdLocal(m.id) || ehIdLocal(msg.id);
54
+ });
49
55
  }
50
56
  var vazia = (m) => !normalizar(m.content || "") && !m.mediaUrl;
51
57
  function useMenuIA(config) {
@@ -80,6 +86,7 @@ function useMenuIA(config) {
80
86
  clientRef.current = null;
81
87
  };
82
88
  }, [config.widgetId, config.agentId, config.apiUrl]);
89
+ const anexosPorBolha = (0, import_react.useRef)(/* @__PURE__ */ new Map());
83
90
  const sendMessage = (0, import_react.useCallback)(async (content, attachments) => {
84
91
  const text = content.trim();
85
92
  const hasAttachments = !!(attachments && attachments.length);
@@ -96,6 +103,7 @@ function useMenuIA(config) {
96
103
  mediaType: firstAtt ? firstAtt.mimeType : void 0
97
104
  };
98
105
  setMessages((prev) => [...prev, userMsg]);
106
+ if (hasAttachments) anexosPorBolha.current.set(userMsg.id, attachments);
99
107
  try {
100
108
  setIsStreaming(true);
101
109
  setStreamingText("");
@@ -138,6 +146,7 @@ function useMenuIA(config) {
138
146
  } catch (fallbackErr) {
139
147
  const errMsg = fallbackErr instanceof Error ? fallbackErr.message : "Erro ao enviar mensagem";
140
148
  setError(errMsg);
149
+ setMessages((prev) => prev.map((m) => m.id === userMsg.id ? { ...m, failed: true } : m));
141
150
  }
142
151
  } finally {
143
152
  setIsLoading(false);
@@ -145,7 +154,74 @@ function useMenuIA(config) {
145
154
  setStreamingText("");
146
155
  }
147
156
  }, []);
157
+ const retryMessage = (0, import_react.useCallback)(async (message) => {
158
+ if (!clientRef.current || !message) return;
159
+ const atts = anexosPorBolha.current.get(message.id);
160
+ const text = (message.content || "").trim();
161
+ if (!text && !(atts && atts.length)) return;
162
+ setError(null);
163
+ setIsLoading(true);
164
+ setMessages((prev) => prev.map((m) => m.id === message.id ? { ...m, failed: false } : m));
165
+ try {
166
+ setIsStreaming(true);
167
+ setStreamingText("");
168
+ const response = await clientRef.current.sendMessageStream(
169
+ { content: text, attachments: atts },
170
+ (_token, fullText) => setStreamingText(fullText)
171
+ );
172
+ setAiPaused(!!response?.data?.aiPaused);
173
+ const finalContent = (response?.data?.message || "").trim();
174
+ if (finalContent && !response?.data?.aiPaused) {
175
+ const assistantMsg = {
176
+ id: `assistant_${Date.now()}`,
177
+ role: "assistant",
178
+ content: finalContent,
179
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
180
+ };
181
+ setMessages((prev) => mesmaMensagem(prev, assistantMsg) ? prev : [...prev, assistantMsg]);
182
+ }
183
+ if (response?.data?.ticketId) setTicketId(response.data.ticketId);
184
+ } catch (err) {
185
+ try {
186
+ setIsStreaming(false);
187
+ setStreamingText("");
188
+ const response = await clientRef.current.sendMessage({ content: text, attachments: atts });
189
+ setAiPaused(!!response?.data?.aiPaused);
190
+ const conteudoFb = (response?.data?.message || "").trim();
191
+ if (conteudoFb && !response?.data?.aiPaused) {
192
+ const fb = {
193
+ id: `assistant_${Date.now()}_fb`,
194
+ role: "assistant",
195
+ content: conteudoFb,
196
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
197
+ };
198
+ setMessages((prev) => mesmaMensagem(prev, fb) ? prev : [...prev, fb]);
199
+ }
200
+ } catch (fallbackErr) {
201
+ const errMsg = fallbackErr instanceof Error ? fallbackErr.message : "Erro ao reenviar mensagem";
202
+ setError(errMsg);
203
+ setMessages((prev) => prev.map((m) => m.id === message.id ? { ...m, failed: true } : m));
204
+ }
205
+ } finally {
206
+ setIsLoading(false);
207
+ setIsStreaming(false);
208
+ setStreamingText("");
209
+ }
210
+ }, []);
211
+ const registrarPush = (0, import_react.useCallback)(async (opcoes) => {
212
+ if (!clientRef.current) return { ok: false, erro: "chat ainda nao iniciado" };
213
+ return clientRef.current.registrarPush(opcoes);
214
+ }, []);
215
+ const removerPush = (0, import_react.useCallback)(async (token) => {
216
+ if (!clientRef.current) return { ok: false, erro: "chat ainda nao iniciado" };
217
+ return clientRef.current.removerPush(token);
218
+ }, []);
219
+ const ativarNotificacaoNoNavegador = (0, import_react.useCallback)(async (opcoes) => {
220
+ if (!clientRef.current) return "indisponivel";
221
+ return clientRef.current.ativarNotificacaoNoNavegador(opcoes);
222
+ }, []);
148
223
  const clearChat = (0, import_react.useCallback)(() => {
224
+ anexosPorBolha.current.clear();
149
225
  clientRef.current?.clearSession();
150
226
  setMessages([]);
151
227
  setTicketId(null);
@@ -160,8 +236,12 @@ function useMenuIA(config) {
160
236
  aiPaused,
161
237
  error,
162
238
  sendMessage,
239
+ retryMessage,
163
240
  clearChat,
164
- ticketId
241
+ ticketId,
242
+ registrarPush,
243
+ removerPush,
244
+ ativarNotificacaoNoNavegador
165
245
  };
166
246
  }
167
247
 
@@ -501,6 +581,10 @@ function MenuIAChat({
501
581
  customFields,
502
582
  metadata,
503
583
  channel,
584
+ sessionToken,
585
+ visitorName,
586
+ visitorEmail,
587
+ visitorPhone,
504
588
  onMessage,
505
589
  onStatusChange,
506
590
  onTicketCreated,
@@ -529,6 +613,11 @@ function MenuIAChat({
529
613
  customFields,
530
614
  metadata,
531
615
  channel,
616
+ // Widget privado: sem repassar o token o componente abria a sessao sem credencial (401).
617
+ sessionToken,
618
+ visitorName,
619
+ visitorEmail,
620
+ visitorPhone,
532
621
  onMessage,
533
622
  onStatusChange,
534
623
  onTicketCreated,
package/dist/index.mjs CHANGED
@@ -5,9 +5,15 @@ import React, { useState as useState2, useRef as useRef2, useEffect as useEffect
5
5
  import { useState, useEffect, useRef, useCallback } from "react";
6
6
  import { MenuIAClient } from "@menuia/core";
7
7
  var normalizar = (s) => (s || "").trim().replace(/\s+/g, " ").toLowerCase();
8
+ var ehIdLocal = (id) => /^(user|assistant)_\d/.test(id || "");
8
9
  function mesmaMensagem(lista, msg) {
9
10
  const alvo = normalizar(msg.content);
10
- return lista.some((m) => m.id === msg.id || !!alvo && m.role === msg.role && normalizar(m.content) === alvo);
11
+ return lista.some((m) => {
12
+ if (m.id === msg.id) return true;
13
+ if (!alvo || m.role !== msg.role) return false;
14
+ if (normalizar(m.content) !== alvo) return false;
15
+ return ehIdLocal(m.id) || ehIdLocal(msg.id);
16
+ });
11
17
  }
12
18
  var vazia = (m) => !normalizar(m.content || "") && !m.mediaUrl;
13
19
  function useMenuIA(config) {
@@ -42,6 +48,7 @@ function useMenuIA(config) {
42
48
  clientRef.current = null;
43
49
  };
44
50
  }, [config.widgetId, config.agentId, config.apiUrl]);
51
+ const anexosPorBolha = useRef(/* @__PURE__ */ new Map());
45
52
  const sendMessage = useCallback(async (content, attachments) => {
46
53
  const text = content.trim();
47
54
  const hasAttachments = !!(attachments && attachments.length);
@@ -58,6 +65,7 @@ function useMenuIA(config) {
58
65
  mediaType: firstAtt ? firstAtt.mimeType : void 0
59
66
  };
60
67
  setMessages((prev) => [...prev, userMsg]);
68
+ if (hasAttachments) anexosPorBolha.current.set(userMsg.id, attachments);
61
69
  try {
62
70
  setIsStreaming(true);
63
71
  setStreamingText("");
@@ -100,6 +108,7 @@ function useMenuIA(config) {
100
108
  } catch (fallbackErr) {
101
109
  const errMsg = fallbackErr instanceof Error ? fallbackErr.message : "Erro ao enviar mensagem";
102
110
  setError(errMsg);
111
+ setMessages((prev) => prev.map((m) => m.id === userMsg.id ? { ...m, failed: true } : m));
103
112
  }
104
113
  } finally {
105
114
  setIsLoading(false);
@@ -107,7 +116,74 @@ function useMenuIA(config) {
107
116
  setStreamingText("");
108
117
  }
109
118
  }, []);
119
+ const retryMessage = useCallback(async (message) => {
120
+ if (!clientRef.current || !message) return;
121
+ const atts = anexosPorBolha.current.get(message.id);
122
+ const text = (message.content || "").trim();
123
+ if (!text && !(atts && atts.length)) return;
124
+ setError(null);
125
+ setIsLoading(true);
126
+ setMessages((prev) => prev.map((m) => m.id === message.id ? { ...m, failed: false } : m));
127
+ try {
128
+ setIsStreaming(true);
129
+ setStreamingText("");
130
+ const response = await clientRef.current.sendMessageStream(
131
+ { content: text, attachments: atts },
132
+ (_token, fullText) => setStreamingText(fullText)
133
+ );
134
+ setAiPaused(!!response?.data?.aiPaused);
135
+ const finalContent = (response?.data?.message || "").trim();
136
+ if (finalContent && !response?.data?.aiPaused) {
137
+ const assistantMsg = {
138
+ id: `assistant_${Date.now()}`,
139
+ role: "assistant",
140
+ content: finalContent,
141
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
142
+ };
143
+ setMessages((prev) => mesmaMensagem(prev, assistantMsg) ? prev : [...prev, assistantMsg]);
144
+ }
145
+ if (response?.data?.ticketId) setTicketId(response.data.ticketId);
146
+ } catch (err) {
147
+ try {
148
+ setIsStreaming(false);
149
+ setStreamingText("");
150
+ const response = await clientRef.current.sendMessage({ content: text, attachments: atts });
151
+ setAiPaused(!!response?.data?.aiPaused);
152
+ const conteudoFb = (response?.data?.message || "").trim();
153
+ if (conteudoFb && !response?.data?.aiPaused) {
154
+ const fb = {
155
+ id: `assistant_${Date.now()}_fb`,
156
+ role: "assistant",
157
+ content: conteudoFb,
158
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
159
+ };
160
+ setMessages((prev) => mesmaMensagem(prev, fb) ? prev : [...prev, fb]);
161
+ }
162
+ } catch (fallbackErr) {
163
+ const errMsg = fallbackErr instanceof Error ? fallbackErr.message : "Erro ao reenviar mensagem";
164
+ setError(errMsg);
165
+ setMessages((prev) => prev.map((m) => m.id === message.id ? { ...m, failed: true } : m));
166
+ }
167
+ } finally {
168
+ setIsLoading(false);
169
+ setIsStreaming(false);
170
+ setStreamingText("");
171
+ }
172
+ }, []);
173
+ const registrarPush = useCallback(async (opcoes) => {
174
+ if (!clientRef.current) return { ok: false, erro: "chat ainda nao iniciado" };
175
+ return clientRef.current.registrarPush(opcoes);
176
+ }, []);
177
+ const removerPush = useCallback(async (token) => {
178
+ if (!clientRef.current) return { ok: false, erro: "chat ainda nao iniciado" };
179
+ return clientRef.current.removerPush(token);
180
+ }, []);
181
+ const ativarNotificacaoNoNavegador = useCallback(async (opcoes) => {
182
+ if (!clientRef.current) return "indisponivel";
183
+ return clientRef.current.ativarNotificacaoNoNavegador(opcoes);
184
+ }, []);
110
185
  const clearChat = useCallback(() => {
186
+ anexosPorBolha.current.clear();
111
187
  clientRef.current?.clearSession();
112
188
  setMessages([]);
113
189
  setTicketId(null);
@@ -122,8 +198,12 @@ function useMenuIA(config) {
122
198
  aiPaused,
123
199
  error,
124
200
  sendMessage,
201
+ retryMessage,
125
202
  clearChat,
126
- ticketId
203
+ ticketId,
204
+ registrarPush,
205
+ removerPush,
206
+ ativarNotificacaoNoNavegador
127
207
  };
128
208
  }
129
209
 
@@ -463,6 +543,10 @@ function MenuIAChat({
463
543
  customFields,
464
544
  metadata,
465
545
  channel,
546
+ sessionToken,
547
+ visitorName,
548
+ visitorEmail,
549
+ visitorPhone,
466
550
  onMessage,
467
551
  onStatusChange,
468
552
  onTicketCreated,
@@ -491,6 +575,11 @@ function MenuIAChat({
491
575
  customFields,
492
576
  metadata,
493
577
  channel,
578
+ // Widget privado: sem repassar o token o componente abria a sessao sem credencial (401).
579
+ sessionToken,
580
+ visitorName,
581
+ visitorEmail,
582
+ visitorPhone,
494
583
  onMessage,
495
584
  onStatusChange,
496
585
  onTicketCreated,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@menuia/react",
3
- "version": "1.5.1",
3
+ "version": "1.7.0",
4
4
  "description": "MenuIA Chat SDK - React Component",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -17,7 +17,7 @@
17
17
  "react-dom": ">=17.0.0"
18
18
  },
19
19
  "dependencies": {
20
- "@menuia/core": "^1.5.2"
20
+ "@menuia/core": "^1.7.0"
21
21
  },
22
22
  "devDependencies": {
23
23
  "@types/react": "^18.2.0",