Translator.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /**
  2. * Translates strings with interpolation & pluralization support.
  3. * Extensible with custom dictionaries and pluralization functions.
  4. *
  5. * Borrows heavily from and inspired by Polyglot https://github.com/airbnb/polyglot.js,
  6. * basically a stripped-down version of it. Differences: pluralization functions are not hardcoded
  7. * and can be easily added among with dictionaries, nested objects are used for pluralization
  8. * as opposed to `||||` delimeter
  9. *
  10. * Usage example: `translator.translate('files_chosen', {smart_count: 3})`
  11. *
  12. * @param {object|Array<object>} locale Locale or list of locales.
  13. */
  14. module.exports = class Translator {
  15. constructor (locales) {
  16. this.locale = {
  17. strings: {},
  18. pluralize: function (n) {
  19. if (n === 1) {
  20. return 0
  21. }
  22. return 1
  23. }
  24. }
  25. if (Array.isArray(locales)) {
  26. locales.forEach((locale) => this._apply(locale))
  27. } else {
  28. this._apply(locales)
  29. }
  30. }
  31. _apply (locale) {
  32. if (!locale || !locale.strings) {
  33. return
  34. }
  35. const prevLocale = this.locale
  36. this.locale = Object.assign({}, prevLocale, {
  37. strings: Object.assign({}, prevLocale.strings, locale.strings)
  38. })
  39. this.locale.pluralize = locale.pluralize || prevLocale.pluralize
  40. }
  41. /**
  42. * Takes a string with placeholder variables like `%{smart_count} file selected`
  43. * and replaces it with values from options `{smart_count: 5}`
  44. *
  45. * @license https://github.com/airbnb/polyglot.js/blob/master/LICENSE
  46. * taken from https://github.com/airbnb/polyglot.js/blob/master/lib/polyglot.js#L299
  47. *
  48. * @param {string} phrase that needs interpolation, with placeholders
  49. * @param {Object} options with values that will be used to replace placeholders
  50. * @returns {string} interpolated
  51. */
  52. interpolate (phrase, options) {
  53. const { split, replace } = String.prototype
  54. const dollarRegex = /\$/g
  55. const dollarBillsYall = '$$$$'
  56. let interpolated = [phrase]
  57. for (let arg in options) {
  58. if (arg !== '_' && options.hasOwnProperty(arg)) {
  59. // Ensure replacement value is escaped to prevent special $-prefixed
  60. // regex replace tokens. the "$$$$" is needed because each "$" needs to
  61. // be escaped with "$" itself, and we need two in the resulting output.
  62. var replacement = options[arg]
  63. if (typeof replacement === 'string') {
  64. replacement = replace.call(options[arg], dollarRegex, dollarBillsYall)
  65. }
  66. // We create a new `RegExp` each time instead of using a more-efficient
  67. // string replace so that the same argument can be replaced multiple times
  68. // in the same phrase.
  69. interpolated = insertReplacement(interpolated, new RegExp('%\\{' + arg + '\\}', 'g'), replacement)
  70. }
  71. }
  72. return interpolated
  73. function insertReplacement (source, rx, replacement) {
  74. const newParts = []
  75. source.forEach((chunk) => {
  76. split.call(chunk, rx).forEach((raw, i, list) => {
  77. if (raw !== '') {
  78. newParts.push(raw)
  79. }
  80. // Interlace with the `replacement` value
  81. if (i < list.length - 1) {
  82. newParts.push(replacement)
  83. }
  84. })
  85. })
  86. return newParts
  87. }
  88. }
  89. /**
  90. * Public translate method
  91. *
  92. * @param {string} key
  93. * @param {Object} options with values that will be used later to replace placeholders in string
  94. * @returns {string} translated (and interpolated)
  95. */
  96. translate (key, options) {
  97. return this.translateArray(key, options).join('')
  98. }
  99. /**
  100. * Get a translation and return the translated and interpolated parts as an array.
  101. *
  102. * @param {string} key
  103. * @param {Object} options with values that will be used to replace placeholders
  104. * @returns {Array} The translated and interpolated parts, in order.
  105. */
  106. translateArray (key, options) {
  107. if (options && typeof options.smart_count !== 'undefined') {
  108. var plural = this.locale.pluralize(options.smart_count)
  109. return this.interpolate(this.locale.strings[key][plural], options)
  110. }
  111. return this.interpolate(this.locale.strings[key], options)
  112. }
  113. }