JSPM

  • Created
  • Published
  • Downloads 189
  • Score
    100M100P100Q98234F
  • License MIT

Embeddable healthcare chatbot widget for websites and mobile apps

Package Exports

  • @mypatientspace/chatbot-widget
  • @mypatientspace/chatbot-widget/dist/mypatientspace-widget.es.js
  • @mypatientspace/chatbot-widget/dist/mypatientspace-widget.umd.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@mypatientspace/chatbot-widget) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

MPS Chatbot Widget

A standalone chatbot widget that third-party websites can embed via a single <script> tag.

npm version

Features

  • Self-contained React application bundled into a single JS file
  • Easy integration with any website
  • Floating button mode (default) or embedded mode
  • Customizable theming
  • Style isolation (won't conflict with host site CSS)
  • Native mobile support via WebView

Tech Stack

  • React 19 with TypeScript
  • Vite (library mode build)
  • Emotion (CSS-in-JS for style isolation)
  • lucide-react (icons)

Compatibility

Via CDN/Script Tag (Any Project)

When using the UMD bundle via <script> tag, the widget bundles its own React and renders in an isolated container. Your project's React version doesn't matter — this works with any framework (or no framework at all), including:

  • Vanilla JavaScript/HTML
  • jQuery
  • Angular, Vue, Svelte
  • Older React versions (14, 15, 16, etc.)

Via npm Import (React 18+ Required)

When importing as an ES module in a React project:

import '@mypatientspace/chatbot-widget';

You need React 18 or higher. The widget uses modern React features (hooks, Context API) that aren't available in older versions.

Integration Method React Version Required
CDN / Script tag Any (bundles own React)
npm import React 18+

Installation

unpkg:

<script src="https://unpkg.com/@mypatientspace/chatbot-widget@latest/dist/mypatientspace-widget.umd.js"></script>

jsDelivr:

<script src="https://cdn.jsdelivr.net/npm/@mypatientspace/chatbot-widget@latest/dist/mypatientspace-widget.umd.js"></script>

Via npm

npm install @mypatientspace/chatbot-widget

Development

# Install dependencies
yarn install

# Start dev server (includes demo UI)
yarn dev

# Build for production
yarn build              # Builds both widget and demo
yarn build:widget       # Widget only
yarn build:demo         # Demo only

# Preview production build
yarn preview

Demo Widget

An embeddable demo page with configuration panel and live preview. Useful for testing and showcasing the widget.

Via CDN

<div id="chatbot-demo" style="height: 600px;"></div>
<script src="https://unpkg.com/@mypatientspace/chatbot-widget@latest/dist/mypatientspace-demo.umd.js"></script>
<script>
  ChatbotWidgetDemo.init({
    containerSelector: '#chatbot-demo',
    showJsonEditor: true,
    initialConfig: {
      headerTitle: 'My Healthcare Bot',
      theme: { colors: { primary: '#007bff' } }
    },
    onConfigChange: (config) => console.log('Config:', config)
  });
</script>

Demo API

ChatbotWidgetDemo.init(config);    // Initialize demo
ChatbotWidgetDemo.destroy();       // Remove demo
ChatbotWidgetDemo.update(config);  // Update configuration

Demo Configuration

Option Type Default Description
containerSelector string Required CSS selector for container
showConfigPanel boolean true Show left config panel
showPreviewPanel boolean true Show right preview panel
showJsonEditor boolean true Show Form/JSON toggle
showDisplaySettings boolean true Show display settings section
showSessionSettings boolean true Show session settings section
showAppearanceSettings boolean true Show appearance section
showThemeSettings boolean true Show theme colors section
showContentSettings boolean true Show content settings section
showQuickActions boolean true Show quick actions section
initialConfig Partial<WidgetConfig> {} Pre-fill widget config
onConfigChange (config) => void - Called when config changes

Web Integration

Minimal Setup

<script src="https://unpkg.com/@mypatientspace/chatbot-widget@latest/dist/mypatientspace-widget.umd.js"></script>
<script>
  ChatbotWidget.init({
    apiEndpoint: 'https://your-api.com/chat',
    token: 'your-auth-token'
  });
</script>

Full Customization

<script src="https://unpkg.com/@mypatientspace/chatbot-widget@latest/dist/mypatientspace-widget.umd.js"></script>
<script>
  ChatbotWidget.init({
    apiEndpoint: 'https://your-api.com/chat',
    token: 'your-auth-token',
    headerTitle: 'Health Support',
    greeting: 'Hi! How can I help?',
    brandingText: 'Powered by MyCompany',
    headerIcon: '/logo.png',
    fabIcon: '/avatar.png',
    placeholder: 'Ask me anything...',
    position: 'bottom-left',
    quickActions: ['I need help', 'Book appointment'],
    theme: {
      // All color properties are optional - only set what you want to change
      colors: {
        // Main colors
        primary: '#ff6600',        // FAB button, links, main accent
        primaryDark: '#cc5200',    // Hover states
        secondary: '#2d3748',      // Header background
        accent: '#4299e1',         // Secondary accent
        accentLight: '#bee3f8',    // Light accent

        // Status colors
        success: '#48bb78',        // Success states
        info: '#4299e1',           // Info states
        error: '#f56565',          // Error states

        // Background colors
        background: '#ffffff',     // Chat window background
        surface: '#f7fafc',        // Input/card backgrounds

        // Text colors
        text: '#2d3748',           // Primary text
        textLight: '#718096',      // Secondary text, timestamps

        // Message bubbles
        userBubble: '#ff6600',     // User message background
        userBubbleText: '#ffffff', // User message text
        botBubble: '#edf2f7',      // Bot message background
        botBubbleText: '#2d3748',  // Bot message text

        // Borders
        border: '#e2e8f0',         // Border color
        borderLight: '#edf2f7',    // Light border

        // Other
        white: '#ffffff',          // White color
        recording: '#f56565',      // Voice recording indicator
      },

      // Typography and shape
      fontFamily: 'Inter, system-ui, sans-serif',
      borderRadius: '8px',
      shadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
    }
  });
</script>

Via npm import

import '@mypatientspace/chatbot-widget';

ChatbotWidget.init({
  apiEndpoint: 'https://your-api.com/chat'
});

API Methods

ChatbotWidget.open();    // Open chat window
ChatbotWidget.close();   // Close chat window
ChatbotWidget.toggle();  // Toggle open/close
ChatbotWidget.destroy(); // Remove widget completely

Embedded Mode

By default, the widget displays as a floating button that opens a popup. You can also embed the chat directly inside any container on your page.

Using containerSelector

Embed the chat inside an existing element:

<div id="my-chat" style="width: 400px; height: 600px;"></div>

<script src="https://unpkg.com/@mypatientspace/chatbot-widget@latest/dist/mypatientspace-widget.umd.js"></script>
<script>
  ChatbotWidget.init({
    apiEndpoint: 'https://your-api.com/chat',
    containerSelector: '#my-chat'
  });
</script>

Using floatingMode

Enable floating mode with FAB button (classic chatbot style):

<script>
  ChatbotWidget.init({
    apiEndpoint: 'https://your-api.com/chat',
    floatingMode: true
  });
</script>

Comparison

Feature Embedded (default) floatingMode: true
FAB button Hidden Shown
Chat visibility Always open Opens on click
Position Fills container Fixed bottom-right/left
Sizing 100% of parent 380x520px

Mobile Integration

Android (Kotlin)

class ChatActivity : AppCompatActivity() {
    private lateinit var webView: WebView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        webView = WebView(this).apply {
            settings.javaScriptEnabled = true
            settings.domStorageEnabled = true
            loadDataWithBaseURL(
                "https://your-domain.com",
                """
                <!DOCTYPE html>
                <html>
                <head>
                    <meta name="viewport" content="width=device-width, initial-scale=1">
                </head>
                <body style="margin:0;padding:0;">
                    <script src="https://unpkg.com/@mypatientspace/chatbot-widget@latest/dist/mypatientspace-widget.umd.js"></script>
                    <script>
                        ChatbotWidget.init({
                            apiEndpoint: 'https://your-api.com/chat'
                        });
                        ChatbotWidget.open();
                    </script>
                </body>
                </html>
                """.trimIndent(),
                "text/html", "UTF-8", null
            )
        }
        setContentView(webView)
    }
}

iOS (Swift)

import UIKit
import WebKit

class ChatViewController: UIViewController {
    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let config = WKWebViewConfiguration()
        config.preferences.javaScriptEnabled = true

        webView = WKWebView(frame: view.bounds, configuration: config)
        webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(webView)

        let html = """
        <!DOCTYPE html>
        <html>
        <head>
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
            <style>body { margin: 0; padding: 0; }</style>
        </head>
        <body>
            <script src="https://unpkg.com/@mypatientspace/chatbot-widget@latest/dist/mypatientspace-widget.umd.js"></script>
            <script>
                ChatbotWidget.init({
                    apiEndpoint: 'https://your-api.com/chat'
                });
                ChatbotWidget.open();
            </script>
        </body>
        </html>
        """

        webView.loadHTMLString(html, baseURL: URL(string: "https://your-domain.com"))
    }
}

React Native

import { WebView } from 'react-native-webview';

const ChatScreen = () => {
  const html = `
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body style="margin:0;padding:0;">
        <script src="https://unpkg.com/@mypatientspace/chatbot-widget@latest/dist/mypatientspace-widget.umd.js"></script>
        <script>
            ChatbotWidget.init({
                apiEndpoint: 'https://your-api.com/chat'
            });
            ChatbotWidget.open();
        </script>
    </body>
    </html>
  `;

  return (
    <WebView
      source={{ html }}
      javaScriptEnabled={true}
      domStorageEnabled={true}
    />
  );
};

Configuration Reference

All Options

Option Type Required Description
apiEndpoint string No Chat API endpoint URL (widget offline if not set)
token string No Auth token for API requests
sessionId string No Existing session ID to resume
assistantId string No Specific assistant ID to use
contextPatientId string No Patient context for the chat
loadHistory boolean No Load previous chat history (default: true)
theme ThemeConfig No Custom theme (see Theme Configuration below)
position 'bottom-right' | 'bottom-left' No FAB button position
containerSelector string No CSS selector for embedded container
floatingMode boolean No Show FAB button and floating chat (default: false)
greeting string No Initial bot greeting message
placeholder string No Input field placeholder text
headerTitle string No Chat window header title
headerSubtitle string No Chat window header subtitle
headerIcon string No Header icon image URL
fabIcon string No FAB button image URL
brandingText string No Footer branding text
quickActions string[] No Predefined quick action buttons (displayed as labels and sent as messages)

Callbacks

Callback Parameters Description
onOpen () Called when chat window opens
onClose () Called when chat window closes
onMessageSent (message: Message) Called after user sends a message
onMessageReceived (message: Message) Called after bot response completes
onQuickAction (action: string) Called when quick action is clicked
onStreamChunk (chunk: string) Called for each streamed response chunk

Message Interface

interface Message {
  id: string;
  content: string;
  sender: 'user' | 'bot';
  timestamp: Date;
  status: 'sending' | 'sent' | 'error';
  audioUrl?: string;  // Base64 audio data URL for TTS playback
}

ThemeConfig Interface

interface ThemeConfig {
  colors?: Partial<ThemeColors>;  // Any subset of theme colors
  fontFamily?: string;
  borderRadius?: string;
  shadow?: string;
}

Available Theme Colors

Color Default Description
primary #00c2d1 FAB button, links, main accent
primaryDark #017992 Hover states
secondary #3c4d73 Header background
accent #33b1e6 Secondary accent color
accentLight #b8ebff Light accent
success #00dec4 Success states
info #30d7ed Info states
background #ffffff Chat window background
surface #fdfefe Input/card backgrounds
text #3c4d73 Primary text
textLight #6b7280 Secondary text, timestamps
userBubble #00c2d1 User message background
userBubbleText #ffffff User message text
botBubble #e0f7fa Bot message background
botBubbleText #3c4d73 Bot message text
border #d1d5db Border color
borderLight #e5e7eb Light border
error #ef4444 Error states
white #ffffff White color
recording #ef4444 Voice recording indicator

Default Values

Option Default Value
headerTitle "AI Doctor"
greeting "Hello! Welcome to our healthcare support. How can I assist you today?"
placeholder "Type a message..."
brandingText "Developed by myPatientSpace"
headerIcon https://web.mypatientspace.com/img/logo-symbol.png
fabIcon https://web.mypatientspace.com/img/logo-symbol.png
position "bottom-right"
loadHistory true
containerSelector undefined (creates container in body)
floatingMode false (embedded is default)
quickActions Book Appointment, Hours, Contact, Location

License

MIT