index.ts 1.9 KB
Newer Older
R
Rongfeng Fu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
/*
 * This file is generated by parrot must
 * DOCUMENT LIST:
 * parrot must: http://gitlab.alibaba-inc.com/parrot/parrot-tool-must
 * @ali/global-locale: http://gitlab.alibaba-inc.com/parrot/global-locale
 * @ali/global-string-format: http://gitlab.alibaba-inc.com/parrot/global-string-format
 */

import locale from '@ali/global-locale';
import stringFormat from '@ali/global-string-format';
import strings from './strings';

let language; // Current language
let intl; // Instance of intl-universal. Create by provideIntl
/**
 * update instance of intl universal
 */
function update() {
  const { lang } = locale.getLocale();
  language = lang;
  intl = stringFormat.init(lang, strings);
}

/**
 * change current language
 * @param {string} langTag language tag config above
 */
function change(langTag) {
  locale.setLang(langTag);
  update();
}
/**
 * Format string by key
 * For example:
 * $i18n.get('jsx.home.title'),
 * $i18n.get({
 *    id: 'jsx.home.hello',
 *    defaultMessage: 'Hello {name}' // not required
 * },{
 *  name: 'Alice'
 * })
 * More syntax: https://formatjs.io/guides/message-syntax/
 * @param {string|object} id key or object
 * @param {object} variable variable for id
 * @return {string} format message
 */
function get(id, variable) {
  if (!intl) update();
  if (typeof id === 'string') {
    return stringFormat.format(
      {
        id: id,
      },
      variable,
    );
  } else if (typeof id === 'object' && id.dm) {
    id.defaultMessage = id.dm;
  }
  return stringFormat.format(
    {
      id: id.id,
      defaultString: id.dm,
    },
    variable,
  );
}

/* set the first hng cookie
 * //! IMPORTANT  remove this after published, only for demo to start up
 * //! IMPORTANT 项目第一次启动后请删除下边的逻辑,这个逻辑只是为了第一次运行的时候,项目能够切换到英文
 */
// Delete start
change('en-US');
// Delete end

module.exports = {
  get,
  update,
  change,
  language,
};