UNPKG

language-management-lib

Version:

A TypeScript library for managing language translations in applications with URL parameter support.

390 lines (296 loc) 10.6 kB
# Language Management Library A powerful TypeScript library for managing language translations in applications with automatic URL parameter detection and React support. ## Features - 🌍 **Multi-language Support**: Easy management of multiple language translations - 🔗 **URL Parameter Integration**: Automatic language detection from URL parameters (`?lng=en` or `?language=en`) - ⚛️ **React Hook**: Built-in `useTranslation` hook for React applications - 🔄 **Dynamic Translation Loading**: Add new translations at runtime - 🎯 **TypeScript Support**: Fully typed with excellent IntelliSense support - 🏃‍♂️ **Lightweight**: Minimal dependencies, works in both browser and Node.js environments - 🔧 **Framework Agnostic**: Core functionality works with any JavaScript framework - 🛡️ **Fallback System**: Automatic fallback to default language when translations are missing ## Installation ```bash npm install language-management-lib ``` For React projects, you'll also need React 16.8+ (for hooks support): ```bash npm install react react-dom ``` ## Quick Start ### Basic Usage ```typescript import { SetLanguage } from "language-management-lib"; const languages = { en: { welcome: "Welcome to our website!", login: "Login", about: "About Us", }, es: { welcome: "¡Bienvenido a nuestro sitio web!", login: "Iniciar Sesión", about: "Acerca de Nosotros", }, fr: { welcome: "Bienvenue sur notre site web!", login: "Connexion", about: "À Propos", }, }; // Initialize with default language (automatically detects from URL) const languageManager = new SetLanguage(languages, "en"); // Get translations console.log(languageManager.translate("welcome")); // Output: "Welcome to our website!" (or URL language if detected) // Change language languageManager.setLanguage("es"); console.log(languageManager.translate("welcome")); // Output: "¡Bienvenido a nuestro sitio web!" ``` ### React Usage ```tsx import React from "react"; import { SetLanguage, useTranslation } from "language-management-lib"; const languages = { en: { welcome: "Welcome!", login: "Login", about: "About Us", }, es: { welcome: "¡Bienvenido!", login: "Iniciar Sesión", about: "Acerca de Nosotros", }, }; const languageManager = new SetLanguage(languages, "en"); function App() { const { t, currentLanguage, changeLanguage, availableLanguages } = useTranslation(languageManager); return ( <div> <h1>{t("welcome")}</h1> <p>Current language: {currentLanguage}</p> {/* Language selector */} <div> {availableLanguages.map((lang) => ( <button key={lang} onClick={() => changeLanguage(lang)} style={{ backgroundColor: currentLanguage === lang ? "#007bff" : "#f8f9fa", margin: "0 5px", padding: "8px 12px", }} > {lang.toUpperCase()} </button> ))} </div> <button>{t("login")}</button> <p>{t("about")}</p> </div> ); } export default App; ``` ## URL Parameter Integration The library automatically detects language from URL parameters on initialization: - `?lng=es` - Sets language to Spanish - `?language=fr` - Sets language to French - Both parameter formats are supported for maximum flexibility ```typescript // Language will be automatically detected from URL on initialization const languageManager = new SetLanguage(languages, "en"); // URL: https://example.com?lng=es console.log(languageManager.getCurrentLanguage()); // Output: "es" // Programmatically change language and optionally update URL languageManager.setLanguage("fr", true); // Updates URL to ?lng=fr languageManager.setLanguage("en", false); // Changes language without updating URL ``` ## API Reference ### SetLanguage Class #### Constructor ```typescript new SetLanguage<T>(languages: T, defaultLanguage?: string) ``` **Parameters:** - `languages`: Object containing all language translations - `defaultLanguage`: Default language code (defaults to "en") #### Methods ##### `translate(key: string): string` Get translation for a key. Falls back to default language if translation is missing. ```typescript languageManager.translate("welcome"); // Returns translated string ``` ##### `setLanguage(language: string, updateURL?: boolean): void` Change current language and optionally update URL parameter. ```typescript languageManager.setLanguage("es"); // Changes language languageManager.setLanguage("fr", true); // Changes language and updates URL languageManager.setLanguage("de", false); // Changes language without updating URL ``` ##### `getCurrentLanguage(): string` Get the current active language code. ```typescript const currentLang = languageManager.getCurrentLanguage(); // Returns: "en", "es", etc. ``` ##### `getAvailableLanguages(): string[]` Get array of all available language codes. ```typescript const languages = languageManager.getAvailableLanguages(); // Returns: ["en", "es", "fr"] ``` ##### `addTranslations(language: string, translations: Record<string, string>): void` Add new translations for a language (creates language if it doesn't exist). ```typescript languageManager.addTranslations("de", { welcome: "Willkommen!", login: "Anmelden", }); ``` ##### `getLanguageData(): T` Get the complete language data object. ```typescript const allData = languageManager.getLanguageData(); ``` ### useTranslation Hook (React) ```typescript const { t, // Translation function: (key: string) => string currentLanguage, // Current language code: string changeLanguage, // Change language: (lang: string, updateURL?: boolean) => void addTranslations, // Add translations: (lang: string, translations: Record<string, string>) => void availableLanguages, // Available languages: string[] } = useTranslation(languageManager); ``` ## Advanced Examples ### Adding Translations Dynamically ```typescript // Add new language at runtime languageManager.addTranslations("de", { welcome: "Willkommen!", login: "Anmelden", about: "Über uns", }); // Add more translations to existing language languageManager.addTranslations("de", { contact: "Kontakt", }); languageManager.setLanguage("de"); console.log(languageManager.translate("welcome")); // Output: "Willkommen!" ``` ### Fallback Handling ```typescript // If a translation is missing, it automatically falls back to the default language const languages = { en: { welcome: "Welcome!", goodbye: "Goodbye!", contact: "Contact Us", }, es: { welcome: "¡Bienvenido!", // Missing 'goodbye' and 'contact' }, }; const manager = new SetLanguage(languages, "en"); manager.setLanguage("es"); console.log(manager.translate("welcome")); // Output: "¡Bienvenido!" console.log(manager.translate("goodbye")); // Output: "Goodbye!" (fallback to English) console.log(manager.translate("contact")); // Output: "Contact Us" (fallback to English) console.log(manager.translate("missing")); // Output: "missing" (returns key if not found) ``` ### Using with Pre-defined Language Object ```typescript import { SetLanguage, lng } from "language-management-lib"; // Use the built-in sample language object const languageManager = new SetLanguage(lng, "en"); console.log(languageManager.translate("welcome")); // Uses built-in translations console.log(languageManager.getAvailableLanguages()); // ["en", "ka", "de"] ``` ### React Hook with Dynamic Updates ```tsx import React, { useEffect } from "react"; import { SetLanguage, useTranslation } from "language-management-lib"; const languageManager = new SetLanguage( { en: { title: "My App", loading: "Loading..." }, es: { title: "Mi Aplicación", loading: "Cargando..." }, }, "en" ); function MyComponent() { const { t, changeLanguage, addTranslations, currentLanguage } = useTranslation(languageManager); useEffect(() => { // Dynamically load more translations addTranslations("fr", { title: "Mon Application", loading: "Chargement...", }); }, [addTranslations]); return ( <div> <h1>{t("title")}</h1> <p>{t("loading")}</p> <select value={currentLanguage} onChange={(e) => changeLanguage(e.target.value, true)} > <option value="en">English</option> <option value="es">Español</option> <option value="fr">Français</option> </select> </div> ); } ``` ## TypeScript Support The library is fully typed and provides excellent IntelliSense support: ```typescript // Type-safe language definitions const languages = { en: { welcome: "Welcome!", login: "Login", }, es: { welcome: "¡Bienvenido!", login: "Iniciar Sesión", }, } as const; // TypeScript will infer the correct types const manager = new SetLanguage(languages, "en"); // IntelliSense will suggest available translation keys manager.translate("welcome"); // ✅ TypeScript knows this key exists manager.translate("invalid"); // ⚠️ TypeScript will warn about unknown key ``` ## Browser Support - **Modern Browsers**: Chrome 60+, Firefox 55+, Safari 12+, Edge 79+ - **Node.js**: 12.0.0+ - **TypeScript**: 4.0+ - **React**: 16.8+ (for hooks support) ## Performance Notes - Lightweight: ~3KB gzipped - No external dependencies for core functionality - Efficient translation lookup with O(1) complexity - React hooks use proper memoization to prevent unnecessary re-renders ## Contributing We welcome contributions! Please follow these steps: 1. Fork the repository 2. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## License MIT License - see [LICENSE](LICENSE) file for details. ## Changelog ### v1.0.0 - Initial release - Core SetLanguage class with TypeScript support - Automatic URL parameter detection (`?lng=` and `?language=`) - React hook for easy integration - Dynamic translation loading - Fallback system for missing translations - Comprehensive examples and documentation