pulsewidget
v1.0.1
Published
A beautiful, customizable chatbot widget for React applications with full TypeScript support and smooth animations
Maintainers
Readme
PulseWidget 💓
A beautiful, customizable AI chatbot widget for React applications with full TypeScript support.
Características
- ✅ Totalmente personalizável (cores, textos, avatares)
- ✅ Suporte a Markdown nas respostas
- ✅ Animações suaves com Framer Motion
- ✅ TypeScript completo
- ✅ Responsivo e mobile-friendly
- ✅ Sugestões de mensagens iniciais
- ✅ Modo expandido opcional
- ✅ Callbacks para eventos
- ✅ API flexível e configurável
Instalação
npm install pulsewidget
# or
yarn add pulsewidget
# or
pnpm add pulsewidgetUso Básico
import { ChatbotWidget } from 'pulsewidget'
import 'pulsewidget/styles.css'
function App() {
return (
<ChatbotWidget
config={{
apiEndpoint: '/api/chat',
}}
/>
)
}Exemplo Completo
import { ChatbotWidget } from 'pulsewidget'
import 'pulsewidget/styles.css'
function App() {
return (
<ChatbotWidget
config={{
apiEndpoint: '/api/chat',
apiHeaders: {
'Authorization': 'Bearer seu-token',
},
// Personalizar formato da requisição
formatRequest: (messages) => ({
historico: messages.map(msg => ({
role: msg.role === 'assistant' ? 'ai' : 'user',
content: msg.content,
})),
}),
// Personalizar extração da resposta
formatResponse: (data) => data.result,
}}
botName="AI Assistant"
botAvatar="/bot-avatar.png"
toggleButtonImage="/chat-button.png"
theme={{
primaryColor: '#DF1463',
backgroundColor: '#252525',
userMessageBg: '#252525',
assistantMessageBg: '#ffffff',
}}
suggestions={[
'Como vocês funcionam?',
'Preciso de ajuda',
'Quais serviços vocês oferecem?',
]}
placeholder="Digite sua mensagem..."
welcomeMessage="Como posso ajudá-lo?"
welcomeSubtitle="Sou sua assistente virtual!"
allowExpand={true}
defaultOpen={false}
onToggle={(isOpen) => {
console.log('Chat toggled:', isOpen)
}}
onMessageSent={(message) => {
console.log('Message sent:', message)
}}
onResponseReceived={(message) => {
console.log('Response received:', message)
}}
/>
)
}Props
config (obrigatório)
Objeto de configuração da API:
| Propriedade | Tipo | Descrição |
|------------|------|-----------|
| apiEndpoint | string | URL do endpoint da API de chat |
| apiHeaders | Record<string, string> | Headers customizados para a requisição |
| formatRequest | (messages) => any | Função para formatar a requisição |
| formatResponse | (response) => string | Função para extrair a resposta da API |
Propriedades Opcionais
| Propriedade | Tipo | Padrão | Descrição |
|------------|------|--------|-----------|
| botName | string | "AI Assistant" | Nome do bot exibido no header |
| botAvatar | string | - | URL da imagem do avatar do bot |
| toggleButtonImage | string | - | URL da imagem do botão de toggle |
| theme | ChatbotTheme | - | Objeto de customização de cores |
| suggestions | string[] | [] | Sugestões iniciais de mensagens |
| placeholder | string | "Digite sua mensagem..." | Placeholder do input |
| welcomeMessage | string | "Como posso ajudá-lo?" | Mensagem de boas-vindas |
| welcomeSubtitle | string | "Sou sua assistente virtual..." | Subtítulo de boas-vindas |
| className | string | "" | Classe CSS customizada |
| allowExpand | boolean | true | Habilitar modo expandido |
| defaultOpen | boolean | false | Estado inicial do chat |
| onToggle | (isOpen) => void | - | Callback ao abrir/fechar |
| onMessageSent | (message) => void | - | Callback ao enviar mensagem |
| onResponseReceived | (message) => void | - | Callback ao receber resposta |
ChatbotTheme
interface ChatbotTheme {
primaryColor?: string // Cor principal (botões, links)
backgroundColor?: string // Cor de fundo
userMessageBg?: string // Cor de fundo mensagem do usuário
assistantMessageBg?: string // Cor de fundo mensagem do bot
borderColor?: string // Cor das bordas
textColor?: string // Cor do texto
}Formato da API
Requisição Padrão
{
"messages": [
{
"role": "user",
"content": "Olá!"
},
{
"role": "assistant",
"content": "Olá! Como posso ajudar?"
}
]
}Resposta Esperada
{
"result": "Resposta do bot aqui",
// ou
"message": "Resposta do bot aqui",
// ou
"content": "Resposta do bot aqui"
}Customizando Formato
Use formatRequest e formatResponse para adaptar ao seu backend:
<ChatbotWidget
config={{
apiEndpoint: '/api/chat',
formatRequest: (messages) => ({
// Seu formato customizado
conversation: messages,
userId: '123',
}),
formatResponse: (data) => {
// Extrair resposta do seu formato
return data.bot.message
},
}}
/>Exemplo de Backend (Next.js API Route)
// app/api/chat/route.ts
import { NextResponse } from 'next/server'
export async function POST(request: Request) {
const { messages } = await request.json()
// Aqui você faria a chamada para sua API de IA
// Por exemplo: OpenAI, Google AI, etc.
const response = await fetch('https://sua-api-ia.com/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages }),
})
const data = await response.json()
return NextResponse.json({ result: data.content })
}
## Hook `useChat`
O pacote também exporta o hook `useChat` para uso independente:
```tsx
import { useChat } from 'pulsewidget'
function CustomChat() {
const { messages, input, isLoading, handleInputChange, handleSubmit } = useChat({
apiEndpoint: '/api/chat',
})
return (
<div>
{messages.map(msg => (
<div key={msg.id}>{msg.content}</div>
))}
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={(e) => handleInputChange(e.target.value)}
/>
<button type="submit">Send</button>
</form>
</div>
)
}TypeScript
Todos os tipos são exportados:
import type {
Message,
ChatbotTheme,
ChatbotConfig,
ChatbotWidgetProps
} from 'pulsewidget'Licença
MIT
Suporte
Para reportar bugs ou solicitar features, abra uma issue no GitHub.
