locale.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module utils/locale
  7. */
  8. import { translate } from './translation-service';
  9. /**
  10. * Represents the localization services.
  11. */
  12. export default class Locale {
  13. /**
  14. * Creates a new instance of the Locale class.
  15. *
  16. * @param {String} [language='en'] The language code in [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) format.
  17. */
  18. constructor( language ) {
  19. /**
  20. * The language code in [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) format.
  21. *
  22. * @readonly
  23. * @member {String}
  24. */
  25. this.language = language || 'en';
  26. /**
  27. * Translates the given string to the {@link #language}. This method is also available in {@link module:core/editor/editor~Editor#t}
  28. * and {@link module:ui/view~View#t}.
  29. *
  30. * The strings may contain placeholders (`%<index>`) for values which are passed as the second argument.
  31. * `<index>` is the index in the `values` array.
  32. *
  33. * editor.t( 'Created file "%0" in %1ms.', [ fileName, timeTaken ] );
  34. *
  35. * This method's context is statically bound to Locale instance,
  36. * so it can be called as a function:
  37. *
  38. * const t = this.t;
  39. * t( 'Label' );
  40. *
  41. * @method #t
  42. * @param {String} str The string to translate.
  43. * @param {String[]} [values] Values that should be used to interpolate the string.
  44. */
  45. this.t = ( ...args ) => this._t( ...args );
  46. }
  47. /**
  48. * Base for the {@link #t} method.
  49. *
  50. * @private
  51. */
  52. _t( str, values ) {
  53. let translatedString = translate( this.language, str );
  54. if ( values ) {
  55. translatedString = translatedString.replace( /%(\d+)/g, ( match, index ) => {
  56. return ( index < values.length ) ? values[ index ] : match;
  57. } );
  58. }
  59. return translatedString;
  60. }
  61. }