vue-i18n.esm.browser.js 58 KB

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