uni-i18n.cjs.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. 'use strict';
  2. const isObject = (val) => val !== null && typeof val === 'object';
  3. const defaultDelimiters = ['{', '}'];
  4. class BaseFormatter {
  5. constructor() {
  6. this._caches = Object.create(null);
  7. }
  8. interpolate(message, values, delimiters = defaultDelimiters) {
  9. if (!values) {
  10. return [message];
  11. }
  12. let tokens = this._caches[message];
  13. if (!tokens) {
  14. tokens = parse(message, delimiters);
  15. this._caches[message] = tokens;
  16. }
  17. return compile(tokens, values);
  18. }
  19. }
  20. const RE_TOKEN_LIST_VALUE = /^(?:\d)+/;
  21. const RE_TOKEN_NAMED_VALUE = /^(?:\w)+/;
  22. function parse(format, [startDelimiter, endDelimiter]) {
  23. const tokens = [];
  24. let position = 0;
  25. let text = '';
  26. while (position < format.length) {
  27. let char = format[position++];
  28. if (char === startDelimiter) {
  29. if (text) {
  30. tokens.push({ type: 'text', value: text });
  31. }
  32. text = '';
  33. let sub = '';
  34. char = format[position++];
  35. while (char !== undefined && char !== endDelimiter) {
  36. sub += char;
  37. char = format[position++];
  38. }
  39. const isClosed = char === endDelimiter;
  40. const type = RE_TOKEN_LIST_VALUE.test(sub)
  41. ? 'list'
  42. : isClosed && RE_TOKEN_NAMED_VALUE.test(sub)
  43. ? 'named'
  44. : 'unknown';
  45. tokens.push({ value: sub, type });
  46. }
  47. // else if (char === '%') {
  48. // // when found rails i18n syntax, skip text capture
  49. // if (format[position] !== '{') {
  50. // text += char
  51. // }
  52. // }
  53. else {
  54. text += char;
  55. }
  56. }
  57. text && tokens.push({ type: 'text', value: text });
  58. return tokens;
  59. }
  60. function compile(tokens, values) {
  61. const compiled = [];
  62. let index = 0;
  63. const mode = Array.isArray(values)
  64. ? 'list'
  65. : isObject(values)
  66. ? 'named'
  67. : 'unknown';
  68. if (mode === 'unknown') {
  69. return compiled;
  70. }
  71. while (index < tokens.length) {
  72. const token = tokens[index];
  73. switch (token.type) {
  74. case 'text':
  75. compiled.push(token.value);
  76. break;
  77. case 'list':
  78. compiled.push(values[parseInt(token.value, 10)]);
  79. break;
  80. case 'named':
  81. if (mode === 'named') {
  82. compiled.push(values[token.value]);
  83. }
  84. else {
  85. if (process.env.NODE_ENV !== 'production') {
  86. console.warn(`Type of token '${token.type}' and format of value '${mode}' don't match!`);
  87. }
  88. }
  89. break;
  90. case 'unknown':
  91. if (process.env.NODE_ENV !== 'production') {
  92. console.warn(`Detect 'unknown' type of token!`);
  93. }
  94. break;
  95. }
  96. index++;
  97. }
  98. return compiled;
  99. }
  100. const LOCALE_ZH_HANS = 'zh-Hans';
  101. const LOCALE_ZH_HANT = 'zh-Hant';
  102. const LOCALE_EN = 'en';
  103. const LOCALE_FR = 'fr';
  104. const LOCALE_ES = 'es';
  105. const hasOwnProperty = Object.prototype.hasOwnProperty;
  106. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  107. const defaultFormatter = new BaseFormatter();
  108. function include(str, parts) {
  109. return !!parts.find((part) => str.indexOf(part) !== -1);
  110. }
  111. function startsWith(str, parts) {
  112. return parts.find((part) => str.indexOf(part) === 0);
  113. }
  114. function normalizeLocale(locale, messages) {
  115. if (!locale) {
  116. return;
  117. }
  118. locale = locale.trim().replace(/_/g, '-');
  119. if (messages && messages[locale]) {
  120. return locale;
  121. }
  122. locale = locale.toLowerCase();
  123. if (locale === 'chinese') {
  124. // 支付宝
  125. return LOCALE_ZH_HANS;
  126. }
  127. if (locale.indexOf('zh') === 0) {
  128. if (locale.indexOf('-hans') > -1) {
  129. return LOCALE_ZH_HANS;
  130. }
  131. if (locale.indexOf('-hant') > -1) {
  132. return LOCALE_ZH_HANT;
  133. }
  134. if (include(locale, ['-tw', '-hk', '-mo', '-cht'])) {
  135. return LOCALE_ZH_HANT;
  136. }
  137. return LOCALE_ZH_HANS;
  138. }
  139. let locales = [LOCALE_EN, LOCALE_FR, LOCALE_ES];
  140. if (messages && Object.keys(messages).length > 0) {
  141. locales = Object.keys(messages);
  142. }
  143. const lang = startsWith(locale, locales);
  144. if (lang) {
  145. return lang;
  146. }
  147. }
  148. class I18n {
  149. constructor({ locale, fallbackLocale, messages, watcher, formater, }) {
  150. this.locale = LOCALE_EN;
  151. this.fallbackLocale = LOCALE_EN;
  152. this.message = {};
  153. this.messages = {};
  154. this.watchers = [];
  155. if (fallbackLocale) {
  156. this.fallbackLocale = fallbackLocale;
  157. }
  158. this.formater = formater || defaultFormatter;
  159. this.messages = messages || {};
  160. this.setLocale(locale || LOCALE_EN);
  161. if (watcher) {
  162. this.watchLocale(watcher);
  163. }
  164. }
  165. setLocale(locale) {
  166. const oldLocale = this.locale;
  167. this.locale = normalizeLocale(locale, this.messages) || this.fallbackLocale;
  168. if (!this.messages[this.locale]) {
  169. // 可能初始化时不存在
  170. this.messages[this.locale] = {};
  171. }
  172. this.message = this.messages[this.locale];
  173. // 仅发生变化时,通知
  174. if (oldLocale !== this.locale) {
  175. this.watchers.forEach((watcher) => {
  176. watcher(this.locale, oldLocale);
  177. });
  178. }
  179. }
  180. getLocale() {
  181. return this.locale;
  182. }
  183. watchLocale(fn) {
  184. const index = this.watchers.push(fn) - 1;
  185. return () => {
  186. this.watchers.splice(index, 1);
  187. };
  188. }
  189. add(locale, message, override = true) {
  190. const curMessages = this.messages[locale];
  191. if (curMessages) {
  192. if (override) {
  193. Object.assign(curMessages, message);
  194. }
  195. else {
  196. Object.keys(message).forEach((key) => {
  197. if (!hasOwn(curMessages, key)) {
  198. curMessages[key] = message[key];
  199. }
  200. });
  201. }
  202. }
  203. else {
  204. this.messages[locale] = message;
  205. }
  206. }
  207. f(message, values, delimiters) {
  208. return this.formater.interpolate(message, values, delimiters).join('');
  209. }
  210. t(key, locale, values) {
  211. let message = this.message;
  212. if (typeof locale === 'string') {
  213. locale = normalizeLocale(locale, this.messages);
  214. locale && (message = this.messages[locale]);
  215. }
  216. else {
  217. values = locale;
  218. }
  219. if (!hasOwn(message, key)) {
  220. console.warn(`Cannot translate the value of keypath ${key}. Use the value of keypath as default.`);
  221. return key;
  222. }
  223. return this.formater.interpolate(message[key], values).join('');
  224. }
  225. }
  226. function watchAppLocale(appVm, i18n) {
  227. // 需要保证 watch 的触发在组件渲染之前
  228. if (appVm.$watchLocale) {
  229. // vue2
  230. appVm.$watchLocale((newLocale) => {
  231. i18n.setLocale(newLocale);
  232. });
  233. }
  234. else {
  235. appVm.$watch(() => appVm.$locale, (newLocale) => {
  236. i18n.setLocale(newLocale);
  237. });
  238. }
  239. }
  240. function getDefaultLocale() {
  241. if (typeof uni !== 'undefined' && uni.getLocale) {
  242. return uni.getLocale();
  243. }
  244. // 小程序平台,uni 和 uni-i18n 互相引用,导致访问不到 uni,故在 global 上挂了 getLocale
  245. if (typeof global !== 'undefined' && global.getLocale) {
  246. return global.getLocale();
  247. }
  248. return LOCALE_EN;
  249. }
  250. function initVueI18n(locale, messages = {}, fallbackLocale, watcher) {
  251. // 兼容旧版本入参
  252. if (typeof locale !== 'string') {
  253. [locale, messages] = [
  254. messages,
  255. locale,
  256. ];
  257. }
  258. if (typeof locale !== 'string') {
  259. // 因为小程序平台,uni-i18n 和 uni 互相引用,导致此时访问 uni 时,为 undefined
  260. locale = getDefaultLocale();
  261. }
  262. if (typeof fallbackLocale !== 'string') {
  263. fallbackLocale =
  264. (typeof __uniConfig !== 'undefined' && __uniConfig.fallbackLocale) ||
  265. LOCALE_EN;
  266. }
  267. const i18n = new I18n({
  268. locale,
  269. fallbackLocale,
  270. messages,
  271. watcher,
  272. });
  273. let t = (key, values) => {
  274. if (typeof getApp !== 'function') {
  275. // app view
  276. /* eslint-disable no-func-assign */
  277. t = function (key, values) {
  278. return i18n.t(key, values);
  279. };
  280. }
  281. else {
  282. let isWatchedAppLocale = false;
  283. t = function (key, values) {
  284. const appVm = getApp().$vm;
  285. // 可能$vm还不存在,比如在支付宝小程序中,组件定义较早,在props的default里使用了t()函数(如uni-goods-nav),此时app还未初始化
  286. // options: {
  287. // type: Array,
  288. // default () {
  289. // return [{
  290. // icon: 'shop',
  291. // text: t("uni-goods-nav.options.shop"),
  292. // }, {
  293. // icon: 'cart',
  294. // text: t("uni-goods-nav.options.cart")
  295. // }]
  296. // }
  297. // },
  298. if (appVm) {
  299. // 触发响应式
  300. appVm.$locale;
  301. if (!isWatchedAppLocale) {
  302. isWatchedAppLocale = true;
  303. watchAppLocale(appVm, i18n);
  304. }
  305. }
  306. return i18n.t(key, values);
  307. };
  308. }
  309. return t(key, values);
  310. };
  311. return {
  312. i18n,
  313. f(message, values, delimiters) {
  314. return i18n.f(message, values, delimiters);
  315. },
  316. t(key, values) {
  317. return t(key, values);
  318. },
  319. add(locale, message, override = true) {
  320. return i18n.add(locale, message, override);
  321. },
  322. watch(fn) {
  323. return i18n.watchLocale(fn);
  324. },
  325. getLocale() {
  326. return i18n.getLocale();
  327. },
  328. setLocale(newLocale) {
  329. return i18n.setLocale(newLocale);
  330. },
  331. };
  332. }
  333. const isString = (val) => typeof val === 'string';
  334. let formater;
  335. function hasI18nJson(jsonObj, delimiters) {
  336. if (!formater) {
  337. formater = new BaseFormatter();
  338. }
  339. return walkJsonObj(jsonObj, (jsonObj, key) => {
  340. const value = jsonObj[key];
  341. if (isString(value)) {
  342. if (isI18nStr(value, delimiters)) {
  343. return true;
  344. }
  345. }
  346. else {
  347. return hasI18nJson(value, delimiters);
  348. }
  349. });
  350. }
  351. function parseI18nJson(jsonObj, values, delimiters) {
  352. if (!formater) {
  353. formater = new BaseFormatter();
  354. }
  355. walkJsonObj(jsonObj, (jsonObj, key) => {
  356. const value = jsonObj[key];
  357. if (isString(value)) {
  358. if (isI18nStr(value, delimiters)) {
  359. jsonObj[key] = compileStr(value, values, delimiters);
  360. }
  361. }
  362. else {
  363. parseI18nJson(value, values, delimiters);
  364. }
  365. });
  366. return jsonObj;
  367. }
  368. function compileI18nJsonStr(jsonStr, { locale, locales, delimiters, }) {
  369. if (!isI18nStr(jsonStr, delimiters)) {
  370. return jsonStr;
  371. }
  372. if (!formater) {
  373. formater = new BaseFormatter();
  374. }
  375. const localeValues = [];
  376. Object.keys(locales).forEach((name) => {
  377. if (name !== locale) {
  378. localeValues.push({
  379. locale: name,
  380. values: locales[name],
  381. });
  382. }
  383. });
  384. localeValues.unshift({ locale, values: locales[locale] });
  385. try {
  386. return JSON.stringify(compileJsonObj(JSON.parse(jsonStr), localeValues, delimiters), null, 2);
  387. }
  388. catch (e) { }
  389. return jsonStr;
  390. }
  391. function isI18nStr(value, delimiters) {
  392. return value.indexOf(delimiters[0]) > -1;
  393. }
  394. function compileStr(value, values, delimiters) {
  395. return formater.interpolate(value, values, delimiters).join('');
  396. }
  397. function compileValue(jsonObj, key, localeValues, delimiters) {
  398. const value = jsonObj[key];
  399. if (isString(value)) {
  400. // 存在国际化
  401. if (isI18nStr(value, delimiters)) {
  402. jsonObj[key] = compileStr(value, localeValues[0].values, delimiters);
  403. if (localeValues.length > 1) {
  404. // 格式化国际化语言
  405. const valueLocales = (jsonObj[key + 'Locales'] = {});
  406. localeValues.forEach((localValue) => {
  407. valueLocales[localValue.locale] = compileStr(value, localValue.values, delimiters);
  408. });
  409. }
  410. }
  411. }
  412. else {
  413. compileJsonObj(value, localeValues, delimiters);
  414. }
  415. }
  416. function compileJsonObj(jsonObj, localeValues, delimiters) {
  417. walkJsonObj(jsonObj, (jsonObj, key) => {
  418. compileValue(jsonObj, key, localeValues, delimiters);
  419. });
  420. return jsonObj;
  421. }
  422. function walkJsonObj(jsonObj, walk) {
  423. if (Array.isArray(jsonObj)) {
  424. for (let i = 0; i < jsonObj.length; i++) {
  425. if (walk(jsonObj, i)) {
  426. return true;
  427. }
  428. }
  429. }
  430. else if (isObject(jsonObj)) {
  431. for (const key in jsonObj) {
  432. if (walk(jsonObj, key)) {
  433. return true;
  434. }
  435. }
  436. }
  437. return false;
  438. }
  439. function resolveLocale(locales) {
  440. return (locale) => {
  441. if (!locale) {
  442. return locale;
  443. }
  444. locale = normalizeLocale(locale) || locale;
  445. return resolveLocaleChain(locale).find((locale) => locales.indexOf(locale) > -1);
  446. };
  447. }
  448. function resolveLocaleChain(locale) {
  449. const chain = [];
  450. const tokens = locale.split('-');
  451. while (tokens.length) {
  452. chain.push(tokens.join('-'));
  453. tokens.pop();
  454. }
  455. return chain;
  456. }
  457. exports.Formatter = BaseFormatter;
  458. exports.I18n = I18n;
  459. exports.LOCALE_EN = LOCALE_EN;
  460. exports.LOCALE_ES = LOCALE_ES;
  461. exports.LOCALE_FR = LOCALE_FR;
  462. exports.LOCALE_ZH_HANS = LOCALE_ZH_HANS;
  463. exports.LOCALE_ZH_HANT = LOCALE_ZH_HANT;
  464. exports.compileI18nJsonStr = compileI18nJsonStr;
  465. exports.hasI18nJson = hasI18nJson;
  466. exports.initVueI18n = initVueI18n;
  467. exports.isI18nStr = isI18nStr;
  468. exports.isString = isString;
  469. exports.normalizeLocale = normalizeLocale;
  470. exports.parseI18nJson = parseI18nJson;
  471. exports.resolveLocale = resolveLocale;