<commit_before>var React           = require('react/addons');
var SequenceViewer  = require('../SequenceViewer');
var SequenceActions = require('../../../actions/SequenceActions');

var _sequence;
var _arrays = [];

function updateSequence () {
  SequenceActions.update(_sequence);
};

var ArrayOperations = {
  initialization: {
    label: 'Initialization',
    operation: function (viewport, data) {

      // add a blur event for the node adder
      d3.select('.edit-node-value')
        .on('blur', function (d) {
          d3.select(this)
            .classed('open', false);
        })
        .on('keydown', function (d) {
          if (d3.event.keyCode === 13) {
            d3.select(this)
              .classed('open', false);
          }
        });

      // add a blur event for the array adder
      function checkArraySize (obj) {
        var sequence;
        if (obj.value === '') {
          d3.select(obj)
            .classed('open', false)
            .classed('error', false);

        } else if (isNaN(parseInt(obj.value))) {
          d3.select(obj)
            .classed('error', true);

          obj.focus();
          obj.value = '';
        } else {
          d3.select(obj)
            .classed('open', false)
            .classed('error', false);

          _sequence.operations.push({
            data: parseInt(obj.value),
            type: 'createArray'
          });

          updateSequence();
        }
      }

      d3.select('.add-array-size')
        .on('blur', function (d) {
          checkArraySize(this);
        })
        .on('keydown', function (d) {
          if (d3.event.keyCode === 13) {
            checkArraySize(this);
          }
        });
    }
  },

  createArray: {
    label: 'Create Array',
    operation: function (viewport, data) {

      // initialize empty array
      var i = 0;
      _array = [];
      for (i; i < data; i += 1) {
        _array.push({ value: null });
      }

      // add the groups for each node
      var nodes = viewport
        .selectAll('g')
        .data(_array)
        .enter()
        .append('g');

      // add the background circle
      nodes
        .append('circle')
        .attr('fill', '#ccc')
        .attr('cx', function (d, i) {
          return (i + 1) * 50;
        })
        .attr('r', '20')
        .attr('stroke', '#aaa')
        .attr('stroke-width', '0')
        .style('cursor', 'pointer')
        .on('mouseover', function (d) {
          d3.select(this)
            .attr('stroke-width', '2');
        })
        .on('mouseout', function (d) {
          d3.select(this)
            .attr('stroke-width', '0');
        });

      // add the value of the node
      nodes
        .append('text')
        .attr('fill', '#aaa')
        .style('font-size', '20px')
        .attr('x', function (d, i) {
          return ((i + 1) * 50);
        })
        .attr('y', 10)
        .attr('text-anchor', 'middle')
        .text(function (d) {
          return (d.value || '_');
        })
        .style('cursor', 'pointer')
        .on('mouseover', function (d) {
          d3.select(this)
            .attr('fill', 'black');
        })
        .on('mouseout', function (d) {
          d3.select(this)
            .attr('fill', '#aaa');
        })
        .on('click', function (d) {
          var elem = d3.select('.edit-node-value')
            .classed('open', true)
            .style('top', d3.event.clientY)
            .style('left', d3.event.clientX);

          var node = elem.node();

          node.focus();
          node.value = '';
        });

      // add opening bracket
      viewport
        .append('text')
        .attr('fill', 'black')
        .attr('y', '12')
        .style('font-size', '40px')
        .text('[');

      // add closing bracket
      viewport
        .append('text')
        .attr('fill', 'black')
        .attr('y', '12')
        .attr('x', ((_array.length + 1) * 50) - 10)
        .style('font-size', '40px')
        .text(']');
    }
  }
};

module.exports = React.createClass({

  addArray: function () {
    var elem = d3.select('.add-array-size')
      .classed('open', true)
      .style('top', window.innerHeight / 2)
      .style('left', window.innerWidth / 2);

    var node = elem.node();
    node.focus();
    node.value = '';
  },

  render: function () {
    var editorProps = {
      sequence:   this.props,
      structure:  ArrayOperations,
      options: [
        { label: '[ ]', action: this.addArray }
      ]
    };
    var viewerProps = {
      sequence:   this.props,
      structure:  ArrayOperations,
      options: [
        { label: '[ ]', action: this.addArray }
      ]
    };
    _sequence = this.props;
    return (

        <input className="edit-node-value value-input" placeholder="Update value" />
        <input className="add-array-size value-input" placeholder="Enter array size" />
        <SequenceViewer {...viewerProps} />

    );
  }
});<commit_msg>can add multiple arrays<commit_after>var React           = require('react/addons');
var SequenceViewer  = require('../SequenceViewer');
var SequenceActions = require('../../../actions/SequenceActions');

var _sequence;
var _arrays = [];
var _groups = [];

function updateSequence () {
  SequenceActions.update(_sequence);
};

var ArrayOperations = {
  initialization: {
    label: 'Initialization',
    operation: function (viewport, data) {

      // add a blur event for the node adder
      d3.select('.edit-node-value')
        .on('blur', function (d) {
          d3.select(this)
            .classed('open', false);
        })
        .on('keydown', function (d) {
          if (d3.event.keyCode === 13) {
            d3.select(this)
              .classed('open', false);
          }
        });

      // add a blur event for the array adder
      function checkArraySize (obj) {
        var sequence;
        if (obj.value === '') {
          d3.select(obj)
            .classed('open', false)
            .classed('error', false);

        } else if (isNaN(parseInt(obj.value))) {
          d3.select(obj)
            .classed('error', true);

          obj.focus();
          obj.value = '';
        } else {
          d3.select(obj)
            .classed('open', false)
            .classed('error', false);

          _sequence.operations.push({
            data: parseInt(obj.value),
            type: 'createArray'
          });

          updateSequence();
        }
      }

      d3.select('.add-array-size')
        .on('blur', function (d) {
          checkArraySize(this);
        })
        .on('keydown', function (d) {
          if (d3.event.keyCode === 13) {
            checkArraySize(this);
          }
        });
    }
  },

  createArray: {
    label: 'Create Array',
    operation: function (viewport, data) {

      // initialize empty array
      var i = 0;
      var array = [];
      for (i; i < data; i += 1) {
        array.push({ value: null });
      }

      _arrays.push(array);

      var verticalOffset = (_arrays.length - 1) * 50;

      // add the groups for each node
      var group = viewport.append('g');
      _groups.push(group);

      var nodes = group
        .selectAll('g')
        .data(array)
        .enter()
        .append('g');

      // add the background circle
      nodes
        .append('circle')
        .attr('fill', '#ccc')
        .attr('cx', function (d, i) {
          return (i + 1) * 50;
        })
        .attr('cy', verticalOffset)
        .attr('r', '20')
        .attr('stroke', '#aaa')
        .attr('stroke-width', '0')
        .style('cursor', 'pointer')
        .on('mouseover', function (d) {
          d3.select(this)
            .attr('stroke-width', '2');
        })
        .on('mouseout', function (d) {
          d3.select(this)
            .attr('stroke-width', '0');
        });

      // add the value of the node
      nodes
        .append('text')
        .attr('fill', '#aaa')
        .style('font-size', '20px')
        .attr('x', function (d, i) {
          return ((i + 1) * 50);
        })
        .attr('y', verticalOffset + 10)
        .attr('text-anchor', 'middle')
        .text(function (d) {
          return (d.value || '_');
        })
        .style('cursor', 'pointer')
        .on('mouseover', function (d) {
          d3.select(this)
            .attr('fill', 'black');
        })
        .on('mouseout', function (d) {
          d3.select(this)
            .attr('fill', '#aaa');
        })
        .on('click', function (d) {
          var elem = d3.select('.edit-node-value')
            .classed('open', true)
            .style('top', d3.event.clientY)
            .style('left', d3.event.clientX);

          var node = elem.node();

          node.focus();
          node.value = '';
        });

      // add opening bracket
      viewport
        .append('text')
        .attr('fill', 'black')
        .attr('y', verticalOffset + 12)
        .style('font-size', '40px')
        .text('[');

      // add closing bracket
      viewport
        .append('text')
        .attr('fill', 'black')
        .attr('y', verticalOffset + 12)
        .attr('x', ((array.length + 1) * 50) - 10)
        .style('font-size', '40px')
        .text(']');
    }
  }
};

module.exports = React.createClass({

  addArray: function () {
    var elem = d3.select('.add-array-size')
      .classed('open', true)
      .style('top', window.innerHeight / 2)
      .style('left', window.innerWidth / 2);

    var node = elem.node();
    node.focus();
    node.value = '';
  },

  render: function () {
    var editorProps = {
      sequence:   this.props,
      structure:  ArrayOperations,
      options: [
        { label: '[ ]', action: this.addArray }
      ]
    };
    var viewerProps = {
      sequence:   this.props,
      structure:  ArrayOperations,
      options: [
        { label: '[ ]', action: this.addArray }
      ]
    };
    _sequence = this.props;
    return (

        <input className="edit-node-value value-input" placeholder="Update value" />
        <input className="add-array-size value-input" placeholder="Enter array size" />
        <SequenceViewer {...viewerProps} />

    );
  }
});<|endoftext|>


<commit_before>/*
Copyright (c) 2011 Cimaron Shanahan

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

var glsl = (function(ARB) {

	/**
	 * Local Scope
	 */
	var glsl, initialized;

	/**
	 * parse_state object
	 */
	function parse_state(target) {
		this.es_shader = true;
		this.language_version = 110;
		this.translation_unit = [];
		this.symbols = new glsl.symbol_table();
		this.target = target;
		this.scanner = glsl.lexer;
	};

	/**
	 * Get next token from lexer
	 *
	 * @param   object    Reference to array to store token in
	 * @param   object    Reference to array to store location of token in source file
	 * @param   object    Unused
	 *
	 * @return  boolean
	 */
	function next_token(yylval, yylloc, scanner) {
		lexer.yylval = {};
		var result = lexer.lex();
		if (result == 1) {
			result = 0; //YYEOF
		}
		yylval[0] = lexer.yylval;
		yylloc[0] = lexer.yylloc;
		return result;
	}

	/*IF DEBUG
	function print_token_value(yyoutput, yytoknum, yyvaluep) {
		glsl.fprintf(2, JSON.stringify(yyvaluep).replace(/"/g, ''));
	}
	*/

	/**
	 * Store parse error
	 *
	 * @param   object    Location of error
	 * @param   object    Unused
	 * @param   object    Error string
	 */
	function print_error(yylloc, state, error) {
		glsl.errors.push(error + " at line " + yylloc.first_line + " column " + yylloc.first_column);
	}

	/**
	 * Compiler object
	 */
	glsl = {

		/**
		 * Compilation mode enumerations
		 */
		mode : {
			vertex : 0,
			fragment : 1
		},

		/**
		 * Compilation results
		 */
		errors : [],

		//expose to lexer/parser
		token : null,
		parseError : function(str, hash) {
			yyerror(lexer.yylloc, state, str);
		},

		initialize : function() {

			//lexer
			this.lexer.yy = this;

			//parser
			this.parser.yy = this;

			this.parser.yylex = next_token;
			this.parser.yyerror = print_error;
			/*IF DEBUG
			this.parser.YYPRINT = print_token_value;
			*/
			//this.parser.initialize_types = initialize_types;

			this.token = this.parser.yytokentype;
		},

		compile : function(source, target) {
			var status, irs;

			if (!initialized) {
				this.initialize();
				initialized = true;
			}

			//reset output
			this.output = null;
			this.errors = [];
			this.state = new parse_state(target);

			//preprocess
			source = this.preprocess(source, this.state);
			if (!source) {
				return false;
			}

			//scan/parse
			lexer.setInput(source);
			//need to get errors here
			if (this.parser.yyparse(this.state) != 0) {
				return false;
			}

			//generate IR code
			irs = this.generate_ir(this.state);
			if (!irs) {
				return false;
			}

			//optimize
			//@todo:

			//generate ARB code
			this.output = this.generate_arb(irs, this.state);

			status = (this.output ? true : false)
			return status;
		}
	};

	return glsl;
}(ARB));

include('cnvGL/includes/glsl/symbol.js');
include('cnvGL/includes/glsl/preprocessor.js');
include('cnvGL/includes/glsl/lexer.js');
include('cnvGL/includes/glsl/lexer_extern.js');
include('cnvGL/includes/glsl/parser.js');
//include('cnvGL/includes/glsl/parser_debug.js');
include('cnvGL/includes/glsl/builtin.js');
include('cnvGL/includes/glsl/ast.js');
include('cnvGL/includes/glsl/type.js');
include('cnvGL/includes/glsl/ir.js');
include('cnvGL/includes/glsl/ir_generator.js');
include('cnvGL/includes/glsl/ir_generator_tables.php');
include('cnvGL/includes/glsl/generator.js');

<commit_msg>Fixing glsl library paths<commit_after>/*
Copyright (c) 2011 Cimaron Shanahan

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

var glsl = (function(ARB) {

	/**
	 * Local Scope
	 */
	var glsl, initialized;

	/**
	 * parse_state object
	 */
	function parse_state(target) {
		this.es_shader = true;
		this.language_version = 110;
		this.translation_unit = [];
		this.symbols = new glsl.symbol_table();
		this.target = target;
		this.scanner = glsl.lexer;
	};

	/**
	 * Get next token from lexer
	 *
	 * @param   object    Reference to array to store token in
	 * @param   object    Reference to array to store location of token in source file
	 * @param   object    Unused
	 *
	 * @return  boolean
	 */
	function next_token(yylval, yylloc, scanner) {
		lexer.yylval = {};
		var result = lexer.lex();
		if (result == 1) {
			result = 0; //YYEOF
		}
		yylval[0] = lexer.yylval;
		yylloc[0] = lexer.yylloc;
		return result;
	}

	/*IF DEBUG
	function print_token_value(yyoutput, yytoknum, yyvaluep) {
		glsl.fprintf(2, JSON.stringify(yyvaluep).replace(/"/g, ''));
	}
	*/

	/**
	 * Store parse error
	 *
	 * @param   object    Location of error
	 * @param   object    Unused
	 * @param   object    Error string
	 */
	function print_error(yylloc, state, error) {
		glsl.errors.push(error + " at line " + yylloc.first_line + " column " + yylloc.first_column);
	}

	/**
	 * Compiler object
	 */
	glsl = {

		/**
		 * Compilation mode enumerations
		 */
		mode : {
			vertex : 0,
			fragment : 1
		},

		/**
		 * Compilation results
		 */
		errors : [],

		//expose to lexer/parser
		token : null,
		parseError : function(str, hash) {
			yyerror(lexer.yylloc, state, str);
		},

		initialize : function() {

			//lexer
			this.lexer.yy = this;

			//parser
			this.parser.yy = this;

			this.parser.yylex = next_token;
			this.parser.yyerror = print_error;
			/*IF DEBUG
			this.parser.YYPRINT = print_token_value;
			*/
			//this.parser.initialize_types = initialize_types;

			this.token = this.parser.yytokentype;
		},

		compile : function(source, target) {
			var status, irs;

			if (!initialized) {
				this.initialize();
				initialized = true;
			}

			//reset output
			this.output = null;
			this.errors = [];
			this.state = new parse_state(target);

			//preprocess
			source = this.preprocess(source, this.state);
			if (!source) {
				return false;
			}

			//scan/parse
			lexer.setInput(source);
			//need to get errors here
			if (this.parser.yyparse(this.state) != 0) {
				return false;
			}

			//generate IR code
			irs = this.generate_ir(this.state);
			if (!irs) {
				return false;
			}

			//optimize
			//@todo:

			//generate ARB code
			this.output = this.generate_arb(irs, this.state);

			status = (this.output ? true : false)
			return status;
		}
	};

	return glsl;
}(ARB));

include('glsl/symbol.js');
include('glsl/preprocessor.js');
include('glsl/lexer.js');
include('glsl/lexer_extern.js');
include('glsl/parser.js');
//include('glsl/parser_debug.js');
include('glsl/builtin.js');
include('glsl/ast.js');
include('glsl/type.js');
include('glsl/ir.js');
include('glsl/ir_generator.js');
include('glsl/ir_generator_tables.php');
include('glsl/generator.js');

<|endoftext|>


<commit_before>(function (window, undefined) {
  var
    // aliases
    document = window.document,
    // constants
    PREFIX = "data-glue",
    R_ATTR_PREFIX = new RegExp("^" + PREFIX + "-"),
    R_BOOL = /^(true|false)$/,
    // state
    callbacks = {},
    invokedNodes = [],

  glue = function (name, callback) {
    if (callback !== undefined) {
      callbacks[name] = callback;
    }

    if (callbacks[name] !== undefined) {
      invokeNodes(findNodes(name), callbacks[name]);
    }
  },

  findNodes = (function () {
    var find;

    if (document.querySelectorAll !== undefined) {
      find = function (name) {
        return toArray(document.querySelectorAll("[" + PREFIX + "=" + name + "]"));
      };
    } else {
      find = function walk(name, root) {
        var child, i, nodes;

        if (root === undefined) {
          return walk(name, document.body);
        }

        nodes = [];

        for (i = 0; child = root.children[i++];) {
          if (child.nodeType === 1) {
            if (child.hasAttribute(PREFIX)) {
              nodes.push(child);
            }

            if (child.children.length > 0) {
              nodes = nodes.concat(walk(name, child));
            }
          }
        }

        return nodes;
      };
    }

    return function (name) {
      var k, invokedNode, node,
          i = 0,
          nodes = find(name),
          uninvokedNodes = [];

      outer: for (;node = nodes[i++];) {
        inner: for (k = 0;invokedNode = invokedNodes[k++];) {
          if (invokedNode === node) {
            continue outer;
          }
        }

        uninvokedNodes.push(node);
      }

      return uninvokedNodes;
    };
  })(),

  findAttributes = function (node) {
    var attr, name,
        attrs = {},
        i = 0;

    for (;attr = node.attributes[i++];) {
      name = attr.name.split(R_ATTR_PREFIX)[1];

      if (name !== undefined) {
        attrs[name] = attr.nodeValue;
      }
    }

    return attrs;
  },

  invokeNodes = function (nodes, callback) {
    var node,
        i = 0;

    for (;node = nodes[i++];) {
      invokeNode(node, callback);
    }
  },

  invokeNode = function (node, callback) {
    var attrs = findAttributes(node),
        settings = {},
        key;

    for (key in attrs) {
      if (attrs.hasOwnProperty(key)) {
        settings[key] = parseAttr(attrs[key]);
      }
    }

    callback.call(node, settings);
    invokedNodes.push(node);
  },

  parseAttr = function (value) {
    // number
    if(/^\-?([0-9]+(\.[0-9]+)?|Infinity)$/.test(value)) {
      return Number(value);
    }
    // boolean
    else if (value.match(R_BOOL)) {
      return (value === "true") ? true : false;
    }

    // json
    try {
      value = JSON.parse(value);
    } catch (e) {}

    // string
    return value;
  },

  toArray = function (arrayLike) {
    return Array.prototype.slice.call(arrayLike);
  };

  glue.reset = function () {
    callbacks = {};
    invokedNodes = [];
  };

  window.glue = glue;
})(this);
<commit_msg>Adds some AMD love.<commit_after>/* global define */
(function (window, undefined) {
  var
    // aliases
    document = window.document,
    // constants
    PREFIX = "data-glue",
    R_ATTR_PREFIX = new RegExp("^" + PREFIX + "-"),
    R_BOOL = /^(true|false)$/,
    // state
    callbacks = {},
    invokedNodes = [],

  glue = function (name, callback) {
    if (callback !== undefined) {
      callbacks[name] = callback;
    }

    if (callbacks[name] !== undefined) {
      invokeNodes(findNodes(name), callbacks[name]);
    }
  },

  findNodes = (function () {
    var find;

    if (document.querySelectorAll !== undefined) {
      find = function (name) {
        return toArray(document.querySelectorAll("[" + PREFIX + "=" + name + "]"));
      };
    } else {
      find = function walk(name, root) {
        var child, i, nodes;

        if (root === undefined) {
          return walk(name, document.body);
        }

        nodes = [];

        for (i = 0; child = root.children[i++];) {
          if (child.nodeType === 1) {
            if (child.hasAttribute(PREFIX)) {
              nodes.push(child);
            }

            if (child.children.length > 0) {
              nodes = nodes.concat(walk(name, child));
            }
          }
        }

        return nodes;
      };
    }

    return function (name) {
      var k, invokedNode, node,
          i = 0,
          nodes = find(name),
          uninvokedNodes = [];

      outer: for (;node = nodes[i++];) {
        inner: for (k = 0;invokedNode = invokedNodes[k++];) {
          if (invokedNode === node) {
            continue outer;
          }
        }

        uninvokedNodes.push(node);
      }

      return uninvokedNodes;
    };
  })(),

  findAttributes = function (node) {
    var attr, name,
        attrs = {},
        i = 0;

    for (;attr = node.attributes[i++];) {
      name = attr.name.split(R_ATTR_PREFIX)[1];

      if (name !== undefined) {
        attrs[name] = attr.nodeValue;
      }
    }

    return attrs;
  },

  invokeNodes = function (nodes, callback) {
    var node,
        i = 0;

    for (;node = nodes[i++];) {
      invokeNode(node, callback);
    }
  },

  invokeNode = function (node, callback) {
    var attrs = findAttributes(node),
        settings = {},
        key;

    for (key in attrs) {
      if (attrs.hasOwnProperty(key)) {
        settings[key] = parseAttr(attrs[key]);
      }
    }

    callback.call(node, settings);
    invokedNodes.push(node);
  },

  parseAttr = function (value) {
    // number
    if(/^\-?([0-9]+(\.[0-9]+)?|Infinity)$/.test(value)) {
      return Number(value);
    }
    // boolean
    else if (value.match(R_BOOL)) {
      return (value === "true") ? true : false;
    }

    // json
    try {
      value = JSON.parse(value);
    } catch (e) {}

    // string
    return value;
  },

  toArray = function (arrayLike) {
    return Array.prototype.slice.call(arrayLike);
  };

  glue.reset = function () {
    callbacks = {};
    invokedNodes = [];
  };

  if (typeof define === "function" && typeof define.amd === "object" && define.amd) {
    define(function () {
      return glue;
    });
  } else {
    window.glue = glue;
  }
})(this);
<|endoftext|>


<commit_before>/* this javascript file should be included by all quotient pages */

if(typeof(Quotient) == "undefined") {
    Quotient = {};
}

if(typeof(Quotient.Common) == "undefined") {
    Quotient.Common = {};
}

Quotient.Common.Util = Nevow.Athena.Widget.subclass();

Quotient.Common.Util.findPosX = function(obj) {
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

Quotient.Common.Util.findPosY = function(obj) {
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

Quotient.Common.Util.stripLeadingTrailingWS = function(str) {
    return str.replace(/^\s+/, "").replace(/\s+$/, "");
}

Quotient.Common.Util.startswith = function(needle, haystack) {
    return haystack.toLowerCase().slice(0, needle.length) == needle.toLowerCase();
}

Quotient.Common.Util.normalizeTag = function(tag) {
    return Quotient.Common.Util.stripLeadingTrailingWS(tag).replace(/\s{2,}/, " ").toLowerCase();
}

Quotient.Common.Util.resizeIFrame = function(frame) {
    // Code is from http://www.ozoneasylum.com/9671&latestPost=true
    try {
        innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
        objToResize = (frame.style) ? frame.style : frame;
        objToResize.height = innerDoc.body.scrollHeight + 20 + 'px';
        objToResize.width = innerDoc.body.scrollWidth + 5 + 'px';
    }
    catch (e) {}
}

Quotient.Common.AddPerson = Nevow.Athena.Widget.subclass();

Quotient.Common.AddPerson.method('replaceAddPersonHTMLWithPersonHTML',
    function(self, identifier) {
        var D = self.callRemote('getPersonHTML');
        D.addCallback(function(HTML) {
            var personIdentifiers = Nevow.Athena.NodesByAttribute(
                                      document.documentElement, 'class', 'person-identifier');
            var e = null;
            for(var i = 0; i < personIdentifiers.length; i++) {
                e = personIdentifiers[i];
                if(e.firstChild.nodeValue == identifier) {
                    e.parentNode.innerHTML = HTML;
                }
            }
        });
    });

Quotient.Common.SenderPerson = Nevow.Athena.Widget.subclass();

Quotient.Common.SenderPerson.method('showAddPerson',
    function(self, node, event) {
        self.node = node;
        self.body = document.getElementsByTagName("body")[0];

        var name = self.nodeByAttribute('class', 'person-name').firstChild.nodeValue;
        var parts = new Object();

        parts["firstname"] = '';
        parts["lastname"] = '';

        if(name.match(/\s+/)) {
            var split = name.split(/\s+/, 2);
            parts["firstname"] = split[0];
            parts["lastname"]  = split[1];
        } else if(name.match(/@/)) {
            parts["firstname"] = name.split(/@/, 2)[0];
        } else {
            parts["firstname"] = name;
        }

        parts["nickname"] = parts["firstname"];

        self.email = self.nodeByAttribute('class', 'person-identifier').firstChild.nodeValue;
        parts["email"] = self.email;

        self.addPersonFragment = MochiKit.DOM.getElement("add-person-fragment");

        self.addPersonFragment.style.top = event.pageY + 'px';
        self.addPersonFragment.style.left = event.pageX + 25 + 'px';

        self.form = self.addPersonFragment.getElementsByTagName("form")[0];
        self.submitFunction = function() { self.submitForm() };

        self.form.addEventListener("submit", self.submitFunction, true);

        var inputs = Nevow.Athena.NodesByAttribute(self.addPersonFragment, 'type', 'text');

        for(var i = 0; i < inputs.length; i++) {
            if(inputs[i].name == "firstname") {
                inputs[i].focus();
            }
            if(inputs[i].name in parts) {
                inputs[i].value = parts[inputs[i].name];
            } else {
                inputs[i].value = "";
            }
        }

        self.body.onclick = function(_event) {
            if(event.target == _event.target) {
                return false;
            }
            var e = _event.target;
            while(e && e.id != self.addPersonFragment.id) {
                e = e.parentNode;
            }
            if (e) {
                return false;
            }
            self.hideAddPerson();
            self.body.onclick = null;
            return false;
        }
        MochiKit.DOM.showElement(self.addPersonFragment);
    });

Quotient.Common.SenderPerson.method('submitForm',
    function(self) {
        var node = Nevow.Athena.NodeByAttribute(self.addPersonFragment, "class", "add-person");
        Quotient.Common.AddPerson.get(node).replaceAddPersonHTMLWithPersonHTML(self.email);
    });

Quotient.Common.SenderPerson.method('hideAddPerson',
    function(self) {
        MochiKit.DOM.hideElement(self.addPersonFragment);
        self.form.removeEventListener("submit", self.submitFunction, true);
        //self.eventTarget.onclick = function(event) {
        //    self.showAddPerson(self.node, event);
        //    return false;
        //}
    });
<commit_msg>some javascript fixes for add person popup, don't default nickname.<commit_after>/* this javascript file should be included by all quotient pages */

if(typeof(Quotient) == "undefined") {
    Quotient = {};
}

if(typeof(Quotient.Common) == "undefined") {
    Quotient.Common = {};
}

Quotient.Common.Util = Nevow.Athena.Widget.subclass();

Quotient.Common.Util.findPosX = function(obj) {
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

Quotient.Common.Util.findPosY = function(obj) {
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

Quotient.Common.Util.stripLeadingTrailingWS = function(str) {
    return str.replace(/^\s+/, "").replace(/\s+$/, "");
}

Quotient.Common.Util.startswith = function(needle, haystack) {
    return haystack.toLowerCase().slice(0, needle.length) == needle.toLowerCase();
}

Quotient.Common.Util.normalizeTag = function(tag) {
    return Quotient.Common.Util.stripLeadingTrailingWS(tag).replace(/\s{2,}/, " ").toLowerCase();
}

Quotient.Common.Util.resizeIFrame = function(frame) {
    // Code is from http://www.ozoneasylum.com/9671&latestPost=true
    try {
        innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
        objToResize = (frame.style) ? frame.style : frame;
        objToResize.height = innerDoc.body.scrollHeight + 20 + 'px';
        objToResize.width = innerDoc.body.scrollWidth + 5 + 'px';
    }
    catch (e) {}
}

Quotient.Common.AddPerson = Nevow.Athena.Widget.subclass();

Quotient.Common.AddPerson.method('replaceAddPersonHTMLWithPersonHTML',
    function(self, identifier) {
        var D = self.callRemote('getPersonHTML');
        D.addCallback(function(HTML) {
            var personIdentifiers = Nevow.Athena.NodesByAttribute(
                                      document.documentElement, 'class', 'person-identifier');
            var e = null;
            for(var i = 0; i < personIdentifiers.length; i++) {
                e = personIdentifiers[i];
                if(e.firstChild.nodeValue == identifier) {
                    e.parentNode.innerHTML = HTML;
                }
            }
        });
    });

Quotient.Common.SenderPerson = Nevow.Athena.Widget.subclass();

Quotient.Common.SenderPerson.method('showAddPerson',
    function(self, node, event) {
        self.node = node;
        self.body = document.getElementsByTagName("body")[0];

        var name = self.nodeByAttribute('class', 'person-name').firstChild.nodeValue;
        var parts = new Object();

        parts["firstname"] = '';
        parts["lastname"] = '';

        if(name.match(/\s+/)) {
            var split = name.split(/\s+/, 2);
            parts["firstname"] = split[0];
            parts["lastname"]  = split[1];
        } else if(name.match(/@/)) {
            parts["firstname"] = name.split(/@/, 2)[0];
        } else {
            parts["firstname"] = name;
        }

        self.email = self.nodeByAttribute('class', 'person-identifier').firstChild.nodeValue;
        parts["email"] = self.email;

        self.addPersonFragment = MochiKit.DOM.getElement("add-person-fragment");

        self.addPersonFragment.style.top = event.pageY + 'px';
        self.addPersonFragment.style.left = event.pageX + 25 + 'px';

        self.form = self.addPersonFragment.getElementsByTagName("form")[0];
        self.submitFunction = function() { self.submitForm() };

        self.form.addEventListener("submit", self.submitFunction, true);

        var inputs = Nevow.Athena.NodesByAttribute(self.addPersonFragment, 'type', 'text');

        for(var i = 0; i < inputs.length; i++) {
            if(inputs[i].name == "firstname") {
                inputs[i].focus();
            }
            if(inputs[i].name in parts) {
                inputs[i].value = parts[inputs[i].name];
            } else {
                inputs[i].value = "";
            }
        }

        self.eventTarget = event.target.parentNode;

        self.eventTarget.onclick = function() {
            self.body.onclick = null;
            self.hideAddPerson();
            return false
        }

        self.body.onclick = function(_event) {
            if(event.target == _event.target) {
                return false;
            }

            e = _event.target;
            while(e && e.id != self.addPersonFragment.id) {
                e = e.parentNode;
            }
            if (e) {
                return false;
            }
            self.hideAddPerson();
            self.body.onclick = null;
            return false;
        }
        MochiKit.DOM.showElement(self.addPersonFragment);
    });

Quotient.Common.SenderPerson.method('submitForm',
    function(self) {
        var node = Nevow.Athena.NodeByAttribute(self.addPersonFragment, "class", "add-person");
        Quotient.Common.AddPerson.get(node).replaceAddPersonHTMLWithPersonHTML(self.email);
    });

Quotient.Common.SenderPerson.method('hideAddPerson',
    function(self) {
        MochiKit.DOM.hideElement(self.addPersonFragment);
        self.form.removeEventListener("submit", self.submitFunction, true);
        self.eventTarget.onclick = function(event) {
            self.showAddPerson(self.node, event);
            return false;
        }
    });
<|endoftext|>


<commit_before>/*!
 * Start Bootstrap - Agnecy Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Highlight the top nav as scrolling occurs
$('body').scrollspy({
    target: '.navbar-fixed-top'
})

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

$('div.modal').on('show.bs.modal', function() {
	var modal = this;
	var hash = modal.id;
	window.location.hash = hash;
	window.onhashchange = function() {
		if (!location.hash){
			$(modal).modal('hide');
		}
	}
});

$('div.modal').on('hidden.bs.modal', function (e) {
  var modal = this;
	var hash = modal.id;
  var videoIframe= modal.getElementsByTagName("iframe")[0];
  console.log(videoIframe);
    //   $(videoFrame).attr("src", $(videoFrame).attr("src"));
});
<commit_msg>attempt to pause video<commit_after>/*!
 * Start Bootstrap - Agnecy Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Highlight the top nav as scrolling occurs
$('body').scrollspy({
    target: '.navbar-fixed-top'
})

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

$('div.modal').on('show.bs.modal', function() {
	var modal = this;
	var hash = modal.id;
	window.location.hash = hash;
	window.onhashchange = function() {
		if (!location.hash){
			$(modal).modal('hide');
		}
	}
});

$('div.modal').on('hidden.bs.modal', function (e) {
  var modal = this;
	var hash = modal.id;
  var videoIframe= modal.getElementsByTagName("iframe")[0];

  if (typeof someUndeclaredVariable == "undefined") {
      console.log(videoIframe);
         videoIframe.attr("src", videoIframe.attr("src"));
}
});
<|endoftext|>


<commit_before>var app = angular.module('bnw-replies', ['ngRoute']);

app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
	var ctrl = {
		templateUrl: 'feed.html',
		controller: 'Replies'
	}
	$routeProvider.when('/', ctrl)
				  .when('/for/:user', ctrl)
				  .when('/top', {
				  	templateUrl: 'feed.html',
				  	controller: 'Top'
				  });

	$locationProvider.html5Mode(true);
}]);

app.directive('autoscroll', function ($timeout) {
	return function (scope, elem, attrs) {
		var height = elem[0].scrollHeight;

		scope.$watch(attrs.autoscroll, function (n, o) {
			$timeout(function () {
				var change = elem[0].scrollHeight - height;
				if ((n || []).length - (o || []).length == 1) {
					elem[0].scrollTop += change;
				}
				height = elem[0].scrollHeight;
			});
		}, true);
	};
});

app.directive('infinitescroll', function () {
	return function (scope, elem, attrs) {
		elem.on('scroll', function () {
			if (elem[0].scrollHeight - elem[0].scrollTop < screen.height + 150) {
				scope.$apply(attrs.infinitescroll);
			}
		});
	};
});

app.filter('moment', function () {
	return function (date) {
		return moment(date, 'X').fromNow();
	};
});

app.filter('lines', function () {
	return function (text) {
		return text.replace(/\n+/g, '\n').replace(/(^\n|\n$)/g, '').split('\n');
	};
});

app.controller('Top', function ($scope, $http) {
	$scope.load = function() {};
	$scope.top = true;

	$http.get('/api/top').success(function (replies) {
		$scope.replies = replies;
	});
});

app.controller('Replies', function ($scope, $http, $routeParams, $timeout) {
	$scope.user = $routeParams.user;
	$scope.replies = [];

	var addReply = function (reply) {
		$timeout(function () {
			$scope.replies.unshift(reply);
		});
	};

	var initWS = function () {
		var ws = new WebSocket('wss://bnw.im/comments/ws');
		ws.onmessage = function (event) {
			var reply = JSON.parse(event.data);
			if (!$scope.user) return addReply(reply);
			if ((reply.text.match(/\@([\-0-9A-z]+)/ig) || []).indexOf('@' + $scope.user) > -1) {
				addReply(reply);
			} else if (!reply.replyto) {
				$http.get('https://bnw.im/api/show?message=' + reply.id.split('/')[0]).success(function (res) {
					if (res.messages[0].user == $scope.user) addReply(reply);
				});
			}
		};
		ws.onclose = initWS;
	};
	initWS();

	$scope.load = function () {
		if ($scope.loading) return;

		$scope.loading = true;

		$http.get('/comments' + (($scope.user) ? '/' + $scope.user : '') + '?skip='+$scope.replies.length)
		.success(function (replies) {
			if (!replies.length) {
				$scope.finish = true;
			} else {
				$scope.replies = $scope.replies.concat(replies);
			}
		}).then(function () {
			$scope.loading = false;
		});
	};
	$scope.load();
});

app.controller('For', ['$scope', '$location', function($scope, $location) {
	$scope.name = localStorage['last'] || 'anonymous';
	$scope.for = function (name) {
		localStorage['last'] = name;
		$location.url('/for/' + name);
	};
}]);

app.controller('Webui', ['$scope', '$rootScope', function($scope, $rootScope) {
	$scope.webuilist = [
		{name: 'meow', url: 'https://meow.bnw.im'},
		{name: '6nw', url: 'http://6nw.im'},
		{name: 'default', url: 'https://bnw.im'}
	];
	$scope.update = function () {
		localStorage['webui'] = $scope.webui;
		$rootScope.webuiurl = $scope.webuilist[$scope.webui].url;
	};
	$scope.webui = localStorage['webui'] || '0';
	$scope.update();
}]);
<commit_msg>6nw - use https<commit_after>var app = angular.module('bnw-replies', ['ngRoute']);

app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
	var ctrl = {
		templateUrl: 'feed.html',
		controller: 'Replies'
	}
	$routeProvider.when('/', ctrl)
				  .when('/for/:user', ctrl)
				  .when('/top', {
				  	templateUrl: 'feed.html',
				  	controller: 'Top'
				  });

	$locationProvider.html5Mode(true);
}]);

app.directive('autoscroll', function ($timeout) {
	return function (scope, elem, attrs) {
		var height = elem[0].scrollHeight;

		scope.$watch(attrs.autoscroll, function (n, o) {
			$timeout(function () {
				var change = elem[0].scrollHeight - height;
				if ((n || []).length - (o || []).length == 1) {
					elem[0].scrollTop += change;
				}
				height = elem[0].scrollHeight;
			});
		}, true);
	};
});

app.directive('infinitescroll', function () {
	return function (scope, elem, attrs) {
		elem.on('scroll', function () {
			if (elem[0].scrollHeight - elem[0].scrollTop < screen.height + 150) {
				scope.$apply(attrs.infinitescroll);
			}
		});
	};
});

app.filter('moment', function () {
	return function (date) {
		return moment(date, 'X').fromNow();
	};
});

app.filter('lines', function () {
	return function (text) {
		return text.replace(/\n+/g, '\n').replace(/(^\n|\n$)/g, '').split('\n');
	};
});

app.controller('Top', function ($scope, $http) {
	$scope.load = function() {};
	$scope.top = true;

	$http.get('/api/top').success(function (replies) {
		$scope.replies = replies;
	});
});

app.controller('Replies', function ($scope, $http, $routeParams, $timeout) {
	$scope.user = $routeParams.user;
	$scope.replies = [];

	var addReply = function (reply) {
		$timeout(function () {
			$scope.replies.unshift(reply);
		});
	};

	var initWS = function () {
		var ws = new WebSocket('wss://bnw.im/comments/ws');
		ws.onmessage = function (event) {
			var reply = JSON.parse(event.data);
			if (!$scope.user) return addReply(reply);
			if ((reply.text.match(/\@([\-0-9A-z]+)/ig) || []).indexOf('@' + $scope.user) > -1) {
				addReply(reply);
			} else if (!reply.replyto) {
				$http.get('https://bnw.im/api/show?message=' + reply.id.split('/')[0]).success(function (res) {
					if (res.messages[0].user == $scope.user) addReply(reply);
				});
			}
		};
		ws.onclose = initWS;
	};
	initWS();

	$scope.load = function () {
		if ($scope.loading) return;

		$scope.loading = true;

		$http.get('/comments' + (($scope.user) ? '/' + $scope.user : '') + '?skip='+$scope.replies.length)
		.success(function (replies) {
			if (!replies.length) {
				$scope.finish = true;
			} else {
				$scope.replies = $scope.replies.concat(replies);
			}
		}).then(function () {
			$scope.loading = false;
		});
	};
	$scope.load();
});

app.controller('For', ['$scope', '$location', function($scope, $location) {
	$scope.name = localStorage['last'] || 'anonymous';
	$scope.for = function (name) {
		localStorage['last'] = name;
		$location.url('/for/' + name);
	};
}]);

app.controller('Webui', ['$scope', '$rootScope', function($scope, $rootScope) {
	$scope.webuilist = [
		{name: 'meow', url: 'https://meow.bnw.im'},
		{name: '6nw', url: 'https://6nw.im'},
		{name: 'default', url: 'https://bnw.im'}
	];
	$scope.update = function () {
		localStorage['webui'] = $scope.webui;
		$rootScope.webuiurl = $scope.webuilist[$scope.webui].url;
	};
	$scope.webui = localStorage['webui'] || '0';
	$scope.update();
}]);
<|endoftext|>


<commit_before>/**
 * Created by Mihail on 11/30/2016.
 */
'use strict';

/* @flow */

import { EventEmitter } from 'fbemitter';
import { List } from 'immutable';
import schema from '../schema';
import ApiCtrl from '../../api/api-controller';

let data: List<Object>;
const emitter = new EventEmitter();

const CRUDStore = {
	init(storage) {
		if (!storage) {
			let initialRecord = {};
			schema.forEach(item => initialRecord[item.id] = item.sample);
			data = List([initialRecord]);
		} else {
			data = List(storage);
		}
	},

	getData(): List<Object> {
		return data;
	},

	getSchema(): Array<Object> {
		return schema;
	},

	addRecord(newRecord: Object, commit: boolean = true) {
		if (commit) {
			ApiCtrl.createPlayerPromise(newRecord.name,
										newRecord.email,
										newRecord.password,
										newRecord.balance,
										newRecord.wins).then((d) => {
				console.log('Added successfully: ', d);
			});
		}
		emitter.emit('change');
	},

	setData(newData: List<Object>, commit: boolean = true) {
		data = newData;
		if (commit && 'localStorage' in window) {
			localStorage.setItem('data', JSON.stringify(newData));
		}
		emitter.emit('change');
	},

	addListener(eventType: string, fn: Function) {
		emitter.addListener(eventType, fn);
	},

	getCount(): number {
		return data.count();
	},

	getRecord(recordId: number): ?Object {
		return data.get(recordId);
	},

};

export default CRUDStore<commit_msg>Added updating of the table with the new added record.<commit_after>/**
 * Created by Mihail on 11/30/2016.
 */
'use strict';

/* @flow */

import { EventEmitter } from 'fbemitter';
import { List } from 'immutable';
import schema from '../schema';
import ApiCtrl from '../../api/api-controller';

let data: List<Object>;
const emitter = new EventEmitter();

const CRUDStore = {
	init(storage) {
		if (!storage) {
			let initialRecord = {};
			schema.forEach(item => initialRecord[item.id] = item.sample);
			data = List([initialRecord]);
		} else {
			data = List(storage);
		}
	},

	getData(): List<Object> {
		return data;
	},

	getSchema(): Array<Object> {
		return schema;
	},

	addRecord(newRecord: Object, commit: boolean = true) {
		if (commit) {
			ApiCtrl.createPlayerPromise(newRecord.name,
										newRecord.email,
										newRecord.password,
										newRecord.balance,
										newRecord.wins).then((e) => {
				console.log(e);
				if (e.isExisted){
					console.log('>>> Existing user - show dialog message.');
					return false;
				}

				if (!e.token) {
					console.log('>>> Creating failed.');
					return false;
				}

				// data.unshift(newRecord);
				CRUDStore.setData(CRUDStore.getData().unshift(newRecord));
				emitter.emit('change');

			});
		}
	},

	setData(newData: List<Object>, commit: boolean = true) {
		data = newData;
		/*if (commit && 'localStorage' in window) {
			localStorage.setItem('data', JSON.stringify(newData));
		}*/
		emitter.emit('change');
	},

	addListener(eventType: string, fn: Function) {
		emitter.addListener(eventType, fn);
	},

	getCount(): number {
		return data.count();
	},

	getRecord(recordId: number): ?Object {
		return data.get(recordId);
	},

};

export default CRUDStore<|endoftext|>


<commit_before>const github = require('./github');
const parseGithubUrl = require('./parseGithubUrl');
const { execSync } = require('child_process');

const generateGithubUrl = () => {
  return execSync(`git fetch origin pull/${id}/head:`, {
    encoding: 'utf8'
  }).trim();
};

const fetch = id => {
  return github.pullRequests
    .get({
      owner: 'facebook',
      repo: 'react',
      number: id
    })
    .then(res => {
      const branch = res.data.head.ref;
      execSync(
        `git fetch origin pull/${id}/head:${branch} && git checkout ${branch}`
      );
    });
};

module.exports = fetch;
<commit_msg>stop hard coding facebook<commit_after>const github = require('./github');
const parseGithubUrl = require('./parseGithubUrl');
const { execSync } = require('child_process');

const generateGithubUrl = () => {
  return execSync(`git fetch origin pull/${id}/head:`, {
    encoding: 'utf8'
  }).trim();
};

const fetch = id => {
  return github.pullRequests
    .get({
      owner: parseGithubUrl.owner,
      repo: parseGithubUrl.repo
      number: id
    })
    .then(res => {
      const branch = res.data.head.ref;
      execSync(
        `git fetch origin pull/${id}/head:${branch} && git checkout ${branch}`
      );
    });
};

module.exports = fetch;
<|endoftext|>


<commit_before>frappe.provide("frappe.search");

frappe.search.SearchDialog = class {
	constructor(opts) {
		$.extend(this, opts);
		this.make();
	}

	make() {
		this.search_dialog = new frappe.ui.Dialog({
			minimizable: true,
			size: "large"
		});
		this.set_header();
		this.$wrapper = $(this.search_dialog.$wrapper).addClass(
			"search-dialog"
		);
		this.$body = $(this.search_dialog.body);
		this.$input = this.$wrapper.find(".search-input");
		this.setup();
	}

	set_header() {
		this.search_dialog.header
			.addClass("search-header")
			.find(".title-section")
			.html(
				`

					<input type="text" class="form-control search-input">

					${frappe.utils.icon("search")}
				`
			);
	}

	setup() {
		this.modal_state = 0;
		this.current_keyword = "";
		this.more_count = 20;
		this.full_lists = {};
		this.nav_lists = {};
		this.init_search_objects();
		this.bind_input();
		this.bind_events();
	}

	init_search_objects() {
		this.searches = {
			global_search: {
				input_placeholder: __("Search"),
				empty_state_text: __("Search for anything"),
				no_results_status: () => __("No Results found"),
				get_results: (keywords, callback) => {
					let start = 0,
						limit = 1000;
					let results = frappe.search.utils.get_nav_results(keywords);
					frappe.search.utils
						.get_global_results(keywords, start, limit)
						.then(
							global_results => {
								results = results.concat(global_results);
								callback(results, keywords);
							},
							err => {
								// eslint-disable-next-line no-console
								console.error(err);
							}
						);
				}
			},
			tags: {
				input_placeholder: __("Search"),
				empty_state_text: __("Search for anything"),
				no_results_status: keyword =>
					"
" +
					__("No documents found tagged with {0}", [keyword]) +
					"
",
				get_results: (keywords, callback) => {
					var results = frappe.search.utils.get_nav_results(keywords);
					frappe.tags.utils.get_tag_results(keywords).then(
						global_results => {
							results = results.concat(global_results);
							callback(results, keywords);
						},
						err => {
							// eslint-disable-next-line no-console
							console.error(err);
						}
					);
				}
			}
		};
	}

	update($r) {
		this.$wrapper.find(".loading-state").addClass("hide");
		this.$body.append($r);
		if (this.$body.find(".search-results").length > 1) {
			this.$body
				.find(".search-results")
				.first()
				.addClass("hide");
			$r.removeClass("hide");
			this.$body
				.find(".search-results")
				.first()
				.remove();
		} else {
			$r.removeClass("hide");
		}
	}

	put_placeholder(status_text) {
		var $placeholder = $(`

${status_text}

`);
		this.update($placeholder);
	}

	bind_input() {
		this.$input.on("input", e => {
			const $el = $(e.currentTarget);
			clearTimeout($el.data("timeout"));
			$el.data(
				"timeout",
				setTimeout(() => {
					if (this.$input.val() === this.current_keyword) return;
					let keywords = this.$input.val();
					if (keywords.length > 1) {
						this.get_results(keywords);
					} else {
						this.current_keyword = "";
						this.put_placeholder(this.search.empty_state_text);
					}
				}, 300)
			);
		});
	}

	bind_events() {
		// Sidebar
		this.$body.on("click", ".list-link", e => {
			const $link = $(e.currentTarget);
			this.$body
				.find(".search-sidebar")
				.find(".list-link")
				.removeClass("active selected");
			$link.addClass("active selected");
			const type = $link.attr("data-category");
			this.$body
				.find(".results-area")
				.empty()
				.html(this.full_lists[type]);
			this.$body
				.find(".module-section-link")
				.first()
				.focus();
		});

		// Summary more links
		this.$body.on("click", ".section-more", e => {
			const $section = $(e.currentTarget);
			const type = $section.attr("data-category");
			this.$body
				.find(".search-sidebar")
				.find('*[data-category="' + type + '"]')
				.trigger("click");
		});

		// Back-links (mobile-view)
		this.$body.on("click", ".all-results-link", () => {
			this.$body
				.find(".search-sidebar")
				.find('*[data-category="All Results"]')
				.trigger("click");
		});

		// Full list more links
		this.$body.on("click", ".list-more", e => {
			const $el = $(e.currentTarget);
			const type = $el.attr("data-category");
			const fetch_type = $el.attr("data-search");
			var current_count = this.$body.find(".result").length;
			if (fetch_type === "Global") {
				frappe.search.utils
					.get_global_results(
						this.current_keyword,
						current_count,
						this.more_count,
						type
					)
					.then(
						doctype_results => {
							doctype_results.length &&
								this.add_more_results(doctype_results);
						},
						err => {
							// eslint-disable-next-line no-console
							console.error(err);
						}
					);
			} else {
				let results = this.nav_lists[type].slice(0, this.more_count);
				this.nav_lists[type].splice(0, this.more_count);
				this.add_more_results([{ title: type, results: results }]);
			}
		});

		// Switch to global search link
		this.$body.on("click", ".switch-to-global-search", () => {
			this.search = this.searches["global_search"];
			this.$input.attr("placeholder", this.search.input_placeholder);
			this.put_placeholder(this.search.empty_state_text);
			this.get_results(this.current_keyword);
		});
	}

	init_search(keywords, search_type) {
		this.search = this.searches[search_type];
		this.$input.attr("placeholder", this.search.input_placeholder);
		this.put_placeholder(this.search.empty_state_text);
		this.get_results(keywords);
		this.search_dialog.show();
		this.$input.val(keywords);
		setTimeout(() => this.$input.select(), 500);
	}

	get_results(keywords) {
		this.current_keyword = keywords;
		if (this.$body.find(".empty-state").length > 0) {
			this.put_placeholder(__("Searching ..."));
		} else {
			this.$wrapper.find(".loading-state").removeClass("hide");
		}

		if (this.current_keyword.charAt(0) === "#") {
			this.search = this.searches["tags"];
		} else {
			this.search = this.searches["global_search"];
		}

		this.search.get_results(keywords, this.parse_results.bind(this));
	}

	parse_results(result_sets, keyword) {
		result_sets = result_sets.filter(function(set) {
			return set.results.length > 0;
		});
		if (result_sets.length > 0) {
			this.render_data(result_sets);
		} else {
			this.put_placeholder(this.search.no_results_status(keyword));
		}
	}

	render_data(result_sets) {
		let $search_results = $(frappe.render_template("search")).addClass(
			"hide"
		);
		let $sidebar = $search_results.find(".search-sidebar").empty();
		let sidebar_item_html =
			'
' +
			'{1}
';

		this.modal_state = 0;
		this.full_lists = {
			"All Results": $('

')
		};
		this.nav_lists = {};

		result_sets.forEach(set => {
			$sidebar.append($(__(sidebar_item_html, [set.title, __(set.title)])));
			this.add_section_to_summary(set.title, set.results);
			this.full_lists[set.title] = this.render_full_list(
				set.title,
				set.results,
				set.fetch_type
			);
		});

		if (result_sets.length > 1) {
			$sidebar.prepend($(__(sidebar_item_html, ['All Results', __('All Results')])));
		}

		this.update($search_results.clone());
		this.$body
			.find(".list-link")
			.first()
			.trigger("click");
	}

	render_full_list(type, results, fetch_type) {
		let max_length = 20;

		let $results_list = $(`

 ${ __(type) }

`);

		results.slice(0, max_length).forEach(result => {
			$results_list
				.find(".result-body")
				.append(this.render_result(type, result));
		});

		if (results.length > 0) {
			if (fetch_type === "Nav") this.nav_lists[type] = results;

			if (results.length > max_length) {
				$(`
						${__("More")}
				`).appendTo($results_list.find(".result-body"));
			}
		}
		return $results_list;
	}

	add_section_to_summary(type, results) {
		let section_length = 4;
		let more_html = "";
		let get_result_html = result => this.render_result(type, result);

		if (results.length > section_length) {
			more_html = `

				${__("More")}

`;
		}

		let $result_section = $(`

${__(type)}

				${more_html}

`).appendTo(this.full_lists["All Results"]);

		$result_section
			.find(".result-body")
			.prepend(results.slice(0, section_length).map(get_result_html));
	}

	get_link(result) {
		let link = "";
		if (result.route) {
			link = `href="#${result.route.join("/")}"`;
		} else if (result.data_path) {
			link = `data-path=${result.data_path}"`;
		}
		return link;
	}

	render_result(type, result) {
		let image_html = "";
		if (result.image !== undefined) {
			let avatar_html = frappe.get_avatar(
				"avatar-medium",
				result.label,
				result.image
			);
			image_html = `

					${avatar_html}

			`;
		}

		let link_html = `${result.label}`;
		let title_html = !result.description
			? link_html
			: `${link_html}
 ${
				result.description
			}
`;

		let result_text = `

			${title_html}

`;

		let $result = $(`

			${image_html}
			${result_text}
			${result.subtypes || ""}

`);

		if (!result.description) {
			this.handle_result_click(result, $result);
		}

		return $result;
	}

	handle_result_click(result, $result) {
		if (result.route_options) {
			frappe.route_options = result.route_options;
		}
		$result.on("click", () => {
			// this.toggle_minimize();
			if (result.onclick) {
				result.onclick(result.match);
			} else {
				var previous_hash = window.location.hash;
				frappe.set_route(result.route);
				// hashchange didn't fire!
				if (window.location.hash == previous_hash) {
					frappe.router.route();
				}
			}
		});
	}

	add_more_results(results_set) {
		let more_results = $('

');
		if (results_set[0].results) {
			results_set[0].results.forEach(result => {
				more_results.append(
					this.render_result(results_set[0].title, result)
				);
			});
		}
		this.$body.find(".list-more").before(more_results);

		if (results_set[0].results.length < this.more_count) {
			// hide more button and add a result count
			this.$body.find(".list-more").hide();
			let no_of_results = this.$body.find(".result").length;
			let no_of_results_cue = $(
				'
' +
					no_of_results +
					" results found
"
			);
			this.$body.find(".more-results:last").append(no_of_results_cue);
		}
		this.$body.find(".more-results.last").slideDown(200, function() {});
	}
};
<commit_msg>fix: old style links in global search<commit_after>frappe.provide("frappe.search");

frappe.search.SearchDialog = class {
	constructor(opts) {
		$.extend(this, opts);
		this.make();
	}

	make() {
		this.search_dialog = new frappe.ui.Dialog({
			minimizable: true,
			size: "large"
		});
		this.set_header();
		this.$wrapper = $(this.search_dialog.$wrapper).addClass(
			"search-dialog"
		);
		this.$body = $(this.search_dialog.body);
		this.$input = this.$wrapper.find(".search-input");
		this.setup();
	}

	set_header() {
		this.search_dialog.header
			.addClass("search-header")
			.find(".title-section")
			.html(
				`

					<input type="text" class="form-control search-input">

					${frappe.utils.icon("search")}
				`
			);
	}

	setup() {
		this.modal_state = 0;
		this.current_keyword = "";
		this.more_count = 20;
		this.full_lists = {};
		this.nav_lists = {};
		this.init_search_objects();
		this.bind_input();
		this.bind_events();
	}

	init_search_objects() {
		this.searches = {
			global_search: {
				input_placeholder: __("Search"),
				empty_state_text: __("Search for anything"),
				no_results_status: () => __("No Results found"),
				get_results: (keywords, callback) => {
					let start = 0,
						limit = 1000;
					let results = frappe.search.utils.get_nav_results(keywords);
					frappe.search.utils
						.get_global_results(keywords, start, limit)
						.then(
							global_results => {
								results = results.concat(global_results);
								callback(results, keywords);
							},
							err => {
								// eslint-disable-next-line no-console
								console.error(err);
							}
						);
				}
			},
			tags: {
				input_placeholder: __("Search"),
				empty_state_text: __("Search for anything"),
				no_results_status: keyword =>
					"
" +
					__("No documents found tagged with {0}", [keyword]) +
					"
",
				get_results: (keywords, callback) => {
					var results = frappe.search.utils.get_nav_results(keywords);
					frappe.tags.utils.get_tag_results(keywords).then(
						global_results => {
							results = results.concat(global_results);
							callback(results, keywords);
						},
						err => {
							// eslint-disable-next-line no-console
							console.error(err);
						}
					);
				}
			}
		};
	}

	update($r) {
		this.$wrapper.find(".loading-state").addClass("hide");
		this.$body.append($r);
		if (this.$body.find(".search-results").length > 1) {
			this.$body
				.find(".search-results")
				.first()
				.addClass("hide");
			$r.removeClass("hide");
			this.$body
				.find(".search-results")
				.first()
				.remove();
		} else {
			$r.removeClass("hide");
		}
	}

	put_placeholder(status_text) {
		var $placeholder = $(`

${status_text}

`);
		this.update($placeholder);
	}

	bind_input() {
		this.$input.on("input", e => {
			const $el = $(e.currentTarget);
			clearTimeout($el.data("timeout"));
			$el.data(
				"timeout",
				setTimeout(() => {
					if (this.$input.val() === this.current_keyword) return;
					let keywords = this.$input.val();
					if (keywords.length > 1) {
						this.get_results(keywords);
					} else {
						this.current_keyword = "";
						this.put_placeholder(this.search.empty_state_text);
					}
				}, 300)
			);
		});
	}

	bind_events() {
		// Sidebar
		this.$body.on("click", ".list-link", e => {
			const $link = $(e.currentTarget);
			this.$body
				.find(".search-sidebar")
				.find(".list-link")
				.removeClass("active selected");
			$link.addClass("active selected");
			const type = $link.attr("data-category");
			this.$body
				.find(".results-area")
				.empty()
				.html(this.full_lists[type]);
			this.$body
				.find(".module-section-link")
				.first()
				.focus();
		});

		// Summary more links
		this.$body.on("click", ".section-more", e => {
			const $section = $(e.currentTarget);
			const type = $section.attr("data-category");
			this.$body
				.find(".search-sidebar")
				.find('*[data-category="' + type + '"]')
				.trigger("click");
		});

		// Back-links (mobile-view)
		this.$body.on("click", ".all-results-link", () => {
			this.$body
				.find(".search-sidebar")
				.find('*[data-category="All Results"]')
				.trigger("click");
		});

		// Full list more links
		this.$body.on("click", ".list-more", e => {
			const $el = $(e.currentTarget);
			const type = $el.attr("data-category");
			const fetch_type = $el.attr("data-search");
			var current_count = this.$body.find(".result").length;
			if (fetch_type === "Global") {
				frappe.search.utils
					.get_global_results(
						this.current_keyword,
						current_count,
						this.more_count,
						type
					)
					.then(
						doctype_results => {
							doctype_results.length &&
								this.add_more_results(doctype_results);
						},
						err => {
							// eslint-disable-next-line no-console
							console.error(err);
						}
					);
			} else {
				let results = this.nav_lists[type].slice(0, this.more_count);
				this.nav_lists[type].splice(0, this.more_count);
				this.add_more_results([{ title: type, results: results }]);
			}
		});

		// Switch to global search link
		this.$body.on("click", ".switch-to-global-search", () => {
			this.search = this.searches["global_search"];
			this.$input.attr("placeholder", this.search.input_placeholder);
			this.put_placeholder(this.search.empty_state_text);
			this.get_results(this.current_keyword);
		});
	}

	init_search(keywords, search_type) {
		this.search = this.searches[search_type];
		this.$input.attr("placeholder", this.search.input_placeholder);
		this.put_placeholder(this.search.empty_state_text);
		this.get_results(keywords);
		this.search_dialog.show();
		this.$input.val(keywords);
		setTimeout(() => this.$input.select(), 500);
	}

	get_results(keywords) {
		this.current_keyword = keywords;
		if (this.$body.find(".empty-state").length > 0) {
			this.put_placeholder(__("Searching ..."));
		} else {
			this.$wrapper.find(".loading-state").removeClass("hide");
		}

		if (this.current_keyword.charAt(0) === "#") {
			this.search = this.searches["tags"];
		} else {
			this.search = this.searches["global_search"];
		}

		this.search.get_results(keywords, this.parse_results.bind(this));
	}

	parse_results(result_sets, keyword) {
		result_sets = result_sets.filter(function(set) {
			return set.results.length > 0;
		});
		if (result_sets.length > 0) {
			this.render_data(result_sets);
		} else {
			this.put_placeholder(this.search.no_results_status(keyword));
		}
	}

	render_data(result_sets) {
		let $search_results = $(frappe.render_template("search")).addClass(
			"hide"
		);
		let $sidebar = $search_results.find(".search-sidebar").empty();
		let sidebar_item_html =
			'
' +
			'{1}
';

		this.modal_state = 0;
		this.full_lists = {
			"All Results": $('

')
		};
		this.nav_lists = {};

		result_sets.forEach(set => {
			$sidebar.append($(__(sidebar_item_html, [set.title, __(set.title)])));
			this.add_section_to_summary(set.title, set.results);
			this.full_lists[set.title] = this.render_full_list(
				set.title,
				set.results,
				set.fetch_type
			);
		});

		if (result_sets.length > 1) {
			$sidebar.prepend($(__(sidebar_item_html, ['All Results', __('All Results')])));
		}

		this.update($search_results.clone());
		this.$body
			.find(".list-link")
			.first()
			.trigger("click");
	}

	render_full_list(type, results, fetch_type) {
		let max_length = 20;

		let $results_list = $(`

 ${ __(type) }

`);

		results.slice(0, max_length).forEach(result => {
			$results_list
				.find(".result-body")
				.append(this.render_result(type, result));
		});

		if (results.length > 0) {
			if (fetch_type === "Nav") this.nav_lists[type] = results;

			if (results.length > max_length) {
				$(`
						${__("More")}
				`).appendTo($results_list.find(".result-body"));
			}
		}
		return $results_list;
	}

	add_section_to_summary(type, results) {
		let section_length = 4;
		let more_html = "";
		let get_result_html = result => this.render_result(type, result);

		if (results.length > section_length) {
			more_html = `

				${__("More")}

`;
		}

		let $result_section = $(`

${__(type)}

				${more_html}

`).appendTo(this.full_lists["All Results"]);

		$result_section
			.find(".result-body")
			.prepend(results.slice(0, section_length).map(get_result_html));
	}

	get_link(result) {
		let link = "";
		if (result.route) {
			link = `href="/app/${result.route.join("/")}"`;
		} else if (result.data_path) {
			link = `data-path=${result.data_path}"`;
		}
		return link;
	}

	render_result(type, result) {
		let image_html = "";
		if (result.image !== undefined) {
			let avatar_html = frappe.get_avatar(
				"avatar-medium",
				result.label,
				result.image
			);
			image_html = `

					${avatar_html}

			`;
		}

		let link_html = `${result.label}`;
		let title_html = !result.description
			? link_html
			: `${link_html}
 ${
				result.description
			}
`;

		let result_text = `

			${title_html}

`;

		let $result = $(`

			${image_html}
			${result_text}
			${result.subtypes || ""}

`);

		if (!result.description) {
			this.handle_result_click(result, $result);
		}

		return $result;
	}

	handle_result_click(result, $result) {
		if (result.route_options) {
			frappe.route_options = result.route_options;
		}
		$result.on("click", () => {
			// this.toggle_minimize();
			if (result.onclick) {
				result.onclick(result.match);
			} else {
				var previous_hash = window.location.hash;
				frappe.set_route(result.route);
				// hashchange didn't fire!
				if (window.location.hash == previous_hash) {
					frappe.router.route();
				}
			}
		});
	}

	add_more_results(results_set) {
		let more_results = $('

');
		if (results_set[0].results) {
			results_set[0].results.forEach(result => {
				more_results.append(
					this.render_result(results_set[0].title, result)
				);
			});
		}
		this.$body.find(".list-more").before(more_results);

		if (results_set[0].results.length < this.more_count) {
			// hide more button and add a result count
			this.$body.find(".list-more").hide();
			let no_of_results = this.$body.find(".result").length;
			let no_of_results_cue = $(
				'
' +
					no_of_results +
					" results found
"
			);
			this.$body.find(".more-results:last").append(no_of_results_cue);
		}
		this.$body.find(".more-results.last").slideDown(200, function() {});
	}
};
<|endoftext|>


<commit_before>const assert = require('yeoman-assert');
const { run } = require('yeoman-test');
const { join } = require('path');

describe('generator-dizmo:sub-typescript', function () {
    const generator = join(__dirname, '../generators/app');
    it('yo @dizmo/dizmo --typescript', () => {
        return run(generator).withOptions({
            'author': 'Dizmo Developer',
            'bundle-id': 'com.dizmo.my_dizmo',
            'email': 'developer@dizmo.com',
            'typescript': true
        }).then(() => {
            assert.file([
                'assets',
                'assets/Icon-dark.svg',
                'assets/Icon.svg',
                'assets/locales',
                'assets/locales/translation.de.json',
                'assets/locales/translation.en.json',
                'assets/Preview.png',
                'babel.config.js',
                'gulp',
                'gulp/miscellanea',
                'gulp/miscellanea/cli-spinner.js',
                'gulp/package.js',
                'gulp/scripts',
                'gulp/scripts/build.js',
                'gulp/scripts/clean.js',
                'gulp/scripts/deploy.js',
                'gulp/scripts/lint.js',
                'gulp/scripts/upload.js',
                'gulp/scripts/watch.js',
                'gulp/tasks',
                'gulp/tasks/build',
                'gulp/tasks/build/assets',
                'gulp/tasks/build/assets/index.js',
                'gulp/tasks/build/assets/watch.js',
                'gulp/tasks/build/dizmo',
                'gulp/tasks/build/dizmo/index.js',
                'gulp/tasks/build/dizmo/watch.js',
                'gulp/tasks/build/help',
                'gulp/tasks/build/help/index.js',
                'gulp/tasks/build/help/watch.js',
                'gulp/tasks/build/index.js',
                'gulp/tasks/build/libraries',
                'gulp/tasks/build/libraries/index.js',
                'gulp/tasks/build/libraries/watch.js',
                'gulp/tasks/build/markup',
                'gulp/tasks/build/markup/index.js',
                'gulp/tasks/build/markup/watch.js',
                'gulp/tasks/build/properties',
                'gulp/tasks/build/properties/index.js',
                'gulp/tasks/build/properties/watch.js',
                'gulp/tasks/build/scripts',
                'gulp/tasks/build/scripts/index.js',
                'gulp/tasks/build/scripts/watch.js',
                'gulp/tasks/build/styles',
                'gulp/tasks/build/styles/index.js',
                'gulp/tasks/build/styles/watch.js',
                'gulp/tasks/build/watch.js',
                'gulp/tasks/clean',
                'gulp/tasks/clean/index.js',
                'gulp/tasks/deploy',
                'gulp/tasks/deploy/index.js',
                'gulp/tasks/deploy/watch.js',
                'gulp/tasks/lint',
                'gulp/tasks/lint/index.js',
                'gulp/tasks/upload',
                'gulp/tasks/upload/index.js',
                'gulp/tasks/watch',
                'gulp/tasks/watch/index.js',
                'gulpfile.js',
                'help',
                'help/en',
                'help/en/help.md',
                'help/en/placeholder-400x275.png',
                '.info.plist',
                'LICENSE',
                '.npmignore',
                'package.json',
                'README.md',
                'src',
                'src/app',
                'src/app/app.ts',
                'src/app/i18n.ts',
                'src/index.html',
                'src/lib',
                'src/lib/i18n-2.0.0.min.js',
                'src/lib/i18n-2.0.0.min.js.map',
                'src/style',
                'src/style/style.scss',
                'tsconfig.json',
                'tslint.json',
                '.yo-rc.json',
            ]);
            assert.noFile([
                'src/index.js',
                '.eslintrc.json',
            ]);
            assert.jsonFileContent('package.json', {
                'name': 'MyDizmo',
                'description': 'My Dizmo',
                'version': '0.0.0',
                'author': {
                    'name': 'Dizmo Developer',
                    'email': 'developer@dizmo.com'
                },
                'contributors': [
                    {
                        'name': 'Dizmo Developer',
                        'email': 'developer@dizmo.com'
                    }
                ],
                'dizmo': {
                    'settings': {
                        'attributes': {
                            'settings/usercontrols/allowresize': true
                        },
                        'bundle-identifier': 'com.dizmo.my_dizmo',
                        'bundle-name': 'MyDizmo',
                        'category': '',
                        'height': 360,
                        'tags': [
                            'my-dizmo'
                        ],
                        'width': 480
                    },
                    'store': {
                        'host': 'https://store-api.dizmo.com'
                    }
                },
                'dependencies': {
                    '@babel/polyfill': '^7.6.0',
                    '@dizmo/functions': '^2.7.5',
                    '@dizmo/types': '^1.0.4'
                },
                'devDependencies': {
                    '@babel/core': '^7.6.2',
                    '@babel/preset-env': '^7.6.2',
                    'ansi-colors': '^4.1.1',
                    'babelify': '^10.0.0',
                    'browserify': '^16.5.0',
                    'fancy-log': '^1.3.3',
                    'gulp': '^4.0.2',
                    'gulp-copy': '^4.0.1',
                    'gulp-htmlmin': '^5.0.1',
                    'gulp-plist': '^0.1.0',
                    'gulp-rename': '^1.4.0',
                    'gulp-sass': '^4.0.2',
                    'gulp-sourcemaps': '^2.6.5',
                    'gulp-tslint': '^8.1.4',
                    'gulp-uglify': '^3.0.2',
                    'gulp-ver': '^0.1.0',
                    'gulp-zip': '^5.0.0',
                    'rimraf': '^3.0.0',
                    'tsify': '^4.0.1',
                    'tslint': '^5.20.0',
                    'typescript': '^3.6.3',
                    'vinyl-buffer': '^1.0.1',
                    'vinyl-source-stream': '^2.0.0',
                    'watchify': '^3.11.1'
                },
                'license': 'ISC',
                'private': true,
                'repository': {
                    'type': 'git',
                    'url': ''
                },
                'scripts': {
                    'build': 'node ./gulp/scripts/build.js',
                    'clean': 'node ./gulp/scripts/clean.js',
                    'deploy': 'node ./gulp/scripts/deploy.js',
                    'lint': 'node ./gulp/scripts/lint.js',
                    'test': 'exit 0',
                    'upload': 'node ./gulp/scripts/upload.js',
                    'watch': 'node ./gulp/scripts/watch.js'
                },
                'optionalDependencies': {
                    'javascript-obfuscator': '^0.18.1',
                    'pump': '^3.0.0'
                }
            });
        });
    });
    it('yo @dizmo/dizmo --typescript --git', () => {
        return run(generator).withOptions({
            'author': 'Dizmo Developer',
            'bundle-id': 'com.dizmo.my_dizmo',
            'email': 'developer@dizmo.com',
            'git': true,
            'typescript': true
        }).then(() => {
            assert.file([
                '.gitignore'
            ]);
            assert.noFile([
                '.npmignore'
            ]);
        });
    });
});
<commit_msg>DD-277: fixed generator tests<commit_after>const assert = require('yeoman-assert');
const { run } = require('yeoman-test');
const { join } = require('path');

describe('generator-dizmo:sub-typescript', function () {
    const generator = join(__dirname, '../generators/app');
    it('yo @dizmo/dizmo --typescript', () => {
        return run(generator).withOptions({
            'author': 'Dizmo Developer',
            'bundle-id': 'com.dizmo.my_dizmo',
            'email': 'developer@dizmo.com',
            'typescript': true
        }).then(() => {
            assert.file([
                'assets',
                'assets/Icon-dark.svg',
                'assets/Icon.svg',
                'assets/locales',
                'assets/locales/translation.de.json',
                'assets/locales/translation.en.json',
                'assets/Preview.png',
                'gulp',
                'gulp/miscellanea',
                'gulp/miscellanea/cli-spinner.js',
                'gulp/package.js',
                'gulp/scripts',
                'gulp/scripts/build.js',
                'gulp/scripts/clean.js',
                'gulp/scripts/deploy.js',
                'gulp/scripts/lint.js',
                'gulp/scripts/upload.js',
                'gulp/scripts/watch.js',
                'gulp/tasks',
                'gulp/tasks/build',
                'gulp/tasks/build/assets',
                'gulp/tasks/build/assets/index.js',
                'gulp/tasks/build/assets/watch.js',
                'gulp/tasks/build/dizmo',
                'gulp/tasks/build/dizmo/index.js',
                'gulp/tasks/build/dizmo/watch.js',
                'gulp/tasks/build/help',
                'gulp/tasks/build/help/index.js',
                'gulp/tasks/build/help/watch.js',
                'gulp/tasks/build/index.js',
                'gulp/tasks/build/libraries',
                'gulp/tasks/build/libraries/index.js',
                'gulp/tasks/build/libraries/watch.js',
                'gulp/tasks/build/markup',
                'gulp/tasks/build/markup/index.js',
                'gulp/tasks/build/markup/watch.js',
                'gulp/tasks/build/properties',
                'gulp/tasks/build/properties/index.js',
                'gulp/tasks/build/properties/watch.js',
                'gulp/tasks/build/scripts',
                'gulp/tasks/build/scripts/index.js',
                'gulp/tasks/build/scripts/watch.js',
                'gulp/tasks/build/styles',
                'gulp/tasks/build/styles/index.js',
                'gulp/tasks/build/styles/watch.js',
                'gulp/tasks/build/watch.js',
                'gulp/tasks/clean',
                'gulp/tasks/clean/index.js',
                'gulp/tasks/deploy',
                'gulp/tasks/deploy/index.js',
                'gulp/tasks/deploy/watch.js',
                'gulp/tasks/lint',
                'gulp/tasks/lint/index.js',
                'gulp/tasks/upload',
                'gulp/tasks/upload/index.js',
                'gulp/tasks/watch',
                'gulp/tasks/watch/index.js',
                'gulpfile.js',
                'help',
                'help/en',
                'help/en/help.md',
                'help/en/placeholder-400x275.png',
                '.info.plist',
                'LICENSE',
                '.npmignore',
                'package.json',
                'README.md',
                'src',
                'src/index.html',
                'src/index.ts',
                'src/lib',
                'src/lib/i18n-2.0.0.min.js',
                'src/lib/i18n-2.0.0.min.js.map',
                'src/style',
                'src/style/style.scss',
                'tsconfig.json',
                'tslint.json',
                'webpack.config.js',
                '.yo-rc.json',
            ]);
            assert.noFile([
                'src/index.js',
                '.eslintrc.json',
            ]);
            assert.jsonFileContent('package.json', {
                'name': 'MyDizmo',
                'description': 'My Dizmo',
                'version': '0.0.0',
                'author': {
                    'name': 'Dizmo Developer',
                    'email': 'developer@dizmo.com'
                },
                'contributors': [
                    {
                        'name': 'Dizmo Developer',
                        'email': 'developer@dizmo.com'
                    }
                ],
                'dizmo': {
                    'settings': {
                        'attributes': {
                            'settings/usercontrols/allowresize': true
                        },
                        'bundle-identifier': 'com.dizmo.my_dizmo',
                        'bundle-name': 'MyDizmo',
                        'category': '',
                        'height': 360,
                        'tags': [
                            'my-dizmo'
                        ],
                        'width': 480
                    },
                    'store': {
                        'host': 'https://store-api.dizmo.com'
                    }
                },
                'dependencies': {
                    '@babel/polyfill': '^7.6.0',
                    '@dizmo/types': '^1.0.4'
                },
                'devDependencies': {
                    '@babel/core': '^7.6.2',
                    '@babel/preset-env': '^7.6.2',
                    'ansi-colors': '^4.1.1',
                    'babel-loader': '^8.0.6',
                    'fancy-log': '^1.3.3',
                    'gulp': '^4.0.2',
                    'gulp-copy': '^4.0.1',
                    'gulp-htmlmin': '^5.0.1',
                    'gulp-plist': '^0.1.0',
                    'gulp-rename': '^1.4.0',
                    'gulp-sass': '^4.0.2',
                    'gulp-sourcemaps': '^2.6.5',
                    'gulp-tslint': '^8.1.4',
                    'gulp-ver': '^0.1.0',
                    'gulp-zip': '^5.0.0',
                    'rimraf': '^3.0.0',
                    'ts-loader': '^6.2.0',
                    'tslint': '^5.20.0',
                    'typescript': '^3.6.3',
                    'webpack': '^4.41.0',
                    'webpack-stream': '^5.2.1'
                },
                'license': 'ISC',
                'optionalDependencies': {
                    'pump': '^3.0.0',
                    'terser-webpack-plugin': '^2.1.2',
                    'webpack-obfuscator': '^0.18.3'
                },
                'private': true,
                'repository': {
                    'type': 'git',
                    'url': ''
                },
                'scripts': {
                    'build': 'node ./gulp/scripts/build.js',
                    'clean': 'node ./gulp/scripts/clean.js',
                    'deploy': 'node ./gulp/scripts/deploy.js',
                    'lint': 'node ./gulp/scripts/lint.js',
                    'test': 'exit 0',
                    'upload': 'node ./gulp/scripts/upload.js',
                    'watch': 'node ./gulp/scripts/watch.js'
                }
            });
        });
    });
    it('yo @dizmo/dizmo --typescript --git', () => {
        return run(generator).withOptions({
            'author': 'Dizmo Developer',
            'bundle-id': 'com.dizmo.my_dizmo',
            'email': 'developer@dizmo.com',
            'git': true,
            'typescript': true
        }).then(() => {
            assert.file([
                '.gitignore'
            ]);
            assert.noFile([
                '.npmignore'
            ]);
        });
    });
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';

import { CSExpandable, CSValidatorChanger } from 'chillisalmon';
import { StopMenu, TimeTable, Title } from 'timetbl';

import UserLocation from './UserLocation.js';
import NavBar from './NavBar.js';

import './App.css';
import './Theme.css';

class App extends Component {
	constructor(props) {
		super(props);

		this.state = this.parseURL();
		window.history.replaceState(this.state, 'timetbl', this.state.url);
		window.onpopstate = (event) => {
			this.setState(event.state);
		};

		this.navigate = this.navigate.bind(this);
	}

	getActiveView() {
		try {
			if (this.state.view.hasOwnProperty('menu')) {
				return (
					<StopMenu lat={this.state.coords.lat} lon={this.state.coords.lon} maxDistance={this.state.coords.r} navigate={this.navigate}/>
				);
			} else if (this.state.view.hasOwnProperty('nearby')) {
				return (
					<TimeTable lat={this.state.coords.lat} lon={this.state.coords.lon} maxDistance={this.state.coords.r} maxResults={15}/>
				);
			} else if (this.state.view.hasOwnProperty('stop')) {
				return (
					<TimeTable stopCode={this.state.view.stop.code} maxResults={15}/>
				);
			} else if (this.state.view.hasOwnProperty('error')) {
				return (

Error

{this.state.view.error}

				);
			} else {
				return (

Error

State can not be resolved

				);
			}
		} catch(e) {
			return (

Loading

Waiting location

			);
		}
	}

	getTitle() {
		if (this.state.hasOwnProperty('error')) return null;
		try {
			if (this.state.hasOwnProperty('title') && this.state.title) {
				return (
					<Title text={this.state.title} clock={true}/>
				);
			} else if (this.state.view.hasOwnProperty('menu')) {
				return (
					<Title lat={this.state.coords.lat} lon={this.state.coords.lon} clock={true}/>
				);
			} else if (this.state.view.hasOwnProperty('nearby')) {
				return (
					<Title lat={this.state.coords.lat} lon={this.state.coords.lon} clock={true}/>
				);
			} else if (this.state.view.hasOwnProperty('stop')) {
				return (
					<Title text={this.state.view.stop.code[0]} clock={true}/>
				);
			} else {
				return null;
			}
		} catch(e) {
			return null;
		}
	}

	getNavBar() {
		if (this.getTitle() === null) return null;

		const buttons = [
			{
				text: 'Nearby',
				onClick: () => {this.navigate('/#/nearby');},
				disabled: this.state.view.hasOwnProperty('nearby')
			},
			{
				text: 'Menu',
				onClick: () => {this.navigate('/#/menu');},
				disabled: this.state.view.hasOwnProperty('menu')
			}
		];

		return (
			<CSExpandable>
				<NavBar buttons={buttons}/>
			</CSExpandable>
		);
	}

	getLazyURLSearchParamsMock(param_str) {
		return {
			get: (param_name) => {
				const match = param_str.match(param_name + /=([^&/]+)/);
				if (!match) return null;
				return match[1];
			}
		};
	}

	parseURL(url=document.location.href) {
		const base_match = url.match(/:\/\/[^/]*(\/[^#]*)/);
		const base = base_match ? base_match[1] : '/';
		const params_match = url.match(/\?.*/);
		const params_str = params_match ? params_match[0] : '';

		var url_params;
		try {
			url_params = new URLSearchParams(params_str);
		} catch(e) {
			url_params = this.getLazyURLSearchParamsMock(params_str);
		}

		var match;
		var state = {};

		if (this.state !== undefined) {
			clearInterval(this.state.follow_interval);
		}

		if (url_params.get('follow') !== 'false') {
			state = Object.assign(state, {
				follow: true
			});
		}

		state = Object.assign(state, {title: url_params.get('title')});

		const lat = Number(url_params.get('lat'));
		const lon = Number(url_params.get('lon'));

		if (lat && lon) {
			var r = Number(url_params.get('r'));
			r = isNaN(r) ? r : 1000;

			state = Object.assign(state, {
				coords: {
					lat: lat,
					lon: lon,
					r: r
				}
			});
		}

		const view = (() => {
			/* eslint-disable no-cond-assign */
			if (match = url.match(/#\/menu.*/)) {
				return {
					'view': {
						'menu': null
					},
					'url': base + match[0]
				};
			} /* else if (match = url.match(/#\/nearby/)) {
				return {
					'view': {
						'nearby': null
					},
					'url': base + match[0]
				};
			} */ else if (match = url.match(/#\/stop(\?[^/]*)/)) {
				return {
					'view': {
						'stop': {
							'code': url_params.get('code').split(',')
						}
					},
					'url': base + match[0]
				};
			} else {
				return {
					'view': {
						'nearby': null
					},
					'url': base + '#/nearby' + params_str
				};
			}
			/* eslint-enable no-cond-assign */
		})();
		return Object.assign(state, view);
	}

	updateLocation() {
		UserLocation.getUserLocation((loc) => {
			const lat = Math.round(loc.coords.latitude*1e6)/1e6;
			const lon = Math.round(loc.coords.longitude*1e6)/1e6;
			this.setState(prev => ({
				coords: {
					lat: lat,
					lon: lon,
					r: prev.coords ? prev.coords.r : 1000
				}
			}));
		}, () => {
			this.setState({view: {error: 'Location not available'}});
		});
	}

	navigate(url) {
		this.setState(this.parseURL(url), ()=>{
			window.history.pushState(this.state, 'timetbl', this.state.url);
		});
	}

	componentDidMount() {
		if (this.state.follow) {
			this.setState({
				follow_interval: setInterval(() => {
					this.updateLocation();
				}, 30e3)
			});
			this.updateLocation();
		}
	}

	render() {
		return(

				{this.getTitle()}
				{this.getNavBar()}
				<CSValidatorChanger error={this.state.view.error} loading={this.state.view.loading}>
					{this.getActiveView()}
				</CSValidatorChanger>

					kangasta / timetbl
					|
					data source

		);
	}
}

export default App;
<commit_msg>Use string, instead of re, syntax to support MS Edge<commit_after>import React, { Component } from 'react';

import { CSExpandable, CSValidatorChanger } from 'chillisalmon';
import { StopMenu, TimeTable, Title } from 'timetbl';

import UserLocation from './UserLocation.js';
import NavBar from './NavBar.js';

import './App.css';
import './Theme.css';

class App extends Component {
	constructor(props) {
		super(props);

		this.state = this.parseURL();
		window.history.replaceState(this.state, 'timetbl', this.state.url);
		window.onpopstate = (event) => {
			this.setState(event.state);
		};

		this.navigate = this.navigate.bind(this);
	}

	getActiveView() {
		try {
			if (this.state.view.hasOwnProperty('menu')) {
				return (
					<StopMenu lat={this.state.coords.lat} lon={this.state.coords.lon} maxDistance={this.state.coords.r} navigate={this.navigate}/>
				);
			} else if (this.state.view.hasOwnProperty('nearby')) {
				return (
					<TimeTable lat={this.state.coords.lat} lon={this.state.coords.lon} maxDistance={this.state.coords.r} maxResults={15}/>
				);
			} else if (this.state.view.hasOwnProperty('stop')) {
				return (
					<TimeTable stopCode={this.state.view.stop.code} maxResults={15}/>
				);
			} else if (this.state.view.hasOwnProperty('error')) {
				return (

Error

{this.state.view.error}

				);
			} else {
				return (

Error

State can not be resolved

				);
			}
		} catch(e) {
			return (

Loading

Waiting location

			);
		}
	}

	getTitle() {
		if (this.state.hasOwnProperty('error')) return null;
		try {
			if (this.state.hasOwnProperty('title') && this.state.title) {
				return (
					<Title text={this.state.title} clock={true}/>
				);
			} else if (this.state.view.hasOwnProperty('menu')) {
				return (
					<Title lat={this.state.coords.lat} lon={this.state.coords.lon} clock={true}/>
				);
			} else if (this.state.view.hasOwnProperty('nearby')) {
				return (
					<Title lat={this.state.coords.lat} lon={this.state.coords.lon} clock={true}/>
				);
			} else if (this.state.view.hasOwnProperty('stop')) {
				return (
					<Title text={this.state.view.stop.code[0]} clock={true}/>
				);
			} else {
				return null;
			}
		} catch(e) {
			return null;
		}
	}

	getNavBar() {
		if (this.getTitle() === null) return null;

		const buttons = [
			{
				text: 'Nearby',
				onClick: () => {this.navigate('/#/nearby');},
				disabled: this.state.view.hasOwnProperty('nearby')
			},
			{
				text: 'Menu',
				onClick: () => {this.navigate('/#/menu');},
				disabled: this.state.view.hasOwnProperty('menu')
			}
		];

		return (
			<CSExpandable>
				<NavBar buttons={buttons}/>
			</CSExpandable>
		);
	}

	getLazyURLSearchParamsMock(param_str) {
		return {
			get: (param_name) => {
				const match = param_str.match(param_name + '=([^&/]+)');
				if (!match) return null;
				return match[1];
			}
		};
	}

	parseURL(url=document.location.href) {
		const base_match = url.match(/:\/\/[^/]*(\/[^#]*)/);
		const base = base_match ? base_match[1] : '/';
		const params_match = url.match(/\?.*/);
		const params_str = params_match ? params_match[0] : '';

		var url_params;
		try {
			url_params = new URLSearchParams(params_str);
		} catch(e) {
			url_params = this.getLazyURLSearchParamsMock(params_str);
		}

		var match;
		var state = {};

		if (this.state !== undefined) {
			clearInterval(this.state.follow_interval);
		}

		if (url_params.get('follow') !== 'false') {
			state = Object.assign(state, {
				follow: true
			});
		}

		state = Object.assign(state, {title: url_params.get('title')});

		const lat = Number(url_params.get('lat'));
		const lon = Number(url_params.get('lon'));

		if (lat && lon) {
			var r = Number(url_params.get('r'));
			r = isNaN(r) ? r : 1000;

			state = Object.assign(state, {
				coords: {
					lat: lat,
					lon: lon,
					r: r
				}
			});
		}

		const view = (() => {
			/* eslint-disable no-cond-assign */
			if (match = url.match(/#\/menu.*/)) {
				return {
					'view': {
						'menu': null
					},
					'url': base + match[0]
				};
			} /* else if (match = url.match(/#\/nearby/)) {
				return {
					'view': {
						'nearby': null
					},
					'url': base + match[0]
				};
			} */ else if (match = url.match(/#\/stop(\?[^/]*)/)) {
				return {
					'view': {
						'stop': {
							'code': url_params.get('code').split(',')
						}
					},
					'url': base + match[0]
				};
			} else {
				return {
					'view': {
						'nearby': null
					},
					'url': base + '#/nearby' + params_str
				};
			}
			/* eslint-enable no-cond-assign */
		})();
		return Object.assign(state, view);
	}

	updateLocation() {
		UserLocation.getUserLocation((loc) => {
			const lat = Math.round(loc.coords.latitude*1e6)/1e6;
			const lon = Math.round(loc.coords.longitude*1e6)/1e6;
			this.setState(prev => ({
				coords: {
					lat: lat,
					lon: lon,
					r: prev.coords ? prev.coords.r : 1000
				}
			}));
		}, () => {
			this.setState({view: {error: 'Location not available'}});
		});
	}

	navigate(url) {
		this.setState(this.parseURL(url), ()=>{
			window.history.pushState(this.state, 'timetbl', this.state.url);
		});
	}

	componentDidMount() {
		if (this.state.follow) {
			this.setState({
				follow_interval: setInterval(() => {
					this.updateLocation();
				}, 30e3)
			});
			this.updateLocation();
		}
	}

	render() {
		return(

				{this.getTitle()}
				{this.getNavBar()}
				<CSValidatorChanger error={this.state.view.error} loading={this.state.view.loading}>
					{this.getActiveView()}
				</CSValidatorChanger>

					kangasta / timetbl
					|
					data source

		);
	}
}

export default App;
<|endoftext|>