vue-i18n.common.js 60 KB

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