npm package: @kajambiya/i18n-config
Description: Shared i18next configuration for multiple portals
Author: ayinza
Latest version: 1.0.2

# ayinza-i18n-config

Shared i18next configuration and formatting utilities for Ayinza portals.

This package centralizes i18n initialization, sensible defaults, and a set of
formatters (currency, number, percent, date/time, relative time) that are
integrated with i18next's interpolation system. It also provides React hooks
for easy consumption in React apps.

## Table of contents

- About
- Installation
- Quick start
- API
- Configuration
- Examples
- Testing
- Development
- License

## About

The library bundles a default i18n configuration (detection, backend, namespaces,
and formatters) and exposes helpers to initialize i18next, access the global
i18n instance, and consume localization + formatting helpers in React
components.

It is intentionally lightweight and designed to be used as a shared
dependency across multiple portals that want consistent localization behavior.

## Installation

Install the package and peer dependencies (peer dependencies are required by
consumers and not bundled):

```bash
# Using npm
npm install @kajambiya/i18n-config i18next react react-i18next

# Using yarn
yarn add @kajambiya/i18n-config i18next react react-i18next
```

Also install the optional runtime backends used by this package (the package
declares them as dependencies):

```bash
npm install i18next-http-backend i18next-browser-languagedetector
```

Note: This package declares `i18next`, `react`, and `react-i18next` as
peerDependencies — install versions compatible with your app.

## Quick start

Initialize i18n at application startup (for example in `src/main.tsx` or
`src/index.tsx` in a React app):

```ts
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { initializeI18n } from "@kajambiya/i18n-config";

// Optional: pass overrides to customize backend, supported languages, or
// formatters.
initializeI18n({
  config: {
    portalName: "My Portal",
    backend: {
      loadPath: "/locales/{{lng}}/{{ns}}.json",
      customHeaders: { "X-Portal": "my-portal" },
    },
    supportedLngs: ["en", "ar", "fr"],
  },
})
  .then(() => {
    const root = createRoot(document.getElementById("root")!);
    root.render(<App />);
  })
  .catch((err) => console.error(err));
```

The function returns the initialized i18next instance and also registers a set
of custom formatters so you may use them inside translations (interpolation
formatters) or via the provided hooks.

## API

Top-level exports (from `src/index.ts`):

- `initializeI18n(options?: I18nInitOptions): Promise<i18n>` — initialize the
  i18next instance with defaults merged with your overrides.
- `getI18nInstance(): i18n` — access the i18next singleton.
- `getFormatters(): I18nFormatters` — get the formatter instance (throws if
  not initialized).
- `defaultConfig` — the default configuration object used by
  `initializeI18n`.
- `useFormatting()` — React hook providing formatting helpers bound to the
  current language.
- `useI18n()` — combined hook returning both `useTranslation()` props and
  formatting helpers.
- Re-exports: `useTranslation`, `Trans`, `Translation` from `react-i18next`.

Types exported (from `src/types.ts`):

- `I18nConfig` — top-level configuration object shape.
- `I18nInitOptions` — options for `initializeI18n`.
- `FormattersConfig`, `LocaleMapping` — configuration shapes for formatters.

Formatters class: `I18nFormatters` provides methods such as:

- `formatCurrency(amount, language, currency?, options?)`
- `formatNumber(value, language, options?)`
- `formatPercent(value, language, options?)`
- `formatDate(date, language, options?)`
- `formatTime(date, language, options?)`
- `formatDateTime(date, language, options?)`
- `formatRelativeTime(value, unit, language, options?)`

These are already wired into i18next as interpolation formatters named
`currency`, `number`, `percent`, `date`, `time`, `datetime`, and `relative`.

## Configuration

`defaultConfig` (summary):

- backend: { loadPath }
- detection: browser language detection configuration
- fallbackLng: `en`
- supportedLngs: `["en","ar","fr","es"]`
- defaultNS / ns: namespaces used
- interpolation.escapeValue: false
- formatters: default formatter configuration (defaultCurrency `USD`)

You can override only the pieces you need — `initializeI18n` merges defaults
with your partial config.

## Examples

Use translation + formatting together in a React component:

```tsx
import React from "react";
import { useI18n } from "@kajambiya/i18n-config";

function Price({ amount }: { amount: number }) {
  const { t, formatCurrency } = useI18n();

  return (
    <div>
      <h3>{t("priceHeading")}</h3>
      <p>{formatCurrency(amount)}</p>
    </div>
  );
}
```

Using formatters directly (non-React):

```ts
import { initializeI18n, getFormatters } from "@kajambiya/i18n-config";

async function start() {
  await initializeI18n();
  const fmt = getFormatters();
  console.log(fmt.formatCurrency(19.99, "en", "USD"));
}
```

Using interpolation in translation strings (example `en/common.json`):

```json
{
  "price": "{{value, currency}}"
}
```

Then `t('price', { value: 19.99, currency: 'EUR' })` will use the registered
`currency` formatter.

## Testing

There are unit tests for `I18nFormatters` located in `src/formatters.test.ts`.
Run tests with Jest:

```bash
npm test
# or, directly
npx jest
```

Note: this repository includes Jest devDependencies configured for TypeScript.

## Development

- Build: `npm run build` (compiles to `dist/` using `tsc`)
- Watch: `npm run build:watch`

If you intend to contribute, please run tests and add coverage for new
features.

## License

MIT — see the `LICENSE` file in this repository.

## Next steps & suggestions

- Add CI (GitHub Actions) to run tests and build on push/PR.
- Add usage examples / Storybook snippets for React components that depend on
  formatting.
- Consider publishing with changelog and semantic-release for automated
  releases.