ShowFor.prototype.ensureSelect = function()

in kitsune/sumo/static/sumo/js/showfor.js [90:177]


ShowFor.prototype.ensureSelect = function ($select, type, product, val) {
  var $opt;
  var key;
  var extra = {};
  var target;

  // Version pattern used for parsing product versions (e.g., 'fx114', 'm95')
  const VERSION_PATTERN = /^([a-z]+)(\d+)/;

  function select(searchArray, slug) {
    for (var i = 0; i < searchArray.length; i++) {
      if (searchArray[i].slug === slug) {
        return searchArray[i];
      }
    }
    return null;
  }

  if (type === 'version') {
    const exactVersionVal = 'version:' + val;
    const exactMatch = $select.find('option[value="' + exactVersionVal + '"]');

    if (exactMatch.length > 0) {
      $select.val(exactVersionVal);
      return;
    }

    const versionMatch = val.match(VERSION_PATTERN);
    if (versionMatch) {
      const [, productPrefix, versionStr] = versionMatch;
      const browserVersion = parseInt(versionStr, 10);

      let highestOption = null;
      let highestVersionNum = 0;

      $select.find('option').each(function () {
        const optVal = $(this).val();
        const optSlug = optVal.split(':')[1];
        const optMatch = optSlug.match(VERSION_PATTERN);

        if (optMatch && optMatch[1] === productPrefix) {
          const optVersion = parseInt(optMatch[2], 10);
          if (optVersion > highestVersionNum) {
            highestVersionNum = optVersion;
            highestOption = optVal;
          }
        }
      });

      if (highestOption && browserVersion > highestVersionNum) {
        $select.val(highestOption);
        return;
      }
    }

    target = select(this.data.versions[product], val);
    if (target !== null) {
      extra['data-min'] = target.min_version;
      extra['data-max'] = target.max_version;
    }
  } else if (type === 'platform') {
    target = select(this.data.platforms[product], val);
  } else if (type === 'product') {
    target = select(this.data.products, val);
  } else {
    throw new Error('Unknown showfor select type ' + type);
  }

  // This will fail if there is no version/product/platform that
  // matches the desired val.
  if (target === null) {
    return;
  }

  val = type + ':' + val;

  if ($select.find('option[value="' + val + '"]').length === 0) {
    $opt = $('<option>')
      .attr('value', val)
      .text(target.name);
    for (key in extra) {
      $opt.attr(key, extra[key]);
    }
    $select.append($opt);
  }

  $select.val(val);
};