@useviber/plugin
v0.1.10
Published
Universal Viber Plugin - Works with any framework (React, Vue, Angular, Svelte, Vanilla)
Maintainers
Readme
Viber Plugin
A framework-agnostic plugin that brings Viber AI assistance to ANY web application, regardless of the frontend framework being used. Viber works with ALL major frameworks: React, Vue, Angular, Svelte, and Vanilla JavaScript! 🎯
✨ Features
- Universal Framework Support: Viber works with ALL major frameworks: React, Vue, Angular, Svelte, and Vanilla JavaScript
- Smart Framework Detection: Automatically detects the framework and provides framework-specific analysis
- Enhanced Element Analysis: Extracts framework-specific props, state, and component information
- Real-time Communication: WebSocket integration for live updates and status monitoring
- Floating UI: Non-intrusive floating icon and chat interface
- Event System: Comprehensive event system for integration with existing applications
📦 Installation
Option 1: NPM Package
npm install @viber/pluginOption 2: Direct Script Include
<script src="https://unpkg.com/@viber/plugin/dist/index.js"></script>Option 3: Build from Source
git clone <repository>
cd viber-plugin
npm install
npm run build🔧 Configuration
Configure the plugin by setting window.VIBER_CONFIG before loading the script:
<script>
window.VIBER_CONFIG = {
port: 8426, // Viber CLI port
viberPort: 8426, // Alternative port name
workspace: 'my-app', // Workspace identifier
debug: true, // Enable debug logging
autoConnect: true, // Auto-connect on initialization
currentFile: 'app.js' // Current file context
};
</script>🎯 Basic Usage
Simple Initialization
// The plugin auto-initializes when VIBER_CONFIG is set
// Access via window.viberPlugin
const plugin = window.viberPlugin;
// Or create manually
const plugin = new PluginViber({
workspace: 'my-app',
debug: true
});Element Selection and Analysis
// Select an element
plugin.selectElement(document.querySelector('.my-component'));
// Analyze the selected element
plugin.analyzeElement(
document.querySelector('.my-component'),
'Make this component more accessible'
);🔍 Framework Detection
The plugin automatically detects the framework and provides enhanced analysis:
Basic Framework Detection
// Get framework information
const frameworkInfo = plugin.getFrameworkInfo();
console.log(frameworkInfo);
// Output: { type: 'react', version: '18.2.0', detected: true }
// Analyze element with framework context
const elementInfo = plugin.analyzeElementWithFramework(element);
console.log(elementInfo);
// Output includes framework-specific props, state, and component infoNEW: Deep Framework Analysis
The plugin now provides deep analysis for all frameworks, similar to React Fiber detection:
// Deep framework analysis (like React Fiber detection)
const deepInfo = plugin.analyzeElementDeep(element);
console.log(deepInfo);
// Output includes deep framework internals, component hierarchy, and state
// Framework-specific deep analysis
if (deepInfo.type === 'react') {
console.log('React Fiber:', deepInfo.fiber);
console.log('Component Hierarchy:', deepInfo.hierarchy);
console.log('Internal Props:', deepInfo.props);
console.log('Internal State:', deepInfo.state);
} else if (deepInfo.type === 'vue') {
console.log('Vue Instance:', deepInfo.instance);
console.log('Component Data:', deepInfo.data);
console.log('Computed Properties:', deepInfo.computed);
console.log('Methods:', deepInfo.methods);
} else if (deepInfo.type === 'angular') {
console.log('Angular Context:', deepInfo.ngContext);
console.log('Component Inputs:', deepInfo.inputs);
console.log('Component Outputs:', deepInfo.outputs);
} else if (deepInfo.type === 'svelte') {
console.log('Svelte Instance:', deepInfo.instance);
console.log('Component Props:', deepInfo.props);
console.log('Component State:', deepInfo.state);
} else {
console.log('Custom Elements:', deepInfo.customElements);
console.log('Shadow DOM:', deepInfo.shadowRoot);
console.log('CSS Custom Properties:', deepInfo.customProperties);
}// Get framework information
const frameworkInfo = plugin.getFrameworkInfo();
console.log(frameworkInfo);
// Output: { type: 'react', version: '18.2.0', detected: true }
// Analyze element with framework context
const elementInfo = plugin.analyzeElementWithFramework(element);
console.log(elementInfo);
// Output includes framework-specific props, state, and component info
// NEW: Deep framework analysis (like React Fiber detection)
const deepInfo = plugin.analyzeElementDeep(element);
console.log(deepInfo);
// Output includes deep framework internals, component hierarchy, and state📡 WebSocket Integration
Subscribe to Status Updates
plugin.subscribeToStatusUpdates((status) => {
console.log(`Status: ${status.status} - ${status.message}`);
console.log(`Progress: ${status.progress}%`);
});Send Custom Messages
plugin.sendMessage({
type: 'custom_action',
data: { action: 'refresh', target: 'component' }
});🎨 UI Components
Floating Icon
The plugin automatically creates a floating icon that:
- Shows connection status
- Opens the chat interface
- Provides quick access to plugin functions
Chat Interface
A comprehensive chat interface that:
- Displays selected element information
- Allows user instructions
- Shows analysis results
- Integrates with Viber AI
📊 Event System
The plugin emits various events for integration:
// Element selection
document.addEventListener('viber:elementSelected', (event) => {
const { element, framework, parentChain } = event.detail;
console.log('Element selected:', element, 'Framework:', framework);
});
// WebSocket messages
document.addEventListener('viber:webSocketMessage', (event) => {
const { message } = event.detail;
console.log('WebSocket message:', message);
});
// Element analysis results
document.addEventListener('viber:elementAnalyzed', (event) => {
const { result, element } = event.detail;
console.log('Analysis result:', result);
});
// Status updates
document.addEventListener('viber:statusUpdate', (event) => {
const { status } = event.detail;
console.log('Status update:', status);
});🔔 CustomEvent System
The plugin uses native browser CustomEvent API (not framework-specific) for universal communication across all frameworks. This ensures compatibility with React, Vue, Angular, Svelte, and vanilla JavaScript applications.
How CustomEvent Works
The plugin creates and dispatches custom events using the native DOM API:
// Plugin creates a custom event
const customEvent = new CustomEvent('viber:elementAnalyzed', {
detail: { result: response, element }
});
// Plugin dispatches the event globally
document.dispatchEvent(customEvent);Available Custom Events
viber:elementAnalyzed
Fired when element analysis is completed successfully.
document.addEventListener('viber:elementAnalyzed', (event) => {
const { result, element } = event.detail;
console.log('✅ Analysis completed:', result);
console.log('🎯 Element analyzed:', element);
// Handle successful analysis
updateUI(result);
showSuccessMessage('Analysis completed!');
});viber:elementAnalysisError
Fired when element analysis fails.
document.addEventListener('viber:elementAnalysisError', (event) => {
const { error, element } = event.detail;
console.log('❌ Analysis failed:', error);
console.log('🎯 Element that failed:', element);
// Handle analysis error
showErrorMessage(error);
retryAnalysis(element);
});viber:elementSelected
Fired when an element is selected for analysis.
document.addEventListener('viber:elementSelected', (event) => {
const { element, framework, parentChain } = event.detail;
console.log('🎯 Element selected:', element);
console.log('⚡ Framework detected:', framework);
console.log('🔗 Parent chain:', parentChain);
// Update UI to show selected element
highlightElement(element);
updateSelectionInfo(framework);
});viber:webSocketMessage
Fired when WebSocket messages are received.
document.addEventListener('viber:webSocketMessage', (event) => {
const { message } = event.detail;
console.log('📡 WebSocket message:', message);
// Handle different message types
switch (message.type) {
case 'status_update':
handleStatusUpdate(message.data);
break;
case 'extensions_updated':
updateExtensionsList(message.extensions);
break;
case 'extension_activated':
showExtensionActivated(message.extensionId);
break;
}
});viber:statusUpdate
Fired when status updates are received.
document.addEventListener('viber:statusUpdate', (event) => {
const { status } = event.detail;
console.log('📊 Status update:', status);
// Update progress indicators
updateProgressBar(status.progress);
updateStatusText(status.message);
// Handle completion
if (status.status === 'completed') {
showCompletionMessage(status.data);
}
});Why CustomEvent Instead of Framework Events?
- Universal Compatibility: Works in any framework (React, Vue, Angular, Svelte, vanilla JS)
- Native Browser API: No external dependencies or framework-specific code
- Loose Coupling: Components don't need direct references to communicate
- Event-Driven Architecture: Clean separation of concerns
- Easy Integration: Simple
addEventListenerpattern familiar to all developers
Integration Examples
React Component
import { useEffect } from 'react';
function ViberIntegration() {
useEffect(() => {
const handleElementAnalyzed = (event) => {
const { result, element } = event.detail;
console.log('Analysis result in React:', result);
// Update React state or trigger actions
};
document.addEventListener('viber:elementAnalyzed', handleElementAnalyzed);
return () => {
document.removeEventListener('viber:elementAnalyzed', handleElementAnalyzed);
};
}, []);
return <div>Viber integration active</div>;
}Vue Component
<template>
<div>Viber integration active</div>
</template>
<script>
export default {
mounted() {
this.handleElementAnalyzed = (event) => {
const { result, element } = event.detail;
console.log('Analysis result in Vue:', result);
// Update Vue reactive data
};
document.addEventListener('viber:elementAnalyzed', this.handleElementAnalyzed);
},
beforeUnmount() {
document.removeEventListener('viber:elementAnalyzed', this.handleElementAnalyzed);
}
}
</script>Angular Component
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-viber-integration',
template: '<div>Viber integration active</div>'
})
export class ViberIntegrationComponent implements OnInit, OnDestroy {
private handleElementAnalyzed = (event: any) => {
const { result, element } = event.detail;
console.log('Analysis result in Angular:', result);
// Update Angular component data
};
ngOnInit() {
document.addEventListener('viber:elementAnalyzed', this.handleElementAnalyzed);
}
ngOnDestroy() {
document.removeEventListener('viber:elementAnalyzed', this.handleElementAnalyzed);
}
}Vanilla JavaScript
// Simple event listener
document.addEventListener('viber:elementAnalyzed', (event) => {
const { result, element } = event.detail;
console.log('Analysis result in vanilla JS:', result);
// Update DOM or trigger actions
updateResultsDisplay(result);
showSuccessNotification();
});
// Multiple event listeners
const eventHandlers = {
'viber:elementAnalyzed': (event) => {
console.log('Analysis completed:', event.detail.result);
},
'viber:elementAnalysisError': (event) => {
console.log('Analysis failed:', event.detail.error);
},
'viber:statusUpdate': (event) => {
console.log('Status update:', event.detail.status);
}
};
// Register all handlers
Object.entries(eventHandlers).forEach(([eventName, handler]) => {
document.addEventListener(eventName, handler);
});Event Cleanup
Always remove event listeners when components are destroyed to prevent memory leaks:
// Store reference to handler
const handleElementAnalyzed = (event) => {
const { result, element } = event.detail;
// Handle event
};
// Add listener
document.addEventListener('viber:elementAnalyzed', handleElementAnalyzed);
// Remove listener (important!)
document.removeEventListener('viber:elementAnalyzed', handleElementAnalyzed);Debugging Custom Events
Monitor all Viber events in the browser console:
// Debug all Viber events
const viberEventNames = [
'viber:elementAnalyzed',
'viber:elementAnalysisError',
'viber:elementSelected',
'viber:webSocketMessage',
'viber:statusUpdate'
];
viberEventNames.forEach(eventName => {
document.addEventListener(eventName, (event) => {
console.log(`🔔 ${eventName}:`, event.detail);
});
});🔧 Advanced Usage
Custom Element Context
// Get detailed element context
const context = plugin.getElementContext(element);
console.log('Element context:', context);
// Includes framework-specific data, props, state, etc.Manual WebSocket Management
// Check connection status
const wsConnected = plugin.isWebSocketConnected();
const wsState = plugin.getWebSocketState();
// Manual connection management
if (!wsConnected) {
// Plugin will auto-reconnect, but you can trigger manually
plugin.connect();
}Plugin State Management
// Check plugin status
const initialized = plugin.isPluginInitialized();
const connected = plugin.isConnected();
// Get selected element
const selectedElement = plugin.getSelectedElement();
const parentChain = plugin.getParentChain();🎯 Framework-Specific Features
React
- Detects React components and props
- Extracts component names and state
- Analyzes React-specific attributes
- NEW: Deep React Fiber analysis
- NEW: Component hierarchy traversal
- NEW: React Server Component detection
- NEW: Internal props and state extraction
Vue
- Identifies Vue directives and components
- Extracts Vue-specific props and data
- Analyzes Vue component structure
- NEW: Deep Vue instance analysis
- NEW: Composition API detection
- NEW: Component data, computed, and methods extraction
- NEW: Vue 2 and Vue 3 support
Angular
- Detects Angular components and controllers
- Extracts Angular-specific attributes
- Analyzes Angular component context
- NEW: Deep Angular context analysis
- NEW: Component inputs and outputs extraction
- NEW: Dependency injection context
- NEW: Change detection analysis
Svelte
- Identifies Svelte components
- Extracts Svelte-specific attributes
- Analyzes Svelte component structure
- NEW: Deep Svelte instance analysis
- NEW: Component props and state extraction
- NEW: Store detection and analysis
- NEW: Lifecycle method detection
Vanilla JavaScript
- Basic DOM element analysis
- Event handler detection
- Attribute and property extraction
- NEW: Custom Elements detection
- NEW: Shadow DOM analysis
- NEW: CSS Custom Properties extraction
- NEW: Data attributes analysis
🚀 Integration Examples
React Application
import { useEffect } from 'react';
function App() {
useEffect(() => {
// Plugin auto-initializes
if (window.viberPlugin) {
window.viberPlugin.subscribeToStatusUpdates((status) => {
console.log('Viber status:', status);
});
}
}, []);
return (
<div className="app">
<button onClick={() => {
window.viberPlugin?.selectElement(document.querySelector('.my-button'));
}}>
Analyze Button
</button>
</div>
);
}Vue Application
<template>
<div class="app">
<button @click="analyzeElement" class="my-button">
Click me
</button>
</div>
</template>
<script>
export default {
mounted() {
if (window.viberPlugin) {
this.plugin = window.viberPlugin;
}
},
methods: {
analyzeElement() {
this.plugin?.selectElement(document.querySelector('.my-button'));
}
}
}
</script>Angular Application
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: '<button (click)="analyzeElement()" class="my-button">Click me</button>'
})
export class AppComponent implements OnInit {
private plugin: any;
ngOnInit() {
if (window['viberPlugin']) {
this.plugin = window['viberPlugin'];
}
}
analyzeElement() {
this.plugin?.selectElement(document.querySelector('.my-button'));
}
}🛠️ Development
Building the Plugin
# Install dependencies
npm install
# Development build with watch
npm run dev
# Production build
npm run buildTesting
# Open demo.html in a browser
# Or serve with a local server
npx serve .Project Structure
src/
├── core/
│ └── FrameworkDetector.ts # Framework detection logic
├── services/
│ ├── WebSocketService.ts # WebSocket communication
│ └── StorageService.ts # Local storage management
├── components/
│ ├── FloatingIcon.ts # Floating UI component
│ └── ChatInterface.ts # Chat interface component
├── PluginViber.ts # Main plugin class
├── UniversalViber.ts # Alternative implementation
└── index.ts # Public API exports🔌 API Reference
PluginViber Class
Constructor
new PluginViber(config: ViberConfig)Methods
selectElement(element: HTMLElement): voidanalyzeElement(element: HTMLElement, userGoal?: string): Promise<void>getElementContext(element: HTMLElement): ElementInfoanalyzeElementWithFramework(element: HTMLElement): FrameworkElementInfo- NEW:
analyzeElementDeep(element: HTMLElement): DeepFrameworkInfo subscribeToStatusUpdates(callback: (status: StatusUpdate) => void): voidsendMessage(message: any): voidshowChat(): voidhideChat(): voiddestroy(): void
Properties
isConnected: booleanisWebSocketConnected(): booleangetWebSocketState(): stringgetFrameworkInfo(): FrameworkInfo
Types
ViberConfig
interface ViberConfig {
port?: number;
viberPort?: number;
workspace: string;
debug?: boolean;
autoConnect?: boolean;
currentFile?: string;
}ElementInfo
interface ElementInfo {
tagName: string;
className: string;
id: string;
innerText: string;
attributes: Record<string, string>;
boundingBox?: DOMRect;
framework?: string;
componentName?: string;
hasState?: boolean;
eventHandlers?: string[];
reactProps?: Record<string, any>;
vueProps?: Record<string, any>;
angularProps?: Record<string, any>;
svelteProps?: Record<string, any>;
}NEW: DeepFrameworkInfo
// Union type for deep framework analysis
type DeepFrameworkInfo = ReactDeepInfo | VueDeepInfo | AngularDeepInfo | SvelteDeepInfo | VanillaDeepInfo;
// Example: ReactDeepInfo
interface ReactDeepInfo {
type: 'react';
version?: string;
componentName?: string;
componentFile?: string;
props?: any;
state?: any;
fiber?: any;
hierarchy?: Array<{name: string, type: 'regular' | 'rsc'}>;
internalInstance?: any;
eventPriority?: number;
lanes?: number;
}🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
📄 License
MIT License - see LICENSE file for details
🆘 Support
- Check the demo.html file for usage examples
- Review the event system for integration patterns
- Ensure VIBER_CONFIG is properly set before plugin loads
- Verify the Viber CLI is running on the configured port
🔄 Changelog
v0.2.0 (Latest)
- NEW: Deep framework analysis for all frameworks
- NEW: React Fiber detection and component hierarchy
- NEW: Vue instance analysis and Composition API support
- NEW: Angular context analysis and dependency injection
- NEW: Svelte instance analysis and store detection
- NEW: Vanilla JS custom elements and Shadow DOM analysis
- Enhanced framework detection capabilities
- Improved element context extraction
v0.1.0
- Initial release with framework detection
- Basic element analysis
- WebSocket integration
- Floating UI components
- Event system
- Framework-specific enhancements
