Implement internationalization (i18n) system for LoRA Manager

- Added i18n support with automatic language detection based on browser settings.
- Implemented translations for English (en) and Simplified Chinese (zh-CN).
- Created utility functions for text replacement in HTML templates and JavaScript.
- Developed a comprehensive translation key structure for various application components.
- Added formatting functions for numbers, dates, and file sizes according to locale.
- Included RTL language support and dynamic updates for DOM elements.
- Created tests to verify the functionality of the i18n system.
This commit is contained in:
Will Miao
2025-08-28 22:22:26 +08:00
parent 4246908f2e
commit f82908221c
18 changed files with 1786 additions and 121 deletions

View File

@@ -0,0 +1,193 @@
# LoRA Manager i18n Implementation Summary
## 📋 Overview
Successfully implemented comprehensive internationalization (i18n) support for LoRA Manager UI with automatic browser language detection, supporting English and Simplified Chinese.
## 🛠 Implementation Details
### Core System Files
1. **`static/js/i18n/index.js`** - Main i18n manager
- Automatic browser language detection
- Translation interpolation with parameters
- Locale-aware number, date, and file size formatting
- RTL language support framework
2. **`static/js/i18n/locales/en.js`** - English translations
- Complete translation set for all UI elements
- Hierarchical key structure (common, header, loras, etc.)
3. **`static/js/i18n/locales/zh-CN.js`** - Simplified Chinese translations
- Full Chinese translation coverage
- Cultural adaptation for UI elements
4. **`static/js/utils/i18nHelpers.js`** - DOM helper utilities
- Automatic DOM text replacement with `data-i18n` attributes
- Dynamic search placeholder updates
- Bulk selection count updates
- Element creation helpers
### Modified Files
#### JavaScript Files (8 files modified)
- `static/js/core.js` - Core app initialization with i18n
- `static/js/components/Header.js` - Header component with i18n
- `static/js/managers/BulkManager.js` - Bulk operations with i18n
- `static/js/loras.js` - LoRA page initialization
- `static/js/checkpoints.js` - Checkpoints page initialization
- `static/js/embeddings.js` - Embeddings page initialization
- `static/js/recipes.js` - Recipes page initialization
- `static/js/statistics.js` - Statistics page initialization
#### HTML Template Files (3 files modified)
- `templates/components/header.html` - Navigation and search elements
- `templates/components/controls.html` - Page controls and bulk operations
- `templates/components/context_menu.html` - Context menu items
## 🌐 Language Support
### Supported Languages
- **English (en)** - Default language, comprehensive coverage
- **Simplified Chinese (zh-CN)** - Complete translation with cultural adaptations
- **Fallback Support** - Graceful fallback to English for missing translations
### Browser Language Detection
- Automatically detects browser language preference
- Supports both `zh-CN` and `zh` language codes (both map to Simplified Chinese)
- Falls back to English for unsupported languages
## ✨ Features
### Automatic Translation
- HTML elements with `data-i18n` attributes are automatically translated
- Support for different target attributes (textContent, placeholder, title, etc.)
- Parameter interpolation for dynamic content
### Formatting Functions
- **File Size**: Locale-aware file size formatting (e.g., "1 MB" / "1 兆字节")
- **Numbers**: Decimal formatting according to locale standards
- **Dates**: Locale-specific date formatting
### Dynamic Updates
- Search placeholders update based on current page
- Bulk selection counts update dynamically
- Theme toggle tooltips reflect current state
## 🔧 Usage Examples
### HTML Template Usage
```html
<!-- Basic text translation -->
<span data-i18n="header.appTitle">LoRA Manager</span>
<!-- Placeholder translation -->
<input data-i18n="header.search.placeholder" data-i18n-target="placeholder" />
<!-- Title attribute translation -->
<button data-i18n="common.actions.refresh" data-i18n-target="title">
```
### JavaScript Usage
```javascript
import { t, formatFileSize, initializePageI18n } from './utils/i18nHelpers.js';
// Basic translation
const message = t('common.status.loading');
// Translation with parameters
const count = t('loras.bulkOperations.selected', { count: 5 });
// Format file size
const size = formatFileSize(1048576); // "1 MB" or "1 兆字节"
// Initialize page translations
initializePageI18n();
```
## 📁 File Structure
```
static/js/
├── i18n/
│ ├── index.js # Main i18n manager
│ └── locales/
│ ├── en.js # English translations
│ └── zh-CN.js # Chinese translations
├── utils/
│ └── i18nHelpers.js # DOM helper utilities
├── test/
│ └── i18nTest.js # Test suite for i18n functionality
└── [existing files modified...]
docs/
└── i18n.md # Comprehensive usage documentation
```
## 🧪 Testing
### Test File
- **`static/js/test/i18nTest.js`** - Comprehensive test suite
- Language detection testing
- Translation functionality testing
- DOM translation testing
- Formatting function testing
### Manual Testing
Add `?test=i18n` to any page URL to run automated tests in browser console.
## 🔄 Integration Points
### Core Integration
- i18n system initializes in `core.js` before any UI components
- Available globally as `window.i18n` for debugging and development
- Each page calls `initializePageI18n()` after DOM setup
### Component Integration
- Header component updates search placeholders dynamically
- Bulk manager uses i18n for selection count updates
- Context menus and modals support localized text
- All form controls include proper translations
## 🚀 Next Steps for Extension
### Adding New Languages
1. Create new locale file in `static/js/i18n/locales/`
2. Import and register in `static/js/i18n/index.js`
3. Test with browser language simulation
### RTL Language Support
- Framework already includes RTL detection
- CSS classes automatically applied for RTL languages
- Ready for Arabic, Hebrew, or other RTL languages
### Dynamic Language Switching
- Core system supports runtime language changes
- Could add language picker UI in settings
- Would require `translateDOM()` re-execution
## ✅ Quality Assurance
### Code Quality
- Comprehensive error handling with fallbacks
- Consistent naming conventions
- Well-documented API with JSDoc comments
- Modular architecture for easy maintenance
### User Experience
- Seamless automatic language detection
- No performance impact on page load
- Graceful degradation if translations fail
- Consistent UI behavior across languages
### Maintainability
- Clear separation of concerns
- Hierarchical translation key structure
- Comprehensive documentation
- Test coverage for core functionality
---
**Implementation Status: ✅ Complete**
The i18n system is fully implemented and ready for production use. All major UI components support both English and Simplified Chinese with automatic browser language detection.

216
docs/i18n.md Normal file
View File

@@ -0,0 +1,216 @@
# LoRA Manager Internationalization (i18n)
This document explains how to use the internationalization system in LoRA Manager.
## Features
- Automatic language detection based on browser language
- Support for English (en) and Simplified Chinese (zh-CN)
- Fallback to English if the browser language is not supported
- Dynamic text replacement in HTML templates
- Number, date, and file size formatting according to locale
- Right-to-Left (RTL) language support (framework ready)
## Browser Language Detection
The system automatically detects the user's browser language using:
1. `navigator.language` - Primary browser language
2. `navigator.languages[0]` - First language in the user's preferred languages
3. Fallback to 'en' if no supported language is found
### Supported Language Codes
- `en` - English (default)
- `zh-CN` - Simplified Chinese
- `zh` - Falls back to Simplified Chinese
## Usage in HTML Templates
### Basic Text Translation
Add the `data-i18n` attribute to any HTML element:
```html
<span data-i18n="header.appTitle">LoRA Manager</span>
<button data-i18n="common.actions.save">Save</button>
```
### Placeholder and Attribute Translation
For form inputs and other attributes:
```html
<input type="text" data-i18n="header.search.placeholder" data-i18n-target="placeholder" placeholder="Search..." />
<button data-i18n="loras.controls.refresh.title" data-i18n-target="title" title="Refresh model list">
```
### Translation with Parameters
For dynamic content with variables:
```html
<span data-i18n="loras.bulkOperations.selected" data-i18n-params='{"count": 5}'>5 selected</span>
```
## Usage in JavaScript
### Import the i18n Helper
```javascript
import { t, formatFileSize, formatDate, formatNumber } from './utils/i18nHelpers.js';
```
### Basic Translation
```javascript
// Simple translation
const message = t('common.status.loading');
// Translation with parameters
const selectedText = t('loras.bulkOperations.selected', { count: 5 });
```
### Dynamic DOM Updates
```javascript
import { setTranslatedText, setTranslatedAttribute, updateBulkSelectionCount } from './utils/i18nHelpers.js';
// Update text content
setTranslatedText('#myButton', 'common.actions.save');
// Update attributes
setTranslatedAttribute('#myInput', 'placeholder', 'header.search.placeholder');
// Update bulk selection count
updateBulkSelectionCount(selectedItems.length);
```
### Formatting Functions
```javascript
// Format file size
const sizeText = formatFileSize(1048576); // "1 MB" or "1 兆字节"
// Format date
const dateText = formatDate(new Date(), { year: 'numeric', month: 'long', day: 'numeric' });
// Format number
const numberText = formatNumber(1234.56, { minimumFractionDigits: 2 });
```
## Page Initialization
Each page should call `initializePageI18n()` after the DOM is loaded:
```javascript
import { initializePageI18n } from './utils/i18nHelpers.js';
document.addEventListener('DOMContentLoaded', async () => {
// Initialize core application
await appCore.initialize();
// Initialize page-specific functionality
const myPage = new MyPageManager();
await myPage.initialize();
// Initialize i18n for the page
initializePageI18n();
});
```
## Translation Key Structure
Translation keys use dot notation for nested objects:
```
common.actions.save → "Save" / "保存"
header.navigation.loras → "LoRAs" / "LoRA 模型"
loras.controls.sort.nameAsc → "A - Z" / "A - Z"
```
### Key Categories
- `common.*` - Shared terms and actions
- `header.*` - Header and navigation
- `loras.*` - LoRA page specific
- `recipes.*` - Recipe page specific
- `checkpoints.*` - Checkpoint page specific
- `embeddings.*` - Embedding page specific
- `statistics.*` - Statistics page specific
- `modals.*` - Modal dialogs
- `errors.*` - Error messages
- `success.*` - Success messages
- `keyboard.*` - Keyboard shortcuts
- `tooltips.*` - Tooltip text
## Adding New Languages
1. Create a new language file in `static/js/i18n/locales/`:
```javascript
// Example: fr.js for French
export const fr = {
common: {
actions: {
save: 'Sauvegarder',
cancel: 'Annuler',
// ...
},
// ...
},
// ...
};
```
2. Import and register the language in `static/js/i18n/index.js`:
```javascript
import { fr } from './locales/fr.js';
class I18nManager {
constructor() {
this.locales = {
'en': en,
'zh-CN': zhCN,
'zh': zhCN,
'fr': fr, // Add new language
};
// ...
}
}
```
## Best Practices
1. **Keep keys descriptive**: Use clear, hierarchical key names
2. **Consistent naming**: Follow the established pattern for similar elements
3. **Fallback text**: Always provide fallback text in HTML for graceful degradation
4. **Context-aware**: Group related translations logically
5. **Parameter usage**: Use parameters for dynamic content instead of string concatenation
6. **Testing**: Test with different languages to ensure UI layout works properly
## RTL Language Support
The system includes framework support for RTL languages:
```javascript
// Check if current language is RTL
if (i18n.isRTL()) {
document.documentElement.setAttribute('dir', 'rtl');
document.body.classList.add('rtl');
}
```
Add CSS for RTL support:
```css
.rtl {
direction: rtl;
}
.rtl .some-element {
text-align: right;
margin-right: 0;
margin-left: auto;
}
```