<commit_before>/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2014 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache.
*
* @class Phaser.LoaderParser
*/
Phaser.LoaderParser = {

    /**
    * Parse a Bitmap Font from an XML file.
    *
    * @method Phaser.LoaderParser.bitmapFont
    * @param {Phaser.Game} game - A reference to the current game.
    * @param {object} xml - XML data you want to parse.
    * @param {string} cacheKey - The key of the texture this font uses in the cache.
    * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
    * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
    */
    bitmapFont: function (game, xml, cacheKey, xSpacing, ySpacing) {

        var data = {};
        var info = xml.getElementsByTagName('info')[0];
        var common = xml.getElementsByTagName('common')[0];

        data.font = info.getAttribute('face');
        data.size = parseInt(info.getAttribute('size'), 10);
        data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing;
        data.chars = {};

        var letters = xml.getElementsByTagName('char');

        for (var i = 0; i < letters.length; i++)
        {
            var charCode = parseInt(letters[i].getAttribute('id'), 10);

            var textureRect = new PIXI.Rectangle(
                parseInt(letters[i].getAttribute('x'), 10),
                parseInt(letters[i].getAttribute('y'), 10),
                parseInt(letters[i].getAttribute('width'), 10),
                parseInt(letters[i].getAttribute('height'), 10)
            );

            data.chars[charCode] = {
                xOffset: parseInt(letters[i].getAttribute('xoffset'), 10),
                yOffset: parseInt(letters[i].getAttribute('yoffset'), 10),
                xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing,
                kerning: {},
                texture: PIXI.TextureCache[cacheKey] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], textureRect)
            };
        }

        var kernings = xml.getElementsByTagName('kerning');

        for (i = 0; i < kernings.length; i++)
        {
            var first = parseInt(kernings[i].getAttribute('first'), 10);
            var second = parseInt(kernings[i].getAttribute('second'), 10);
            var amount = parseInt(kernings[i].getAttribute('amount'), 10);

            data.chars[second].kerning[first] = amount;
        }

        PIXI.BitmapText.fonts[cacheKey] = data;

    }

};
<commit_msg>Continuing removal of PIXI and commenting required changes for the new renderer.<commit_after>/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2014 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache.
*
* @class Phaser.LoaderParser
*/
Phaser.LoaderParser = {

    /**
    * Parse a Bitmap Font from an XML file.
    *
    * @method Phaser.LoaderParser.bitmapFont
    * @param {Phaser.Game} game - A reference to the current game.
    * @param {object} xml - XML data you want to parse.
    * @param {string} cacheKey - The key of the texture this font uses in the cache.
    * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
    * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
    */
    bitmapFont: function (game, xml, cacheKey, xSpacing, ySpacing) {

        var data = {};
        var info = xml.getElementsByTagName('info')[0];
        var common = xml.getElementsByTagName('common')[0];

        data.font = info.getAttribute('face');
        data.size = parseInt(info.getAttribute('size'), 10);
        data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing;
        data.chars = {};

        var letters = xml.getElementsByTagName('char');

        for (var i = 0; i < letters.length; i++)
        {
            var charCode = parseInt(letters[i].getAttribute('id'), 10);

// PJBNOTE: not sure why this is using PIXI.Rectangle as that has been over-ridden with Phaser.Rectangle already
//            var textureRect = new PIXI.Rectangle(
            var textureRect = new Phaser.Rectangle(
                parseInt(letters[i].getAttribute('x'), 10),
                parseInt(letters[i].getAttribute('y'), 10),
                parseInt(letters[i].getAttribute('width'), 10),
                parseInt(letters[i].getAttribute('height'), 10)
            );

            data.chars[charCode] = {
                xOffset: parseInt(letters[i].getAttribute('xoffset'), 10),
                yOffset: parseInt(letters[i].getAttribute('yoffset'), 10),
                xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing,
                kerning: {}
// PJBNOTE: pbText replaces prior bitmap-font handling, probably want a reference to its pbSurface here
//                texture: PIXI.TextureCache[cacheKey] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], textureRect)
            };
        }

        var kernings = xml.getElementsByTagName('kerning');

        for (i = 0; i < kernings.length; i++)
        {
            var first = parseInt(kernings[i].getAttribute('first'), 10);
            var second = parseInt(kernings[i].getAttribute('second'), 10);
            var amount = parseInt(kernings[i].getAttribute('amount'), 10);

            data.chars[second].kerning[first] = amount;
        }

// PJBNOTE: pbText replaces prior bitmap-font handling
//        PIXI.BitmapText.fonts[cacheKey] = data;

    }

};
<|endoftext|>


<commit_before>"use strict";

var phantom = require("phantom");

const DEBUG = true;

/**
 * Print all arguments to the console.
 */
function inspectArgs() {
    if (DEBUG) console.log.apply(null, arguments);
}

// NOTE: The <phantomjs-node> module no longer supports a port configuration object.
// Pick a random int between two ranges.
// function getRandomPort(min, max) {
//     return Math.floor(Math.random() * (max - min + 1)) + min;
// }

module.exports.capture = function (option, callback) {
    callback = callback || function () { return undefined };

    var phInstance,
        phPage,
        timer;

    // Set arguments mapped to the PhantomJS command line.
    var phantomArgs = (function () {
        let args = [];

        [ "ssl-protocol"
        , "ignore-ssl-errors"
        , "web-security"
        , "cookies-file"
        ].forEach(function(key) {
            if (option[key]) {
                args.push(["--", key, "=", option[key]].join(""));
            }
        });

        // NOTE: The <phantomjs-node> module no longer supports a port configuration object.
        // Pick a random port for phantom to use on start up
        // var port = getRandomPort(40000, 60000);
        // args.unshift({"port": port});

        return args;
    })();

    // NOTE: The <phantomjs-node> module no longer supports a port configuration object.
    // Reset the handler in case we grab an in-use port.
    // function onUncaughtException(err) {
    //     if (err.errno === "EADDRINUSE") {
    //         createPhantomInstance(args);
    //     } else {
    //         console.log(err);
    //         process.exit(1);
    //     }
    // }

    /**
     * Generate a new PhantomJS instance.
     */
    function createPhantomHandler(ph) {
        if (DEBUG && typeof ph !== "object") inspectArgs("createPhantomHandler: ", ph);

        phInstance = ph;
        return ph.createPage();
    };

    /**
     * Configure page settings then open a new page in PhantomJS.
     */
    function createPageHandler(page) {
        if (DEBUG && !page.phantom) inspectArgs("createPageHandler: ", page);

        phPage = page;
        var matches;

        if (option.viewportsize) {
            matches = option.viewportsize.match(/^(\d+)x(\d+)$/);
            if (matches !== null) {
                page.property("viewportSize", {width: matches[1], height: matches[2]});
            }
        }

        if (option.cliprect) {
            matches = option.cliprect.match(/^(\d+)x(\d+)x(\d+)x(\d+)$/);
            if (matches !== null) {
                page.setting("clipRect", {top: matches[1], left: matches[2],
                    width: matches[3], height: matches[4]});
            }
        }

        if (option["user-agent"]) {
            page.setting("userAgent", option["user-agent"]);
        }

        if (option.zoomfactor) {
            page.setting("zoomFactor", parseFloat(option.zoomfactor));
        }

        if (option.timeout) {
            timer = setTimeout(function () {
                var err = `capturejs: cannot access ${option.uri}: request timed out`;
                console.error(err);
                phInstance.exit();
                process.nextTick(function () { callback(err) });
            }, +option.timeout);
        }

        return page.open(option.uri);
    };

    /**
     * Log status messages, and close PhantomJS on failure.
     */
    function reportStatus(status) {
        if (DEBUG && status !== "success") inspectArgs("reportStatus: ", status);

        if (status === "fail") {
            var err = `capturejs: cannot access ${option.uri}: failed to open page`;
            console.error(err);
            phInstance.exit();
            process.nextTick(callback, err);
        } else {
            return phPage;
        }
    }

    /**
     * Inject JavaScript into the open page.
     */
    function manipulatePage(page) {
        if (DEBUG && !page.phantom) inspectArgs("manipulatePage: ", page);

        if (timer !== undefined) {
            clearTimeout(timer);
        }

        // Inject an external script file.
        if (option["javascript-file"]) {
            page.injectJs(option["javascript-file"]);
        }

        // Inject an in-line script from the command line.
        if (option["inject-script"]) {
            var injectScript = option["inject-script"];
            injectScript = (typeof injectScript === "function") ?
                injectScript.toString() : `function() { ${injectScript} }`;
            page.evaluateJavaScript(injectScript);
        }

        if (option.waitcapturedelay) {
            setTimeout(function () { return page }, +option.waitcapturedelay);
        } else {
            return page;
        }
    };

    /**
     * Capture the specified image.
     */
    function captureImage(page) {
        if (DEBUG && !page.phantom) inspectArgs("captureImage: ", page);

        if (option.selector) {
            let getElement = [ "function () {",
                , "document.body.bgColor = 'white';"
                , `var elem = document.querySelector('${option.selector}');`
                , "return (elem !== null) ? elem.getBoundingClientRect() : null; };"
            ].join("");

            return page.evaluateJavaScript(getElement);
        }
    }

    /**
     * Output the saved image to the specified file.
     */
    function saveImage(rect) {
        if (DEBUG && rect && !rect.bottom) inspectArgs("saveImage: ", rect);

        if (rect && typeof rect.bottom === "number") {
            phPage.property("clipRect", rect);
        }

        // Set a timeout to give the page a chance to render.
        setTimeout(function () {
            phPage.render(option.output)
                  .then(function () {
                      phInstance.exit();
                      // process.removeListener("uncaughtException", onUncaughtException);
                      process.nextTick(callback);
                  });
        }, option.renderdelay || 250);
    }

    // Monitor for conflicts when using a randomized port number.
    // process.on("uncaughtException", onUncaughtException);

    // Initialize PhantomJS using all command-line arguments.
    phantom.create(phantomArgs)
           .then(createPhantomHandler)
           .then(createPageHandler)
           .then(reportStatus)
           .then(manipulatePage)
           .then(captureImage)
           .then(saveImage)
           .catch(function(err) {
               console.error(err);
               phInstance.exit();
               process.nextTick(callback, err);
           });

};

// vim: set fenc=utf-8 ts=4 sts=4 sw=4 :
<commit_msg>Turn off debug mode.<commit_after>"use strict";

var phantom = require("phantom");

const DEBUG = false;

/**
 * Print all arguments to the console.
 */
function inspectArgs() {
    if (DEBUG) console.log.apply(null, arguments);
}

// NOTE: The <phantomjs-node> module no longer supports a port configuration object.
// Pick a random int between two ranges.
// function getRandomPort(min, max) {
//     return Math.floor(Math.random() * (max - min + 1)) + min;
// }

module.exports.capture = function (option, callback) {
    callback = callback || function () { return undefined };

    var phInstance,
        phPage,
        timer;

    // Set arguments mapped to the PhantomJS command line.
    var phantomArgs = (function () {
        let args = [];

        [ "ssl-protocol"
        , "ignore-ssl-errors"
        , "web-security"
        , "cookies-file"
        ].forEach(function(key) {
            if (option[key]) {
                args.push(["--", key, "=", option[key]].join(""));
            }
        });

        // NOTE: The <phantomjs-node> module no longer supports a port configuration object.
        // Pick a random port for phantom to use on start up
        // var port = getRandomPort(40000, 60000);
        // args.unshift({"port": port});

        return args;
    })();

    // NOTE: The <phantomjs-node> module no longer supports a port configuration object.
    // Reset the handler in case we grab an in-use port.
    // function onUncaughtException(err) {
    //     if (err.errno === "EADDRINUSE") {
    //         createPhantomInstance(args);
    //     } else {
    //         console.log(err);
    //         process.exit(1);
    //     }
    // }

    /**
     * Generate a new PhantomJS instance.
     */
    function createPhantomHandler(ph) {
        if (DEBUG && typeof ph !== "object") inspectArgs("createPhantomHandler: ", ph);

        phInstance = ph;
        return ph.createPage();
    };

    /**
     * Configure page settings then open a new page in PhantomJS.
     */
    function createPageHandler(page) {
        if (DEBUG && !page.phantom) inspectArgs("createPageHandler: ", page);

        phPage = page;
        var matches;

        if (option.viewportsize) {
            matches = option.viewportsize.match(/^(\d+)x(\d+)$/);
            if (matches !== null) {
                page.property("viewportSize", {width: matches[1], height: matches[2]});
            }
        }

        if (option.cliprect) {
            matches = option.cliprect.match(/^(\d+)x(\d+)x(\d+)x(\d+)$/);
            if (matches !== null) {
                page.setting("clipRect", {top: matches[1], left: matches[2],
                    width: matches[3], height: matches[4]});
            }
        }

        if (option["user-agent"]) {
            page.setting("userAgent", option["user-agent"]);
        }

        if (option.zoomfactor) {
            page.setting("zoomFactor", parseFloat(option.zoomfactor));
        }

        if (option.timeout) {
            timer = setTimeout(function () {
                var err = `capturejs: cannot access ${option.uri}: request timed out`;
                console.error(err);
                phInstance.exit();
                process.nextTick(function () { callback(err) });
            }, +option.timeout);
        }

        return page.open(option.uri);
    };

    /**
     * Log status messages, and close PhantomJS on failure.
     */
    function reportStatus(status) {
        if (DEBUG && status !== "success") inspectArgs("reportStatus: ", status);

        if (status === "fail") {
            var err = `capturejs: cannot access ${option.uri}: failed to open page`;
            console.error(err);
            phInstance.exit();
            process.nextTick(callback, err);
        } else {
            return phPage;
        }
    }

    /**
     * Inject JavaScript into the open page.
     */
    function manipulatePage(page) {
        if (DEBUG && !page.phantom) inspectArgs("manipulatePage: ", page);

        if (timer !== undefined) {
            clearTimeout(timer);
        }

        // Inject an external script file.
        if (option["javascript-file"]) {
            page.injectJs(option["javascript-file"]);
        }

        // Inject an in-line script from the command line.
        if (option["inject-script"]) {
            var injectScript = option["inject-script"];
            injectScript = (typeof injectScript === "function") ?
                injectScript.toString() : `function() { ${injectScript} }`;
            page.evaluateJavaScript(injectScript);
        }

        if (option.waitcapturedelay) {
            setTimeout(function () { return page }, +option.waitcapturedelay);
        } else {
            return page;
        }
    };

    /**
     * Capture the specified image.
     */
    function captureImage(page) {
        if (DEBUG && !page.phantom) inspectArgs("captureImage: ", page);

        if (option.selector) {
            let getElement = [ "function () {",
                , "document.body.bgColor = 'white';"
                , `var elem = document.querySelector('${option.selector}');`
                , "return (elem !== null) ? elem.getBoundingClientRect() : null; };"
            ].join("");

            return page.evaluateJavaScript(getElement);
        }
    }

    /**
     * Output the saved image to the specified file.
     */
    function saveImage(rect) {
        if (DEBUG && rect && !rect.bottom) inspectArgs("saveImage: ", rect);

        if (rect && typeof rect.bottom === "number") {
            phPage.property("clipRect", rect);
        }

        // Set a timeout to give the page a chance to render.
        setTimeout(function () {
            phPage.render(option.output)
                  .then(function () {
                      phInstance.exit();
                      // process.removeListener("uncaughtException", onUncaughtException);
                      process.nextTick(callback);
                  });
        }, option.renderdelay || 250);
    }

    // Monitor for conflicts when using a randomized port number.
    // process.on("uncaughtException", onUncaughtException);

    // Initialize PhantomJS using all command-line arguments.
    phantom.create(phantomArgs)
           .then(createPhantomHandler)
           .then(createPageHandler)
           .then(reportStatus)
           .then(manipulatePage)
           .then(captureImage)
           .then(saveImage)
           .catch(function(err) {
               console.error(err);
               phInstance.exit();
               process.nextTick(callback, err);
           });

};

// vim: set fenc=utf-8 ts=4 sts=4 sw=4 :
<|endoftext|>


<commit_before>/*jshint strict:false, asi:true, laxcomma:true, laxbreak:true, boss:true, curly:true, node:true, browser:true, devel:true */

function VCompiler(ast, originalMarkup, Helpers, options){
	this.ast = ast;
	this.originalMarkup = originalMarkup || '';
	this.Helpers = Helpers || vash.helpers.constructor;
	this.options = options || {};

	this.reQuote = /(["'])/gi
	this.reEscapedQuote = /\\+(["'])/gi
	this.reLineBreak = /[\n\r]/gi
	this.reHelpersName = /HELPERSNAME/g
	this.reModelName = /MODELNAME/g
	this.reOriginalMarkup = /ORIGINALMARKUP/g

	this.buffer = [];
}

var VCP = VCompiler.prototype;

VCP.insertDebugVars = function(tok){

	if(this.options.debug){
		this.buffer.push(
			this.options.helpersName + '.vl = ' + tok.line + ', '
			,this.options.helpersName + '.vc = ' + tok.chr + '; \n'
		);
	}
}

VCP.visitMarkupTok = function(tok, parentNode, index){

	this.insertDebugVars(tok);
	this.buffer.push(
		"MKP('" + tok.val
			.replace(this.reQuote, '\\$1')
			.replace(this.reLineBreak, '\\n')
		+ "')MKP" );
}

VCP.visitBlockTok = function(tok, parentNode, index){

	this.buffer.push( tok.val );
}

VCP.visitExpressionTok = function(tok, parentNode, index, isHomogenous){

	var  start = ''
		,end = ''
		,parentParentIsNotEXP = parentNode.parent && parentNode.parent.mode !== EXP;

	if(this.options.htmlEscape !== false){

		if( parentParentIsNotEXP && index === 0 && isHomogenous ){
			start += this.options.helpersName + '.escape(';
		}

		if( parentParentIsNotEXP && index === parentNode.length - 1 && isHomogenous){
			end += ").toHtmlString()";
		}
	}

	if(parentParentIsNotEXP && (index === 0 ) ){
		this.insertDebugVars(tok);
		start = "__vbuffer.push(" + start;
	}

	if( parentParentIsNotEXP && index === parentNode.length - 1 ){
		end += "); \n";
	}

	this.buffer.push( start + tok.val + end );

	if(parentParentIsNotEXP && index === parentNode.length - 1){
		this.insertDebugVars(tok);
	}
}

VCP.visitNode = function(node){

	var n, children = node.slice(0), nonExp, i, child;

	if(node.mode === EXP && (node.parent && node.parent.mode !== EXP)){
		// see if this node's children are all EXP
		nonExp = node.filter(VCompiler.findNonExp).length;
	}

	for(i = 0; i < children.length; i++){
		child = children[i];

		// if saveAT is true, or if AT_COLON is used, these should not be compiled
		if( child.type && child.type === AT || child.type === AT_COLON ) continue;

		if(child.vquery){

			this.visitNode(child);

		} else if(node.mode === MKP){

			this.visitMarkupTok(child, node, i);

		} else if(node.mode === BLK){

			this.visitBlockTok(child, node, i);

		} else if(node.mode === EXP){

			this.visitExpressionTok(child, node, i, (nonExp > 0 ? false : true));

		}
	}

}

VCP.escapeForDebug = function( str ){
	return str
		.replace(this.reLineBreak, '!LB!')
		.replace(this.reQuote, '\\$1')
		.replace(this.reEscapedQuote, '\\$1')
}

VCP.replaceDevTokens = function( str ){
	return str
		.replace( this.reHelpersName, this.options.helpersName )
		.replace( this.reModelName, this.options.modelName );
}

VCP.generate = function(){

	// clear whatever's in the current buffer
	this.buffer.length = 0;

	var options = this.options;

	var head = ''
		+ (options.debug ? 'try { \n' : '')
		+ 'var __vbuffer = HELPERSNAME.buffer; \n'
		+ 'MODELNAME = MODELNAME || {}; \n'
		+ (options.useWith ? 'with( MODELNAME ){ \n' : '');

	var foot = ''
		+ 'return (__vopts && __vopts.context) \n'
		+ '  ? HELPERSNAME \n'
		+ '  : HELPERSNAME.toString(); \n'
		+ (options.debug ? '} catch( e ){ \n'
			+ '  HELPERSNAME.reportError( e, HELPERSNAME.vl, HELPERSNAME.vc, "ORIGINALMARKUP" ); \n'
			+ '} \n' : '')
		+ (options.useWith ? '} \n' : '');

	head = this.replaceDevTokens( head );
	foot = this.replaceDevTokens( foot )
		.replace( this.reOriginalMarkup, this.escapeForDebug( this.originalMarkup ) );

	this.visitNode(this.ast);

	// coalesce markup
	var joined = this.buffer
		.join("")
		.split("')MKPMKP('").join('')
		.split("MKP(").join( "__vbuffer.push(")
		.split(")MKP").join("); \n");

	joined = head + joined + foot;

	if(options.debugCompiler){
		console.log(joined);
	}

	try {
		this.cmpFunc = new Function(options.modelName, options.helpersName, '__vopts', joined);
	} catch(e){
		this.Helpers.reportError(e, 0, 0, joined, /\n/)
	}

	return this.compiledFunc;
}

VCP.assemble = function( cmpFunc ){
	return VCompiler.assemble( cmpFunc || this.cmpFunc, this.Helpers );
}

VCompiler.assemble = function( cmpFunc, Helpers ){
	Helpers = Helpers || vash.helpers.constructor;

	var linked = function( model, opts ){
		return cmpFunc( model, new Helpers( model ), opts );
	}

	linked.toString = function(){
		return cmpFunc.toString();
	}

	linked.toClientString = function(){
		return 'vash.link( ' + cmpFunc.toString() + ' )';
	}

	return linked;
}

VCompiler.findNonExp = function(node){

	if(node.vquery && node.mode === EXP){
		return node.filter(VCompiler.findNonExp).length > 0;
	}

	if(node.vquery && node.mode !== EXP){
		return true;
	} else {
		return false;
	}
}
<commit_msg>`options.context` injects a `Helpers` instance<commit_after>/*jshint strict:false, asi:true, laxcomma:true, laxbreak:true, boss:true, curly:true, node:true, browser:true, devel:true */

function VCompiler(ast, originalMarkup, Helpers, options){
	this.ast = ast;
	this.originalMarkup = originalMarkup || '';
	this.Helpers = Helpers || vash.helpers.constructor;
	this.options = options || {};

	this.reQuote = /(["'])/gi
	this.reEscapedQuote = /\\+(["'])/gi
	this.reLineBreak = /[\n\r]/gi
	this.reHelpersName = /HELPERSNAME/g
	this.reModelName = /MODELNAME/g
	this.reOriginalMarkup = /ORIGINALMARKUP/g

	this.buffer = [];
}

var VCP = VCompiler.prototype;

VCP.insertDebugVars = function(tok){

	if(this.options.debug){
		this.buffer.push(
			this.options.helpersName + '.vl = ' + tok.line + ', '
			,this.options.helpersName + '.vc = ' + tok.chr + '; \n'
		);
	}
}

VCP.visitMarkupTok = function(tok, parentNode, index){

	this.insertDebugVars(tok);
	this.buffer.push(
		"MKP('" + tok.val
			.replace(this.reQuote, '\\$1')
			.replace(this.reLineBreak, '\\n')
		+ "')MKP" );
}

VCP.visitBlockTok = function(tok, parentNode, index){

	this.buffer.push( tok.val );
}

VCP.visitExpressionTok = function(tok, parentNode, index, isHomogenous){

	var  start = ''
		,end = ''
		,parentParentIsNotEXP = parentNode.parent && parentNode.parent.mode !== EXP;

	if(this.options.htmlEscape !== false){

		if( parentParentIsNotEXP && index === 0 && isHomogenous ){
			start += this.options.helpersName + '.escape(';
		}

		if( parentParentIsNotEXP && index === parentNode.length - 1 && isHomogenous){
			end += ").toHtmlString()";
		}
	}

	if(parentParentIsNotEXP && (index === 0 ) ){
		this.insertDebugVars(tok);
		start = "__vbuffer.push(" + start;
	}

	if( parentParentIsNotEXP && index === parentNode.length - 1 ){
		end += "); \n";
	}

	this.buffer.push( start + tok.val + end );

	if(parentParentIsNotEXP && index === parentNode.length - 1){
		this.insertDebugVars(tok);
	}
}

VCP.visitNode = function(node){

	var n, children = node.slice(0), nonExp, i, child;

	if(node.mode === EXP && (node.parent && node.parent.mode !== EXP)){
		// see if this node's children are all EXP
		nonExp = node.filter(VCompiler.findNonExp).length;
	}

	for(i = 0; i < children.length; i++){
		child = children[i];

		// if saveAT is true, or if AT_COLON is used, these should not be compiled
		if( child.type && child.type === AT || child.type === AT_COLON ) continue;

		if(child.vquery){

			this.visitNode(child);

		} else if(node.mode === MKP){

			this.visitMarkupTok(child, node, i);

		} else if(node.mode === BLK){

			this.visitBlockTok(child, node, i);

		} else if(node.mode === EXP){

			this.visitExpressionTok(child, node, i, (nonExp > 0 ? false : true));

		}
	}

}

VCP.escapeForDebug = function( str ){
	return str
		.replace(this.reLineBreak, '!LB!')
		.replace(this.reQuote, '\\$1')
		.replace(this.reEscapedQuote, '\\$1')
}

VCP.replaceDevTokens = function( str ){
	return str
		.replace( this.reHelpersName, this.options.helpersName )
		.replace( this.reModelName, this.options.modelName );
}

VCP.generate = function(){

	// clear whatever's in the current buffer
	this.buffer.length = 0;

	var options = this.options;

	var head = ''
		+ (options.debug ? 'try { \n' : '')
		+ 'var __vbuffer = HELPERSNAME.buffer; \n'
		+ 'MODELNAME = MODELNAME || {}; \n'
		+ (options.useWith ? 'with( MODELNAME ){ \n' : '');

	var foot = ''
		+ 'return (__vopts && __vopts.asContext) \n'
		+ '  ? HELPERSNAME \n'
		+ '  : HELPERSNAME.toString(); \n'
		+ (options.debug ? '} catch( e ){ \n'
			+ '  HELPERSNAME.reportError( e, HELPERSNAME.vl, HELPERSNAME.vc, "ORIGINALMARKUP" ); \n'
			+ '} \n' : '')
		+ (options.useWith ? '} \n' : '');

	head = this.replaceDevTokens( head );
	foot = this.replaceDevTokens( foot )
		.replace( this.reOriginalMarkup, this.escapeForDebug( this.originalMarkup ) );

	this.visitNode(this.ast);

	// coalesce markup
	var joined = this.buffer
		.join("")
		.split("')MKPMKP('").join('')
		.split("MKP(").join( "__vbuffer.push(")
		.split(")MKP").join("); \n");

	joined = head + joined + foot;

	if(options.debugCompiler){
		console.log(joined);
	}

	try {
		this.cmpFunc = new Function(options.modelName, options.helpersName, '__vopts', joined);
	} catch(e){
		this.Helpers.reportError(e, 0, 0, joined, /\n/)
	}

	return this.compiledFunc;
}

VCP.assemble = function( cmpFunc ){
	return VCompiler.assemble( cmpFunc || this.cmpFunc, this.Helpers );
}

VCompiler.assemble = function( cmpFunc, Helpers ){
	Helpers = Helpers || vash.helpers.constructor;

	var linked = function( model, opts ){
		return cmpFunc( model, (opts && opts.context) || new Helpers( model ), opts );
	}

	linked.toString = function(){
		return cmpFunc.toString();
	}

	linked.toClientString = function(){
		return 'vash.link( ' + cmpFunc.toString() + ' )';
	}

	return linked;
}

VCompiler.findNonExp = function(node){

	if(node.vquery && node.mode === EXP){
		return node.filter(VCompiler.findNonExp).length > 0;
	}

	if(node.vquery && node.mode !== EXP){
		return true;
	} else {
		return false;
	}
}
<|endoftext|>


<commit_before>THREE.TRKLoader = function() {};

THREE.TRKLoader.prototype = {

	constructor: THREE.EventDispatcher,

    load: function(url, onLoad, onProgress, onError) {
        window.console.log(url, onLoad, onProgress, onError);

        var scope = this;
        var xhr = new XMLHttpRequest();

        function onloaded(event) {
            if (event.target.status === 200 || event.target.status === 0) {
                var geometry = scope.parse(event.target.response || event.target.responseText);
                scope.dispatchEvent({
                    type: 'load',
                    content: geometry,
                });
                if (onLoad) {
                    onLoad(geometry);
                }
            } else {
                scope.dispatchEvent({
                    type: 'error',
                    message: 'Couldn\'t load URL [' + url + ']',
                    response: event.target.statusText,
                });
            }
        }

        xhr.addEventListener('load', onloaded, false);

        xhr.addEventListener('progress', function(event) {
            scope.dispatchEvent({
                type: 'progress',
                loaded: event.loaded,
                total: event.total,
            });
        }, false);

        xhr.addEventListener('error', function() {
            scope.dispatchEvent({
                type: 'error',
                message: 'Couldn\'t load URL [' + url + ']',
            });
        }, false);

        if (xhr.overrideMimeType) {
            xhr.overrideMimeType('text/plain; charset=x-user-defined');
        }

        xhr.open('GET', url, true);

        xhr.responseType = 'arraybuffer';

        xhr.send(null);
    },

    littleEndian: function() {
        var buffer = new ArrayBuffer(2);
        new DataView(buffer).setInt16(0, 256, true);

        return new Int16Array(buffer)[0] === 256;
    },

    scan: function(type, chunks, offset, data) {
        window.console.log(type, chunks, offset, data);
    },

    parse: function(data) {
        var littleEndian = this.littleEndian();
        var reader = new DataView(data);

        // String.fromCharCode
        // str.charCodeAt(position)

        // ////////////////////////////////////////////
        //
        // parse all trk header
        // http://msdn.microsoft.com/en-us/library/s3f49ktz.aspx
        //
        // ////////////////////////////////////////////

        var offset = 0;
        var header = {};

        // id_string[6]
        // char
        // 6
        // ID string for track file. The first 5 characters must be "TRACK".
        header.ID_STRING = [];
        for (var i = 0; i < 6; i++) {
            header.ID_STRING.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // dim[3]
        // short int
        // 6
        // Dimension of the image volume.
        header.dim = [];
        for (var q = 0; q < 3; q++) {
            header.dim.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        // voxel_size[3]
        // float
        // 12
        // Voxel size of the image volume.
        header.VOXEL_SIZE = [];
        for (var r = 0; r < 3; r++) {
            header.VOXEL_SIZE.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }
        // origin[3]
        // float
        // 12
        // Origin of the image volume. This field is not yet being used by TrackVis. That means the origin is always (0, 0, 0).
        header.origin = [];
        for (var s = 0; s < 3; s++) {
            header.origin.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }

        // n_scalars
        // short int
        // 2
        // Number of scalars saved at each track point (besides x, y and z coordinates).
        header.N_SCALARS = [];
        for (var t = 0; t < 1; t++) {
            header.N_SCALARS.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        //  scalar_name[10][20]
        //  char
        //  200
        //  Name of each scalar. Can not be longer than 20 characters each. Can only store up to 10 names.
        header.SCALAR_NAME = [];
        for (var u = 0; u < 10; u++) {
            header.SCALAR_NAME.push([]);
            for (var v = 0; v < 20; v++) {
                header.SCALAR_NAME[u].push(String.fromCharCode(reader.getUint8(offset)));
                offset++;
            }
        }

        // n_propertiess
        // short int
        // 2
        // Number of properties saved at each track.
        header.N_PROPERTIES = [];
        for (var x = 0; x < 1; x++) {
            header.N_PROPERTIES.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        //  scalar_name[10][20]
        //  char
        //  200
        //  Name of each scalar. Can not be longer than 20 characters each. Can only store up to 10 names.
        header.PROPERTY_NAME = [];
        for (var y = 0; y < 10; y++) {
            header.PROPERTY_NAME.push([]);
            for (var z = 0; z < 20; z++) {
                header.PROPERTY_NAME[y].push(String.fromCharCode(reader.getUint8(offset)));
                offset++;
            }
        }

        // vox_to_ras[4][4]
        // float
        // 64
        // 4x4 matrix for voxel to RAS (crs to xyz) transformation. If vox_to_ras[3][3] is 0, it means the matrix is not recorded. This field is added from version 2.
        header.VOX_TO_RAS = [];
        for (var a = 0; a < 4; a++) {
            header.VOX_TO_RAS.push([]);
            for (var b = 0; b < 4; b++) {
                header.VOX_TO_RAS[a].push(reader.getFloat32(offset));
                offset += 4;
            }
        }

        // reserved[444]
        // char
        // 444
        // Reserved space for future version.
        offset += 444;

        // voxel_order[4]
        // char
        // 4
        // Storing order of the original image data.
        header.VOXEL_ORDER = [];
        for (var c = 0; c < 4; c++) {
            header.VOXEL_ORDER.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // pad2[4]
        // char
        // 4
        // Paddings.
        header.pad2 = [];
        for (var d = 0; d < 4; d++) {
            header.pad2.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // image_orientation_patient[6]
        // float
        // 24
        // Image orientation of the original image. As defined in the DICOM header.
        header.IMAGE_ORIENTATION_PATIENT = [];
        for (var e = 0; e < 6; e++) {
            header.IMAGE_ORIENTATION_PATIENT.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }

        // pad1[2]
        // char
        // 2
        // Paddings.
        header.pad1 = [];
        for (var f = 0; f < 2; f++) {
            header.pad2.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // invert_x, invert_y, invert_z, swap_xy, swap_yz, swap_zx
        // unsigned_char
        // 1
        // Inversion/rotation flags used to generate this track file. For internal use only.
        header.INVERT_X = [];
        for (var g = 0; g < 1; g++) {
            header.INVERT_X.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.INVERT_Y = [];
        for (var h = 0; h < 1; h++) {
            header.INVERT_Y.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.INVERT_Z = [];
        for (var ii = 0; ii < 1; ii++) {
            header.INVERT_Z.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_XY = [];
        for (var ij = 0; ij < 1; ij++) {
            header.SWAP_XY.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_YZ = [];
        for (var ik = 0; ik < 1; ik++) {
            header.SWAP_YZ.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_ZX = [];
        for (var il = 0; il < 1; il++) {
            header.SWAP_ZX.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // n_count
        // int
        // 4
        // Number of tracks stored in this track file. 0 means the number was NOT stored.
        header.N_COUNT = [];
        for (var im = 0; im < 1; im++) {
            header.N_COUNT.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        // version
        // int
        // 4
        // Version number. Current version is 2.
        header.version = [];
        for (var io = 0; io < 1; io++) {
            header.version.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        // hdr_size
        // int
        // 4
        // Size of the header. Used to determine byte swap. Should be 1000.
        header.HDR_SIZE = [];
        for (var ip = 0; ip < 1; ip++) {
            header.HDR_SIZE.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        window.console.log(header);

        // /////////////////////////////////////
        //
        // parse the tracts now...!
        //
        // ////////////////////////////////////

        // we should also store each track length

        // get the number of points in this track
        var tracks = [];

        while (offset < reader.byteLength) {
            var nbPoints = -1;
            nbPoints = reader.getUint32(offset, littleEndian);
            offset += 4;

            var track = {
                'points': [],
                'scalars': [],
                'properties': [],
                'geometry': new THREE.Geometry(),
                'xProperties': {},
            };

            var length = 0;

            for (var k = 0; k < nbPoints; k++) {
                // first 3 floats are the coordinates
                track.points[k] = [];
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;

                // add geometry
                //
                track.geometry.vertices.push(new THREE.Vector3(track.points[k][0], track.points[k][1], track.points[k][2]));

                // then the scalars
                track.scalars[k] = [];
                for (var l = 0; l < header.N_SCALARS[0]; l++) {
                    track.scalars[k][l] = [];
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                }

                if (k !== 0) {
                    // get previous and current points
                    var prev = track.points[k - 1];
                    var cur = track.points[k];
                    var xDist = cur[0] - prev[0];
                    var yDist = cur[1] - prev[1];
                    var zDist = cur[2] - prev[2];
                    // get distance
                    var distance = Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2) + Math.pow(zDist, 2));
                    // add add to length
                    length += distance;
                }
            }

            track.xProperties.length = length;

            for (var p = 0; p < nbPoints; p++) {
                // get previous point if any
                var first = track.points[0];
                if (p > 1) {
                    first = track.points[p - 1];
                }

                // get next point if any
                var last = track.points[nbPoints - 1];
                if (p < nbPoints - 2) {
                    last = track.points[p + 1];
                }

                var diff = [Math.abs(last[0] - first[0]),
                    Math.abs(last[1] - first[1]),
                    Math.abs(last[2] - first[2]),
                ];

                var colordistance = Math.sqrt(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]);
                diff[0] /= colordistance;
                diff[1] /= colordistance;
                diff[2] /= colordistance;

                track.geometry.colors.push(new THREE.Color(diff[0], diff[1], diff[2]));
            }

            // get the property of this track
            for (var o = 0; o < header.N_PROPERTIES[0]; o++) {
                track.properties[o] = [];
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
            }

            tracks.push(track);
        }

        return tracks;
    }
};
<commit_msg>Update loaders.trk.js<commit_after>THREE.TRKLoader = function() {
  Object.assign( this.prototype, EventDispatcher.prototype );
};

THREE.TRKLoader.prototype = {

    constructor: THREE.TRKLoader,

    load: function(url, onLoad, onProgress, onError) {
        window.console.log(url, onLoad, onProgress, onError);

        var scope = this;
        var xhr = new XMLHttpRequest();

        function onloaded(event) {
            if (event.target.status === 200 || event.target.status === 0) {
                var geometry = scope.parse(event.target.response || event.target.responseText);
                scope.dispatchEvent({
                    type: 'load',
                    content: geometry,
                });
                if (onLoad) {
                    onLoad(geometry);
                }
            } else {
                scope.dispatchEvent({
                    type: 'error',
                    message: 'Couldn\'t load URL [' + url + ']',
                    response: event.target.statusText,
                });
            }
        }

        xhr.addEventListener('load', onloaded, false);

        xhr.addEventListener('progress', function(event) {
            scope.dispatchEvent({
                type: 'progress',
                loaded: event.loaded,
                total: event.total,
            });
        }, false);

        xhr.addEventListener('error', function() {
            scope.dispatchEvent({
                type: 'error',
                message: 'Couldn\'t load URL [' + url + ']',
            });
        }, false);

        if (xhr.overrideMimeType) {
            xhr.overrideMimeType('text/plain; charset=x-user-defined');
        }

        xhr.open('GET', url, true);

        xhr.responseType = 'arraybuffer';

        xhr.send(null);
    },

    littleEndian: function() {
        var buffer = new ArrayBuffer(2);
        new DataView(buffer).setInt16(0, 256, true);

        return new Int16Array(buffer)[0] === 256;
    },

    scan: function(type, chunks, offset, data) {
        window.console.log(type, chunks, offset, data);
    },

    parse: function(data) {
        var littleEndian = this.littleEndian();
        var reader = new DataView(data);

        // String.fromCharCode
        // str.charCodeAt(position)

        // ////////////////////////////////////////////
        //
        // parse all trk header
        // http://msdn.microsoft.com/en-us/library/s3f49ktz.aspx
        //
        // ////////////////////////////////////////////

        var offset = 0;
        var header = {};

        // id_string[6]
        // char
        // 6
        // ID string for track file. The first 5 characters must be "TRACK".
        header.ID_STRING = [];
        for (var i = 0; i < 6; i++) {
            header.ID_STRING.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // dim[3]
        // short int
        // 6
        // Dimension of the image volume.
        header.dim = [];
        for (var q = 0; q < 3; q++) {
            header.dim.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        // voxel_size[3]
        // float
        // 12
        // Voxel size of the image volume.
        header.VOXEL_SIZE = [];
        for (var r = 0; r < 3; r++) {
            header.VOXEL_SIZE.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }
        // origin[3]
        // float
        // 12
        // Origin of the image volume. This field is not yet being used by TrackVis. That means the origin is always (0, 0, 0).
        header.origin = [];
        for (var s = 0; s < 3; s++) {
            header.origin.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }

        // n_scalars
        // short int
        // 2
        // Number of scalars saved at each track point (besides x, y and z coordinates).
        header.N_SCALARS = [];
        for (var t = 0; t < 1; t++) {
            header.N_SCALARS.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        //  scalar_name[10][20]
        //  char
        //  200
        //  Name of each scalar. Can not be longer than 20 characters each. Can only store up to 10 names.
        header.SCALAR_NAME = [];
        for (var u = 0; u < 10; u++) {
            header.SCALAR_NAME.push([]);
            for (var v = 0; v < 20; v++) {
                header.SCALAR_NAME[u].push(String.fromCharCode(reader.getUint8(offset)));
                offset++;
            }
        }

        // n_propertiess
        // short int
        // 2
        // Number of properties saved at each track.
        header.N_PROPERTIES = [];
        for (var x = 0; x < 1; x++) {
            header.N_PROPERTIES.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        //  scalar_name[10][20]
        //  char
        //  200
        //  Name of each scalar. Can not be longer than 20 characters each. Can only store up to 10 names.
        header.PROPERTY_NAME = [];
        for (var y = 0; y < 10; y++) {
            header.PROPERTY_NAME.push([]);
            for (var z = 0; z < 20; z++) {
                header.PROPERTY_NAME[y].push(String.fromCharCode(reader.getUint8(offset)));
                offset++;
            }
        }

        // vox_to_ras[4][4]
        // float
        // 64
        // 4x4 matrix for voxel to RAS (crs to xyz) transformation. If vox_to_ras[3][3] is 0, it means the matrix is not recorded. This field is added from version 2.
        header.VOX_TO_RAS = [];
        for (var a = 0; a < 4; a++) {
            header.VOX_TO_RAS.push([]);
            for (var b = 0; b < 4; b++) {
                header.VOX_TO_RAS[a].push(reader.getFloat32(offset));
                offset += 4;
            }
        }

        // reserved[444]
        // char
        // 444
        // Reserved space for future version.
        offset += 444;

        // voxel_order[4]
        // char
        // 4
        // Storing order of the original image data.
        header.VOXEL_ORDER = [];
        for (var c = 0; c < 4; c++) {
            header.VOXEL_ORDER.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // pad2[4]
        // char
        // 4
        // Paddings.
        header.pad2 = [];
        for (var d = 0; d < 4; d++) {
            header.pad2.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // image_orientation_patient[6]
        // float
        // 24
        // Image orientation of the original image. As defined in the DICOM header.
        header.IMAGE_ORIENTATION_PATIENT = [];
        for (var e = 0; e < 6; e++) {
            header.IMAGE_ORIENTATION_PATIENT.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }

        // pad1[2]
        // char
        // 2
        // Paddings.
        header.pad1 = [];
        for (var f = 0; f < 2; f++) {
            header.pad2.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // invert_x, invert_y, invert_z, swap_xy, swap_yz, swap_zx
        // unsigned_char
        // 1
        // Inversion/rotation flags used to generate this track file. For internal use only.
        header.INVERT_X = [];
        for (var g = 0; g < 1; g++) {
            header.INVERT_X.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.INVERT_Y = [];
        for (var h = 0; h < 1; h++) {
            header.INVERT_Y.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.INVERT_Z = [];
        for (var ii = 0; ii < 1; ii++) {
            header.INVERT_Z.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_XY = [];
        for (var ij = 0; ij < 1; ij++) {
            header.SWAP_XY.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_YZ = [];
        for (var ik = 0; ik < 1; ik++) {
            header.SWAP_YZ.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_ZX = [];
        for (var il = 0; il < 1; il++) {
            header.SWAP_ZX.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // n_count
        // int
        // 4
        // Number of tracks stored in this track file. 0 means the number was NOT stored.
        header.N_COUNT = [];
        for (var im = 0; im < 1; im++) {
            header.N_COUNT.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        // version
        // int
        // 4
        // Version number. Current version is 2.
        header.version = [];
        for (var io = 0; io < 1; io++) {
            header.version.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        // hdr_size
        // int
        // 4
        // Size of the header. Used to determine byte swap. Should be 1000.
        header.HDR_SIZE = [];
        for (var ip = 0; ip < 1; ip++) {
            header.HDR_SIZE.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        window.console.log(header);

        // /////////////////////////////////////
        //
        // parse the tracts now...!
        //
        // ////////////////////////////////////

        // we should also store each track length

        // get the number of points in this track
        var tracks = [];

        while (offset < reader.byteLength) {
            var nbPoints = -1;
            nbPoints = reader.getUint32(offset, littleEndian);
            offset += 4;

            var track = {
                'points': [],
                'scalars': [],
                'properties': [],
                'geometry': new THREE.Geometry(),
                'xProperties': {},
            };

            var length = 0;

            for (var k = 0; k < nbPoints; k++) {
                // first 3 floats are the coordinates
                track.points[k] = [];
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;

                // add geometry
                //
                track.geometry.vertices.push(new THREE.Vector3(track.points[k][0], track.points[k][1], track.points[k][2]));

                // then the scalars
                track.scalars[k] = [];
                for (var l = 0; l < header.N_SCALARS[0]; l++) {
                    track.scalars[k][l] = [];
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                }

                if (k !== 0) {
                    // get previous and current points
                    var prev = track.points[k - 1];
                    var cur = track.points[k];
                    var xDist = cur[0] - prev[0];
                    var yDist = cur[1] - prev[1];
                    var zDist = cur[2] - prev[2];
                    // get distance
                    var distance = Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2) + Math.pow(zDist, 2));
                    // add add to length
                    length += distance;
                }
            }

            track.xProperties.length = length;

            for (var p = 0; p < nbPoints; p++) {
                // get previous point if any
                var first = track.points[0];
                if (p > 1) {
                    first = track.points[p - 1];
                }

                // get next point if any
                var last = track.points[nbPoints - 1];
                if (p < nbPoints - 2) {
                    last = track.points[p + 1];
                }

                var diff = [Math.abs(last[0] - first[0]),
                    Math.abs(last[1] - first[1]),
                    Math.abs(last[2] - first[2]),
                ];

                var colordistance = Math.sqrt(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]);
                diff[0] /= colordistance;
                diff[1] /= colordistance;
                diff[2] /= colordistance;

                track.geometry.colors.push(new THREE.Color(diff[0], diff[1], diff[2]));
            }

            // get the property of this track
            for (var o = 0; o < header.N_PROPERTIES[0]; o++) {
                track.properties[o] = [];
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
            }

            tracks.push(track);
        }

        return tracks;
    }
};
<|endoftext|>


<commit_before>import { ATTR_KEY } from '../constants';
import { isSameNodeType, isNamedNode } from './index';
import { buildComponentFromVNode } from './component';
import { createNode, setAccessor } from '../dom/index';
import { unmountComponent } from './component';
import options from '../options';
import { removeNode } from '../dom';

/** Queue of components that have been mounted and are awaiting componentDidMount */
export const mounts = [];

/** Diff recursion count, used to track the end of the diff cycle. */
export let diffLevel = 0;

/** Global flag indicating if the diff is currently within an SVG */
let isSvgMode = false;

/** Global flag indicating if the diff is performing hydration */
let hydrating = false;

/** Invoke queued componentDidMount lifecycle methods */
export function flushMounts() {
	let c;
	while ((c=mounts.pop())) {
		if (options.afterMount) options.afterMount(c);
		if (c.componentDidMount) c.componentDidMount();
	}
}

/** Apply differences in a given vnode (and it's deep children) to a real DOM Node.
 *	@param {Element} [dom=null]		A DOM node to mutate into the shape of the `vnode`
 *	@param {VNode} vnode			A VNode (with descendants forming a tree) representing the desired DOM structure
 *	@returns {Element} dom			The created/mutated element
 *	@private
 */
export function diff(dom, vnode, context, mountAll, parent, componentRoot) {
	// diffLevel having been 0 here indicates initial entry into the diff (not a subdiff)
	if (!diffLevel++) {
		// when first starting the diff, check if we're diffing an SVG or within an SVG
		isSvgMode = parent!=null && parent.ownerSVGElement!==undefined;

		// hydration is inidicated by the existing element to be diffed not having a prop cache
		hydrating = dom!=null && !(ATTR_KEY in dom);
	}

	let ret = idiff(dom, vnode, context, mountAll, componentRoot);

	// append the element if its a new parent
	if (parent && ret.parentNode!==parent) parent.appendChild(ret);

	// diffLevel being reduced to 0 means we're exiting the diff
	if (!--diffLevel) {
		hydrating = false;
		// invoke queued componentDidMount lifecycle methods
		if (!componentRoot) flushMounts();
	}

	return ret;
}

/** Internals of `diff()`, separated to allow bypassing diffLevel / mount flushing. */
function idiff(dom, vnode, context, mountAll, componentRoot) {
	let out = dom,
		prevSvgMode = isSvgMode;

	// empty values (null & undefined) render as empty Text nodes
	if (vnode==null) vnode = '';

	// Fast case: Strings create/update Text nodes.
	if (typeof vnode==='string') {

		// update if it's already a Text node:
		if (dom && dom.splitText!==undefined && dom.parentNode && (!dom._component || componentRoot)) {
			if (dom.nodeValue!=vnode) {
				dom.nodeValue = vnode;
			}
		}
		else {
			// it wasn't a Text node: replace it with one and recycle the old Element
			out = document.createTextNode(vnode);
			if (dom) {
				if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
				recollectNodeTree(dom, true);
			}
		}

		out[ATTR_KEY] = true;

		return out;
	}

	// If the VNode represents a Component, perform a component diff:
	if (typeof vnode.nodeName==='function') {
		return buildComponentFromVNode(dom, vnode, context, mountAll);
	}

	// Tracks entering and exiting SVG namespace when descending through the tree.
	isSvgMode = vnode.nodeName==='svg' ? true : vnode.nodeName==='foreignObject' ? false : isSvgMode;

	// If there's no existing element or it's the wrong type, create a new one:
	if (!dom || !isNamedNode(dom, vnode.nodeName)) {
		out = createNode(vnode.nodeName, isSvgMode);

		if (dom) {
			// move children into the replacement node
			while (dom.firstChild) out.appendChild(dom.firstChild);

			// if the previous Element was mounted into the DOM, replace it inline
			if (dom.parentNode) dom.parentNode.replaceChild(out, dom);

			// recycle the old element (skips non-Element node types)
			recollectNodeTree(dom, true);
		}
	}

	let fc = out.firstChild,
		props = out[ATTR_KEY] || (out[ATTR_KEY] = {}),
		vchildren = vnode.children;

	// Optimization: fast-path for elements containing a single TextNode:
	if (!hydrating && vchildren && vchildren.length===1 && typeof vchildren[0]==='string' && fc!=null && fc.splitText!==undefined && fc.nextSibling==null) {
		if (fc.nodeValue!=vchildren[0]) {
			fc.nodeValue = vchildren[0];
		}
	}
	// otherwise, if there are existing or new children, diff them:
	else if (vchildren && vchildren.length || fc!=null) {
		innerDiffNode(out, vchildren, context, mountAll, hydrating || props.dangerouslySetInnerHTML!=null);
	}

	// Apply attributes/props from VNode to the DOM Element:
	diffAttributes(out, vnode.attributes, props);

	// restore previous SVG mode: (in case we're exiting an SVG namespace)
	isSvgMode = prevSvgMode;

	return out;
}

/** Apply child and attribute changes between a VNode and a DOM Node to the DOM.
 *	@param {Element} dom			Element whose children should be compared & mutated
 *	@param {Array} vchildren		Array of VNodes to compare to `dom.childNodes`
 *	@param {Object} context			Implicitly descendant context object (from most recent `getChildContext()`)
 *	@param {Boolean} mountAll
 *	@param {Boolean} isHydrating	If `true`, consumes externally created elements similar to hydration
 */
function innerDiffNode(dom, vchildren, context, mountAll, isHydrating) {
	let originalChildren = dom.childNodes,
		children = [],
		keyed = {},
		keyedLen = 0,
		min = 0,
		len = originalChildren.length,
		childrenLen = 0,
		vlen = vchildren ? vchildren.length : 0,
		j, c, vchild, child;

	// Build up a map of keyed children and an Array of unkeyed children:
	if (len!==0) {
		for (let i=0; i<len; i++) {
			let child = originalChildren[i],
				props = child[ATTR_KEY],
				key = vlen && props ? child._component ? child._component.__key : props.key : null;
			if (key!=null) {
				keyedLen++;
				keyed[key] = child;
			}
			else if (props || (child.splitText!==undefined ? (isHydrating ? child.nodeValue.trim() : true) : isHydrating)) {
				children[childrenLen++] = child;
			}
		}
	}

	if (vlen!==0) {
		for (let i=0; i<vlen; i++) {
			vchild = vchildren[i];
			child = null;

			// attempt to find a node based on key matching
			let key = vchild.key;
			if (key!=null) {
				if (keyedLen && keyed[key]!==undefined) {
					child = keyed[key];
					keyed[key] = undefined;
					keyedLen--;
				}
			}
			// attempt to pluck a node of the same type from the existing children
			else if (!child && min<childrenLen) {
				for (j=min; j<childrenLen; j++) {
					if (children[j]!==undefined && isSameNodeType(c = children[j], vchild, isHydrating)) {
						child = c;
						children[j] = undefined;
						if (j===childrenLen-1) childrenLen--;
						if (j===min) min++;
						break;
					}
				}
			}

			// morph the matched/found/created DOM child to match vchild (deep)
			child = idiff(child, vchild, context, mountAll);

			if (child && child!==dom) {
				if (i>=len) {
					dom.appendChild(child);
				}
				else if (child!==originalChildren[i]) {
					if (child===originalChildren[i+1]) {
						removeNode(originalChildren[i]);
					}
					else {
						dom.insertBefore(child, originalChildren[i] || null);
					}
				}
			}
		}
	}

	// remove unused keyed children:
	if (keyedLen) {
		for (let i in keyed) if (keyed[i]!==undefined) recollectNodeTree(keyed[i], false);
	}

	// remove orphaned unkeyed children:
	while (min<=childrenLen) {
		if ((child = children[childrenLen--])!==undefined) recollectNodeTree(child, false);
	}
}

/** Recursively recycle (or just unmount) a node an its descendants.
 *	@param {Node} node						DOM node to start unmount/removal from
 *	@param {Boolean} [unmountOnly=false]	If `true`, only triggers unmount lifecycle, skips removal
 */
export function recollectNodeTree(node, unmountOnly) {
	let component = node._component;
	if (component) {
		// if node is owned by a Component, unmount that component (ends up recursing back here)
		unmountComponent(component);
	}
	else {
		// If the node's VNode had a ref function, invoke it with null here.
		// (this is part of the React spec, and smart for unsetting references)
		if (node[ATTR_KEY]!=null && node[ATTR_KEY].ref) node[ATTR_KEY].ref(null);

		if (unmountOnly===false || node[ATTR_KEY]==null) {
			removeNode(node);
		}

		removeChildren(node);
	}
}

/** Recollect/unmount all children.
 *	- we use .lastChild here because it causes less reflow than .firstChild
 *	- it's also cheaper than accessing the .childNodes Live NodeList
 */
export function removeChildren(node) {
	node = node.lastChild;
	while (node) {
		let next = node.previousSibling;
		recollectNodeTree(node, true);
		node = next;
	}
}

/** Apply differences in attributes from a VNode to the given DOM Element.
 *	@param {Element} dom		Element with attributes to diff `attrs` against
 *	@param {Object} attrs		The desired end-state key-value attribute pairs
 *	@param {Object} old			Current/previous attributes (from previous VNode or element's prop cache)
 */
function diffAttributes(dom, attrs, old) {
	let name;

	// remove attributes no longer present on the vnode by setting them to undefined
	for (name in old) {
		if (!(attrs && attrs[name]!=null) && old[name]!=null) {
			setAccessor(dom, name, old[name], old[name] = undefined, isSvgMode);
		}
	}

	// add new & update changed attributes
	for (name in attrs) {
		if (name!=='children' && name!=='innerHTML' && (!(name in old) || attrs[name]!==(name==='value' || name==='checked' ? dom[name] : old[name]))) {
			setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode);
		}
	}
}
<commit_msg>Don't throw on undefined components (`preact/debug` will be doing a much better job of that with proper stack traces).<commit_after>import { ATTR_KEY } from '../constants';
import { isSameNodeType, isNamedNode } from './index';
import { buildComponentFromVNode } from './component';
import { createNode, setAccessor } from '../dom/index';
import { unmountComponent } from './component';
import options from '../options';
import { removeNode } from '../dom';

/** Queue of components that have been mounted and are awaiting componentDidMount */
export const mounts = [];

/** Diff recursion count, used to track the end of the diff cycle. */
export let diffLevel = 0;

/** Global flag indicating if the diff is currently within an SVG */
let isSvgMode = false;

/** Global flag indicating if the diff is performing hydration */
let hydrating = false;

/** Invoke queued componentDidMount lifecycle methods */
export function flushMounts() {
	let c;
	while ((c=mounts.pop())) {
		if (options.afterMount) options.afterMount(c);
		if (c.componentDidMount) c.componentDidMount();
	}
}

/** Apply differences in a given vnode (and it's deep children) to a real DOM Node.
 *	@param {Element} [dom=null]		A DOM node to mutate into the shape of the `vnode`
 *	@param {VNode} vnode			A VNode (with descendants forming a tree) representing the desired DOM structure
 *	@returns {Element} dom			The created/mutated element
 *	@private
 */
export function diff(dom, vnode, context, mountAll, parent, componentRoot) {
	// diffLevel having been 0 here indicates initial entry into the diff (not a subdiff)
	if (!diffLevel++) {
		// when first starting the diff, check if we're diffing an SVG or within an SVG
		isSvgMode = parent!=null && parent.ownerSVGElement!==undefined;

		// hydration is inidicated by the existing element to be diffed not having a prop cache
		hydrating = dom!=null && !(ATTR_KEY in dom);
	}

	let ret = idiff(dom, vnode, context, mountAll, componentRoot);

	// append the element if its a new parent
	if (parent && ret.parentNode!==parent) parent.appendChild(ret);

	// diffLevel being reduced to 0 means we're exiting the diff
	if (!--diffLevel) {
		hydrating = false;
		// invoke queued componentDidMount lifecycle methods
		if (!componentRoot) flushMounts();
	}

	return ret;
}

/** Internals of `diff()`, separated to allow bypassing diffLevel / mount flushing. */
function idiff(dom, vnode, context, mountAll, componentRoot) {
	let out = dom,
		prevSvgMode = isSvgMode;

	// empty values (null & undefined) render as empty Text nodes
	if (vnode==null) vnode = '';

	// Fast case: Strings create/update Text nodes.
	if (typeof vnode==='string') {

		// update if it's already a Text node:
		if (dom && dom.splitText!==undefined && dom.parentNode && (!dom._component || componentRoot)) {
			if (dom.nodeValue!=vnode) {
				dom.nodeValue = vnode;
			}
		}
		else {
			// it wasn't a Text node: replace it with one and recycle the old Element
			out = document.createTextNode(vnode);
			if (dom) {
				if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
				recollectNodeTree(dom, true);
			}
		}

		out[ATTR_KEY] = true;

		return out;
	}

	// If the VNode represents a Component, perform a component diff:
	if (typeof vnode.nodeName==='function') {
		return buildComponentFromVNode(dom, vnode, context, mountAll);
	}

	// Tracks entering and exiting SVG namespace when descending through the tree.
	isSvgMode = vnode.nodeName==='svg' ? true : vnode.nodeName==='foreignObject' ? false : isSvgMode;

	// If there's no existing element or it's the wrong type, create a new one:
	if (!dom || !isNamedNode(dom, String(vnode.nodeName))) {
		out = createNode(String(vnode.nodeName), isSvgMode);

		if (dom) {
			// move children into the replacement node
			while (dom.firstChild) out.appendChild(dom.firstChild);

			// if the previous Element was mounted into the DOM, replace it inline
			if (dom.parentNode) dom.parentNode.replaceChild(out, dom);

			// recycle the old element (skips non-Element node types)
			recollectNodeTree(dom, true);
		}
	}

	let fc = out.firstChild,
		props = out[ATTR_KEY] || (out[ATTR_KEY] = {}),
		vchildren = vnode.children;

	// Optimization: fast-path for elements containing a single TextNode:
	if (!hydrating && vchildren && vchildren.length===1 && typeof vchildren[0]==='string' && fc!=null && fc.splitText!==undefined && fc.nextSibling==null) {
		if (fc.nodeValue!=vchildren[0]) {
			fc.nodeValue = vchildren[0];
		}
	}
	// otherwise, if there are existing or new children, diff them:
	else if (vchildren && vchildren.length || fc!=null) {
		innerDiffNode(out, vchildren, context, mountAll, hydrating || props.dangerouslySetInnerHTML!=null);
	}

	// Apply attributes/props from VNode to the DOM Element:
	diffAttributes(out, vnode.attributes, props);

	// restore previous SVG mode: (in case we're exiting an SVG namespace)
	isSvgMode = prevSvgMode;

	return out;
}

/** Apply child and attribute changes between a VNode and a DOM Node to the DOM.
 *	@param {Element} dom			Element whose children should be compared & mutated
 *	@param {Array} vchildren		Array of VNodes to compare to `dom.childNodes`
 *	@param {Object} context			Implicitly descendant context object (from most recent `getChildContext()`)
 *	@param {Boolean} mountAll
 *	@param {Boolean} isHydrating	If `true`, consumes externally created elements similar to hydration
 */
function innerDiffNode(dom, vchildren, context, mountAll, isHydrating) {
	let originalChildren = dom.childNodes,
		children = [],
		keyed = {},
		keyedLen = 0,
		min = 0,
		len = originalChildren.length,
		childrenLen = 0,
		vlen = vchildren ? vchildren.length : 0,
		j, c, vchild, child;

	// Build up a map of keyed children and an Array of unkeyed children:
	if (len!==0) {
		for (let i=0; i<len; i++) {
			let child = originalChildren[i],
				props = child[ATTR_KEY],
				key = vlen && props ? child._component ? child._component.__key : props.key : null;
			if (key!=null) {
				keyedLen++;
				keyed[key] = child;
			}
			else if (props || (child.splitText!==undefined ? (isHydrating ? child.nodeValue.trim() : true) : isHydrating)) {
				children[childrenLen++] = child;
			}
		}
	}

	if (vlen!==0) {
		for (let i=0; i<vlen; i++) {
			vchild = vchildren[i];
			child = null;

			// attempt to find a node based on key matching
			let key = vchild.key;
			if (key!=null) {
				if (keyedLen && keyed[key]!==undefined) {
					child = keyed[key];
					keyed[key] = undefined;
					keyedLen--;
				}
			}
			// attempt to pluck a node of the same type from the existing children
			else if (!child && min<childrenLen) {
				for (j=min; j<childrenLen; j++) {
					if (children[j]!==undefined && isSameNodeType(c = children[j], vchild, isHydrating)) {
						child = c;
						children[j] = undefined;
						if (j===childrenLen-1) childrenLen--;
						if (j===min) min++;
						break;
					}
				}
			}

			// morph the matched/found/created DOM child to match vchild (deep)
			child = idiff(child, vchild, context, mountAll);

			if (child && child!==dom) {
				if (i>=len) {
					dom.appendChild(child);
				}
				else if (child!==originalChildren[i]) {
					if (child===originalChildren[i+1]) {
						removeNode(originalChildren[i]);
					}
					else {
						dom.insertBefore(child, originalChildren[i] || null);
					}
				}
			}
		}
	}

	// remove unused keyed children:
	if (keyedLen) {
		for (let i in keyed) if (keyed[i]!==undefined) recollectNodeTree(keyed[i], false);
	}

	// remove orphaned unkeyed children:
	while (min<=childrenLen) {
		if ((child = children[childrenLen--])!==undefined) recollectNodeTree(child, false);
	}
}

/** Recursively recycle (or just unmount) a node an its descendants.
 *	@param {Node} node						DOM node to start unmount/removal from
 *	@param {Boolean} [unmountOnly=false]	If `true`, only triggers unmount lifecycle, skips removal
 */
export function recollectNodeTree(node, unmountOnly) {
	let component = node._component;
	if (component) {
		// if node is owned by a Component, unmount that component (ends up recursing back here)
		unmountComponent(component);
	}
	else {
		// If the node's VNode had a ref function, invoke it with null here.
		// (this is part of the React spec, and smart for unsetting references)
		if (node[ATTR_KEY]!=null && node[ATTR_KEY].ref) node[ATTR_KEY].ref(null);

		if (unmountOnly===false || node[ATTR_KEY]==null) {
			removeNode(node);
		}

		removeChildren(node);
	}
}

/** Recollect/unmount all children.
 *	- we use .lastChild here because it causes less reflow than .firstChild
 *	- it's also cheaper than accessing the .childNodes Live NodeList
 */
export function removeChildren(node) {
	node = node.lastChild;
	while (node) {
		let next = node.previousSibling;
		recollectNodeTree(node, true);
		node = next;
	}
}

/** Apply differences in attributes from a VNode to the given DOM Element.
 *	@param {Element} dom		Element with attributes to diff `attrs` against
 *	@param {Object} attrs		The desired end-state key-value attribute pairs
 *	@param {Object} old			Current/previous attributes (from previous VNode or element's prop cache)
 */
function diffAttributes(dom, attrs, old) {
	let name;

	// remove attributes no longer present on the vnode by setting them to undefined
	for (name in old) {
		if (!(attrs && attrs[name]!=null) && old[name]!=null) {
			setAccessor(dom, name, old[name], old[name] = undefined, isSvgMode);
		}
	}

	// add new & update changed attributes
	for (name in attrs) {
		if (name!=='children' && name!=='innerHTML' && (!(name in old) || attrs[name]!==(name==='value' || name==='checked' ? dom[name] : old[name]))) {
			setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode);
		}
	}
}
<|endoftext|>


<commit_before>import colors from '../settings/colors';
import styles from '../settings/styles';
import darken from '../internal/darken';

export default {
  root: {
    borderRadius: '3px',
    backgroundColor: colors.white,
    overflow: 'hidden',
    width: '100%',
    height: '200px',
    boxShadow: styles.depthShadows[0],
    position: 'relative',
    zIndex: 1
  },
  header: {
    backgroundColor: colors.theme,
    color: colors.white,
    transition: 'background .3s ease-in-out',
    padding: '10px',
    fontSize: '16px'
  },
  commands: {
    height: 'calc(100% - 40px)',
    overflowY: 'scroll'
  },
  command: {
    padding: '10px 20px 10px 10px',
    margin: 0,
    fontSize: '14px',
    cursor: 'pointer',
    color: colors.primaryText,
    transition: 'all .3s ease-in-out',

    ':hover': {
      backgroundColor: darken(colors.white, 0.05)
    },
    ':active': {
      backgroundColor: darken(colors.white, 0.15)
    }
  },
  title: {
    fontWeight: 'bold',
    marginRight: '5px',
    fontSize: '14px'
  },
  description: {
    fontStyle: 'italic',
    fontSize: '14px',
    float: 'right'
  },
  clickAway: {
    pointerEvents: 'all',
    position: 'fixed',
    width: '100%',
    height: '100%',
    top: 0,
    left: 0,
    zIndex: 1,
    opacity: 0
  },
  container: {
    width: '100%'
  }
};
<commit_msg>:lipstick: Changed color<commit_after>import colors from '../settings/colors';
import styles from '../settings/styles';
import darken from '../internal/darken';

export default {
  root: {
    borderRadius: '3px',
    backgroundColor: colors.white,
    overflow: 'hidden',
    width: '100%',
    height: '200px',
    boxShadow: styles.depthShadows[0],
    position: 'relative',
    zIndex: 1
  },
  header: {
    backgroundColor: colors.theme,
    color: colors.white,
    transition: 'background .3s ease-in-out',
    padding: '10px',
    fontSize: '16px'
  },
  commands: {
    height: 'calc(100% - 40px)',
    overflowY: 'scroll'
  },
  command: {
    padding: '10px 20px 10px 10px',
    margin: 0,
    fontSize: '14px',
    cursor: 'pointer',
    color: colors.secondaryText,
    transition: 'all .3s ease-in-out',

    ':hover': {
      backgroundColor: darken(colors.white, 0.05)
    },
    ':active': {
      backgroundColor: darken(colors.white, 0.15)
    }
  },
  title: {
    fontWeight: 'bold',
    marginRight: '5px',
    fontSize: '14px'
  },
  description: {
    fontStyle: 'italic',
    fontSize: '14px',
    float: 'right'
  },
  clickAway: {
    pointerEvents: 'all',
    position: 'fixed',
    width: '100%',
    height: '100%',
    top: 0,
    left: 0,
    zIndex: 1,
    opacity: 0
  },
  container: {
    width: '100%'
  }
};
<|endoftext|>


<commit_before>const steps = [
  { label_en: 'Pick your base', label_el: 'Διάλεξε γεύση' },
  { label_en: 'Add your toppings', label_el: 'Πρόσθεσε toppings' },
  { label_en: 'Enjoy!', label_el: 'Απόλαυσε!' }
]

const headline = {
  content_en: 'Enjoying summer is as simple as 1, 2, 3!',
  content_el: 'Απόλαυσε... καλοκαίρι με 3 βήματα!'
}

const body = {
  content_en: [
    'No matter the calendar season, you can always get that "sunshine and lollipops" feeling by devouring some Yogo Frozen!',
    'Create your own cup full of summer in three simple steps:'
  ],
  content_el: [
    'Ανεξαρτήτως εποχής, μπορείς να γεμίσεις ηλιόλουστη και δροσιστική διάθεση τρώγοντας Yogo Frozen!',
    'Φτιάξε ένα κυπελλάκι που θα ξεχυλίζει καλοκαίρι, ακολουθώντας τρία απλά βήματα:'
  ]
}

const buttons = {
  content_en: {
    back: 'back',
    next: 'next',
    vote: 'vote!'
  },
  content_el: {
    back: 'ΠΙΣΩ',
    next: 'ΕΠΟΜΕΝΟ',
    vote: 'ΨΗΦΙΣΕ!'
  }
}

const flavourIntro = {
  content_en: 'It all starts with a solid base! From plain classic, to extravagant mango, you can rest assured you will always be getting fresh, pure, Greek yoghurt.',
  content_el: 'Όλα ξεκινούν απο μία σταθερή βάση! Από απλή κλασσική σε πολυτελής μάνγκο, το σίγουρο είναι ότι πάντα θα παίρνεις φρέσκο, καθαρό, Ελληνικό γιαούρτι.'
}

const toppingsIntro = {
  content_en: 'Perfect! Next step is to add as many of our delicious toppings as your heart desires!',
  content_el: 'Τέλεια! Το επόμενο βήμα είναι να προσθέσεις όσα από τα πεντανόστιμά μας toppings τραβάει η καρδιά σου!'
}

const votingIntro = {
  content_en: [
    'The last and definitely most important step, is to enjoy your tasty creation.',
    'It is also the easiest step! Who wouldn\'t enjoy a fresh froyo',
    'If you are satisfied with your picks and are wondering what the most popular ones are, vote! Prizes await each month\'s luckiest participants!'
  ],
  content_el: [
    'Το τελευταίο και πιο σημαντικό βήμα είναι να απολαύσεις τη δημιουργία σου.',
    'Ταυτόχρονα είναι και το πιο εύκολο! Ποιός δεν θα απολάμβανε ένα φρέσκο παγωμένο γιαούρτι',
    'Έαν είσαι ευχαριστημένος από τις επιλογές σου και αναρωτιέσαι ποιές είναι οι πιο δημοφιλής, ψήφισε! Πλούσια δώρα περιμένουν τους πιο τυχερούς συμμετέχοντες του μήνα!'
  ]
}

const voted = {
  content_en: 'Thanks for voting! We\'ll get back to you once we start processing votes.',
  content_el: 'Ευχαριστούμε για την ψήφο σας! Θα επανέλθουμε όταν ξεκινήσουμε την καταμέτρηση.'
}

export default {
  steps,
  headline,
  body,
  buttons,
  flavourIntro,
  toppingsIntro,
  votingIntro,
  voted
}
<commit_msg>Removes the promise of prizes for voting.<commit_after>const steps = [
  { label_en: 'Pick your base', label_el: 'Διάλεξε γεύση' },
  { label_en: 'Add your toppings', label_el: 'Πρόσθεσε toppings' },
  { label_en: 'Enjoy!', label_el: 'Απόλαυσε!' }
]

const headline = {
  content_en: 'Enjoying summer is as simple as 1, 2, 3!',
  content_el: 'Απόλαυσε... καλοκαίρι με 3 βήματα!'
}

const body = {
  content_en: [
    'No matter the calendar season, you can always get that "sunshine and lollipops" feeling by devouring some Yogo Frozen!',
    'Create your own cup full of summer in three simple steps:'
  ],
  content_el: [
    'Ανεξαρτήτως εποχής, μπορείς να γεμίσεις ηλιόλουστη και δροσιστική διάθεση τρώγοντας Yogo Frozen!',
    'Φτιάξε ένα κυπελλάκι που θα ξεχυλίζει καλοκαίρι, ακολουθώντας τρία απλά βήματα:'
  ]
}

const buttons = {
  content_en: {
    back: 'back',
    next: 'next',
    vote: 'vote!'
  },
  content_el: {
    back: 'ΠΙΣΩ',
    next: 'ΕΠΟΜΕΝΟ',
    vote: 'ΨΗΦΙΣΕ!'
  }
}

const flavourIntro = {
  content_en: 'It all starts with a solid base! From plain classic, to extravagant mango, you can rest assured you will always be getting fresh, pure, Greek yoghurt.',
  content_el: 'Όλα ξεκινούν απο μία σταθερή βάση! Από απλή κλασσική σε πολυτελής μάνγκο, το σίγουρο είναι ότι πάντα θα παίρνεις φρέσκο, καθαρό, Ελληνικό γιαούρτι.'
}

const toppingsIntro = {
  content_en: 'Perfect! Next step is to add as many of our delicious toppings as your heart desires!',
  content_el: 'Τέλεια! Το επόμενο βήμα είναι να προσθέσεις όσα από τα πεντανόστιμά μας toppings τραβάει η καρδιά σου!'
}

const votingIntro = {
  content_en: [
    'The last and definitely most important step, is to enjoy your tasty creation.',
    'It is also the easiest step! Who wouldn\'t enjoy a fresh froyo',
    'If you are satisfied with your picks and are wondering what the most popular ones are, vote!'
  ],
  content_el: [
    'Το τελευταίο και πιο σημαντικό βήμα είναι να απολαύσεις τη δημιουργία σου.',
    'Ταυτόχρονα είναι και το πιο εύκολο! Ποιός δεν θα απολάμβανε ένα φρέσκο παγωμένο γιαούρτι',
    'Έαν είσαι ευχαριστημένος από τις επιλογές σου και αναρωτιέσαι ποιές είναι οι πιο δημοφιλής, ψήφισε!'
  ]
}

const voted = {
  content_en: 'Thanks for voting! We\'ll get back to you once we start processing votes.',
  content_el: 'Ευχαριστούμε για την ψήφο σας! Θα επανέλθουμε όταν ξεκινήσουμε την καταμέτρηση.'
}

export default {
  steps,
  headline,
  body,
  buttons,
  flavourIntro,
  toppingsIntro,
  votingIntro,
  voted
}
<|endoftext|>


<commit_before>import * as constants from './constants';

export function newKernel(kernelSpecName, cwd) {
  return {
    type: constants.LAUNCH_KERNEL,
    kernelSpecName,
    cwd,
  };
}

export function setNotebookKernelInfo(kernelInfo) {
  return {
    type: constants.SET_KERNEL_INFO,
    kernelInfo,
  };
}

export function setExecutionState(executionState) {
  return {
    type: constants.SET_EXECUTION_STATE,
    executionState,
  };
}

export function updateCellSource(id, source) {
  return {
    type: constants.UPDATE_CELL_SOURCE,
    id,
    source,
  };
}

export function updateCellOutputs(id, outputs) {
  return {
    type: constants.UPDATE_CELL_OUTPUTS,
    id,
    outputs,
  };
}

export function moveCell(id, destinationId, above) {
  return {
    type: constants.MOVE_CELL,
    id,
    destinationId,
    above,
  };
}

export function removeCell(id) {
  return {
    type: constants.REMOVE_CELL,
    id,
  };
}

export function createCellAfter(cellType, id, source) {
  return {
    type: constants.NEW_CELL_AFTER,
    source: source || '',
    cellType,
    id,
  };
}

export function createCellBefore(cellType, id) {
  return {
    type: constants.NEW_CELL_BEFORE,
    cellType,
    id,
  };
}

export function createCellAppend(cellType) {
  return {
    type: constants.NEW_CELL_APPEND,
    cellType,
  };
}

export function mergeCellAfter(id) {
  return {
    type: constants.MERGE_CELL_AFTER,
    id,
  };
}

export function updateCellExecutionCount(id, count) {
  return {
    type: constants.UPDATE_CELL_EXECUTION_COUNT,
    id,
    count,
  };
}

export function clearCellOutput(id) {
  return {
    type: constants.CLEAR_CELL_OUTPUT,
    id,
  };
}

export function changeOutputVisibility(id) {
  return {
    type: constants.CHANGE_OUTPUT_VISIBILITY,
    id,
  };
}

export function changeInputVisibility(id) {
  return {
    type: constants.CHANGE_INPUT_VISIBILITY,
    id,
  };
}

export function updateCellPagers(id, pagers) {
  return {
    type: constants.UPDATE_CELL_PAGERS,
    id,
    pagers,
  };
}

export function updateCellStatus(id, status) {
  return {
    type: constants.UPDATE_CELL_STATUS,
    id,
    status,
  };
}

export function focusCell(id) {
  return {
    type: constants.FOCUS_CELL,
    id,
  };
}

export function focusNextCell(id, createCellIfUndefined) {
  return {
    type: constants.FOCUS_NEXT_CELL,
    id,
    createCellIfUndefined,
  };
}

export function focusPreviousCell(id) {
  return {
    type: constants.FOCUS_PREVIOUS_CELL,
    id,
  };
}

export function toggleStickyCell(id) {
  return {
    type: constants.TOGGLE_STICKY_CELL,
    id,
  };
}

export function splitCell(id, position) {
  return {
    type: constants.SPLIT_CELL,
    id,
    position,
  };
}

export function overwriteMetadata(field, value) {
  return {
    type: constants.OVERWRITE_METADATA_FIELD,
    field,
    value,
  };
}

export const killKernel = {
  type: constants.KILL_KERNEL,
};

export const interruptKernel = {
  type: constants.INTERRUPT_KERNEL,
};

export function setNotificationSystem(notificationSystem) {
  return {
    type: constants.SET_NOTIFICATION_SYSTEM,
    notificationSystem,
  };
}

export function setForwardCheckpoint(documentState) {
  return {
    type: constants.SET_FORWARD_CHECKPOINT,
    documentState,
  };
}

export function setBackwardCheckpoint(documentState, clearFutureStack) {
  return {
    type: constants.SET_BACKWARD_CHECKPOINT,
    documentState,
    clearFutureStack,
  };
}

export function copyCell(id) {
  return {
    type: constants.COPY_CELL,
    id,
  };
}

export function cutCell(id) {
  return {
    type: constants.CUT_CELL,
    id,
  };
}

export function pasteCell() {
  return {
    type: constants.PASTE_CELL,
  };
}

export function changeCellType(id, to) {
  return {
    type: constants.CHANGE_CELL_TYPE,
    id,
    to,
  };
}

export function setAnonGithub() {
  return {
    type: constants.SET_ANON_GITHUB,
  };
}

export function setUserGithub() {
  return {
    type: constants.SET_USER_GITHUB,
  };
}

export function setGithubToken(githubToken) {
  return {
    type: constants.SET_GITHUB_TOKEN,
    githubToken,
  };
}

export function setKey(key, value) {
  return {
    type: constants.SET_KEY,
    key,
    value,
  };
}
<commit_msg>fix(config): Update setKey action creator to setConfigKey<commit_after>import * as constants from './constants';

export function newKernel(kernelSpecName, cwd) {
  return {
    type: constants.LAUNCH_KERNEL,
    kernelSpecName,
    cwd,
  };
}

export function setNotebookKernelInfo(kernelInfo) {
  return {
    type: constants.SET_KERNEL_INFO,
    kernelInfo,
  };
}

export function setExecutionState(executionState) {
  return {
    type: constants.SET_EXECUTION_STATE,
    executionState,
  };
}

export function updateCellSource(id, source) {
  return {
    type: constants.UPDATE_CELL_SOURCE,
    id,
    source,
  };
}

export function updateCellOutputs(id, outputs) {
  return {
    type: constants.UPDATE_CELL_OUTPUTS,
    id,
    outputs,
  };
}

export function moveCell(id, destinationId, above) {
  return {
    type: constants.MOVE_CELL,
    id,
    destinationId,
    above,
  };
}

export function removeCell(id) {
  return {
    type: constants.REMOVE_CELL,
    id,
  };
}

export function createCellAfter(cellType, id, source) {
  return {
    type: constants.NEW_CELL_AFTER,
    source: source || '',
    cellType,
    id,
  };
}

export function createCellBefore(cellType, id) {
  return {
    type: constants.NEW_CELL_BEFORE,
    cellType,
    id,
  };
}

export function createCellAppend(cellType) {
  return {
    type: constants.NEW_CELL_APPEND,
    cellType,
  };
}

export function mergeCellAfter(id) {
  return {
    type: constants.MERGE_CELL_AFTER,
    id,
  };
}

export function updateCellExecutionCount(id, count) {
  return {
    type: constants.UPDATE_CELL_EXECUTION_COUNT,
    id,
    count,
  };
}

export function clearCellOutput(id) {
  return {
    type: constants.CLEAR_CELL_OUTPUT,
    id,
  };
}

export function changeOutputVisibility(id) {
  return {
    type: constants.CHANGE_OUTPUT_VISIBILITY,
    id,
  };
}

export function changeInputVisibility(id) {
  return {
    type: constants.CHANGE_INPUT_VISIBILITY,
    id,
  };
}

export function updateCellPagers(id, pagers) {
  return {
    type: constants.UPDATE_CELL_PAGERS,
    id,
    pagers,
  };
}

export function updateCellStatus(id, status) {
  return {
    type: constants.UPDATE_CELL_STATUS,
    id,
    status,
  };
}

export function focusCell(id) {
  return {
    type: constants.FOCUS_CELL,
    id,
  };
}

export function focusNextCell(id, createCellIfUndefined) {
  return {
    type: constants.FOCUS_NEXT_CELL,
    id,
    createCellIfUndefined,
  };
}

export function focusPreviousCell(id) {
  return {
    type: constants.FOCUS_PREVIOUS_CELL,
    id,
  };
}

export function toggleStickyCell(id) {
  return {
    type: constants.TOGGLE_STICKY_CELL,
    id,
  };
}

export function splitCell(id, position) {
  return {
    type: constants.SPLIT_CELL,
    id,
    position,
  };
}

export function overwriteMetadata(field, value) {
  return {
    type: constants.OVERWRITE_METADATA_FIELD,
    field,
    value,
  };
}

export const killKernel = {
  type: constants.KILL_KERNEL,
};

export const interruptKernel = {
  type: constants.INTERRUPT_KERNEL,
};

export function setNotificationSystem(notificationSystem) {
  return {
    type: constants.SET_NOTIFICATION_SYSTEM,
    notificationSystem,
  };
}

export function setForwardCheckpoint(documentState) {
  return {
    type: constants.SET_FORWARD_CHECKPOINT,
    documentState,
  };
}

export function setBackwardCheckpoint(documentState, clearFutureStack) {
  return {
    type: constants.SET_BACKWARD_CHECKPOINT,
    documentState,
    clearFutureStack,
  };
}

export function copyCell(id) {
  return {
    type: constants.COPY_CELL,
    id,
  };
}

export function cutCell(id) {
  return {
    type: constants.CUT_CELL,
    id,
  };
}

export function pasteCell() {
  return {
    type: constants.PASTE_CELL,
  };
}

export function changeCellType(id, to) {
  return {
    type: constants.CHANGE_CELL_TYPE,
    id,
    to,
  };
}

export function setAnonGithub() {
  return {
    type: constants.SET_ANON_GITHUB,
  };
}

export function setUserGithub() {
  return {
    type: constants.SET_USER_GITHUB,
  };
}

export function setGithubToken(githubToken) {
  return {
    type: constants.SET_GITHUB_TOKEN,
    githubToken,
  };
}

export function setConfigKey(key, value) {
  return {
    type: constants.SET_CONFIG_KEY,
    key,
    value,
  };
}
<|endoftext|>


<commit_before>// detect node for conditional import for jsonToFormData
const isNode = typeof process !== 'undefined' && process.versions && !!process.versions.node
if (isNode) {
// TODO : deal with node.js side  for example using https://www.npmjs.com/package/form-data: fake one for now
}

export function jsonToFormData (jsonData) {
  jsonData = JSON.parse(JSON.stringify(jsonData))
  let formData
  if (isNode) {
    formData = {append: function (fieldName, value) {}} // FIXME: hack for tests/nodes.js
  } else {
    formData = new FormData()
  }
  for (let fieldName in jsonData) {
    let value = jsonData[fieldName]
    // value = encodeURIComponent(JSON.stringify(value))
    // value = JSON.stringify(value)
    // value = value.replace(/\"/g, '')
    if (Object.prototype.toString.call(value) === '[object Object]') {
      value = JSON.stringify(value)
    // console.log("value",value)
    }
    if (Object.prototype.toString.call(value) === '[object Array]') {
      // value = //JSON.stringify(value)
      // value = 'arr[]', arr[i]//value.reduce()
      // console.log("value",value)
      value = `{ ${value.join(',')} }`
    }
    if(typeof value === 'boolean') {
      value = `'${value}'`
    }

    // console.log("append",fieldName, value)
    formData.append(fieldName, value)
  }
  return formData
}
<commit_msg>fix(boolean formadata handling): fixed boolean formdata field handling (for real this time)<commit_after>// detect node for conditional import for jsonToFormData
const isNode = typeof process !== 'undefined' && process.versions && !!process.versions.node
if (isNode) {
// TODO : deal with node.js side  for example using https://www.npmjs.com/package/form-data: fake one for now
}

export function jsonToFormData (jsonData) {
  jsonData = JSON.parse(JSON.stringify(jsonData))
  let formData
  if (isNode) {
    formData = {append: function (fieldName, value) {}} // FIXME: hack for tests/nodes.js
  } else {
    formData = new FormData()
  }
  for (let fieldName in jsonData) {
    let value = jsonData[fieldName]
    // value = encodeURIComponent(JSON.stringify(value))
    // value = JSON.stringify(value)
    // value = value.replace(/\"/g, '')
    if (Object.prototype.toString.call(value) === '[object Object]') {
      value = JSON.stringify(value)
    // console.log("value",value)
    }
    if (Object.prototype.toString.call(value) === '[object Array]') {
      // value = //JSON.stringify(value)
      // value = 'arr[]', arr[i]//value.reduce()
      // console.log("value",value)
      value = `{ ${value.join(',')} }`
    }
    if (typeof value === 'boolean') {
      value = '' + value
    }

    // console.log("append",fieldName, value)
    formData.append(fieldName, value)
  }
  return formData
}
<|endoftext|>