12 KiB
12 KiB
Translation Management System Guide
🎯 Overview
The translation management system has been successfully modernized from legacy window.TranslationClient to modern Vue 3 composables. This provides:
- ✅ Modern Vue 3 Composables - Reactive translation state management
- ✅ Better Error Handling - Comprehensive error states and fallbacks
- ✅ Loading States - Built-in loading indicators for translations
- ✅ Batch Translation - Efficient multiple text translation
- ✅ Backward Compatibility - Existing code continues to work during migration
📁 File Structure
eveai_chat_client/static/assets/js/
├── translation.js.old # Legacy TranslationClient (being phased out)
└── composables/
├── index.js # Barrel export for composables
└── useTranslation.js # Vue 3 translation composables
🔧 Available Composables
1. useTranslation() - Full Featured
The main composable providing complete translation functionality with reactive state management.
<script setup>
import { useTranslation } from '@/composables/useTranslation.js';
const {
translate,
translateSafe,
translateBatch,
isTranslationReady,
isTranslating,
currentLanguage,
lastError
} = useTranslation();
// Translate with full control
const result = await translate('Hello world', 'nl', 'en', 'greeting');
// Safe translation with fallback
const translated = await translateSafe('Hello world', 'nl', {
fallbackText: 'Hello world',
context: 'greeting'
});
// Batch translate multiple texts
const texts = ['Hello', 'World', 'Vue'];
const translated = await translateBatch(texts, 'nl');
</script>
2. useTranslationClient() - Simplified
Simplified composable for basic translation needs without reactive state management.
<script setup>
import { useTranslationClient } from '@/composables/useTranslation.js';
const {
translate,
translateSafe,
isTranslationReady,
isTranslating,
lastError
} = useTranslationClient();
// Simple translation
const result = await translateSafe('Hello world', 'nl');
</script>
3. useReactiveTranslation() - Automatic Translation
Composable for reactive text translation that automatically updates when language changes.
<script setup>
import { useReactiveTranslation } from '@/composables/useTranslation.js';
const originalText = 'Hello world';
const {
translatedText,
isLoading,
updateTranslation
} = useReactiveTranslation(originalText, {
context: 'greeting',
autoTranslate: true
});
// Manual translation update
await updateTranslation('nl');
</script>
<template>
<div>
<span v-if="isLoading">Translating...</span>
<span v-else>{{ translatedText }}</span>
</div>
</template>
🔄 Migration Guide
From window.TranslationClient (Old)
<!-- OLD: Using window.TranslationClient -->
<script>
export default {
async methods: {
async translatePlaceholder(language) {
if (!window.TranslationClient || typeof window.TranslationClient.translate !== 'function') {
console.error('TranslationClient.translate is niet beschikbaar');
return;
}
const apiPrefix = window.chatConfig?.apiPrefix || '';
const response = await window.TranslationClient.translate(
this.originalText,
language,
null,
'chat_input_placeholder',
apiPrefix
);
if (response.success) {
this.translatedText = response.translated_text;
}
}
}
}
</script>
To Vue 3 Composable (New)
<!-- NEW: Using composable -->
<script setup>
import { useTranslationClient } from '@/composables';
const { translateSafe, isTranslating } = useTranslationClient();
const translatePlaceholder = async (language) => {
const apiPrefix = window.chatConfig?.apiPrefix || '';
const translated = await translateSafe(originalText, language, {
context: 'chat_input_placeholder',
apiPrefix,
fallbackText: originalText
});
translatedText.value = translated;
};
</script>
📋 Current Usage in Vue Components
Components Using window.TranslationClient
- ChatInput.vue - Lines 235-243: Placeholder translation
- MessageHistory.vue - Lines 144-151: Message translation
✅ Migration Examples
ChatInput.vue Migration
Before (Problematic):
<script>
export default {
methods: {
async translatePlaceholder(language) {
if (!window.TranslationClient || typeof window.TranslationClient.translate !== 'function') {
console.error('TranslationClient.translate is niet beschikbaar voor placeholder');
return;
}
const apiPrefix = window.chatConfig?.apiPrefix || '';
const response = await window.TranslationClient.translate(
originalText,
language,
null,
'chat_input_placeholder',
apiPrefix
);
if (response.success) {
this.translatedPlaceholder = response.translated_text;
} else {
console.error('Vertaling placeholder mislukt:', response.error);
}
}
}
}
</script>
After (Modern Vue 3):
<script setup>
import { ref } from 'vue';
import { useTranslationClient } from '@/composables';
const { translateSafe, isTranslating } = useTranslationClient();
const translatedPlaceholder = ref('');
const translatePlaceholder = async (language) => {
const apiPrefix = window.chatConfig?.apiPrefix || '';
const result = await translateSafe(originalText, language, {
context: 'chat_input_placeholder',
apiPrefix,
fallbackText: originalText
});
translatedPlaceholder.value = result;
};
</script>
MessageHistory.vue Migration
Before (Problematic):
<script>
export default {
methods: {
async handleLanguageChange(event) {
if (!window.TranslationClient || typeof window.TranslationClient.translate !== 'function') {
console.error('TranslationClient.translate is niet beschikbaar');
return;
}
const response = await window.TranslationClient.translate(
firstMessage.originalContent,
event.detail.language,
null,
'chat_message',
this.apiPrefix
);
if (response.success) {
firstMessage.content = response.translated_text;
}
}
}
}
</script>
After (Modern Vue 3):
<script setup>
import { useTranslationClient } from '@/composables';
const { translateSafe } = useTranslationClient();
const handleLanguageChange = async (event) => {
const translated = await translateSafe(
firstMessage.originalContent,
event.detail.language,
{
context: 'chat_message',
apiPrefix: props.apiPrefix,
fallbackText: firstMessage.originalContent
}
);
firstMessage.content = translated;
};
</script>
🚀 Recommended Usage Patterns
For New Components
<script setup>
import { useTranslationClient } from '@/composables';
const { translateSafe, isTranslating } = useTranslationClient();
const handleTranslation = async (text, targetLang) => {
return await translateSafe(text, targetLang, {
context: 'component_specific_context',
apiPrefix: window.chatConfig?.apiPrefix || ''
});
};
</script>
For Reactive Translation
<script setup>
import { useReactiveTranslation } from '@/composables';
const originalText = 'Welcome to EveAI';
const { translatedText, isLoading, updateTranslation } = useReactiveTranslation(originalText);
// Automatically update when language changes
document.addEventListener('language-changed', (event) => {
updateTranslation(event.detail.language);
});
</script>
<template>
<div>
<span v-if="isLoading">🔄 Translating...</span>
<span v-else>{{ translatedText }}</span>
</div>
</template>
For Batch Translation
<script setup>
import { useTranslation } from '@/composables';
const { translateBatch } = useTranslation();
const translateMultipleTexts = async (texts, targetLang) => {
const results = await translateBatch(texts, targetLang, {
context: 'batch_translation',
apiPrefix: window.chatConfig?.apiPrefix || ''
});
return results;
};
</script>
🔍 API Reference
useTranslation()
Returns:
isTranslationReady: Ref<boolean>- Translation system availabilitycurrentLanguage: ComputedRef<string>- Current language from chatConfigisTranslating: Ref<boolean>- Loading state for translationslastError: Ref<Error|null>- Last translation errortranslate(text, targetLang, sourceLang?, context?, apiPrefix?)- Full translation methodtranslateSafe(text, targetLang, options?)- Safe translation with fallbacktranslateBatch(texts, targetLang, options?)- Batch translationgetCurrentLanguage()- Get current languagegetApiPrefix()- Get API prefix
useTranslationClient()
Returns:
translate- Full translation methodtranslateSafe- Safe translation with fallbackisTranslationReady- Translation system availabilityisTranslating- Loading statelastError- Last error
useReactiveTranslation(text, options?)
Parameters:
text: string- Text to translateoptions.context?: string- Translation contextoptions.sourceLang?: string- Source languageoptions.autoTranslate?: boolean- Auto-translate on language change
Returns:
translatedText: Ref<string>- Translated textisLoading: Ref<boolean>- Loading stateupdateTranslation(newLanguage?)- Manual translation update
🔧 Configuration
Translation Options
const options = {
sourceLang: 'en', // Source language (optional)
context: 'chat_message', // Translation context
apiPrefix: '/chat-client', // API prefix for tenant routing
fallbackText: 'Fallback' // Fallback text on error
};
Error Handling
<script setup>
import { useTranslation } from '@/composables';
const { translate, lastError, isTranslating } = useTranslation();
const handleTranslation = async () => {
try {
const result = await translate('Hello', 'nl');
console.log('Translation successful:', result);
} catch (error) {
console.error('Translation failed:', error);
// lastError.value will also contain the error
}
};
</script>
📈 Benefits Achieved
- ✅ Modern Vue 3 Patterns - Composition API and reactive state
- ✅ Better Error Handling - Comprehensive error states and fallbacks
- ✅ Loading States - Built-in loading indicators
- ✅ Type Safety Ready - Prepared for TypeScript integration
- ✅ Batch Operations - Efficient multiple text translation
- ✅ Reactive Translation - Automatic updates on language changes
- ✅ Backward Compatibility - Gradual migration support
🎉 Migration Status
✅ Completed
- Modern Vue 3 composables created
- Barrel export updated
- Documentation completed
- Migration patterns established
🔄 In Progress
- ChatInput.vue migration
- MessageHistory.vue migration
📋 Next Steps
- Complete component migrations
- Remove legacy window.TranslationClient
- Verify all translations work correctly
🚀 Future Enhancements
- TypeScript Support - Add proper type definitions
- Caching System - Cache translated texts for performance
- Offline Support - Fallback for offline scenarios
- Translation Memory - Remember previous translations
- Language Detection - Automatic source language detection
This modern translation system provides a solid foundation for scalable, maintainable translation management in the Vue 3 application!