1.0.8 β€’ Published 5 months ago

@developer.notchatbot/webchat v1.0.8

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

πŸ”· WebChat Widget

A beautiful, embeddable chatbot widget built with React, TypeScript, Vite, pnpm and Tailwind CSS that can be easily integrated into any website with just one file.

✨ Features

  • πŸ“¦ Single File Bundle: Everything in one file - no separate CSS needed!
  • πŸ”· TypeScript: Full type safety with strict typing and excellent IntelliSense
  • βš›οΈ React 18: Component-based architecture for maintainability
  • 🎨 Tailwind CSS: Utility-first styling with prefixed classes (ncb-)
  • ⚑ Vite: Lightning-fast development and optimized builds
  • πŸ“¦ pnpm: Efficient package management and faster installs
  • πŸ”§ Easy Integration: Add to any website with just one script tag
  • 🎨 Modern Design: Beautiful, responsive UI that works on all devices
  • πŸ› οΈ Customizable: Configure colors, text, and behavior to match your brand
  • ✨ Smooth Animations: Typing indicators and smooth transitions
  • πŸ“± Mobile Responsive: Optimized for mobile and desktop
  • πŸ”Œ API Ready: Built-in support for chat API integration
  • 🚫 Zero Conflicts: Prefixed CSS classes prevent style conflicts
  • πŸ›‘οΈ Type Safe: Catch errors at compile time with TypeScript

πŸ“¦ Quick Start

1. Add the widget to your website

<div id="webchat-component"></div>

<script src="https://your-cdn.com/webchat-bundle.min.umd.cjs"></script>
<script>
WebChat.initialize({
    title: "Customer Support",
    placeholder: "Ask us anything...",
    primaryColor: "#667eea"
});
</script>

2. That's it! πŸŽ‰

The chatbot button will appear in the bottom-right corner of your page. CSS is automatically injected!

βš™οΈ Configuration Options

interface WebChatConfig {
  title?: string;                       // Chat window title
  placeholder?: string;                 // Input placeholder text
  primaryColor?: string;                // Primary theme color
  apiKey?: string;                      // Your chatbot UID (required for API)
  position?: 'bottom-right' | 'bottom-left'; // Widget position
  initialMessage?: string;              // Custom initial bot message
  closeButtonIcon?: 'default' | 'text' | 'custom'; // Close button type
  closeButtonText?: string;             // Text for close button (when type is 'text')
  closeButtonCustomIcon?: string;       // Custom icon SVG or URL (when type is 'custom')
  marginBottom?: number;                // Distance from bottom edge in pixels (default: 16)
  marginSide?: number;                  // Distance from left/right edge in pixels (default: 16)
  mobile?: WebChatPositionConfig;       // Mobile-specific position settings
  desktop?: WebChatPositionConfig;      // Desktop-specific position settings
}

interface WebChatPositionConfig {
  position?: 'bottom-right' | 'bottom-left';
  marginBottom?: number;
  marginSide?: number;
}

WebChat.initialize({
    title: "Chat Assistant",
    placeholder: "Type your message...",
    primaryColor: "#007bff",
    apiKey: "your-chatbot-uid",        // Chatbot UID from admin panel
    position: "bottom-right",
    initialMessage: "Β‘Hola! πŸ‘‹ Soy tu asistente virtual. ΒΏEn quΓ© puedo ayudarte hoy?",
    closeButtonIcon: "default", // or "text" or "custom"
    marginBottom: 20,           // Distance from bottom edge (default: 16px)
    marginSide: 20,             // Distance from side edge (default: 16px)
    // Device-specific overrides
    mobile: {
        position: "bottom-left",
        marginBottom: 80,
        marginSide: 15
    },
    desktop: {
        position: "bottom-right", 
        marginBottom: 30,
        marginSide: 30
    }
});

🎨 Customization

Colors

WebChat.initialize({
    primaryColor: "#ff6b6b",  // Custom brand color
    // ... other options
});

API Integration

The WebChat widget automatically detects the environment and uses the appropriate API endpoints:

  • Development (localhost): http://localhost:3001/api/webchat
  • Production (any other domain): https://next.notchatbot.com/api/webchat
WebChat.initialize({
    apiKey: "your-chatbot-uid",    // Chatbot UID from your Next.js admin panel
    // Endpoints are automatically configured based on environment
    // No need to specify apiEndpoint manually
});

Manual Endpoint Override (Advanced)

If you need to override the automatic endpoint detection:

// This is handled automatically, but you can check the environment:
import { getChatEndpoint, getConversationEndpoint } from './src/config/endpoints';

console.log('Chat endpoint:', getChatEndpoint());
console.log('Conversation endpoint:', getConversationEndpoint());

πŸ’¬ Initial Message Customization

Customize the first message your users see when they open the chat:

WebChat.initialize({
    title: "MiTienda Support",
    // Custom welcome message with your brand's personality
    initialMessage: "Β‘Hola! πŸ‘‹ Soy el asistente de MiTienda.\n\nΒΏBuscas algΓΊn producto especΓ­fico? Β‘Estoy aquΓ­ para ayudarte!\n\nPuedes preguntarme sobre:\nβ€’ Productos disponibles\nβ€’ Precios y ofertas\nβ€’ EnvΓ­os y devoluciones\nβ€’ Soporte tΓ©cnico\n\nΒΏEn quΓ© puedo ayudarte hoy? 😊",
    apiKey: "your-api-key"
});

❌ Close Button Customization

Customize the appearance of the close button in the chat header:

Option 1: Default X Icon (SVG)

WebChat.initialize({
    closeButtonIcon: "default" // Standard X icon
});

Option 2: Custom Text

WebChat.initialize({
    closeButtonIcon: "text",
    closeButtonText: "CERRAR" // or "βœ•", "CLOSE", etc.
});

Option 3: Custom SVG Icon

WebChat.initialize({
    closeButtonIcon: "custom",
    closeButtonCustomIcon: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>'
});

Option 4: Custom Icon from URL

WebChat.initialize({
    closeButtonIcon: "custom",
    closeButtonCustomIcon: "https://yoursite.com/icons/close-icon.svg"
});

πŸ“ Position and Margins Customization

Control where the chat widget appears on the screen and how much space it has from the edges:

Bottom Right Position (Default)

WebChat.initialize({
    position: "bottom-right",
    marginBottom: 20,  // 20px from bottom edge
    marginSide: 25,    // 25px from right edge
    apiKey: "your-api-key"
});

Bottom Left Position

WebChat.initialize({
    position: "bottom-left",
    marginBottom: 30,  // 30px from bottom edge
    marginSide: 20,    // 20px from left edge
    apiKey: "your-api-key"
});

Position Examples for Different Layouts

E-commerce Site (avoid cart button)

WebChat.initialize({
    position: "bottom-left",
    marginBottom: 20,
    marginSide: 20,
    apiKey: "your-api-key"
});

Corporate Website (professional look)

WebChat.initialize({
    position: "bottom-right",
    marginBottom: 40,   // More space from bottom
    marginSide: 30,     // More space from side
    apiKey: "your-api-key"
});

Mobile-First Design (more accessible)

WebChat.initialize({
    position: "bottom-right",
    marginBottom: 80,   // Avoid mobile navigation
    marginSide: 15,     // Less space on mobile
    apiKey: "your-api-key"
});

πŸ’° Cost Optimization

The WebChat widget is optimized to minimize API costs:

  • Lazy Loading: Conversation history is only fetched when the chat is opened, not on page load
  • Smart Caching: Once loaded, conversation history is cached to avoid duplicate fetches
  • Conditional Fetching: Only fetches when a conversation actually exists

This ensures users can visit your e-commerce site without triggering unnecessary API calls.

πŸ“±πŸ’» Device-Specific Configurations

Configure different positions and margins for mobile and desktop devices:

Complete Device-Specific Setup

WebChat.initialize({
    title: "Customer Support",
    apiKey: "your-api-key",
    
    // Global fallback settings (used if device-specific not provided)
    position: "bottom-right",
    marginBottom: 20,
    marginSide: 20,
    
    // Desktop-specific settings
    desktop: {
        position: "bottom-right",
        marginBottom: 30,        // More space on desktop
        marginSide: 40           // More space from edge
    },
    
    // Mobile-specific settings  
    mobile: {
        position: "bottom-left", // Different position on mobile
        marginBottom: 80,        // Avoid mobile navigation bars
        marginSide: 15           // Less space on smaller screens
    }
});

E-commerce Site Example

WebChat.initialize({
    title: "Shopping Assistant",
    apiKey: "your-api-key",
    
    // Desktop: bottom-right (standard)
    desktop: {
        position: "bottom-right",
        marginBottom: 25,
        marginSide: 25
    },
    
    // Mobile: bottom-left (avoid cart/menu buttons)
    mobile: {
        position: "bottom-left",
        marginBottom: 90,        // Clear mobile navigation
        marginSide: 15
    }
});

Corporate Website Example

WebChat.initialize({
    title: "Business Support",
    apiKey: "your-api-key",
    
    // Consistent position, different margins
    position: "bottom-right",   // Global fallback
    
    desktop: {
        marginBottom: 40,        // Professional spacing
        marginSide: 50
    },
    
    mobile: {
        marginBottom: 70,        // Clear mobile UI elements  
        marginSide: 20
    }
});

πŸ‘¨β€πŸ’» Developer Guide

πŸš€ Getting Started

Prerequisites

  • Node.js 18+ (for modern React and TypeScript)
  • pnpm 8+ (recommended package manager - faster than npm/yarn)
  • Git (for version control)
  • VS Code (recommended IDE with TypeScript support)

Initial Setup

# 1. Clone the repository
git clone https://github.com/your-username/webchat-widget.git
cd webchat-widget

# 2. Install dependencies with pnpm (much faster than npm)
pnpm install

# 3. Start development server
pnpm dev

The development server will start at http://localhost:3000 and automatically open example.html.

πŸ”§ Development Workflow

1. Understanding the Codebase Structure

src/
β”œβ”€β”€ components/           # React TypeScript components
β”‚   β”œβ”€β”€ ChatBot.tsx      # Main container component
β”‚   β”œβ”€β”€ ChatButton.tsx   # Floating chat button
β”‚   β”œβ”€β”€ ChatWindow.tsx   # Chat window container
β”‚   β”œβ”€β”€ ChatHeader.tsx   # Window header with close button
β”‚   β”œβ”€β”€ MessageList.tsx  # Scrollable message list
β”‚   β”œβ”€β”€ Message.tsx      # Individual message bubble
β”‚   β”œβ”€β”€ MessageInput.tsx # Input field with send button
β”‚   └── TypingIndicator.tsx # Animated typing dots
β”œβ”€β”€ types.ts             # TypeScript interfaces and types
β”œβ”€β”€ index.tsx            # Main entry point (exports WebChat API)
β”œβ”€β”€ vite-env.d.ts        # Type declarations for Vite
└── styles.css           # Tailwind CSS directives

2. Adding New Features

Step 1: Update Types (if needed)

// src/types.ts
export interface NewFeatureProps {
  enabled: boolean;
  config?: SomeConfig;
}

Step 2: Create/Modify Components

// src/components/NewFeature.tsx
import React from 'react';
import type { NewFeatureProps } from '../types';

const NewFeature: React.FC<NewFeatureProps> = ({ enabled, config }) => {
  // Component logic here
  return (
    <div className="nbc-new-feature">
      {/* Use nbc- prefix for all CSS classes */}
    </div>
  );
};

export default NewFeature;

Step 3: Add to Main Component

// src/components/ChatBot.tsx
import NewFeature from './NewFeature';

// Use the new component in ChatBot

3. Styling Guidelines

  • Always use nbc- prefix for CSS classes to avoid conflicts
  • Use Tailwind utilities whenever possible
  • Follow the existing pattern for consistent styling
// βœ… Good - uses nbc- prefix
<div className="nbc-bg-blue-500 nbc-text-white nbc-p-4">

// ❌ Bad - no prefix, will conflict with host site
<div className="bg-blue-500 text-white p-4">

4. TypeScript Best Practices

  • Define interfaces for all component props
  • Use strict typing for functions and variables
  • Leverage IntelliSense for better development experience
// βœ… Good - strict typing
const handleMessage = (message: string): void => {
  // Function implementation
};

// ❌ Bad - no typing
const handleMessage = (message) => {
  // Function implementation
};

πŸ—οΈ Building & Compilation

Development Build

# Start development server with hot reload
pnpm dev

# Access at: http://localhost:3000
# Changes are reflected immediately

Production Build

# Build for production (TypeScript compilation + bundling)
pnpm build

# Output: dist/webchat-bundle.min.umd.cjs (single file)
# Size: ~159KB (50KB gzipped)

Build Process Explanation

  1. TypeScript Compilation (tsc) - Type checking and compilation
  2. Vite Bundling - Bundles React, CSS, and all dependencies
  3. CSS Injection - Inlines CSS into JavaScript for single-file output
  4. Minification - Optimizes and compresses the output

πŸ§ͺ Testing the Compiled Version

Option 1: Preview Server

# Build and start preview server
pnpm build
pnpm preview

# Access at: http://localhost:4173
# Tests the actual production build

Option 2: Local Testing

# After building, test locally
pnpm build

# Open example/production.html in browser
# Or serve with any static file server
python3 -m http.server 8000
# Then visit: http://localhost:8000/example/production.html

Option 3: Integration Testing

Create a test HTML file:

<!DOCTYPE html>
<html>
<head>
    <title>Widget Test</title>
</head>
<body>
    <h1>Testing WebChat Widget</h1>
    <div id="chat-test"></div>
    
    <!-- Load your built widget -->
    <script src="./dist/webchat-bundle.min.umd.cjs"></script>
    <script>
        // Test the widget
        WebChat.initialize({
            elementId: "chat-test",
            title: "Test Chat",
            placeholder: "Test message...",
            primaryColor: "#007bff"
        });
    </script>
</body>
</html>

πŸ“¦ Publishing to npm

1. Prepare for Publishing

# 1. Update version in package.json
npm version patch  # or minor, major

# 2. Build the production version
pnpm build

# 3. Test the build
pnpm preview

2. Configure package.json for npm

{
  "name": "@yourorg/webchat-widget",
  "version": "1.0.0",
  "description": "Embeddable React TypeScript chatbot widget",
  "main": "dist/webchat-bundle.min.umd.cjs",
  "types": "dist/types/index.d.ts",
  "files": [
    "dist",
    "README.md"
  ],
  "keywords": ["chatbot", "widget", "react", "typescript", "embeddable"],
  "repository": {
    "type": "git",
    "url": "https://github.com/yourorg/webchat-widget.git"
  },
  "publishConfig": {
    "access": "public"
  }
}

3. Publish to npm

# 1. Login to npm (if not already)
npm login

# 2. Publish the package
npm publish

# 3. Verify publication
npm view @yourorg/webchat-widget

4. Using Published Package

<!-- From npm CDN -->
<script src="https://unpkg.com/@yourorg/webchat-widget/dist/webchat-bundle.min.umd.cjs"></script>

<!-- Or install via npm -->
npm install @yourorg/webchat-widget

🌐 Hosting on unpkg

Automatic unpkg Hosting

Once published to npm, your package is automatically available on unpkg:

<!-- Latest version -->
<script src="https://unpkg.com/@yourorg/webchat-widget"></script>

<!-- Specific version -->
<script src="https://unpkg.com/@yourorg/webchat-widget@1.0.0"></script>

<!-- Direct file access -->
<script src="https://unpkg.com/@yourorg/webchat-widget/dist/webchat-bundle.min.umd.cjs"></script>

unpkg URLs Explained

  • https://unpkg.com/package-name - Latest version, main file
  • https://unpkg.com/package-name@version - Specific version
  • https://unpkg.com/package-name/file-path - Direct file access
  • https://unpkg.com/package-name@version/file-path - Version + file

Real-world Integration Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Website with Chat</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <p>Content goes here...</p>
    
    <!-- Chat widget integration -->
    <div id="customer-chat"></div>
    
    <!-- Load from unpkg -->
    <script src="https://unpkg.com/@yourorg/webchat-widget@latest"></script>
    <script>
        WebChat.initialize({
            elementId: "customer-chat",
            title: "Customer Support",
            placeholder: "How can we help you?",
            primaryColor: "#007bff",
            apiEndpoint: "https://your-api.com/chat",
            apiKey: "your-api-key"
        });
    </script>
</body>
</html>

πŸš€ Deployment Workflow Summary

# Complete workflow from development to deployment
git checkout -b feature/new-feature
# ... make changes ...
git commit -m "Add new feature"
git push origin feature/new-feature
# ... create PR, review, merge ...

# Deployment
git checkout main
git pull origin main
npm version patch
pnpm build
npm publish
git push --tags

# Your widget is now available at:
# https://unpkg.com/@yourorg/webchat-widget@latest

πŸ› οΈ Troubleshooting

Common Issues

TypeScript Errors

# Check TypeScript errors
pnpm build  # Will show TS errors

# Fix common issues:
# 1. Missing types - add to src/types.ts
# 2. Import errors - check file extensions (.tsx)
# 3. Strict mode - follow TypeScript strict rules

Build Issues

# Clear cache and rebuild
rm -rf node_modules dist
pnpm install
pnpm build

CSS Conflicts

// Always use nbc- prefix in className
className="nbc-bg-blue-500 nbc-text-white"

unpkg Caching

# Force cache refresh
https://unpkg.com/@yourorg/webchat-widget?t=timestamp

πŸ› οΈ Development

Prerequisites

  • Node.js 18+ (for modern React and TypeScript)
  • pnpm 8+ (recommended package manager)

Setup

# Clone the repository
git clone https://github.com/your-username/webchat-widget.git
cd webchat-widget

# Install dependencies with pnpm
pnpm install

# Start development server with hot reload
pnpm dev

Build for Production

pnpm build

This creates a single optimized file in the dist/ directory:

  • webchat-bundle.min.umd.cjs (159KB / 50KB gzipped) - Complete TypeScript bundle with React, Tailwind CSS, and all functionality

Preview Production Build

pnpm preview

πŸ“ Project Structure

webchat-widget/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ components/           # React TypeScript components
β”‚   β”‚   β”œβ”€β”€ ChatBot.tsx      # Main chatbot component
β”‚   β”‚   β”œβ”€β”€ ChatButton.tsx   # Toggle button
β”‚   β”‚   β”œβ”€β”€ ChatWindow.tsx   # Chat window container
β”‚   β”‚   β”œβ”€β”€ ChatHeader.tsx   # Window header
β”‚   β”‚   β”œβ”€β”€ MessageList.tsx  # Message list with scroll
β”‚   β”‚   β”œβ”€β”€ Message.tsx      # Individual message
β”‚   β”‚   β”œβ”€β”€ MessageInput.tsx # Input field
β”‚   β”‚   └── TypingIndicator.tsx # Typing animation
β”‚   β”œβ”€β”€ types.ts             # TypeScript interfaces and types
β”‚   β”œβ”€β”€ index.tsx            # Main entry point (auto-injects CSS)
β”‚   β”œβ”€β”€ vite-env.d.ts        # Vite environment types
β”‚   └── styles.css           # Tailwind directives
β”œβ”€β”€ example.html             # Development example
β”œβ”€β”€ example/
β”‚   └── production.html      # Production example
β”œβ”€β”€ dist/                    # Built files
β”‚   └── webchat-bundle.min.umd.cjs # Single file TypeScript bundle
β”œβ”€β”€ tsconfig.json            # TypeScript configuration
β”œβ”€β”€ tsconfig.node.json       # Node TypeScript configuration
β”œβ”€β”€ tailwind.config.js       # Tailwind configuration
β”œβ”€β”€ postcss.config.js        # PostCSS configuration
β”œβ”€β”€ vite.config.js           # Vite configuration
└── package.json             # pnpm + React + TypeScript dependencies

πŸ“„ License

MIT License - see the LICENSE file for details.

1.0.8

5 months ago

1.0.7

5 months ago

1.0.6

5 months ago

1.0.5

5 months ago

1.0.4

5 months ago

1.0.3

5 months ago

1.0.1

5 months ago

1.0.0

5 months ago