Files
eveAI/documentation/TRANSLATION_MANAGEMENT_GUIDE.md

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:

  1. Modern Vue 3 Composables - Reactive translation state management
  2. Better Error Handling - Comprehensive error states and fallbacks
  3. Loading States - Built-in loading indicators for translations
  4. Batch Translation - Efficient multiple text translation
  5. 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

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

  1. ChatInput.vue - Lines 235-243: Placeholder translation
  2. 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>

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 availability
  • currentLanguage: ComputedRef<string> - Current language from chatConfig
  • isTranslating: Ref<boolean> - Loading state for translations
  • lastError: Ref<Error|null> - Last translation error
  • translate(text, targetLang, sourceLang?, context?, apiPrefix?) - Full translation method
  • translateSafe(text, targetLang, options?) - Safe translation with fallback
  • translateBatch(texts, targetLang, options?) - Batch translation
  • getCurrentLanguage() - Get current language
  • getApiPrefix() - Get API prefix

useTranslationClient()

Returns:

  • translate - Full translation method
  • translateSafe - Safe translation with fallback
  • isTranslationReady - Translation system availability
  • isTranslating - Loading state
  • lastError - Last error

useReactiveTranslation(text, options?)

Parameters:

  • text: string - Text to translate
  • options.context?: string - Translation context
  • options.sourceLang?: string - Source language
  • options.autoTranslate?: boolean - Auto-translate on language change

Returns:

  • translatedText: Ref<string> - Translated text
  • isLoading: Ref<boolean> - Loading state
  • updateTranslation(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

  1. Modern Vue 3 Patterns - Composition API and reactive state
  2. Better Error Handling - Comprehensive error states and fallbacks
  3. Loading States - Built-in loading indicators
  4. Type Safety Ready - Prepared for TypeScript integration
  5. Batch Operations - Efficient multiple text translation
  6. Reactive Translation - Automatic updates on language changes
  7. 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

  1. TypeScript Support - Add proper type definitions
  2. Caching System - Cache translated texts for performance
  3. Offline Support - Fallback for offline scenarios
  4. Translation Memory - Remember previous translations
  5. Language Detection - Automatic source language detection

This modern translation system provides a solid foundation for scalable, maintainable translation management in the Vue 3 application!