sapio-widget
v1.0.14
Published
Embeddable chat widget for Sapio Knowledge Assistant
Maintainers
Readme
Sapio Widget
A lightweight, embeddable chat widget for the Sapio Knowledge Assistant platform. Available as both a React component and vanilla JavaScript widget.
Features
- 🚀 Lightweight: < 50KB minified and gzipped
- ⚛️ React Ready: First-class React component support
- 🎨 Customizable: Colors, position, avatar, and messages
- 📱 Responsive: Works on desktop and mobile
- 🔒 Secure: reCAPTCHA integration and API key authentication
- ♿ Accessible: ARIA labels and keyboard navigation
- 🌙 Modern: Clean, modern design with smooth animations
- 📦 Multiple Formats: UMD, ESM, and React component exports
Installation
npm install sapio-widgetUsage
React Component
import React, { useRef } from "react";
import { SapioWidget } from "sapio-widget";
import type { SapioWidgetRef } from "sapio-widget";
function App() {
const widgetRef = useRef < SapioWidgetRef > null;
const handleError = (error: Error) => {
console.error("Widget error:", error);
};
const clearChat = () => {
widgetRef.current?.clearMessages();
};
return (
<div>
<SapioWidget
ref={widgetRef}
apiKey="your-api-key"
maxHeight={400}
onError={handleError}
/>
<button onClick={clearChat}>Clear Chat</button>
</div>
);
}Vanilla JavaScript (Browser)
<!-- Load Sapio Widget -->
<script src="https://unpkg.com/sapio-widget@latest/dist/sapio-widget.js"></script>
<script>
const widget = SapioWidget.init({
apiKey: "your-api-key",
maxHeight: 400,
});
</script>ES Modules (Modern JavaScript)
import { SapioWidgetAPI } from "sapio-widget";
const widget = SapioWidgetAPI.init({
apiKey: "your-api-key",
maxHeight: 400,
});CommonJS (Node.js)
const { SapioWidgetAPI } = require("sapio-widget");
const widget = SapioWidgetAPI.init({
apiKey: "your-api-key",
maxHeight: 400,
});Configuration
Basic Configuration
All configuration options work the same across React and vanilla JavaScript:
interface WidgetInitConfig {
apiKey: string; // Required: Your Sapio API key
apiUrl?: string; // Optional: API base URL (default: 'https://assistant.sapio.ro/api')
maxHeight?: number; // Optional: Max chat window height (default: 400)
zIndex?: number; // Optional: CSS z-index
}React Component Props
<SapioWidget
apiKey="your-api-key"
apiUrl="http://localhost:8000/api" // Optional: for local development
maxHeight={400}
zIndex={999999}
onError={(error) => console.error(error)}
/>Vanilla JavaScript
const widget = SapioWidgetAPI.init({
apiKey: "your-api-key",
apiUrl: "http://localhost:8000/api", // Optional: for local development
maxHeight: 400,
zIndex: 999999,
});Note: Style configuration (colors, position, persona name, welcome message, avatar) and reCAPTCHA settings are fetched automatically from your Sapio backend configuration and cannot be overridden at initialization.
Local Development
For local development, you can point the widget to your local backend:
// React
<SapioWidget apiKey="your-api-key" apiUrl="http://localhost:8000/api" />;
// Vanilla JS
SapioWidgetAPI.init({
apiKey: "your-api-key",
apiUrl: "http://localhost:8000/api",
});This allows you to test changes without redeploying your backend.
API Methods
React Component Ref
const widgetRef = useRef < SapioWidgetRef > null;
// Clear messages
widgetRef.current?.clearMessages();
// Update configuration
widgetRef.current?.updateConfig({
maxHeight: 500,
zIndex: 1000000,
});
// Destroy widget
widgetRef.current?.destroy();Vanilla JavaScript
// Initialize widget
const widget = SapioWidgetAPI.init(config);
// Clear messages
widget.clearMessages();
// Update configuration
widget.updateConfig({
maxHeight: 500,
zIndex: 1000000,
});
// Destroy widget
widget.destroy();Publishing and Distribution
NPM Publishing
The widget is distributed via NPM for easy installation and updates:
# Build the widget
npm run build
# Publish to NPM
npm publishThis creates optimized files in the dist/ directory:
sapio-widget.min.js/sapio-widget.esm.js- Widget bundlessapio-widget.min.css/sapio-widget.esm.css- Stylesindex.d.ts- TypeScript declarations- Source maps for debugging
Version Management
To update the widget:
# Update version
npm version patch # or minor, major
# Rebuild and publish
npm run build
npm publishInstallation for Clients
Clients can install the widget in their projects:
npm install sapio-widgetDevelopment
Project Structure
widget/
├── src/
│ ├── sapio-widget.ts # Main widget class
│ ├── react-wrapper.tsx # React component wrapper
│ ├── index.ts # Main entry point with exports
│ ├── types.ts # TypeScript interfaces
│ └── styles.css # Widget styles
├── dist/ # Built files (generated)
│ ├── sapio-widget.min.js # UMD bundle
│ ├── sapio-widget.esm.js # ESM bundle
│ ├── *.css # Extracted styles
│ └── *.d.ts # TypeScript declarations
├── webpack.config.js # Development config
├── webpack.umd.config.js # UMD build config
├── webpack.esm.config.js # ESM build config
├── package.json
├── tsconfig.json
└── README.mdBuild Process
The build process creates multiple formats for maximum compatibility:
UMD Build (
webpack.umd.config.js):- Creates
sapio-widget.min.jsfor browser<script>tags - Bundles React and all dependencies
- Exposes global
SapioWidgetobject
- Creates
ESM Build (
webpack.esm.config.js):- Creates
sapio-widget.esm.jsfor modern bundlers - Supports tree-shaking and code splitting
- External React dependencies for smaller bundles
- Creates
TypeScript Declarations:
- Generates
.d.tsfiles for full TypeScript support - Includes React component types and vanilla JS types
- Generates
Browser Support
- Chrome 70+
- Firefox 65+
- Safari 12+
- Edge 79+
- Mobile browsers (iOS Safari 12+, Android Chrome 70+)
reCAPTCHA Integration
reCAPTCHA protection is automatically handled by the widget - no client configuration required!
How it Works
- Backend Configuration: reCAPTCHA settings are stored in your Sapio backend
- Automatic Loading: The widget automatically loads the reCAPTCHA script when needed
- Seamless Integration: reCAPTCHA tokens are generated and sent with each message
- Zero Client Setup: Clients don't need to handle reCAPTCHA keys or scripts
This approach ensures:
- ✅ Consistent protection across all client sites
- ✅ Simplified integration - just provide the API key
- ✅ Centralized management - update reCAPTCHA settings without touching client code
Security
- ✅ API key authentication - Secure client identification
- ✅ Automatic reCAPTCHA protection - Bot prevention without client setup
- ✅ HTTPS-only communication - Encrypted data transmission
- ✅ Content Security Policy compatible - Works with strict CSP
- ✅ No external runtime dependencies - Self-contained bundle
Performance
- Bundle size: ~30KB minified + gzipped (ESM), ~45KB (UMD with React)
- Load time: < 1 second on 3G networks
- Memory usage: < 5MB runtime footprint
- Tree-shaking: ESM build supports dead code elimination
- Lazy loading: reCAPTCHA and assets loaded only when needed
Troubleshooting
Widget not appearing
- Check console for JavaScript errors
- Verify API key is correct and active
- Ensure React dependencies are available (for React component usage)
- Check network connectivity to Sapio backend
Installation issues
- NPM installation: Ensure
npm install sapio-widgetcompleted successfully - React compatibility: Requires React 16.8+ for hooks support
- TypeScript: Ensure TypeScript 4.0+ for proper type support
API errors
- Authentication: Verify API key has proper permissions
- Network: Check if backend is accessible
- CORS: Ensure domain is allowed in Sapio backend settings
Styling conflicts
- Z-index: Widget uses high z-index (2147483000) by default
- CSS conflicts: Widget styles are scoped to avoid conflicts
- Responsive: Test on different screen sizes
License
MIT License - see LICENSE file for details.
