locale.js 1.6 KB

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