Code coverage report for lib/localize.js

Statements: 100% (32 / 32)      Branches: 100% (14 / 14)      Functions: 100% (5 / 5)      Lines: 100% (32 / 32)      Ignored: none     

All files » lib/ » localize.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74    1   1 11 1   10 1   9 1       1 10             10 10       1   10       1 10           8 8 9           8 1     8 8 4 4   8 9 9 10           8 4   8    
'use strict';
 
var utils = require('./utils');
 
module.exports = function(html, options) {
  if (!options.nativeLocale) {
    throw new Error('s18n: missing required option `nativeLocale`.');
  }
  if (!options.locales && !options.locale) {
    throw new Error('s18n: missing required option `locale` or `locales`.');
  }
  if (options.locales && options.locale) {
    throw new Error('s18n: both `locale` and `locales` options are defined.');
  }
 
  // avoids unintentional localization of unrelated strings
  function softReplace(document, nativeString, localizedString) {
    var escapedString = ignoreExtraSpaces(
      ignoreEmptyAttrs(
        utils.escapeRegExpSpecialChars(
          nativeString
        )
      )
    );
    var regex = new RegExp('([>"\']\\s*)(' + escapedString + ')(\\s*[<"\'])', 'g');
    return document.replace(regex, '$1' + localizedString + '$3');
  }
 
  // reconcile output of htmlparser2's `toString()` with the original document
  function ignoreEmptyAttrs(string) {
    // make `=""` optional in regex
    return string.replace(/(\\\="")/g, '\(\?\:\\\=""\)\?');
  }
 
  // reconcile output of htmlparser2's `toString()` with the original document
  function ignoreExtraSpaces(string) {
    return string.replace(/(\s+)/g, '\\s+')
    .replace(/(<\\\/)/g, '<\/\\s*')
      .replace(/(<)/g, '<\\s*')
      .replace(/(>)/g, '\\s*>');
  }
 
  var nativeLocale = [];
  for (var hash in options.nativeLocale) {
    nativeLocale.push({
      hash: hash,
      string: options.nativeLocale[hash]
    });
  }
  //sort nativeLocale by length to match longest strings first
  nativeLocale.sort(function(a, b) {
    return b.string.length - a.string.length;
  });
 
  var localizations = {};
  if (options.locale) {
    options.locales = {};
    options.locales.tmp = options.locale;
  }
  for (var id in options.locales) {
    localizations[id] = html;
    for (var i = 0; i < nativeLocale.length; i++) {
      localizations[id] = softReplace(
        localizations[id],
        nativeLocale[i].string,
        options.locales[id][nativeLocale[i].hash]);
    }
  }
  if (options.locale) {
    localizations = localizations.tmp;
  }
  return localizations;
};