6.0.0 • Published 4 months ago

aspirechat v6.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

AspireChat

A highly customizable React chatbot component with extensive configuration options for modern web applications.

npm version license

Features

  • 🎨 Highly Customizable: Customize every aspect of the chatbot UI through extensive theme options
  • 🔌 Plug and Play: Easy to integrate with any React application
  • 📱 Responsive: Works seamlessly across devices and screen sizes
  • 🔗 API Integration: Connect to any backend API for dynamic responses
  • 🧩 Plugin System: Extend functionality through custom plugins
  • 🌓 Dark Mode Support: Built-in dark theme and custom theme options
  • 📊 Button-Based Flows: Guide users through conversations with predefined buttons
  • 💬 Typing Indicators: Natural typing indicators for a more engaging experience
  • 🔄 Persistent Chat: Option to persist chat history between sessions

Installation

npm install aspirechat
# or
yarn add aspirechat

Quick Start

Button-Based Flows

import React from "react";
import { Chatbot } from "aspirechat";
import { ChatContextProvider } from "aspirechat";

const App = () => {
  // Define your chat flows
  const chatFlows = {
    welcome: {
      id: "welcome",
      messages: [
        {
          text: "Welcome to our support chatbot! How can I help you today?",
          type: "bot",
        },
      ],
      options: [
        {
          id: "1",
          text: "Product Information",
          value: "",
          nextFlow: "products",
        },
        {
          id: "2",
          text: "Pricing Plans",
          value: "",
          nextFlow: "pricing",
        },
        {
          id: "3",
          text: "Contact Support",
          value: "",
          nextFlow: "contact",
        },
      ],
    },
    products: {
      id: "products",
      messages: [
        {
          text: "We offer the following products:",
          type: "bot",
        },
        {
          text: "<ul><li>Product A - Analytics Suite</li><li>Product B - CRM Solution</li><li>Product C - Marketing Automation</li></ul>",
          type: "bot",
          html: true,
        },
      ],
      options: [
        {
          id: "1",
          text: "Tell me about Product A",
          value: "",
          nextFlow: "productA",
        },
        {
          id: "2",
          text: "Tell me about Product B",
          value: "",
          nextFlow: "productB",
        },
        { id: "3", text: "Back to menu", value: "", nextFlow: "welcome" },
      ],
    },
    pricing: {
      id: "pricing",
      messages: [
        {
          text: "Our pricing starts at $49/month for the basic plan.",
          type: "bot",
        },
      ],
      options: [
        {
          id: "1",
          text: "See pricing details",
          value: "Here's our detailed pricing structure...",
          nextFlow: null,
        },
        { id: "2", text: "Back to menu", value: "", nextFlow: "welcome" },
      ],
    },
    contact: {
      id: "contact",
      messages: [
        {
          text: "You can reach our support team at support@example.com or by phone at 555-123-4567.",
          type: "bot",
        },
      ],
      options: [
        {
          id: "1",
          text: "Email Support",
          value: "I'll open your email client to contact support.",
          nextFlow: null,
        },
        {
          id: "2",
          text: "Call Support",
          value: "Connecting you with our support team...",
          nextFlow: null,
        },
        { id: "3", text: "Back to menu", value: "", nextFlow: "welcome" },
      ],
    },
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>My Website</h1>
      </header>

      <ChatContextProvider
        initialConfig={{
          headerTitle: "Support Bot",
          initiallyOpen: true,
        }}
        initialOptions={{
          flows: chatFlows,
          initialFlow: "welcome",
        }}
      >
        <Chatbot />
      </ChatContextProvider>
    </div>
  );
};

export default App;

Advanced Configuration

AspireChat is designed to be highly customizable. Below are some examples of more advanced configurations.

Connecting to an API endpoint

import { Chatbot } from "aspirechat";

const App = () => {
  const api = {
    endpoint: "https://api.example.com/chat",
    headers: {
      Authorization: "Bearer YOUR_API_KEY",
    },
    transformRequest: (message) => ({
      query: message.text,
      userId: "user-123",
    }),
    transformResponse: (data) => ({
      text: data.response,
      type: "bot",
    }),
  };

  return <Chatbot api={api} />;
};

Custom Theme

import { Chatbot, darkTheme } from "aspirechat";

const App = () => {
  // Start with the built-in dark theme and customize it
  const customTheme = {
    ...darkTheme,
    primary: "#6d28d9", // purple-700
    secondary: "#8b5cf6", // purple-500
    userBubbleBackground: "#6d28d9", // purple-700
    userBubbleText: "#ffffff",
    botBubbleBackground: "#4c1d95", // purple-900
    botBubbleText: "#ffffff",
    fontFamily: "'Poppins', sans-serif",
  };

  return (
    <Chatbot
      config={{
        theme: customTheme,
        headerTitle: "Custom Support Bot",
      }}
    />
  );
};

Customizing Chat Position

import { Chatbot } from "aspirechat";

const App = () => {
  return (
    <Chatbot
      config={{
        position: {
          placement: "bottom-left", // "top-left", "top-right", "bottom-left", "bottom-right"
          offsetX: "30px",
          offsetY: "30px",
        },
        width: "400px",
        maxHeight: "700px",
      }}
    />
  );
};

Persistent Chat History

import { Chatbot } from "aspirechat";

const App = () => {
  return (
    <Chatbot
      config={{
        persistHistory: true,
        persistKey: "my-app-chat-history",
      }}
    />
  );
};

Mobile Configuration

import { Chatbot } from "aspirechat";

const App = () => {
  return (
    <Chatbot
      config={{
        mobile: {
          fullScreen: true, // Full screen on mobile
          bottomOffset: "60px", // Space for bottom navigation bar
        },
        fullScreenBreakpoint: "768px", // Switch to full screen below this width
      }}
    />
  );
};

Using with Next.js

AspireChat is compatible with Next.js, but requires proper client component setup:

"use client"; // This directive is important!

import React from "react";
import { Chatbot, ChatContextProvider } from "aspirechat";

export default function ChatWidget() {
  return (
    <ChatContextProvider
      initialConfig={{
        headerTitle: "Support Bot",
        initiallyOpen: true,
      }}
      initialOptions={{
        flows: {
          welcome: {
            id: "welcome",
            messages: [
              {
                text: "Welcome! How can I help you?",
                type: "bot",
              },
            ],
            options: [
              {
                id: "1",
                text: "Learn More",
                value: "Here's some information...",
                nextFlow: null,
              },
            ],
          },
        },
        initialFlow: "welcome",
      }}
    >
      <Chatbot />
    </ChatContextProvider>
  );
}

Important: Make sure to only use AspireChat components in client components (marked with 'use client').

API Reference

<Chatbot> Props

PropTypeDescription
configobjectConfiguration options for the chatbot
handlersobjectEvent handlers for various chatbot actions
responsesarrayArray of predefined response patterns
apiobjectAPI configuration for connecting to a backend
pluginsarrayCustom plugins to extend functionality
classNamestringAdditional CSS class names
disableDefaultStylesbooleanDisable default styled-components styles

Configuration Options

Basic Configuration

OptionTypeDefaultDescription
headerTitlestring"Chat Support"Title displayed in the header
welcomeMessagestring or objectundefinedInitial message sent by the bot
placeholderTextstring"Type a message..."Placeholder text for the input field
initiallyOpenbooleanfalseWhether the chat window should be open on initial render
showMinimizeButtonbooleantrueDisplay minimize button in the header
showCloseButtonbooleantrueDisplay close button in the header
logostringundefinedURL to the logo image displayed in the header

Appearance

OptionTypeDefaultDescription
themeobjectdefaultThemeTheme configuration object
positionobject{ placement: 'bottom-right' }Positioning of the chat window
widthstring"350px"Width of the chat window
heightstringundefinedHeight of the chat window
maxHeightstring"600px"Maximum height of the chat window
minHeightstring"300px"Minimum height of the chat window
roundedCornersbooleantrueUse rounded corners for the chat window
boxShadowbooleantrueApply box shadow to the chat window
floatingButtonobjectundefinedConfiguration for the floating toggle button

Behavior

OptionTypeDefaultDescription
enableTypingIndicatorbooleantrueShow typing indicator when the bot is "typing"
typingIndicatorTimeoutnumber1000Duration of the typing indicator in milliseconds
autoFocusbooleantrueAuto focus the input field when the chat opens
persistHistorybooleanfalsePersist chat history in localStorage
persistKeystringundefinedKey for localStorage when persisting chat history
showTimestampbooleantrueShow timestamps for messages
timestampFormatstring"HH:mm"Format for timestamps (HH:mm:ss)
enableAutoScrollbooleantrueAuto scroll to the latest message

Event Handlers

HandlerParametersDescription
onMessage(message: ChatMessage)Called when a message is added
onSendMessage(text: string)Called when a user sends a message
onOpennoneCalled when the chat window is opened
onClosenoneCalled when the chat window is closed
onMinimizenoneCalled when the chat window is minimized
onMaximizenoneCalled when the chat window is maximized
onFileUpload(file: File)Called when a file is uploaded
onError(error: Error)Called when an error occurs

Creating Custom Plugins

You can extend AspireChat's functionality with custom plugins:

import { Chatbot } from "aspirechat";

// Analytics plugin example
const analyticsPlugin = {
  id: "analytics",
  name: "Analytics Tracker",
  initialize: (chat) => {
    // Plugin initialization
    console.log("Analytics plugin initialized");
  },
  middleware: (message, next) => {
    // Track all messages
    if (message.type === "user") {
      console.log("User message tracked:", message.text);
      // You could send to analytics service here
    }
    // Continue processing
    next();
  },
  destroy: () => {
    console.log("Analytics plugin destroyed");
  },
};

const App = () => {
  return <Chatbot plugins={[analyticsPlugin]} />;
};

TypeScript Support

AspireChat is built with TypeScript and exports all types for excellent developer experience:

import { Chatbot, ChatConfig, ChatResponse, ChatAPI } from "aspirechat";

const config: ChatConfig = {
  headerTitle: "TypeScript Chat",
  welcomeMessage: "Welcome to our TypeScript-powered chat!",
};

const responses: ChatResponse[] = [
  {
    pattern: /hello/i,
    response: "Hi there!",
  },
];

const api: ChatAPI = {
  endpoint: "/api/chat",
};

const App = () => {
  return <Chatbot config={config} responses={responses} api={api} />;
};

License

MIT © AspireDev