@agentcrafta/chat-next 0.0.2 → 0.0.3
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 +322 -0
- package/dist/chat-server-DoG_Rvk7.d.ts +20 -0
- package/dist/chunk-MOTD6MKH.js +410 -0
- package/dist/chunk-MOTD6MKH.js.map +1 -0
- package/dist/index.d.ts +2 -84
- package/dist/index.js +5 -344
- package/dist/index.js.map +1 -1
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +3 -1
- package/package.json +1 -1
- package/dist/chunk-RI5TL55G.js +0 -69
- package/dist/chunk-RI5TL55G.js.map +0 -1
package/README.md
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
# Agente Conversacional Embebido
|
|
2
|
+
|
|
3
|
+
## Descripción del Componente
|
|
4
|
+
|
|
5
|
+
El **Agente Conversacional Embebido** es un componente React que integra Microsoft Bot Framework Web Chat en una interfaz moderna y personalizable. Proporciona una experiencia de chat completa con soporte para reinicio de conversación, personalización de estilos dinámicos basados en variables CSS, y gestión automática del estado de conexión.
|
|
6
|
+
|
|
7
|
+
Este componente utiliza el Web Chat de Bot Framework para comunicarse con Power Virtual Agents (PVA) u otros bots compatibles, ofreciendo una interfaz de usuario intuitiva y responsive.
|
|
8
|
+
|
|
9
|
+
## Índice
|
|
10
|
+
|
|
11
|
+
- [Instalación y Configuración](#instalación-y-configuración)
|
|
12
|
+
- [Variables de Entorno](#variables-de-entorno)
|
|
13
|
+
- [Uso del Componente](#uso-del-componente)
|
|
14
|
+
- [Server Actions](#server-actions)
|
|
15
|
+
- [Hook useChat](#hook-usechat)
|
|
16
|
+
- [Configuración de StyleOptions](#configuración-de-styleoptions)
|
|
17
|
+
- [Tipos y Interfaces](#tipos-y-interfaces)
|
|
18
|
+
|
|
19
|
+
## Instalación y Configuración
|
|
20
|
+
|
|
21
|
+
### Variables de Entorno
|
|
22
|
+
|
|
23
|
+
Configure las siguientes variables en su archivo `.env.local` para desarrollo local:
|
|
24
|
+
|
|
25
|
+
```env
|
|
26
|
+
# URL del endpoint para obtener tokens del agente conversacional
|
|
27
|
+
TOKEN_AGENTE_URL=https://your-bot-endpoint.com/powervirtualagents/botsbyschema/...
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Para PRODUCCIÓN, asegúrese de establecer estas variables en su entorno de despliegue.
|
|
31
|
+
|
|
32
|
+
**Importante**: La variable `TOKEN_AGENTE_URL` debe apuntar al endpoint completo de Power Virtual Agents que incluye el esquema del bot y la API version.
|
|
33
|
+
|
|
34
|
+
## Uso del Componente
|
|
35
|
+
|
|
36
|
+
### Características
|
|
37
|
+
|
|
38
|
+
- **Chat flotante**: Aparece como un botón flotante en la esquina inferior derecha
|
|
39
|
+
- **Interfaz responsive**: Se adapta a diferentes tamaños de pantalla
|
|
40
|
+
- **Reinicio de conversación**: Botón para reiniciar la conversación completa
|
|
41
|
+
- **Personalización de estilos**: Utiliza variables CSS para temas dinámicos
|
|
42
|
+
- **Gestión de errores**: Manejo robusto de errores tanto en cliente como en servidor
|
|
43
|
+
|
|
44
|
+
### Props del Componente
|
|
45
|
+
|
|
46
|
+
| Prop | Tipo | Default | Descripción |
|
|
47
|
+
| -------------- | -------------- | ----------- | --------------------------------------------------------------- |
|
|
48
|
+
| `botName` | `string` | `"Agent"` | Nombre que se mostrará en la cabecera del chat |
|
|
49
|
+
| `logoUrl` | `string` | `undefined` | URL del logo que se mostrará junto al nombre del bot (opcional) |
|
|
50
|
+
| `show` | `boolean` | `true` | Indica si el chat debe mostrarse o no (por defecto es true) |
|
|
51
|
+
| `styleOptions` | `StyleOptions` | `undefined` | Opciones de estilo personalizadas para el chat (opcional) |
|
|
52
|
+
|
|
53
|
+
### Importación y Uso
|
|
54
|
+
|
|
55
|
+
#### Básico
|
|
56
|
+
|
|
57
|
+
```tsx
|
|
58
|
+
import { Chat } from "../chat";
|
|
59
|
+
|
|
60
|
+
export default function HomePage() {
|
|
61
|
+
return (
|
|
62
|
+
<div>
|
|
63
|
+
<h1>Mi Aplicación</h1>
|
|
64
|
+
<Chat botName="Asistente Virtual" />
|
|
65
|
+
</div>
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
#### Avanzado con Personalización de Estilos
|
|
71
|
+
|
|
72
|
+
```tsx
|
|
73
|
+
import { Chat } from "../chat";
|
|
74
|
+
|
|
75
|
+
export default function HomePage() {
|
|
76
|
+
return (
|
|
77
|
+
<div>
|
|
78
|
+
<h1>Mi Aplicación</h1>
|
|
79
|
+
<Chat
|
|
80
|
+
botName="Asistente Virtual"
|
|
81
|
+
logoUrl="logo.svg"
|
|
82
|
+
styleOptions={{
|
|
83
|
+
accent: getCssVariableAsHex("var(--primary)"),
|
|
84
|
+
backgroundColor: getCssVariableAsHex("var(--background)"),
|
|
85
|
+
//Respuestas del Bot
|
|
86
|
+
botAvatarBackgroundColor: getCssVariableAsHex("var(--background)"),
|
|
87
|
+
bubbleBackground: getCssVariableAsHex("var(--muted)"),
|
|
88
|
+
bubbleBorderRadius: 10,
|
|
89
|
+
//Mensajes del usuario
|
|
90
|
+
bubbleFromUserBackground: getCssVariableAsHex("var(--secondary)"),
|
|
91
|
+
bubbleFromUserBorderRadius: 10,
|
|
92
|
+
bubbleFromUserTextColor: getCssVariableAsHex("var(--background)"),
|
|
93
|
+
userAvatarBackgroundColor: getCssVariableAsHex("var(--primary)"),
|
|
94
|
+
//Caja de escritura
|
|
95
|
+
sendBoxHeight: 50,
|
|
96
|
+
sendBoxPlaceholderColor: getCssVariableAsHex("var(--muted)"),
|
|
97
|
+
sendBoxBackground: getCssVariableAsHex("var(--background)"),
|
|
98
|
+
sendBoxBorderTop: `solid 1px ${getCssVariableAsHex("var(--border)")}`,
|
|
99
|
+
sendBoxButtonColor: getCssVariableAsHex("var(--primary)"),
|
|
100
|
+
}}
|
|
101
|
+
/>
|
|
102
|
+
</div>
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Server Actions
|
|
108
|
+
|
|
109
|
+
### `getRegionalSettings()`
|
|
110
|
+
|
|
111
|
+
**Propósito**: Obtiene la configuración regional del bot, incluyendo las URLs de los canales disponibles.
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
const data = await getRegionalSettings();
|
|
115
|
+
console.log(data.channelUrlsById.directline); // URL de DirectLine
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
**Retorna**: Configuración regional con URLs de canales disponibles.
|
|
119
|
+
|
|
120
|
+
### `getConversationToken()`
|
|
121
|
+
|
|
122
|
+
**Propósito**: Obtiene el token de autenticación necesario para establecer la conexión con DirectLine.
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
const token = await getConversationToken();
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
**Retorna**: Token de conversación válido para DirectLine.
|
|
129
|
+
|
|
130
|
+
### `getChatStoreConfig()`
|
|
131
|
+
|
|
132
|
+
**Propósito**: Obtiene la configuración del store de Web Chat, incluyendo eventos iniciales y filtros.
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
const config = await getChatStoreConfig();
|
|
136
|
+
// config.eventConfig.startConversation - Evento para iniciar conversación
|
|
137
|
+
// config.filterConfig - Configuración de filtros
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
**Retorna**: Configuración del store con estado inicial y eventos.
|
|
141
|
+
|
|
142
|
+
### `logChatError(input)`
|
|
143
|
+
|
|
144
|
+
**Propósito**: Registra errores del chat en el servidor para monitoreo y debugging.
|
|
145
|
+
|
|
146
|
+
```typescript
|
|
147
|
+
await logChatError({
|
|
148
|
+
errorType: "connection_failed",
|
|
149
|
+
errorMessage: "No se pudo conectar al bot",
|
|
150
|
+
actionType: "initialize_chat",
|
|
151
|
+
userId: "optional-user-id",
|
|
152
|
+
});
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
**Parámetros**:
|
|
156
|
+
|
|
157
|
+
- `errorType`: Tipo de error (string)
|
|
158
|
+
- `errorMessage`: Mensaje descriptivo del error
|
|
159
|
+
- `actionType`: Acción que causó el error (opcional)
|
|
160
|
+
- `userId`: ID del usuario (opcional)
|
|
161
|
+
|
|
162
|
+
## Hook useChat
|
|
163
|
+
|
|
164
|
+
### Funciones y Estado
|
|
165
|
+
|
|
166
|
+
#### Estado del Chat
|
|
167
|
+
|
|
168
|
+
### Props del Hook
|
|
169
|
+
|
|
170
|
+
| Prop | Tipo | Default | Descripción |
|
|
171
|
+
| -------------- | -------------- | ----------- | --------------------------------------------------------- |
|
|
172
|
+
| `styleOptions` | `StyleOptions` | `undefined` | Opciones de estilo personalizadas para el chat (opcional) |
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
const {
|
|
176
|
+
isVisible, // boolean - Chat visible/oculto
|
|
177
|
+
isRestarting, // boolean - Estado de reinicio
|
|
178
|
+
chatKey, // number - Key para forzar re-render
|
|
179
|
+
webChatRef, // RefObject - Referencia al DOM del chat
|
|
180
|
+
styleOptions, // StyleOptions - Configuración de estilos
|
|
181
|
+
// ... funciones
|
|
182
|
+
} = useChat();
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
#### Funciones Principales
|
|
186
|
+
|
|
187
|
+
##### `handleChangeVisibility(visible: boolean)`
|
|
188
|
+
|
|
189
|
+
Controla la visibilidad del chat.
|
|
190
|
+
|
|
191
|
+
```typescript
|
|
192
|
+
handleChangeVisibility(true); // Mostrar chat
|
|
193
|
+
handleChangeVisibility(false); // Ocultar chat
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
##### `initializeChat()`
|
|
197
|
+
|
|
198
|
+
Inicializa el chat embebido obteniendo tokens y configuración.
|
|
199
|
+
|
|
200
|
+
- Obtiene configuración regional
|
|
201
|
+
- Solicita token de conversación
|
|
202
|
+
- Crea la instancia de DirectLine
|
|
203
|
+
- Renderiza Web Chat con estilos personalizados
|
|
204
|
+
|
|
205
|
+
##### `restartConversation()`
|
|
206
|
+
|
|
207
|
+
Reinicia completamente la conversación utilizando el patrón React key.
|
|
208
|
+
|
|
209
|
+
- Limpia referencias actuales
|
|
210
|
+
- Regenera el chatKey para forzar remount
|
|
211
|
+
- Reinicializa la conexión
|
|
212
|
+
|
|
213
|
+
##### `cleanup()`
|
|
214
|
+
|
|
215
|
+
Limpia la instancia del chat de forma segura.
|
|
216
|
+
|
|
217
|
+
## Configuración de StyleOptions
|
|
218
|
+
|
|
219
|
+
### Opciones de Color y Tema
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
interface StyleOptions {
|
|
223
|
+
// Colores principales
|
|
224
|
+
accent: string; // Color principal (#0078D4)
|
|
225
|
+
backgroundColor: string; // Fondo del chat (#e8e9eb)
|
|
226
|
+
|
|
227
|
+
// Configuración de burbujas del bot
|
|
228
|
+
bubbleBackground: string; // Fondo de mensajes del bot
|
|
229
|
+
bubbleBorderRadius: number; // Radio de borde de burbujas
|
|
230
|
+
bubbleTextColor: string; // Color del texto del bot
|
|
231
|
+
|
|
232
|
+
// Configuración de burbujas del usuario
|
|
233
|
+
bubbleFromUserBackground: string; // Fondo de mensajes del usuario
|
|
234
|
+
bubbleFromUserBorderRadius: number; // Radio de borde del usuario
|
|
235
|
+
bubbleFromUserTextColor: string; // Color del texto del usuario
|
|
236
|
+
|
|
237
|
+
// Configuración de avatares
|
|
238
|
+
botAvatarImage: string; // URL del avatar del bot
|
|
239
|
+
botAvatarInitials: string; // Iniciales del bot
|
|
240
|
+
userAvatarImage: string; // URL del avatar del usuario
|
|
241
|
+
userAvatarInitials: string; // Iniciales del usuario
|
|
242
|
+
userAvatarBackgroundColor: string; // Color de fondo del avatar
|
|
243
|
+
|
|
244
|
+
// Caja de entrada
|
|
245
|
+
sendBoxBackground: string; // Fondo de la caja de texto
|
|
246
|
+
sendBoxBorderTop: string; // Borde superior de la caja
|
|
247
|
+
sendBoxButtonColor: string; // Color del botón de enviar
|
|
248
|
+
sendBoxHeight: number; // Altura de la caja (50px)
|
|
249
|
+
|
|
250
|
+
// Animaciones
|
|
251
|
+
typingAnimationBackgroundImage: string; // GIF de animación de escritura
|
|
252
|
+
typingAnimationDuration: number; // Duración de la animación (ms)
|
|
253
|
+
typingAnimationHeight: number; // Altura de la animación
|
|
254
|
+
typingAnimationWidth: number; // Ancho de la animación
|
|
255
|
+
}
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
### Categorías de Configuración
|
|
259
|
+
|
|
260
|
+
#### **Diseño y Layout**
|
|
261
|
+
|
|
262
|
+
- `avatarSize`: Tamaño de avatares (31px)
|
|
263
|
+
- `bubbleMessageMaxWidth`: Ancho máximo de burbujas (480px)
|
|
264
|
+
- `paddingRegular`: Padding estándar (10px)
|
|
265
|
+
|
|
266
|
+
#### **Tipografía**
|
|
267
|
+
|
|
268
|
+
- `primaryFont`: Fuente principal del chat
|
|
269
|
+
- `monospaceFont`: Fuente para código (Consolas)
|
|
270
|
+
- `fontSizeSmall`: Tamaño de fuente pequeña (70%)
|
|
271
|
+
|
|
272
|
+
#### **Interactividad**
|
|
273
|
+
|
|
274
|
+
- `suggestedActionBackgroundColor`: Color de acciones sugeridas
|
|
275
|
+
- `suggestedActionLayout`: Layout de acciones ('flow', 'stacked', 'carousel')
|
|
276
|
+
- `hideUploadButton`: Ocultar botón de subir archivos
|
|
277
|
+
|
|
278
|
+
#### **Animaciones y Feedback**
|
|
279
|
+
|
|
280
|
+
- `spinnerAnimationHeight/Width`: Dimensiones del spinner (16px)
|
|
281
|
+
- `autoScrollSnapOnPage`: Auto-scroll en nuevos mensajes
|
|
282
|
+
|
|
283
|
+
## Tipos e Interfaces
|
|
284
|
+
|
|
285
|
+
### `StyleOptions`
|
|
286
|
+
|
|
287
|
+
Interface completa para la configuración de estilos del Web Chat.
|
|
288
|
+
|
|
289
|
+
### `WebChatAction`
|
|
290
|
+
|
|
291
|
+
Define las acciones disponibles para el store de Web Chat:
|
|
292
|
+
|
|
293
|
+
- `DIRECT_LINE/CONNECT_FULFILLED`: Conexión establecida
|
|
294
|
+
- `DIRECT_LINE/POST_ACTIVITY`: Enviar actividad/mensaje
|
|
295
|
+
- `DIRECT_LINE/INCOMING_ACTIVITY`: Recibir actividad/mensaje
|
|
296
|
+
|
|
297
|
+
### `WebChatStore`
|
|
298
|
+
|
|
299
|
+
Interface para el store personalizado con middleware para manejo de eventos y filtros.
|
|
300
|
+
|
|
301
|
+
### `WebChatLib`
|
|
302
|
+
|
|
303
|
+
Interface para la biblioteca global de Web Chat con métodos de creación y renderizado.
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
## Notas de Implementación
|
|
308
|
+
|
|
309
|
+
1. **Seguridad**: El componente incluye validación de tokens y manejo de errores robusto
|
|
310
|
+
2. **Performance**: Utiliza el patrón React key para reinicializaciones eficientes
|
|
311
|
+
3. **Accesibilidad**: Incluye labels ARIA y soporte para navegación por teclado
|
|
312
|
+
4. **Responsive**: Diseño adaptable para diferentes dispositivos
|
|
313
|
+
5. **Temas**: Integración completa con el sistema de temas de la aplicación
|
|
314
|
+
|
|
315
|
+
## Troubleshooting
|
|
316
|
+
|
|
317
|
+
### Problemas Comunes
|
|
318
|
+
|
|
319
|
+
1. **Chat no se inicializa**: Verificar `TOKEN_AGENTE_URL` en `.env`
|
|
320
|
+
2. **Estilos no se aplican**: Verificar variables CSS disponibles
|
|
321
|
+
3. **Errores de conexión**: Revisar configuración de CORS y headers de seguridad
|
|
322
|
+
4. **Imágenes no cargan**: Verificar rutas en carpeta `public/`
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
|
+
import { StyleOptions } from '@agentcrafta/core';
|
|
3
|
+
|
|
4
|
+
type ChatProps = {
|
|
5
|
+
show?: boolean;
|
|
6
|
+
botName?: string;
|
|
7
|
+
logoUrl?: string;
|
|
8
|
+
styleOptions?: Partial<StyleOptions>;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* @description Componente de servidor para el chat. Este componente se encarga de manejar la lógica del servidor y la comunicación con el cliente.
|
|
12
|
+
* @param botName Nombre del bot a mostrar en el encabezado del chat
|
|
13
|
+
* @param logoUrl URL del logo a mostrar junto al nombre del bot (opcional)
|
|
14
|
+
* @param show Indica si el chat debe mostrarse o no (por defecto es true)
|
|
15
|
+
* @param styleOptions: StyleOptions Opciones de estilo personalizadas para el chat (opcional)
|
|
16
|
+
* @returns
|
|
17
|
+
*/
|
|
18
|
+
declare function ChatServer(props: ChatProps): react_jsx_runtime.JSX.Element;
|
|
19
|
+
|
|
20
|
+
export { ChatServer as C };
|