Skip to content

Add localization support for a components #55

Open
@donskov

Description

@donskov

src/locales/en.json

{
  "title": "Hello"
}

src/utils/l10n.ts

import en from '../locales/en.json';

type ReplacerType = {
  pattern: string;
  replacer: any;
};

const MESSAGES_ALL = {
  en,
};

export type SupportedMessagesType = keyof typeof MESSAGES_ALL;

export class Localization {
  private locale: string;

  private bundle: { [id: string]: string };

  constructor() {
    const language = window.navigator.language.slice(0, 2).toLowerCase();

    this.setLocale(language as any);
  }

  setLocale = (locale: SupportedMessagesType) => {
    this.locale = locale && MESSAGES_ALL[locale] ? locale : 'en';
    this.bundle = MESSAGES_ALL[this.locale];
  };

  getLocale = () => this.locale;

  getString(id: string, replacer?: ReplacerType): string | any[] {
    const value = this.bundle[id];

    if (!value) {
      return '';
    }

    if (!replacer) {
      return value;
    }

    const splitted = value.split(replacer.pattern);

    if (splitted.length > 1) {
      return [
        splitted[0],
        replacer.replacer,
        splitted[1],
      ];
    }

    return value;
  }
}

export const l10n = new Localization();
export const getString = l10n.getString.bind(l10n);

Usage:

import { getString } from'../utils/l10n';

getString('title'); // => 'Hello'

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions