JSPM

@logistically/i18n-react-core

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

React integration for @logistically/i18n with state management agnostic design

Package Exports

  • @logistically/i18n-react-core
  • @logistically/i18n-react-core/adapters/context
  • @logistically/i18n-react-core/adapters/context.esm
  • @logistically/i18n-react-core/adapters/redux
  • @logistically/i18n-react-core/adapters/redux.esm
  • @logistically/i18n-react-core/adapters/zustand
  • @logistically/i18n-react-core/adapters/zustand.esm
  • @logistically/i18n-react-core/react-native
  • @logistically/i18n-react-core/ssr

Readme

@logistically/i18n-react-core

React integration for @logistically/i18n with state management agnostic design, supporting both React Web and React Native.

๐Ÿš€ Features

Core Features:

  • โœ… State Management Agnostic - Use with Context API, Zustand, Redux, or custom solutions
  • โœ… React 18+ Support - Full compatibility with modern React
  • โœ… TypeScript First - Complete type safety
  • โœ… Tree Shaking - Optimized bundle sizes
  • โœ… SSR Support - Server-side rendering utilities
  • โœ… React Native Support - Cross-platform compatibility

Translation Features:

  • โœ… Multi-locale Support - Easy locale switching
  • โœ… Parameter Interpolation - Dynamic content support
  • โœ… Pluralization - Complex plural rules
  • โœ… RTL Support - Right-to-left language support
  • โœ… Date/Number Formatting - Locale-aware formatting
  • โœ… Error Handling - Graceful fallbacks

๐Ÿ“ฆ Installation

npm install @logistically/i18n-react-core

๐ŸŽฏ Quick Start

Basic Usage (Web):

import React from 'react';
import { 
  TranslationProvider, 
  TranslatedText, 
  useTranslation 
} from '@logistically/i18n-react-core';

const config = {
  defaultLocale: 'en',
  supportedLocales: ['en', 'fr', 'es'],
  translationsPath: 'src/translations',
  serviceName: 'my-app'
};

const App = () => (
  <TranslationProvider config={config}>
    <MyComponent />
  </TranslationProvider>
);

const MyComponent = () => {
  const { t, setLocale } = useTranslation();
  
  return (
    <div>
      <h1><TranslatedText translationKey="welcome.title" /></h1>
      <TranslatedText translationKey="welcome.message" params={{ name: 'John' }} />
      <button onClick={() => setLocale('fr')}>Switch to French</button>
    </div>
  );
};

React Native Usage:

import React from 'react';
import { View } from 'react-native';
import { 
  TranslationProvider, 
  TranslatedTextRN, 
  useTranslation 
} from '@logistically/i18n-react-core/react-native';

const config = {
  defaultLocale: 'en',
  supportedLocales: ['en', 'fr', 'es'],
  translationsPath: 'src/translations',
  serviceName: 'my-app'
};

const App = () => (
  <TranslationProvider config={config}>
    <MyComponent />
  </TranslationProvider>
);

const MyComponent = () => {
  const { t, setLocale } = useTranslation();
  
  return (
    <View>
      <TranslatedTextRN translationKey="welcome.title" />
      <TranslatedTextRN translationKey="welcome.message" params={{ name: 'John' }} />
    </View>
  );
};

๐Ÿ”ง API Reference

Hooks:

useTranslation()

const { 
  t,                    // Translation function
  translate,            // Direct translation
  translatePlural,      // Plural translation
  formatDate,          // Date formatting
  formatNumber,        // Number formatting
  getTextDirection,    // Text direction
  isLoading,           // Loading state
  error,               // Error state
  locale,              // Current locale
  setLocale,           // Change locale
  isRTLLocale,         // RTL detection
  reloadTranslations,  // Reload translations
  clearCache           // Clear cache
} = useTranslation();

useLocale()

const { 
  locale,              // Current locale
  setLocale,           // Change locale
  supportedLocales,    // Available locales
  isRTL,               // Current RTL state
  direction,           // Text direction
  isRTLLocale          // RTL detection function
} = useLocale();

Components:

TranslatedText

<TranslatedText 
  translationKey="translation.key"
  params={{ name: 'John', count: 5 }}
  locale="fr"
  fallback="Fallback text"
  className="my-class"
  style={{ color: 'red' }}
  debug={true}
/>

Convenience Components (Web):

  • TranslatedSpan, TranslatedDiv, TranslatedP
  • TranslatedH1, TranslatedH2, TranslatedH3
  • TranslatedLabel, TranslatedButton

Convenience Components (React Native):

  • TranslatedTextRN, TranslatedView
  • TranslatedHeading, TranslatedSubheading
  • TranslatedBody, TranslatedCaption

SSR Utilities:

import { SSRTranslationUtils } from '@logistically/i18n-react-core/ssr';

const utils = new SSRTranslationUtils(config);

// Get translations for server-side rendering
const translations = await utils.getTranslation('en');

// Create SSR context
const context = await utils.createSSRContext('en');

// Serialize/deserialize context
const serialized = utils.serializeContext(context);
const deserialized = utils.deserializeContext(serialized);

// Next.js utilities
const serverTranslations = await utils.getServerSideTranslations('en');
const serverUtils = await utils.getServerTranslation('en');
const { t } = serverUtils; // Use the t function from serverUtils

๐Ÿ—๏ธ Architecture

Package Structure:

@logistically/i18n-react-core/
โ”œโ”€โ”€ dist/
โ”‚   โ”œโ”€โ”€ index.js              # Main bundle (Web)
โ”‚   โ”œโ”€โ”€ react-native.js       # React Native bundle
โ”‚   โ”œโ”€โ”€ ssr.js               # SSR utilities
โ”‚   โ””โ”€โ”€ adapters/            # State management adapters
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ core/                # Core translation logic
โ”‚   โ”œโ”€โ”€ adapters/            # State management adapters
โ”‚   โ”œโ”€โ”€ components/          # React components
โ”‚   โ”œโ”€โ”€ ssr/                 # SSR utilities
โ”‚   โ”œโ”€โ”€ types/               # TypeScript definitions
โ”‚   โ””โ”€โ”€ react-native/        # React Native specific

Bundle Sizes:

  • Main Bundle (Web): ~20KB (gzipped: ~6-8KB)
  • React Native Bundle: ~19KB (gzipped: ~6-7KB)
  • SSR Utilities: ~1.5KB (gzipped: ~0.5KB)
  • Total: ~40KB (gzipped: ~12-15KB)

๐Ÿงช Testing

Test Coverage:

  • โœ… Core Functionality: Translation logic, state management (92.53%)
  • โœ… React Integration: Hooks, components, context (76.74%)
  • โœ… SSR Support: Server-side utilities (comprehensive coverage)
  • โœ… Error Handling: Graceful fallbacks
  • โœ… Integration Tests: React apps, Next.js, performance
  • ๐ŸŸก React Native: Platform-specific testing (80% coverage)

Running Tests:

npm test                    # Run all tests
npm run test:coverage      # Run with coverage
npm run test:watch         # Watch mode

๐Ÿ”„ State Management

Default: Context API

The package uses React Context API by default, but supports multiple state management solutions:

Available Adapters:

// Context API (default) โœ…
import { TranslationProvider } from '@logistically/i18n-react-core';

// Zustand (placeholder - coming soon)
import { createZustandAdapter } from '@logistically/i18n-react-core/adapters/zustand';

// Redux (placeholder - coming soon)
import { createReduxAdapter } from '@logistically/i18n-react-core/adapters/redux';

// Custom adapter
const customAdapter = (core) => ({
  getState: () => core.getState(),
  getActions: () => core.getActions(),
  subscribe: (listener) => core.subscribe(listener),
});

๐ŸŒ Internationalization Features

Supported Locales:

  • Western Languages: English, French, Spanish, German, etc.
  • RTL Languages: Arabic, Hebrew, Persian, etc.
  • Asian Languages: Chinese, Japanese, Korean, etc.

Pluralization:

// Simple plural
<TranslatedText translationKey="user.count" params={{ count: 5 }} />

// Complex plural rules
<TranslatedText translationKey="item.count" params={{ count: 21 }} />

RTL Support:

const { isRTL, direction } = useLocale();

// Automatic RTL detection
<div dir={direction}>
  <TranslatedText translationKey="welcome.message" />
</div>

๐Ÿš€ Performance

Optimizations:

  • Tree Shaking: Only include what you use
  • Lazy Loading: Load translations on demand
  • Caching: Intelligent translation caching
  • Bundle Splitting: Separate bundles for different use cases

Best Practices:

// โœ… Good: Use specific imports
import { TranslatedText } from '@logistically/i18n-react-core';

// โŒ Avoid: Import everything
import * as I18n from '@logistically/i18n-react-core';

// โœ… Good: Preload critical translations
await utils.preloadTranslations(['en', 'fr']);

// โœ… Good: Use fallbacks
<TranslatedText translationKey="missing.key" fallback="Default text" />

๐Ÿ”ง Configuration

TranslationConfig:

const config = {
  defaultLocale: 'en',
  supportedLocales: ['en', 'fr', 'es'],
  translationsPath: 'src/translations',
  serviceName: 'my-app', // Required field
  debug: {
    enabled: true,
    logMissingKeys: true,
    logPerformance: true,
  },
  interpolation: {
    prefix: '${',
    suffix: '}',
  },
  fallbackStrategy: 'default',
  cache: {
    enabled: true,
    ttl: 3600,
  },
  rtl: {
    enabled: true,
    autoDetect: true,
  },
  pluralization: {
    enabled: true,
    formatNumbers: true,
  },
};

Migration from react-i18next:

// Before (react-i18next)
import { useTranslation } from 'react-i18next';
const { t } = useTranslation();
t('welcome.message', { name: 'John' });

// After (@logistically/i18n-react-core)
import { useTranslation } from '@logistically/i18n-react-core';
const { t } = useTranslation();
t('welcome.message', { params: { name: 'John' } });

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ†˜ Support