<commit_before>window.cls || (window.cls = {});

window.cls.DOMSerializer = function(){};

window.cls.DOMSerializer.prototype = new function()
{

  const
  ID = 0,
  TYPE = 1,
  NAME = 2,
  DEPTH = 3,
  NAMESPACE = 4,
  VALUE = 7,
  ATTRS = 5,
  ATTR_PREFIX = 0,
  ATTR_KEY = 1,
  ATTR_VALUE = 2,
  CHILDREN_LENGTH = 6,
  PUBLIC_ID = 8,
  SYSTEM_ID = 9,
  INDENT = "  ",
  LINEBREAK = '\n',
  VOID_ELEMENTS =
  {
    'area': 1,
    'base': 1,
    'basefont': 1,
    'bgsound': 1,
    'br': 1,
    'col': 1,
    'embed': 1,
    'frame': 1,
    'hr': 1,
    'img': 1,
    'input': 1,
    'link': 1,
    'meta': 1,
    'param': 1,
    'spacer': 1,
    'wbr': 1,
    'command': 1,
    'event-source': 1,
    'source': 1,
  };

  var getIndent = function(count)
  {
    var ret = '';
    if(count)
    {
      count--;
    }
    while(count > -1)
    {
      ret += INDENT;
      count--;
    }
    return ret;
  };

  var getDoctypeName = function(data)
  {
    for (var node = null, i = 0; node = data[i]; i++)
    {
      if (node[TYPE] == 1)
        return node[NAME];
    }
    return null;
  }

  this['text/html'] = function(model, is_xml)
  {
    const LINEBREAK = '\r\n';

    var
    data = model.getData(),
    tree = '',
    i = 0,
    node = null,
    length = data.length,
    attrs = '',
    attr = null,
    k = 0,
    key = '',
    is_open = 0,
    has_only_one_child = 0,
    one_child_value = '',
    current_depth = 0,
    child_pointer = 0,
    child_level = 0,
    j = 0,
    children_length = 0,
    closing_tags = [],
    force_lower_case = window.settings.dom.get('force-lowercase'),
    node_name = '',
    tag_head = '',
    start_depth = data[0][DEPTH] - 1,
    disregard_force_lower_case_whitelist =
      cls.EcmascriptDebugger["5.0"].DOMData.DISREGARD_FORCE_LOWER_CASE_WHITELIST,
    disregard_force_lower_case_depth = 0;

    for( ; node = data[i]; i++ )
    {
      while( current_depth > node[DEPTH] )
      {
        tree += closing_tags.pop();
        current_depth--;
      }
      current_depth = node[DEPTH];
      children_length = node[CHILDREN_LENGTH];
      child_pointer = 0;
      node_name =  node[NAME];

      if (force_lower_case && disregard_force_lower_case_whitelist.indexOf(node[NAME].toLowerCase()) != -1)
      {
        disregard_force_lower_case_depth = node[DEPTH];
        force_lower_case = false;
      }
      else if (disregard_force_lower_case_depth && disregard_force_lower_case_depth == node[DEPTH])
      {
        disregard_force_lower_case_depth = 0;
        force_lower_case = model.isTextHtml() && window.settings.dom.get('force-lowercase');
      }

      if( force_lower_case )
      {
        node_name = node_name.toLowerCase();
      }
      switch (node[TYPE])
      {
        case 1: // elements
        {
          attrs = '';
          for( k = 0; attr = node[ATTRS][k]; k++ )
          {
            attrs += " " +
              (attr[ATTR_PREFIX] ? attr[ATTR_PREFIX] + ':' : '') +
              ( force_lower_case ? attr[ATTR_KEY].toLowerCase() : attr[ATTR_KEY] ) +
              "=\"" +
              attr[ATTR_VALUE].replace(/"/g, """) +
              "\"";
          }
          child_pointer = i + 1;
          is_open = ( data[child_pointer] && ( node[DEPTH] < data[child_pointer][DEPTH] ) );
          if( is_open )
          {
            has_only_one_child = 1;
            one_child_value = '';
            child_level = data[child_pointer][DEPTH];
            for( ; data[child_pointer] && data[child_pointer][DEPTH] == child_level; child_pointer++ )
            {
              one_child_value += data[child_pointer][VALUE];
              if( data[child_pointer][TYPE] != 3 )
              {
                has_only_one_child = 0;
                one_child_value = '';
                break;
              }
            }
          }
          if( is_open )
          {
            if( has_only_one_child )
            {
              tree += LINEBREAK  + getIndent(node[DEPTH] - start_depth) +
                      "<" + node_name +  attrs + ">" +
                        helpers.escapeTextHtml(one_child_value) +
                      "</" + node_name + ">";
              i = child_pointer - 1;
            }
            else
            {
              tree += LINEBREAK  + getIndent(node[DEPTH] - start_depth) +
                      "<" + node_name + attrs + ">";
              if( !(node_name in VOID_ELEMENTS) ) // TODO: why?
              {
                closing_tags.push
                (
                  LINEBREAK  + getIndent(node[DEPTH] - start_depth) + "</" + node_name + ">"
                );
              }
            }
          }
          else // is closed or empty
          {
            tree +=  LINEBREAK  + getIndent(node[DEPTH] - start_depth) + "<" + node_name + attrs +
              ( is_xml && "/>" || ">" +  ( node_name in VOID_ELEMENTS ? "" : "</" + node_name + ">" ) );
          }
          break;
        }
        case 7:  // processing instruction
        {
          tree += LINEBREAK  + getIndent(node[DEPTH] - start_depth) +
            "<?" + node[NAME] + ( node[VALUE] ? ' ' + node[VALUE] : '' ) + "?>";
          break;
        }
        case 8:  // comments
        {
          tree += LINEBREAK  + getIndent(node[DEPTH] - start_depth) +
                  "<!--" + ( node[ VALUE ] || ' ' ) + "-->";
          break;
        }
        case 9:  // document node
        {
          break;
        }
        case 10:  // doctype
        {
          tree += LINEBREAK + getIndent(node[DEPTH] - start_depth) +
                  "<!DOCTYPE " + getDoctypeName(data) +
                  (node[PUBLIC_ID] ?
                    (" PUBLIC " + "\"" + node[PUBLIC_ID] + "\"") : "") +
                  (!node[PUBLIC_ID] && node[SYSTEM_ID] ?
                    " SYSTEM" : "") +
                  (node[SYSTEM_ID] ?
                    (" \"" + node[SYSTEM_ID] + "\"") : "") +
                  ">";
          break;
        }
        default:
        {
          if( !/^\s*$/.test(node[ VALUE ] ) )
          {
            tree += LINEBREAK  + getIndent(node[DEPTH] - start_depth) + helpers.escapeTextHtml(node[VALUE]);
          }
        }
      }
    }
    while( closing_tags.length )
    {
      tree += closing_tags.pop();
    }
    return tree.replace(/^(?:\r\n)+/, '');
  };

  this['application/xml'] = function(model)
  {
    // TODO
    return this['text/html'](model, true);
  };

  this.serialize = function(model /* of type InspectableDOMNode */)
  {
    return this[model.get_mime()](model);
  }
};
<commit_msg>Better fix for DFL-1669.<commit_after>window.cls || (window.cls = {});

window.cls.DOMSerializer = function(){};

window.cls.DOMSerializer.prototype = new function()
{

  const
  ID = 0,
  TYPE = 1,
  NAME = 2,
  DEPTH = 3,
  NAMESPACE = 4,
  VALUE = 7,
  ATTRS = 5,
  ATTR_PREFIX = 0,
  ATTR_KEY = 1,
  ATTR_VALUE = 2,
  CHILDREN_LENGTH = 6,
  PUBLIC_ID = 8,
  SYSTEM_ID = 9,
  INDENT = "  ",
  LINEBREAK = '\n',
  VOID_ELEMENTS =
  {
    'area': 1,
    'base': 1,
    'basefont': 1,
    'bgsound': 1,
    'br': 1,
    'col': 1,
    'embed': 1,
    'frame': 1,
    'hr': 1,
    'img': 1,
    'input': 1,
    'link': 1,
    'meta': 1,
    'param': 1,
    'spacer': 1,
    'wbr': 1,
    'command': 1,
    'event-source': 1,
    'source': 1,
  };

  var getIndent = function(count)
  {
    var ret = '';
    if (count)
    {
      count--;
    }
    while (count > 0)
    {
      ret += INDENT;
      count--;
    }
    return ret;
  };

  var getDoctypeName = function(data)
  {
    for (var node = null, i = 0; node = data[i]; i++)
    {
      if (node[TYPE] == 1)
        return node[NAME];
    }
    return null;
  }

  this['text/html'] = function(model, is_xml)
  {
    const LINEBREAK = '\r\n';

    var
    data = model.getData(),
    tree = '',
    i = 0,
    node = null,
    length = data.length,
    attrs = '',
    attr = null,
    k = 0,
    key = '',
    is_open = 0,
    has_only_one_child = 0,
    one_child_value = '',
    current_depth = 0,
    child_pointer = 0,
    child_level = 0,
    j = 0,
    children_length = 0,
    closing_tags = [],
    force_lower_case = window.settings.dom.get('force-lowercase'),
    node_name = '',
    tag_head = '',
    start_depth = data[0][DEPTH] - 1,
    disregard_force_lower_case_whitelist =
      cls.EcmascriptDebugger["5.0"].DOMData.DISREGARD_FORCE_LOWER_CASE_WHITELIST,
    disregard_force_lower_case_depth = 0;

    for( ; node = data[i]; i++ )
    {
      while( current_depth > node[DEPTH] )
      {
        tree += closing_tags.pop();
        current_depth--;
      }
      current_depth = node[DEPTH];
      children_length = node[CHILDREN_LENGTH];
      child_pointer = 0;
      node_name =  node[NAME];

      if (force_lower_case && disregard_force_lower_case_whitelist.indexOf(node[NAME].toLowerCase()) != -1)
      {
        disregard_force_lower_case_depth = node[DEPTH];
        force_lower_case = false;
      }
      else if (disregard_force_lower_case_depth && disregard_force_lower_case_depth == node[DEPTH])
      {
        disregard_force_lower_case_depth = 0;
        force_lower_case = model.isTextHtml() && window.settings.dom.get('force-lowercase');
      }

      if( force_lower_case )
      {
        node_name = node_name.toLowerCase();
      }
      switch (node[TYPE])
      {
        case 1: // elements
        {
          attrs = '';
          for( k = 0; attr = node[ATTRS][k]; k++ )
          {
            attrs += " " +
              (attr[ATTR_PREFIX] ? attr[ATTR_PREFIX] + ':' : '') +
              ( force_lower_case ? attr[ATTR_KEY].toLowerCase() : attr[ATTR_KEY] ) +
              "=\"" +
              attr[ATTR_VALUE].replace(/"/g, """) +
              "\"";
          }
          child_pointer = i + 1;
          is_open = ( data[child_pointer] && ( node[DEPTH] < data[child_pointer][DEPTH] ) );
          if( is_open )
          {
            has_only_one_child = 1;
            one_child_value = '';
            child_level = data[child_pointer][DEPTH];
            for( ; data[child_pointer] && data[child_pointer][DEPTH] == child_level; child_pointer++ )
            {
              one_child_value += data[child_pointer][VALUE];
              if( data[child_pointer][TYPE] != 3 )
              {
                has_only_one_child = 0;
                one_child_value = '';
                break;
              }
            }
          }
          if( is_open )
          {
            if( has_only_one_child )
            {
              tree += LINEBREAK  + getIndent(node[DEPTH] - start_depth) +
                      "<" + node_name +  attrs + ">" +
                        helpers.escapeTextHtml(one_child_value) +
                      "</" + node_name + ">";
              i = child_pointer - 1;
            }
            else
            {
              tree += LINEBREAK  + getIndent(node[DEPTH] - start_depth) +
                      "<" + node_name + attrs + ">";
              if( !(node_name in VOID_ELEMENTS) ) // TODO: why?
              {
                closing_tags.push
                (
                  LINEBREAK  + getIndent(node[DEPTH] - start_depth) + "</" + node_name + ">"
                );
              }
            }
          }
          else // is closed or empty
          {
            tree +=  LINEBREAK  + getIndent(node[DEPTH] - start_depth) + "<" + node_name + attrs +
              ( is_xml && "/>" || ">" +  ( node_name in VOID_ELEMENTS ? "" : "</" + node_name + ">" ) );
          }
          break;
        }
        case 7:  // processing instruction
        {
          tree += LINEBREAK  + getIndent(node[DEPTH] - start_depth) +
            "<?" + node[NAME] + ( node[VALUE] ? ' ' + node[VALUE] : '' ) + "?>";
          break;
        }
        case 8:  // comments
        {
          tree += LINEBREAK  + getIndent(node[DEPTH] - start_depth) +
                  "<!--" + ( node[ VALUE ] || ' ' ) + "-->";
          break;
        }
        case 9:  // document node
        {
          break;
        }
        case 10:  // doctype
        {
          tree += LINEBREAK + getIndent(node[DEPTH] - start_depth) +
                  "<!DOCTYPE " + getDoctypeName(data) +
                  (node[PUBLIC_ID] ?
                    (" PUBLIC " + "\"" + node[PUBLIC_ID] + "\"") : "") +
                  (!node[PUBLIC_ID] && node[SYSTEM_ID] ?
                    " SYSTEM" : "") +
                  (node[SYSTEM_ID] ?
                    (" \"" + node[SYSTEM_ID] + "\"") : "") +
                  ">";
          break;
        }
        default:
        {
          if( !/^\s*$/.test(node[ VALUE ] ) )
          {
            tree += LINEBREAK  + getIndent(node[DEPTH] - start_depth) + helpers.escapeTextHtml(node[VALUE]);
          }
        }
      }
    }
    while( closing_tags.length )
    {
      tree += closing_tags.pop();
    }
    return tree.replace(/^(?:\r\n)+/, '');
  };

  this['application/xml'] = function(model)
  {
    // TODO
    return this['text/html'](model, true);
  };

  this.serialize = function(model /* of type InspectableDOMNode */)
  {
    return this[model.get_mime()](model);
  }
};
<|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("Make sure the version number is accurate", function(assert) {

  // Given
  var required_version_number = "0.5.0";

  // When
  var imageLoader = new ImageLoader_0_5_x();

  // Then
  assert.equal(imageLoader.version_number(), required_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>Made it easier to see target version number.<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: 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");
//
//
// });
//
//
<|endoftext|>


<commit_before>var instantsearch = require('instantsearch.js')
  , Mustache = require('mustache')
  , _ = require('lodash');

var infiniteScrollWidget = function(options) {
  var container = document.querySelector(options.container);
  var options = options;
  var templates = options.templates;
  var loading = false;

  if (!container) {
    throw new Error('infiniteScroll: cannot select \'' + options.container + '\'');
  }

  return {
    render: function(args) {
      var helper = args.helper;
      var page = args.state.page;
      var nbPages = args.results.nbPages;
      var parent = document.createElement('div');

      var addNewRecords = function(){
        if( window.scrollY > (document.querySelector('body').clientHeight - window.innerHeight) - 300 ) {
          if(!loading && page < nbPages - 1) {
            loading = true;
            page += 1;
            helper.searchOnce({page: page}, function(err, res, state){
              page = res.page;
              _.assign(res, {pageNo: page + 1});
              loading = false;
              result = document.createElement('div');
              result.innerHTML = Mustache.render(templates.items, res);
              container.appendChild(result);

              if(page === nbPages - 1){
                window.removeEventListener('scroll', addNewRecords);
              }
            });
          }
        }
      };

      if(args.results.nbHits) {
        _.assign(args.results, {pageNo: page + 1});
        parent.innerHTML = Mustache.render(templates.items, args.results);
      } else {
        parent.innerHTML = Mustache.render(templates.empty, args.results);
        parent.querySelector('.clear-all').addEventListener('click', function(e){
          e.preventDefault();
          helper.clearRefinements().setQuery('').search();
        });
      }

      window.addEventListener('scroll', addNewRecords);

      container.innerHTML = '';
      container.appendChild(parent);

      if(window.innerHeight > document.body.clientHeight) {
        addNewRecords();
      }
    }
  }
};

module.exports  = instantsearch.widgets.infiniteScrollWidget = infiniteScrollWidget;
<commit_msg>Move variable declarations out of render method<commit_after>var instantsearch = require('instantsearch.js')
  , Mustache = require('mustache')
  , _ = require('lodash');

var cursor;
var index;
var page;
var nbPages;

var infiniteScrollWidget = function(options) {
  var container = document.querySelector(options.container);
  var options = options;
  var templates = options.templates;
  var loading = false;

  if (!container) {
    throw new Error('infiniteScroll: cannot select \'' + options.container + '\'');
  }

  return {
    init: function(){
      page = undefined;
      nbPages = undefined;
    },

    render: function(args) {
      var helper = args.helper;
      var parent = document.createElement('div');

      page = args.state.page;
      nbPages = args.results.nbPages;

      var addNewRecords = function(){
        if( window.scrollY > (document.querySelector('body').clientHeight - window.innerHeight) - 300 ) {
          if(!loading && page < nbPages - 1) {
            loading = true;
            page += 1;
            helper.searchOnce({page: page}, function(err, res, state){
              page = res.page;
              _.assign(res, {pageNo: page + 1});
              loading = false;
              result = document.createElement('div');
              result.innerHTML = Mustache.render(templates.items, res);
              container.appendChild(result);

              if(page === nbPages - 1){
                window.removeEventListener('scroll', addNewRecords);
              }
            });
          }
        }
      };

      if(args.results.nbHits) {
        _.assign(args.results, {pageNo: page + 1});
        parent.innerHTML = Mustache.render(templates.items, args.results);
      } else {
        parent.innerHTML = Mustache.render(templates.empty, args.results);
        parent.querySelector('.clear-all').addEventListener('click', function(e){
          e.preventDefault();
          helper.clearRefinements().setQuery('').search();
        });
      }

      window.addEventListener('scroll', addNewRecords);

      container.innerHTML = '';
      container.appendChild(parent);

      if(window.innerHeight > document.body.clientHeight) {
        addNewRecords();
      }
    }
  }
};

module.exports  = instantsearch.widgets.infiniteScrollWidget = infiniteScrollWidget;
<|endoftext|>


<commit_before>/**
 * Stateless (or almost) object to render variants.
 *
 * If you have a svg element where you want to draw, pass it to VariantRenderer.init()
 * and later, in each VariantRenderer.render() as args.svgCanvasFeatures.
 *
 * @type {Renderer}
 */
class VariantRenderer extends Renderer {

    constructor(args) {
        super(args);

        this.sampleTrackY = 15;
        this.sampleTrackHeight = 20;
        this.sampleTrackFontSize = 12;

        Object.assign(this, args);

        // Extend and add Backbone Events
        Object.assign(this, Backbone.Events);
        this.on(this.handlers);
    }

    init(svgGroup, sample) {
        //Prevent browser context menu
        console.log(this.track.main);
        $(svgGroup).contextmenu(function (e) {
            console.log("right click");
            e.preventDefault();
        });

        // Get sample name array, it can be a string or an array
        if (typeof this.sampleNames === "string") {
            this.sampleNames = this.sampleNames.split(",");
        }

        let y = this.sampleTrackY;
        for (let i = 0; i < this.sampleNames.length; i++) {
            let sampleSvg = SVG.addChild(this.track.main, "text", {
                "x": 0,
                "y": y,
                "stroke": "black",
                "stroke-width": 1,
                "font-size": this.sampleTrackFontSize,
                "cursor": "pointer"
            });
            sampleSvg.textContent = this.sampleNames[i];

            y += this.sampleTrackHeight;

            let _this = this;
            $(sampleSvg).click(function (event) {
                // $(this).css({"strokeWidth":"3","stroke":"#ff7200"}).hide(100).show(500).css({"stroke":"#51c000"})});
                // amarillo FCFC92
                let label = $(this);
                //label.css({"stroke":"#ff7200"}).hide(100).show(500).css({"stroke":"#ff7200"});

                //POSIBILIDAD 1
                //let rect = SVG.addChild(_this.track.main,  "rect",{
                //    'x': 0,
                //    'y': label[0].y.baseVal[0].value-7,
                //    'width': _this.track.width,
                //    'height': 8,
                //    'stroke': '#FFFF00',
                //    'fill': '#FCFC92'
                //});
                //$(rect).css({"z-index": -1});

                //POSIBILIDAD 2
                let yrect = label[0].y.baseVal[0].value - 7;
                if (this.getAttribute("stroke") === "black") {
                    label.css({"stroke": "#ff7200"}).hide(100).show(500).css({"stroke": "#ff7200"});
                    this.setAttribute("stroke", "#ff7200");
                    let rect = SVG.create("rect", {
                        "x": 0,
                        "y": yrect,
                        "width": _this.track.width,
                        "height": 8,
                        "stroke": "#FFFF00",
                        "fill": "#F2F5A9",
                        "opacity": 0.5
                    });
                    rect.setAttribute("id", this.innerHTML + "_rect" + yrect);
                    _this.track.main.insertBefore(rect, this);
                } else {
                    let rect = document.getElementById(this.innerHTML + "_rect" + yrect);
                    rect.parentNode.removeChild(rect);
                    this.setAttribute("stroke", "black");
                    label.css({"stroke": "black"});
                }

                //let divpadre = _this.track.main.parentNode;
                //let selBox = $('

')[0];
                //divpadre.append(selBox);
                //$(selBox).css({
                //    'z-index': 0,
                //    'position': 'absolute',
                //    'left': 0,
                //    'top': label[0].y.baseVal[0].value-8,
                //    'height': 8,
                //    'width':'100%',
                //    'border': '2px solid #FFFF00',
                //    'opacity': 0.5,
                //    //'visibility': 'hidden',
                //    'background-color': '#F2F5A9'
                //});
                //$(selBox).click(function(event){
                //    this.parentNode.removeChild(this);
                //});
            });
        }
    }

    render(features, args) {
        // for (let i = 0; i < features.length; i++) {
        //     this._renderExtendedGenotypes(features[i], args);
        // }
        if (typeof this.sampleNames !== "undefined" && this.sampleNames !== null && this.sampleNames.length > 0) {
            this._renderExtendedGenotypes(features, args);
        } else {
            this._renderExtendedGenotypes(features, args);
        }
    }

    _renderExtendedGenotypes(features, args) {
        for (let feature of features) {
            // get feature render configuration
            // let color = _.isFunction(this.color) ? this.color(feature) : this.color;
            // let label = _.isFunction(this.label) ? this.label(feature) : this.label;
            // let height = _.isFunction(this.height) ? this.height(feature) : this.height;
            let tooltipTitle = _.isFunction(this.tooltipTitle) ? this.tooltipTitle(feature) : this.tooltipTitle;
            let tooltipText = _.isFunction(this.tooltipText) ? this.tooltipText(feature) : this.tooltipText;
            // let infoWidgetId = _.isFunction(this.infoWidgetId) ? this.infoWidgetId(feature) : this.infoWidgetId;

            //get feature genomic information
            let start = feature.start;
            let end = feature.end;
            let length = (end - start) + 1;

            //check genomic length
            length = (length < 0) ? Math.abs(length) : length;
            length = (length === 0) ? 1 : length;

            // Transform to pixel position, minimum width set to 1px
            let width = length * args.pixelBase;
            width = Math.max(width, 1);

            // let svgLabelWidth = this.getLabelWidth(label, args);
            //calculate x to draw svg rect
            let x = this.getFeatureX(start, args);
            // let maxWidth = Math.max(width, 2);
            // let textHeight = 0;
            // if (args.regionSize < args.maxLabelRegionSize) {
            //     textHeight = 9;
            //     maxWidth = Math.max(width, svgLabelWidth);
            // }
            // let rowY = 0;
            // let textY = textHeight + height;
            // let rowHeight = textHeight + height + 2;

            // Color: Dark blue: 0/0, Orange: 0/1, Red: 1/1, Black: ./.
            let d00 = "";
            let dDD = "";
            let d11 = "";
            let d01 = "";
            let xs = x;         // x start
            let xe = x + width; // x end
            let ys = 5;         // y
            let yi = 10;         // y increment
            let yi2 = this.sampleTrackHeight;       // y increment

            let samplesCount = feature.studies[0].samplesData.length;
            for (let i in feature.studies[0].samplesData) {
                let svgPath = "M" + xs + "," + ys + " L" + xe + "," + ys + " L" + xe + "," + (ys + yi) + " L" + xs + "," + (ys + yi) + " z ";

                // Only one study is expected, and GT is always the first field in samplesData
                let genotype = feature.studies[0].samplesData[i]["0"];
                switch (genotype) {
                    case "0|0":
                    case "0/0":
                        d00 += svgPath;
                        break;
                    case "0|1":
                    case "0/1":
                    case "1|0":
                    case "1/0":
                        d01 += svgPath;
                        break;
                    case "1|1":
                    case "1/1":
                        d11 += svgPath;
                        break;
                    case ".|.":
                    case "./.":
                        dDD += svgPath;
                        break;
                }
                ys += yi2;
            }

            let featureGroup = SVG.addChild(args.svgCanvasFeatures, "g", {"feature_id": feature.id});
            // let dummyRect = SVG.addChild(featureGroup, "rect", {
            //     "x": xs,
            //     "y": 1,
            //     "width": width,
            //     "height": ys,
            //     "fill": "transparent",
            //     "cursor": "pointer"
            // });
            if (d00 !== "") {
                let path = SVG.addChild(featureGroup, "path", {
                    "d": d00,
                    "fill": "blue",
                    "cursor": "pointer"
                });
            }
            if (dDD !== "") {
                let path = SVG.addChild(featureGroup, "path", {
                    "d": dDD,
                    "fill": "black",
                    "cursor": "pointer"
                });
            }
            if (d11 !== "") {
                let path = SVG.addChild(featureGroup, "path", {
                    "d": d11,
                    "fill": "red",
                    "cursor": "pointer"
                });
            }
            if (d01 !== "") {
                let path = SVG.addChild(featureGroup, "path", {
                    "d": d01,
                    "fill": "orange",
                    "cursor": "pointer"
                });
            }

            let lastSampleIndex = 0;
            $(featureGroup).qtip({
                //        content: {text: tooltipText + '
' + feature.files[lastSampleIndex], title: tooltipTitle},
                content: {text: tooltipText + "
" + samplesCount + " samples", title: tooltipTitle},
                //                        position: {target: "mouse", adjust: {x: 15, y: 0}, effect: false},
                position: {target: "mouse", adjust: {x: 25, y: 15}},
                style: {width: true, classes: this.toolTipfontClass + " ui-tooltip ui-tooltip-shadow"},
                show: {delay: 300},
                hide: {delay: 300}
            });

            $(featureGroup).mousemove(function (event) {
                let sampleIndex = parseInt(event.offsetY / yi2);
                if (sampleIndex !== lastSampleIndex) {
                    console.log(sampleIndex);
                    samplesCount = 0;
                    let sampleName = "";
                    let found = false;
                    for (let i in feature.studies) {
                        for (let j in feature.studies[i].samplesData) {   // better search it up than storing it? memory could be an issue.
                            if (sampleIndex === samplesCount) {
                                found = true;
                                sampleName = j;
                            }
                            samplesCount++;
                        }
                    }
                    $(featureGroup).qtip("option", "content.text", tooltipText + "
" + sampleName);
                }
                lastSampleIndex = sampleIndex;
            });
        }
    }
}
<commit_msg>gb: implement two render modes, closes #53<commit_after>/**
 * Stateless (or almost) object to render variants.
 *
 * If you have a svg element where you want to draw, pass it to VariantRenderer.init()
 * and later, in each VariantRenderer.render() as args.svgCanvasFeatures.
 *
 * @type {Renderer}
 */
class VariantRenderer extends Renderer {

    constructor(args) {
        super(args);

        this.sampleTrackY = 15;
        this.sampleTrackHeight = 20;
        this.sampleTrackFontSize = 12;

        Object.assign(this, args);

        // Extend and add Backbone Events
        Object.assign(this, Backbone.Events);
        this.on(this.handlers);
    }

    init(svgGroup, sample) {
        //Prevent browser context menu
        console.log(this.track.main);
        $(svgGroup).contextmenu(function (e) {
            console.log("right click");
            e.preventDefault();
        });

        // Get sample name array, it can be a string or an array
        if (typeof this.sampleNames === "string") {
            this.sampleNames = this.sampleNames.split(",");
        }

        // FIXME sampleNames should be renderer here but in the variant-track.js
        if (typeof this.sampleNames !== "undefined" && this.sampleNames !== null) {
            let y = this.sampleTrackY;
            for (let i = 0; i < this.sampleNames.length; i++) {
                let sampleSvg = SVG.addChild(this.track.main, "text", {
                    "x": 0,
                    "y": y,
                    "stroke": "black",
                    "stroke-width": 1,
                    "font-size": this.sampleTrackFontSize,
                    "cursor": "pointer"
                });
                sampleSvg.textContent = this.sampleNames[i];

                y += this.sampleTrackHeight;

                let _this = this;
                $(sampleSvg).click(function (event) {
                    // $(this).css({"strokeWidth":"3","stroke":"#ff7200"}).hide(100).show(500).css({"stroke":"#51c000"})});
                    // amarillo FCFC92
                    let label = $(this);
                    //label.css({"stroke":"#ff7200"}).hide(100).show(500).css({"stroke":"#ff7200"});

                    //POSIBILIDAD 1
                    //let rect = SVG.addChild(_this.track.main,  "rect",{
                    //    'x': 0,
                    //    'y': label[0].y.baseVal[0].value-7,
                    //    'width': _this.track.width,
                    //    'height': 8,
                    //    'stroke': '#FFFF00',
                    //    'fill': '#FCFC92'
                    //});
                    //$(rect).css({"z-index": -1});

                    //POSIBILIDAD 2
                    let yrect = label[0].y.baseVal[0].value - 7;
                    if (this.getAttribute("stroke") === "black") {
                        label.css({"stroke": "#ff7200"}).hide(100).show(500).css({"stroke": "#ff7200"});
                        this.setAttribute("stroke", "#ff7200");
                        let rect = SVG.create("rect", {
                            "x": 0,
                            "y": yrect,
                            "width": _this.track.width,
                            "height": 8,
                            "stroke": "#FFFF00",
                            "fill": "#F2F5A9",
                            "opacity": 0.5
                        });
                        rect.setAttribute("id", this.innerHTML + "_rect" + yrect);
                        _this.track.main.insertBefore(rect, this);
                    } else {
                        let rect = document.getElementById(this.innerHTML + "_rect" + yrect);
                        rect.parentNode.removeChild(rect);
                        this.setAttribute("stroke", "black");
                        label.css({"stroke": "black"});
                    }

                    //let divpadre = _this.track.main.parentNode;
                    //let selBox = $('

')[0];
                    //divpadre.append(selBox);
                    //$(selBox).css({
                    //    'z-index': 0,
                    //    'position': 'absolute',
                    //    'left': 0,
                    //    'top': label[0].y.baseVal[0].value-8,
                    //    'height': 8,
                    //    'width':'100%',
                    //    'border': '2px solid #FFFF00',
                    //    'opacity': 0.5,
                    //    //'visibility': 'hidden',
                    //    'background-color': '#F2F5A9'
                    //});
                    //$(selBox).click(function(event){
                    //    this.parentNode.removeChild(this);
                    //});
                });
            }
        }
    }

    render(features, args) {
        // for (let i = 0; i < features.length; i++) {
        //     this._renderExtendedGenotypes(features[i], args);
        // }
        if (typeof this.sampleNames !== "undefined" && this.sampleNames !== null && this.sampleNames.length > 0) {
            this._renderExtendedGenotypes(features, args);
        } else {
            this._renderCompactVariants(features, args);
        }
    }

    _renderExtendedGenotypes(features, args) {
        console.time("Variant Extended GT Renderer");

        for (let feature of features) {
            // get feature render configuration
            // let color = _.isFunction(this.color) ? this.color(feature) : this.color;
            // let label = _.isFunction(this.label) ? this.label(feature) : this.label;
            // let height = _.isFunction(this.height) ? this.height(feature) : this.height;
            let tooltipTitle = _.isFunction(this.tooltipTitle) ? this.tooltipTitle(feature) : this.tooltipTitle;
            let tooltipText = _.isFunction(this.tooltipText) ? this.tooltipText(feature) : this.tooltipText;
            // let infoWidgetId = _.isFunction(this.infoWidgetId) ? this.infoWidgetId(feature) : this.infoWidgetId;

            //get feature genomic information
            let start = feature.start;
            let end = feature.end;
            let length = (end - start) + 1;

            //check genomic length
            length = (length < 0) ? Math.abs(length) : length;
            length = (length === 0) ? 1 : length;

            // Transform to pixel position, minimum width set to 1px
            let width = length * args.pixelBase;
            width = Math.max(width, 1);

            // let svgLabelWidth = this.getLabelWidth(label, args);
            //calculate x to draw svg rect
            let x = this.getFeatureX(start, args);
            // let maxWidth = Math.max(width, 2);
            // let textHeight = 0;
            // if (args.regionSize < args.maxLabelRegionSize) {
            //     textHeight = 9;
            //     maxWidth = Math.max(width, svgLabelWidth);
            // }
            // let rowY = 0;
            // let textY = textHeight + height;
            // let rowHeight = textHeight + height + 2;

            // Color: Dark blue: 0/0, Orange: 0/1, Red: 1/1, Black: ./.
            let d00 = "";
            let dDD = "";
            let d11 = "";
            let d01 = "";
            let xs = x;         // x start
            let xe = x + width; // x end
            let ys = 5;         // y
            let yi = 10;         // y increment
            let yi2 = this.sampleTrackHeight;       // y increment

            let samplesCount = feature.studies[0].samplesData.length;
            for (let i in feature.studies[0].samplesData) {
                let svgPath = "M" + xs + "," + ys + " L" + xe + "," + ys + " L" + xe + "," + (ys + yi) + " L" + xs + "," + (ys + yi) + " z ";

                // Only one study is expected, and GT is always the first field in samplesData
                let genotype = feature.studies[0].samplesData[i]["0"];
                switch (genotype) {
                    case "0|0":
                    case "0/0":
                        d00 += svgPath;
                        break;
                    case "0|1":
                    case "0/1":
                    case "1|0":
                    case "1/0":
                        d01 += svgPath;
                        break;
                    case "1|1":
                    case "1/1":
                        d11 += svgPath;
                        break;
                    case ".|.":
                    case "./.":
                        dDD += svgPath;
                        break;
                }
                ys += yi2;
            }

            let featureGroup = SVG.addChild(args.svgCanvasFeatures, "g", {"feature_id": feature.id});
            let dummyRect = SVG.addChild(featureGroup, "rect", {
                "x": xs,
                "y": 1,
                "width": width,
                "height": ys,
                "fill": "transparent",
                "cursor": "pointer"
            });
            if (d00 !== "") {
                let path = SVG.addChild(featureGroup, "path", {
                    "d": d00,
                    "fill": "blue",
                    "cursor": "pointer"
                });
            }
            if (dDD !== "") {
                let path = SVG.addChild(featureGroup, "path", {
                    "d": dDD,
                    "fill": "black",
                    "cursor": "pointer"
                });
            }
            if (d11 !== "") {
                let path = SVG.addChild(featureGroup, "path", {
                    "d": d11,
                    "fill": "red",
                    "cursor": "pointer"
                });
            }
            if (d01 !== "") {
                let path = SVG.addChild(featureGroup, "path", {
                    "d": d01,
                    "fill": "orange",
                    "cursor": "pointer"
                });
            }

            let lastSampleIndex = 0;
            $(featureGroup).qtip({
                //        content: {text: tooltipText + '
' + feature.files[lastSampleIndex], title: tooltipTitle},
                content: {text: tooltipText + "
" + samplesCount + " samples", title: tooltipTitle},
                //                        position: {target: "mouse", adjust: {x: 15, y: 0}, effect: false},
                position: {target: "mouse", adjust: {x: 25, y: 15}},
                style: {width: true, classes: this.toolTipfontClass + " ui-tooltip ui-tooltip-shadow"},
                show: {delay: 300},
                hide: {delay: 300}
            });

            $(featureGroup).mousemove(function (event) {
                let sampleIndex = parseInt(event.offsetY / yi2);
                if (sampleIndex !== lastSampleIndex) {
                    console.log(sampleIndex);
                    samplesCount = 0;
                    let sampleName = "";
                    let found = false;
                    for (let i in feature.studies) {
                        for (let j in feature.studies[i].samplesData) {   // better search it up than storing it? memory could be an issue.
                            if (sampleIndex === samplesCount) {
                                found = true;
                                sampleName = j;
                            }
                            samplesCount++;
                        }
                    }
                    $(featureGroup).qtip("option", "content.text", tooltipText + "
" + sampleName);
                }
                lastSampleIndex = sampleIndex;
            });
        }
        console.timeEnd("Variant Extended GT Renderer");
    }

    _renderCompactVariants(features, args) {
        console.time("Variant Compact Renderer");

        let svgGroup = SVG.create("g");
        for (let i = 0; i < features.length; i++) {
            let feature = features[i];

            if ("featureType" in feature) {
                Object.assign(this, FEATURE_TYPES[feature.featureType]);
            }
            if ("featureClass" in feature) {
                Object.assign(this, FEATURE_TYPES[feature.featureClass]);
            }

            //Temporal fix for clinical
            if (args.featureType === "clinical") {
                if ("clinvarSet" in feature) {
                    Object.assign(this, FEATURE_TYPES["Clinvar"]);
                } else if ("mutationID" in feature) {
                    Object.assign(this, FEATURE_TYPES["Cosmic"]);
                } else {
                    Object.assign(this, FEATURE_TYPES["GWAS"]);
                }
            }

            // get feature render configuration
            let color = _.isFunction(this.color) ? this.color(feature) : this.color;
            let strokeColor = _.isFunction(this.strokeColor) ? this.color(feature) : this.strokeColor;
            let label = _.isFunction(this.label) ? this.label(feature) : this.label;
            let height = _.isFunction(this.height) ? this.height(feature) : this.height;
            let tooltipTitle = _.isFunction(this.tooltipTitle) ? this.tooltipTitle(feature) : this.tooltipTitle;
            let tooltipText = _.isFunction(this.tooltipText) ? this.tooltipText(feature) : this.tooltipText;
            let infoWidgetId = _.isFunction(this.infoWidgetId) ? this.infoWidgetId(feature) : this.infoWidgetId;

            // get feature genomic information
            let start = feature.start;
            let end = feature.end;
            let length = (end - start) + 1;

            // check genomic length
            length = (length < 0) ? Math.abs(length) : length;
            length = (length === 0) ? 1 : length;

            // transform to pixel position
            let width = length * args.pixelBase;

            //        var svgLabelWidth = this.getLabelWidth(label, args);
            let svgLabelWidth = label.length * 6.4;

            //calculate x to draw svg rect
            let x = this.getFeatureX(start, args);

            let maxWidth = Math.max(width, 2);
            let textHeight = 0;
            if (args.maxLabelRegionSize > args.regionSize) {
                textHeight = 9;
                maxWidth = Math.max(width, svgLabelWidth);
            }

            let rowY = 0;
            let textY = textHeight + height;
            let rowHeight = textHeight + height + 2;

            while (true) {
                if (!(rowY in args.renderedArea)) {
                    args.renderedArea[rowY] = new FeatureBinarySearchTree();
                }
                let foundArea = args.renderedArea[rowY].add({start: x, end: x + maxWidth - 1});

                if (foundArea) {
                    let featureGroup = SVG.addChild(svgGroup, "g", {"feature_id": feature.id});
                    let rect = SVG.addChild(featureGroup, "rect", {
                        "x": x,
                        "y": rowY,
                        "width": width,
                        "height": height,
                        "stroke": strokeColor,
                        "stroke-width": 1,
                        "stroke-opacity": 0.7,
                        "fill": color,
                        "cursor": "pointer"
                    });

                    if (args.maxLabelRegionSize > args.regionSize) {
                        let text = SVG.addChild(featureGroup, "text", {
                            "i": i,
                            "x": x,
                            "y": textY,
                            "font-weight": 400,
                            "opacity": null,
                            "fill": "black",
                            "cursor": "pointer",
                            "class": this.fontClass
                        });
                        text.textContent = label;
                    }

                    if ("tooltipText" in this) {
                        $(featureGroup).qtip({
                            content: {text: tooltipText, title: tooltipTitle},
                            //                        position: {target: "mouse", adjust: {x: 15, y: 0}, effect: false},
                            position: {viewport: $(window), target: "mouse", adjust: {x: 25, y: 15}},
                            style: {width: true, classes: this.toolTipfontClass + " ui-tooltip ui-tooltip-shadow"},
                            show: {delay: 300},
                            hide: {delay: 300}
                        });
                    }

                    $(featureGroup).mouseover(function (event) {
                        this.trigger("feature:mouseover", {
                            query: feature[infoWidgetId],
                            feature: feature,
                            featureType: feature.featureType,
                            mouseoverEvent: event
                        });
                    });

                    $(featureGroup).click(function (event) {
                        this.trigger("feature:click", {
                            query: feature[infoWidgetId],
                            feature: feature,
                            featureType: feature.featureType,
                            clickEvent: event
                        });
                    });
                    break;
                }
                rowY += rowHeight;
                textY += rowHeight;
            }
        }
        args.svgCanvasFeatures.appendChild(svgGroup);
        console.timeEnd("Variant Compact Renderer");
    }
}
<|endoftext|>


<commit_before>App.SingleBlogController = App.DashboardController.extend({
});
<commit_msg>Cleanup<commit_after>App.SingleBlogController = App.DashboardController.extend({});
<|endoftext|>


<commit_before>'use strict';

(function () {

angular
  .module('copayApp.controllers')
  .controller('walletSelectorController', walletSelectorController);

  function walletSelectorController ($scope, $state, sendFlowService, configService, gettextCatalog, ongoingProcess, profileService, walletService, txFormatService) {
    var fromWalletId = '';
    var priceDisplayAsFiat = false;
    var unitDecimals = 0;
    var unitsFromSatoshis = 0;

    //
    // Needs to migrate $scope to vm.
    //
    function initVariables() {
      // Private variables
      fromWalletId = '';
      priceDisplayAsFiat = false;
      unitDecimals = 0;
      unitsFromSatoshis = 0;
    }

    $scope.$on("$ionicView.beforeEnter", onBeforeEnter);

    function onBeforeEnter(event, data) {
      if (data.direction == "back") {
        sendFlowService.state.pop();
      }

      // Init before entering on this screen
      initVariables();
      // Then start

      $scope.params = sendFlowService.state.getClone();

      console.log('walletSelector onBeforeEnter after back sendflow', $scope.params);

      var config = configService.getSync().wallet.settings;
      $scope.selectedPriceDisplay = config.priceDisplay;
      priceDisplayAsFiat = config.priceDisplay === 'fiat';
      unitDecimals = config.unitDecimals;
      unitsFromSatoshis = 1 / config.unitToSatoshi;

      if ($scope.params.isWalletTransfer) {
        $scope.sendFlowTitle = gettextCatalog.getString('Transfer between wallets');
      } else if (!$scope.params.thirdParty) {
        $scope.sendFlowTitle = gettextCatalog.getString('Send');
      }

      $scope.coin = false; // Wallets to show (for destination screen or contacts)
      $scope.type = $scope.params['fromWalletId'] ? 'destination' : 'origin'; // origin || destination
      fromWalletId = $scope.params['fromWalletId'];

      if ($scope.type === 'destination' && $scope.params.toAddress) {
        $state.transitionTo(getNextStep($scope.params));
      }

      if ($scope.params.coin) {
        $scope.coin = $scope.params.coin; // Contacts have a coin embedded
      }

      if ($scope.params.amount) { // There is an amount, so presume that it is a payment request
        $scope.sendFlowTitle = gettextCatalog.getString('Payment Request');
        $scope.specificAmount = $scope.specificAlternativeAmount = '';
        $scope.isPaymentRequest = true;
      }

      if ($scope.params.thirdParty) {
        // Third party services specific logic
        handleThirdPartyIfShapeshift();
      }

      prepareWalletLists();
      formatRequestedAmount();
    };

    function formatRequestedAmount() {
      if ($scope.params.amount) {
        var cryptoAmount = (unitsFromSatoshis * $scope.params.amount).toFixed(unitDecimals);
        var cryptoCoin = $scope.coin.toUpperCase();

        txFormatService.formatAlternativeStr($scope.coin, $scope.params.amount, function onFormatAlternativeStr(formatted){
          if (formatted) {
            var fiatParts = formatted.split(' ');
            var fiatAmount = fiatParts[0];
            var fiatCurrrency = fiatParts.length > 1 ? fiatParts[1] : '';

            if (priceDisplayAsFiat) {
              $scope.requestAmount = fiatAmount;
              $scope.requestCurrency = fiatCurrrency;

              $scope.requestAmountSecondary = cryptoAmount;
              $scope.requestCurrencySecondary = cryptoCoin;
            } else {
              $scope.requestAmount = cryptoAmount;
              $scope.requestCurrency = cryptoCoin;

              $scope.requestAmountSecondary = fiatAmount;
              $scope.requestCurrencySecondary = fiatCurrrency;
            }
            $scope.$apply();
          }
        });
      }
    }

    function handleThirdPartyIfShapeshift() {
      console.log($scope.params.thirdParty, $scope.coin);
      if ($scope.params.thirdParty.id === 'shapeshift' && $scope.type === 'destination') { // Shapeshift wants to know the
        $scope.coin = profileService.getWallet(fromWalletId).coin;
        if ($scope.coin === 'bch') {
          $scope.coin = 'btc';
        } else {
          $scope.coin = 'bch';
        }
      }
    }

    function prepareWalletLists() {
      var walletsAll = [];
      var walletsSufficientFunds = [];
      $scope.walletsInsufficientFunds = []; // For origin screen
      $scope.walletsBtc = [];
      $scope.walletsBch = [];

      if ($scope.type === 'origin') {
        $scope.headerTitle = gettextCatalog.getString('Choose a wallet to send from');

        if ($scope.params.amount || $scope.coin) {

          walletsAll = profileService.getWallets({coin: $scope.coin});
          ongoingProcess.set('scanning', true);
          walletsAll.forEach(function forWallet(wallet) {
            if (!wallet.status && !wallet.cachedStatus) {
              walletService.getStatus(wallet, {}, function(err, status) {
                wallet.status = status;
                if (status.availableBalanceSat > ($scope.params.amount ? $scope.params.amount : 0)) {
                  walletsSufficientFunds.push(wallet);
                } else {
                  $scope.walletsInsufficientFunds.push(wallet);
                }
                if ($scope.coin === 'btc') { // As this is a promise
                  $scope.walletsBtc = walletsSufficientFunds;
                } else {
                  $scope.walletsBch = walletsSufficientFunds;
                }
                ongoingProcess.set('scanning', false);
              });
            } else {
              var walletStatus = null;
              if (wallet.status && wallet.status.isValid) {
                walletStatus = wallet.status;
              } else if (wallet.cachedStatus && wallet.status.isValid) {
                walletStatus = wallet.cachedStatus;
              }

              if (walletStatus && walletStatus.availableBalanceSat > ($scope.params.amount ? $scope.params.amount : 0)) {
                walletsSufficientFunds.push(wallet);
              } else {
                $scope.walletsInsufficientFunds.push(wallet);
              }
              ongoingProcess.set('scanning', false);
            }
          });

          if ($scope.coin === 'btc') {
            $scope.walletsBtc = walletsSufficientFunds;
          } else {
            $scope.walletsBch = walletsSufficientFunds;
          }
        } else {
          $scope.walletsBch = profileService.getWallets({coin: 'bch', hasFunds: true});
          $scope.walletsBtc = profileService.getWallets({coin: 'btc', hasFunds: true});
          $scope.walletsInsufficientFunds = profileService.getWallets({coin: $scope.coin, hasNoFunds: true});
        }

      } else if ($scope.type === 'destination') {
        if (!$scope.coin) { // Allow for the coin to be set by a third party
          $scope.fromWallet = profileService.getWallet(fromWalletId);
          $scope.coin = $scope.fromWallet.coin; // Only show wallets with the select origin wallet coin
        }
        $scope.headerTitle = gettextCatalog.getString('Choose a wallet to send to');

        if ($scope.coin === 'btc') { // if no specific coin is set or coin is set btc
          $scope.walletsBtc = profileService.getWallets({coin: $scope.coin});
        } else {
          $scope.walletsBch = profileService.getWallets({coin: $scope.coin});
        }
      }
    }

    $scope.useWallet = function(wallet) {
      var params = sendFlowService.state.getClone();
      if ($scope.type === 'origin') { // we're on the origin screen, set wallet to send from
        params.fromWalletId = wallet.id;
      } else { // we're on the destination screen, set wallet to send to
        params.toWalletId = wallet.id;
      }
      sendFlowService.goNext(params);
    };

    $scope.goBack = function() {
      sendFlowService.router.goBack();
    }

  }
})();<commit_msg>Fix insufficient funds : cached values + refresh UI for some cases.<commit_after>'use strict';

(function () {

angular
  .module('copayApp.controllers')
  .controller('walletSelectorController', walletSelectorController);

  function walletSelectorController ($scope, $timeout, $state, sendFlowService, configService, gettextCatalog, ongoingProcess, profileService, walletService, txFormatService) {
    var fromWalletId = '';
    var priceDisplayAsFiat = false;
    var unitDecimals = 0;
    var unitsFromSatoshis = 0;

    //
    // Needs to migrate $scope to vm.
    //
    function initVariables() {
      // Private variables
      fromWalletId = '';
      priceDisplayAsFiat = false;
      unitDecimals = 0;
      unitsFromSatoshis = 0;
    }

    $scope.$on("$ionicView.beforeEnter", onBeforeEnter);

    function onBeforeEnter(event, data) {
      if (data.direction == "back") {
        sendFlowService.state.pop();
      }

      // Init before entering on this screen
      initVariables();
      // Then start

      $scope.params = sendFlowService.state.getClone();

      console.log('walletSelector onBeforeEnter after back sendflow', $scope.params);

      var config = configService.getSync().wallet.settings;
      $scope.selectedPriceDisplay = config.priceDisplay;
      priceDisplayAsFiat = config.priceDisplay === 'fiat';
      unitDecimals = config.unitDecimals;
      unitsFromSatoshis = 1 / config.unitToSatoshi;

      if ($scope.params.isWalletTransfer) {
        $scope.sendFlowTitle = gettextCatalog.getString('Transfer between wallets');
      } else if (!$scope.params.thirdParty) {
        $scope.sendFlowTitle = gettextCatalog.getString('Send');
      }

      $scope.coin = false; // Wallets to show (for destination screen or contacts)
      $scope.type = $scope.params['fromWalletId'] ? 'destination' : 'origin'; // origin || destination
      fromWalletId = $scope.params['fromWalletId'];

      if ($scope.type === 'destination' && $scope.params.toAddress) {
        $state.transitionTo(getNextStep($scope.params));
      }

      if ($scope.params.coin) {
        $scope.coin = $scope.params.coin; // Contacts have a coin embedded
      }

      if ($scope.params.amount) { // There is an amount, so presume that it is a payment request
        $scope.sendFlowTitle = gettextCatalog.getString('Payment Request');
        $scope.specificAmount = $scope.specificAlternativeAmount = '';
        $scope.isPaymentRequest = true;
      }

      if ($scope.params.thirdParty) {
        // Third party services specific logic
        handleThirdPartyIfShapeshift();
      }

      prepareWalletLists();
      formatRequestedAmount();
    };

    function formatRequestedAmount() {
      if ($scope.params.amount) {
        var cryptoAmount = (unitsFromSatoshis * $scope.params.amount).toFixed(unitDecimals);
        var cryptoCoin = $scope.coin.toUpperCase();

        txFormatService.formatAlternativeStr($scope.coin, $scope.params.amount, function onFormatAlternativeStr(formatted){
          if (formatted) {
            var fiatParts = formatted.split(' ');
            var fiatAmount = fiatParts[0];
            var fiatCurrrency = fiatParts.length > 1 ? fiatParts[1] : '';

            if (priceDisplayAsFiat) {
              $scope.requestAmount = fiatAmount;
              $scope.requestCurrency = fiatCurrrency;

              $scope.requestAmountSecondary = cryptoAmount;
              $scope.requestCurrencySecondary = cryptoCoin;
            } else {
              $scope.requestAmount = cryptoAmount;
              $scope.requestCurrency = cryptoCoin;

              $scope.requestAmountSecondary = fiatAmount;
              $scope.requestCurrencySecondary = fiatCurrrency;
            }
            $scope.$apply();
          }
        });
      }
    }

    function handleThirdPartyIfShapeshift() {
      console.log($scope.params.thirdParty, $scope.coin);
      if ($scope.params.thirdParty.id === 'shapeshift' && $scope.type === 'destination') { // Shapeshift wants to know the
        $scope.coin = profileService.getWallet(fromWalletId).coin;
        if ($scope.coin === 'bch') {
          $scope.coin = 'btc';
        } else {
          $scope.coin = 'bch';
        }
      }
    }

    function prepareWalletLists() {
      var walletsAll = [];
      var walletsSufficientFunds = [];
      $scope.walletsInsufficientFunds = []; // For origin screen
      $scope.walletsBtc = [];
      $scope.walletsBch = [];

      if ($scope.type === 'origin') {
        $scope.headerTitle = gettextCatalog.getString('Choose a wallet to send from');

        if ($scope.params.amount || $scope.coin) {

          ongoingProcess.set('scanning', true);
          walletsAll = profileService.getWallets({coin: $scope.coin});
          walletsAll.forEach(function forWallet(wallet) {
            var walletStatus = null;
            if (wallet.status && wallet.status.isValid) { // We never get there after checking a wallet, are we sure concerning this object?
              walletStatus = wallet.status;
            } else if (wallet.cachedStatus && wallet.status.isValid) { // We never get there after checking a wallet, are we sure concerning this object?
              walletStatus = wallet.cachedStatus;
            }

            if (!walletStatus) {
              walletService.getStatus(wallet, {}, function(err, status) {
                console.log(err); // We need to handle the error properly

                wallet.status = status;

                $timeout(function () { // because of promise
                  if (status.availableBalanceSat > ($scope.params.amount ? $scope.params.amount : 0)) {
                    if (wallet.coin === 'btc') {
                      $scope.walletsBtc.push(wallet);
                    } else {
                      $scope.walletsBch.push(wallet);
                    }
                  } else {
                    $scope.walletsInsufficientFunds.push(wallet);
                  }

                  ongoingProcess.set('scanning', false);
                }, 60);
              });
            } else {
              $timeout(function () { // because of promise
                if (walletStatus && walletStatus.availableBalanceSat > ($scope.params.amount ? $scope.params.amount : 0)) {
                  walletsSufficientFunds.push(wallet);
                  if (wallet.coin === 'btc') {
                    $scope.walletsBtc.push(wallet);
                  } else {
                    $scope.walletsBch.push(wallet);
                  }
                } else {
                  $scope.walletsInsufficientFunds.push(wallet);
                }
                ongoingProcess.set('scanning', false);
              }, 60);
            }
          });
        } else {
          $scope.walletsBch = profileService.getWallets({coin: 'bch', hasFunds: true});
          $scope.walletsBtc = profileService.getWallets({coin: 'btc', hasFunds: true});
          $scope.walletsInsufficientFunds = profileService.getWallets({coin: $scope.coin, hasNoFunds: true});
        }

      } else if ($scope.type === 'destination') {
        if (!$scope.coin) { // Allow for the coin to be set by a third party
          $scope.fromWallet = profileService.getWallet(fromWalletId);
          $scope.coin = $scope.fromWallet.coin; // Only show wallets with the select origin wallet coin
        }
        $scope.headerTitle = gettextCatalog.getString('Choose a wallet to send to');

        if ($scope.coin === 'btc') { // if no specific coin is set or coin is set btc
          $scope.walletsBtc = profileService.getWallets({coin: $scope.coin});
        } else {
          $scope.walletsBch = profileService.getWallets({coin: $scope.coin});
        }
      }
    }

    $scope.useWallet = function(wallet) {
      var params = sendFlowService.state.getClone();
      if ($scope.type === 'origin') { // we're on the origin screen, set wallet to send from
        params.fromWalletId = wallet.id;
      } else { // we're on the destination screen, set wallet to send to
        params.toWalletId = wallet.id;
      }
      sendFlowService.goNext(params);
    };

    $scope.goBack = function() {
      sendFlowService.router.goBack();
    }

  }
})();<|endoftext|>


<commit_before>var reqs = {
  sort: {
    sortType: 'asc',
    sortField: 'status'
  },
  filter: 'all',
  categories: [
    {"title": "Foo", "slug": "foo"},
    {"title": "Bar", "slug": "bar"},
    {"title": "Baz", "slug": "baz"}
  ],
  data: [],
  viewData: []
}

var data = [
  {
    "path": "http://google.com",
    "status": 200,
    "type": "Some type",
    "size": 1323333,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Foo", "slug": "foo"},
    "description": "http://my-api.com/123"
  },
  {
    "path": "http://facebook.com",
    "status": 304,
    "type": "Another type",
    "size": "330000",
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Bar", "slug": "bar"},
    "description": "http://my-api.com/356"
  },
  {
    "path": "http://microsoft.com",
    "status": 500,
    "type": "Type",
    "size": 20000000,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Bar", "slug": "bar"},
    "description": "http://my-api.com/34"
  },
  {
    "path": "http://microsoft.com",
    "status": 600,
    "type": "Type",
    "size": 123000,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Bar", "slug": "bar"},
    "description": "http://my-api.com/34"
  },
  {
    "path": "http://microsoft.com",
    "status": 600,
    "type": "Type",
    "size": 123000,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Baz", "slug": "baz"},
    "description": "http://my-api.com/34"
  },
  {
    "path": "http://microsoft.com",
    "status": 600,
    "type": "Type",
    "size": 123000,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Baz", "slug": "baz"},
    "description": "http://my-api.com/34"
  },
  {
    "path": "http://microsoft.com",
    "status": 600,
    "type": "Type",
    "size": 123000,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Foo", "slug": "foo"},
    "description": "http://my-api.com/34"
  }
]

function ListingReducer(state = reqs, action) {
  switch (action.type) {
    case 'SET_REQUEST_ENTRIES': {
      return sorting(filtering(Object.assign(state, {data: data})));
    }
    case 'SORT_ENTRIES': {
      let sortType = action.sortType;
      if (!action.sortType) {
        if (state.sort.sortField === action.sortField) {
          sortType = state.sort.sortType === 'asc' ? 'desc' : 'asc';
        } else {
          sortType = 'asc';
        }
      }
      return Object.assign(state, {
        sort: {
          sortField: action.sortField,
          sortType: sortType
        }
      })
    }
    case 'FILTERING_ENTRIES': {
      if (action.filterType === state.filter) { return state; }
      return Object.assign(state, {
        filter: action.filterType
      });
    }
    default:
      return state;
  }
}

function sorting(state) {
  if (!state.sort.sortField) { return state; }
  let sortCondition = state.sort.sortType === 'asc' ? [1, 0] : [0, 1];
  let data = [...state.viewData];
  data.sort(function (a, b) {
    return a[state.sort.sortField] > b[state.sort.sortField] ? sortCondition[0] : sortCondition[1];
  });
  return Object.assign(state, {viewData: data});
}

function filtering(state) {
  let viewData = [];
  state.data.forEach(function (el) {
    if (state.filter === el.category.slug || state.filter === 'all') {
      viewData.push(el);
    }
  });
  return Object.assign(state, {viewData: viewData});
}

export { ListingReducer }<commit_msg>Change default state<commit_after>var reqs = {
  sort: {},
  filter: 'all',
  categories: [
    {"title": "Foo", "slug": "foo"},
    {"title": "Bar", "slug": "bar"},
    {"title": "Baz", "slug": "baz"}
  ],
  data: [],
  viewData: []
}

var data = [
  {
    "path": "http://google.com",
    "status": 200,
    "type": "Some type",
    "size": 1323333,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Foo", "slug": "foo"},
    "description": "http://my-api.com/123"
  },
  {
    "path": "http://facebook.com",
    "status": 304,
    "type": "Another type",
    "size": "330000",
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Bar", "slug": "bar"},
    "description": "http://my-api.com/356"
  },
  {
    "path": "http://microsoft.com",
    "status": 500,
    "type": "Type",
    "size": 20000000,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Bar", "slug": "bar"},
    "description": "http://my-api.com/34"
  },
  {
    "path": "http://microsoft.com",
    "status": 600,
    "type": "Type",
    "size": 123000,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Bar", "slug": "bar"},
    "description": "http://my-api.com/34"
  },
  {
    "path": "http://microsoft.com",
    "status": 600,
    "type": "Type",
    "size": 123000,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Baz", "slug": "baz"},
    "description": "http://my-api.com/34"
  },
  {
    "path": "http://microsoft.com",
    "status": 600,
    "type": "Type",
    "size": 123000,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Baz", "slug": "baz"},
    "description": "http://my-api.com/34"
  },
  {
    "path": "http://microsoft.com",
    "status": 600,
    "type": "Type",
    "size": 123000,
    "time": {
      "from": "1462887783",
      "to": "1462887783"
    },
    "category": {"title": "Foo", "slug": "foo"},
    "description": "http://my-api.com/34"
  }
]

function ListingReducer(state = reqs, action) {
  switch (action.type) {
    case 'SET_REQUEST_ENTRIES': {
      return sorting(filtering(Object.assign(state, {data: data})));
    }
    case 'SORT_ENTRIES': {
      let sortType = action.sortType;
      if (!action.sortType) {
        if (state.sort.sortField === action.sortField) {
          sortType = state.sort.sortType === 'asc' ? 'desc' : 'asc';
        } else {
          sortType = 'asc';
        }
      }
      return Object.assign(state, {
        sort: {
          sortField: action.sortField,
          sortType: sortType
        }
      })
    }
    case 'FILTERING_ENTRIES': {
      if (action.filterType === state.filter) { return state; }
      return Object.assign(state, {
        filter: action.filterType
      });
    }
    default:
      return state;
  }
}

function sorting(state) {
  if (!state.sort.sortField) { return state; }
  let sortCondition = state.sort.sortType === 'asc' ? [1, 0] : [0, 1];
  let data = [...state.viewData];
  data.sort(function (a, b) {
    return a[state.sort.sortField] > b[state.sort.sortField] ? sortCondition[0] : sortCondition[1];
  });
  return Object.assign(state, {viewData: data});
}

function filtering(state) {
  let viewData = [];
  state.data.forEach(function (el) {
    if (state.filter === el.category.slug || state.filter === 'all') {
      viewData.push(el);
    }
  });
  return Object.assign(state, {viewData: viewData});
}

export { ListingReducer }<|endoftext|>


<commit_before>'use strict'
const AWS = require('aws-sdk');
const promise = require('promise');
const rp = require('request-promise');

const USERDATA_URI = 'https://raw.githubusercontent.com/hhvm/packaging/master/ng/aws/userdata/make-source-tarball.sh';

function make_source_tarball(version, user_data, callback) {
  if (version === undefined) {
    version = 'nightly';
  } else {
    user_data = "#!/bin/bash\nVERSION="+version+"\n"+user_data;
  }

  const params = {
    ImageId: /* ubuntu 16.04 */ 'ami-6e1a0117',
    MaxCount: 1,
    MinCount: 1,
    InstanceType: 't2.micro',
    SecurityGroups: [ 'hhvm-binary-package-builders' ],
    InstanceInitiatedShutdownBehavior: 'terminate',
    IamInstanceProfile: { Arn: 'arn:aws:iam::223121549624:instance-profile/hhvm-binary-package-builder' },
    KeyName: "hhvm-package-builders",
    TagSpecifications: [
      {
        ResourceType: 'instance',
        Tags: [{
          Key: 'Name',
          Value: 'hhvm-build-source-tarball-'+version
        }]
      }
    ],
    UserData: (new Buffer(user_data)).toString('base64')
  };

  const ec2 = new AWS.EC2();
  ec2.runInstances(params, function(err, data) {
    if (err) {
      callback(err, 'failed to schedule instance');
    } else {
      callback(null, {
        version: version,
        instances: data.Instances.map(function(instance) {
          return instance.InstanceId;
        }),
      });
    }
  });
}

exports.handler = (event, context, callback) => {
  rp(USERDATA_URI)
  .then(function(response) {
    make_source_tarball(event.version, response, callback);
  })
  .done();
};
<commit_msg>pass source tarball params to userdata script<commit_after>'use strict'
const AWS = require('aws-sdk');
const promise = require('promise');
const rp = require('request-promise');

const USERDATA_URI = 'https://raw.githubusercontent.com/hhvm/packaging/master/ng/aws/userdata/make-source-tarball.sh';

function make_source_tarball(event, user_data, callback) {
  if (!(
    event.version &&
    event.source &&
    event.source.bucket &&
    event.source.path
  )) {
    callback("Need version and source on input");
    return;
  }

  user_data =
    "#!/bin/bash\n"+
    "VERSION="+event.version+"\n"+
    "IS_NIGHTLY="+(event.nightly ? "true" : "false")+"\n"+
    "S3_BUCKET="+event.source.bucket+"\n"+
    "S3_PATH="+event.source.path+"\n"+
    user_data;

  const params = {
    ImageId: /* ubuntu 16.04 */ 'ami-6e1a0117',
    MaxCount: 1,
    MinCount: 1,
    InstanceType: 't2.micro',
    SecurityGroups: [ 'hhvm-binary-package-builders' ],
    InstanceInitiatedShutdownBehavior: 'terminate',
    IamInstanceProfile: { Arn: 'arn:aws:iam::223121549624:instance-profile/hhvm-binary-package-builder' },
    KeyName: "hhvm-package-builders",
    TagSpecifications: [
      {
        ResourceType: 'instance',
        Tags: [{
          Key: 'Name',
          Value: 'hhvm-build-'+event.version+'-source-tarball'
        }]
      }
    ],
    UserData: (new Buffer(user_data)).toString('base64')
  };

  const ec2 = new AWS.EC2();
  ec2.runInstances(params, function(err, data) {
    if (err) {
      callback(err, 'failed to schedule instance');
    } else {
      event.instances = data.Instances.map(instance => instance.InstanceId);
      callback(null, event);
    }
  });
}

exports.handler = (event, context, callback) => {
  rp(USERDATA_URI)
  .then(function(response) {
    make_source_tarball(event, response, callback);
  })
  .done();
};
<|endoftext|>