JSPM

wild-js-translations

1.0.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • 0
  • Score
    100M100P100Q15771F
  • License MIT

A flexible, database-backed translation system with automatic translation via OpenAI

Package Exports

  • wild-js-translations
  • wild-js-translations/dist/index.js
  • wild-js-translations/dist/index.mjs

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (wild-js-translations) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

wild-js-translations

A flexible, database-backed translation system for React applications with automatic translation support via OpenAI.

Features

  • 🌍 Multi-language support - Built-in support for 9 languages
  • 🔄 Auto-translation - Automatic translation via OpenAI when translations are missing
  • 💾 Database-backed - Store translations in your database for persistence
  • Performance optimized - Smart caching and lazy loading
  • 🎯 Type-safe - Full TypeScript support
  • 🔌 Adapter pattern - Plug in any data source (Supabase, REST API, memory)
  • 📦 Zustand integration - Persistent language preferences
  • 🎨 React hooks - Simple, intuitive API

Installation

npm install wild-js-translations
# or
yarn add wild-js-translations
# or
pnpm add wild-js-translations

Quick Start

1. Basic Usage with Memory Adapter

import { TranslationProvider, useTranslation, MemoryAdapter } from 'wild-js-translations';

// Create a simple in-memory adapter
const adapter = new MemoryAdapter([
  { language: 'fr', key: 'Hello', value: 'Bonjour' },
  { language: 'es', key: 'Hello', value: 'Hola' }
]);

function App() {
  return (
    <TranslationProvider config={{ adapter }}>
      <MyComponent />
    </TranslationProvider>
  );
}

function MyComponent() {
  const { t, language, setLanguage } = useTranslation();
  
  return (
    <div>
      <h1>{t('Hello')}</h1>
      <button onClick={() => setLanguage('fr')}>French</button>
      <button onClick={() => setLanguage('es')}>Spanish</button>
    </div>
  );
}

2. Supabase Integration with Auto-Translation

import { createClient } from '@supabase/supabase-js';
import { TranslationProvider, SupabaseAdapter } from 'wild-js-translations';

const supabase = createClient('YOUR_URL', 'YOUR_KEY');

const adapter = new SupabaseAdapter(
  supabase,
  'translations', // table name
  process.env.OPENAI_API_KEY // for auto-translation
);

function App() {
  return (
    <TranslationProvider 
      config={{ 
        adapter,
        autoTranslate: true,
        defaultLanguage: 'en'
      }}
    >
      <YourApp />
    </TranslationProvider>
  );
}

Database Schema

If using Supabase or a similar database, create a translations table:

CREATE TABLE translations (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  language VARCHAR(2) NOT NULL,
  key TEXT NOT NULL,
  value TEXT NOT NULL,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW(),
  UNIQUE(language, key)
);

CREATE INDEX idx_translations_language ON translations(language);
CREATE INDEX idx_translations_key ON translations(key);

API Reference

useTranslation()

The main hook for accessing translations:

const { t, language, setLanguage, isLoading } = useTranslation();
  • t(key: string): string - Translate a key
  • language: Language - Current language
  • setLanguage(language: Language): void - Change language
  • isLoading: boolean - Loading state

TranslationProvider

Wrap your app with the provider:

<TranslationProvider config={config}>
  {children}
</TranslationProvider>

Config options:

  • adapter: TranslationAdapter - Required. Data source adapter
  • defaultLanguage?: Language - Default language (default: 'en')
  • autoTranslate?: boolean - Enable auto-translation (default: true)
  • onTranslationError?: (error: Error) => void - Error handler

Supported Languages

type Language = 'en' | 'fr' | 'de' | 'it' | 'es' | 'pt' | 'ru' | 'zh' | 'ja';

Creating Custom Adapters

Implement the TranslationAdapter interface:

import { TranslationAdapter, Language, Translation } from 'wild-js-translations';

class MyCustomAdapter implements TranslationAdapter {
  async getTranslations(language: Language): Promise<Translation[]> {
    // Fetch translations from your source
  }

  async saveTranslation(language: Language, key: string, value: string): Promise<void> {
    // Save a new translation
  }

  async autoTranslate(text: string, targetLanguage: Language): Promise<string> {
    // Optional: Implement auto-translation
  }
}

Auto-Translation

When enabled, missing translations are automatically generated:

  1. User requests a translation that doesn't exist
  2. The English text (key) is sent to OpenAI
  3. Translation is saved to the database
  4. UI updates automatically when translation arrives
// This will auto-translate if French translation is missing
const { t } = useTranslation();
setLanguage('fr');
return <h1>{t('Welcome to our application')}</h1>;

Performance Optimization

Caching

Translations are cached in memory per language to avoid repeated database queries.

Lazy Loading

Translations are loaded on-demand when a language is selected.

Persistence

Language preference is persisted to localStorage via Zustand.

Advanced Usage

Clearing Cache

import { TranslationService } from 'wild-js-translations';

const service = new TranslationService(adapter);
service.clearCache('fr'); // Clear French translations
service.clearCache(); // Clear all cached translations

Direct Store Access

import { createTranslationStore } from 'wild-js-translations';

const useStore = createTranslationStore('en');
const { language, setLanguage } = useStore();

Translation Events

Listen for translation updates:

window.addEventListener('translation-updated', (event) => {
  console.log('New translation:', event.detail);
  // { language: 'fr', key: 'Hello', value: 'Bonjour' }
});

Examples

Check the /examples directory for:

  • Basic usage with memory adapter
  • Supabase integration
  • Custom adapter implementation
  • Auto-translation setup

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT

Credits

Originally developed for the Wink dating feature in the Noxx restaurant management platform.