Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add localization support for a components #55

Open
donskov opened this issue Aug 17, 2020 · 0 comments
Open

Add localization support for a components #55

donskov opened this issue Aug 17, 2020 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@donskov
Copy link
Collaborator

donskov commented Aug 17, 2020

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'
@donskov donskov self-assigned this Aug 17, 2020
@donskov donskov added the enhancement New feature or request label Aug 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant