dphelper
Version:
dphelper devtools for developers
293 lines (225 loc) • 8.31 kB
Markdown
# i18n
Internationalization and localization utilities for multi-language support, including translations, pluralization, date/number formatting, and relative time.
## Functions
| Function | Description | Example |
|----------|-------------|---------|
| `setLocale` | Set current locale | `dphelper.i18n.setLocale('it')` |
| `getLocale` | Get current locale | `dphelper.i18n.getLocale()` |
| `t` | Translate a key | `dphelper.i18n.t('hello', { name: 'World' })` |
| `addTranslations` | Add translation strings | `dphelper.i18n.addTranslations('it', { hello: 'Ciao!' })` |
| `pluralize` | Get pluralized string | `dphelper.i18n.pluralize(5, { one: 'item', other: 'items' })` |
| `number` | Format number by locale | `dphelper.i18n.number(1234.56, 'de-DE', { currency: 'EUR' })` |
| `date` | Format date by locale | `dphelper.i18n.date(new Date(), 'en-US', { dateStyle: 'long' })` |
| `relativeTime` | Get relative time string | `dphelper.i18n.relativeTime(Date.now() - 3600000)` |
| `list` | Format list by locale | `dphelper.i18n.list(['a', 'b', 'c'], 'en')` |
| `getSupportedLocales` | Get list of locales | `dphelper.i18n.getSupportedLocales()` |
## Description
Complete internationalization module featuring:
- **Translation System** - Key-based translations with variable interpolation
- **Pluralization** - Support for multiple plural forms (zero, one, two, few, many, other)
- **Locale-aware Formatting** - Numbers, dates, and lists formatted per locale
- **Relative Time** - "2 hours ago", "in 5 minutes" style strings
- **Auto-detection** - Automatic browser locale detection
- **Extensible** - Add custom translations for any language
## Usage Examples
### Basic Translation
```javascript
// Set locale
dphelper.i18n.setLocale('en');
// Simple translation
console.log(dphelper.i18n.t('hello')); // "Hello {name}!"
console.log(dphelper.i18n.t('hello', { name: 'World' })); // "Hello World!"
console.log(dphelper.i18n.t('goodbye')); // "Goodbye!"
// Change locale
dphelper.i18n.setLocale('it');
console.log(dphelper.i18n.t('hello', { name: 'Mario' })); // "Ciao Mario!"
```
### Adding Custom Translations
```javascript
// Add Italian translations
dphelper.i18n.addTranslations('it', {
'hello': 'Ciao {name}!',
'goodbye': 'Arrivederci!',
'welcome': 'Benvenuto nella nostra app!',
'items_count': 'Hai {count} oggetti'
});
// Add Spanish translations
dphelper.i18n.addTranslations('es', {
'hello': '¡Hola {name}!',
'goodbye': '¡Adiós!',
'welcome': '¡Bienvenido a nuestra aplicación!'
});
// Use translations
dphelper.i18n.setLocale('es');
console.log(dphelper.i18n.t('welcome')); // "¡Bienvenido a nuestra aplicación!"
```
### Pluralization
```javascript
dphelper.i18n.setLocale('en');
// Basic pluralization
console.log(dphelper.i18n.pluralize(0, { one: 'item', other: 'items' }));
// "items" (uses 'other' for 0 in English)
console.log(dphelper.i18n.pluralize(1, { one: 'item', other: 'items' }));
// "item"
console.log(dphelper.i18n.pluralize(5, { one: 'item', other: 'items' }));
// "items"
// With translation keys
dphelper.i18n.addTranslations('en', {
'items': '{count} item',
'items_plural': '{count} items'
});
// In a message
const count = 10;
const message = count === 1
? dphelper.i18n.t('items', { count })
: dphelper.i18n.t('items_plural', { count });
```
### Number Formatting
```javascript
dphelper.i18n.setLocale('en-US');
// Basic number formatting
console.log(dphelper.i18n.number(1234.56)); // "1,234.56"
// Currency
console.log(dphelper.i18n.number(1234.56, 'en-US', {
style: 'currency',
currency: 'USD'
})); // "$1,234.56"
console.log(dphelper.i18n.number(1234.56, 'de-DE', {
style: 'currency',
currency: 'EUR'
})); // "1.234,56 €"
// Percentages
console.log(dphelper.i18n.number(0.75, 'en-US', { style: 'percent' })); // "75%"
// Different locales
console.log(dphelper.i18n.number(1234.56, 'ja-JP')); // "1,234.56"
console.log(dphelper.i18n.number(1234.56, 'fr-FR')); // "1 234,56"
```
### Date Formatting
```javascript
const date = new Date('2026-03-15T14:30:00Z');
// Date only
console.log(dphelper.i18n.date(date, 'en-US', { dateStyle: 'short' }));
// "3/15/2026"
console.log(dphelper.i18n.date(date, 'en-US', { dateStyle: 'long' }));
// "March 15, 2026"
// Time only
console.log(dphelper.i18n.date(date, 'en-US', { timeStyle: 'short' }));
// "2:30 PM"
// Full date and time
console.log(dphelper.i18n.date(date, 'it-IT', {
dateStyle: 'full',
timeStyle: 'short' }));
// "domenica 15 marzo 2026, 14:30"
// Custom format
console.log(dphelper.i18n.date(date, 'en-GB', {
year: 'numeric',
month: 'long',
day: 'numeric'
})); // "15 March 2026"
```
### Relative Time
```javascript
const now = Date.now();
// Past
console.log(dphelper.i18n.relativeTime(now - 60000)); // "1 minute ago"
console.log(dphelper.i18n.relativeTime(now - 3600000)); // "1 hour ago"
console.log(dphelper.i18n.relativeTime(now - 86400000)); // "1 day ago"
// Future
console.log(dphelper.i18n.relativeTime(now + 60000)); // "in 1 minute"
console.log(dphelper.i18n.relativeTime(now + 3600000)); // "in 1 hour"
// With locale
console.log(dphelper.i18n.relativeTime(now - 3600000, 'es')); // "hace 1 hora"
console.log(dphelper.i18n.relativeTime(now + 3600000, 'es')); // "dentro de 1 hora"
```
### List Formatting
```javascript
const items = ['Apple', 'Banana', 'Orange'];
// Basic list
console.log(dphelper.i18n.list(items, 'en'));
// "Apple, Banana, and Orange"
console.log(dphelper.i18n.list(items, 'it'));
// "Apple, Banana e Orange"
// With options
console.log(dphelper.i18n.list(items, 'en', { type: 'disjunction' }));
// "Apple, Banana, or Orange"
```
## Advanced Usage
### Complete i18n Setup
```javascript
// Initialize i18n with custom translations
function initI18n(locale) {
// Set locale
dphelper.i18n.setLocale(locale);
// Add translations for common strings
dphelper.i18n.addTranslations(locale, {
'app.name': 'My Application',
'app.tagline': 'Building the future',
'nav.home': 'Home',
'nav.about': 'About',
'nav.contact': 'Contact',
'common.save': 'Save',
'common.cancel': 'Cancel',
'common.delete': 'Delete',
'common.loading': 'Loading...',
'error.generic': 'An error occurred',
'error.network': 'Network error. Please try again.',
'user.greeting': 'Welcome, {name}!',
'items.count': '{count, plural, =0{No items} one{# item} other{# items}}'
});
}
// Usage
initI18n('en');
console.log(dphelper.i18n.t('user.greeting', { name: 'John' }));
```
### Dynamic Locale Switching
```javascript
class I18nManager {
constructor() {
this.locale = 'en';
}
async setLocale(locale) {
// Fetch translations from server
const translations = await fetch(`/api/translations/${locale}`)
.then(r => r.json());
// Add translations
dphelper.i18n.addTranslations(locale, translations);
// Set locale
dphelper.i18n.setLocale(locale);
this.locale = locale;
// Dispatch event for UI update
window.dispatchEvent(new CustomEvent('localechange', { detail: { locale } }));
}
t(key, vars) {
return dphelper.i18n.t(key, vars);
}
formatNumber(value, options) {
return dphelper.i18n.number(value, this.locale, options);
}
formatDate(date, options) {
return dphelper.i18n.date(date, this.locale, options);
}
}
const i18n = new I18nManager();
```
### React-like Translation Component
```javascript
// Simple translation helper for templates
function tr(key, vars) {
return dphelper.i18n.t(key, vars);
}
// Usage in templates
const template = `
<h1>${tr('app.name')}</h1>
<p>${tr('user.greeting', { name: userName })}</p>
<p>${tr('items.count', { count: itemCount })}</p>
<p>${tr('common.lastUpdated', { date: dphelper.i18n.date(lastUpdate) })}</p>
`;
```
## Details
- **Author:** Dario Passariello
- **Version:** 0.0.1
- **Creation Date:** 20260313
- **Last Modified:** 20260313
- **Environment:** Works in both client and server environments
---
*Automatically generated document*