<commit_before>var Component = new Brick.Component();
Component.requires = {
    mod: [
        {name: 'sys', files: ['editor.js']},
        {name: '{C#MODNAME}', files: ['lib.js', 'employeesList.js']}
    ]
};
Component.entryPoint = function(NS){

	var Y = Brick.YUI,
        COMPONENT = this,
        SYS = Brick.mod.sys;

    NS.AddSelectValueModalWidget = Y.Base.create('addSelectValueModalWidget', SYS.AppWidget, [], {
        onInitAppWidget: function(err, appInstance){

        },
        showModal: function(valueid, attrid, numrow, relationid){
        	var tp = this.template;

          	this.set('attrid', attrid);
        	this.set('valueid', valueid);
        	this.set('relationid', relationid);
        	this.set('numrow', numrow);

	        	tp.setHTML('modal', tp.replace('modalForm', {
	        		none: 'block'
	        	}));

        	this.employees = new NS.EmployeesListWidget({
                srcNode: tp.gel('modalForm.form'),
                select: true,
                relationid: relationid
    		});

        },
        destroy: function(){
        	if(this.employees){
        		this.employees.destroy();
        	}
        },
        unSetSuccess: function(tr){
        	var collect = tr.parentNode.childNodes;

        	collect.forEach(function(item){
        		item.classList.remove('success');
        	});
        },
        selectValueAct: function(callback){
        	var data = {
        		valueid: this.get('valueid'),
        		attrid: this.get('attrid'),
        		relationid: this.get('relationid'),
        		numrow: this.get('numrow')
        	};

        	this.set('waiting', true);
	        	this.get('appInstance').selectValueAct(data, function(err, result){
	        		this.set('waiting', false);
		        		if(!err){
		        			this.template.setHTML('modal', '');
		        				callback(result.selectValueAct);
		        		}
	        	}, this);
        }
    }, {
        ATTRS: {
        	component: {value: COMPONENT},
            templateBlockName: {value: 'widget, modalForm'},
            valueid: {value: 0},
            attrid: {value: 0},
            relationid: {value: 0},
            numrow: {value: 0}
        },
        CLICKS: {
        	'addValue-cancel': {
        		event: function(){
        			this.template.setHTML('modal', '');
        		}
        	},
        	pickRow: {
        		event: function(e){
        			var targ = e.target,
        				tr = e.target.getDOMNode().parentNode;

        			if(tr.tagName != 'TR' || tr.id == ''){
        				return;
        			}

        			this.unSetSuccess(tr);
        			tr.classList.add('success');

        			this.set('relationid', tr.id.match(/-(\d)+/)[1]);
        		}
        	}
        }
    });
};<commit_msg>bugfix: parse id emploees<commit_after>var Component = new Brick.Component();
Component.requires = {
    mod: [
        {name: 'sys', files: ['editor.js']},
        {name: '{C#MODNAME}', files: ['lib.js', 'employeesList.js']}
    ]
};
Component.entryPoint = function(NS){

	var Y = Brick.YUI,
        COMPONENT = this,
        SYS = Brick.mod.sys;

    NS.AddSelectValueModalWidget = Y.Base.create('addSelectValueModalWidget', SYS.AppWidget, [], {
        onInitAppWidget: function(err, appInstance){

        },
        showModal: function(valueid, attrid, numrow, relationid){
        	var tp = this.template;

          	this.set('attrid', attrid);
        	this.set('valueid', valueid);
        	this.set('relationid', relationid);
        	this.set('numrow', numrow);

	        	tp.setHTML('modal', tp.replace('modalForm', {
	        		none: 'block'
	        	}));

        	this.employees = new NS.EmployeesListWidget({
                srcNode: tp.gel('modalForm.form'),
                select: true,
                relationid: relationid
    		});

        },
        destroy: function(){
        	if(this.employees){
        		this.employees.destroy();
        	}
        },
        unSetSuccess: function(tr){
        	var collect = tr.parentNode.childNodes;

        	collect.forEach(function(item){
        		item.classList.remove('success');
        	});
        },
        selectValueAct: function(callback){
        	var data = {
        		valueid: this.get('valueid'),
        		attrid: this.get('attrid'),
        		relationid: this.get('relationid'),
        		numrow: this.get('numrow')
        	};

        	this.set('waiting', true);
	        	this.get('appInstance').selectValueAct(data, function(err, result){
	        		this.set('waiting', false);
		        		if(!err){
		        			this.template.setHTML('modal', '');
		        				callback(result.selectValueAct);
		        		}
	        	}, this);
        }
    }, {
        ATTRS: {
        	component: {value: COMPONENT},
            templateBlockName: {value: 'widget, modalForm'},
            valueid: {value: 0},
            attrid: {value: 0},
            relationid: {value: 0},
            numrow: {value: 0}
        },
        CLICKS: {
        	'addValue-cancel': {
        		event: function(){
        			this.template.setHTML('modal', '');
        		}
        	},
        	pickRow: {
        		event: function(e){
        			var targ = e.target,
        				tr = e.target.getDOMNode().parentNode;

        			if(tr.tagName != 'TR' || tr.id == ''){
        				return;
        			}

        			this.unSetSuccess(tr);
        			tr.classList.add('success');

        			this.set('relationid', tr.id.match(/-(\d+)/)[1]);
        		}
        	}
        }
    });
};<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.13.0');
		this.setClientTag('node:20-12-29');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.13.0');
		this.setClientTag('node:20-12-30');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>/*
  The code here has been adapted from the npm css module, the source code for
  which is available at http://github.com/reworkcss/css.
  It is available under an MIT license.
*/
var commentre = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g

function parse (css, options) {
  options = options || {};

  /**
   * Positional.
   */

  var lineno = 1;
  var column = 1;

  /**
   * Update lineno and column based on `str`.
   */

  function updatePosition(str) {
    var lines = str.match(/\n/g);
    if (lines) lineno += lines.length;
    var i = str.lastIndexOf('\n');
    column = ~i ? str.length - i : column + str.length;
  }

  /**
   * Mark position and patch `node.position`.
   */

  function position() {
    var start = { line: lineno, column: column };
    return function(node){
      node.position = new Position(start);
      whitespace();
      return node;
    };
  }

  /**
   * Store position information for a node
   */

  function Position(start) {
    this.start = start;
    this.end = { line: lineno, column: column };
    this.source = options.source;
  }

  /**
   * Non-enumerable source string
   */

  Position.prototype.content = css;

  /**
   * Error `msg`.
   */

  var errorsList = [];

  function error(msg) {
    var err = new Error(options.source + ':' + lineno + ':' + column + ': ' + msg);
    err.reason = msg;
    err.filename = options.source;
    err.line = lineno;
    err.column = column;
    err.source = css;

    if (options.silent) {
      errorsList.push(err);
    } else {
      throw err;
    }
  }

  /**
   * Parse stylesheet.
   */

  function stylesheet() {
    var rulesList = rules();

    return {
      type: 'stylesheet',
      stylesheet: {
        rules: rulesList,
        parsingErrors: errorsList
      }
    };
  }

  /**
   * Opening brace.
   */

  function open() {
    return match(/^{\s*/);
  }

  /**
   * Closing brace.
   */

  function close() {
    return match(/^}/);
  }

  /**
   * Parse ruleset.
   */

  function rules() {
    var node;
    var rules = [];
    whitespace();
    comments(rules);
    while (css.length && css.charAt(0) != '}' && ((node = rule()))) {
      if (node !== false) {
        rules.push(node);
        comments(rules);
      }
    }
    return rules;
  }

  /**
   * Match `re` and return captures.
   */

  function match(re) {
    var m = re.exec(css);
    if (!m) return;
    var str = m[0];
    updatePosition(str);
    css = css.slice(str.length);
    return m;
  }

  /**
   * Parse whitespace.
   */

  function whitespace() {
    match(/^\s*/);
  }

  /**
   * Parse comments;
   */

  function comments(rules) {
    var c;
    rules = rules || [];
    while ((c = comment())) {
      if (c !== false) {
        rules.push(c);
      }
    }
    return rules;
  }

  /**
   * Parse comment.
   */

  function comment() {
    var pos = position();
    if ('/' != css.charAt(0) || '*' != css.charAt(1)) return;

    var i = 2;
    while ("" != css.charAt(i) && ('*' != css.charAt(i) || '/' != css.charAt(i + 1))) ++i;
    i += 2;

    if ("" === css.charAt(i-1)) {
      return error('End of comment missing');
    }

    var str = css.slice(2, i - 2);
    column += 2;
    updatePosition(str);
    css = css.slice(i);
    column += 2;

    return pos({
      type: 'comment',
      comment: str
    });
  }

  /**
   * Parse selector.
   */

  function selector() {
    var m = match(/^([^{]+)/);
    if (!m) return;
    /* @fix Remove all comments from selectors
     * http://ostermiller.org/findcomment.html */
    return trim(m[0])
      .replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '')
      .replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function(m) {
        return m.replace(/,/g, '\u200C');
      })
      .split(/\s*(?![^(]*\)),\s*/)
      .map(function(s) {
        return s.replace(/\u200C/g, ',');
      });
  }

  /**
   * Parse declaration.
   */

  function declaration() {
    var pos = position();

    // prop
    var prop = match(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);
    if (!prop) return;
    prop = trim(prop[0]);

    // :
    if (!match(/^:\s*/)) return error("property missing ':'");

    // val
    var val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/);

    var ret = pos({
      type: 'declaration',
      property: prop.replace(commentre, ''),
      value: val ? trim(val[0]).replace(commentre, '') : ''
    });

    // ;
    match(/^[;\s]*/);

    return ret;
  }

  /**
   * Parse declarations.
   */

  function declarations() {
    var decls = [];

    if (!open()) return error("missing '{'");
    comments(decls);

    // declarations
    var decl;
    while ((decl = declaration())) {
      if (decl !== false) {
        decls.push(decl);
        comments(decls);
      }
    }

    if (!close()) return error("missing '}'");
    return decls;
  }

  /**
   * Parse rule.
   */

  function rule() {
    var pos = position();
    var sel = selector();

    if (!sel) return error('selector missing');
    comments();

    return pos({
      type: 'rule',
      selectors: sel,
      declarations: declarations()
    });
  }

  return addParent(stylesheet());
};

/**
 * Trim `str`.
 */

function trim(str) {
  return str ? str.replace(/^\s+|\s+$/g, '') : '';
}

/**
 * Adds non-enumerable parent node reference to each node.
 */

function addParent(obj, parent) {
  var isNode = obj && typeof obj.type === 'string';
  var childParent = isNode ? obj : parent;

  for (var k in obj) {
    var value = obj[k];
    if (Array.isArray(value)) {
      value.forEach(function(v) { addParent(v, childParent); });
    } else if (value && typeof value === 'object') {
      addParent(value, childParent);
    }
  }

  if (isNode) {
    Object.defineProperty(obj, 'parent', {
      configurable: true,
      writable: true,
      enumerable: false,
      value: parent || null
    });
  }

  return obj;
}
<commit_msg>CSS Parser patch: Explicitly return undefined<commit_after>/*
  The code here has been adapted from the npm css module, the source code for
  which is available at http://github.com/reworkcss/css.
  It is available under an MIT license.
*/
var commentre = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g

function parse (css, options) {
  options = options || {};

  /**
   * Positional.
   */

  var lineno = 1;
  var column = 1;

  /**
   * Update lineno and column based on `str`.
   */

  function updatePosition(str) {
    var lines = str.match(/\n/g);
    if (lines) lineno += lines.length;
    var i = str.lastIndexOf('\n');
    column = ~i ? str.length - i : column + str.length;
  }

  /**
   * Mark position and patch `node.position`.
   */

  function position() {
    var start = { line: lineno, column: column };
    return function(node){
      node.position = new Position(start);
      whitespace();
      return node;
    };
  }

  /**
   * Store position information for a node
   */

  function Position(start) {
    this.start = start;
    this.end = { line: lineno, column: column };
    this.source = options.source;
  }

  /**
   * Non-enumerable source string
   */

  Position.prototype.content = css;

  /**
   * Error `msg`.
   */

  var errorsList = [];

  function error(msg) {
    var err = new Error(options.source + ':' + lineno + ':' + column + ': ' + msg);
    err.reason = msg;
    err.filename = options.source;
    err.line = lineno;
    err.column = column;
    err.source = css;

    if (options.silent) {
      errorsList.push(err);
    } else {
      throw err;
    }
  }

  /**
   * Parse stylesheet.
   */

  function stylesheet() {
    var rulesList = rules();

    return {
      type: 'stylesheet',
      stylesheet: {
        rules: rulesList,
        parsingErrors: errorsList
      }
    };
  }

  /**
   * Opening brace.
   */

  function open() {
    return match(/^{\s*/);
  }

  /**
   * Closing brace.
   */

  function close() {
    return match(/^}/);
  }

  /**
   * Parse ruleset.
   */

  function rules() {
    var node;
    var rules = [];
    whitespace();
    comments(rules);
    while (css.length && css.charAt(0) != '}' && ((node = rule()))) {
      if (node !== false) {
        rules.push(node);
        comments(rules);
      }
    }
    return rules;
  }

  /**
   * Match `re` and return captures.
   */

  function match(re) {
    var m = re.exec(css);
    if (!m) return undefined;
    var str = m[0];
    updatePosition(str);
    css = css.slice(str.length);
    return m;
  }

  /**
   * Parse whitespace.
   */

  function whitespace() {
    match(/^\s*/);
  }

  /**
   * Parse comments;
   */

  function comments(rules) {
    var c;
    rules = rules || [];
    while ((c = comment())) {
      if (c !== false) {
        rules.push(c);
      }
    }
    return rules;
  }

  /**
   * Parse comment.
   */

  function comment() {
    var pos = position();
    if ('/' != css.charAt(0) || '*' != css.charAt(1)) return undefined;

    var i = 2;
    while ("" != css.charAt(i) && ('*' != css.charAt(i) || '/' != css.charAt(i + 1))) ++i;
    i += 2;

    if ("" === css.charAt(i-1)) {
      return error('End of comment missing');
    }

    var str = css.slice(2, i - 2);
    column += 2;
    updatePosition(str);
    css = css.slice(i);
    column += 2;

    return pos({
      type: 'comment',
      comment: str
    });
  }

  /**
   * Parse selector.
   */

  function selector() {
    var m = match(/^([^{]+)/);
    if (!m) return undefined;
    /* @fix Remove all comments from selectors
     * http://ostermiller.org/findcomment.html */
    return trim(m[0])
      .replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '')
      .replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function(m) {
        return m.replace(/,/g, '\u200C');
      })
      .split(/\s*(?![^(]*\)),\s*/)
      .map(function(s) {
        return s.replace(/\u200C/g, ',');
      });
  }

  /**
   * Parse declaration.
   */

  function declaration() {
    var pos = position();

    // prop
    var prop = match(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);
    if (!prop) return undefined;
    prop = trim(prop[0]);

    // :
    if (!match(/^:\s*/)) return error("property missing ':'");

    // val
    var val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/);

    var ret = pos({
      type: 'declaration',
      property: prop.replace(commentre, ''),
      value: val ? trim(val[0]).replace(commentre, '') : ''
    });

    // ;
    match(/^[;\s]*/);

    return ret;
  }

  /**
   * Parse declarations.
   */

  function declarations() {
    var decls = [];

    if (!open()) return error("missing '{'");
    comments(decls);

    // declarations
    var decl;
    while ((decl = declaration())) {
      if (decl !== false) {
        decls.push(decl);
        comments(decls);
      }
    }

    if (!close()) return error("missing '}'");
    return decls;
  }

  /**
   * Parse rule.
   */

  function rule() {
    var pos = position();
    var sel = selector();

    if (!sel) return error('selector missing');
    comments();

    return pos({
      type: 'rule',
      selectors: sel,
      declarations: declarations()
    });
  }

  return addParent(stylesheet());
};

/**
 * Trim `str`.
 */

function trim(str) {
  return str ? str.replace(/^\s+|\s+$/g, '') : '';
}

/**
 * Adds non-enumerable parent node reference to each node.
 */

function addParent(obj, parent) {
  var isNode = obj && typeof obj.type === 'string';
  var childParent = isNode ? obj : parent;

  for (var k in obj) {
    var value = obj[k];
    if (Array.isArray(value)) {
      value.forEach(function(v) { addParent(v, childParent); });
    } else if (value && typeof value === 'object') {
      addParent(value, childParent);
    }
  }

  if (isNode) {
    Object.defineProperty(obj, 'parent', {
      configurable: true,
      writable: true,
      enumerable: false,
      value: parent || null
    });
  }

  return obj;
}
<|endoftext|>


<commit_before>module.exports = CssLocator;

function CssLocator(target) {
  var element = target, result = [];

  while (element.tagName !== 'BODY') {
    // go through known attributes (in order) and create css selector
    for (var i = 0; i < CssLocator.attributes.length; i++) {
      var attr = CssLocator.attributes[i], value, prefix = '', suffix = '', index;
      // take as is
      if (attr === 'tagName') {
        value = element.tagName.toLowerCase();
      } else if (typeof (attr) === 'string') {
        value = element.getAttribute(attr);
        prefix = element.tagName.toLowerCase() + '[' + attr + '="';
        suffix = '"]';
        if (value) {
          value = value.replace(/"/g, '\"');
        }
      } else if (typeof (attr) === 'object') {
        value = element.getAttribute(attr.name);
        if (value && attr.format) {
          value = attr.format(value, element);
        }
        prefix = attr.prefix || '';
        suffix = attr.suffix || '';
      }

      if (value) {
        // get element index
        index = Array.prototype.indexOf.call(element.parentNode.children, element);
        if (index > 0 && element.parentNode.querySelectorAll(prefix + value + suffix).length > 1) {
          suffix +=':nth-child(' + (index + 1) + ')';
        }

        result.unshift(prefix + value + suffix);
        break;
      }
    }

    element = element.parentNode;
  }
  return 'css=' + result.join(' ');
}

CssLocator.classBlacklist = [/^ng\-/];
CssLocator.attributes = [
  {
    name: 'id',
    format: (v) => /^\d/.test(v) ? '[id="' + v + '"]' : '#' + v
  },
  'name',
  {
    name: 'class',
    prefix: '.',
    format: (v, element) => v.split(' ').filter((c) => !CssLocator.classBlacklist.some((regex)=>regex.test(c))).join('.')
  },
  'type',
  'alt',
  'title',
  'value',
  'tagName'
];

CssLocator.find = function(locator, parent) {
  return parent.querySelector(locator);
};<commit_msg>added support for :contains pseudo class. also made sure that ids would not be duplicated in resulting selector<commit_after>module.exports = CssLocator;

function CssLocator(target) {
  var element = target, result = [], interrupt = false;

  while (element.tagName !== 'BODY') {
    // go through known attributes (in order) and create css selector
    for (var i = 0; i < CssLocator.attributes.length; i++) {
      var attr = CssLocator.attributes[i], value, prefix = '', suffix = '', index;
      // take as is
      if (attr === 'tagName') {
        value = element.tagName.toLowerCase();
      } else if (typeof (attr) === 'string') {
        value = element.getAttribute(attr);
        prefix = element.tagName.toLowerCase() + '[' + attr + '="';
        suffix = '"]';
        if (value) {
          value = value.replace(/"/g, '\"');
        }
      } else if (typeof (attr) === 'object') {
        value = element.getAttribute(attr.name);
        if (value && attr.format) {
          value = attr.format(value, element);
        }
        prefix = attr.prefix || '';
        suffix = attr.suffix || '';
      }

      if (value) {
        // get element index
        index = Array.prototype.indexOf.call(element.parentNode.children, element);
        if (index > 0 && element.parentNode.querySelectorAll(prefix + value + suffix).length > 1) {
          suffix += ':nth-child(' + (index + 1) + ')';
        }

        result.unshift(prefix + value + suffix);
        interrupt = attr.interrupt === true; // interrupt generation if it is significant enough
        break;
      }
    }
    if (interrupt) {
      break;
    }
    element = element.parentNode;
  }
  return 'css=' + result.join(' ');
}

CssLocator.classBlacklist = [/^ng\-/];
CssLocator.attributes = [
  {
    name: 'id',
    format: (v) => /^\d/.test(v) ? '[id="' + v + '"]' : '#' + v,
    interrupt: true
  },
  'name',
  {
    name: 'class',
    prefix: '.',
    format: (v, element) => v.split(' ').filter((c) => !CssLocator.classBlacklist.some((regex) => regex.test(c))).join('.')
  },
  'type',
  'alt',
  'title',
  'value',
  'tagName'
];

CssLocator.find = function (locator, parent) {
  locator = locator.trim();
  var containsStartIndex = locator.indexOf(':contains(');
  var containsEndIndex = locator.indexOf(')', containsStartIndex);
  var result, item;
  if (containsStartIndex !==-1 && containsEndIndex !==-1) {
    var prefix = locator.substring(0, containsStartIndex);
    var text = locator.substring(containsStartIndex + ":contains(".length + 1, containsEndIndex - 1).toLowerCase();
    var suffix = locator.substring(containsEndIndex + 1).trim();
    var items = parent.querySelectorAll(prefix);
    for (var i = 0, len = items.length; i < len; i++) {
      item = items[i];
      if (item.textContent.toLowerCase().indexOf(text) !== -1) {
        if (suffix) {
          result = CssLocator.find(suffix, item);
          if (result) {
            break;
          }
        } else {
          result = item;
          break;
        }
      }
    }
  } else {
    result = parent.querySelector(locator);
  }
  return result;
};<|endoftext|>


<commit_before>"use strict";

/*  ------------------------------------------------------------------------ */

const isNumber          = Number.isFinite
    , isArray           = Array.isArray
    , hasProps          = o => ((o !== undefined) && (o !== null))
    , isString          = s =>                 (typeof s === 'string')
    , isObject          = o => ((o !== null) && (typeof o === 'object'))
    , isDictionary      = o => (isObject (o) && !isArray (o))
    , isStringCoercible = x => ((hasProps (x) && x.toString) || isNumber (x))

/*  .............................................   */

const prop = (o, k) => (isObject (o) ? o[k] : undefined)
    , prop2 = (o, k1, k2) => (!isObject (o) ? undefined : ((k1 in o) ? o[k1] : o[k2]))

/*  .............................................   */

const asFloat   = x => ((isNumber (x) || isString (x)) ? parseFloat (x)     : NaN)
    , asInteger = x => ((isNumber (x) || isString (x)) ? parseInt   (x, 10) : NaN)

/*  .............................................   */

module.exports = {

    isNumber
    , isArray
    , isObject
    , isString
    , isStringCoercible
    , isDictionary

    , hasProps
    , prop

    , asFloat
    , asInteger

    , safeFloat:          (o, k,          $default, n =   asFloat (prop (o, k))) => (isNumber (n)          ? n                         : $default)
    , safeInteger:        (o, k,          $default, n = asInteger (prop (o, k))) => (isNumber (n)          ? n                         : $default)
    , safeIntegerProduct: (o, k, $factor, $default, n = asInteger (prop (o, k))) => (isNumber (n)          ? parseInt (n) * $factor    : $default)
    , safeTimestamp:      (o, k,          $default, n = asInteger (prop (o, k))) => (isNumber (n)          ? parseInt (parseFloat (n) * 1000) : $default)
    , safeValue:          (o, k,          $default, x =            prop (o, k))  => (hasProps (x)          ? x                         : $default)
    , safeString:         (o, k,          $default, x =            prop (o, k))  => (isStringCoercible (x) ? String (x)                : $default)
    , safeStringLower:    (o, k,          $default, x =            prop (o, k))  => (isStringCoercible (x) ? String (x).toLowerCase () : $default)
    , safeStringUpper:    (o, k,          $default, x =            prop (o, k))  => (isStringCoercible (x) ? String (x).toUpperCase () : $default)

    // not using safeFloats with an array argument as we're trying to save some cycles here
    // we're not using safeFloat3 either because those cases are too rare to deserve their own optimization

    , safeFloat2:          (o, k1, k2,          $default, n =   asFloat (prop2 (o, k1, k2))) => (isNumber (n)          ? n                         : $default)
    , safeInteger2:        (o, k1, k2,          $default, n = asInteger (prop2 (o, k1, k2))) => (isNumber (n)          ? n                         : $default)
    , safeIntegerProduct2: (o, k1, k2, $factor, $default, n = asInteger (prop2 (o, k1, k2))) => (isNumber (n)          ? parseInt (n) * $factor    : $default)
    , safeTimestamp2:      (o, k1, k2,          $default, n = asInteger (prop2 (o, k1, k2))) => (isNumber (n)          ? parseInt (parseFloat (n) * 1000) : $default)
    , safeValue2:          (o, k1, k2,          $default, x =            prop2 (o, k1, k2))  => (hasProps (x)          ? x                         : $default)
    , safeString2:         (o, k1, k2,          $default, x =            prop2 (o, k1, k2))  => (isStringCoercible (x) ? String (x)                : $default)
    , safeStringLower2:    (o, k1, k2,          $default, x =            prop2 (o, k1, k2))  => (isStringCoercible (x) ? String (x).toLowerCase () : $default)
    , safeStringUpper2:    (o, k1, k2,          $default, x =            prop2 (o, k1, k2))  => (isStringCoercible (x) ? String (x).toUpperCase () : $default)

}

/*  ------------------------------------------------------------------------ */
<commit_msg>type.js remove parseFloat from safeTimestamp<commit_after>"use strict";

/*  ------------------------------------------------------------------------ */

const isNumber          = Number.isFinite
    , isArray           = Array.isArray
    , hasProps          = o => ((o !== undefined) && (o !== null))
    , isString          = s =>                 (typeof s === 'string')
    , isObject          = o => ((o !== null) && (typeof o === 'object'))
    , isDictionary      = o => (isObject (o) && !isArray (o))
    , isStringCoercible = x => ((hasProps (x) && x.toString) || isNumber (x))

/*  .............................................   */

const prop = (o, k) => (isObject (o) ? o[k] : undefined)
    , prop2 = (o, k1, k2) => (!isObject (o) ? undefined : ((k1 in o) ? o[k1] : o[k2]))

/*  .............................................   */

const asFloat   = x => ((isNumber (x) || isString (x)) ? parseFloat (x)     : NaN)
    , asInteger = x => ((isNumber (x) || isString (x)) ? parseInt   (x, 10) : NaN)

/*  .............................................   */

module.exports = {

    isNumber
    , isArray
    , isObject
    , isString
    , isStringCoercible
    , isDictionary

    , hasProps
    , prop

    , asFloat
    , asInteger

    , safeFloat:          (o, k,          $default, n =   asFloat (prop (o, k))) => (isNumber (n)          ? n                         : $default)
    , safeInteger:        (o, k,          $default, n = asInteger (prop (o, k))) => (isNumber (n)          ? n                         : $default)
    , safeIntegerProduct: (o, k, $factor, $default, n = asInteger (prop (o, k))) => (isNumber (n)          ? parseInt (n) * $factor    : $default)
    , safeTimestamp:      (o, k,          $default, n = asInteger (prop (o, k))) => (isNumber (n)          ? parseInt (n * 1000)       : $default)
    , safeValue:          (o, k,          $default, x =            prop (o, k))  => (hasProps (x)          ? x                         : $default)
    , safeString:         (o, k,          $default, x =            prop (o, k))  => (isStringCoercible (x) ? String (x)                : $default)
    , safeStringLower:    (o, k,          $default, x =            prop (o, k))  => (isStringCoercible (x) ? String (x).toLowerCase () : $default)
    , safeStringUpper:    (o, k,          $default, x =            prop (o, k))  => (isStringCoercible (x) ? String (x).toUpperCase () : $default)

    // not using safeFloats with an array argument as we're trying to save some cycles here
    // we're not using safeFloat3 either because those cases are too rare to deserve their own optimization

    , safeFloat2:          (o, k1, k2,          $default, n =   asFloat (prop2 (o, k1, k2))) => (isNumber (n)          ? n                         : $default)
    , safeInteger2:        (o, k1, k2,          $default, n = asInteger (prop2 (o, k1, k2))) => (isNumber (n)          ? n                         : $default)
    , safeIntegerProduct2: (o, k1, k2, $factor, $default, n = asInteger (prop2 (o, k1, k2))) => (isNumber (n)          ? parseInt (n) * $factor    : $default)
    , safeTimestamp2:      (o, k1, k2,          $default, n = asInteger (prop2 (o, k1, k2))) => (isNumber (n)          ? parseInt (n * 1000)       : $default)
    , safeValue2:          (o, k1, k2,          $default, x =            prop2 (o, k1, k2))  => (hasProps (x)          ? x                         : $default)
    , safeString2:         (o, k1, k2,          $default, x =            prop2 (o, k1, k2))  => (isStringCoercible (x) ? String (x)                : $default)
    , safeStringLower2:    (o, k1, k2,          $default, x =            prop2 (o, k1, k2))  => (isStringCoercible (x) ? String (x).toLowerCase () : $default)
    , safeStringUpper2:    (o, k1, k2,          $default, x =            prop2 (o, k1, k2))  => (isStringCoercible (x) ? String (x).toUpperCase () : $default)

}

/*  ------------------------------------------------------------------------ */
<|endoftext|>


<commit_before>$(function() {
  var indexWords, searchWord, words = {}, lewisShortDir = '../lewis-short/'
  function setLoading(loading) {
    $('#dictionary .content').text(loading? 'Loading '+loading+'...' : '');
  }
  setLoading('word index');
  $.getJSON(lewisShortDir + '-.json', function(data) {
    indexWords = data;
    setLoading(false);
    if(searchWord) search(searchWord);
  });
  $('#search').keyup(function(e){
    var word = $(this).val().toLowerCase();
    if(word == searchWord) return;
    search(word);
  });
  $(document).on('click', 'a[show-word]', function(e){
    e.preventDefault();
    $('#search').val($(this).text()).keyup();
  })
  function hashChanged() {
    var word = location.hash.slice(1);
    if(word && word != searchWord) {
      $('#search').val(word).keyup();
    }
  }
  $(window).on('hashchange',hashChanged);
  hashChanged();
  hashChanged();
  function search(word) {
    if(!word) return;
    location.hash = searchWord = word;
    if(!indexWords) return;
    var index = lookup(word, indexWords);
    displayWord(word, index);
  }
  function lookup(word, list) {
    if(word != searchWord || !list) return;
    var words = list.slice();
    words.push(word);
    words.sort();
    var index = words.lastIndexOf(word);
    return index - 1;
  }
  function getWordIndex(indexWord, word, callback) {
    $.getJSON(lewisShortDir + indexWord + '.json', function(data) {
      words[indexWord] = data;
      if(word == searchWord) callback(data);
    });
  }
  function displayWord(word, index) {
    var indexWord = indexWords[index];
    if(indexWord in words) {
      var dictionary = words[indexWord];
      var wordList = Object.keys(dictionary);
      var myIndex = lookup(word, wordList);
      wordList.sort();
      var prev = wordList[myIndex],
          curr = prev,
          next = wordList[myIndex + 1] || indexWords[index + 1] || '';
      if(prev == word) {
        if(myIndex == 0) {
          if(index > 0) {
            getWordIndex(indexWords[index - 1], word, function(data) {
              var keys = Object.keys(data);
              keys.sort();
              $('#navigation a.previous').attr('href','').text(keys.slice(-1)[0]);
            });
            prev = 'Loading...'
          } else {
            prev = '';
          }
        } else { // previous == word, myIndex > 0
          prev = wordList[myIndex - 1];
        }
      }
      var entry = words[indexWord][curr];
      var html = '';
      if(curr == word) {
        if(entry.length > 1) html = '(' + entry.length + ' entries)';
      } else {
        html = '(' + word + ' was not found)';
      }
      $('#search-info').html(html);
      html = '';
      if(prev) html += ' Previous Entry: ' + prev + '';
      if(next) html += ', Next Entry: ' + next + '';
      $('#navigation').html(html);
      $('.panel-title').text(curr);
      $('#dictionary .previous').text(prev);
      $('#dictionary .next').text(next);
      $('#dictionary .content').html(entry.join('
').replace(/v\.\s+(?!(irreg|dep)\.)([a-z]{2,})\./g, function(match, word){
        return 'v. ' + word + '.';
      }).replace(/([āēīōūȳ])\^/gi, function(match, vowel) {
        return vowel + '\u0306'; // combining breve (˘)
      }).replace(/([ăĕĭŏŭ])_/gi, function(match, vowel) {
        return vowel + '\u0304'; // combining macron (¯)
      }));
      $('#dictionary .content foreign[lang=greek]').each(function() {
        var $this = $(this);
        $this.text(betaCodeToGreek($this.text()));
      });
    } else {
      setLoading(indexWord+'-'+(indexWords[index+1]||''));
      getWordIndex(indexWord, word, function() {
        displayWord(word, index);
      });
    }
  }
})<commit_msg>Fixed a bug with the v. word. replacements<commit_after>$(function() {
  var indexWords, searchWord, words = {}, lewisShortDir = '../lewis-short/'
  function setLoading(loading) {
    $('#dictionary .content').text(loading? 'Loading '+loading+'...' : '');
  }
  setLoading('word index');
  $.getJSON(lewisShortDir + '-.json', function(data) {
    indexWords = data;
    setLoading(false);
    if(searchWord) search(searchWord);
  });
  $('#search').keyup(function(e){
    var word = $(this).val().toLowerCase();
    if(word == searchWord) return;
    search(word);
  });
  $(document).on('click', 'a[show-word]', function(e){
    e.preventDefault();
    $('#search').val($(this).text()).keyup();
  })
  function hashChanged() {
    var word = location.hash.slice(1);
    if(word && word != searchWord) {
      $('#search').val(word).keyup();
    }
  }
  $(window).on('hashchange',hashChanged);
  hashChanged();
  hashChanged();
  function search(word) {
    if(!word) return;
    location.hash = searchWord = word;
    if(!indexWords) return;
    var index = lookup(word, indexWords);
    displayWord(word, index);
  }
  function lookup(word, list) {
    if(word != searchWord || !list) return;
    var words = list.slice();
    words.push(word);
    words.sort();
    var index = words.lastIndexOf(word);
    return index - 1;
  }
  function getWordIndex(indexWord, word, callback) {
    $.getJSON(lewisShortDir + indexWord + '.json', function(data) {
      words[indexWord] = data;
      if(word == searchWord) callback(data);
    });
  }
  function displayWord(word, index) {
    var indexWord = indexWords[index];
    if(indexWord in words) {
      var dictionary = words[indexWord];
      var wordList = Object.keys(dictionary);
      var myIndex = lookup(word, wordList);
      wordList.sort();
      var prev = wordList[myIndex],
          curr = prev,
          next = wordList[myIndex + 1] || indexWords[index + 1] || '';
      if(prev == word) {
        if(myIndex == 0) {
          if(index > 0) {
            getWordIndex(indexWords[index - 1], word, function(data) {
              var keys = Object.keys(data);
              keys.sort();
              $('#navigation a.previous').attr('href','').text(keys.slice(-1)[0]);
            });
            prev = 'Loading...'
          } else {
            prev = '';
          }
        } else { // previous == word, myIndex > 0
          prev = wordList[myIndex - 1];
        }
      }
      var entry = words[indexWord][curr];
      var html = '';
      if(curr == word) {
        if(entry.length > 1) html = '(' + entry.length + ' entries)';
      } else {
        html = '(' + word + ' was not found)';
      }
      $('#search-info').html(html);
      html = '';
      if(prev) html += ' Previous Entry: ' + prev + '';
      if(next) html += ', Next Entry: ' + next + '';
      $('#navigation').html(html);
      $('.panel-title').text(curr);
      $('#dictionary .previous').text(prev);
      $('#dictionary .next').text(next);
      $('#dictionary .content').html(entry.join('
').replace(/v\.\s+(?!(?:irreg|dep)\.)([a-z]{2,})\./g, function(match, word){
        return 'v. ' + word + '.';
      }).replace(/([āēīōūȳ])\^/gi, function(match, vowel) {
        return vowel + '\u0306'; // combining breve (˘)
      }).replace(/([ăĕĭŏŭ])_/gi, function(match, vowel) {
        return vowel + '\u0304'; // combining macron (¯)
      }));
      $('#dictionary .content foreign[lang=greek]').each(function() {
        var $this = $(this);
        $this.text(betaCodeToGreek($this.text()));
      });
    } else {
      setLoading(indexWord+'-'+(indexWords[index+1]||''));
      getWordIndex(indexWord, word, function() {
        displayWord(word, index);
      });
    }
  }
})<|endoftext|>


<commit_before>import { vec3 } from 'gl-matrix';
import { gltfCamera } from './camera.js';
import { jsToGl, clamp } from './utils.js';
import { getSceneExtents } from './gltf_utils.js';

const VecZero = vec3.create();
const PanSpeedDenominator = 1200;
const MaxNearFarRatio = 10000;

class UserCamera extends gltfCamera
{
    constructor(
        target = [0, 0, 0],
        xRot = 0,
        yRot = 0,
        zoom = 1)
    {
        super();

        this.target = jsToGl(target);
        this.xRot = xRot;
        this.yRot = yRot;
        this.zoom = zoom;
        this.zoomFactor = 1.04;
        this.rotateSpeed = 1 / 180;
        this.panSpeed = 1;
        this.sceneExtents = {
            min: vec3.create(),
            max: vec3.create()
        };
    }

    getPosition()
    {
        // calculate direction from focus to camera (assuming camera is at positive z)
        // yRot rotates *around* x-axis, xRot rotates *around* y-axis
        const direction = vec3.fromValues(0, 0, this.zoom);
        this.toLocalRotation(direction);

        const position = vec3.create();
        vec3.add(position, this.target, direction);
        return position;
    }

    lookAt(from, to)
    {
        // up is implicitly (0, 1, 0)
        this.target = to;

        const difference = vec3.create();
        vec3.subtract(difference, from, to);
        const projectedDifference = vec3.fromValues(from[0] - to[0], 0, from[2] - to[2]);

        this.yRot = vec3.angle(difference, projectedDifference);
        this.xRot = vec3.angle(projectedDifference, vec3.fromValues(1.0, 0.0, 0.0));
        this.zoom = vec3.length(difference);
    }

    setRotation(yaw, pitch)
    {
        // Rotates target instead of position

        const difference = vec3.create();
        vec3.subtract(difference, this.target, this.position);

        vec3.rotateY(difference, difference, VecZero, -yaw * this.rotateSpeed);
        vec3.rotateX(difference, difference, VecZero, -pitch * this.rotateSpeed);

        vec3.add(this.target, this.position, difference);
    }

    reset(gltf, sceneIndex)
    {
        this.xRot = 0;
        this.yRot = 0;
        this.fitViewToScene(gltf, sceneIndex, true);
    }

    zoomBy(value)
    {
        if (value > 0)
        {
            this.zoom *= this.zoomFactor;
        }
        else
        {
            this.zoom /= this.zoomFactor;
        }
        this.fitCameraPlanesToExtents(this.sceneExtents.min, this.sceneExtents.max);
    }

    orbit(x, y)
    {
        const yMax = Math.PI / 2 - 0.01;
        this.xRot += (x * this.rotateSpeed);
        this.yRot += (y * this.rotateSpeed);
        this.yRot = clamp(this.yRot, -yMax, yMax);

        // const difference = vec3.create();
        // vec3.subtract(difference, this.position, this.target);

        // vec3.rotateY(difference, difference, VecZero, -x * this.rotateSpeed);
        // vec3.rotateX(difference, difference, VecZero, -y * this.rotateSpeed);

        // vec3.add(this.position, this.target, difference);
    }

    pan(x, y)
    {
        const left = vec3.fromValues(-1, 0, 0);
        this.toLocalRotation(left);
        vec3.scale(left, left, x * this.panSpeed);

        const up = vec3.fromValues(0, 1, 0);
        this.toLocalRotation(up);
        vec3.scale(up, up, y * this.panSpeed);

        vec3.add(this.target, this.target, up);
        vec3.add(this.target, this.target, left);
    }

    fitPanSpeedToScene(min, max)
    {
        const longestDistance = vec3.distance(min, max);
        this.panSpeed = longestDistance / PanSpeedDenominator;
    }

    fitViewToScene(gltf, sceneIndex)
    {
        getSceneExtents(gltf, sceneIndex, this.sceneExtents.min, this.sceneExtents.max);
        this.fitCameraTargetToExtents(this.sceneExtents.min, this.sceneExtents.max);
        this.fitZoomToExtents(this.sceneExtents.min, this.sceneExtents.max);

        const direction = vec3.fromValues(0, 0, this.zoom);
        vec3.add(this.getPosition(), this.target, direction);

        this.fitPanSpeedToScene(this.sceneExtents.min, this.sceneExtents.max);
        this.fitCameraPlanesToExtents(this.sceneExtents.min, this.sceneExtents.max);
    }

    toLocalRotation(vector)
    {
        vec3.rotateX(vector, vector, VecZero, -this.yRot);
        vec3.rotateY(vector, vector, VecZero, -this.xRot);
    }

    getLookAtTarget()
    {
        return this.target;
    }

    fitZoomToExtents(min, max)
    {
        const maxAxisLength = Math.max(max[0] - min[0], max[1] - min[1]);
        this.zoom = this.getFittingZoom(maxAxisLength);
    }

    fitCameraTargetToExtents(min, max)
    {
        for (const i of [0, 1, 2])
        {
            this.target[i] = (max[i] + min[i]) / 2;
        }
    }

    fitCameraPlanesToExtents(min, max)
    {
        // depends only on scene min/max and the camera zoom

        // Manually increase scene extent just for the camera planes to avoid camera clipping in most situations.
        const longestDistance = 10 * vec3.distance(min, max);
        let zNear = this.zoom - (longestDistance * 0.6);
        let zFar = this.zoom + (longestDistance * 0.6);

        // minimum near plane value needs to depend on far plane value to avoid z fighting or too large near planes
        zNear = Math.max(zNear, zFar / MaxNearFarRatio);

        this.znear = zNear;
        this.zfar = zFar;
    }

    getFittingZoom(axisLength)
    {
        const yfov = this.yfov;
        const xfov = this.yfov * this.aspectRatio;

        const yZoom = axisLength / 2 / Math.tan(yfov / 2);
        const xZoom = axisLength / 2 / Math.tan(xfov / 2);

        return Math.max(xZoom, yZoom);
    }
}

export { UserCamera };
<commit_msg>implement setPosition, setTarget, setZoom<commit_after>import { vec3 } from 'gl-matrix';
import { gltfCamera } from './camera.js';
import { jsToGl, clamp } from './utils.js';
import { getSceneExtents } from './gltf_utils.js';

const VecZero = vec3.create();
const PanSpeedDenominator = 1200;
const MaxNearFarRatio = 10000;

class UserCamera extends gltfCamera
{
    constructor(
        target = [0, 0, 0],
        xRot = 0,
        yRot = 0,
        zoom = 1)
    {
        super();

        this.target = jsToGl(target);
        this.xRot = xRot;
        this.yRot = yRot;
        this.zoom = zoom;
        this.zoomFactor = 1.04;
        this.rotateSpeed = 1 / 180;
        this.panSpeed = 1;
        this.sceneExtents = {
            min: vec3.create(),
            max: vec3.create()
        };
    }

    getPosition()
    {
        // calculate direction from focus to camera (assuming camera is at positive z)
        // yRot rotates *around* x-axis, xRot rotates *around* y-axis
        const direction = vec3.fromValues(0, 0, this.zoom);
        this.toLocalRotation(direction);

        const position = vec3.create();
        vec3.add(position, this.target, direction);
        return position;
    }

    lookAt(from, to)
    {
        // up is implicitly (0, 1, 0)
        this.target = to;

        const difference = vec3.create();
        vec3.subtract(difference, from, to);
        const projectedDifference = vec3.fromValues(from[0] - to[0], 0, from[2] - to[2]);

        this.yRot = vec3.angle(difference, projectedDifference);
        this.xRot = vec3.angle(projectedDifference, vec3.fromValues(1.0, 0.0, 0.0));
        this.zoom = vec3.length(difference);
    }

    setPosition(position)
    {
        this.lookAt(position, this.target);
    }

    setTarget(target)
    {
        this.lookAt(target, this.getPosition());
    }

    setRotation(yaw, pitch)
    {
        // Rotates target instead of position

        const difference = vec3.create();
        vec3.subtract(difference, this.target, this.position);

        vec3.rotateY(difference, difference, VecZero, -yaw * this.rotateSpeed);
        vec3.rotateX(difference, difference, VecZero, -pitch * this.rotateSpeed);

        vec3.add(this.target, this.position, difference);
    }

    setZoom(zoom)
    {
        this.zoom = zoom;
    }

    reset(gltf, sceneIndex)
    {
        this.xRot = 0;
        this.yRot = 0;
        this.fitViewToScene(gltf, sceneIndex, true);
    }

    zoomBy(value)
    {
        if (value > 0)
        {
            this.zoom *= this.zoomFactor;
        }
        else
        {
            this.zoom /= this.zoomFactor;
        }
        this.fitCameraPlanesToExtents(this.sceneExtents.min, this.sceneExtents.max);
    }

    orbit(x, y)
    {
        const yMax = Math.PI / 2 - 0.01;
        this.xRot += (x * this.rotateSpeed);
        this.yRot += (y * this.rotateSpeed);
        this.yRot = clamp(this.yRot, -yMax, yMax);

        // const difference = vec3.create();
        // vec3.subtract(difference, this.position, this.target);

        // vec3.rotateY(difference, difference, VecZero, -x * this.rotateSpeed);
        // vec3.rotateX(difference, difference, VecZero, -y * this.rotateSpeed);

        // vec3.add(this.position, this.target, difference);
    }

    pan(x, y)
    {
        const left = vec3.fromValues(-1, 0, 0);
        this.toLocalRotation(left);
        vec3.scale(left, left, x * this.panSpeed);

        const up = vec3.fromValues(0, 1, 0);
        this.toLocalRotation(up);
        vec3.scale(up, up, y * this.panSpeed);

        vec3.add(this.target, this.target, up);
        vec3.add(this.target, this.target, left);
    }

    fitPanSpeedToScene(min, max)
    {
        const longestDistance = vec3.distance(min, max);
        this.panSpeed = longestDistance / PanSpeedDenominator;
    }

    fitViewToScene(gltf, sceneIndex)
    {
        getSceneExtents(gltf, sceneIndex, this.sceneExtents.min, this.sceneExtents.max);
        this.fitCameraTargetToExtents(this.sceneExtents.min, this.sceneExtents.max);
        this.fitZoomToExtents(this.sceneExtents.min, this.sceneExtents.max);

        const direction = vec3.fromValues(0, 0, this.zoom);
        vec3.add(this.getPosition(), this.target, direction);

        this.fitPanSpeedToScene(this.sceneExtents.min, this.sceneExtents.max);
        this.fitCameraPlanesToExtents(this.sceneExtents.min, this.sceneExtents.max);
    }

    toLocalRotation(vector)
    {
        vec3.rotateX(vector, vector, VecZero, -this.yRot);
        vec3.rotateY(vector, vector, VecZero, -this.xRot);
    }

    getLookAtTarget()
    {
        return this.target;
    }

    fitZoomToExtents(min, max)
    {
        const maxAxisLength = Math.max(max[0] - min[0], max[1] - min[1]);
        this.zoom = this.getFittingZoom(maxAxisLength);
    }

    fitCameraTargetToExtents(min, max)
    {
        for (const i of [0, 1, 2])
        {
            this.target[i] = (max[i] + min[i]) / 2;
        }
    }

    fitCameraPlanesToExtents(min, max)
    {
        // depends only on scene min/max and the camera zoom

        // Manually increase scene extent just for the camera planes to avoid camera clipping in most situations.
        const longestDistance = 10 * vec3.distance(min, max);
        let zNear = this.zoom - (longestDistance * 0.6);
        let zFar = this.zoom + (longestDistance * 0.6);

        // minimum near plane value needs to depend on far plane value to avoid z fighting or too large near planes
        zNear = Math.max(zNear, zFar / MaxNearFarRatio);

        this.znear = zNear;
        this.zfar = zFar;
    }

    getFittingZoom(axisLength)
    {
        const yfov = this.yfov;
        const xfov = this.yfov * this.aspectRatio;

        const yZoom = axisLength / 2 / Math.tan(yfov / 2);
        const xZoom = axisLength / 2 / Math.tan(xfov / 2);

        return Math.max(xZoom, yZoom);
    }
}

export { UserCamera };
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011 Andr Mekkawi <contact@andremekkawi.com>
 *
 * LICENSE
 *
 * This source file is subject to the MIT license in the file LICENSE.txt.
 * The license is also available at http://diskusagereport.sf.net/license.html
 */

;(function($) {

$.widget("ui.dialog", {

	options: {
		opening: null,
		opened: null,
		closed: null,
		title: null,
		roundedBorders: true,
		shadow: true,
		closeButton: true,
		dimmer: true,
		borderColor: null,
		backgroundColor: null,
		titleColor: null,
		textColor: null,
		borderSize: 10
	},

	_create: function() {
		var self = this,
			$elem = $(this.element).addClass(this.widgetBaseClass).hide();

		this._parent = $elem.parent();

		this._contents = $elem
			.wrapInner('
')
			.children().first();

		this._scroller = this._contents.wrap('
').parent();

		$elem.scrollerResize({ scroller: this._scroller });

		$('
').appendTo(this._scroller);

		this._title = $('
').insertBefore(this._scroller);

		this._close = $('
')
			.click(function(){ self.close(); })
			.appendTo($elem);

		this._dimmer = $('#' + this.widgetBaseClass + '-dimmer');

		if (this._dimmer.size() == 0)
			this._dimmer = $('
').attr('id', this.widgetBaseClass + '-dimmer').appendTo('body');

		$('#' + this.widgetBaseClass + '-dimmer').live('click', function() { if (self.options.dimmer) self.close(); });

		for (var key in this.options) {
			this._processOption(key, this.options[key]);
		}
	},

	option: function(key, value) {
		var $elem = $(this.element);

		if (key == "parent") value = $(value);

		if (this._processOption(key, value))
			$.Widget.prototype.option.call(this, key, value);
	},

	_processOption: function(key, value) {
		var $elem = $(this.element);

		switch (key) {
			case 'parent':
				if (!value.isParentOf($elem)) return false;
				break;

			case 'title':
				if ($.isString(value) && value.length > 0)
					this._title.text(value).show();
				else
					this._title.text('').hide();

				this.resize();
				break;

			case 'roundedBorders':
				$elem[value ? 'addClass' : 'removeClass'](this.widgetBaseClass + '-has-rounded-borders');
				break;

			case 'shadow':
				$elem[value ? 'addClass' : 'removeClass'](this.widgetBaseClass + '-has-shadow');
				break;

			case 'closeButton':
				this._close[value ? 'show' : 'hide']();
				break;

			case 'borderSize':
				if (!$.isNumber(value)) return false;
				$elem.css('border-width', value);
				this._close.css({ top: (-10 - value) + 'px', right: (-10 - value) + 'px' });
				this.resize();
				break;

			case 'borderColor':
				if (!$.isString(value)) return false;
				$elem.css('border-color', value);
				this._title.css('background-color', value);
				break;

			case 'backgroundColor':
				if (!$.isString(value)) return false;
				$elem.css('background-color', value);
				break;

			case 'titleColor':
				if (!$.isString(value)) return false;
				this._title.css('color', value);
				break;

			case 'textColor':
				if (!$.isString(value)) return false;
				this._contents.css('color', value);
				break;
		}

		return true;
	},

	open: function() {
		var self = this, $elem = $(this.element);

		this._trigger('opening', null, [ this._contents ]);

		$elem.css({ left: '-100000px', top:  '-100000px' }).show();
		this.resize();

		if (this.options.dimmer)
			this._dimmer.show();

		this._trigger('opened');
	},

	close: function() {
		$(this.element).hide();
		if (this.options.dimmer) this._dimmer.hide();
		this._trigger('closed');
	},

	resize: function() {
		var $elem = $(this.element);

		if ($elem.is(':visible'))
			$elem.scrollerResize('resize', true);
	},

	contents: function(contents) {
		if (contents) {
			this._contents.html(contents);
			this.resize();
		}
		else {
			return this._contents;
		}
	}
});

})(jQuery);<commit_msg>* Dialog's resize method makes sure the scroller is not smaller than the width of the dialog.<commit_after>/*
 * Copyright (c) 2011 Andr Mekkawi <contact@andremekkawi.com>
 *
 * LICENSE
 *
 * This source file is subject to the MIT license in the file LICENSE.txt.
 * The license is also available at http://diskusagereport.sf.net/license.html
 */

;(function($) {

$.widget("ui.dialog", {

	options: {
		opening: null,
		opened: null,
		closed: null,
		title: null,
		roundedBorders: true,
		shadow: true,
		closeButton: true,
		dimmer: true,
		borderColor: null,
		backgroundColor: null,
		titleColor: null,
		textColor: null,
		borderSize: 10
	},

	_create: function() {
		var self = this,
			$elem = $(this.element).addClass(this.widgetBaseClass).hide();

		this._parent = $elem.parent();

		this._contents = $elem
			.wrapInner('
')
			.children().first();

		this._scroller = this._contents.wrap('
').parent();

		$elem.scrollerResize({ scroller: this._scroller });

		$('
').appendTo(this._scroller);

		this._title = $('
').insertBefore(this._scroller);

		this._close = $('
')
			.click(function(){ self.close(); })
			.appendTo($elem);

		this._dimmer = $('#' + this.widgetBaseClass + '-dimmer');

		if (this._dimmer.size() == 0)
			this._dimmer = $('
').attr('id', this.widgetBaseClass + '-dimmer').appendTo('body');

		$('#' + this.widgetBaseClass + '-dimmer').live('click', function() { if (self.options.dimmer) self.close(); });

		for (var key in this.options) {
			this._processOption(key, this.options[key]);
		}
	},

	option: function(key, value) {
		var $elem = $(this.element);

		if (key == "parent") value = $(value);

		if (this._processOption(key, value))
			$.Widget.prototype.option.call(this, key, value);
	},

	_processOption: function(key, value) {
		var $elem = $(this.element);

		switch (key) {
			case 'parent':
				if (!value.isParentOf($elem)) return false;
				break;

			case 'title':
				if ($.isString(value) && value.length > 0)
					this._title.text(value).show();
				else
					this._title.text('').hide();

				this.resize();
				break;

			case 'roundedBorders':
				$elem[value ? 'addClass' : 'removeClass'](this.widgetBaseClass + '-has-rounded-borders');
				break;

			case 'shadow':
				$elem[value ? 'addClass' : 'removeClass'](this.widgetBaseClass + '-has-shadow');
				break;

			case 'closeButton':
				this._close[value ? 'show' : 'hide']();
				break;

			case 'borderSize':
				if (!$.isNumber(value)) return false;
				$elem.css('border-width', value);
				this._close.css({ top: (-10 - value) + 'px', right: (-10 - value) + 'px' });
				this.resize();
				break;

			case 'borderColor':
				if (!$.isString(value)) return false;
				$elem.css('border-color', value);
				this._title.css('background-color', value);
				break;

			case 'backgroundColor':
				if (!$.isString(value)) return false;
				$elem.css('background-color', value);
				break;

			case 'titleColor':
				if (!$.isString(value)) return false;
				this._title.css('color', value);
				break;

			case 'textColor':
				if (!$.isString(value)) return false;
				this._contents.css('color', value);
				break;
		}

		return true;
	},

	open: function() {
		var self = this, $elem = $(this.element);

		this._trigger('opening', null, [ this._contents ]);

		$elem.css({ left: '-100000px', top:  '-100000px' }).show();
		this.resize();

		if (this.options.dimmer)
			this._dimmer.show();

		this._trigger('opened');
	},

	close: function() {
		$(this.element).hide();
		if (this.options.dimmer) this._dimmer.hide();
		this._trigger('closed');
	},

	resize: function() {
		var $elem = $(this.element);

		if (!$elem.is(':visible')) return;

		$elem.scrollerResize('resize', true);

		var scrollerWidth = this._scroller.outerWidth(true),
			scrollerDiff = scrollerWidth - this._scroller.width(),
			min = $elem.width();

		if (scrollerWidth < min) {
			this._scroller.width(min);
		}
	},

	contents: function(contents) {
		if (contents) {
			this._contents.html(contents);
			this.resize();
		}
		else {
			return this._contents;
		}
	}
});

})(jQuery);<|endoftext|>


<commit_before>var SYSTEM = require("system");
var FILE = require("file");
var OS = require("os");
var UTIL = require("narwhal/util");
var stream = require("narwhal/term").stream;

var requiresSudo = false;

SYSTEM.args.slice(1).forEach(function(arg){
    if (arg === "sudo-install")
        requiresSudo = true;
});

function ensurePackageUpToDate(packageName, requiredVersion, options)
{
    options = options || {};

    var packageInfo = require("narwhal/packages").catalog[packageName];
    if (!packageInfo)
    {
        if (options.optional)
            return;

        print("You are missing package \"" + packageName + "\", version " + requiredVersion + " or later. Please install using \"tusk install "+packageName+"\" and re-run jake");
        OS.exit(1);
    }

    var version = packageInfo.version;
    if (typeof version === "string")
        version = version.split(".");

    if (typeof requiredVersion === "string")
        requiredVersion = requiredVersion.split(".");

    if (version && UTIL.compare(version, requiredVersion) !== -1)
        return;

    print("Your copy of " + packageName + " is out of date (" + (version||["0"]).join(".") + " installed, " + requiredVersion.join(".") + " required).");

    if (!options.noupdate)
    {
        print("Update? yes or no:");
        if (!SYSTEM.env["CAPP_AUTO_UPGRADE"] && system.stdin.readLine() !== "yes\n")
        {
            print("Jake aborted.");
            OS.exit(1);
        }

        if (requiresSudo)
        {
            if (OS.system(["sudo", "tusk", "install", "--force", packageName]))
            {
                // Attempt a hackish work-around for sudo compiled with the --with-secure-path option
                if (OS.system("sudo bash -c 'source " + getShellConfigFile() + "; tusk install --force "+packageName))
                    OS.exit(1); //rake abort if ($? != 0)
            }
        }
        else
            OS.system(["tusk", "install", "--force", packageName]);
    }

    if (options.message)
    {
        print(options.message)
        OS.exit(1);
    }
}

// UPDATE THESE TO PICK UP CORRESPONDING CHANGES IN DEPENDENCIES
ensurePackageUpToDate("jake",           "0.1.5");
ensurePackageUpToDate("browserjs",      "0.1.1");
ensurePackageUpToDate("shrinksafe",     "0.2");
ensurePackageUpToDate("narwhal",        "0.2.2", {
    noupdate : true,
    message : "Update Narwhal to 0.2.1 by running bootstrap.sh, or pulling the latest from git (see: http://github.com/280north/narwhal)."
});
ensurePackageUpToDate("narwhal-jsc",    "0.1.1", {
    optional : true,
    message : "Rebuild narwhal-jsc by changing to the narwhal-jsc package directory and running \"make webkit\"."
});

var JAKE = require("jake");

// Set up development environment variables.

// record the initial SYSTEM.env so we know which need to be serialized later
var envInitial = Object.freeze(UTIL.copy(SYSTEM.env));

SYSTEM.env["BUILD_PATH"] = FILE.absolute(
    SYSTEM.env["BUILD_PATH"] ||
    SYSTEM.env["CAPP_BUILD"] || // Global Cappuccino build directory.
    SYSTEM.env["STEAM_BUILD"] || // Maintain backwards compatibility with steam.
    FILE.join(FILE.dirname(module.path), "Build") // Just build here.
);

if (!SYSTEM.env["CAPP_BUILD"] && SYSTEM.env["STEAM_BUILD"])
    system.stderr.print("STEAM_BUILD environment variable is deprecated; Please use CAPP_BUILD instead.");

if (!SYSTEM.env["CONFIG"])
    SYSTEM.env["CONFIG"] = "Release";

global.ENV  = SYSTEM.env;
global.ARGV = SYSTEM.args
global.FILE = FILE;
global.OS   = OS;

global.task = JAKE.task;
global.directory = JAKE.directory;
global.file = JAKE.file;
global.filedir = JAKE.filedir;
global.FileList = JAKE.FileList;

global.$CONFIGURATION                   = SYSTEM.env['CONFIG'];
global.$BUILD_DIR                       = SYSTEM.env['BUILD_PATH'];
global.$BUILD_CONFIGURATION_DIR         = FILE.join($BUILD_DIR, $CONFIGURATION);

global.$BUILD_CJS_OBJECTIVE_J           = FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "objective-j");

global.$BUILD_CJS_CAPPUCCINO            = FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "cappuccino");
global.$BUILD_CJS_CAPPUCCINO_BIN        = FILE.join($BUILD_CJS_CAPPUCCINO, "bin");
global.$BUILD_CJS_CAPPUCCINO_LIB        = FILE.join($BUILD_CJS_CAPPUCCINO, "lib");
global.$BUILD_CJS_CAPPUCCINO_FRAMEWORKS = FILE.join($BUILD_CJS_CAPPUCCINO, "Frameworks");

global.CLEAN = require("jake/clean").CLEAN;
global.CLOBBER = require("jake/clean").CLOBBER;
global.CLEAN.include(global.$BUILD_DIR);
global.CLOBBER.include(global.$BUILD_DIR);

global.$HOME_DIR        = FILE.absolute(FILE.dirname(module.path));
global.$LICENSE_FILE    = FILE.absolute(FILE.join(FILE.dirname(module.path), 'LICENSE'));

global.FIXME_fileDependency = function(destinationPath, sourcePath)
{
    file(destinationPath, [sourcePath], function(){
        FILE.touch(destinationPath);
    });
};

// logic to determine which packages should be loaded but are not.
// used in serializedENV()
function additionalPackages()
{
    var builtObjectiveJPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "objective-j", "");
    var builtCappuccinoPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "cappuccino", "");

    var packages = [];

    // load built objective-j if exists, otherwise unbuilt
    if (builtObjectiveJPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtObjectiveJPackage))
            packages.push(builtObjectiveJPackage);
    }

    // load built cappuccino if it exists
    if (builtCappuccinoPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtCappuccinoPackage))
            packages.push(builtCappuccinoPackage);
    }

    return packages;
}

// checks to see if a path is in the package catalog
function packageInCatalog(path)
{
    var catalog = require("narwhal/packages").catalog;
    for (var name in catalog)
        if (String(catalog[name].directory) === String(path))
            return true;
    return false;
}

serializedENV = function()
{
    var envNew = {};

    // add changed keys to the new ENV
    Object.keys(SYSTEM.env).forEach(function(key) {
        if (SYSTEM.env[key] !== envInitial[key])
            envNew[key] = SYSTEM.env[key];
    });

    // pseudo-HACK: add NARWHALOPT with packages we should ensure are loaded
    var packages = additionalPackages();
    if (packages.length) {
        envNew["NARWHALOPT"] = packages.map(function(p) { return "-p " + OS.enquote(p); }).join(" ");
        envNew["PATH"] = packages.map(function(p) { return FILE.join(p, "bin"); }).concat(SYSTEM.env["PATH"]).join(":");
    }

    return Object.keys(envNew).map(function(key) {
        return key + "=" + OS.enquote(envNew[key]);
    }).join(" ");
}

function reforkWithPackages()
{
    if (additionalPackages().length > 0) {
        var cmd = serializedENV() + " " + system.args.map(OS.enquote).join(" ");
        //print("REFORKING: " + cmd);
        OS.exit(OS.system(cmd));
    }
}

reforkWithPackages();

function handleSetupEnvironmentError(e) {
    if (String(e).indexOf("require error")==-1) {
        print("setupEnvironment warning: " + e);
        //throw e;
    }
}

function setupEnvironment()
{
    try {
        require("objective-j").OBJJ_INCLUDE_PATHS.push(FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "cappuccino", "Frameworks"));
    } catch (e) {
        handleSetupEnvironmentError(e);
    }
}

setupEnvironment();

global.rm_rf = function(/*String*/ aFilename)
{
    try { FILE.rmtree(aFilename); }
    catch (anException) { }
}

global.cp_r = function(/*String*/ from, /*String*/ to)
{
    if (FILE.exists(to))
        rm_rf(to);

    if (FILE.isDirectory(from))
        FILE.copyTree(from, to);
    else{try{
        FILE.copy(from, to);}catch(e) { print(e + FILE.exists(from) + " " + FILE.exists(FILE.dirname(to))); }}
}

global.cp = function(/*String*/ from, /*String*/ to)
{
    FILE.copy(from, to);
//    FILE.chmod(to, FILE.mod(from));
}

global.mv = function(/*String*/ from, /*String*/ to)
{
    FILE.move(from, to);
}

global.subjake = function(/*Array<String>*/ directories, /*String*/ aTaskName)
{
    if (!Array.isArray(directories))
        directories = [directories];

    directories.forEach(function(/*String*/ aDirectory)
    {
        if (FILE.isDirectory(aDirectory) && FILE.isFile(FILE.join(aDirectory, "Jakefile")))
        {
            var cmd = "cd " + OS.enquote(aDirectory) + " && " + serializedENV() + " " + OS.enquote(SYSTEM.args[0]) + " " + OS.enquote(aTaskName);
            var returnCode = OS.system(cmd);
            if (returnCode)
                OS.exit(returnCode);
        }
        else
            print("warning: subjake missing: " + aDirectory + " (this is not necessarily an error, " + aDirectory + " may be optional)");
    });
}

global.executableExists = function(/*String*/ executableName)
{
    var paths = SYSTEM.env["PATH"].split(':');
    for (var i = 0; i < paths.length; i++) {
        var path = FILE.join(paths[i], executableName);
        if (FILE.exists(path))
            return path;
    }
    return null;
}

$OBJJ_TEMPLATE_EXECUTABLE = FILE.join($HOME_DIR, "Objective-J", "CommonJS", "objj-executable");

global.make_objj_executable = function(aPath)
{
    cp($OBJJ_TEMPLATE_EXECUTABLE, aPath);
    FILE.chmod(aPath, 0755);
}

global.symlink_executable = function(source)
{
    relative = FILE.relative($ENVIRONMENT_NARWHAL_BIN_DIR, source);
    destination = FILE.join($ENVIRONMENT_NARWHAL_BIN_DIR, FILE.basename(source));
    FILE.symlink(relative, destination);
}

global.getCappuccinoVersion = function() {
    var versionFile = FILE.path(module.path).dirname().join("version.json");
    return JSON.parse(versionFile.read({ charset : "UTF-8" })).version;
}

global.setPackageMetadata = function(packagePath) {
    var pkg = JSON.parse(FILE.read(packagePath, { charset : "UTF-8" }));

    var p = OS.popen(["git", "rev-parse", "--verify", "HEAD"]);
    if (p.wait() === 0) {
        var sha = p.stdout.read().split("\n")[0];
        if (sha.length === 40)
            pkg["cappuccino-revision"] = sha;
    }

    pkg["cappuccino-timestamp"] = new Date().getTime();
    pkg["version"] = getCappuccinoVersion();

    stream.print("    Version:   \0purple(" + pkg["version"] + "\0)");
    stream.print("    Revision:  \0purple(" + pkg["cappuccino-revision"] + "\0)");
    stream.print("    Timestamp: \0purple(" + pkg["cappuccino-timestamp"] + "\0)");

    FILE.write(packagePath, JSON.stringify(pkg, null, 4), { charset : "UTF-8" });
}

global.subtasks = function(subprojects, taskNames)
{
    taskNames.forEach(function(aTaskName)
    {
        var subtaskName = aTaskName + "_subprojects";

        task (aTaskName, [subtaskName]);

        task (subtaskName, function()
        {
            subjake(subprojects, aTaskName);
        });
    });
}

function spawnJake(/*String*/ aTaskName)
{
    if (OS.system(serializedENV() + " " + SYSTEM.args[0] + " " + aTaskName))
        OS.exit(1);//rake abort if ($? != 0)
}

// built in tasks

task ("build");
task ("default", "build");

task ("release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("build");
});

task ("debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("build");
});

task ("all", ["debug", "release"]);

task ("clean-debug", function()
{
    SYSTEM.env['CONFIG'] = 'Debug'
    spawnJake("clean");
});

task ("cleandebug", ["clean-debug"]);

task ("clean-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clean");
});

task ("cleanrelease", ["clean-release"]);

task ("clean-all", ["clean-debug", "clean-release"]);
task ("cleanall", ["clean-all"]);

task ("clobber-debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("clobber");
});

task ("clobberdebug", ["clobber-debug"]);

task ("clobber-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clobber");
});

task ("clobberrelease", ['clobber-release']);

task ("clobber-all", ["clobber-debug", "clobber-release"]);
task ("clobberall", ["clobber-all"]);
<commit_msg>Require latest versions of all package to eliminate deprecation warnings.<commit_after>var SYSTEM = require("system");
var FILE = require("file");
var OS = require("os");
var UTIL = require("narwhal/util");
var stream = require("narwhal/term").stream;

var requiresSudo = false;

SYSTEM.args.slice(1).forEach(function(arg){
    if (arg === "sudo-install")
        requiresSudo = true;
});

function ensurePackageUpToDate(packageName, requiredVersion, options)
{
    options = options || {};

    var packageInfo = require("narwhal/packages").catalog[packageName];
    if (!packageInfo)
    {
        if (options.optional)
            return;

        print("You are missing package \"" + packageName + "\", version " + requiredVersion + " or later. Please install using \"tusk install "+packageName+"\" and re-run jake");
        OS.exit(1);
    }

    var version = packageInfo.version;
    if (typeof version === "string")
        version = version.split(".");

    if (typeof requiredVersion === "string")
        requiredVersion = requiredVersion.split(".");

    if (version && UTIL.compare(version, requiredVersion) !== -1)
        return;

    print("Your copy of " + packageName + " is out of date (" + (version||["0"]).join(".") + " installed, " + requiredVersion.join(".") + " required).");

    if (!options.noupdate)
    {
        print("Update? Existing package will be overwritten. yes or no:");
        if (!SYSTEM.env["CAPP_AUTO_UPGRADE"] && system.stdin.readLine() !== "yes\n")
        {
            print("Jake aborted.");
            OS.exit(1);
        }

        if (requiresSudo)
        {
            if (OS.system(["sudo", "tusk", "install", "--force", packageName]))
            {
                // Attempt a hackish work-around for sudo compiled with the --with-secure-path option
                if (OS.system("sudo bash -c 'source " + getShellConfigFile() + "; tusk install --force "+packageName))
                    OS.exit(1); //rake abort if ($? != 0)
            }
        }
        else
            OS.system(["tusk", "install", "--force", packageName]);
    }

    if (options.after)
    {
        options.after(packageInfo.directory);
    }

    if (options.message)
    {
        print(options.message);
        OS.exit(1);
    }
}

// UPDATE THESE TO PICK UP CORRESPONDING CHANGES IN DEPENDENCIES
ensurePackageUpToDate("jake",           "0.3");
ensurePackageUpToDate("browserjs",      "0.1.1");
ensurePackageUpToDate("shrinksafe",     "0.2");
ensurePackageUpToDate("narwhal",        "0.3.1", {
    noupdate : true,
    message : "Update Narwhal by re-running bootstrap.sh, or pulling the latest from git (see: http://github.com/280north/narwhal)."
});
ensurePackageUpToDate("narwhal-jsc",    "0.3", {
    optional : true,
    after : function(dir) {
        if (OS.system("cd " + OS.enquote(dir) + " && make webkit")) {
            print("Problem building narwhal-jsc.");
            OS.exit(1);
        }
    }
});

var JAKE = require("jake");

// Set up development environment variables.

// record the initial SYSTEM.env so we know which need to be serialized later
var envInitial = Object.freeze(UTIL.copy(SYSTEM.env));

SYSTEM.env["BUILD_PATH"] = FILE.absolute(
    SYSTEM.env["BUILD_PATH"] ||
    SYSTEM.env["CAPP_BUILD"] || // Global Cappuccino build directory.
    SYSTEM.env["STEAM_BUILD"] || // Maintain backwards compatibility with steam.
    FILE.join(FILE.dirname(module.path), "Build") // Just build here.
);

if (!SYSTEM.env["CAPP_BUILD"] && SYSTEM.env["STEAM_BUILD"])
    system.stderr.print("STEAM_BUILD environment variable is deprecated; Please use CAPP_BUILD instead.");

if (!SYSTEM.env["CONFIG"])
    SYSTEM.env["CONFIG"] = "Release";

global.ENV  = SYSTEM.env;
global.ARGV = SYSTEM.args
global.FILE = FILE;
global.OS   = OS;

global.task = JAKE.task;
global.directory = JAKE.directory;
global.file = JAKE.file;
global.filedir = JAKE.filedir;
global.FileList = JAKE.FileList;

global.$CONFIGURATION                   = SYSTEM.env['CONFIG'];
global.$BUILD_DIR                       = SYSTEM.env['BUILD_PATH'];
global.$BUILD_CONFIGURATION_DIR         = FILE.join($BUILD_DIR, $CONFIGURATION);

global.$BUILD_CJS_OBJECTIVE_J           = FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "objective-j");

global.$BUILD_CJS_CAPPUCCINO            = FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "cappuccino");
global.$BUILD_CJS_CAPPUCCINO_BIN        = FILE.join($BUILD_CJS_CAPPUCCINO, "bin");
global.$BUILD_CJS_CAPPUCCINO_LIB        = FILE.join($BUILD_CJS_CAPPUCCINO, "lib");
global.$BUILD_CJS_CAPPUCCINO_FRAMEWORKS = FILE.join($BUILD_CJS_CAPPUCCINO, "Frameworks");

global.CLEAN = require("jake/clean").CLEAN;
global.CLOBBER = require("jake/clean").CLOBBER;
global.CLEAN.include(global.$BUILD_DIR);
global.CLOBBER.include(global.$BUILD_DIR);

global.$HOME_DIR        = FILE.absolute(FILE.dirname(module.path));
global.$LICENSE_FILE    = FILE.absolute(FILE.join(FILE.dirname(module.path), 'LICENSE'));

global.FIXME_fileDependency = function(destinationPath, sourcePath)
{
    file(destinationPath, [sourcePath], function(){
        FILE.touch(destinationPath);
    });
};

// logic to determine which packages should be loaded but are not.
// used in serializedENV()
function additionalPackages()
{
    var builtObjectiveJPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "objective-j", "");
    var builtCappuccinoPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "cappuccino", "");

    var packages = [];

    // load built objective-j if exists, otherwise unbuilt
    if (builtObjectiveJPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtObjectiveJPackage))
            packages.push(builtObjectiveJPackage);
    }

    // load built cappuccino if it exists
    if (builtCappuccinoPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtCappuccinoPackage))
            packages.push(builtCappuccinoPackage);
    }

    return packages;
}

// checks to see if a path is in the package catalog
function packageInCatalog(path)
{
    var catalog = require("narwhal/packages").catalog;
    for (var name in catalog)
        if (String(catalog[name].directory) === String(path))
            return true;
    return false;
}

serializedENV = function()
{
    var envNew = {};

    // add changed keys to the new ENV
    Object.keys(SYSTEM.env).forEach(function(key) {
        if (SYSTEM.env[key] !== envInitial[key])
            envNew[key] = SYSTEM.env[key];
    });

    // pseudo-HACK: add NARWHALOPT with packages we should ensure are loaded
    var packages = additionalPackages();
    if (packages.length) {
        envNew["NARWHALOPT"] = packages.map(function(p) { return "-p " + OS.enquote(p); }).join(" ");
        envNew["PATH"] = packages.map(function(p) { return FILE.join(p, "bin"); }).concat(SYSTEM.env["PATH"]).join(":");
    }

    return Object.keys(envNew).map(function(key) {
        return key + "=" + OS.enquote(envNew[key]);
    }).join(" ");
}

function reforkWithPackages()
{
    if (additionalPackages().length > 0) {
        var cmd = serializedENV() + " " + system.args.map(OS.enquote).join(" ");
        //print("REFORKING: " + cmd);
        OS.exit(OS.system(cmd));
    }
}

reforkWithPackages();

function handleSetupEnvironmentError(e) {
    if (String(e).indexOf("require error")==-1) {
        print("setupEnvironment warning: " + e);
        //throw e;
    }
}

function setupEnvironment()
{
    try {
        require("objective-j").OBJJ_INCLUDE_PATHS.push(FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "cappuccino", "Frameworks"));
    } catch (e) {
        handleSetupEnvironmentError(e);
    }
}

setupEnvironment();

global.rm_rf = function(/*String*/ aFilename)
{
    try { FILE.rmtree(aFilename); }
    catch (anException) { }
}

global.cp_r = function(/*String*/ from, /*String*/ to)
{
    if (FILE.exists(to))
        rm_rf(to);

    if (FILE.isDirectory(from))
        FILE.copyTree(from, to);
    else{try{
        FILE.copy(from, to);}catch(e) { print(e + FILE.exists(from) + " " + FILE.exists(FILE.dirname(to))); }}
}

global.cp = function(/*String*/ from, /*String*/ to)
{
    FILE.copy(from, to);
//    FILE.chmod(to, FILE.mod(from));
}

global.mv = function(/*String*/ from, /*String*/ to)
{
    FILE.move(from, to);
}

global.subjake = function(/*Array<String>*/ directories, /*String*/ aTaskName)
{
    if (!Array.isArray(directories))
        directories = [directories];

    directories.forEach(function(/*String*/ aDirectory)
    {
        if (FILE.isDirectory(aDirectory) && FILE.isFile(FILE.join(aDirectory, "Jakefile")))
        {
            var cmd = "cd " + OS.enquote(aDirectory) + " && " + serializedENV() + " " + OS.enquote(SYSTEM.args[0]) + " " + OS.enquote(aTaskName);
            var returnCode = OS.system(cmd);
            if (returnCode)
                OS.exit(returnCode);
        }
        else
            print("warning: subjake missing: " + aDirectory + " (this is not necessarily an error, " + aDirectory + " may be optional)");
    });
}

global.executableExists = function(/*String*/ executableName)
{
    var paths = SYSTEM.env["PATH"].split(':');
    for (var i = 0; i < paths.length; i++) {
        var path = FILE.join(paths[i], executableName);
        if (FILE.exists(path))
            return path;
    }
    return null;
}

$OBJJ_TEMPLATE_EXECUTABLE = FILE.join($HOME_DIR, "Objective-J", "CommonJS", "objj-executable");

global.make_objj_executable = function(aPath)
{
    cp($OBJJ_TEMPLATE_EXECUTABLE, aPath);
    FILE.chmod(aPath, 0755);
}

global.symlink_executable = function(source)
{
    relative = FILE.relative($ENVIRONMENT_NARWHAL_BIN_DIR, source);
    destination = FILE.join($ENVIRONMENT_NARWHAL_BIN_DIR, FILE.basename(source));
    FILE.symlink(relative, destination);
}

global.getCappuccinoVersion = function() {
    var versionFile = FILE.path(module.path).dirname().join("version.json");
    return JSON.parse(versionFile.read({ charset : "UTF-8" })).version;
}

global.setPackageMetadata = function(packagePath) {
    var pkg = JSON.parse(FILE.read(packagePath, { charset : "UTF-8" }));

    var p = OS.popen(["git", "rev-parse", "--verify", "HEAD"]);
    if (p.wait() === 0) {
        var sha = p.stdout.read().split("\n")[0];
        if (sha.length === 40)
            pkg["cappuccino-revision"] = sha;
    }

    pkg["cappuccino-timestamp"] = new Date().getTime();
    pkg["version"] = getCappuccinoVersion();

    stream.print("    Version:   \0purple(" + pkg["version"] + "\0)");
    stream.print("    Revision:  \0purple(" + pkg["cappuccino-revision"] + "\0)");
    stream.print("    Timestamp: \0purple(" + pkg["cappuccino-timestamp"] + "\0)");

    FILE.write(packagePath, JSON.stringify(pkg, null, 4), { charset : "UTF-8" });
}

global.subtasks = function(subprojects, taskNames)
{
    taskNames.forEach(function(aTaskName)
    {
        var subtaskName = aTaskName + "_subprojects";

        task (aTaskName, [subtaskName]);

        task (subtaskName, function()
        {
            subjake(subprojects, aTaskName);
        });
    });
}

function spawnJake(/*String*/ aTaskName)
{
    if (OS.system(serializedENV() + " " + SYSTEM.args[0] + " " + aTaskName))
        OS.exit(1);//rake abort if ($? != 0)
}

// built in tasks

task ("build");
task ("default", "build");

task ("release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("build");
});

task ("debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("build");
});

task ("all", ["debug", "release"]);

task ("clean-debug", function()
{
    SYSTEM.env['CONFIG'] = 'Debug'
    spawnJake("clean");
});

task ("cleandebug", ["clean-debug"]);

task ("clean-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clean");
});

task ("cleanrelease", ["clean-release"]);

task ("clean-all", ["clean-debug", "clean-release"]);
task ("cleanall", ["clean-all"]);

task ("clobber-debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("clobber");
});

task ("clobberdebug", ["clobber-debug"]);

task ("clobber-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clobber");
});

task ("clobberrelease", ['clobber-release']);

task ("clobber-all", ["clobber-debug", "clobber-release"]);
task ("clobberall", ["clobber-all"]);
<|endoftext|>


<commit_before>"use strict";

/*  ------------------------------------------------------------------------ */

const isNumber          = Number.isFinite
    , isArray           = Array.isArray
    , isString          = s =>                 (typeof s === 'string')
    , isObject          = o => (o !== null) && (typeof o === 'object')
    , isDictionary      = o => (isObject (o) && !isArray (o))
    , isStringCoercible = x => (hasProps (x) && x.toString) || isNumber (x)

/*  .............................................   */

const hasProps = o => (o !== undefined) &&
                      (o !== null)

    , prop = (o, k) => isObject (o) ? o[k] : undefined

/*  .............................................   */

const asFloat   = x => (isNumber (x) || isString (x)) ? parseFloat (x)     : NaN
    , asInteger = x => (isNumber (x) || isString (x)) ? parseInt   (x, 10) : NaN

/*  .............................................   */

module.exports =

    { isNumber
    , isArray
    , isObject
    , isString
    , isStringCoercible
    , isDictionary

    , hasProps
    , prop

    , asFloat
    , asInteger

    , safeFloat:   (o, k, $default, n =   asFloat (prop (o, k))) => isNumber (n)          ? n          : $default
    , safeInteger: (o, k, $default, n = asInteger (prop (o, k))) => isNumber (n)          ? n          : $default
    , safeValue:   (o, k, $default, x =            prop (o, k) ) => hasProps (x)          ? x          : $default
    , safeString:  (o, k, $default, x =            prop (o, k) ) => isStringCoercible (x) ? String (x) : $default

    }

/*  ------------------------------------------------------------------------ */
<commit_msg>added safeValue2 family to type.js<commit_after>"use strict";

/*  ------------------------------------------------------------------------ */

const isNumber          = Number.isFinite
    , isArray           = Array.isArray
    , isString          = s =>                 (typeof s === 'string')
    , isObject          = o => (o !== null) && (typeof o === 'object')
    , isDictionary      = o => (isObject (o) && !isArray (o))
    , isStringCoercible = x => (hasProps (x) && x.toString) || isNumber (x)

/*  .............................................   */

const hasProps = o => (o !== undefined) &&
                      (o !== null)

    , prop = (o, k) => (isObject (o) ? o[k] : undefined)
    , prop2 = (o, k1, k2) => (!isObject (o) ? undefined : ((k1 in o) ? o[k1] : o[k2]))

/*  .............................................   */

const asFloat   = x => ((isNumber (x) || isString (x)) ? parseFloat (x)     : NaN)
    , asInteger = x => ((isNumber (x) || isString (x)) ? parseInt   (x, 10) : NaN)

/*  .............................................   */

module.exports =

    { isNumber
    , isArray
    , isObject
    , isString
    , isStringCoercible
    , isDictionary

    , hasProps
    , prop

    , asFloat
    , asInteger

    , safeFloat:   (o, k, $default, n =   asFloat (prop (o, k))) => isNumber (n)          ? n          : $default
    , safeInteger: (o, k, $default, n = asInteger (prop (o, k))) => isNumber (n)          ? n          : $default
    , safeValue:   (o, k, $default, x =            prop (o, k) ) => hasProps (x)          ? x          : $default
    , safeString:  (o, k, $default, x =            prop (o, k) ) => isStringCoercible (x) ? String (x) : $default

    // not using safeFloats with an array argument as we're trying to save some cycles here
    // we're not using safeFloat3 either because those cases are too rare to deserve their own optimization

    , safeFloat2:   (o, k1, k2, $default, n =   asFloat (prop2 (o, k1, k2))) => isNumber (n)          ? n          : $default
    , safeInteger2: (o, k1, k2, $default, n = asInteger (prop2 (o, k1, k2))) => isNumber (n)          ? n          : $default
    , safeValue2:   (o, k1, k2, $default, x =            prop2 (o, k1, k2) ) => hasProps (x)          ? x          : $default
    , safeString2:  (o, k1, k2, $default, x =            prop2 (o, k1, k2) ) => isStringCoercible (x) ? String (x) : $default

    }

/*  ------------------------------------------------------------------------ */
<|endoftext|>