Skip to content

Instantly share code, notes, and snippets.

@aliceklipper
Created April 1, 2017 14:12
Show Gist options
  • Save aliceklipper/9f84045861d2a186857fcd331b521af2 to your computer and use it in GitHub Desktop.
Save aliceklipper/9f84045861d2a186857fcd331b521af2 to your computer and use it in GitHub Desktop.
Abstract class for creating localizable React components (TS & MobX)
import * as React from 'react';
import { LocalizableStore } from './LocalizableStore';
export interface LocalizableProps {
l10n : LocalizableStore;
}
export abstract class Localizable<PropsType extends LocalizableProps, StateType> extends React.Component<PropsType, StateType> {
tl : (string : string) => string;
__ : (strings : TemplateStringsArray, ...props : any[]) => string;
fn : (fn : string, string : any) => string;
constructor (props : PropsType) {
super(props);
this.tl = this.props.l10n.tl.bind(this.props.l10n);
this.__ = this.props.l10n.__.bind(this.props.l10n);
this.fn = this.props.l10n.fn.bind(this.props.l10n);
}
}
import { observable } from 'mobx';
export interface LocalizableLanguage {
strings : { [key : string] : string };
fns : { [key : string] : (...args : any[]) => string };
}
export interface LocalizableStrings {
[key : string] : LocalizableLanguage;
}
export class LocalizableStore {
@observable lang = 'en_US';
private langs : LocalizableStrings;
constructor (strings : LocalizableStrings) {
this.langs = strings;
this.tl = this.tl.bind(this);
this.__ = this.__.bind(this);
this.fn = this.fn.bind(this);
}
tl (string : string) : string {
return this.langs[this.lang] && this.langs[this.lang].strings[string]
|| this.langs['en_US'] && this.langs['en_US'].strings[string]
|| string;
}
fn (fn : string, string : any) : string {
return this.langs[this.lang] && this.langs[this.lang].fns[fn] && this.langs[this.lang].fns[fn](string)
|| this.langs['en_US'] && this.langs['en_US'].fns[fn] && this.langs['en_US'].fns[fn](string)
|| string;
}
__ (strings : TemplateStringsArray, ...props : any[]) : string {
const buffer : string[] = [];
strings.forEach((string, index) => {
buffer.push(this.tl(string));
if (props[index]) {
buffer.push(this.tl(props[index].toString()));
}
});
return buffer.join('');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment