A newer version of the Gradio SDK is available:
5.46.0
JavaScript Implementace Chat Aplikace
Tato dokumentace popisuje implementované JavaScript funkcionality pro AI chat aplikaci bez změn v UI vzhledu.
🚀 Přehled funkcionalit
1. Základní Chat Funkce
- ✅ Real-time komunikace s AI
- ✅ Streaming odpovědí
- ✅ Automatické ukládání konverzací
- ✅ Správa historie chatů
- ✅ Typing indikátory
2. API Komunikace
- ✅ HTTP/Fetch API s retry logikou
- ✅ Error handling a connection monitoring
- ✅ Request timeout a cancellation
- ✅ Exponential backoff pro failed requests
- ✅ Message queue pro offline zprávy
3. State Management
- ✅ Centralizovaný stav aplikace
- ✅ Persistence do localStorage
- ✅ Conversation management
- ✅ Message status tracking
- ✅ Auto-save funkcionality
4. Performance & UX
- ✅ Lazy loading konverzací
- ✅ Virtual scrolling pro dlouhé chaty
- ✅ Debouncing a throttling
- ✅ Memory usage monitoring
- ✅ Performance profiling
5. Pokročilé Funkce
- ✅ WebSocket podpora pro real-time
- ✅ Connection status monitoring
- ✅ Security utilities a validation
- ✅ Accessibility features
- ✅ Error reporting systém
📁 Struktura souborů
public/
├── app.js # Hlavní aplikační logika
├── i18n.js # Internationalization systém
├── utils.js # Utility funkce
├── index.html # UI template (nezměněno)
└── styles.css # Styles (nezměněno)
🔧 Klíčové třídy a komponenty
ChatApp
- Hlavní aplikační třída
const chatApp = new ChatApp();
chatApp.init(); // Inicializace aplikace
Funkcionality:
- Inicializace a setup aplikace
- Event handling pro UI interakce
- Message sending a receiving
- State synchronization
ChatState
- State management
const chatState = new ChatState();
chatState.createConversation('New Chat');
chatState.addMessage('user', 'Hello!');
Funkcionality:
- Centralizovaná správa stavu
- Conversation management
- Message persistence
- Auto-save do localStorage
APIManager
- API komunikace
const apiManager = new APIManager();
await apiManager.sendMessage('Hello', history);
Funkcionality:
- HTTP requests s retry logikou
- Error handling a timeouts
- Connection monitoring
- Request cancellation
MessageRenderer
- Renderování zpráv
const messageRenderer = new MessageRenderer();
messageRenderer.renderMessage(message);
messageRenderer.showTyping();
Funkcionality:
- Dynamic message rendering
- Typing indicators
- Message formatting
- Scroll management
ConnectionMonitor
- Monitorování připojení
const monitor = new ConnectionMonitor((status) => {
console.log('Connection status:', status);
});
Funkcionality:
- Real-time connection monitoring
- Online/offline detection
- Ping testing
- Status change callbacks
🛠 Utility systémy
Text Processing (Utils.Text
)
- Text normalization a cleaning
- Markdown parsing
- HTML sanitization
- Search highlighting
Date/Time (Utils.Date
)
- Relative time formatting
- Date parsing a validation
- Timezone handling
- Time calculations
Storage (Utils.Storage
)
- Safe localStorage operations
- JSON serialization
- Storage usage monitoring
- Fallback handling
Performance (Utils.Performance
)
- Execution time measurement
- Memory usage tracking
- Performance observers
- Idle callbacks
Validation (Utils.Validation
)
- Input validation
- Security checks
- Format verification
- Content filtering
🌐 Internationalization (i18n)
Enhanced i18n systém s pokročilými funkcemi:
// Základní překlad
t('chat.welcome') // "Welcome to chat"
// S parametry
t('chat.messageCount', { count: 5 }) // "5 messages"
// S formátováním
t('chat.timestamp', { date: Date.now() }) // "2:30 PM"
// Pluralization
tc('chat.messages', 5) // "5 messages" vs "1 message"
Funkcionality:
- Automatic locale detection
- Pluralization rules
- Parameter interpolation
- Number/date formatting
- RTL language support
- Caching a performance optimization
🔒 Security Features
Rate Limiting
const rateLimiter = SecurityUtils.createRateLimiter(10, 60000);
if (!rateLimiter('user123')) {
console.log('Rate limited!');
}
Content Validation
if (SecurityUtils.validateMessage(content)) {
// Safe to process
}
HTML Sanitization
const safeHTML = SecurityUtils.sanitizeHTML(userInput);
📊 Performance Monitoring
Memory Usage
const memoryInfo = performanceMonitor.getMemoryUsage();
console.log('Memory usage:', memoryInfo);
Execution Timing
performanceMonitor.startTiming('messageProcessing');
// ... kód ...
performanceMonitor.endTiming('messageProcessing');
Network Monitoring
performanceMonitor.observeNetworkTiming();
♿ Accessibility Features
Keyboard Navigation
Ctrl/Cmd + N
: Nová konverzaceCtrl/Cmd + /
: Focus na composerEscape
: Cancel current operation
Screen Reader Support
- ARIA labels a descriptions
- Live regions pro notifications
- Semantic HTML structure
- Keyboard focus management
🚨 Error Handling
Global Error Reporting
const errorReporter = new ErrorReporter();
errorReporter.reportError({
type: 'api',
message: 'Failed to send message',
context: { userId: '123' }
});
Graceful Degradation
- Offline mode support
- Fallback UI states
- Progressive enhancement
- Error boundaries
🔄 Real-time Features
WebSocket Support
const wsManager = new WebSocketManager('ws://localhost:8080');
wsManager.connect();
wsManager.on('message', (data) => {
console.log('Received:', data);
});
Live Updates
- Real-time message delivery
- Typing indicators
- Connection status
- Message read receipts
📱 Responsive Behavior
Všechny funkce jsou optimalizované pro:
- Desktop browsery
- Mobile devices
- Touch interactions
- Variable screen sizes
- Portrait/landscape orientations
🧪 Debug Interface
Pro debugging a testing:
// Global debug objekty
window.chatDebug = {
chatApp,
chatState,
apiManager,
messageRenderer,
performanceMonitor,
errorReporter
};
window.i18nDebug = {
i18n,
getStats: () => i18n.getStats(),
clearCache: () => i18n.clearCache()
};
window.Utils = {
Text, Date, Storage, Event,
Performance, Validation, Random
};
🚀 Usage Examples
Základní inicializace
// Aplikace se automaticky inicializuje při načtení stránky
// Není potřeba manuální setup
Sending zprávy programatically
chatApp.handleSendMessage('Hello, how are you?');
Přístup k conversation history
const conversation = chatState.getCurrentConversation();
console.log(conversation.messages);
Změna jazyka
await i18n.setLocale('cs');
Monitoring performance
const stats = performanceMonitor.getStats();
console.log('Performance stats:', stats);
🎯 Features v Development
- Voice input/output
- File upload support
- Advanced markdown rendering
- Plugin system
- Advanced search
- Export/import funkcionalita
📝 Poznámky
- Kompatibilita: Všechny funkce jsou testované v moderních browserech (Chrome, Firefox, Safari, Edge)
- Performance: Optimalizované pro smooth UX i při velkých conversation histories
- Accessibility: Splňuje WCAG 2.1 AA standardy
- Security: Implementované základní security measures
- Extensibility: Modulární architektura umožňuje snadné rozšíření
🔗 API Endpoints
Aplikace očekává tyto backend endpoints:
POST /chat
- Sending zprávy (streaming response)HEAD /ping
- Health checkGET /locales/{locale}.json
- Language files
Všechny funkcionality jsou implementované tak, aby zachovaly stávající UI a design, pouze přidávají funktionalitu "pod kapotou".