<commit_before>angular.module('codepuppy').controller('NavigationCtrl',
['$scope', '$stateParams', '$http', function($scope, $stateParams, $http) {

  $scope.navigationSelectors = [];

  /* Compute the selected attribute for 'navSelector' based on the routing
   * parameter 'targetSuffix' */
  function computeSelected(navSelector, targetSuffix) {
    var endsWith = function(string, query) {
      return (string.length >= query.length &&
        string.substr(string.length - query.length) == query);
    };

    var elements = navSelector.elements;
    for (i = 0; i < elements.length; ++i) {
      if (endsWith(elements[i].url, targetSuffix)) {
        navSelector.selected = elements[i].name;
      }
    }
  }

  var getCourses = function() {
    $http({method: 'GET', url: '/courses/active.json', cache:true})
    .success(function(data, status, headers, config) {
      var courses = [];
      for (var i = 0; i < data.length; ++i) {
        courses.push({
          name: data[i].course_name + ' (' +
            data[i].term_name + ' ' +
            data[i].period + ')',
          url: '/#/courses/' + data[i].id
        });
      }
      var courseNav = {'title': 'Courses', 'elements': courses,
        'selected': null};
      if ($stateParams.courseID !== undefined) {
        computeSelected(courseNav, $stateParams.courseID);
      }
      $scope.navigationSelectors[0] = courseNav;
    });
  };

  /* COURSE HANDLING */
  getCourses();

  // If they haven't selected a course, this is all we need to render
  if ($stateParams.courseID === undefined)
    return;

  /* ASSIGNMENT HANDLING */
  var getAssignments = function(courseID) {
    $http({method: 'GET', url: '/courses/' + courseID + '/assignments.json', cache:true})
    .success(function(data, status, headers, config) {
      var assignments = [];
      for (var i = 0; i < data.length; ++i) {
        assignments.push({
          'name': 'Assignment ' + data[i].number,
          'url': '/#/courses/' + courseID + '/assignments/' + data[i].id
        });
      }
      var assignmentNav = {'title': 'Assignments', 'elements': assignments,
        'selected': null};
      if ($stateParams.assigmentID !== undefined)
        computeSelected(assignmentNav, $stateParams.assignmentID);
      $scope.navigationSelectors[1] = assignmentNav;
    });
  };

  getAssignments($stateParams.courseID);

  // If they haven't selected an assignment, this is all we need to render
  if ($stateParams.assignmentID === undefined)
    return;

  /* SUBMISSION HANDLING */
  var getSubmissions = function(courseID, assignmentID) {
    $http({method: 'GET', url: '/assignments/' + assignmentID +
          '/submissions.json'})
    .success(function(data, status, headers, config) {
      var submissions = [];
      for (var i = 0; i < data.length; ++i) {
        submissions.push({
          'name': 'Submission: ' + data[i].person.user_system_id,
          'url': '/#/courses/' + courseID + '/assignments/' + assignmentID +
            '/submissions/' + data[i].submission.id
        });
      }
      var submissionNav = {'title': 'Submissions', 'elements': submissions,
        'selected': null};
      if ($stateParams.submissionID !== undefined)
        computeSelected(submissionNav, $stateParams.submissionID);
      $scope.navigationSelectors[2] = submissionNav;
    });
  };

  getSubmissions($stateParams.courseID, $stateParams.assignmentID);
}]);
<commit_msg>Fixed typo.  Now assignment nav bar expands and collapses<commit_after>angular.module('codepuppy').controller('NavigationCtrl',
['$scope', '$stateParams', '$http', function($scope, $stateParams, $http) {

  $scope.navigationSelectors = [];

  /* Compute the selected attribute for 'navSelector' based on the routing
   * parameter 'targetSuffix' */
  function computeSelected(navSelector, targetSuffix) {
    var endsWith = function(string, query) {
      return (string.length >= query.length &&
        string.substr(string.length - query.length) == query);
    };

    var elements = navSelector.elements;
    for (i = 0; i < elements.length; ++i) {
      if (endsWith(elements[i].url, targetSuffix)) {
        navSelector.selected = elements[i].name;
      }
    }
  }

  var getCourses = function() {
    $http({method: 'GET', url: '/courses/active.json', cache:true})
    .success(function(data, status, headers, config) {
      var courses = [];
      for (var i = 0; i < data.length; ++i) {
        courses.push({
          name: data[i].course_name + ' (' +
            data[i].term_name + ' ' +
            data[i].period + ')',
          url: '/#/courses/' + data[i].id
        });
      }
      var courseNav = {'title': 'Courses', 'elements': courses,
        'selected': null};
      if ($stateParams.courseID !== undefined) {
        computeSelected(courseNav, $stateParams.courseID);
      }
      $scope.navigationSelectors[0] = courseNav;
    });
  };

  /* COURSE HANDLING */
  getCourses();

  // If they haven't selected a course, this is all we need to render
  if ($stateParams.courseID === undefined)
    return;

  /* ASSIGNMENT HANDLING */
  var getAssignments = function(courseID) {
    $http({method: 'GET', url: '/courses/' + courseID + '/assignments.json', cache:true})
    .success(function(data, status, headers, config) {
      var assignments = [];
      for (var i = 0; i < data.length; ++i) {
        assignments.push({
          'name': 'Assignment ' + data[i].number,
          'url': '/#/courses/' + courseID + '/assignments/' + data[i].id
        });
      }
      var assignmentNav = {'title': 'Assignments', 'elements': assignments,
        'selected': null};
      if ($stateParams.assignmentID !== undefined)
        computeSelected(assignmentNav, $stateParams.assignmentID);
      $scope.navigationSelectors[1] = assignmentNav;
    });
  };

  getAssignments($stateParams.courseID);

  // If they haven't selected an assignment, this is all we need to render
  if ($stateParams.assignmentID === undefined)
    return;

  /* SUBMISSION HANDLING */
  var getSubmissions = function(courseID, assignmentID) {
    $http({method: 'GET', url: '/assignments/' + assignmentID +
          '/submissions.json'})
    .success(function(data, status, headers, config) {
      var submissions = [];
      for (var i = 0; i < data.length; ++i) {
        submissions.push({
          'name': 'Submission: ' + data[i].person.user_system_id,
          'url': '/#/courses/' + courseID + '/assignments/' + assignmentID +
            '/submissions/' + data[i].submission.id
        });
      }
      var submissionNav = {'title': 'Submissions', 'elements': submissions,
        'selected': null};
      if ($stateParams.submissionID !== undefined)
        computeSelected(submissionNav, $stateParams.submissionID);
      $scope.navigationSelectors[2] = submissionNav;
    });
  };

  getSubmissions($stateParams.courseID, $stateParams.assignmentID);
}]);
<|endoftext|>


<commit_before>$(document).on('ready', function() {
  _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;

  $('form.petition-tool').on('submit', function(ev) {
    var form = $(ev.currentTarget);

    // There are two types of errors: inline (.has-error) and not (.alert-danger)
    form.find('.has-error').removeClass('has-error');
    form.find('.alert-danger').remove();
    form.find('.error').remove();
    form.find(".progress-striped").show();
    form.find("input[type=submit]").hide();
    var petition_id = $('[name="petition-id"]', form).val();
    // var url = 'http://eff-call-tool.herokuapp.com/eff_test';
    var url = '/tools/petition';
    $.ajax({
      url: url,
      data: form.serializeObject(),
      type: 'POST',
      success: function(data) {
        if (data.success) {
          $('#petition-tool').removeClass('unsigned').addClass('signed');
          height_changed();
          incrementPetitionCount();
        }
        else if (data.errors) {
          var errors = JSON.parse(data.errors);
          for (var field_name in errors) {
            var field = form.find("#signature_" + field_name);
            var error = $('
').text(errors[field_name]);
            if (field.length) {
              error.prepend(field.attr('placeholder') + ': ');
              field.closest('fieldset').addClass('has-error');
              error.insertAfter(field);
              form.find(".progress-striped").hide;
              form.find("input[type=submit]").show();
            }
            else {
              show_error(error, form);
            }
          }
        }
      },
      error: function() {
        show_error("Something seems to have gone wrong. Please try again.", form);
      }
    });
    return false;
  });

  function show_error(error, form) {
    form.find(".progress-striped").hide();
    form.find("input[type=submit]").show();
    form.find('.alert-danger').remove();
    form.prepend($('
').text(error));
  }

  function incrementPetitionCount() {
    var n = getPetitionCount() + 1;
    setPetitionCountValue(n);
  }

  // give it an integer and it prints it all pretty on the screen
  function setPetitionCountValue(n) {
    var countEle = petitionCountElement();
    countEle.text(applyPrettyFormatting(n));

    function applyPrettyFormatting() {
      return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
  }

  function getPetitionCount() {
    var countEle = petitionCountElement();
    return parseInt(countEle.text().replace(",",""));
  }

  function petitionCountElement() {
    return $('#petition-tool .count b');
  }

  var getSignaturesInterval = 2000;
  var previousSignatures = {};
  var getSignatures = function(){
    $.ajax({
      url: '/petition/' + petition_id + '/recent_signatures',
      success: function(data){
        var signatures_total = data.signatures_total;
        setPetitionCountValue(signatures_total);

        var progress_total = $('.signatures-bar').attr('aria-valuemax');
        $(".signatures-bar").attr('aria-valuenow', signatures_total).css({width: signatures_total/progress_total*100 + '%'});
        var signatures = data.signatories;
        var individual_signature_template = $('#individual_signature').html();
        var signatures_html = _.map(signatures, function(signature){
          return _.template(individual_signature_template)({
            name: (signature.first_name ? signature.first_name + " " + signature.last_name : "Anonymous"),
            location: signature.location,
            time_ago: signature.time_ago + " ago"
          });
        }).join("");
        $("div#signatures tbody").html(signatures_html);

        // did anything change? if no, wait longer til next check.
        if (_.isEqual(data, previousSignatures)) {
          getSignaturesInterval *= 2;
        } else {
          getSignaturesInterval = 2000;
        }
        previousSignatures = data
        window.setTimeout(getSignatures, getSignaturesInterval);
      },
      error: function() {
        window.setTimeout(getSignatures, getSignaturesInterval);
      }
    });
  }

  var zip_pattern = '\\d{5}(-?\\d{4})?';

  var toggle_intl = function(){
    $('.intl-toggle').toggle();
    height_changed();
    if ($('.intl:visible').length) {
      $('#signature_zipcode').removeAttr('required');
      $('#signature_zipcode').removeAttr('pattern');
      $('#signature_city, #signature_country_code').attr('required', 'required');
    } else {
      $('#signature_zipcode').attr('required', 'required')
      $('#signature_zipcode').attr('pattern', zip_pattern);
      $('#signature_city, #signature_country_code').removeAttr('required');
    }
  }

  if($('#petition-tool').length != 0) {
    window.setTimeout(getSignatures, getSignaturesInterval);

    $('#signature_zipcode').attr('required', 'required')
    $('#signature_zipcode').attr('pattern', zip_pattern);
  }

  if(typeof international_only != 'undefined' && international_only){
    toggle_intl();
    $('.intl-toggler').hide();
  }

  $('.intl-toggler').click(function(e) {
    toggle_intl();
  });

});
<commit_msg>do not require zipcode if action is international only - fixes EFForg/ngw-website#6<commit_after>$(document).on('ready', function() {
  _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;

  $('form.petition-tool').on('submit', function(ev) {
    var form = $(ev.currentTarget);

    // There are two types of errors: inline (.has-error) and not (.alert-danger)
    form.find('.has-error').removeClass('has-error');
    form.find('.alert-danger').remove();
    form.find('.error').remove();
    form.find(".progress-striped").show();
    form.find("input[type=submit]").hide();
    var petition_id = $('[name="petition-id"]', form).val();
    // var url = 'http://eff-call-tool.herokuapp.com/eff_test';
    var url = '/tools/petition';
    $.ajax({
      url: url,
      data: form.serializeObject(),
      type: 'POST',
      success: function(data) {
        if (data.success) {
          $('#petition-tool').removeClass('unsigned').addClass('signed');
          height_changed();
          incrementPetitionCount();
        }
        else if (data.errors) {
          var errors = JSON.parse(data.errors);
          for (var field_name in errors) {
            var field = form.find("#signature_" + field_name);
            var error = $('
').text(errors[field_name]);
            if (field.length) {
              error.prepend(field.attr('placeholder') + ': ');
              field.closest('fieldset').addClass('has-error');
              error.insertAfter(field);
              form.find(".progress-striped").hide;
              form.find("input[type=submit]").show();
            }
            else {
              show_error(error, form);
            }
          }
        }
      },
      error: function() {
        show_error("Something seems to have gone wrong. Please try again.", form);
      }
    });
    return false;
  });

  function show_error(error, form) {
    form.find(".progress-striped").hide();
    form.find("input[type=submit]").show();
    form.find('.alert-danger').remove();
    form.prepend($('
').text(error));
  }

  function incrementPetitionCount() {
    var n = getPetitionCount() + 1;
    setPetitionCountValue(n);
  }

  // give it an integer and it prints it all pretty on the screen
  function setPetitionCountValue(n) {
    var countEle = petitionCountElement();
    countEle.text(applyPrettyFormatting(n));

    function applyPrettyFormatting() {
      return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
  }

  function getPetitionCount() {
    var countEle = petitionCountElement();
    return parseInt(countEle.text().replace(",",""));
  }

  function petitionCountElement() {
    return $('#petition-tool .count b');
  }

  var getSignaturesInterval = 2000;
  var previousSignatures = {};
  var getSignatures = function(){
    $.ajax({
      url: '/petition/' + petition_id + '/recent_signatures',
      success: function(data){
        var signatures_total = data.signatures_total;
        setPetitionCountValue(signatures_total);

        var progress_total = $('.signatures-bar').attr('aria-valuemax');
        $(".signatures-bar").attr('aria-valuenow', signatures_total).css({width: signatures_total/progress_total*100 + '%'});
        var signatures = data.signatories;
        var individual_signature_template = $('#individual_signature').html();
        var signatures_html = _.map(signatures, function(signature){
          return _.template(individual_signature_template)({
            name: (signature.first_name ? signature.first_name + " " + signature.last_name : "Anonymous"),
            location: signature.location,
            time_ago: signature.time_ago + " ago"
          });
        }).join("");
        $("div#signatures tbody").html(signatures_html);

        // did anything change? if no, wait longer til next check.
        if (_.isEqual(data, previousSignatures)) {
          getSignaturesInterval *= 2;
        } else {
          getSignaturesInterval = 2000;
        }
        previousSignatures = data
        window.setTimeout(getSignatures, getSignaturesInterval);
      },
      error: function() {
        window.setTimeout(getSignatures, getSignaturesInterval);
      }
    });
  }

  var zip_pattern = '\\d{5}(-?\\d{4})?';

  var toggle_intl = function(){
    $('.intl-toggle').toggle();
    height_changed();
    if ($('.intl:visible').length) {
      $('#signature_zipcode').removeAttr('required');
      $('#signature_zipcode').removeAttr('pattern');
      $('#signature_city, #signature_country_code').attr('required', 'required');
    } else {
      $('#signature_zipcode').attr('required', 'required')
      $('#signature_zipcode').attr('pattern', zip_pattern);
      $('#signature_city, #signature_country_code').removeAttr('required');
    }
  }

  if($('#petition-tool').length != 0) {
    window.setTimeout(getSignatures, getSignaturesInterval);

    $('#signature_zipcode').attr('required', 'required')
    $('#signature_zipcode').attr('pattern', zip_pattern);
  }

  if(typeof international_only != 'undefined' && international_only){
    toggle_intl();
    $('.intl-toggler').hide();
    $('#signature_zipcode').removeAttr('required');
  }

  $('.intl-toggler').click(function(e) {
    toggle_intl();
  });

});
<|endoftext|>


<commit_before>// TODO:
//
// - See if there is a setup feature so the version number only has
//   to be changed in one place.

QUnit.test("Confirm version number has been updated.", function(assert) {

    // Given
    var imageLoader = new ImageLoader_0_5_x();

    // Then
    assert.equal(
        "0.5.0",
        imageLoader.version_number()
    );

});

QUnit.test("Integration Test: Basic call verification", function(assert) {

    // TODO:
    // - Add environmental overrides so it doesn't matter what browser is being tested.
    // - Add something like `imageLoader.load_environment()` to Given for the standard setup
    // - Add something like `imageLoader.set_url_template()` to Given for the standard setup

    // Preflight
    var target_string = '';

    // Given
    var imageLoader = new ImageLoader_0_5_x();

    // When
    var result_string = imageLoader.image_string_from_params( {
        filename: "horses.jpg",
        alt_text: "Photo of Horses",
        source_width: 1600,
        source_height: 1067
    });

    // Then
    assert.equal(result_string, target_string);

});

/******************************************************\
 * DEPRECATED TESTS
 *
 * The tests below are for the prior versoin. They
 * are being kept temporarirly to make sure new
 * versions testing the same things are completed
 * before they are removed.
 *
/******************************************************/

// QUnit.test("Integration Test: Verify environmental parameters load", function(assert) {
//
//     // It's a little weird to tests these params, but I
//     // want to make sure they work for integration purposes.
//
//     // Given
//     var target_dpr = window.devicePixelRatio ? window.devicePixelRatio : 1;
//
//     // When
//     var imageLoader = new ImageLoader_0_5_x();
//     imageLoader.load_environmental_params();
//
//     // Then
//     assert.equal(imageLoader._dpr, target_dpr);
//
// });
//
//
// QUnit.test("2x DPR Basic call stright to load_params", function(assert) {
//
//   // Given
// 	var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//     	image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then - Verify instance variables.
//   assert.equal(imageLoader._dpr, 2, "Device pixel resolution");
//   assert.equal(imageLoader._image_name, "horses.jpg", "Image name");
//   assert.equal(imageLoader._raw_height, 1067, "Raw image height");
//   assert.equal(imageLoader._raw_width, 1600, "Raw image width");
//   assert.equal(imageLoader._percent_of_viewport_width, 50, "Percent of viewport width");
//   assert.equal(imageLoader._quality, 80, "Quality level");
//   assert.equal(imageLoader._viewport_height, 680, "Viewport height");
//   assert.equal(imageLoader._viewport_width, 1024, "Viewport width");
//   assert.equal(imageLoader._url_template, "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]", "URL Template");
//
//   // And - Verify functions
//   assert.equal(imageLoader.url_to_call(), "http://res.cloudinary.com/demo/image/upload/w_1024,h_682,q_80/horses.jpg", "Final URL");
//   assert.equal(imageLoader.render_height(), 341, "Render height");
//   assert.equal(imageLoader.render_width(), 512, "Render width");
//   assert.equal(imageLoader.url_request_height(), 682, "Request height");
//   assert.equal(imageLoader.url_request_width(), 1024, "Request width");
//   assert.equal(imageLoader.img_tag(), '', "Image tag");
//
// });
//
// QUnit.test("2x DPR stright to load_params with max width enforced", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       max_render_width: 200,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 200, "Max render width");
//   assert.equal(imageLoader.render_width(), 200, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.render_height(), 133, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.url_request_width(), 400, "Request width");
//   assert.equal(imageLoader.url_request_height(), 266, "Request height");
//
// });
//
//
// QUnit.test("Verify defaults", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       image_name: "horses.jpg",
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 1600, "Default Max Render Width == Raw Width");
//   assert.equal(imageLoader._dpr, 1, "Device pixel ratio default");
//   assert.equal(imageLoader._percent_of_viewport_width, 100, "Percent of viewport width default");
//   assert.equal(imageLoader._quality, 80, "Quality default");
//
// });
//
//
//
// QUnit.test("Ensure values are integers", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 25,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1021,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader.render_height(), 170, "Render height");
//   assert.equal(imageLoader.render_width(), 255, "Render width is 255 and not 255.25");
//   assert.equal(imageLoader.url_request_height(), 340, "Request height");
//   assert.equal(imageLoader.url_request_width(), 510, "Request width is 510 and not 510.5");
//
// });
//
//
// QUnit.test("Restrict height", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 1,
//       image_name: "horses.jpg",
//       percent_of_viewport_height: 90,
//       raw_height: 2000,
//       raw_width: 2200,
//       viewport_height: 1000,
//       viewport_width: 1800,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   assert.equal(imageLoader.render_height(), 900, "Render height");
//
//
// });
//
//
<commit_msg>Renamed initial integration test with better description.<commit_after>// TODO:
//
// - See if there is a setup feature so the version number only has
//   to be changed in one place.

QUnit.test("Confirm version number has been updated.", function(assert) {

    // Given
    var imageLoader = new ImageLoader_0_5_x();

    // Then
    assert.equal(
        "0.5.0",
        imageLoader.version_number()
    );

});

QUnit.test("Integration Test 1: Base functionality using the minimum setup and call", function(assert) {

    // TODO:
    // - Add environmental overrides so it doesn't matter what browser is being tested.
    // - Add something like `imageLoader.load_environment()` to Given for the standard setup
    // - Add something like `imageLoader.set_url_template()` to Given for the standard setup

    // Preflight
    var target_string = '';

    // Given
    var imageLoader = new ImageLoader_0_5_x();

    // When
    var result_string = imageLoader.image_string_from_params( {
        filename: "horses.jpg",
        alt_text: "Photo of Horses",
        source_width: 1600,
        source_height: 1067
    });

    // Then
    assert.equal(result_string, target_string);

});

/******************************************************\
 * DEPRECATED TESTS
 *
 * The tests below are for the prior versoin. They
 * are being kept temporarirly to make sure new
 * versions testing the same things are completed
 * before they are removed.
 *
/******************************************************/

// QUnit.test("Integration Test: Verify environmental parameters load", function(assert) {
//
//     // It's a little weird to tests these params, but I
//     // want to make sure they work for integration purposes.
//
//     // Given
//     var target_dpr = window.devicePixelRatio ? window.devicePixelRatio : 1;
//
//     // When
//     var imageLoader = new ImageLoader_0_5_x();
//     imageLoader.load_environmental_params();
//
//     // Then
//     assert.equal(imageLoader._dpr, target_dpr);
//
// });
//
//
// QUnit.test("2x DPR Basic call stright to load_params", function(assert) {
//
//   // Given
// 	var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//     	image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then - Verify instance variables.
//   assert.equal(imageLoader._dpr, 2, "Device pixel resolution");
//   assert.equal(imageLoader._image_name, "horses.jpg", "Image name");
//   assert.equal(imageLoader._raw_height, 1067, "Raw image height");
//   assert.equal(imageLoader._raw_width, 1600, "Raw image width");
//   assert.equal(imageLoader._percent_of_viewport_width, 50, "Percent of viewport width");
//   assert.equal(imageLoader._quality, 80, "Quality level");
//   assert.equal(imageLoader._viewport_height, 680, "Viewport height");
//   assert.equal(imageLoader._viewport_width, 1024, "Viewport width");
//   assert.equal(imageLoader._url_template, "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]", "URL Template");
//
//   // And - Verify functions
//   assert.equal(imageLoader.url_to_call(), "http://res.cloudinary.com/demo/image/upload/w_1024,h_682,q_80/horses.jpg", "Final URL");
//   assert.equal(imageLoader.render_height(), 341, "Render height");
//   assert.equal(imageLoader.render_width(), 512, "Render width");
//   assert.equal(imageLoader.url_request_height(), 682, "Request height");
//   assert.equal(imageLoader.url_request_width(), 1024, "Request width");
//   assert.equal(imageLoader.img_tag(), '', "Image tag");
//
// });
//
// QUnit.test("2x DPR stright to load_params with max width enforced", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       max_render_width: 200,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 200, "Max render width");
//   assert.equal(imageLoader.render_width(), 200, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.render_height(), 133, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.url_request_width(), 400, "Request width");
//   assert.equal(imageLoader.url_request_height(), 266, "Request height");
//
// });
//
//
// QUnit.test("Verify defaults", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       image_name: "horses.jpg",
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 1600, "Default Max Render Width == Raw Width");
//   assert.equal(imageLoader._dpr, 1, "Device pixel ratio default");
//   assert.equal(imageLoader._percent_of_viewport_width, 100, "Percent of viewport width default");
//   assert.equal(imageLoader._quality, 80, "Quality default");
//
// });
//
//
//
// QUnit.test("Ensure values are integers", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 25,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1021,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader.render_height(), 170, "Render height");
//   assert.equal(imageLoader.render_width(), 255, "Render width is 255 and not 255.25");
//   assert.equal(imageLoader.url_request_height(), 340, "Request height");
//   assert.equal(imageLoader.url_request_width(), 510, "Request width is 510 and not 510.5");
//
// });
//
//
// QUnit.test("Restrict height", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 1,
//       image_name: "horses.jpg",
//       percent_of_viewport_height: 90,
//       raw_height: 2000,
//       raw_width: 2200,
//       viewport_height: 1000,
//       viewport_width: 1800,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   assert.equal(imageLoader.render_height(), 900, "Render height");
//
//
// });
//
//
<|endoftext|>


<commit_before>QUnit.module("Loader Factory", {
    beforeEach: function() {
        console.log("Creating new test object");
        this.image_loader = new ImageLoader_0_5_x();
    }
	// TODO: Add function that runs before suite to show date
	//		 to make it easier to see when the browser automatically
	//       refreshes in the background.
});

QUnit.test("Confirm version number has been updated.", function(assert) {
    var target_version = "0.5.0";
    assert.equal(target_version, this.image_loader.version_number());
});

QUnit.test("Integration Test 1: Base functionality using the minimum setup and call", function(assert) {
    // TODO:
    // - Add environmental overrides so it doesn't matter what browser is being tested.
    // - Add something like `imageLoader.load_environment()` to Given for the standard setup

    // Given
    this.image_loader.set_url_template('//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]');

    // When
    var target_string = '';

    var result_string = this.image_loader.image_string_from_params( {
        filename: "horses.jpg",
        alt_text: "Photo of Horses",
		// TODO: Rename these to `max_physical_width` and `max_physical_height`.
        source_width: 1600,
        source_height: 1067
    });

    // Then
    assert.equal(result_string, target_string);
});

QUnit.test("Unit Test: set_url_template()", function(assert) {
    // Given
    var target_string = '//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]';

    // When
    this.image_loader.set_url_template('//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]');
    var result_string = this.image_loader._url_template;

    // Then
    assert.equal(result_string, target_string);
});

QUnit.test("Unit Test: Ensure default max width is set.", function(assert) {
    // Given
    var target_default_max_percentage_width_of_window = 94;

    // When
    var result = this.image_loader._max_width_of_window_percentage;

    // Then
    assert.equal(result, target_default_max_percentage_width_of_window)
});

QUnit.test("Unit Test: calculate_logical_width(params)", function(assert) {

    // Given
    var target = 640;

    // When
    var result = this.image_loader.calculate_logical_width({
        max_physical_width: 640,
        percent_of_viewport_width: 94,
        viewport_width: 1028
    });

    // Then
    assert.equal(result, target);

});

/******************************************************\
 * DEPRECATED TESTS
 *
 * The tests below are for the prior versoin. They
 * are being kept temporarirly to make sure new
 * versions testing the same things are completed
 * before they are removed.
 *
/******************************************************/

// QUnit.test("Integration Test: Verify environmental parameters load", function(assert) {
//
//     // It's a little weird to tests these params, but I
//     // want to make sure they work for integration purposes.
//
//     // Given
//     var target_dpr = window.devicePixelRatio ? window.devicePixelRatio : 1;
//
//     // When
//     var imageLoader = new ImageLoader_0_5_x();
//     imageLoader.load_environmental_params();
//
//     // Then
//     assert.equal(imageLoader._dpr, target_dpr);
//
// });
//
//
// QUnit.test("2x DPR Basic call stright to load_params", function(assert) {
//
//   // Given
// 	var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//     	image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then - Verify instance variables.
//   assert.equal(imageLoader._dpr, 2, "Device pixel resolution");
//   assert.equal(imageLoader._image_name, "horses.jpg", "Image name");
//   assert.equal(imageLoader._raw_height, 1067, "Raw image height");
//   assert.equal(imageLoader._raw_width, 1600, "Raw image width");
//   assert.equal(imageLoader._percent_of_viewport_width, 50, "Percent of viewport width");
//   assert.equal(imageLoader._quality, 80, "Quality level");
//   assert.equal(imageLoader._viewport_height, 680, "Viewport height");
//   assert.equal(imageLoader._viewport_width, 1024, "Viewport width");
//   assert.equal(imageLoader._url_template, "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]", "URL Template");
//
//   // And - Verify functions
//   assert.equal(imageLoader.url_to_call(), "http://res.cloudinary.com/demo/image/upload/w_1024,h_682,q_80/horses.jpg", "Final URL");
//   assert.equal(imageLoader.render_height(), 341, "Render height");
//   assert.equal(imageLoader.render_width(), 512, "Render width");
//   assert.equal(imageLoader.url_request_height(), 682, "Request height");
//   assert.equal(imageLoader.url_request_width(), 1024, "Request width");
//   assert.equal(imageLoader.img_tag(), '', "Image tag");
//
// });
//
// QUnit.test("2x DPR stright to load_params with max width enforced", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       max_render_width: 200,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 200, "Max render width");
//   assert.equal(imageLoader.render_width(), 200, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.render_height(), 133, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.url_request_width(), 400, "Request width");
//   assert.equal(imageLoader.url_request_height(), 266, "Request height");
//
// });
//
//
// QUnit.test("Verify defaults", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       image_name: "horses.jpg",
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 1600, "Default Max Render Width == Raw Width");
//   assert.equal(imageLoader._dpr, 1, "Device pixel ratio default");
//   assert.equal(imageLoader._percent_of_viewport_width, 100, "Percent of viewport width default");
//   assert.equal(imageLoader._quality, 80, "Quality default");
//
// });
//
//
//
// QUnit.test("Ensure values are integers", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 25,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1021,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader.render_height(), 170, "Render height");
//   assert.equal(imageLoader.render_width(), 255, "Render width is 255 and not 255.25");
//   assert.equal(imageLoader.url_request_height(), 340, "Request height");
//   assert.equal(imageLoader.url_request_width(), 510, "Request width is 510 and not 510.5");
//
// });
//
//
// QUnit.test("Restrict height", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 1,
//       image_name: "horses.jpg",
//       percent_of_viewport_height: 90,
//       raw_height: 2000,
//       raw_width: 2200,
//       viewport_height: 1000,
//       viewport_width: 1800,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   assert.equal(imageLoader.render_height(), 900, "Render height");
//
//
// });
//
//
<commit_msg>Stubbed `.calculate_logical_height()`<commit_after>QUnit.module("Loader Factory", {
    beforeEach: function() {
        console.log("Creating new test object");
        this.image_loader = new ImageLoader_0_5_x();
    }
	// TODO: Add function that runs before suite to show date
	//		 to make it easier to see when the browser automatically
	//       refreshes in the background.
});

QUnit.test("Confirm version number has been updated.", function(assert) {
    var target_version = "0.5.0";
    assert.equal(target_version, this.image_loader.version_number());
});

QUnit.test("Integration Test 1: Base functionality using the minimum setup and call", function(assert) {
    // TODO:
    // - Add environmental overrides so it doesn't matter what browser is being tested.
    // - Add something like `imageLoader.load_environment()` to Given for the standard setup

    // Given
    this.image_loader.set_url_template('//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]');

    // When
    var target_string = '';

    var result_string = this.image_loader.image_string_from_params( {
        filename: "horses.jpg",
        alt_text: "Photo of Horses",
		// TODO: Rename these to `max_physical_width` and `max_physical_height`.
        source_width: 1600,
        source_height: 1067
    });

    // Then
    assert.equal(result_string, target_string);
});

QUnit.test("Unit Test: set_url_template()", function(assert) {
    // Given
    var target_string = '//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]';

    // When
    this.image_loader.set_url_template('//res.cloudinary.com/demo/image/upload/w_[PHYSICAL_WIDTH],h_[PHYSICAL_HEIGHT]/[FILENAME]');
    var result_string = this.image_loader._url_template;

    // Then
    assert.equal(result_string, target_string);
});

QUnit.test("Unit Test: Ensure default max width is set.", function(assert) {
    // Given
    var target_default_max_percentage_width_of_window = 94;

    // When
    var result = this.image_loader._max_width_of_window_percentage;

    // Then
    assert.equal(result, target_default_max_percentage_width_of_window)
});

QUnit.test("Unit Test: calculate_logical_width(params)", function(assert) {

    // Given
    var target = 640;

    // When
    var result = this.image_loader.calculate_logical_width({
        max_physical_width: 640,
        percent_of_viewport_width: 94,
        viewport_width: 1028
    });

    // Then
    assert.equal(result, target);

});

QUnit.test("Unit Test: calculate_logical_height(params)", function(assert) {

    // Given
    var target = 436;

    // When
    var result = 436;

    // Then
    assert.equal(result, target);
});

/******************************************************\
 * DEPRECATED TESTS
 *
 * The tests below are for the prior versoin. They
 * are being kept temporarirly to make sure new
 * versions testing the same things are completed
 * before they are removed.
 *
/******************************************************/

// QUnit.test("Integration Test: Verify environmental parameters load", function(assert) {
//
//     // It's a little weird to tests these params, but I
//     // want to make sure they work for integration purposes.
//
//     // Given
//     var target_dpr = window.devicePixelRatio ? window.devicePixelRatio : 1;
//
//     // When
//     var imageLoader = new ImageLoader_0_5_x();
//     imageLoader.load_environmental_params();
//
//     // Then
//     assert.equal(imageLoader._dpr, target_dpr);
//
// });
//
//
// QUnit.test("2x DPR Basic call stright to load_params", function(assert) {
//
//   // Given
// 	var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//     	image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then - Verify instance variables.
//   assert.equal(imageLoader._dpr, 2, "Device pixel resolution");
//   assert.equal(imageLoader._image_name, "horses.jpg", "Image name");
//   assert.equal(imageLoader._raw_height, 1067, "Raw image height");
//   assert.equal(imageLoader._raw_width, 1600, "Raw image width");
//   assert.equal(imageLoader._percent_of_viewport_width, 50, "Percent of viewport width");
//   assert.equal(imageLoader._quality, 80, "Quality level");
//   assert.equal(imageLoader._viewport_height, 680, "Viewport height");
//   assert.equal(imageLoader._viewport_width, 1024, "Viewport width");
//   assert.equal(imageLoader._url_template, "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]", "URL Template");
//
//   // And - Verify functions
//   assert.equal(imageLoader.url_to_call(), "http://res.cloudinary.com/demo/image/upload/w_1024,h_682,q_80/horses.jpg", "Final URL");
//   assert.equal(imageLoader.render_height(), 341, "Render height");
//   assert.equal(imageLoader.render_width(), 512, "Render width");
//   assert.equal(imageLoader.url_request_height(), 682, "Request height");
//   assert.equal(imageLoader.url_request_width(), 1024, "Request width");
//   assert.equal(imageLoader.img_tag(), '', "Image tag");
//
// });
//
// QUnit.test("2x DPR stright to load_params with max width enforced", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 50,
//       quality: 80,
//       raw_height: 1067,
//       raw_width: 1600,
//       max_render_width: 200,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 200, "Max render width");
//   assert.equal(imageLoader.render_width(), 200, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.render_height(), 133, "Verify render_width == max_render_width");
//   assert.equal(imageLoader.url_request_width(), 400, "Request width");
//   assert.equal(imageLoader.url_request_height(), 266, "Request height");
//
// });
//
//
// QUnit.test("Verify defaults", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//       image_name: "horses.jpg",
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1024,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader._max_render_width, 1600, "Default Max Render Width == Raw Width");
//   assert.equal(imageLoader._dpr, 1, "Device pixel ratio default");
//   assert.equal(imageLoader._percent_of_viewport_width, 100, "Percent of viewport width default");
//   assert.equal(imageLoader._quality, 80, "Quality default");
//
// });
//
//
//
// QUnit.test("Ensure values are integers", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 2,
//       image_name: "horses.jpg",
//       percent_of_viewport_width: 25,
//       raw_height: 1067,
//       raw_width: 1600,
//       viewport_height: 680,
//       viewport_width: 1021,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   // Then:
//   assert.equal(imageLoader.render_height(), 170, "Render height");
//   assert.equal(imageLoader.render_width(), 255, "Render width is 255 and not 255.25");
//   assert.equal(imageLoader.url_request_height(), 340, "Request height");
//   assert.equal(imageLoader.url_request_width(), 510, "Request width is 510 and not 510.5");
//
// });
//
//
// QUnit.test("Restrict height", function(assert) {
//
//   // Given
//   var imageLoader = new ImageLoader_0_5_x();
//
//   // When
//   imageLoader.load_params(
//     {
//     	dpr: 1,
//       image_name: "horses.jpg",
//       percent_of_viewport_height: 90,
//       raw_height: 2000,
//       raw_width: 2200,
//       viewport_height: 1000,
//       viewport_width: 1800,
//       url_template: "http://res.cloudinary.com/demo/image/upload/w_[WIDTH],h_[HEIGHT],q_[QUALITY]/[IMAGE_NAME]"
//     }
//   );
//
//   assert.equal(imageLoader.render_height(), 900, "Render height");
//
//
// });
//
//
<|endoftext|>


<commit_before>/**
 * TagManager module setup tests.
 *
 * Site Kit by Google, Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */
import {
	activatePlugin,
	deactivatePlugin,
	visitAdminPage,
	createURL,
} from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import {
	deactivateUtilityPlugins,
	pageWait,
	resetSiteKit,
	setAMPMode,
	setupSiteKit,
	useRequestInterception,
} from '../../../utils';

async function proceedToTagManagerSetup() {
	await visitAdminPage( 'admin.php', 'page=googlesitekit-settings' );
	await page.waitForSelector( '.mdc-tab-bar' );
	await expect( page ).toClick( '.mdc-tab', { text: /connect more services/i } );
	await page.waitForSelector( '.googlesitekit-settings-connect-module--tagmanager' );

	await Promise.all( [
		page.waitForSelector( '.googlesitekit-setup-module__action .mdc-button' ),
		expect( page ).toClick( '.googlesitekit-cta-link', { text: /set up tag manager/i } ),
	] );
}

describe( 'Tag Manager module setup', () => {
	beforeAll( async () => {
		await page.setRequestInterception( true );
		useRequestInterception( ( request ) => {
			if ( request.url().match( 'google-site-kit/v1/data/' ) ) {
				request.respond( {
					status: 200,
				} );
			} else if ( request.url().match( 'modules/tagmanager/data/live-container-version' ) ) {
				// A 404 is returned for containers without a published version.
				request.respond( { status: 404, body: JSON.stringify( { code: 404 } ) } );
			} else if ( request.url().match( /^https:\/\/www\.googletagmanager\.com\/(gtm\.js|amp\.json)/ ) ) {
				request.respond( { status: 200 } );
			} else {
				request.continue();
			}
		} );
	} );

	beforeEach( async () => {
		await setupSiteKit();
	} );

	afterEach( async () => {
		await deactivateUtilityPlugins();
		await resetSiteKit();
	} );

	it( 'displays account creation form when user has no Tag Manager account', async () => {
		await activatePlugin( 'e2e-tests-module-setup-tagmanager-api-mock-no-account' );
		await proceedToTagManagerSetup();

		// Intercept the call to window.open and call our API to simulate a created account.
		await page.evaluate( () => {
			window.open = () => {
				window._e2eApiFetch( {
					path: 'google-site-kit/v1/e2e/setup/tagmanager/account-created',
					method: 'post',
				} );
			};
		} );

		// Clicking Create Account button will switch API mock plugins on the server to the one that has accounts.
		await Promise.all( [
			page.waitForResponse( ( res ) => res.url().match( 'google-site-kit/v1/e2e/setup/tagmanager/account-created' ) ),
			expect( page ).toClick( '.mdc-button', { text: /Create an account/i } ),
		] );

		await Promise.all( [
			page.waitForResponse( ( req ) => req.url().match( 'tagmanager/data/accounts' ) ),
			expect( page ).toClick( '.googlesitekit-cta-link', { text: /Re-fetch My Account/i } ),
		] );
		await page.waitForSelector( '.googlesitekit-setup-module__inputs' );

		// Ensure account and container selections are cleared.
		await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-account .mdc-select__selected-text', { text: '' } );
		await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container .mdc-select__selected-text', { text: '' } );

		// Choose an account.
		await expect( page ).toClick( '.googlesitekit-tagmanager__select-account' );
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test account a/i } );

		// Ensure "Set up a new container" option is present in container select.
		await expect( page ).toClick( '.googlesitekit-tagmanager__select-container' );
		await expect( page ).toMatchElement( '.mdc-menu-surface--open .mdc-list-item', { text: /set up a new container/i } );
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test container x/i } );

		await pageWait( 1000 );
		await expect( page ).toClick( 'button', { text: /confirm \& continue/i } );

		await page.waitForSelector( '.googlesitekit-publisher-win--win-success' );
		await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Tag Manager!/i } );

		// Ensure expected tag is placed.
		await Promise.all( [
			page.goto( createURL( '/' ) ),
			page.waitForNavigation(),
		] );
		await expect( page ).toMatchElement( 'script[src^="https://www.googletagmanager.com/gtm.js?id=GTM-ABCXYZ"]' );
	} );

	it( 'displays available accounts and containers for the chosen account', async () => {
		await activatePlugin( 'e2e-tests-module-setup-tagmanager-api-mock' );
		await proceedToTagManagerSetup();

		// Ensure only web container select is shown.
		await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--web' );
		await expect( page ).not.toMatchElement( '.googlesitekit-tagmanager__select-container--amp' );

		// Ensure account and container are selected by default.
		await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-account .mdc-select__selected-text', { text: /test account a/i } );
		await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container .mdc-select__selected-text', { text: /test container x/i } );

		// Ensure choosing a different account loads the proper values.
		await expect( page ).toClick( '.googlesitekit-tagmanager__select-account' );
		await Promise.all( [
			page.waitForResponse( ( res ) => res.url().match( 'modules/tagmanager/data' ) ),
			expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test account b/i } ),
		] );

		// Ensure account is selected.
		await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-account .mdc-select__selected-text', { text: /test account b/i } );

		// Select a container.
		await expect( page ).toClick( '.googlesitekit-tagmanager__select-container' );
		// Ensure no AMP containers are shown as options.
		// expect(...).not.toMatchElement with textContent matching does not work as expected.
		await expect(
			await page.$$eval( '.mdc-menu-surface--open .mdc-list-item', ( nodes ) => !! nodes.find( ( e ) => e.textContent.match( /test amp container/i ) ) )
		).toStrictEqual( false );
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test container y/i } );

		await pageWait( 1000 );
		await expect( page ).toClick( 'button', { text: /confirm \& continue/i } );

		await page.waitForSelector( '.googlesitekit-publisher-win--win-success' );
		await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Tag Manager!/i } );

		// Ensure expected tag is placed.
		await Promise.all( [
			page.goto( createURL( '/' ) ),
			page.waitForNavigation(),
		] );
		await expect( page ).toMatchElement( 'script[src^="https://www.googletagmanager.com/gtm.js?id=GTM-BCDWXY"]' );
	} );

	it( 'displays instructions for account creation when "Set up a new account" option is selected', async () => {
		await activatePlugin( 'e2e-tests-module-setup-tagmanager-api-mock' );
		await proceedToTagManagerSetup();

		// Ensure "setup a new account" is an available choice.
		await expect( page ).toClick( '.googlesitekit-tagmanager__select-account' );
		await expect( page ).toMatchElement( '.mdc-menu-surface--open .mdc-list-item', { text: /set up a new account/i } );

		// Choose set up a new account.
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /set up a new account/i } );

		// Ensure instructions are present.
		await expect( page ).toMatchElement( '.googlesitekit-setup-module p', { text: /to create a new account/i } );

		// Ensure buttons are present.
		await expect( page ).toMatchElement( '.googlesitekit-setup-module .mdc-button', { text: /create an account/i } );
		await expect( page ).toMatchElement( '.googlesitekit-setup-module .googlesitekit-cta-link', { text: /re-fetch my account/i } );
	} );

	describe( 'Setup with AMP active', () => {
		beforeAll( async () => {
			await activatePlugin( 'amp' );
		} );

		beforeEach( async () => {
			await activatePlugin( 'e2e-tests-module-setup-tagmanager-api-mock' );
			await proceedToTagManagerSetup();
		} );

		afterAll( async () => {
			await deactivatePlugin( 'amp' );
		} );

		describe( 'with Primary AMP', () => {
			beforeAll( async () => {
				await setAMPMode( 'primary' );
			} );

			it( 'renders only the AMP container select menu', async () => {
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--amp' );
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--amp .mdc-floating-label', { text: 'Container' } );
				await expect( page ).not.toMatchElement( '.googlesitekit-tagmanager__select-container--web' );
			} );

			it( 'validates Homepage AMP for logged-in users', async () => {
				await expect( '/' ).toHaveValidAMPForUser();
			} );

			it( 'validates Homepage AMP for non-logged-in users', async () => {
				await expect( '/' ).toHaveValidAMPForVisitor();
			} );
		} );

		describe( 'with Secondary AMP', () => {
			beforeAll( async () => {
				await setAMPMode( 'secondary' );
			} );

			it( 'renders both the AMP and web container select menus', async () => {
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--web' );
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--web .mdc-floating-label', { text: 'Web Container' } );
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--amp' );
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--amp .mdc-floating-label', { text: 'AMP Container' } );
			} );

			it( 'validates homepage AMP for logged-in users', async () => {
				await expect( page ).toClick( 'button:not(:disabled)', { text: /confirm \& continue/i } );
				await page.waitForSelector( '.googlesitekit-publisher-win--win-success' );
				await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Tag Manager!/i } );
				await page.goto( createURL( '/', 'amp' ), { waitUntil: 'load' } );
				await expect( page ).toHaveValidAMPForUser();
			} );

			it( 'validates homepage AMP for non-logged-in users', async () => {
				await expect( page ).toClick( 'button:not(:disabled)', { text: /confirm \& continue/i } );
				await page.waitForSelector( '.googlesitekit-publisher-win--win-success' );
				await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Tag Manager!/i } );
				await page.goto( createURL( '/', 'amp' ), { waitUntil: 'load' } );
				await expect( page ).toHaveValidAMPForVisitor();
			} );
		} );
	} );
} );
<commit_msg>Regroup setup without AMP tests and ensure AMP is not active.<commit_after>/**
 * TagManager module setup tests.
 *
 * Site Kit by Google, Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */
import {
	activatePlugin,
	deactivatePlugin,
	visitAdminPage,
	createURL,
} from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import {
	deactivateUtilityPlugins,
	pageWait,
	resetSiteKit,
	setAMPMode,
	setupSiteKit,
	useRequestInterception,
} from '../../../utils';

async function proceedToTagManagerSetup() {
	await visitAdminPage( 'admin.php', 'page=googlesitekit-settings' );
	await page.waitForSelector( '.mdc-tab-bar' );
	await expect( page ).toClick( '.mdc-tab', { text: /connect more services/i } );
	await page.waitForSelector( '.googlesitekit-settings-connect-module--tagmanager' );

	await Promise.all( [
		page.waitForSelector( '.googlesitekit-setup-module__action .mdc-button' ),
		expect( page ).toClick( '.googlesitekit-cta-link', { text: /set up tag manager/i } ),
	] );
}

describe( 'Tag Manager module setup', () => {
	beforeAll( async () => {
		await page.setRequestInterception( true );
		useRequestInterception( ( request ) => {
			if ( request.url().match( 'google-site-kit/v1/data/' ) ) {
				request.respond( {
					status: 200,
				} );
			} else if ( request.url().match( 'modules/tagmanager/data/live-container-version' ) ) {
				// A 404 is returned for containers without a published version.
				request.respond( { status: 404, body: JSON.stringify( { code: 404 } ) } );
			} else if ( request.url().match( /^https:\/\/www\.googletagmanager\.com\/(gtm\.js|amp\.json)/ ) ) {
				request.respond( { status: 200 } );
			} else {
				request.continue();
			}
		} );
	} );

	beforeEach( async () => {
		await setupSiteKit();
	} );

	afterEach( async () => {
		await deactivateUtilityPlugins();
		await resetSiteKit();
	} );

	describe( 'Setup without AMP active', () => {
		beforeAll( async () => {
			await deactivatePlugin( 'amp' );
		} );

		it( 'displays account creation form when user has no Tag Manager account', async () => {
			await activatePlugin( 'e2e-tests-module-setup-tagmanager-api-mock-no-account' );
			await proceedToTagManagerSetup();

			// Intercept the call to window.open and call our API to simulate a created account.
			await page.evaluate( () => {
				window.open = () => {
					window._e2eApiFetch( {
						path: 'google-site-kit/v1/e2e/setup/tagmanager/account-created',
						method: 'post',
					} );
				};
			} );

			// Clicking Create Account button will switch API mock plugins on the server to the one that has accounts.
			await Promise.all( [
				page.waitForResponse( ( res ) => res.url().match( 'google-site-kit/v1/e2e/setup/tagmanager/account-created' ) ),
				expect( page ).toClick( '.mdc-button', { text: /Create an account/i } ),
			] );

			await Promise.all( [
				page.waitForResponse( ( req ) => req.url().match( 'tagmanager/data/accounts' ) ),
				expect( page ).toClick( '.googlesitekit-cta-link', { text: /Re-fetch My Account/i } ),
			] );
			await page.waitForSelector( '.googlesitekit-setup-module__inputs' );

			// Ensure account and container selections are cleared.
			await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-account .mdc-select__selected-text', { text: '' } );
			await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container .mdc-select__selected-text', { text: '' } );

			// Choose an account.
			await expect( page ).toClick( '.googlesitekit-tagmanager__select-account' );
			await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test account a/i } );

			// Ensure "Set up a new container" option is present in container select.
			await expect( page ).toClick( '.googlesitekit-tagmanager__select-container' );
			await expect( page ).toMatchElement( '.mdc-menu-surface--open .mdc-list-item', { text: /set up a new container/i } );
			await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test container x/i } );

			await pageWait( 1000 );
			await expect( page ).toClick( 'button', { text: /confirm \& continue/i } );

			await page.waitForSelector( '.googlesitekit-publisher-win--win-success' );
			await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Tag Manager!/i } );

			// Ensure expected tag is placed.
			await Promise.all( [
				page.goto( createURL( '/' ) ),
				page.waitForNavigation(),
			] );
			await expect( page ).toMatchElement( 'script[src^="https://www.googletagmanager.com/gtm.js?id=GTM-ABCXYZ"]' );
		} );

		it( 'displays available accounts and containers for the chosen account', async () => {
			await activatePlugin( 'e2e-tests-module-setup-tagmanager-api-mock' );
			await proceedToTagManagerSetup();

			// Ensure only web container select is shown.
			await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--web' );
			await expect( page ).not.toMatchElement( '.googlesitekit-tagmanager__select-container--amp' );

			// Ensure account and container are selected by default.
			await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-account .mdc-select__selected-text', { text: /test account a/i } );
			await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container .mdc-select__selected-text', { text: /test container x/i } );

			// Ensure choosing a different account loads the proper values.
			await expect( page ).toClick( '.googlesitekit-tagmanager__select-account' );
			await Promise.all( [
				page.waitForResponse( ( res ) => res.url().match( 'modules/tagmanager/data' ) ),
				expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test account b/i } ),
			] );

			// Ensure account is selected.
			await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-account .mdc-select__selected-text', { text: /test account b/i } );

			// Select a container.
			await expect( page ).toClick( '.googlesitekit-tagmanager__select-container' );
			// Ensure no AMP containers are shown as options.
			// expect(...).not.toMatchElement with textContent matching does not work as expected.
			await expect(
				await page.$$eval( '.mdc-menu-surface--open .mdc-list-item', ( nodes ) => !! nodes.find( ( e ) => e.textContent.match( /test amp container/i ) ) )
			).toStrictEqual( false );
			await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test container y/i } );

			await pageWait( 1000 );
			await expect( page ).toClick( 'button', { text: /confirm \& continue/i } );

			await page.waitForSelector( '.googlesitekit-publisher-win--win-success' );
			await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Tag Manager!/i } );

			// Ensure expected tag is placed.
			await Promise.all( [
				page.goto( createURL( '/' ) ),
				page.waitForNavigation(),
			] );
			await expect( page ).toMatchElement( 'script[src^="https://www.googletagmanager.com/gtm.js?id=GTM-BCDWXY"]' );
		} );

		it( 'displays instructions for account creation when "Set up a new account" option is selected', async () => {
			await activatePlugin( 'e2e-tests-module-setup-tagmanager-api-mock' );
			await proceedToTagManagerSetup();

			// Ensure "setup a new account" is an available choice.
			await expect( page ).toClick( '.googlesitekit-tagmanager__select-account' );
			await expect( page ).toMatchElement( '.mdc-menu-surface--open .mdc-list-item', { text: /set up a new account/i } );

			// Choose set up a new account.
			await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /set up a new account/i } );

			// Ensure instructions are present.
			await expect( page ).toMatchElement( '.googlesitekit-setup-module p', { text: /to create a new account/i } );

			// Ensure buttons are present.
			await expect( page ).toMatchElement( '.googlesitekit-setup-module .mdc-button', { text: /create an account/i } );
			await expect( page ).toMatchElement( '.googlesitekit-setup-module .googlesitekit-cta-link', { text: /re-fetch my account/i } );
		} );
	} );

	describe( 'Setup with AMP active', () => {
		beforeAll( async () => {
			await activatePlugin( 'amp' );
		} );

		beforeEach( async () => {
			await activatePlugin( 'e2e-tests-module-setup-tagmanager-api-mock' );
			await proceedToTagManagerSetup();
		} );

		afterAll( async () => {
			await deactivatePlugin( 'amp' );
		} );

		describe( 'with Primary AMP', () => {
			beforeAll( async () => {
				await setAMPMode( 'primary' );
			} );

			it( 'renders only the AMP container select menu', async () => {
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--amp' );
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--amp .mdc-floating-label', { text: 'Container' } );
				await expect( page ).not.toMatchElement( '.googlesitekit-tagmanager__select-container--web' );
			} );

			it( 'validates Homepage AMP for logged-in users', async () => {
				await expect( '/' ).toHaveValidAMPForUser();
			} );

			it( 'validates Homepage AMP for non-logged-in users', async () => {
				await expect( '/' ).toHaveValidAMPForVisitor();
			} );
		} );

		describe( 'with Secondary AMP', () => {
			beforeAll( async () => {
				await setAMPMode( 'secondary' );
			} );

			it( 'renders both the AMP and web container select menus', async () => {
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--web' );
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--web .mdc-floating-label', { text: 'Web Container' } );
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--amp' );
				await expect( page ).toMatchElement( '.googlesitekit-tagmanager__select-container--amp .mdc-floating-label', { text: 'AMP Container' } );
			} );

			it( 'validates homepage AMP for logged-in users', async () => {
				await expect( page ).toClick( 'button:not(:disabled)', { text: /confirm \& continue/i } );
				await page.waitForSelector( '.googlesitekit-publisher-win--win-success' );
				await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Tag Manager!/i } );
				await page.goto( createURL( '/', 'amp' ), { waitUntil: 'load' } );
				await expect( page ).toHaveValidAMPForUser();
			} );

			it( 'validates homepage AMP for non-logged-in users', async () => {
				await expect( page ).toClick( 'button:not(:disabled)', { text: /confirm \& continue/i } );
				await page.waitForSelector( '.googlesitekit-publisher-win--win-success' );
				await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Tag Manager!/i } );
				await page.goto( createURL( '/', 'amp' ), { waitUntil: 'load' } );
				await expect( page ).toHaveValidAMPForVisitor();
			} );
		} );
	} );
} );
<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import {
  render,
  findAll,
  click,
  fillIn,
  find
} from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import { setupMirage } from 'ember-cli-mirage/test-support';

module('Integration | Component | user search', function(hooks) {
  setupRenderingTest(hooks);
  setupMirage(hooks);

  hooks.beforeEach(function() {
    this.server.get('api/users', (schema) => {
      return schema.users.all();
    });
  });

  test('it renders', async function(assert) {
    await render(hbs`<UserSearch />`);
    assert.dom('input').exists({ count: 1 });
  });

  test('less than 3 characters triggers warning', async function(assert) {
    await render(hbs`<UserSearch />`);

    await fillIn('input', 'ab');
    assert.dom('ul').hasText('keep typing...');
  });

  test('input triggers search', async function (assert) {
    this.server.create('user');
    this.server.get('api/users', (schema, { queryParams }) => {
      assert.equal(queryParams['q'], 'search words');
      return schema.users.all();
    });
    await render(hbs`<UserSearch />`);

    await fillIn('input', 'search words');

    assert.dom('li').hasText('1 Results');
    assert.equal(find(findAll('li')[1]).textContent.replace(/[\t\n\s]+/g, ""), '0guyM.Mc0sonuser@example.edu');
  });

  test('no results displays messages', async function(assert) {
    await render(hbs`<UserSearch />`);

    await fillIn('input', 'search words');
    assert.dom('li').hasText('no results');
  });

  test('search for groups', async function (assert) {
    this.server.createList('instructor-group', 2);
    const instructorGroups = this.owner.lookup('service:store').findAll('instructor-group');
    this.set('availableInstructorGroups', instructorGroups);
    await render(hbs`<UserSearch @availableInstructorGroups={{availableInstructorGroups}} />`);

    await fillIn('input', 'group');
    assert.dom('li').hasText('2 Results');
    assert.dom(findAll('li')[1]).hasText('instructor group 0');
    assert.dom(findAll('li')[2]).hasText('instructor group 1');
  });

  test('click user fires add user', async function(assert) {
    const user = this.server.create('user');

    this.set('action', passedUser => {
      assert.equal(user.id, passedUser.id);
    });
    await render(hbs`<UserSearch @addUser={{action action}} />`);

    await fillIn('input', 'test');
    assert.equal(findAll('li')[1].textContent.replace(/[\t\n\s]+/g, ""), '0guyM.Mc0sonuser@example.edu');
    await click(findAll('li')[1]);
  });

  test('click group fires add group', async function(assert) {
    this.set('action', group => {
      assert.equal(1, group.id);
    });
    this.server.createList('instructor-group', 2);
    const instructorGroups = this.owner.lookup('service:store').findAll('instructor-group');
    this.set('availableInstructorGroups', instructorGroups);

    await render(hbs`<UserSearch
      @availableInstructorGroups={{availableInstructorGroups}}
      @addInstructorGroup={{action action}}
    />`);

    await fillIn('input', 'group');
    assert.dom(findAll('li')[1]).hasText('instructor group 0');
    await click(findAll('li')[1]);
  });

  test('sorting is natural', async function(assert) {
    this.server.create('user', {
      firstName: '20',
      lastName: 'person',
    });
    this.server.create('user', {
      firstName: '10',
      lastName: 'person',
    });
    this.server.create('user', {
      firstName: '3',
      lastName: 'person',
    });
    this.server.create('user', {
      lastName: 'person',
    });

    await render(hbs`<UserSearch />`);
    await fillIn('input', 'person');

    const items = '.results li';
    const first = `${items}:nth-of-type(1)`;
    const second = `${items}:nth-of-type(2)`;
    const third = `${items}:nth-of-type(3)`;
    const fourth = `${items}:nth-of-type(4)`;
    const fifth = `${items}:nth-of-type(5)`;

    assert.dom(first).hasText('4 Results');
    assert.dom(second).includesText('person');
    assert.dom(third).includesText('3');
    assert.dom(fourth).includesText('10');
    assert.dom(fifth).includesText('20');
  });

  test('reads currentlyActiveUsers', async function(assert) {
    const user = this.server.create('user');
    this.server.get('api/users', (schema) => {
      return schema.users.all();
    });
    const userModel = await this.owner.lookup('service:store').find('user', user.id);
    this.set('currentlyActiveUsers', [userModel]);
    await render(hbs`<UserSearch @currentlyActiveUsers={{this.currentlyActiveUsers}} />`);
    await fillIn('input', 'foo');

    assert.dom('[data-test-results-count]').hasText('1 Results');
    assert.dom('[data-test-result]').includesText('0 guy');
    assert.dom('[data-test-result]').hasClass('inactive');
  });

  test('reads currentlyActiveUsers from a promise', async function(assert) {
    const user = this.server.create('user');
    this.server.get('api/users', (schema) => {
      return schema.users.all();
    });
    const userPromise = this.owner.lookup('service:store').find('user', user.id);
    this.set('currentlyActiveUsersPromise', userPromise);
    await render(hbs`<UserSearch
      @currentlyActiveUsers={{await this.currentlyActiveUsersPromise}}
    />`);
    await fillIn('input', 'foo');

    assert.dom('[data-test-results-count]').hasText('1 Results');
    assert.dom('[data-test-result]').includesText('0 guy');
    assert.dom('[data-test-result]').hasClass('inactive');
  });
});
<commit_msg>corrects test input from single record wrapped in promise to array containing single record wrapped in promise.<commit_after>import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import {
  render,
  findAll,
  click,
  fillIn,
  find
} from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import { setupMirage } from 'ember-cli-mirage/test-support';

module('Integration | Component | user search', function(hooks) {
  setupRenderingTest(hooks);
  setupMirage(hooks);

  hooks.beforeEach(function() {
    this.server.get('api/users', (schema) => {
      return schema.users.all();
    });
  });

  test('it renders', async function(assert) {
    await render(hbs`<UserSearch />`);
    assert.dom('input').exists({ count: 1 });
  });

  test('less than 3 characters triggers warning', async function(assert) {
    await render(hbs`<UserSearch />`);

    await fillIn('input', 'ab');
    assert.dom('ul').hasText('keep typing...');
  });

  test('input triggers search', async function (assert) {
    this.server.create('user');
    this.server.get('api/users', (schema, { queryParams }) => {
      assert.equal(queryParams['q'], 'search words');
      return schema.users.all();
    });
    await render(hbs`<UserSearch />`);

    await fillIn('input', 'search words');

    assert.dom('li').hasText('1 Results');
    assert.equal(find(findAll('li')[1]).textContent.replace(/[\t\n\s]+/g, ""), '0guyM.Mc0sonuser@example.edu');
  });

  test('no results displays messages', async function(assert) {
    await render(hbs`<UserSearch />`);

    await fillIn('input', 'search words');
    assert.dom('li').hasText('no results');
  });

  test('search for groups', async function (assert) {
    this.server.createList('instructor-group', 2);
    const instructorGroups = this.owner.lookup('service:store').findAll('instructor-group');
    this.set('availableInstructorGroups', instructorGroups);
    await render(hbs`<UserSearch @availableInstructorGroups={{availableInstructorGroups}} />`);

    await fillIn('input', 'group');
    assert.dom('li').hasText('2 Results');
    assert.dom(findAll('li')[1]).hasText('instructor group 0');
    assert.dom(findAll('li')[2]).hasText('instructor group 1');
  });

  test('click user fires add user', async function(assert) {
    const user = this.server.create('user');

    this.set('action', passedUser => {
      assert.equal(user.id, passedUser.id);
    });
    await render(hbs`<UserSearch @addUser={{action action}} />`);

    await fillIn('input', 'test');
    assert.equal(findAll('li')[1].textContent.replace(/[\t\n\s]+/g, ""), '0guyM.Mc0sonuser@example.edu');
    await click(findAll('li')[1]);
  });

  test('click group fires add group', async function(assert) {
    this.set('action', group => {
      assert.equal(1, group.id);
    });
    this.server.createList('instructor-group', 2);
    const instructorGroups = this.owner.lookup('service:store').findAll('instructor-group');
    this.set('availableInstructorGroups', instructorGroups);

    await render(hbs`<UserSearch
      @availableInstructorGroups={{availableInstructorGroups}}
      @addInstructorGroup={{action action}}
    />`);

    await fillIn('input', 'group');
    assert.dom(findAll('li')[1]).hasText('instructor group 0');
    await click(findAll('li')[1]);
  });

  test('sorting is natural', async function(assert) {
    this.server.create('user', {
      firstName: '20',
      lastName: 'person',
    });
    this.server.create('user', {
      firstName: '10',
      lastName: 'person',
    });
    this.server.create('user', {
      firstName: '3',
      lastName: 'person',
    });
    this.server.create('user', {
      lastName: 'person',
    });

    await render(hbs`<UserSearch />`);
    await fillIn('input', 'person');

    const items = '.results li';
    const first = `${items}:nth-of-type(1)`;
    const second = `${items}:nth-of-type(2)`;
    const third = `${items}:nth-of-type(3)`;
    const fourth = `${items}:nth-of-type(4)`;
    const fifth = `${items}:nth-of-type(5)`;

    assert.dom(first).hasText('4 Results');
    assert.dom(second).includesText('person');
    assert.dom(third).includesText('3');
    assert.dom(fourth).includesText('10');
    assert.dom(fifth).includesText('20');
  });

  test('reads currentlyActiveUsers', async function(assert) {
    const user = this.server.create('user');
    this.server.get('api/users', (schema) => {
      return schema.users.all();
    });
    const userModel = await this.owner.lookup('service:store').find('user', user.id);
    this.set('currentlyActiveUsers', [userModel]);
    await render(hbs`<UserSearch @currentlyActiveUsers={{this.currentlyActiveUsers}} />`);
    await fillIn('input', 'foo');

    assert.dom('[data-test-results-count]').hasText('1 Results');
    assert.dom('[data-test-result]').includesText('0 guy');
    assert.dom('[data-test-result]').hasClass('inactive');
  });

  test('reads currentlyActiveUsers from a promise', async function(assert) {
    const user = this.server.create('user');
    this.server.get('api/users', (schema) => {
      return schema.users.all();
    });
    const userPromise = this.owner.lookup('service:store').query('user', { id : user.id });
    this.set('currentlyActiveUsersPromise', userPromise);
    await render(hbs`<UserSearch
      @currentlyActiveUsers={{await this.currentlyActiveUsersPromise}}
    />`);
    await fillIn('input', 'foo');

    assert.dom('[data-test-results-count]').hasText('1 Results');
    assert.dom('[data-test-result]').includesText('0 guy');
    assert.dom('[data-test-result]').hasClass('inactive');
  });
});
<|endoftext|>


<commit_before>Hummingbird.ReviewsIndexRoute = Ember.Route.extend(Hummingbird.Paginated, {
  fetchPage: function(page) {
    return this.store.find('review', {
      anime_id: this.modelFor('anime').get('id'),
      page: page
    });
  },

  afterModel: function(resolvedModel) {
    var anime = this.modelFor('anime');
    return Hummingbird.TitleManager.setTitle(anime.get('canonicalTitle') + " Reviews");
  }
});
<commit_msg>Scroll to top when entering reviews route.<commit_after>Hummingbird.ReviewsIndexRoute = Ember.Route.extend(Hummingbird.Paginated, {
  fetchPage: function(page) {
    return this.store.find('review', {
      anime_id: this.modelFor('anime').get('id'),
      page: page
    });
  },

  afterModel: function(resolvedModel) {
    Ember.run.next(function() { window.scrollTo(0, 0); });
    var anime = this.modelFor('anime');
    return Hummingbird.TitleManager.setTitle(anime.get('canonicalTitle') + " Reviews");
  }
});
<|endoftext|>


<commit_before>(function (angular) {
    'use strict';

    var module = angular.module('ships');

    /**
     * @ngdoc controller
     * @name ships.controller:ShipsDetailCtrl
     *
     * @description
     *
     */
    module.controller('ShipsDetailCtrl',
        function ($scope, $stateParams, $state, ShipsDetailConstants, zooAPISubjectSets) {
            if (angular.isDefined($stateParams.id)) {
                zooAPISubjectSets.get({id: $stateParams.id})
                    .then(function (response) {
                        $scope.ship = response[0];
                        $scope.shipInfo = ShipsDetailConstants[$scope.ship.metadata.shortName] || false;
                    }, function () {
                        $state.go('404');
                    });

            } else {
                $state.go('ships-list');
            }
        }
    );
}(window.angular));

<commit_msg>Try and determine ship info from display_name as well<commit_after>(function (angular) {
    'use strict';

    var module = angular.module('ships');

    /**
     * @ngdoc controller
     * @name ships.controller:ShipsDetailCtrl
     *
     * @description
     *
     */
    module.controller('ShipsDetailCtrl',
        function ($scope, $stateParams, $state, ShipsDetailConstants, zooAPISubjectSets) {
            if (angular.isDefined($stateParams.id)) {
                zooAPISubjectSets.get({id: $stateParams.id})
                    .then(function (response) {
                        $scope.ship = response[0];
                        $scope.shipInfo = ShipsDetailConstants[$scope.ship.metadata.shortName] || ShipsDetailConstants[$scope.ship.display_name.split(' ')[0].toLowerCase()] || false;
                    }, function () {
                        $state.go('404');
                    });

            } else {
                $state.go('ships-list');
            }
        }
    );
}(window.angular));

<|endoftext|>


<commit_before>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function mark_for_destroy(element) {
    $(element).next('.should_destroy').value = 1;
    $(element).up('.role_membership').hide();
}

function toggle_investigator_forms(id_to_show) {

    id_to_hide = $("active_form").value;
    id_to_hide = "form_investigate_" + id_to_hide;

    $("active_form").value = id_to_show;
    id_to_show = "form_investigate_" + id_to_show;

    $(id_to_hide).hide();
    $(id_to_show).show();

}

function sendConditionRequest(path, element, event_id, question_element_id, spinner_id) {
    if (typeof spinner_id == "undefined")
        spinner_id = 'investigator_answer_' +  question_element_id + '_spinner';
    new Ajax.Request(path + '?question_element_id=' + question_element_id +'&response=' + element.value + '&event_id=' + event_id, {
        asynchronous: true,
        evalScripts:  true,
        onCreate:     function() {
            $(spinner_id).show();
        },
        onComplete:   function() {
            $(spinner_id).hide();
        }
    });
}

function sendCoreConditionRequest(path, element, event_id, core_path, spinner_id) {
    if (typeof spinner_id == "undefined")
        spinner_id = core_path + '_spinner';
    new Ajax.Request(path +'?core_path=' + core_path + '&response=' + element.value + '&event_id=' + event_id, {
        asynchronous: true,
        evalScripts:  true,
        onCreate:     function() {
            $(spinner_id).show();
        },
        onComplete:   function() {
            $(spinner_id).hide();
        }
    });
}

function updateStatusRequest(path, value) {
    separator = (path.indexOf("?") > 0) ? "&" : "?";
    new Ajax.Request(path + separator + 'task[status]=' + value, {
        asynchronous:true,
        evalScripts:true,
        method:'put'
    });
}

function setUpSearchFields() {
    if (document.getElementById("name").value.length > 0) {
        document.getElementById("sw_first_name").disabled = true;
        document.getElementById("sw_last_name").disabled = true;
    }

    if (document.getElementById("sw_first_name").value.length > 0 || document.getElementById("sw_last_name").value.length > 0) {
        document.getElementById("name").disabled = true;
    }
}

function checkNameSearchFields(field) {
    if (field.id == "name") {
        if (field.value.length > 0) {
            document.getElementById("sw_first_name").disabled = true;
            document.getElementById("sw_last_name").disabled = true;
        }
        else {
            document.getElementById("sw_first_name").disabled = false;
            document.getElementById("sw_last_name").disabled = false;
        }
    }
    else if (field.id == "sw_first_name" || field.id == "sw_last_name") {
        first = document.getElementById("sw_first_name");
        last = document.getElementById("sw_last_name");

        if (first.value.length > 0 || last.value.length > 0) {
            document.getElementById("name").disabled = true;
        }
        else {
            document.getElementById("name").disabled = false;
        }
    }
}

function build_url_with_tab_index(url) {
    if (!(window.myTabs === undefined)) {
        url = url + "?tab_index=" + myTabs.get("activeIndex");
    }
    return url;
}

function send_url_with_tab_index(url) {
    url = build_url_with_tab_index(url);
    location.href = url;
}

function add_tab_index_to_action(form) {
    form.action = build_url_with_tab_index(form.action);
}

function post_and_return(form_id) {
    form = document.getElementById(form_id);
    form.action = build_url_with_tab_index(form.action);
    form.action = form.action + "&return=true";
    form.submit();
}

function post_and_exit(form_id) {
    form = document.getElementById(form_id);
    form.action = build_url_with_tab_index(form.action);
    form.submit();
}

function toggle_strike_through(element_id) {
    Element.toggleClassName(element_id, 'struck-through');
}

function safe_disable(target) {
    element = document.getElementById(target);
    if (element) {
        element.disabled=true;
    }
}

function toggle_save_buttons(state) {
    btn1 = document.getElementById('save_and_exit_btn');
    btn2 = document.getElementById('save_and_continue_btn');

    var btns = new Array(btn1, btn2);
    $A(btns).each(function(btn) {
        if (btn) {
            if (state == 'on') {
                btn.disabled=false;
            } else {
                btn.disabled=true;
            }
        }
    });
}

function contact_parent_address(id) {
  new Ajax.Request('../../contact_events/copy_address/' + id, {
    asynchronous: true,
    evalScripts:  true,
    onComplete: function(transport, json) {
      $H(json).each(function(pair) {
        $('contact_event_address_attributes_' + pair.key).value = pair.value;
      });
    }
  });
}

function global_shortcuts_init() {
  shortcut.add("Ctrl+Shift+N", function() {
    window.location = "/cmrs/new";
  });

  shortcut.add("Ctrl+Shift+M", function() {
    window.location = "/forms";
  });

  shortcut.add("Ctrl+Shift+.",function() {
    window.location = "/search/people";
  });

  shortcut.add("Ctrl+Shift+Question",function(){
    window.location = "/search/cmrs";
  });

  shortcut.add("Ctrl+Shift+,",function(){
    window.location = "/cmrs";
  });
}

function cmr_shortcuts_init() {
  shortcut.add("Ctrl+Shift+X", function() {
    myTabs.set('activeIndex', (
        myTabs.get('activeIndex') == myTabs.get('tabs').length-1 ?
        0 : myTabs.get('activeIndex') + 1
      ));

    //Grab the first thing to focus in the tab
    YAHOO.util.Dom.getElementsBy(function(el) {
        return (el.tagName == 'SELECT' || el.tagName == 'INPUT' || el.tagName == 'A');
      }, '', myTabs.get('activeTab').get('contentEl'))[0].focus();
  });

  shortcut.add("Ctrl+Shift+Z", function() {
    myTabs.set('activeIndex', (
        myTabs.get('activeIndex') == 0 ?
        myTabs.get('tabs').length-1 : myTabs.get('activeIndex')-1
      ));

    YAHOO.util.Dom.getElementsBy(function(el) {
        return (el.tagName == 'SELECT' || el.tagName == 'INPUT' || el.tagName == 'A');
      }, '', myTabs.get('activeTab').get('contentEl'))[0].focus();
  });

  shortcut.add("Ctrl+Shift+S", function() {
    document.getElementById('save_and_exit_btn').focus();
  });
}
<commit_msg>tri1339 -- switched "Ctrl+Alt" to "Meta" to reduce collision frequency (a precursor to custom keys).  Needs to be tested in windows<commit_after>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function mark_for_destroy(element) {
    $(element).next('.should_destroy').value = 1;
    $(element).up('.role_membership').hide();
}

function toggle_investigator_forms(id_to_show) {

    id_to_hide = $("active_form").value;
    id_to_hide = "form_investigate_" + id_to_hide;

    $("active_form").value = id_to_show;
    id_to_show = "form_investigate_" + id_to_show;

    $(id_to_hide).hide();
    $(id_to_show).show();

}

function sendConditionRequest(path, element, event_id, question_element_id, spinner_id) {
    if (typeof spinner_id == "undefined")
        spinner_id = 'investigator_answer_' +  question_element_id + '_spinner';
    new Ajax.Request(path + '?question_element_id=' + question_element_id +'&response=' + element.value + '&event_id=' + event_id, {
        asynchronous: true,
        evalScripts:  true,
        onCreate:     function() {
            $(spinner_id).show();
        },
        onComplete:   function() {
            $(spinner_id).hide();
        }
    });
}

function sendCoreConditionRequest(path, element, event_id, core_path, spinner_id) {
    if (typeof spinner_id == "undefined")
        spinner_id = core_path + '_spinner';
    new Ajax.Request(path +'?core_path=' + core_path + '&response=' + element.value + '&event_id=' + event_id, {
        asynchronous: true,
        evalScripts:  true,
        onCreate:     function() {
            $(spinner_id).show();
        },
        onComplete:   function() {
            $(spinner_id).hide();
        }
    });
}

function updateStatusRequest(path, value) {
    separator = (path.indexOf("?") > 0) ? "&" : "?";
    new Ajax.Request(path + separator + 'task[status]=' + value, {
        asynchronous:true,
        evalScripts:true,
        method:'put'
    });
}

function setUpSearchFields() {
    if (document.getElementById("name").value.length > 0) {
        document.getElementById("sw_first_name").disabled = true;
        document.getElementById("sw_last_name").disabled = true;
    }

    if (document.getElementById("sw_first_name").value.length > 0 || document.getElementById("sw_last_name").value.length > 0) {
        document.getElementById("name").disabled = true;
    }
}

function checkNameSearchFields(field) {
    if (field.id == "name") {
        if (field.value.length > 0) {
            document.getElementById("sw_first_name").disabled = true;
            document.getElementById("sw_last_name").disabled = true;
        }
        else {
            document.getElementById("sw_first_name").disabled = false;
            document.getElementById("sw_last_name").disabled = false;
        }
    }
    else if (field.id == "sw_first_name" || field.id == "sw_last_name") {
        first = document.getElementById("sw_first_name");
        last = document.getElementById("sw_last_name");

        if (first.value.length > 0 || last.value.length > 0) {
            document.getElementById("name").disabled = true;
        }
        else {
            document.getElementById("name").disabled = false;
        }
    }
}

function build_url_with_tab_index(url) {
    if (!(window.myTabs === undefined)) {
        url = url + "?tab_index=" + myTabs.get("activeIndex");
    }
    return url;
}

function send_url_with_tab_index(url) {
    url = build_url_with_tab_index(url);
    location.href = url;
}

function add_tab_index_to_action(form) {
    form.action = build_url_with_tab_index(form.action);
}

function post_and_return(form_id) {
    form = document.getElementById(form_id);
    form.action = build_url_with_tab_index(form.action);
    form.action = form.action + "&return=true";
    form.submit();
}

function post_and_exit(form_id) {
    form = document.getElementById(form_id);
    form.action = build_url_with_tab_index(form.action);
    form.submit();
}

function toggle_strike_through(element_id) {
    Element.toggleClassName(element_id, 'struck-through');
}

function safe_disable(target) {
    element = document.getElementById(target);
    if (element) {
        element.disabled=true;
    }
}

function toggle_save_buttons(state) {
    btn1 = document.getElementById('save_and_exit_btn');
    btn2 = document.getElementById('save_and_continue_btn');

    var btns = new Array(btn1, btn2);
    $A(btns).each(function(btn) {
        if (btn) {
            if (state == 'on') {
                btn.disabled=false;
            } else {
                btn.disabled=true;
            }
        }
    });
}

function contact_parent_address(id) {
  new Ajax.Request('../../contact_events/copy_address/' + id, {
    asynchronous: true,
    evalScripts:  true,
    onComplete: function(transport, json) {
      $H(json).each(function(pair) {
        $('contact_event_address_attributes_' + pair.key).value = pair.value;
      });
    }
  });
}

function global_shortcuts_init() {
  shortcut.add("Meta+N", function() {
    window.location = "/cmrs/new";
  });

  shortcut.add("Meta+M", function() {
    window.location = "/forms";
  });

  shortcut.add("Meta+.",function() {
    window.location = "/search/people";
  });

  shortcut.add("Meta+Question",function(){
    window.location = "/search/cmrs";
  });

  shortcut.add("Meta+,",function(){
    window.location = "/cmrs";
  });
}

function cmr_shortcuts_init() {
  shortcut.add("Meta+X", function() {
    myTabs.set('activeIndex', (
        myTabs.get('activeIndex') == myTabs.get('tabs').length-1 ?
        0 : myTabs.get('activeIndex') + 1
      ));

    //Grab the first thing to focus in the tab
    YAHOO.util.Dom.getElementsBy(function(el) {
        return (el.tagName == 'SELECT' || el.tagName == 'INPUT' || el.tagName == 'A');
      }, '', myTabs.get('activeTab').get('contentEl'))[0].focus();
  });

  shortcut.add("Meta+Z", function() {
    myTabs.set('activeIndex', (
        myTabs.get('activeIndex') == 0 ?
        myTabs.get('tabs').length-1 : myTabs.get('activeIndex')-1
      ));

    YAHOO.util.Dom.getElementsBy(function(el) {
        return (el.tagName == 'SELECT' || el.tagName == 'INPUT' || el.tagName == 'A');
      }, '', myTabs.get('activeTab').get('contentEl'))[0].focus();
  });

  shortcut.add("Meta+S", function() {
    document.getElementById('save_and_exit_btn').focus();
  });
}
<|endoftext|>