vue-i18n.esm.browser.js 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104
  1. /* */
  2. /**
  3. * constants
  4. */
  5. const numberFormatKeys = [
  6. 'style',
  7. 'currency',
  8. 'currencyDisplay',
  9. 'useGrouping',
  10. 'minimumIntegerDigits',
  11. 'minimumFractionDigits',
  12. 'maximumFractionDigits',
  13. 'minimumSignificantDigits',
  14. 'maximumSignificantDigits',
  15. 'localeMatcher',
  16. 'formatMatcher',
  17. 'unit'
  18. ];
  19. /**
  20. * utilities
  21. */
  22. function warn (msg, err) {
  23. if (typeof console !== 'undefined') {
  24. console.warn('[vue-i18n] ' + msg);
  25. /* istanbul ignore if */
  26. if (err) {
  27. console.warn(err.stack);
  28. }
  29. }
  30. }
  31. function error (msg, err) {
  32. if (typeof console !== 'undefined') {
  33. console.error('[vue-i18n] ' + msg);
  34. /* istanbul ignore if */
  35. if (err) {
  36. console.error(err.stack);
  37. }
  38. }
  39. }
  40. const isArray = Array.isArray;
  41. function isObject (obj) {
  42. return obj !== null && typeof obj === 'object'
  43. }
  44. function isBoolean (val) {
  45. return typeof val === 'boolean'
  46. }
  47. function isString (val) {
  48. return typeof val === 'string'
  49. }
  50. const toString = Object.prototype.toString;
  51. const OBJECT_STRING = '[object Object]';
  52. function isPlainObject (obj) {
  53. return toString.call(obj) === OBJECT_STRING
  54. }
  55. function isNull (val) {
  56. return val === null || val === undefined
  57. }
  58. function isFunction (val) {
  59. return typeof val === 'function'
  60. }
  61. function parseArgs (...args) {
  62. let locale = null;
  63. let params = null;
  64. if (args.length === 1) {
  65. if (isObject(args[0]) || isArray(args[0])) {
  66. params = args[0];
  67. } else if (typeof args[0] === 'string') {
  68. locale = args[0];
  69. }
  70. } else if (args.length === 2) {
  71. if (typeof args[0] === 'string') {
  72. locale = args[0];
  73. }
  74. /* istanbul ignore if */
  75. if (isObject(args[1]) || isArray(args[1])) {
  76. params = args[1];
  77. }
  78. }
  79. return { locale, params }
  80. }
  81. function looseClone (obj) {
  82. return JSON.parse(JSON.stringify(obj))
  83. }
  84. function remove (arr, item) {
  85. if (arr.length) {
  86. const index = arr.indexOf(item);
  87. if (index > -1) {
  88. return arr.splice(index, 1)
  89. }
  90. }
  91. }
  92. function includes (arr, item) {
  93. return !!~arr.indexOf(item)
  94. }
  95. const hasOwnProperty = Object.prototype.hasOwnProperty;
  96. function hasOwn (obj, key) {
  97. return hasOwnProperty.call(obj, key)
  98. }
  99. function merge (target) {
  100. const output = Object(target);
  101. for (let i = 1; i < arguments.length; i++) {
  102. const source = arguments[i];
  103. if (source !== undefined && source !== null) {
  104. let key;
  105. for (key in source) {
  106. if (hasOwn(source, key)) {
  107. if (isObject(source[key])) {
  108. output[key] = merge(output[key], source[key]);
  109. } else {
  110. output[key] = source[key];
  111. }
  112. }
  113. }
  114. }
  115. }
  116. return output
  117. }
  118. function looseEqual (a, b) {
  119. if (a === b) { return true }
  120. const isObjectA = isObject(a);
  121. const isObjectB = isObject(b);
  122. if (isObjectA && isObjectB) {
  123. try {
  124. const isArrayA = isArray(a);
  125. const isArrayB = isArray(b);
  126. if (isArrayA && isArrayB) {
  127. return a.length === b.length && a.every((e, i) => {
  128. return looseEqual(e, b[i])
  129. })
  130. } else if (!isArrayA && !isArrayB) {
  131. const keysA = Object.keys(a);
  132. const keysB = Object.keys(b);
  133. return keysA.length === keysB.length && keysA.every((key) => {
  134. return looseEqual(a[key], b[key])
  135. })
  136. } else {
  137. /* istanbul ignore next */
  138. return false
  139. }
  140. } catch (e) {
  141. /* istanbul ignore next */
  142. return false
  143. }
  144. } else if (!isObjectA && !isObjectB) {
  145. return String(a) === String(b)
  146. } else {
  147. return false
  148. }
  149. }
  150. /* */
  151. function extend (Vue) {
  152. if (!Vue.prototype.hasOwnProperty('$i18n')) {
  153. // $FlowFixMe
  154. Object.defineProperty(Vue.prototype, '$i18n', {
  155. get () { return this._i18n }
  156. });
  157. }
  158. Vue.prototype.$t = function (key, ...values) {
  159. const i18n = this.$i18n;
  160. return i18n._t(key, i18n.locale, i18n._getMessages(), this, ...values)
  161. };
  162. Vue.prototype.$tc = function (key, choice, ...values) {
  163. const i18n = this.$i18n;
  164. return i18n._tc(key, i18n.locale, i18n._getMessages(), this, choice, ...values)
  165. };
  166. Vue.prototype.$te = function (key, locale) {
  167. const i18n = this.$i18n;
  168. return i18n._te(key, i18n.locale, i18n._getMessages(), locale)
  169. };
  170. Vue.prototype.$d = function (value, ...args) {
  171. return this.$i18n.d(value, ...args)
  172. };
  173. Vue.prototype.$n = function (value, ...args) {
  174. return this.$i18n.n(value, ...args)
  175. };
  176. }
  177. /* */
  178. var mixin = {
  179. beforeCreate () {
  180. const options = this.$options;
  181. options.i18n = options.i18n || (options.__i18n ? {} : null);
  182. if (options.i18n) {
  183. if (options.i18n instanceof VueI18n) {
  184. // init locale messages via custom blocks
  185. if (options.__i18n) {
  186. try {
  187. let localeMessages = {};
  188. options.__i18n.forEach(resource => {
  189. localeMessages = merge(localeMessages, JSON.parse(resource));
  190. });
  191. Object.keys(localeMessages).forEach((locale) => {
  192. options.i18n.mergeLocaleMessage(locale, localeMessages[locale]);
  193. });
  194. } catch (e) {
  195. {
  196. error(`Cannot parse locale messages via custom blocks.`, e);
  197. }
  198. }
  199. }
  200. this._i18n = options.i18n;
  201. this._i18nWatcher = this._i18n.watchI18nData();
  202. } else if (isPlainObject(options.i18n)) {
  203. const rootI18n = this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n
  204. ? this.$root.$i18n
  205. : null;
  206. // component local i18n
  207. if (rootI18n) {
  208. options.i18n.root = this.$root;
  209. options.i18n.formatter = rootI18n.formatter;
  210. options.i18n.fallbackLocale = rootI18n.fallbackLocale;
  211. options.i18n.formatFallbackMessages = rootI18n.formatFallbackMessages;
  212. options.i18n.silentTranslationWarn = rootI18n.silentTranslationWarn;
  213. options.i18n.silentFallbackWarn = rootI18n.silentFallbackWarn;
  214. options.i18n.pluralizationRules = rootI18n.pluralizationRules;
  215. options.i18n.preserveDirectiveContent = rootI18n.preserveDirectiveContent;
  216. }
  217. // init locale messages via custom blocks
  218. if (options.__i18n) {
  219. try {
  220. let localeMessages = {};
  221. options.__i18n.forEach(resource => {
  222. localeMessages = merge(localeMessages, JSON.parse(resource));
  223. });
  224. options.i18n.messages = localeMessages;
  225. } catch (e) {
  226. {
  227. warn(`Cannot parse locale messages via custom blocks.`, e);
  228. }
  229. }
  230. }
  231. const { sharedMessages } = options.i18n;
  232. if (sharedMessages && isPlainObject(sharedMessages)) {
  233. options.i18n.messages = merge(options.i18n.messages, sharedMessages);
  234. }
  235. this._i18n = new VueI18n(options.i18n);
  236. this._i18nWatcher = this._i18n.watchI18nData();
  237. if (options.i18n.sync === undefined || !!options.i18n.sync) {
  238. this._localeWatcher = this.$i18n.watchLocale();
  239. }
  240. if (rootI18n) {
  241. rootI18n.onComponentInstanceCreated(this._i18n);
  242. }
  243. } else {
  244. {
  245. warn(`Cannot be interpreted 'i18n' option.`);
  246. }
  247. }
  248. } else if (this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n) {
  249. // root i18n
  250. this._i18n = this.$root.$i18n;
  251. } else if (options.parent && options.parent.$i18n && options.parent.$i18n instanceof VueI18n) {
  252. // parent i18n
  253. this._i18n = options.parent.$i18n;
  254. }
  255. },
  256. beforeMount () {
  257. const options = this.$options;
  258. options.i18n = options.i18n || (options.__i18n ? {} : null);
  259. if (options.i18n) {
  260. if (options.i18n instanceof VueI18n) {
  261. // init locale messages via custom blocks
  262. this._i18n.subscribeDataChanging(this);
  263. this._subscribing = true;
  264. } else if (isPlainObject(options.i18n)) {
  265. this._i18n.subscribeDataChanging(this);
  266. this._subscribing = true;
  267. } else {
  268. {
  269. warn(`Cannot be interpreted 'i18n' option.`);
  270. }
  271. }
  272. } else if (this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n) {
  273. this._i18n.subscribeDataChanging(this);
  274. this._subscribing = true;
  275. } else if (options.parent && options.parent.$i18n && options.parent.$i18n instanceof VueI18n) {
  276. this._i18n.subscribeDataChanging(this);
  277. this._subscribing = true;
  278. }
  279. },
  280. beforeDestroy () {
  281. if (!this._i18n) { return }
  282. const self = this;
  283. this.$nextTick(() => {
  284. if (self._subscribing) {
  285. self._i18n.unsubscribeDataChanging(self);
  286. delete self._subscribing;
  287. }
  288. if (self._i18nWatcher) {
  289. self._i18nWatcher();
  290. self._i18n.destroyVM();
  291. delete self._i18nWatcher;
  292. }
  293. if (self._localeWatcher) {
  294. self._localeWatcher();
  295. delete self._localeWatcher;
  296. }
  297. });
  298. }
  299. };
  300. /* */
  301. var interpolationComponent = {
  302. name: 'i18n',
  303. functional: true,
  304. props: {
  305. tag: {
  306. type: [String, Boolean, Object],
  307. default: 'span'
  308. },
  309. path: {
  310. type: String,
  311. required: true
  312. },
  313. locale: {
  314. type: String
  315. },
  316. places: {
  317. type: [Array, Object]
  318. }
  319. },
  320. render (h, { data, parent, props, slots }) {
  321. const { $i18n } = parent;
  322. if (!$i18n) {
  323. {
  324. warn('Cannot find VueI18n instance!');
  325. }
  326. return
  327. }
  328. const { path, locale, places } = props;
  329. const params = slots();
  330. const children = $i18n.i(
  331. path,
  332. locale,
  333. onlyHasDefaultPlace(params) || places
  334. ? useLegacyPlaces(params.default, places)
  335. : params
  336. );
  337. const tag = (!!props.tag && props.tag !== true) || props.tag === false ? props.tag : 'span';
  338. return tag ? h(tag, data, children) : children
  339. }
  340. };
  341. function onlyHasDefaultPlace (params) {
  342. let prop;
  343. for (prop in params) {
  344. if (prop !== 'default') { return false }
  345. }
  346. return Boolean(prop)
  347. }
  348. function useLegacyPlaces (children, places) {
  349. const params = places ? createParamsFromPlaces(places) : {};
  350. if (!children) { return params }
  351. // Filter empty text nodes
  352. children = children.filter(child => {
  353. return child.tag || child.text.trim() !== ''
  354. });
  355. const everyPlace = children.every(vnodeHasPlaceAttribute);
  356. if (everyPlace) {
  357. warn('`place` attribute is deprecated in next major version. Please switch to Vue slots.');
  358. }
  359. return children.reduce(
  360. everyPlace ? assignChildPlace : assignChildIndex,
  361. params
  362. )
  363. }
  364. function createParamsFromPlaces (places) {
  365. {
  366. warn('`places` prop is deprecated in next major version. Please switch to Vue slots.');
  367. }
  368. return Array.isArray(places)
  369. ? places.reduce(assignChildIndex, {})
  370. : Object.assign({}, places)
  371. }
  372. function assignChildPlace (params, child) {
  373. if (child.data && child.data.attrs && child.data.attrs.place) {
  374. params[child.data.attrs.place] = child;
  375. }
  376. return params
  377. }
  378. function assignChildIndex (params, child, index) {
  379. params[index] = child;
  380. return params
  381. }
  382. function vnodeHasPlaceAttribute (vnode) {
  383. return Boolean(vnode.data && vnode.data.attrs && vnode.data.attrs.place)
  384. }
  385. /* */
  386. var numberComponent = {
  387. name: 'i18n-n',
  388. functional: true,
  389. props: {
  390. tag: {
  391. type: [String, Boolean, Object],
  392. default: 'span'
  393. },
  394. value: {
  395. type: Number,
  396. required: true
  397. },
  398. format: {
  399. type: [String, Object]
  400. },
  401. locale: {
  402. type: String
  403. }
  404. },
  405. render (h, { props, parent, data }) {
  406. const i18n = parent.$i18n;
  407. if (!i18n) {
  408. {
  409. warn('Cannot find VueI18n instance!');
  410. }
  411. return null
  412. }
  413. let key = null;
  414. let options = null;
  415. if (isString(props.format)) {
  416. key = props.format;
  417. } else if (isObject(props.format)) {
  418. if (props.format.key) {
  419. key = props.format.key;
  420. }
  421. // Filter out number format options only
  422. options = Object.keys(props.format).reduce((acc, prop) => {
  423. if (includes(numberFormatKeys, prop)) {
  424. return Object.assign({}, acc, { [prop]: props.format[prop] })
  425. }
  426. return acc
  427. }, null);
  428. }
  429. const locale = props.locale || i18n.locale;
  430. const parts = i18n._ntp(props.value, locale, key, options);
  431. const values = parts.map((part, index) => {
  432. const slot = data.scopedSlots && data.scopedSlots[part.type];
  433. return slot ? slot({ [part.type]: part.value, index, parts }) : part.value
  434. });
  435. const tag = (!!props.tag && props.tag !== true) || props.tag === false ? props.tag : 'span';
  436. return tag
  437. ? h(tag, {
  438. attrs: data.attrs,
  439. 'class': data['class'],
  440. staticClass: data.staticClass
  441. }, values)
  442. : values
  443. }
  444. };
  445. /* */
  446. function bind (el, binding, vnode) {
  447. if (!assert(el, vnode)) { return }
  448. t(el, binding, vnode);
  449. }
  450. function update (el, binding, vnode, oldVNode) {
  451. if (!assert(el, vnode)) { return }
  452. const i18n = vnode.context.$i18n;
  453. if (localeEqual(el, vnode) &&
  454. (looseEqual(binding.value, binding.oldValue) &&
  455. looseEqual(el._localeMessage, i18n.getLocaleMessage(i18n.locale)))) { return }
  456. t(el, binding, vnode);
  457. }
  458. function unbind (el, binding, vnode, oldVNode) {
  459. const vm = vnode.context;
  460. if (!vm) {
  461. warn('Vue instance does not exists in VNode context');
  462. return
  463. }
  464. const i18n = vnode.context.$i18n || {};
  465. if (!binding.modifiers.preserve && !i18n.preserveDirectiveContent) {
  466. el.textContent = '';
  467. }
  468. el._vt = undefined;
  469. delete el['_vt'];
  470. el._locale = undefined;
  471. delete el['_locale'];
  472. el._localeMessage = undefined;
  473. delete el['_localeMessage'];
  474. }
  475. function assert (el, vnode) {
  476. const vm = vnode.context;
  477. if (!vm) {
  478. warn('Vue instance does not exists in VNode context');
  479. return false
  480. }
  481. if (!vm.$i18n) {
  482. warn('VueI18n instance does not exists in Vue instance');
  483. return false
  484. }
  485. return true
  486. }
  487. function localeEqual (el, vnode) {
  488. const vm = vnode.context;
  489. return el._locale === vm.$i18n.locale
  490. }
  491. function t (el, binding, vnode) {
  492. const value = binding.value;
  493. const { path, locale, args, choice } = parseValue(value);
  494. if (!path && !locale && !args) {
  495. warn('value type not supported');
  496. return
  497. }
  498. if (!path) {
  499. warn('`path` is required in v-t directive');
  500. return
  501. }
  502. const vm = vnode.context;
  503. if (choice != null) {
  504. el._vt = el.textContent = vm.$i18n.tc(path, choice, ...makeParams(locale, args));
  505. } else {
  506. el._vt = el.textContent = vm.$i18n.t(path, ...makeParams(locale, args));
  507. }
  508. el._locale = vm.$i18n.locale;
  509. el._localeMessage = vm.$i18n.getLocaleMessage(vm.$i18n.locale);
  510. }
  511. function parseValue (value) {
  512. let path;
  513. let locale;
  514. let args;
  515. let choice;
  516. if (isString(value)) {
  517. path = value;
  518. } else if (isPlainObject(value)) {
  519. path = value.path;
  520. locale = value.locale;
  521. args = value.args;
  522. choice = value.choice;
  523. }
  524. return { path, locale, args, choice }
  525. }
  526. function makeParams (locale, args) {
  527. const params = [];
  528. locale && params.push(locale);
  529. if (args && (Array.isArray(args) || isPlainObject(args))) {
  530. params.push(args);
  531. }
  532. return params
  533. }
  534. let Vue;
  535. function install (_Vue) {
  536. /* istanbul ignore if */
  537. if (install.installed && _Vue === Vue) {
  538. warn('already installed.');
  539. return
  540. }
  541. install.installed = true;
  542. Vue = _Vue;
  543. const version = (Vue.version && Number(Vue.version.split('.')[0])) || -1;
  544. /* istanbul ignore if */
  545. if (version < 2) {
  546. warn(`vue-i18n (${install.version}) need to use Vue 2.0 or later (Vue: ${Vue.version}).`);
  547. return
  548. }
  549. extend(Vue);
  550. Vue.mixin(mixin);
  551. Vue.directive('t', { bind, update, unbind });
  552. Vue.component(interpolationComponent.name, interpolationComponent);
  553. Vue.component(numberComponent.name, numberComponent);
  554. // use simple mergeStrategies to prevent i18n instance lose '__proto__'
  555. const strats = Vue.config.optionMergeStrategies;
  556. strats.i18n = function (parentVal, childVal) {
  557. return childVal === undefined
  558. ? parentVal
  559. : childVal
  560. };
  561. }
  562. /* */
  563. class BaseFormatter {
  564. constructor () {
  565. this._caches = Object.create(null);
  566. }
  567. interpolate (message, values) {
  568. if (!values) {
  569. return [message]
  570. }
  571. let tokens = this._caches[message];
  572. if (!tokens) {
  573. tokens = parse(message);
  574. this._caches[message] = tokens;
  575. }
  576. return compile(tokens, values)
  577. }
  578. }
  579. const RE_TOKEN_LIST_VALUE = /^(?:\d)+/;
  580. const RE_TOKEN_NAMED_VALUE = /^(?:\w)+/;
  581. function parse (format) {
  582. const tokens = [];
  583. let position = 0;
  584. let text = '';
  585. while (position < format.length) {
  586. let char = format[position++];
  587. if (char === '{') {
  588. if (text) {
  589. tokens.push({ type: 'text', value: text });
  590. }
  591. text = '';
  592. let sub = '';
  593. char = format[position++];
  594. while (char !== undefined && char !== '}') {
  595. sub += char;
  596. char = format[position++];
  597. }
  598. const isClosed = char === '}';
  599. const type = RE_TOKEN_LIST_VALUE.test(sub)
  600. ? 'list'
  601. : isClosed && RE_TOKEN_NAMED_VALUE.test(sub)
  602. ? 'named'
  603. : 'unknown';
  604. tokens.push({ value: sub, type });
  605. } else if (char === '%') {
  606. // when found rails i18n syntax, skip text capture
  607. if (format[(position)] !== '{') {
  608. text += char;
  609. }
  610. } else {
  611. text += char;
  612. }
  613. }
  614. text && tokens.push({ type: 'text', value: text });
  615. return tokens
  616. }
  617. function compile (tokens, values) {
  618. const compiled = [];
  619. let index = 0;
  620. const mode = Array.isArray(values)
  621. ? 'list'
  622. : isObject(values)
  623. ? 'named'
  624. : 'unknown';
  625. if (mode === 'unknown') { return compiled }
  626. while (index < tokens.length) {
  627. const token = tokens[index];
  628. switch (token.type) {
  629. case 'text':
  630. compiled.push(token.value);
  631. break
  632. case 'list':
  633. compiled.push(values[parseInt(token.value, 10)]);
  634. break
  635. case 'named':
  636. if (mode === 'named') {
  637. compiled.push((values)[token.value]);
  638. } else {
  639. {
  640. warn(`Type of token '${token.type}' and format of value '${mode}' don't match!`);
  641. }
  642. }
  643. break
  644. case 'unknown':
  645. {
  646. warn(`Detect 'unknown' type of token!`);
  647. }
  648. break
  649. }
  650. index++;
  651. }
  652. return compiled
  653. }
  654. /* */
  655. /**
  656. * Path parser
  657. * - Inspired:
  658. * Vue.js Path parser
  659. */
  660. // actions
  661. const APPEND = 0;
  662. const PUSH = 1;
  663. const INC_SUB_PATH_DEPTH = 2;
  664. const PUSH_SUB_PATH = 3;
  665. // states
  666. const BEFORE_PATH = 0;
  667. const IN_PATH = 1;
  668. const BEFORE_IDENT = 2;
  669. const IN_IDENT = 3;
  670. const IN_SUB_PATH = 4;
  671. const IN_SINGLE_QUOTE = 5;
  672. const IN_DOUBLE_QUOTE = 6;
  673. const AFTER_PATH = 7;
  674. const ERROR = 8;
  675. const pathStateMachine = [];
  676. pathStateMachine[BEFORE_PATH] = {
  677. 'ws': [BEFORE_PATH],
  678. 'ident': [IN_IDENT, APPEND],
  679. '[': [IN_SUB_PATH],
  680. 'eof': [AFTER_PATH]
  681. };
  682. pathStateMachine[IN_PATH] = {
  683. 'ws': [IN_PATH],
  684. '.': [BEFORE_IDENT],
  685. '[': [IN_SUB_PATH],
  686. 'eof': [AFTER_PATH]
  687. };
  688. pathStateMachine[BEFORE_IDENT] = {
  689. 'ws': [BEFORE_IDENT],
  690. 'ident': [IN_IDENT, APPEND],
  691. '0': [IN_IDENT, APPEND],
  692. 'number': [IN_IDENT, APPEND]
  693. };
  694. pathStateMachine[IN_IDENT] = {
  695. 'ident': [IN_IDENT, APPEND],
  696. '0': [IN_IDENT, APPEND],
  697. 'number': [IN_IDENT, APPEND],
  698. 'ws': [IN_PATH, PUSH],
  699. '.': [BEFORE_IDENT, PUSH],
  700. '[': [IN_SUB_PATH, PUSH],
  701. 'eof': [AFTER_PATH, PUSH]
  702. };
  703. pathStateMachine[IN_SUB_PATH] = {
  704. "'": [IN_SINGLE_QUOTE, APPEND],
  705. '"': [IN_DOUBLE_QUOTE, APPEND],
  706. '[': [IN_SUB_PATH, INC_SUB_PATH_DEPTH],
  707. ']': [IN_PATH, PUSH_SUB_PATH],
  708. 'eof': ERROR,
  709. 'else': [IN_SUB_PATH, APPEND]
  710. };
  711. pathStateMachine[IN_SINGLE_QUOTE] = {
  712. "'": [IN_SUB_PATH, APPEND],
  713. 'eof': ERROR,
  714. 'else': [IN_SINGLE_QUOTE, APPEND]
  715. };
  716. pathStateMachine[IN_DOUBLE_QUOTE] = {
  717. '"': [IN_SUB_PATH, APPEND],
  718. 'eof': ERROR,
  719. 'else': [IN_DOUBLE_QUOTE, APPEND]
  720. };
  721. /**
  722. * Check if an expression is a literal value.
  723. */
  724. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  725. function isLiteral (exp) {
  726. return literalValueRE.test(exp)
  727. }
  728. /**
  729. * Strip quotes from a string
  730. */
  731. function stripQuotes (str) {
  732. const a = str.charCodeAt(0);
  733. const b = str.charCodeAt(str.length - 1);
  734. return a === b && (a === 0x22 || a === 0x27)
  735. ? str.slice(1, -1)
  736. : str
  737. }
  738. /**
  739. * Determine the type of a character in a keypath.
  740. */
  741. function getPathCharType (ch) {
  742. if (ch === undefined || ch === null) { return 'eof' }
  743. const code = ch.charCodeAt(0);
  744. switch (code) {
  745. case 0x5B: // [
  746. case 0x5D: // ]
  747. case 0x2E: // .
  748. case 0x22: // "
  749. case 0x27: // '
  750. return ch
  751. case 0x5F: // _
  752. case 0x24: // $
  753. case 0x2D: // -
  754. return 'ident'
  755. case 0x09: // Tab
  756. case 0x0A: // Newline
  757. case 0x0D: // Return
  758. case 0xA0: // No-break space
  759. case 0xFEFF: // Byte Order Mark
  760. case 0x2028: // Line Separator
  761. case 0x2029: // Paragraph Separator
  762. return 'ws'
  763. }
  764. return 'ident'
  765. }
  766. /**
  767. * Format a subPath, return its plain form if it is
  768. * a literal string or number. Otherwise prepend the
  769. * dynamic indicator (*).
  770. */
  771. function formatSubPath (path) {
  772. const trimmed = path.trim();
  773. // invalid leading 0
  774. if (path.charAt(0) === '0' && isNaN(path)) { return false }
  775. return isLiteral(trimmed) ? stripQuotes(trimmed) : '*' + trimmed
  776. }
  777. /**
  778. * Parse a string path into an array of segments
  779. */
  780. function parse$1 (path) {
  781. const keys = [];
  782. let index = -1;
  783. let mode = BEFORE_PATH;
  784. let subPathDepth = 0;
  785. let c;
  786. let key;
  787. let newChar;
  788. let type;
  789. let transition;
  790. let action;
  791. let typeMap;
  792. const actions = [];
  793. actions[PUSH] = function () {
  794. if (key !== undefined) {
  795. keys.push(key);
  796. key = undefined;
  797. }
  798. };
  799. actions[APPEND] = function () {
  800. if (key === undefined) {
  801. key = newChar;
  802. } else {
  803. key += newChar;
  804. }
  805. };
  806. actions[INC_SUB_PATH_DEPTH] = function () {
  807. actions[APPEND]();
  808. subPathDepth++;
  809. };
  810. actions[PUSH_SUB_PATH] = function () {
  811. if (subPathDepth > 0) {
  812. subPathDepth--;
  813. mode = IN_SUB_PATH;
  814. actions[APPEND]();
  815. } else {
  816. subPathDepth = 0;
  817. if (key === undefined) { return false }
  818. key = formatSubPath(key);
  819. if (key === false) {
  820. return false
  821. } else {
  822. actions[PUSH]();
  823. }
  824. }
  825. };
  826. function maybeUnescapeQuote () {
  827. const nextChar = path[index + 1];
  828. if ((mode === IN_SINGLE_QUOTE && nextChar === "'") ||
  829. (mode === IN_DOUBLE_QUOTE && nextChar === '"')) {
  830. index++;
  831. newChar = '\\' + nextChar;
  832. actions[APPEND]();
  833. return true
  834. }
  835. }
  836. while (mode !== null) {
  837. index++;
  838. c = path[index];
  839. if (c === '\\' && maybeUnescapeQuote()) {
  840. continue
  841. }
  842. type = getPathCharType(c);
  843. typeMap = pathStateMachine[mode];
  844. transition = typeMap[type] || typeMap['else'] || ERROR;
  845. if (transition === ERROR) {
  846. return // parse error
  847. }
  848. mode = transition[0];
  849. action = actions[transition[1]];
  850. if (action) {
  851. newChar = transition[2];
  852. newChar = newChar === undefined
  853. ? c
  854. : newChar;
  855. if (action() === false) {
  856. return
  857. }
  858. }
  859. if (mode === AFTER_PATH) {
  860. return keys
  861. }
  862. }
  863. }
  864. class I18nPath {
  865. constructor () {
  866. this._cache = Object.create(null);
  867. }
  868. /**
  869. * External parse that check for a cache hit first
  870. */
  871. parsePath (path) {
  872. let hit = this._cache[path];
  873. if (!hit) {
  874. hit = parse$1(path);
  875. if (hit) {
  876. this._cache[path] = hit;
  877. }
  878. }
  879. return hit || []
  880. }
  881. /**
  882. * Get path value from path string
  883. */
  884. getPathValue (obj, path) {
  885. if (!isObject(obj)) { return null }
  886. const paths = this.parsePath(path);
  887. if (paths.length === 0) {
  888. return null
  889. } else {
  890. const length = paths.length;
  891. let last = obj;
  892. let i = 0;
  893. while (i < length) {
  894. const value = last[paths[i]];
  895. if (value === undefined) {
  896. return null
  897. }
  898. last = value;
  899. i++;
  900. }
  901. return last
  902. }
  903. }
  904. }
  905. /* */
  906. const htmlTagMatcher = /<\/?[\w\s="/.':;#-\/]+>/;
  907. const linkKeyMatcher = /(?:@(?:\.[a-z]+)?:(?:[\w\-_|.]+|\([\w\-_|.]+\)))/g;
  908. const linkKeyPrefixMatcher = /^@(?:\.([a-z]+))?:/;
  909. const bracketsMatcher = /[()]/g;
  910. const defaultModifiers = {
  911. 'upper': str => str.toLocaleUpperCase(),
  912. 'lower': str => str.toLocaleLowerCase(),
  913. 'capitalize': str => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`
  914. };
  915. const defaultFormatter = new BaseFormatter();
  916. class VueI18n {
  917. constructor (options = {}) {
  918. // Auto install if it is not done yet and `window` has `Vue`.
  919. // To allow users to avoid auto-installation in some cases,
  920. // this code should be placed here. See #290
  921. /* istanbul ignore if */
  922. if (!Vue && typeof window !== 'undefined' && window.Vue) {
  923. install(window.Vue);
  924. }
  925. const locale = options.locale || 'en-US';
  926. const fallbackLocale = options.fallbackLocale === false
  927. ? false
  928. : options.fallbackLocale || 'en-US';
  929. const messages = options.messages || {};
  930. const dateTimeFormats = options.dateTimeFormats || {};
  931. const numberFormats = options.numberFormats || {};
  932. this._vm = null;
  933. this._formatter = options.formatter || defaultFormatter;
  934. this._modifiers = options.modifiers || {};
  935. this._missing = options.missing || null;
  936. this._root = options.root || null;
  937. this._sync = options.sync === undefined ? true : !!options.sync;
  938. this._fallbackRoot = options.fallbackRoot === undefined
  939. ? true
  940. : !!options.fallbackRoot;
  941. this._formatFallbackMessages = options.formatFallbackMessages === undefined
  942. ? false
  943. : !!options.formatFallbackMessages;
  944. this._silentTranslationWarn = options.silentTranslationWarn === undefined
  945. ? false
  946. : options.silentTranslationWarn;
  947. this._silentFallbackWarn = options.silentFallbackWarn === undefined
  948. ? false
  949. : !!options.silentFallbackWarn;
  950. this._dateTimeFormatters = {};
  951. this._numberFormatters = {};
  952. this._path = new I18nPath();
  953. this._dataListeners = [];
  954. this._componentInstanceCreatedListener = options.componentInstanceCreatedListener || null;
  955. this._preserveDirectiveContent = options.preserveDirectiveContent === undefined
  956. ? false
  957. : !!options.preserveDirectiveContent;
  958. this.pluralizationRules = options.pluralizationRules || {};
  959. this._warnHtmlInMessage = options.warnHtmlInMessage || 'off';
  960. this._postTranslation = options.postTranslation || null;
  961. /**
  962. * @param choice {number} a choice index given by the input to $tc: `$tc('path.to.rule', choiceIndex)`
  963. * @param choicesLength {number} an overall amount of available choices
  964. * @returns a final choice index
  965. */
  966. this.getChoiceIndex = (choice, choicesLength) => {
  967. const thisPrototype = Object.getPrototypeOf(this);
  968. if (thisPrototype && thisPrototype.getChoiceIndex) {
  969. const prototypeGetChoiceIndex = (thisPrototype.getChoiceIndex);
  970. return (prototypeGetChoiceIndex).call(this, choice, choicesLength)
  971. }
  972. // Default (old) getChoiceIndex implementation - english-compatible
  973. const defaultImpl = (_choice, _choicesLength) => {
  974. _choice = Math.abs(_choice);
  975. if (_choicesLength === 2) {
  976. return _choice
  977. ? _choice > 1
  978. ? 1
  979. : 0
  980. : 1
  981. }
  982. return _choice ? Math.min(_choice, 2) : 0
  983. };
  984. if (this.locale in this.pluralizationRules) {
  985. return this.pluralizationRules[this.locale].apply(this, [choice, choicesLength])
  986. } else {
  987. return defaultImpl(choice, choicesLength)
  988. }
  989. };
  990. this._exist = (message, key) => {
  991. if (!message || !key) { return false }
  992. if (!isNull(this._path.getPathValue(message, key))) { return true }
  993. // fallback for flat key
  994. if (message[key]) { return true }
  995. return false
  996. };
  997. if (this._warnHtmlInMessage === 'warn' || this._warnHtmlInMessage === 'error') {
  998. Object.keys(messages).forEach(locale => {
  999. this._checkLocaleMessage(locale, this._warnHtmlInMessage, messages[locale]);
  1000. });
  1001. }
  1002. this._initVM({
  1003. locale,
  1004. fallbackLocale,
  1005. messages,
  1006. dateTimeFormats,
  1007. numberFormats
  1008. });
  1009. }
  1010. _checkLocaleMessage (locale, level, message) {
  1011. const paths = [];
  1012. const fn = (level, locale, message, paths) => {
  1013. if (isPlainObject(message)) {
  1014. Object.keys(message).forEach(key => {
  1015. const val = message[key];
  1016. if (isPlainObject(val)) {
  1017. paths.push(key);
  1018. paths.push('.');
  1019. fn(level, locale, val, paths);
  1020. paths.pop();
  1021. paths.pop();
  1022. } else {
  1023. paths.push(key);
  1024. fn(level, locale, val, paths);
  1025. paths.pop();
  1026. }
  1027. });
  1028. } else if (isArray(message)) {
  1029. message.forEach((item, index) => {
  1030. if (isPlainObject(item)) {
  1031. paths.push(`[${index}]`);
  1032. paths.push('.');
  1033. fn(level, locale, item, paths);
  1034. paths.pop();
  1035. paths.pop();
  1036. } else {
  1037. paths.push(`[${index}]`);
  1038. fn(level, locale, item, paths);
  1039. paths.pop();
  1040. }
  1041. });
  1042. } else if (isString(message)) {
  1043. const ret = htmlTagMatcher.test(message);
  1044. if (ret) {
  1045. const msg = `Detected HTML in message '${message}' of keypath '${paths.join('')}' at '${locale}'. Consider component interpolation with '<i18n>' to avoid XSS. See https://bit.ly/2ZqJzkp`;
  1046. if (level === 'warn') {
  1047. warn(msg);
  1048. } else if (level === 'error') {
  1049. error(msg);
  1050. }
  1051. }
  1052. }
  1053. };
  1054. fn(level, locale, message, paths);
  1055. }
  1056. _initVM (data) {
  1057. const silent = Vue.config.silent;
  1058. Vue.config.silent = true;
  1059. this._vm = new Vue({ data });
  1060. Vue.config.silent = silent;
  1061. }
  1062. destroyVM () {
  1063. this._vm.$destroy();
  1064. }
  1065. subscribeDataChanging (vm) {
  1066. this._dataListeners.push(vm);
  1067. }
  1068. unsubscribeDataChanging (vm) {
  1069. remove(this._dataListeners, vm);
  1070. }
  1071. watchI18nData () {
  1072. const self = this;
  1073. return this._vm.$watch('$data', () => {
  1074. let i = self._dataListeners.length;
  1075. while (i--) {
  1076. Vue.nextTick(() => {
  1077. self._dataListeners[i] && self._dataListeners[i].$forceUpdate();
  1078. });
  1079. }
  1080. }, { deep: true })
  1081. }
  1082. watchLocale () {
  1083. /* istanbul ignore if */
  1084. if (!this._sync || !this._root) { return null }
  1085. const target = this._vm;
  1086. return this._root.$i18n.vm.$watch('locale', (val) => {
  1087. target.$set(target, 'locale', val);
  1088. target.$forceUpdate();
  1089. }, { immediate: true })
  1090. }
  1091. onComponentInstanceCreated (newI18n) {
  1092. if (this._componentInstanceCreatedListener) {
  1093. this._componentInstanceCreatedListener(newI18n, this);
  1094. }
  1095. }
  1096. get vm () { return this._vm }
  1097. get messages () { return looseClone(this._getMessages()) }
  1098. get dateTimeFormats () { return looseClone(this._getDateTimeFormats()) }
  1099. get numberFormats () { return looseClone(this._getNumberFormats()) }
  1100. get availableLocales () { return Object.keys(this.messages).sort() }
  1101. get locale () { return this._vm.locale }
  1102. set locale (locale) {
  1103. this._vm.$set(this._vm, 'locale', locale);
  1104. }
  1105. get fallbackLocale () { return this._vm.fallbackLocale }
  1106. set fallbackLocale (locale) {
  1107. this._localeChainCache = {};
  1108. this._vm.$set(this._vm, 'fallbackLocale', locale);
  1109. }
  1110. get formatFallbackMessages () { return this._formatFallbackMessages }
  1111. set formatFallbackMessages (fallback) { this._formatFallbackMessages = fallback; }
  1112. get missing () { return this._missing }
  1113. set missing (handler) { this._missing = handler; }
  1114. get formatter () { return this._formatter }
  1115. set formatter (formatter) { this._formatter = formatter; }
  1116. get silentTranslationWarn () { return this._silentTranslationWarn }
  1117. set silentTranslationWarn (silent) { this._silentTranslationWarn = silent; }
  1118. get silentFallbackWarn () { return this._silentFallbackWarn }
  1119. set silentFallbackWarn (silent) { this._silentFallbackWarn = silent; }
  1120. get preserveDirectiveContent () { return this._preserveDirectiveContent }
  1121. set preserveDirectiveContent (preserve) { this._preserveDirectiveContent = preserve; }
  1122. get warnHtmlInMessage () { return this._warnHtmlInMessage }
  1123. set warnHtmlInMessage (level) {
  1124. const orgLevel = this._warnHtmlInMessage;
  1125. this._warnHtmlInMessage = level;
  1126. if (orgLevel !== level && (level === 'warn' || level === 'error')) {
  1127. const messages = this._getMessages();
  1128. Object.keys(messages).forEach(locale => {
  1129. this._checkLocaleMessage(locale, this._warnHtmlInMessage, messages[locale]);
  1130. });
  1131. }
  1132. }
  1133. get postTranslation () { return this._postTranslation }
  1134. set postTranslation (handler) { this._postTranslation = handler; }
  1135. _getMessages () { return this._vm.messages }
  1136. _getDateTimeFormats () { return this._vm.dateTimeFormats }
  1137. _getNumberFormats () { return this._vm.numberFormats }
  1138. _warnDefault (locale, key, result, vm, values, interpolateMode) {
  1139. if (!isNull(result)) { return result }
  1140. if (this._missing) {
  1141. const missingRet = this._missing.apply(null, [locale, key, vm, values]);
  1142. if (isString(missingRet)) {
  1143. return missingRet
  1144. }
  1145. } else {
  1146. if (!this._isSilentTranslationWarn(key)) {
  1147. warn(
  1148. `Cannot translate the value of keypath '${key}'. ` +
  1149. 'Use the value of keypath as default.'
  1150. );
  1151. }
  1152. }
  1153. if (this._formatFallbackMessages) {
  1154. const parsedArgs = parseArgs(...values);
  1155. return this._render(key, interpolateMode, parsedArgs.params, key)
  1156. } else {
  1157. return key
  1158. }
  1159. }
  1160. _isFallbackRoot (val) {
  1161. return !val && !isNull(this._root) && this._fallbackRoot
  1162. }
  1163. _isSilentFallbackWarn (key) {
  1164. return this._silentFallbackWarn instanceof RegExp
  1165. ? this._silentFallbackWarn.test(key)
  1166. : this._silentFallbackWarn
  1167. }
  1168. _isSilentFallback (locale, key) {
  1169. return this._isSilentFallbackWarn(key) && (this._isFallbackRoot() || locale !== this.fallbackLocale)
  1170. }
  1171. _isSilentTranslationWarn (key) {
  1172. return this._silentTranslationWarn instanceof RegExp
  1173. ? this._silentTranslationWarn.test(key)
  1174. : this._silentTranslationWarn
  1175. }
  1176. _interpolate (
  1177. locale,
  1178. message,
  1179. key,
  1180. host,
  1181. interpolateMode,
  1182. values,
  1183. visitedLinkStack
  1184. ) {
  1185. if (!message) { return null }
  1186. const pathRet = this._path.getPathValue(message, key);
  1187. if (isArray(pathRet) || isPlainObject(pathRet)) { return pathRet }
  1188. let ret;
  1189. if (isNull(pathRet)) {
  1190. /* istanbul ignore else */
  1191. if (isPlainObject(message)) {
  1192. ret = message[key];
  1193. if (!(isString(ret) || isFunction(ret))) {
  1194. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallback(locale, key)) {
  1195. warn(`Value of key '${key}' is not a string or function !`);
  1196. }
  1197. return null
  1198. }
  1199. } else {
  1200. return null
  1201. }
  1202. } else {
  1203. /* istanbul ignore else */
  1204. if (isString(pathRet) || isFunction(pathRet)) {
  1205. ret = pathRet;
  1206. } else {
  1207. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallback(locale, key)) {
  1208. warn(`Value of key '${key}' is not a string or function!`);
  1209. }
  1210. return null
  1211. }
  1212. }
  1213. // Check for the existence of links within the translated string
  1214. if (isString(ret) && (ret.indexOf('@:') >= 0 || ret.indexOf('@.') >= 0)) {
  1215. ret = this._link(locale, message, ret, host, 'raw', values, visitedLinkStack);
  1216. }
  1217. return this._render(ret, interpolateMode, values, key)
  1218. }
  1219. _link (
  1220. locale,
  1221. message,
  1222. str,
  1223. host,
  1224. interpolateMode,
  1225. values,
  1226. visitedLinkStack
  1227. ) {
  1228. let ret = str;
  1229. // Match all the links within the local
  1230. // We are going to replace each of
  1231. // them with its translation
  1232. const matches = ret.match(linkKeyMatcher);
  1233. for (let idx in matches) {
  1234. // ie compatible: filter custom array
  1235. // prototype method
  1236. if (!matches.hasOwnProperty(idx)) {
  1237. continue
  1238. }
  1239. const link = matches[idx];
  1240. const linkKeyPrefixMatches = link.match(linkKeyPrefixMatcher);
  1241. const [linkPrefix, formatterName] = linkKeyPrefixMatches;
  1242. // Remove the leading @:, @.case: and the brackets
  1243. const linkPlaceholder = link.replace(linkPrefix, '').replace(bracketsMatcher, '');
  1244. if (includes(visitedLinkStack, linkPlaceholder)) {
  1245. {
  1246. warn(`Circular reference found. "${link}" is already visited in the chain of ${visitedLinkStack.reverse().join(' <- ')}`);
  1247. }
  1248. return ret
  1249. }
  1250. visitedLinkStack.push(linkPlaceholder);
  1251. // Translate the link
  1252. let translated = this._interpolate(
  1253. locale, message, linkPlaceholder, host,
  1254. interpolateMode === 'raw' ? 'string' : interpolateMode,
  1255. interpolateMode === 'raw' ? undefined : values,
  1256. visitedLinkStack
  1257. );
  1258. if (this._isFallbackRoot(translated)) {
  1259. if (!this._isSilentTranslationWarn(linkPlaceholder)) {
  1260. warn(`Fall back to translate the link placeholder '${linkPlaceholder}' with root locale.`);
  1261. }
  1262. /* istanbul ignore if */
  1263. if (!this._root) { throw Error('unexpected error') }
  1264. const root = this._root.$i18n;
  1265. translated = root._translate(
  1266. root._getMessages(), root.locale, root.fallbackLocale,
  1267. linkPlaceholder, host, interpolateMode, values
  1268. );
  1269. }
  1270. translated = this._warnDefault(
  1271. locale, linkPlaceholder, translated, host,
  1272. isArray(values) ? values : [values],
  1273. interpolateMode
  1274. );
  1275. if (this._modifiers.hasOwnProperty(formatterName)) {
  1276. translated = this._modifiers[formatterName](translated);
  1277. } else if (defaultModifiers.hasOwnProperty(formatterName)) {
  1278. translated = defaultModifiers[formatterName](translated);
  1279. }
  1280. visitedLinkStack.pop();
  1281. // Replace the link with the translated
  1282. ret = !translated ? ret : ret.replace(link, translated);
  1283. }
  1284. return ret
  1285. }
  1286. _createMessageContext (values) {
  1287. const _list = isArray(values) ? values : [];
  1288. const _named = isObject(values) ? values : {};
  1289. const list = (index) => _list[index];
  1290. const named = (key) => _named[key];
  1291. return {
  1292. list,
  1293. named
  1294. }
  1295. }
  1296. _render (message, interpolateMode, values, path) {
  1297. if (isFunction(message)) {
  1298. return message(this._createMessageContext(values))
  1299. }
  1300. let ret = this._formatter.interpolate(message, values, path);
  1301. // If the custom formatter refuses to work - apply the default one
  1302. if (!ret) {
  1303. ret = defaultFormatter.interpolate(message, values, path);
  1304. }
  1305. // if interpolateMode is **not** 'string' ('row'),
  1306. // return the compiled data (e.g. ['foo', VNode, 'bar']) with formatter
  1307. return interpolateMode === 'string' && !isString(ret) ? ret.join('') : ret
  1308. }
  1309. _appendItemToChain (chain, item, blocks) {
  1310. let follow = false;
  1311. if (!includes(chain, item)) {
  1312. follow = true;
  1313. if (item) {
  1314. follow = item[item.length - 1] !== '!';
  1315. item = item.replace(/!/g, '');
  1316. chain.push(item);
  1317. if (blocks && blocks[item]) {
  1318. follow = blocks[item];
  1319. }
  1320. }
  1321. }
  1322. return follow
  1323. }
  1324. _appendLocaleToChain (chain, locale, blocks) {
  1325. let follow;
  1326. const tokens = locale.split('-');
  1327. do {
  1328. const item = tokens.join('-');
  1329. follow = this._appendItemToChain(chain, item, blocks);
  1330. tokens.splice(-1, 1);
  1331. } while (tokens.length && (follow === true))
  1332. return follow
  1333. }
  1334. _appendBlockToChain (chain, block, blocks) {
  1335. let follow = true;
  1336. for (let i = 0; (i < block.length) && (isBoolean(follow)); i++) {
  1337. const locale = block[i];
  1338. if (isString(locale)) {
  1339. follow = this._appendLocaleToChain(chain, locale, blocks);
  1340. }
  1341. }
  1342. return follow
  1343. }
  1344. _getLocaleChain (start, fallbackLocale) {
  1345. if (start === '') { return [] }
  1346. if (!this._localeChainCache) {
  1347. this._localeChainCache = {};
  1348. }
  1349. let chain = this._localeChainCache[start];
  1350. if (!chain) {
  1351. if (!fallbackLocale) {
  1352. fallbackLocale = this.fallbackLocale;
  1353. }
  1354. chain = [];
  1355. // first block defined by start
  1356. let block = [start];
  1357. // while any intervening block found
  1358. while (isArray(block)) {
  1359. block = this._appendBlockToChain(
  1360. chain,
  1361. block,
  1362. fallbackLocale
  1363. );
  1364. }
  1365. // last block defined by default
  1366. let defaults;
  1367. if (isArray(fallbackLocale)) {
  1368. defaults = fallbackLocale;
  1369. } else if (isObject(fallbackLocale)) {
  1370. /* $FlowFixMe */
  1371. if (fallbackLocale['default']) {
  1372. defaults = fallbackLocale['default'];
  1373. } else {
  1374. defaults = null;
  1375. }
  1376. } else {
  1377. defaults = fallbackLocale;
  1378. }
  1379. // convert defaults to array
  1380. if (isString(defaults)) {
  1381. block = [defaults];
  1382. } else {
  1383. block = defaults;
  1384. }
  1385. if (block) {
  1386. this._appendBlockToChain(
  1387. chain,
  1388. block,
  1389. null
  1390. );
  1391. }
  1392. this._localeChainCache[start] = chain;
  1393. }
  1394. return chain
  1395. }
  1396. _translate (
  1397. messages,
  1398. locale,
  1399. fallback,
  1400. key,
  1401. host,
  1402. interpolateMode,
  1403. args
  1404. ) {
  1405. const chain = this._getLocaleChain(locale, fallback);
  1406. let res;
  1407. for (let i = 0; i < chain.length; i++) {
  1408. const step = chain[i];
  1409. res =
  1410. this._interpolate(step, messages[step], key, host, interpolateMode, args, [key]);
  1411. if (!isNull(res)) {
  1412. if (step !== locale && "development" !== 'production' && !this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1413. warn(("Fall back to translate the keypath '" + key + "' with '" + step + "' locale."));
  1414. }
  1415. return res
  1416. }
  1417. }
  1418. return null
  1419. }
  1420. _t (key, _locale, messages, host, ...values) {
  1421. if (!key) { return '' }
  1422. const parsedArgs = parseArgs(...values);
  1423. const locale = parsedArgs.locale || _locale;
  1424. let ret = this._translate(
  1425. messages, locale, this.fallbackLocale, key,
  1426. host, 'string', parsedArgs.params
  1427. );
  1428. if (this._isFallbackRoot(ret)) {
  1429. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1430. warn(`Fall back to translate the keypath '${key}' with root locale.`);
  1431. }
  1432. /* istanbul ignore if */
  1433. if (!this._root) { throw Error('unexpected error') }
  1434. return this._root.$t(key, ...values)
  1435. } else {
  1436. ret = this._warnDefault(locale, key, ret, host, values, 'string');
  1437. if (this._postTranslation && ret !== null && ret !== undefined) {
  1438. ret = this._postTranslation(ret, key);
  1439. }
  1440. return ret
  1441. }
  1442. }
  1443. t (key, ...values) {
  1444. return this._t(key, this.locale, this._getMessages(), null, ...values)
  1445. }
  1446. _i (key, locale, messages, host, values) {
  1447. const ret =
  1448. this._translate(messages, locale, this.fallbackLocale, key, host, 'raw', values);
  1449. if (this._isFallbackRoot(ret)) {
  1450. if (!this._isSilentTranslationWarn(key)) {
  1451. warn(`Fall back to interpolate the keypath '${key}' with root locale.`);
  1452. }
  1453. if (!this._root) { throw Error('unexpected error') }
  1454. return this._root.$i18n.i(key, locale, values)
  1455. } else {
  1456. return this._warnDefault(locale, key, ret, host, [values], 'raw')
  1457. }
  1458. }
  1459. i (key, locale, values) {
  1460. /* istanbul ignore if */
  1461. if (!key) { return '' }
  1462. if (!isString(locale)) {
  1463. locale = this.locale;
  1464. }
  1465. return this._i(key, locale, this._getMessages(), null, values)
  1466. }
  1467. _tc (
  1468. key,
  1469. _locale,
  1470. messages,
  1471. host,
  1472. choice,
  1473. ...values
  1474. ) {
  1475. if (!key) { return '' }
  1476. if (choice === undefined) {
  1477. choice = 1;
  1478. }
  1479. const predefined = { 'count': choice, 'n': choice };
  1480. const parsedArgs = parseArgs(...values);
  1481. parsedArgs.params = Object.assign(predefined, parsedArgs.params);
  1482. values = parsedArgs.locale === null ? [parsedArgs.params] : [parsedArgs.locale, parsedArgs.params];
  1483. return this.fetchChoice(this._t(key, _locale, messages, host, ...values), choice)
  1484. }
  1485. fetchChoice (message, choice) {
  1486. /* istanbul ignore if */
  1487. if (!message && !isString(message)) { return null }
  1488. const choices = message.split('|');
  1489. choice = this.getChoiceIndex(choice, choices.length);
  1490. if (!choices[choice]) { return message }
  1491. return choices[choice].trim()
  1492. }
  1493. tc (key, choice, ...values) {
  1494. return this._tc(key, this.locale, this._getMessages(), null, choice, ...values)
  1495. }
  1496. _te (key, locale, messages, ...args) {
  1497. const _locale = parseArgs(...args).locale || locale;
  1498. return this._exist(messages[_locale], key)
  1499. }
  1500. te (key, locale) {
  1501. return this._te(key, this.locale, this._getMessages(), locale)
  1502. }
  1503. getLocaleMessage (locale) {
  1504. return looseClone(this._vm.messages[locale] || {})
  1505. }
  1506. setLocaleMessage (locale, message) {
  1507. if (this._warnHtmlInMessage === 'warn' || this._warnHtmlInMessage === 'error') {
  1508. this._checkLocaleMessage(locale, this._warnHtmlInMessage, message);
  1509. }
  1510. this._vm.$set(this._vm.messages, locale, message);
  1511. }
  1512. mergeLocaleMessage (locale, message) {
  1513. if (this._warnHtmlInMessage === 'warn' || this._warnHtmlInMessage === 'error') {
  1514. this._checkLocaleMessage(locale, this._warnHtmlInMessage, message);
  1515. }
  1516. this._vm.$set(this._vm.messages, locale, merge({}, this._vm.messages[locale] || {}, message));
  1517. }
  1518. getDateTimeFormat (locale) {
  1519. return looseClone(this._vm.dateTimeFormats[locale] || {})
  1520. }
  1521. setDateTimeFormat (locale, format) {
  1522. this._vm.$set(this._vm.dateTimeFormats, locale, format);
  1523. this._clearDateTimeFormat(locale, format);
  1524. }
  1525. mergeDateTimeFormat (locale, format) {
  1526. this._vm.$set(this._vm.dateTimeFormats, locale, merge(this._vm.dateTimeFormats[locale] || {}, format));
  1527. this._clearDateTimeFormat(locale, format);
  1528. }
  1529. _clearDateTimeFormat (locale, format) {
  1530. for (let key in format) {
  1531. const id = `${locale}__${key}`;
  1532. if (!this._dateTimeFormatters.hasOwnProperty(id)) {
  1533. continue
  1534. }
  1535. delete this._dateTimeFormatters[id];
  1536. }
  1537. }
  1538. _localizeDateTime (
  1539. value,
  1540. locale,
  1541. fallback,
  1542. dateTimeFormats,
  1543. key
  1544. ) {
  1545. let _locale = locale;
  1546. let formats = dateTimeFormats[_locale];
  1547. const chain = this._getLocaleChain(locale, fallback);
  1548. for (let i = 0; i < chain.length; i++) {
  1549. const current = _locale;
  1550. const step = chain[i];
  1551. formats = dateTimeFormats[step];
  1552. _locale = step;
  1553. // fallback locale
  1554. if (isNull(formats) || isNull(formats[key])) {
  1555. if (step !== locale && "development" !== 'production' && !this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1556. warn(`Fall back to '${step}' datetime formats from '${current}' datetime formats.`);
  1557. }
  1558. } else {
  1559. break
  1560. }
  1561. }
  1562. if (isNull(formats) || isNull(formats[key])) {
  1563. return null
  1564. } else {
  1565. const format = formats[key];
  1566. const id = `${_locale}__${key}`;
  1567. let formatter = this._dateTimeFormatters[id];
  1568. if (!formatter) {
  1569. formatter = this._dateTimeFormatters[id] = new Intl.DateTimeFormat(_locale, format);
  1570. }
  1571. return formatter.format(value)
  1572. }
  1573. }
  1574. _d (value, locale, key) {
  1575. /* istanbul ignore if */
  1576. if (!VueI18n.availabilities.dateTimeFormat) {
  1577. warn('Cannot format a Date value due to not supported Intl.DateTimeFormat.');
  1578. return ''
  1579. }
  1580. if (!key) {
  1581. return new Intl.DateTimeFormat(locale).format(value)
  1582. }
  1583. const ret =
  1584. this._localizeDateTime(value, locale, this.fallbackLocale, this._getDateTimeFormats(), key);
  1585. if (this._isFallbackRoot(ret)) {
  1586. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1587. warn(`Fall back to datetime localization of root: key '${key}'.`);
  1588. }
  1589. /* istanbul ignore if */
  1590. if (!this._root) { throw Error('unexpected error') }
  1591. return this._root.$i18n.d(value, key, locale)
  1592. } else {
  1593. return ret || ''
  1594. }
  1595. }
  1596. d (value, ...args) {
  1597. let locale = this.locale;
  1598. let key = null;
  1599. if (args.length === 1) {
  1600. if (isString(args[0])) {
  1601. key = args[0];
  1602. } else if (isObject(args[0])) {
  1603. if (args[0].locale) {
  1604. locale = args[0].locale;
  1605. }
  1606. if (args[0].key) {
  1607. key = args[0].key;
  1608. }
  1609. }
  1610. } else if (args.length === 2) {
  1611. if (isString(args[0])) {
  1612. key = args[0];
  1613. }
  1614. if (isString(args[1])) {
  1615. locale = args[1];
  1616. }
  1617. }
  1618. return this._d(value, locale, key)
  1619. }
  1620. getNumberFormat (locale) {
  1621. return looseClone(this._vm.numberFormats[locale] || {})
  1622. }
  1623. setNumberFormat (locale, format) {
  1624. this._vm.$set(this._vm.numberFormats, locale, format);
  1625. this._clearNumberFormat(locale, format);
  1626. }
  1627. mergeNumberFormat (locale, format) {
  1628. this._vm.$set(this._vm.numberFormats, locale, merge(this._vm.numberFormats[locale] || {}, format));
  1629. this._clearNumberFormat(locale, format);
  1630. }
  1631. _clearNumberFormat (locale, format) {
  1632. for (let key in format) {
  1633. const id = `${locale}__${key}`;
  1634. if (!this._numberFormatters.hasOwnProperty(id)) {
  1635. continue
  1636. }
  1637. delete this._numberFormatters[id];
  1638. }
  1639. }
  1640. _getNumberFormatter (
  1641. value,
  1642. locale,
  1643. fallback,
  1644. numberFormats,
  1645. key,
  1646. options
  1647. ) {
  1648. let _locale = locale;
  1649. let formats = numberFormats[_locale];
  1650. const chain = this._getLocaleChain(locale, fallback);
  1651. for (let i = 0; i < chain.length; i++) {
  1652. const current = _locale;
  1653. const step = chain[i];
  1654. formats = numberFormats[step];
  1655. _locale = step;
  1656. // fallback locale
  1657. if (isNull(formats) || isNull(formats[key])) {
  1658. if (step !== locale && "development" !== 'production' && !this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1659. warn(`Fall back to '${step}' number formats from '${current}' number formats.`);
  1660. }
  1661. } else {
  1662. break
  1663. }
  1664. }
  1665. if (isNull(formats) || isNull(formats[key])) {
  1666. return null
  1667. } else {
  1668. const format = formats[key];
  1669. let formatter;
  1670. if (options) {
  1671. // If options specified - create one time number formatter
  1672. formatter = new Intl.NumberFormat(_locale, Object.assign({}, format, options));
  1673. } else {
  1674. const id = `${_locale}__${key}`;
  1675. formatter = this._numberFormatters[id];
  1676. if (!formatter) {
  1677. formatter = this._numberFormatters[id] = new Intl.NumberFormat(_locale, format);
  1678. }
  1679. }
  1680. return formatter
  1681. }
  1682. }
  1683. _n (value, locale, key, options) {
  1684. /* istanbul ignore if */
  1685. if (!VueI18n.availabilities.numberFormat) {
  1686. {
  1687. warn('Cannot format a Number value due to not supported Intl.NumberFormat.');
  1688. }
  1689. return ''
  1690. }
  1691. if (!key) {
  1692. const nf = !options ? new Intl.NumberFormat(locale) : new Intl.NumberFormat(locale, options);
  1693. return nf.format(value)
  1694. }
  1695. const formatter = this._getNumberFormatter(value, locale, this.fallbackLocale, this._getNumberFormats(), key, options);
  1696. const ret = formatter && formatter.format(value);
  1697. if (this._isFallbackRoot(ret)) {
  1698. if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) {
  1699. warn(`Fall back to number localization of root: key '${key}'.`);
  1700. }
  1701. /* istanbul ignore if */
  1702. if (!this._root) { throw Error('unexpected error') }
  1703. return this._root.$i18n.n(value, Object.assign({}, { key, locale }, options))
  1704. } else {
  1705. return ret || ''
  1706. }
  1707. }
  1708. n (value, ...args) {
  1709. let locale = this.locale;
  1710. let key = null;
  1711. let options = null;
  1712. if (args.length === 1) {
  1713. if (isString(args[0])) {
  1714. key = args[0];
  1715. } else if (isObject(args[0])) {
  1716. if (args[0].locale) {
  1717. locale = args[0].locale;
  1718. }
  1719. if (args[0].key) {
  1720. key = args[0].key;
  1721. }
  1722. // Filter out number format options only
  1723. options = Object.keys(args[0]).reduce((acc, key) => {
  1724. if (includes(numberFormatKeys, key)) {
  1725. return Object.assign({}, acc, { [key]: args[0][key] })
  1726. }
  1727. return acc
  1728. }, null);
  1729. }
  1730. } else if (args.length === 2) {
  1731. if (isString(args[0])) {
  1732. key = args[0];
  1733. }
  1734. if (isString(args[1])) {
  1735. locale = args[1];
  1736. }
  1737. }
  1738. return this._n(value, locale, key, options)
  1739. }
  1740. _ntp (value, locale, key, options) {
  1741. /* istanbul ignore if */
  1742. if (!VueI18n.availabilities.numberFormat) {
  1743. {
  1744. warn('Cannot format to parts a Number value due to not supported Intl.NumberFormat.');
  1745. }
  1746. return []
  1747. }
  1748. if (!key) {
  1749. const nf = !options ? new Intl.NumberFormat(locale) : new Intl.NumberFormat(locale, options);
  1750. return nf.formatToParts(value)
  1751. }
  1752. const formatter = this._getNumberFormatter(value, locale, this.fallbackLocale, this._getNumberFormats(), key, options);
  1753. const ret = formatter && formatter.formatToParts(value);
  1754. if (this._isFallbackRoot(ret)) {
  1755. if (!this._isSilentTranslationWarn(key)) {
  1756. warn(`Fall back to format number to parts of root: key '${key}' .`);
  1757. }
  1758. /* istanbul ignore if */
  1759. if (!this._root) { throw Error('unexpected error') }
  1760. return this._root.$i18n._ntp(value, locale, key, options)
  1761. } else {
  1762. return ret || []
  1763. }
  1764. }
  1765. }
  1766. let availabilities;
  1767. // $FlowFixMe
  1768. Object.defineProperty(VueI18n, 'availabilities', {
  1769. get () {
  1770. if (!availabilities) {
  1771. const intlDefined = typeof Intl !== 'undefined';
  1772. availabilities = {
  1773. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  1774. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  1775. };
  1776. }
  1777. return availabilities
  1778. }
  1779. });
  1780. VueI18n.install = install;
  1781. VueI18n.version = '8.21.0';
  1782. export default VueI18n;