<commit_before>
define( [ "slick/paging/Local",
	"slick/paging/Remote",
	"slick/paging/Conditions",
	"slick/core/Dataview" ], function( Local, Remote, Conditions ) {

	var html =
			"
" +
			"
" +
				"<button class='pager-prev' disabled='disabled'></button>" +
				"<button class='pager-next' disabled='disabled'></button>" +
			"
" +

			"
" +
				"<input type='text' class='pager-current' maxlength='5' value='1'>" +
				"<button disabled='disabled' class='pager-total'>1</button>" +
			"
" +

			"
" +
				"<input type='checkbox' class='slick-fast-query' id='slick-fast-query' checked='checked'>" +
				"" +
			"
" +

			"

" +

			"
" +
				"" +
					"<select></select>" +
				"" +
			"
" +
			"
"

	, defaults = {

		container: undefined,

		pagingInfo: {
			pageSize: 50,
			pageNum: 0,

			sizes: [ 50, 100 ]
		}
	};

	return function( $G, dataView, options ) {

		var settings = $.extend( {}, defaults, options || {} )

		, container = $( html )

		, current = container.find( "input.pager-current" )
		, size = container.find( "select:first" )
		, total = container.find( "button.pager-total" )

		, ajaxOptions = options.ajaxOptions

		/** Update the paging info to UI */
		, uiRefresh = function( pagingInfo ) {

			var

			  prev = container.find( ".pager-prev" ),
			  next = container.find( ".pager-next" ),

			  value = pagingInfo.pageNum >= 0 ? ++pagingInfo.pageNum : 1;
			  max = pagingInfo.totalPages || 1;

			/** Clear the last state, prevent has been disabled after the size change */
			prev.removeAttr( "disabled" ), next.removeAttr( "disabled" );

			(value < max && value > 1) && ( prev.removeAttr( "disabled" ), next.removeAttr( "disabled" ) );

			value <= 1 && prev.attr( "disabled", "disabled" );
			value === max && next.attr( "disabled", "disabled" );

			$G.resetActiveCell();

			current.val( value );
			size.val( pagingInfo.pageSize );
			total.html( max ).attr( "data-total", max );
		}

		/** A function that implement for paging */
		, pager;

		dataView.onRowCountChanged.subscribe( function() {
			$G.updateRowCount();
			$G.render();
		});

		dataView.onRowsChanged.subscribe( function( e, args ) {
			$G.invalidateRows( args.rows );
			$G.render();
		} );

		/** Prevent refresh dataview */
		dataView.beginUpdate();

		for ( var sizes = settings.pagingInfo.sizes, length = sizes.length, i = 0; i < length; ) {

			/** Right now DOM is not in the render tree, so there is no reflow */
			size.append( "<option value=" + sizes[ i ] + ">" + sizes[ i++ ] + "</option>" );
		}

		/** All operations in local */
		if ( !ajaxOptions ) {

			dataView.setItems( settings.data );

			/** Skip the first notify */
			dataView.setPagingOptions( settings.pagingInfo );

			dataView.onPagingInfoChanged.subscribe( function( e, args ) {

				if ( args.doSearch ) {

					pager( args.pagingInfo || {

						pageSize: +size.val(),
						pageNum: +current.val() - 1
					} );
				} else uiRefresh( dataView.getPagingInfo() );
			} );

			(pager = Local( $G, true ))( dataView.getPagingInfo() );
		} else {

			dataView.onPagingInfoChanged.subscribe( function( e, args ) {

				if ( args.doSearch ) {

					pager( args.pagingInfo || {
						pageSize: +size.val(),
						/** In SCM the 'pageNum' start from 1, so you should specify an offset to patch it */
						pageNum: +current.val() + 1
					}, uiRefresh, Conditions.getConditions() );

				} else e.stopImmediatePropagation();
			} );

			(pager = Remote( $G, settings.ajaxOptions, true ))( settings.pagingInfo, uiRefresh );
		}

		/** This function will be cause a refresh */
		Conditions = Conditions( $G, container.find( ":checkbox.slick-fast-query" ) );

		/** Refresh dataview */
		dataView.endUpdate();

		container

		.delegate( ".pager-prev", "click", function( e ) {

			e.stopImmediatePropagation();
			e.preventDefault();

			current.val( +current.val() - 1 );

			dataView.onPagingInfoChanged.notify( { doSearch: 1 } );
		} )

		.delegate( ".pager-next", "click", function( e ) {

			e.stopImmediatePropagation();
			e.preventDefault();

			current.val( +current.val() + 1 );

			dataView.onPagingInfoChanged.notify( { doSearch: 1 } );
		} )

		.delegate( "select", "change", function( e ) {

			e.stopImmediatePropagation();

			dataView.onPagingInfoChanged.notify( { doSearch: 1 } );
		} )

		.delegate( "input.pager-current", "keyup", function( e ) {

			var value = +current.val() || 1
			, max = +total.attr( "data-total" ) || 1;

			switch ( e.keyCode ) {

				case 38:
					++value <= max
						? current.val( value )
						: --value;
					break;

				case 40:
					--value >= 1
						? current.val( value )
						: ++value;
					break;

				case 13:

					if ( value <= max && value >= 1 ) {

						current.blur();

						dataView.onPagingInfoChanged.notify( { doSearch: 1 } );
					} else {
						current.select();
					}
					break;
			}

			e.stopImmediatePropagation();
		} )

		.delegate( ":checkbox.slick-fast-query", "click", function( e ) {

			if ( $( this ).is( ":checked" ) ) {

				Local( $G, false );
				Remote( $G, ajaxOptions, true );
			} else {
				Local( $G, true );
				Remote( $G, ajaxOptions, false );
			}
		} )

		.delegate( "div.pager-refresh", "click", function( e ) {

			dataView.onPagingInfoChanged.notify( { doSearch: 1 } );

			$G.setDeleteRows( [] );
			$G.setUpdateRows( [] );
			$G.setAddRows( [] );

			e.stopPropagation();
		} );

		$( $G.getContainerNode() )

			.after( container );

		$.extend( $G, {

			search: function( pagingInfo, VO ) {

				var args = Conditions.getConditions();

				args.result = {

					result: {

						items2Create: JSON.stringify( $G.getAddRows ? $G.getAddRows() : [] ),
						items2Update: JSON.stringify( $G.getUpdateRows ? $G.getUpdateRows() : [] ),
						items2Delete: JSON.stringify( $G.getDeleteRows ? $G.getDeleteRows() : [] ),
						items2Selected: JSON.stringify( $G.getSelectedRow ? $G.getSelectedRows() : [] )
					}
				};

				pager( pagingInfo || {
					pageSize: +size.val(),
					pageNum: 0
				}, uiRefresh, args );
			}
		} );
	};
} );
<commit_msg>Update Paging.js<commit_after>
define( [ "slick/paging/Local",
	"slick/paging/Remote",
	"slick/paging/Conditions",
	"slick/core/Dataview" ], function( Local, Remote, Conditions ) {

	var html =
			"
" +
			"
" +
				"<button class='pager-prev' disabled='disabled'></button>" +
				"<button class='pager-next' disabled='disabled'></button>" +
			"
" +

			"
" +
				"<input type='text' class='pager-current' maxlength='5' value='1'>" +
				"<button disabled='disabled' class='pager-total'>1</button>" +
			"
" +

			"
" +
				"<input type='checkbox' class='slick-fast-query' id='slick-fast-query' checked='checked'>" +
				"" +
			"
" +

			"

" +

			"
" +
				"" +
					"<select></select>" +
				"" +
			"
" +
			"
"

	, defaults = {

		container: undefined,

		pagingInfo: {
			pageSize: 50,
			pageNum: 0,

			sizes: [ 50, 100 ]
		}
	};

	return function( $G, dataView, options ) {

		var settings = $.extend( {}, defaults, options || {} )

		, container = $( html )

		, current = container.find( "input.pager-current" )
		, size = container.find( "select:first" )
		, total = container.find( "button.pager-total" )

		, ajaxOptions = options.ajaxOptions

		/** Update the paging info to UI */
		, uiRefresh = function( pagingInfo ) {

			var

			  prev = container.find( ".pager-prev" ),
			  next = container.find( ".pager-next" ),

			  value = pagingInfo.pageNum >= 0 ? ++pagingInfo.pageNum : 1;
			  max = pagingInfo.totalPages || 1;

			/** Clear the last state, prevent has been disabled after the size change */
			prev.removeAttr( "disabled" ), next.removeAttr( "disabled" );

			(value < max && value > 1) && ( prev.removeAttr( "disabled" ), next.removeAttr( "disabled" ) );

			value <= 1 && prev.attr( "disabled", "disabled" );
			value === max && next.attr( "disabled", "disabled" );

			$G.resetActiveCell();

			current.val( value );
			size.val( pagingInfo.pageSize );
			total.html( max ).attr( "data-total", max );
		}

		, reset = function() {

			$G.setDeleteRows && $G.setDeleteRows( [] );
			$G.setUpdateRows && $G.setUpdateRows( [] );
			$G.setAddRows && $G.setAddRows( [] );

			$G.setSelectedRows( [] );
		}

		/** A function that implement for paging */
		, pager;

		dataView.onRowCountChanged.subscribe( function() {
			$G.updateRowCount();
			$G.render();
		});

		dataView.onRowsChanged.subscribe( function( e, args ) {
			$G.invalidateRows( args.rows );
			$G.render();
		} );

		/** Prevent refresh dataview */
		dataView.beginUpdate();

		for ( var sizes = settings.pagingInfo.sizes, length = sizes.length, i = 0; i < length; ) {

			/** Right now DOM is not in the render tree, so there is no reflow */
			size.append( "<option value=" + sizes[ i ] + ">" + sizes[ i++ ] + "</option>" );
		}

		/** All operations in local */
		if ( !ajaxOptions ) {

			dataView.setItems( settings.data );

			/** Skip the first notify */
			dataView.setPagingOptions( settings.pagingInfo );

			dataView.onPagingInfoChanged.subscribe( function( e, args ) {

				if ( args.doSearch ) {

					pager( args.pagingInfo || {

						pageSize: +size.val(),
						pageNum: +current.val() - 1
					} );
				} else uiRefresh( dataView.getPagingInfo() );
			} );

			(pager = Local( $G, true ))( dataView.getPagingInfo() );
		} else {

			dataView.onPagingInfoChanged.subscribe( function( e, args ) {

				if ( args.doSearch ) {

					pager( args.pagingInfo || {
						pageSize: +size.val(),
						/** In SCM the 'pageNum' start from 1, so you should specify an offset to patch it */
						pageNum: +current.val() + 1
					}, uiRefresh, Conditions.getConditions() );

				} else e.stopImmediatePropagation();
			} );

			(pager = Remote( $G, settings.ajaxOptions, true ))( settings.pagingInfo, uiRefresh );
		}

		/** This function will be cause a refresh */
		Conditions = Conditions( $G, container.find( ":checkbox.slick-fast-query" ) );

		/** Refresh dataview */
		dataView.endUpdate();

		container

		.delegate( ".pager-prev", "click", function( e ) {

			e.stopImmediatePropagation();
			e.preventDefault();

			current.val( +current.val() - 1 );

			dataView.onPagingInfoChanged.notify( { doSearch: 1 } );
		} )

		.delegate( ".pager-next", "click", function( e ) {

			e.stopImmediatePropagation();
			e.preventDefault();

			current.val( +current.val() + 1 );

			dataView.onPagingInfoChanged.notify( { doSearch: 1 } );
		} )

		.delegate( "select", "change", function( e ) {

			e.stopImmediatePropagation();

			dataView.onPagingInfoChanged.notify( { doSearch: 1 } );
		} )

		.delegate( "input.pager-current", "keyup", function( e ) {

			var value = +current.val() || 1
			, max = +total.attr( "data-total" ) || 1;

			switch ( e.keyCode ) {

				case 38:
					++value <= max
						? current.val( value )
						: --value;
					break;

				case 40:
					--value >= 1
						? current.val( value )
						: ++value;
					break;

				case 13:

					if ( value <= max && value >= 1 ) {

						current.blur();

						dataView.onPagingInfoChanged.notify( { doSearch: 1 } );
					} else {
						current.select();
					}
					break;
			}

			e.stopImmediatePropagation();
		} )

		.delegate( ":checkbox.slick-fast-query", "click", function( e ) {

			if ( $( this ).is( ":checked" ) ) {

				Local( $G, false );
				Remote( $G, ajaxOptions, true );
			} else {
				Local( $G, true );
				Remote( $G, ajaxOptions, false );
			}
		} )

		.delegate( "div.pager-refresh", "click", function( e ) {

			dataView.onPagingInfoChanged.notify( { doSearch: 1 } );

			reset();

			e.stopPropagation();
		} );

		$( $G.getContainerNode() )

			.after( container );

		$.extend( $G, {

			search: function( pagingInfo, VO ) {

				var args = Conditions.getConditions();

				args.result = {

					result: {

						items2Create: JSON.stringify( $G.getAddRows ? $G.getAddRows() : [] ),
						items2Update: JSON.stringify( $G.getUpdateRows ? $G.getUpdateRows() : [] ),
						items2Delete: JSON.stringify( $G.getDeleteRows ? $G.getDeleteRows() : [] ),
						items2Selected: JSON.stringify( $G.getSelectedRow ? $G.getSelectedRows() : [] )
					}
				};

				reset();

				return pager( pagingInfo || {
					pageSize: +size.val(),
					pageNum: 0
				}, uiRefresh, args );

			}
		} );
	};
} );
<|endoftext|>


<commit_before>/* jslint node: true */
'use strict';

var Config		= require('./config.js').config;

var _			= require('lodash');
var assert		= require('assert');

exports.parseAsset				= parseAsset;
exports.getAssetWithShorthand	= getAssetWithShorthand;
exports.getArtAsset				= getArtAsset;
exports.getModuleAsset			= getModuleAsset;
exports.resolveConfigAsset		= resolveConfigAsset;
exports.getViewPropertyAsset	= getViewPropertyAsset;

const ALL_ASSETS = [
	'art',
	'menu',
	'method',
	'systemMethod',
	'systemModule',
	'prompt',
	'config',
];

var ASSET_RE = new RegExp('\\@(' + ALL_ASSETS.join('|') + ')\\:([\\w\\d\\.]*)(?:\\/([\\w\\d\\_]+))*');

function parseAsset(s) {
	var m = ASSET_RE.exec(s);

	if(m) {
		var result = { type : m[1] };

		if(m[3]) {
			result.location = m[2];
			result.asset	= m[3];
		} else {
			result.asset	= m[2];
		}

		return result;
	}
}

function getAssetWithShorthand(spec, defaultType) {
	if(!_.isString(spec)) {
		return null;
	}

	if('@' === spec[0]) {
		var asset = parseAsset(spec);
		assert(_.isString(asset.type));

		return asset;
	} else {
		return {
			type	: defaultType,
			asset	: spec,
		}
	}
}

//	:TODO: Convert these to getAssetWithShorthand()
function getArtAsset(art) {
	if(!_.isString(art)) {
		return null;
	}

	if('@' === art[0]) {
		var artAsset = parseAsset(art);
		assert('art' === artAsset.type || 'method' === artAsset.type);

		return artAsset;
	} else {
		return {
			type	: 'art',
			asset	: art,
		};
	}
}

function getModuleAsset(module) {
	if(!_.isString(module)) {
		return null;
	}

	if('@' === module[0]) {
		var modAsset = parseAsset(module);
		assert('module' === modAsset.type || 'systemModule' === modAsset.type);

		return modAsset;
	} else {
		return {
			type	: 'module',
			asset	: module,
		}
	}
}

function resolveConfigAsset(from) {
	var asset = parseAsset(from);
	if(asset) {
		assert('config' === asset.type);

		var path = asset.asset.split('.');
		var conf = Config;
		for(var i = 0; i < path.length; ++i) {
			if(_.isUndefined(conf[path[i]])) {
				return from;
			}
			conf = conf[path[i]];
		}
		return conf;
	} else {
		return from;
	}
}

function getViewPropertyAsset(src) {
	if(!_.isString(src) || '@' !== src.charAt(0)) {
		return null;
	}

	return parseAsset(src);
};
<commit_msg>ES6 + misc cleanup<commit_after>/* jslint node: true */
'use strict';

//	ENiGMA½
const Config	= require('./config.js').config;

//	deps
const _			= require('lodash');
const assert	= require('assert');

exports.parseAsset				= parseAsset;
exports.getAssetWithShorthand	= getAssetWithShorthand;
exports.getArtAsset				= getArtAsset;
exports.getModuleAsset			= getModuleAsset;
exports.resolveConfigAsset		= resolveConfigAsset;
exports.getViewPropertyAsset	= getViewPropertyAsset;

const ALL_ASSETS = [
	'art',
	'menu',
	'method',
	'module',
	'systemMethod',
	'systemModule',
	'prompt',
	'config',
];

const ASSET_RE = new RegExp('\\@(' + ALL_ASSETS.join('|') + ')\\:([\\w\\d\\.]*)(?:\\/([\\w\\d\\_]+))*');

function parseAsset(s) {
	const m = ASSET_RE.exec(s);

	if(m) {
		let result = { type : m[1] };

		if(m[3]) {
			result.location = m[2];
			result.asset	= m[3];
		} else {
			result.asset	= m[2];
		}

		return result;
	}
}

function getAssetWithShorthand(spec, defaultType) {
	if(!_.isString(spec)) {
		return null;
	}

	if('@' === spec[0]) {
		const asset = parseAsset(spec);
		assert(_.isString(asset.type));

		return asset;
	} else {
		return {
			type	: defaultType,
			asset	: spec,
		};
	}
}

function getArtAsset(spec) {
	const asset = getAssetWithShorthand(spec, 'art');

	if(!asset) {
		return null;
	}

	assert( ['art', 'method' ].indexOf(asset.type) > -1);
	return asset;
}

function getModuleAsset(spec) {
	const asset = getAssetWithShorthand(spec, 'module');

	if(!asset) {
		return null;
	}

	assert( ['module', 'systemModule' ].indexOf(asset.type) > -1);
	return asset;
}

function resolveConfigAsset(spec) {
	const asset = parseAsset(spec);
	if(asset) {
		assert('config' === asset.type);

		const path	= asset.asset.split('.');
		let conf	= Config;
		for(let i = 0; i < path.length; ++i) {
			if(_.isUndefined(conf[path[i]])) {
				return spec;
			}
			conf = conf[path[i]];
		}
		return conf;
	} else {
		return spec;
	}
}

function getViewPropertyAsset(src) {
	if(!_.isString(src) || '@' !== src.charAt(0)) {
		return null;
	}

	return parseAsset(src);
}
<|endoftext|>


<commit_before>var md = require('node-markdown').Markdown;

parser = {};

parser.parseItalic = function(string) {
  string = md(string, true, "em");

  var italicRegexp = /<em>(.*)<\/em>/g;
  var italics = string.match(italicRegexp);

  for(i in italics) {
    string = string.replace(italicRegexp, "::$1::");
  }

  return string;
}

parser.parseMiniCode = function(string) {

  string = string.replace('`', '%%')

  return string;
}

module.exports = parser;<commit_msg>Fixing italic parsing<commit_after>var md = require('node-markdown').Markdown;

parser = {};

parser.parseItalic = function(string) {
  string = md(string, true, "em");

  var italicRegexp = /<em>/g;
  var italics = string.match(italicRegexp);

  for(i in italics) {
    string = string.replace("<em>", "::");
    string = string.replace("</em>", "::");
  }

  return string;
}

parser.parseMiniCode = function(string) {

  string = string.replace('`', '%%')

  return string;
}

module.exports = parser;
<|endoftext|>


<commit_before>define([
    'require',
    '../lib/aloha-loader',
    '../logging',
    '../patterns'
], function(require) {
    log = require('../logging').getLogger('edit');

    // Grab a element of the editor controls
    var init = function($el, opts) {
        var $form    = $el.parents('form'),
            $ctrls   = $('.editor-ctrls'),
            buttons  = {};

        // ensure form is ajaxified
        var ajaxify = require('../patterns').ajaxify.init;
        ajaxify($form);

        // I have taken the liberty of commenting out buttons
        // that I believe serve no purpose, if they end up being
        // critical, just uncomment.

        // buttons.b                   = $ctrls.find('.strong');
        buttons.bold                = $ctrls.find('.strong');
        // buttons.i                   = $ctrls.find('.emphasised');
        buttons.italic              = $ctrls.find('.emphasised');
        // buttons.ol                  = $ctrls.find('.list-ordered');
        buttons.insertorderedlist   = $ctrls.find('.list-ordered');
        // buttons.ul                  = $ctrls.find('.list-unordered');
        buttons.insertunorderedlist = $ctrls.find('.list-unordered');
        //buttons.insertparagraph     = $ctrls.find('.paragraph');
        buttons.clear               = $ctrls.find('.clear');
        // buttons.h1                  = $ctrls.find('.header_1');
        buttons.inserth1            = $ctrls.find('.header_1');
        // buttons.h2                  = $ctrls.find('.header_2');
        buttons.inserth2            = $ctrls.find('.header_2');
        // buttons.h3                  = $ctrls.find('.header_3');
        buttons.inserth3            = $ctrls.find('.header_3');
        buttons.upload_image        = $ctrls.find('.upload_image');
        buttons.link_image          = $ctrls.find('.link_image');

        var button_handler = {
                'bold'                  : function(){ document.execCommand('bold'); },

                'italic'                : function(){ document.execCommand('italic'); },

                'insertparagraph'       : function(){ return 0; },

                'insertorderedlist'     : function(){ document.execCommand('insertorderedlist'); },

                'insertunorderedlist'   : function(){ document.execCommand('insertunorderedlist'); },

                'inserth1'              : function(){ wrap_selection('<h1>') },

                'inserth2'              : function(){ wrap_selection('<h2>') },

                'inserth3'              : function(){ wrap_selection('<h3>') },

                'clear'                 : function(){
                                                var selection_node = $(window.getSelection().anchorNode);
                                                document.execCommand('removeformat');
                                                if (is_contenteditable(selection_node)) {
                                                    selection_node.unwrap();
                                                    if (!$(selection_node).parent().is("p")) {
                                                        $(selection_node).wrap('<p>');
                                                    }
                                                }
                                          },

                'upload_image'          : function(){ document.execCommand(); },

                'link_image'            : function(){
                                                var source = prompt('URL of Image');
                                                if(source) {
                                                  document.execCommand('insertImage', false, source);
                                                }
                                          }
            };

        // utility method for determining if something is contenteditable
        var is_contenteditable = function(element) {
            mapped_elements = $(element).parents().map(function() {
                            if ($(this).is("[contenteditable='true']")) {
                                        return true;
                            }
                              }).get();

            // mapped_element[0] is the closest parent
            // in the document tree -- If it's true
            // the element will inherit contentEditable
            if (mapped_elements[0]) { return true; }
            return false;
         }

        // simply replaces
        // rather than toggles, but
        // theres no reason you couldn't have
        // it do both!
        var wrap_selection = function(wrap_html){
            var selection_node = $(window.getSelection().anchorNode);
            if(is_contenteditable(selection_node)) {
                selection_node.unwrap();
                selection_node.wrap(wrap_html);
            }
            // wrap() normally breaks contentEditable
            // this is a hacky replacement
            selection_node.attr('contenteditable', true);
        };

        // lame helper that
        // toggles the class,
        // triggers the handler
        var button_click = function(element) {
            buttons[element].toggleClass('selected');
            button_handler[element]();
        }

        // bind click to button_click()/1
        for (var key in buttons) {
                buttons[key].click(function(element){
                 return function() {
                        log.debug('clicked', element);
                        button_click(element);
                        };
            }(key));
        }

        // Enables contentEditable
        $('form').attr('contenteditable','true');

         var setstate = function(selection) {
             var markup = selection.markupEffectiveAtStart;
          if (!markup) return;
             $ctrls.find('*').removeClass('selected');
             $.each(markup, function(idx, el) {
                 var tag = el.nodeName.toLowerCase(),
                 $button = buttons[tag];
                 if ($button) $button.addClass('selected');
                 log.debug('selected', tag);
             });
         };
     };

     var pattern = {
        markup_trigger: 'form textarea.edit',
        initialised_class: 'edit',
        init: init
    };
    return pattern;
});
<commit_msg>Toggle headings w/ header_N<commit_after>define([
    'require',
    '../lib/aloha-loader',
    '../logging',
    '../patterns'
], function(require) {
    log = require('../logging').getLogger('edit');

    // Grab a element of the editor controls
    var init = function($el, opts) {
        var $form    = $el.parents('form'),
            $ctrls   = $('.editor-ctrls'),
            buttons  = {};

        // ensure form is ajaxified
        var ajaxify = require('../patterns').ajaxify.init;
        ajaxify($form);

        // I have taken the liberty of commenting out buttons
        // that I believe serve no purpose, if they end up being
        // critical, just uncomment.

        // buttons.b                   = $ctrls.find('.strong');
        buttons.bold                = $ctrls.find('.strong');
        // buttons.i                   = $ctrls.find('.emphasised');
        buttons.italic              = $ctrls.find('.emphasised');
        // buttons.ol                  = $ctrls.find('.list-ordered');
        buttons.insertorderedlist   = $ctrls.find('.list-ordered');
        // buttons.ul                  = $ctrls.find('.list-unordered');
        buttons.insertunorderedlist = $ctrls.find('.list-unordered');
        //buttons.insertparagraph     = $ctrls.find('.paragraph');
        buttons.clear               = $ctrls.find('.clear');
        // buttons.h1                  = $ctrls.find('.header_1');
        buttons.inserth1            = $ctrls.find('.header_1');
        // buttons.h2                  = $ctrls.find('.header_2');
        buttons.inserth2            = $ctrls.find('.header_2');
        // buttons.h3                  = $ctrls.find('.header_3');
        buttons.inserth3            = $ctrls.find('.header_3');
        buttons.upload_image        = $ctrls.find('.upload_image');
        buttons.link_image          = $ctrls.find('.link_image');

        var button_handler = {
                'bold'                  : function(){ document.execCommand('bold'); },

                'italic'                : function(){ document.execCommand('italic'); },

                'insertparagraph'       : function(){ return 0; },

                'insertorderedlist'     : function(){ document.execCommand('insertorderedlist'); },

                'insertunorderedlist'   : function(){ document.execCommand('insertunorderedlist'); },

                'inserth1'              : function(){ wrap_selection('h1') },

                'inserth2'              : function(){ wrap_selection('h2') },

                'inserth3'              : function(){ wrap_selection('h3') },

                'clear'                 : function(){
                                                var selection_node = $(window.getSelection().anchorNode);
                                                document.execCommand('removeformat');
                                                if (is_contenteditable(selection_node)) {
                                                    selection_node.unwrap();
                                                    if (!$(selection_node).parent().is("p")) {
                                                        $(selection_node).wrap('<p>');
                                                    }
                                                }
                                          },

                'upload_image'          : function(){ document.execCommand(); },

                'link_image'            : function(){
                                                var source = prompt('URL of Image');
                                                if(source) {
                                                  document.execCommand('insertImage', false, source);
                                                }
                                          }
            };

        // utility method for determining if something is contenteditable
        var is_contenteditable = function(element) {
            mapped_elements = $(element).parents().map(function() {
                            if ($(this).is("[contenteditable='true']")) {
                                        return true;
                            }
                              }).get();

            // mapped_element[0] is the closest parent
            // in the document tree -- If it's true
            // the element will inherit contentEditable
            if (mapped_elements[0]) { return true; }
            return false;
         }

        // simply replaces
        // rather than toggles, but
        // theres no reason you couldn't have
        // it do both!
        var wrap_selection = function(wrap_html){
            var selection_node = $(window.getSelection().anchorNode);
            if(is_contenteditable(selection_node)) {
                // You just want to unwrap if your
                // parent is already selected
                if(selection_node.parent().is(wrap_html)) {
                    selection_node.unwrap();
                }
                else {
                    selection_node.wrap("<" + wrap_html + ">");
                }
            }
            // wrap() normally breaks contentEditable
            // this is a hacky replacement
            selection_node.attr('contenteditable', true);
        };

        // lame helper that
        // toggles the class,
        // triggers the handler
        var button_click = function(element) {
            buttons[element].toggleClass('selected');
            button_handler[element]();
        }

        // bind click to button_click()/1
        for (var key in buttons) {
                buttons[key].click(function(element){
                 return function() {
                        log.debug('clicked', element);
                        button_click(element);
                        };
            }(key));
        }

        // Enables contentEditable
        $('form').attr('contenteditable','true');

         var setstate = function(selection) {
             var markup = selection.markupEffectiveAtStart;
          if (!markup) return;
             $ctrls.find('*').removeClass('selected');
             $.each(markup, function(idx, el) {
                 var tag = el.nodeName.toLowerCase(),
                 $button = buttons[tag];
                 if ($button) $button.addClass('selected');
                 log.debug('selected', tag);
             });
         };
     };

     var pattern = {
        markup_trigger: 'form textarea.edit',
        initialised_class: 'edit',
        init: init
    };
    return pattern;
});
<|endoftext|>


<commit_before>/**
 * Creates a new LayerManager
 *
 * The LayerManager handels add/remove/activate and reordering layers
 *
 * @constructor
 * @param {OpenLayers.Map} olMap
 */
gbi.LayerManager = function(olMap) {
    this.counter = 0;
    this._layers = {};
    this.backgroundLayers = {};
    this.rasterLayers = {};
    this.vectorLayers = {};
    this._activeLayer = false;
    this.olMap = olMap;
};
gbi.LayerManager.prototype = {
    CLASS_NAME: 'gbi.LayerManager',
    /**
     * Generates  continuing id
     *
     * @returns {Integer} id
     */
    nextID: function() {
        return this.counter++;
    },
    /**
     * Adds a layer
     *
     * @param {gbi.Layers.Layer} layer
     */
    addLayer: function(layer) {
        var id = this.nextID();
        layer.id = layer.olLayer.gbiId = id;
        this._layers[id] = layer;
        this.olMap.addLayer(layer.olLayer);
        if(layer.isVector) {
            this.vectorLayers[id] = layer;
            $(gbi).trigger('gbi.layermanager.vectorlayer.add', layer);
            if(!this.active()) {
                this.active(layer);
            }
        } else if (layer.isBackground) {
            this.backgroundLayers[id] = layer;
            $(gbi).trigger('gbi.layermanager.backgroundlayer.add', layer);
        } else if (layer.isRaster) {
            this.rasterLayers[id] = layer;
            $(gbi).trigger('gbi.layermanager.rasterlayer.add', layer);
        }
        this.position(layer, this.minMaxPosition(layer)['max']);
        $(gbi).trigger('gbi.layermanager.layer.add');

    },
    /**
     * Adds a layers
     *
     * @param {gbi.Layers.Layer} layers
     */
    addLayers: function(layers) {
        var self = this;
        $.each(layers, function(idx, layer) {
            self.addLayer(layer);
        });
    },
    /**
     * Removes a layer
     *
     * @param {gbi.Layers.Layer} layer
     */
    removeLayer: function(layer) {
        var id = layer.id;
        this.olMap.removeLayer(layer.olLayer);
        delete this._layers[id];
        $(gbi).trigger('gbi.layermanager.layer.remove');
        if(layer.isVector) {
            delete this.vectorLayers[id];
            if(layer.isActive) {
                this._activeLayer = false;
                $(gbi).trigger('gbi.layermanager.layer.active', false);
            }
            $(gbi).trigger('gbi.layermanager.vectorlayer.remove', layer);
        } else if(layer.isBackground) {
            delete this.backgroundLayers[id];
            $(gbi).trigger('gbi.layermanager.backgroundLayer.remove', layer);
        } else if(layer.isRaster) {
            delete this.rasterLayers[id];
            $(gbi).trigger('gbi.layermanager.rasterlayer.remove', layer);
        }
        layer.destroy();
    },
    /**
     * Get all useable layers in top-down order
     *
     * @returns {gbi.Layers.Layer[]} List of layers
     */
     //XXXkai: think about! see _layers
    layers: function() {
        var self = this;
        var result = [];
        $.each(this.olMap.layers, function(idx, olLayer) {
            if(olLayer && !olLayer.isBaseLayer) {
                var gbiLayer = self._layers[olLayer.gbiId];
                if(gbiLayer) {
                    result.push(gbiLayer);
                }
            }
        });
        return result.reverse();
    },
    /**
     * Get layer by it's id
     *
     * @param {Integer} id
     * @returns {gbi.Layers.Layer}
     */
    layerById: function(id) {
        return this._layers[id];
    },
    /**
     * Get layer by it's name
     *
     * @param {String} name
     * @returns {gbi.Layers.Layer}
     */
    layerByName: function(name) {
        return this.olMap.getLayersByName(name)[0].gbiLayer;
    },
    /**
     * Activates a layer
     *
     * @param {gbi.Layers.Layer}
     */
    active: function(layer) {
        var self = this;
        if(arguments.length == 0) {
            return self._activeLayer;
        }
        if(self._activeLayer) {
            self._activeLayer.deactivate();
        }
        self._activeLayer = layer;
        self._activeLayer.activate();
        $(gbi).trigger('gbi.layermanager.layer.active', layer);
    },
    /**
     * Moves a layer up in the order of it's group (baselayer|rasterlayer|vectorlayer)
     *
     * @param {gbi.Layers.Layer} layer
     * @param {Integer} delta
     * @returns {Boolean} success
     */
    up: function(layer, delta) {
        var max = this.minMaxPosition(layer)['max'];
        delta = delta || 1;
        var pos = this.position(layer) + delta;
        if(pos > max) {
            return false;
        }
        this.position(layer, pos);
        return true;
    },
    /**
     * Moves a layer on the top
     *
     * @param {gbi.Layers.Layer} layer
     * @param {Integer} delta
     * @returns {Boolean} success
     */
    top: function(layer) {
        this.position(layer, this.minMaxPosition(layer)['max']);
    },
    /**
     * Moves a layer down in order
     *
     * @param {gbi.Layers.Layer} layer
     * @returns {Boolean} success
     */
    down: function(layer, delta) {
        var min = this.minMaxPosition(layer)['min'];
        delta = delta || 1;
        var pos = this.position(layer) - delta;
        if(pos < min) {
            return false;
        }
        this.position(layer, pos);
        return true;
    },
    /**
     * Gets/sets the position of a layer in layerorder
     *
     * @param {gbi.Layers.Layer} layer
     * @param {Integer} [pos]
     * @return {Integer} Position of layer in layerorder if no pos param is passed
     */
    position: function(layer, pos) {
        if(!pos) {
            return this.olMap.getLayerIndex(layer.olLayer);
        }
        this.olMap.setLayerIndex(layer.olLayer, pos);
    },
    /**
     * Moves a layer at the bottom
     *
     * @param {gbi.Layers.Layer} layer
     * @param {Integer} delta
     * @returns {Boolean} success
     */
    bottom: function(layer) {
        this.position(layer, this.minMaxPosition(layer)['min']);
    },
    /**
     * Gets min/max position of a layer in the layerorder
     *
     * @param {gbi.Layers.Layer} layer
     * @returns {Object} The returned object has a min- and a max-property
     */
    minMaxPosition: function(layer) {
        var min;
        var max;
        if(layer.isBackground) {
            min = 1;
            max = Object.keys(this.backgroundLayers).length;
        } else if (layer.isRaster) {
            min = Object.keys(this.backgroundLayers).length + 1;
            max = min + Object.keys(this.rasterLayers).length -1;
        } else {
            min = Object.keys(this.backgroundLayers).length + Object.keys(this.rasterLayers).length + 1;
            max = this.olMap.layers.length;
        }
        return {min: min, max: max};
    }
};
<commit_msg>When add a layer with isBaseLayer, set it as map baselayer<commit_after>/**
 * Creates a new LayerManager
 *
 * The LayerManager handels add/remove/activate and reordering layers
 *
 * @constructor
 * @param {OpenLayers.Map} olMap
 */
gbi.LayerManager = function(olMap) {
    this.counter = 0;
    this._layers = {};
    this.backgroundLayers = {};
    this.rasterLayers = {};
    this.vectorLayers = {};
    this._activeLayer = false;
    this.olMap = olMap;
};
gbi.LayerManager.prototype = {
    CLASS_NAME: 'gbi.LayerManager',
    /**
     * Generates  continuing id
     *
     * @returns {Integer} id
     */
    nextID: function() {
        return this.counter++;
    },
    /**
     * Adds a layer
     *
     * @param {gbi.Layers.Layer} layer
     */
    addLayer: function(layer) {
        var id = this.nextID();
        layer.id = layer.olLayer.gbiId = id;
        this._layers[id] = layer;
        this.olMap.addLayer(layer.olLayer);
        if(layer.isBaseLayer) {
            this.olMap.setBaseLayer(layer.olLayer);
        }
        if(layer.isVector) {
            this.vectorLayers[id] = layer;
            $(gbi).trigger('gbi.layermanager.vectorlayer.add', layer);
            if(!this.active()) {
                this.active(layer);
            }
        } else if (layer.isBackground) {
            this.backgroundLayers[id] = layer;
            $(gbi).trigger('gbi.layermanager.backgroundlayer.add', layer);
        } else if (layer.isRaster) {
            this.rasterLayers[id] = layer;
            $(gbi).trigger('gbi.layermanager.rasterlayer.add', layer);
        }
        this.position(layer, this.minMaxPosition(layer)['max']);
        $(gbi).trigger('gbi.layermanager.layer.add');

    },
    /**
     * Adds a layers
     *
     * @param {gbi.Layers.Layer} layers
     */
    addLayers: function(layers) {
        var self = this;
        $.each(layers, function(idx, layer) {
            self.addLayer(layer);
        });
    },
    /**
     * Removes a layer
     *
     * @param {gbi.Layers.Layer} layer
     */
    removeLayer: function(layer) {
        var id = layer.id;
        this.olMap.removeLayer(layer.olLayer);
        delete this._layers[id];
        $(gbi).trigger('gbi.layermanager.layer.remove');
        if(layer.isVector) {
            delete this.vectorLayers[id];
            if(layer.isActive) {
                this._activeLayer = false;
                $(gbi).trigger('gbi.layermanager.layer.active', false);
            }
            $(gbi).trigger('gbi.layermanager.vectorlayer.remove', layer);
        } else if(layer.isBackground) {
            delete this.backgroundLayers[id];
            $(gbi).trigger('gbi.layermanager.backgroundLayer.remove', layer);
        } else if(layer.isRaster) {
            delete this.rasterLayers[id];
            $(gbi).trigger('gbi.layermanager.rasterlayer.remove', layer);
        }
        layer.destroy();
    },
    /**
     * Get all useable layers in top-down order
     *
     * @returns {gbi.Layers.Layer[]} List of layers
     */
     //XXXkai: think about! see _layers
    layers: function() {
        var self = this;
        var result = [];
        $.each(this.olMap.layers, function(idx, olLayer) {
            if(olLayer && !olLayer.isBaseLayer) {
                var gbiLayer = self._layers[olLayer.gbiId];
                if(gbiLayer) {
                    result.push(gbiLayer);
                }
            }
        });
        return result.reverse();
    },
    /**
     * Get layer by it's id
     *
     * @param {Integer} id
     * @returns {gbi.Layers.Layer}
     */
    layerById: function(id) {
        return this._layers[id];
    },
    /**
     * Get layer by it's name
     *
     * @param {String} name
     * @returns {gbi.Layers.Layer}
     */
    layerByName: function(name) {
        return this.olMap.getLayersByName(name)[0].gbiLayer;
    },
    /**
     * Activates a layer
     *
     * @param {gbi.Layers.Layer}
     */
    active: function(layer) {
        var self = this;
        if(arguments.length == 0) {
            return self._activeLayer;
        }
        if(self._activeLayer) {
            self._activeLayer.deactivate();
        }
        self._activeLayer = layer;
        self._activeLayer.activate();
        $(gbi).trigger('gbi.layermanager.layer.active', layer);
    },
    /**
     * Moves a layer up in the order of it's group (baselayer|rasterlayer|vectorlayer)
     *
     * @param {gbi.Layers.Layer} layer
     * @param {Integer} delta
     * @returns {Boolean} success
     */
    up: function(layer, delta) {
        var max = this.minMaxPosition(layer)['max'];
        delta = delta || 1;
        var pos = this.position(layer) + delta;
        if(pos > max) {
            return false;
        }
        this.position(layer, pos);
        return true;
    },
    /**
     * Moves a layer on the top
     *
     * @param {gbi.Layers.Layer} layer
     * @param {Integer} delta
     * @returns {Boolean} success
     */
    top: function(layer) {
        this.position(layer, this.minMaxPosition(layer)['max']);
    },
    /**
     * Moves a layer down in order
     *
     * @param {gbi.Layers.Layer} layer
     * @returns {Boolean} success
     */
    down: function(layer, delta) {
        var min = this.minMaxPosition(layer)['min'];
        delta = delta || 1;
        var pos = this.position(layer) - delta;
        if(pos < min) {
            return false;
        }
        this.position(layer, pos);
        return true;
    },
    /**
     * Gets/sets the position of a layer in layerorder
     *
     * @param {gbi.Layers.Layer} layer
     * @param {Integer} [pos]
     * @return {Integer} Position of layer in layerorder if no pos param is passed
     */
    position: function(layer, pos) {
        if(!pos) {
            return this.olMap.getLayerIndex(layer.olLayer);
        }
        this.olMap.setLayerIndex(layer.olLayer, pos);
    },
    /**
     * Moves a layer at the bottom
     *
     * @param {gbi.Layers.Layer} layer
     * @param {Integer} delta
     * @returns {Boolean} success
     */
    bottom: function(layer) {
        this.position(layer, this.minMaxPosition(layer)['min']);
    },
    /**
     * Gets min/max position of a layer in the layerorder
     *
     * @param {gbi.Layers.Layer} layer
     * @returns {Object} The returned object has a min- and a max-property
     */
    minMaxPosition: function(layer) {
        var min;
        var max;
        if(layer.isBackground) {
            min = 1;
            max = Object.keys(this.backgroundLayers).length;
        } else if (layer.isRaster) {
            min = Object.keys(this.backgroundLayers).length + 1;
            max = min + Object.keys(this.rasterLayers).length -1;
        } else {
            min = Object.keys(this.backgroundLayers).length + Object.keys(this.rasterLayers).length + 1;
            max = this.olMap.layers.length;
        }
        return {min: min, max: max};
    }
};
<|endoftext|>


<commit_before>var exports = module.exports = {};

/*
 * shall we output debug logs?
 * if so start the app with:
 *    DEBUG=ledconodel node app.js
 */
const debug = require('debug')('ledconodel');
const name = 'ledconodel';
debug('booting %s', name);

/*
 * we need some timers to have the leds blink
 */
//var sleep = require('system-sleep');

/*
 * require rpio2 node module to drive GPIO pins and use hardware pin numbering
 */
const Gpio = require('rpio2').Gpio;
var options = {
  gpiomem: true,          /* Use /dev/gpiomem */
  mapping: 'physical',    /* Use the P1-P40 numbering scheme */
}

/*
 * set the pins for the 3 leds as a new instance of Gpio
							HW --> BCM --> WiringPI
		redled		33 --> 13  --> 23
		greenled	35 --> 19  --> 24
		blueled		37 --> 26  --> 25
*/
const redled = new Gpio(33);
const greenled = new Gpio(35);
const blueled = new Gpio(37);

var isRedLedOn = 0;
var isGreenLedOn = 0;
var isBlueLedOn = 0;

/*
 * function to turn off an led
 */
function turnOffLed(led) {
  led.open(Gpio.OUTPUT, Gpio.LOW)
}

/*
 * Set the initial state to low.  The state is set prior to the pin becoming
 * active, so is safe for devices which require a stable setup.
 */
turnOffLed(redled);
turnOffLed(greenled);
turnOffLed(blueled);
//greenled.open(Gpio.OUTPUT, Gpio.LOW);
//redled.open(Gpio.OUTPUT, Gpio.LOW);
//blueled.open(Gpio.OUTPUT, Gpio.LOW);

setInterval(function(configPin, isLedOn) {
  isLedOn = +!isLedOn;
	//isLedOn = !isLedOn;
	wpi.digitalWrite(configPin, isLedOn );
}, configTimeout);

setInterval(redled,isRedLedOn)

debug('closing GPIO');
turnOffLed(redled);
turnOffLed(greenled);
turnOffLed(blueled);

redled.close();
greenled.close();
blueled.close();
debug('shutdown!');
process.exit(0);

process.on("SIGINT", function(){
  redled.close();
  greenled.close();
  blueled.close();
  debug('shutdown!');
  process.exit(0);
});
<commit_msg>addedf configTimeout<commit_after>var exports = module.exports = {};

/*
 * shall we output debug logs?
 * if so start the app with:
 *    DEBUG=ledconodel node app.js
 */
const debug = require('debug')('ledconodel');
const name = 'ledconodel';
debug('booting %s', name);

/*
 * we need some timers to have the leds blink
 */
//var sleep = require('system-sleep');

/*
 * require rpio2 node module to drive GPIO pins and use hardware pin numbering
 */
const Gpio = require('rpio2').Gpio;
var options = {
  gpiomem: true,          /* Use /dev/gpiomem */
  mapping: 'physical',    /* Use the P1-P40 numbering scheme */
}

/*
 * set the pins for the 3 leds as a new instance of Gpio
							HW --> BCM --> WiringPI
		redled		33 --> 13  --> 23
		greenled	35 --> 19  --> 24
		blueled		37 --> 26  --> 25
*/
const redled = new Gpio(33);
const greenled = new Gpio(35);
const blueled = new Gpio(37);

var isRedLedOn = 0;
var isGreenLedOn = 0;
var isBlueLedOn = 0;

// Blinking interval in usec
var configTimeout = 1000;

/*
 * function to turn off an led
 */
function turnOffLed(led) {
  led.open(Gpio.OUTPUT, Gpio.LOW)
}

/*
 * Set the initial state to low.  The state is set prior to the pin becoming
 * active, so is safe for devices which require a stable setup.
 */
turnOffLed(redled);
turnOffLed(greenled);
turnOffLed(blueled);
//greenled.open(Gpio.OUTPUT, Gpio.LOW);
//redled.open(Gpio.OUTPUT, Gpio.LOW);
//blueled.open(Gpio.OUTPUT, Gpio.LOW);

setInterval(function(configPin, isLedOn) {
  isLedOn = +!isLedOn;
	//isLedOn = !isLedOn;
	wpi.digitalWrite(configPin, isLedOn );
}, configTimeout);

setInterval(redled,isRedLedOn)

debug('closing GPIO');
turnOffLed(redled);
turnOffLed(greenled);
turnOffLed(blueled);

redled.close();
greenled.close();
blueled.close();
debug('shutdown!');
process.exit(0);

process.on("SIGINT", function(){
  redled.close();
  greenled.close();
  blueled.close();
  debug('shutdown!');
  process.exit(0);
});
<|endoftext|>


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

export default function generateReducers(options) {
  const {idAttr, initialState, resourceName} = options;

  const actionReducers = {
    CREATE_RESOURCE: reducers.create.bind(null, resourceName, idAttr),
    CREATE_RESOURCE_FAIL: reducers.createFail.bind(null, resourceName, idAttr),
    CREATE_RESOURCE_SUCCEED: reducers.createSucceed.bind(null, resourceName, idAttr),
    CREATE_RESOURCE_ABORT: reducers.createAbort.bind(null, resourceName, idAttr),
    CREATE_RESOURCE_RESET: reducers.createReset.bind(null, resourceName, idAttr),

    READ_RESOURCE: reducers.read.bind(null, resourceName, idAttr),
    READ_RESOURCE_FAIL: reducers.readFail.bind(null, resourceName, idAttr),
    READ_RESOURCE_SUCCEED: reducers.readSucceed.bind(null, resourceName, idAttr),
    READ_RESOURCE_ABORT: reducers.readAbort.bind(null, resourceName, idAttr),
    READ_RESOURCE_RESET: reducers.readReset.bind(null, resourceName, idAttr),

    UPDATE_RESOURCE: reducers.update.bind(null, resourceName, idAttr),
    UPDATE_RESOURCE_FAIL: reducers.updateFail.bind(null, resourceName, idAttr),
    UPDATE_RESOURCE_SUCCEED: reducers.updateSucceed.bind(null, resourceName, idAttr),
    UPDATE_RESOURCE_ABORT: reducers.updateAbort.bind(null, resourceName, idAttr),
    UPDATE_RESOURCE_RESET: reducers.updateReset.bind(null, resourceName, idAttr),

    DELETE_RESOURCE: reducers.del.bind(null, resourceName, idAttr),
    DELETE_RESOURCE_FAIL: reducers.delFail.bind(null, resourceName, idAttr),
    DELETE_RESOURCE_SUCCEED: reducers.delSucceed.bind(null, resourceName, idAttr),
    DELETE_RESOURCE_ABORT: reducers.delAbort.bind(null, resourceName, idAttr),
    DELETE_RESOURCE_RESET: reducers.delReset.bind(null, resourceName, idAttr),

    CREATE_MANY_RESOURCES: reducers.createMany.bind(null, resourceName, idAttr),
    CREATE_MANY_RESOURCES_FAIL: reducers.createManyFail.bind(null, resourceName, idAttr),
    CREATE_MANY_RESOURCES_SUCCEED: reducers.createManySucceed.bind(null, resourceName, idAttr),
    CREATE_MANY_RESOURCES_ABORT: reducers.createManyAbort.bind(null, resourceName, idAttr),
    CREATE_MANY_RESOURCES_RESET: reducers.createManyReset.bind(null, resourceName, idAttr),

    READ_MANY_RESOURCES: reducers.readMany.bind(null, resourceName, idAttr),
    READ_MANY_RESOURCES_FAIL: reducers.readManyFail.bind(null, resourceName, idAttr),
    READ_MANY_RESOURCES_SUCCEED: reducers.readManySucceed.bind(null, resourceName, idAttr),
    READ_MANY_RESOURCES_ABORT: reducers.readManyAbort.bind(null, resourceName, idAttr),
    READ_MANY_RESOURCES_RESET: reducers.readManyReset.bind(null, resourceName, idAttr),

    UPDATE_MANY_RESOURCES: reducers.updateMany.bind(null, resourceName, idAttr),
    UPDATE_MANY_RESOURCES_FAIL: reducers.updateManyFail.bind(null, resourceName, idAttr),
    UPDATE_MANY_RESOURCES_SUCCEED: reducers.updateManySucceed.bind(null, resourceName, idAttr),
    UPDATE_MANY_RESOURCES_ABORT: reducers.updateManyAbort.bind(null, resourceName, idAttr),
    UPDATE_MANY_RESOURCES_RESET: reducers.updateManyReset.bind(null, resourceName, idAttr),

    DELETE_MANY_RESOURCES: reducers.delMany.bind(null, resourceName, idAttr),
    DELETE_MANY_RESOURCES_FAIL: reducers.delManyFail.bind(null, resourceName, idAttr),
    DELETE_MANY_RESOURCES_SUCCEED: reducers.delManySucceed.bind(null, resourceName, idAttr),
    DELETE_MANY_RESOURCES_ABORT: reducers.delManyAbort.bind(null, resourceName, idAttr),
    DELETE_MANY_RESOURCES_RESET: reducers.delManyReset.bind(null, resourceName, idAttr)
  };

  return function reducer(state = initialState, action) {
    const actionReducer = actionReducers[action.type];
    if (!actionReducer) {
      return state;
    }

    const result = actionReducer(state, action);
    return result ? result : state;
  };
}
<commit_msg>Return the state when the resource name does not match<commit_after>import * as reducers from './reducers';

export default function generateReducers(options) {
  const {idAttr, initialState, resourceName} = options;

  const actionReducers = {
    CREATE_RESOURCE: reducers.create.bind(null, resourceName, idAttr),
    CREATE_RESOURCE_FAIL: reducers.createFail.bind(null, resourceName, idAttr),
    CREATE_RESOURCE_SUCCEED: reducers.createSucceed.bind(null, resourceName, idAttr),
    CREATE_RESOURCE_ABORT: reducers.createAbort.bind(null, resourceName, idAttr),
    CREATE_RESOURCE_RESET: reducers.createReset.bind(null, resourceName, idAttr),

    READ_RESOURCE: reducers.read.bind(null, resourceName, idAttr),
    READ_RESOURCE_FAIL: reducers.readFail.bind(null, resourceName, idAttr),
    READ_RESOURCE_SUCCEED: reducers.readSucceed.bind(null, resourceName, idAttr),
    READ_RESOURCE_ABORT: reducers.readAbort.bind(null, resourceName, idAttr),
    READ_RESOURCE_RESET: reducers.readReset.bind(null, resourceName, idAttr),

    UPDATE_RESOURCE: reducers.update.bind(null, resourceName, idAttr),
    UPDATE_RESOURCE_FAIL: reducers.updateFail.bind(null, resourceName, idAttr),
    UPDATE_RESOURCE_SUCCEED: reducers.updateSucceed.bind(null, resourceName, idAttr),
    UPDATE_RESOURCE_ABORT: reducers.updateAbort.bind(null, resourceName, idAttr),
    UPDATE_RESOURCE_RESET: reducers.updateReset.bind(null, resourceName, idAttr),

    DELETE_RESOURCE: reducers.del.bind(null, resourceName, idAttr),
    DELETE_RESOURCE_FAIL: reducers.delFail.bind(null, resourceName, idAttr),
    DELETE_RESOURCE_SUCCEED: reducers.delSucceed.bind(null, resourceName, idAttr),
    DELETE_RESOURCE_ABORT: reducers.delAbort.bind(null, resourceName, idAttr),
    DELETE_RESOURCE_RESET: reducers.delReset.bind(null, resourceName, idAttr),

    CREATE_MANY_RESOURCES: reducers.createMany.bind(null, resourceName, idAttr),
    CREATE_MANY_RESOURCES_FAIL: reducers.createManyFail.bind(null, resourceName, idAttr),
    CREATE_MANY_RESOURCES_SUCCEED: reducers.createManySucceed.bind(null, resourceName, idAttr),
    CREATE_MANY_RESOURCES_ABORT: reducers.createManyAbort.bind(null, resourceName, idAttr),
    CREATE_MANY_RESOURCES_RESET: reducers.createManyReset.bind(null, resourceName, idAttr),

    READ_MANY_RESOURCES: reducers.readMany.bind(null, resourceName, idAttr),
    READ_MANY_RESOURCES_FAIL: reducers.readManyFail.bind(null, resourceName, idAttr),
    READ_MANY_RESOURCES_SUCCEED: reducers.readManySucceed.bind(null, resourceName, idAttr),
    READ_MANY_RESOURCES_ABORT: reducers.readManyAbort.bind(null, resourceName, idAttr),
    READ_MANY_RESOURCES_RESET: reducers.readManyReset.bind(null, resourceName, idAttr),

    UPDATE_MANY_RESOURCES: reducers.updateMany.bind(null, resourceName, idAttr),
    UPDATE_MANY_RESOURCES_FAIL: reducers.updateManyFail.bind(null, resourceName, idAttr),
    UPDATE_MANY_RESOURCES_SUCCEED: reducers.updateManySucceed.bind(null, resourceName, idAttr),
    UPDATE_MANY_RESOURCES_ABORT: reducers.updateManyAbort.bind(null, resourceName, idAttr),
    UPDATE_MANY_RESOURCES_RESET: reducers.updateManyReset.bind(null, resourceName, idAttr),

    DELETE_MANY_RESOURCES: reducers.delMany.bind(null, resourceName, idAttr),
    DELETE_MANY_RESOURCES_FAIL: reducers.delManyFail.bind(null, resourceName, idAttr),
    DELETE_MANY_RESOURCES_SUCCEED: reducers.delManySucceed.bind(null, resourceName, idAttr),
    DELETE_MANY_RESOURCES_ABORT: reducers.delManyAbort.bind(null, resourceName, idAttr),
    DELETE_MANY_RESOURCES_RESET: reducers.delManyReset.bind(null, resourceName, idAttr)
  };

  return function reducer(state = initialState, action) {
    const actionReducer = actionReducers[action.type];
    if (!actionReducer || action.resourceName !== resourceName) {
      return state;
    }

    const result = actionReducer(state, action);
    return result ? result : state;
  };
}
<|endoftext|>


<commit_before>/**
 * @fileoverview
 * Object representing a Scratch Comment (block or workspace).
 */

const uid = require('../util/uid');
const cast = require('../util/cast');

class Comment {
    /**
     * @param {string} id Id of the variable.
     * @param {string} name Name of the variable.
     * @param {string} type Type of the variable, one of '' or 'list'
     * @param {boolean} isCloud Whether the variable is stored in the cloud.
     * @constructor
     */ /* TODO should the comment constructor take in an id? will we need this for sb3? */
    constructor (id, text, x, y, width, height, minimized) {
        this.id = id || uid();
        this.text = text;
        this.x = x;
        this.y = y;
        this.width = Math.max(cast.toNumber(width), Comment.MIN_WIDTH);
        this.height = Math.max(cast.toNumber(height), Comment.MIN_HEIGHT);
        this.minimized = minimized || false;
        this.blockId = null;
    }

    toXML () {
        return `<comment type="scratch" id="${this.id}" x="${this.x}" y="${
            this.y}" w="${this.width}" h="${this.height}" pinned="${
            this.blockId !== null}" minimized="${this.minimized}">${this.text}</comment>`;
    }

    // TODO choose min and defaults for width and height
    static get MIN_WIDTH () {
        return 20;
    }

    static get MIN_HEIGHT () {
        return 20;
    }

    static get DEFAULT_WIDTH () {
        return 100;
    }

    static get DEFAULT_HEIGHT () {
        return 100;
    }

}

module.exports = Comment;
<commit_msg>No more xml differentiation for 'scratch' type of comments.<commit_after>/**
 * @fileoverview
 * Object representing a Scratch Comment (block or workspace).
 */

const uid = require('../util/uid');
const cast = require('../util/cast');

class Comment {
    /**
     * @param {string} id Id of the variable.
     * @param {string} name Name of the variable.
     * @param {string} type Type of the variable, one of '' or 'list'
     * @param {boolean} isCloud Whether the variable is stored in the cloud.
     * @constructor
     */ /* TODO should the comment constructor take in an id? will we need this for sb3? */
    constructor (id, text, x, y, width, height, minimized) {
        this.id = id || uid();
        this.text = text;
        this.x = x;
        this.y = y;
        this.width = Math.max(cast.toNumber(width), Comment.MIN_WIDTH);
        this.height = Math.max(cast.toNumber(height), Comment.MIN_HEIGHT);
        this.minimized = minimized || false;
        this.blockId = null;
    }

    toXML () {
        return `<comment id="${this.id}" x="${this.x}" y="${
            this.y}" w="${this.width}" h="${this.height}" pinned="${
            this.blockId !== null}" minimized="${this.minimized}">${this.text}</comment>`;
    }

    // TODO choose min and defaults for width and height
    static get MIN_WIDTH () {
        return 20;
    }

    static get MIN_HEIGHT () {
        return 20;
    }

    static get DEFAULT_WIDTH () {
        return 100;
    }

    static get DEFAULT_HEIGHT () {
        return 100;
    }

}

module.exports = Comment;
<|endoftext|>


<commit_before>import { Entity } from './entity.js'
import { invoke } from './utilities.js'

/** @ignore */
export class EntityStorage {
  constructor(world) {
    /** @ignore */
    this.world = world
    /** @ignore */
    this.componentClasses = {}
    /** @ignore */
    this.nextEntityId = 1

    /**
     * Maps entity IDs to entities
     * @ignore
     */
    this.entities = new Map()

    /**
     * Maps component keys to entities
     * @ignore
     */
    this.index = new Map()
  }

  clear() {
    // Call onRemove on all components of all entities
    for (const { data } of this.entities.values()) {
      for (const componentName in data) {
        invoke(data[componentName], 'onRemove')
      }
    }

    // Clear entities
    this.entities.clear()
    this.index.clear()
  }

  registerComponent(name, componentClass) {
    // Only allow functions and classes to be components
    if (typeof componentClass !== 'function') {
      throw new Error('Component is not a valid function or class.')
    }
    this.componentClasses[name] = componentClass
  }

  // Creates a new entity attached to the world
  createEntity() {
    const entityId = this.nextEntityId++
    const entity = new Entity(this.world, entityId)
    this.entities.set(entityId, entity)
    return entity
  }

  // Forwards query args from world
  each(...args) {
    return this.queryIndex(this.queryArgs(...args))
  }

  // Returns an existing or new index
  accessIndex(component) {
    return (
      this.index.get(component) ||
      this.index.set(component, new Map()).get(component)
    )
  }

  // Add component with an entity to the index
  addToIndex(entity, compName) {
    this.accessIndex(compName).set(entity.id, entity)
  }

  // Remove component from the index for an entity
  removeFromIndex(entity, compName) {
    this.accessIndex(compName).delete(entity.id)
  }

  queryArgs(...args) {
    // Gather component names and a callback (if any) from args
    const result = {
      componentNames: [],
      callback: null,
    }
    for (const arg of args) {
      if (typeof arg === 'string') {
        result.componentNames.push(arg)
      } else if (typeof arg === 'function') {
        result.callback = arg
      } else if (Array.isArray(arg)) {
        // Add 1-level deep arrays of strings as separate component names
        for (const name of arg) {
          result.componentNames.push(name)
        }
      } else {
        throw new Error(
          `Unknown argument ${arg} with type ${typeof arg} passed to world.each().`
        )
      }
    }
    return result
  }

  // Uses an existing index or builds a new index, to get entities with the specified components
  // If callback is defined, it will be called for each entity with component data, and returns undefined
  // If callback is not defined, an array of entities will be returned
  queryIndex({ componentNames, callback }) {
    // Return all entities (array if no callback)
    if (componentNames.length === 0) {
      const iter = this.entities.values()
      if (!callback) {
        return [...iter]
      }
      for (const entity of iter) {
        if (callback(entity.data, entity) === false) {
          break
        }
      }
      return
    }

    // Sort component names by number of components in each index
    // This allows us to get the minimum component index as the first element
    // This also helps short-circuit much faster during the full query loops with .every()
    componentNames.sort(
      (a, b) => this.accessIndex(a).size - this.accessIndex(b).size
    )
    const iter = this.accessIndex(componentNames[0]).values()

    // Return array of matched entities
    if (!callback) {
      const results = []
      for (const entity of iter) {
        const { data } = entity
        if (componentNames.every(name => name in data)) {
          results.push(entity)
        }
      }
      return results
    }

    // Invoke callback for each matched entity
    for (const entity of iter) {
      const { data } = entity
      if (
        componentNames.every(name => name in data) &&
        callback(data, entity) === false
      ) {
        return
      }
    }
  }
}
<commit_msg>Fixed #55<commit_after>import { Entity } from './entity.js'
import { invoke } from './utilities.js'

/** @ignore */
export class EntityStorage {
  constructor(world) {
    /** @ignore */
    this.world = world
    /** @ignore */
    this.componentClasses = {}
    /** @ignore */
    this.nextEntityId = 1

    /**
     * Maps entity IDs to entities
     * @ignore
     */
    this.entities = new Map()

    /**
     * Maps component keys to entities
     * @ignore
     */
    this.index = new Map()
  }

  clear() {
    // Call onRemove on all components of all entities
    for (const { data } of this.entities.values()) {
      for (const componentName in data) {
        invoke(data[componentName], 'onRemove')
      }
    }

    // Clear entities
    this.entities.clear()
    this.index.clear()
  }

  registerComponent(name, componentClass) {
    // Only allow functions and classes to be components
    if (typeof componentClass !== 'function') {
      throw new Error('Component is not a valid function or class.')
    }
    this.componentClasses[name] = componentClass
  }

  // Creates a new entity attached to the world
  createEntity() {
    const entityId = this.nextEntityId++
    const entity = new Entity(this.world, entityId)
    this.entities.set(entityId, entity)
    return entity
  }

  // Forwards query args from world
  each(...args) {
    return this.queryIndex(this.queryArgs(...args))
  }

  // Returns an existing or new index
  accessIndex(component) {
    return (
      this.index.get(component) ||
      this.index.set(component, new Map()).get(component)
    )
  }

  // Add component with an entity to the index
  addToIndex(entity, compName) {
    this.accessIndex(compName).set(entity.id, entity)
  }

  // Remove component from the index for an entity
  removeFromIndex(entity, compName) {
    this.accessIndex(compName).delete(entity.id)
  }

  queryArgs(...args) {
    // Gather component names and a callback (if any) from args
    const result = {
      componentNames: [],
      callback: null,
    }
    for (const arg of args) {
      if (typeof arg === 'string') {
        result.componentNames.push(arg)
      } else if (typeof arg === 'function') {
        result.callback = arg
      } else if (Array.isArray(arg)) {
        // Add 1-level deep arrays of strings as separate component names
        for (const name of arg) {
          result.componentNames.push(name)
        }
      } else {
        throw new Error(
          `Unknown argument ${arg} with type ${typeof arg} passed to world.each().`
        )
      }
    }
    return result
  }

  // Uses an existing index or builds a new index, to get entities with the specified components
  // If callback is defined, it will be called for each entity with component data, and returns undefined
  // If callback is not defined, an array of entities will be returned
  queryIndex({ componentNames, callback }) {
    // Return all entities (array if no callback)
    if (componentNames.length === 0) {
      const iter = this.entities.values()
      if (!callback) {
        return [...iter]
      }
      for (const entity of iter) {
        if (callback(entity.data, entity) === false) {
          break
        }
      }
      return
    }

    // Sort component names by number of components in each index
    // This allows us to get the minimum component index as the first element
    // This also helps short-circuit much faster during the full query loops with .every()
    componentNames.sort(
      (a, b) => this.accessIndex(a).size - this.accessIndex(b).size
    )
    const iter = this.accessIndex(componentNames.shift()).values()

    // Return array of matched entities
    if (!callback) {
      const results = []
      for (const entity of iter) {
        const { data } = entity
        if (componentNames.every(name => name in data)) {
          results.push(entity)
        }
      }
      return results
    }

    // Invoke callback for each matched entity
    for (const entity of iter) {
      const { data } = entity
      if (
        componentNames.every(name => name in data) &&
        callback(data, entity) === false
      ) {
        return
      }
    }
  }
}
<|endoftext|>


<commit_before>export default function() {
  if (typeof arguments[0].signal !== 'object') {
    throw new TypeError();
  }

  var zcr = 0;
  for (var i = 1; i < arguments[0].signal.length; i++) {
    if ((arguments[0].signal[i-1] >= 0 && arguments[0].signal[i] < 0) ||
         (arguments[0].signal[i-1] < 0 && arguments[0].signal[i] >= 0)) {
      zcr++;
    }
  }

  return zcr;
}
<commit_msg>Revert "Fix bug in ZCR"<commit_after>export default function() {
  if (typeof arguments[0].signal !== 'object') {
    throw new TypeError();
  }

  var zcr = 0;
  for (var i = 0; i < arguments[0].signal.length; i++) {
    if ((arguments[0].signal[i] >= 0 && arguments[0].signal[i + 1] < 0) ||
         (arguments[0].signal[i] < 0 && arguments[0].signal[i + 1] >= 0)) {
      zcr++;
    }
  }

  return zcr;
}
<|endoftext|>


<commit_before>GLOW.Load = (function() {

    "use strict"; "use restrict";

    // constructor
    function load( parameters ) {
        this.parameters         = parameters;
        this.onLoadComplete     = undefined;
        this.onLoadContext      = null;
        this.onLoadItem         = undefined;
        this.numItemsToLoad     = 0;
        this.numItemsLeftToLoad = 0;

        for( var p in parameters ) {
            if( p !== "onLoadComplete" && p !== "onLoadItem" && p!== "dontParseJS" && p != "onLoadContext" ) {
                this.numItemsToLoad++;
            } else {
                this[ p ] = parameters[ p ];
                delete parameters[ p ];
            }
        }
        this.numItemsLeftToLoad = this.numItemsToLoad;

        for( var p in parameters ) {
            var originalURL  = parameters[ p ];
            var lowerCaseURL = parameters[ p ];
            if( lowerCaseURL.indexOf( ".png" ) !== -1 ||
                lowerCaseURL.indexOf( ".gif" ) !== -1 ||
                lowerCaseURL.indexOf( ".jpg" ) !== -1 ||
                lowerCaseURL.indexOf( "jpeg" ) !== -1 ) {
                parameters[ p ] = new Image();
                parameters[ p ].scope = this;
                parameters[ p ].onload = this.onLoadImage;
                parameters[ p ].onerror = this.onLoadError;
                parameters[ p ].onabort = this.onLoadError;
                parameters[ p ].src = originalURL;
            } else if( lowerCaseURL.indexOf( ".glsl" ) !== -1 ) {
                parameters[ p ] = new XMLHttpRequest();
                parameters[ p ].scope = this;
                parameters[ p ].parametersProperty = p;
                parameters[ p ].open( "GET", originalURL );
                parameters[ p ].onreadystatechange = this.onLoadGLSL;
                parameters[ p ].onerror = this.onLoadError;
                parameters[ p ].onabort = this.onLoadError;
                parameters[ p ].send();
            } else if( lowerCaseURL.indexOf( ".js" ) !== -1 || lowerCaseURL.indexOf( ".json" ) !== -1 ) {
                parameters[ p ] = new XMLHttpRequest();
                parameters[ p ].scope = this;
                parameters[ p ].parametersProperty = p;
                parameters[ p ].open( "GET", originalURL );
                parameters[ p ].onreadystatechange = this.onLoadJSON;
                parameters[ p ].onerror = this.onLoadError;
                parameters[ p ].onabort = this.onLoadError;
                parameters[ p ].send();
            } else {
                parameters[ p ] = document.createElement( "video" );
                parameters[ p ].scope = this;
                parameters[ p ].addEventListener( "loadeddata", this.onLoadVideo, false );
                parameters[ p ].src = originalURL;
            }
        }
    }

    // methods
    load.prototype.handleLoadedItem = function() {
        this.numItemsLeftToLoad--;
        if( this.onLoadItem !== undefined ) {
            this.onLoadItem.call( this.onLoadContext, 1 - this.numItemsLeftToLoad / this.numItemsToLoad );
        }
        if( this.numItemsLeftToLoad <= 0 ) {
            this.onLoadComplete.call( this.onLoadContext, this.parameters );
        }
    };

    load.prototype.onLoadJSON = function() {
        if( this.readyState === 4 ) {
   /*         var originalData;
            var data = {};

            // Three.js
            if( this.scope.dontParseJS !== true ) {
                if( this.responseText.indexOf( "var model = {" ) !== -1 ) {
                    var dataString = this.responseText.slice( this.responseText.indexOf( "var model = {" ) + 12,
                                                              this.responseText.indexOf( "};" ) + 1 );
                    originalData = JSON.parse( dataString );
                    data = this.scope.parseThreeJS( originalData );
                // J3D
                } else {
                    originalData = JSON.parse( this.responseText );

                    if( originalData.vertices && originalData.vertices.length > 0 ) data.vertices = new Float32Array( originalData.vertices );
                    if( originalData.normals && originalData.normals.length > 0 ) data.normals = new Float32Array( originalData.normals );
                    if( originalData.uv1 && originalData.uv1.length > 0 ) data.uv1 = new Float32Array( originalData.uv1 );
                    if( originalData.uv2 && originalData.uv2.length > 0 ) data.uv2 = new Float32Array( originalData.uv2 );
                    if( originalData.colors && originalData.colors.length > 0 ) data.colors = new Float32Array( originalData.colors );
                    if( originalData.tris && originalData.tris.length > 0 ) data.triangles = new Uint16Array( originalData.tris );
                }
            } else {
                data = JSON.parse( this.responseText );
            }*/

            this.scope.parameters[ this.parametersProperty ] = JSON.parse( this.responseText );;
            this.scope.handleLoadedItem();
        }
    };

    load.prototype.onLoadImage = function() {
        this.scope.handleLoadedItem();
    };

    load.prototype.onLoadVideo = function() {
        this.removeEventListener( "loadeddata", this.scope.onLoadVideo, false );
        this.scope.handleLoadedItem();
    };

    /*
    * GLSL parser by Bartek Drozyz
    * Slightly modified to suit GLOW by Mikael Emtinger
    */

    load.prototype.onLoadGLSL = function() {
        if( this.readyState === 4 ) {
            // glsl parser by Bartek Drozyz
        	var vs = "";
        	var fs = "";
        	var ls = this.responseText.split( "\n" );
        	var buf = "";
        	for( var i = 0; i < ls.length; i++ ) {
        		if( ls[ i ].indexOf( "//#" ) > -1 ) {
        			if( ls[ i ].indexOf( "Fragment" ) > -1 ) {
        				vs = buf;
        				buf = "";
        			}
        		} else {
        			var l = ls[ i ];
        			if( l.indexOf( "//" ) > -1 ) {
        			    l = l.substring( 0, l.indexOf( "//" ));
    			    }
                    if( l.indexOf( ";" ) === -1 ) {
                        l += "\n";
                    }
        			buf += l;
        		}
        	}
        	fs = buf;

            this.scope.parameters[ this.parametersProperty ] = { fragmentShader: "#ifdef GL_ES\nprecision highp float;\n#endif\n" + fs, vertexShader: vs };
            this.scope.handleLoadedItem();
        }
    };

    load.prototype.onLoadError = function( event ) {
        GLOW.error( "GLOW.Load.onLoadError: Error " + event.target.status );
    };

    /*
     * Three.js file format parser by
     * @author mrdoob / http://mrdoob.com/
     * @author alteredq / http://alteredqualia.com/
     * Slightly modified to suit GLOW by Mikael Emtinger
     */

    load.prototype.parseThreeJS = function( json ) {
        var geometry = {};
    	var scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;

    	parseModel( scale );
    	parseSkin();
    	parseMorphing( scale );
    	parseEdges();

    	function parseModel( scale ) {
    		if( json.version === undefined || json.version != 2 ) {
    			GLOW.error( 'Deprecated file format.' );
    			return;
    		}

    		function isBitSet( value, position ) {
    			return value & ( 1 << position );
    		};

    		var i, j, fi,
    		offset, zLength, nVertices,
    		colorIndex, normalIndex, uvIndex, materialIndex,
    		type,
    		isQuad,
    		hasMaterial,
    		hasFaceUv, hasFaceVertexUv,
    		hasFaceNormal, hasFaceVertexNormal,
    		hasFaceColor, hasFaceVertexColor,
    		vertex, face, color, normal,
    		uvLayer, uvs, u, v,
    		faces = json.faces,
    		vertices = json.vertices,
    		normals = json.normals,
    		colors = json.colors,
    		nUvLayers = 0;

    		// disregard empty arrays

    		for( i = 0; i < json.uvs.length; i++ ) {
    			if ( json.uvs[ i ].length ) nUvLayers ++;
    		}

    		for( i = 0; i < nUvLayers; i++ ) {
    			geometry.faceUvs[ i ] = [];
    			geometry.faceVertexUvs[ i ] = [];

    		}

    		offset = 0;
    		zLength = vertices.length;

    		while( offset < zLength ) {

    			vertex = new THREE.Vertex();

    			vertex.position.x = vertices[ offset ++ ] * scale;
    			vertex.position.y = vertices[ offset ++ ] * scale;
    			vertex.position.z = vertices[ offset ++ ] * scale;

    			geometry.vertices.push( vertex );

    		}

    		offset = 0;
    		zLength = faces.length;

    		while ( offset < zLength ) {

    			type = faces[ offset ++ ];

    			isQuad          	= isBitSet( type, 0 );
    			hasMaterial         = isBitSet( type, 1 );
    			hasFaceUv           = isBitSet( type, 2 );
    			hasFaceVertexUv     = isBitSet( type, 3 );
    			hasFaceNormal       = isBitSet( type, 4 );
    			hasFaceVertexNormal = isBitSet( type, 5 );
    			hasFaceColor	    = isBitSet( type, 6 );
    			hasFaceVertexColor  = isBitSet( type, 7 );

    			//GLOW.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);

    			if ( isQuad ) {

    				face = new THREE.Face4();

    				face.a = faces[ offset ++ ];
    				face.b = faces[ offset ++ ];
    				face.c = faces[ offset ++ ];
    				face.d = faces[ offset ++ ];

    				nVertices = 4;

    			} else {

    				face = new THREE.Face3();

    				face.a = faces[ offset ++ ];
    				face.b = faces[ offset ++ ];
    				face.c = faces[ offset ++ ];

    				nVertices = 3;

    			}

    			if ( hasMaterial ) {

    				materialIndex = faces[ offset ++ ];
    				face.materials = geometry.materials[ materialIndex ];

    			}

    			// to get face <=> uv index correspondence

    			fi = geometry.faces.length;

    			if ( hasFaceUv ) {

    				for ( i = 0; i < nUvLayers; i++ ) {

    					uvLayer = json.uvs[ i ];

    					uvIndex = faces[ offset ++ ];

    					u = uvLayer[ uvIndex * 2 ];
    					v = uvLayer[ uvIndex * 2 + 1 ];

    					geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );

    				}

    			}

    			if ( hasFaceVertexUv ) {

    				for ( i = 0; i < nUvLayers; i++ ) {

    					uvLayer = json.uvs[ i ];

    					uvs = [];

    					for ( j = 0; j < nVertices; j ++ ) {

    						uvIndex = faces[ offset ++ ];

    						u = uvLayer[ uvIndex * 2 ];
    						v = uvLayer[ uvIndex * 2 + 1 ];

    						uvs[ j ] = new THREE.UV( u, v );

    					}

    					geometry.faceVertexUvs[ i ][ fi ] = uvs;

    				}

    			}

    			if ( hasFaceNormal ) {

    				normalIndex = faces[ offset ++ ] * 3;

    				normal = new THREE.Vector3();

    				normal.x = normals[ normalIndex ++ ];
    				normal.y = normals[ normalIndex ++ ];
    				normal.z = normals[ normalIndex ];

    				face.normal = normal;

    			}

    			if ( hasFaceVertexNormal ) {

    				for ( i = 0; i < nVertices; i++ ) {

    					normalIndex = faces[ offset ++ ] * 3;

    					normal = new THREE.Vector3();

    					normal.x = normals[ normalIndex ++ ];
    					normal.y = normals[ normalIndex ++ ];
    					normal.z = normals[ normalIndex ];

    					face.vertexNormals.push( normal );

    				}

    			}

    			if ( hasFaceColor ) {

    				colorIndex = faces[ offset ++ ];

    				color = new THREE.Color( colors[ colorIndex ] );
    				face.color = color;

    			}

    			if ( hasFaceVertexColor ) {

    				for ( i = 0; i < nVertices; i++ ) {

    					colorIndex = faces[ offset ++ ];

    					color = new THREE.Color( colors[ colorIndex ] );
    					face.vertexColors.push( color );

    				}

    			}

    			geometry.faces.push( face );

    		}

    	};

    	function parseSkin() {

    		var i, l, x, y, z, w, a, b, c, d;

    		if ( json.skinWeights ) {

    			for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {

    				x = json.skinWeights[ i     ];
    				y = json.skinWeights[ i + 1 ];
    				z = 0;
    				w = 0;

    				geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );

    			}

    		}

    		if ( json.skinIndices ) {

    			for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {

    				a = json.skinIndices[ i     ];
    				b = json.skinIndices[ i + 1 ];
    				c = 0;
    				d = 0;

    				geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );

    			}

    		}

    		geometry.bones = json.bones;
    		geometry.animation = json.animation;

    	};

    	function parseMorphing( scale ) {

    		if ( json.morphTargets !== undefined ) {

    			var i, l, v, vl, x, y, z, dstVertices, srcVertices;

    			for ( i = 0, l = json.morphTargets.length; i < l; i++ ) {

    				geometry.morphTargets[ i ] = {};
    				geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
    				geometry.morphTargets[ i ].vertices = [];

    				dstVertices = geometry.morphTargets[ i ].vertices;
    				srcVertices = json.morphTargets [ i ].vertices;

    				for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {

    					x = srcVertices[ v ] * scale;
    					y = srcVertices[ v + 1 ] * scale;
    					z = srcVertices[ v + 2 ] * scale;

    					dstVertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );

    				}

    			}

    		}

    		if ( json.morphColors !== undefined ) {

    			var i, l, c, cl, dstColors, srcColors, color;

    			for ( i = 0, l = json.morphColors.length; i < l; i++ ) {

    				geometry.morphColors[ i ] = {};
    				geometry.morphColors[ i ].name = json.morphColors[ i ].name;
    				geometry.morphColors[ i ].colors = [];

    				dstColors = geometry.morphColors[ i ].colors;
    				srcColors = json.morphColors [ i ].colors;

    				for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {

    					color = new THREE.Color( 0xffaa00 );
    					color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
    					dstColors.push( color );

    				}

    			}

    		}

    	};

    	function parseEdges() {

    		if( json.edges !== undefined ) {

    			var i, il, v1, v2;

    			for ( i = 0; i < json.edges.length; i+= 2 ) {

    				v1 = json.edges[ i ];
    				v2 = json.edges[ i + 1 ];

    				geometry.edges.push( new THREE.Edge( geometry.vertices[ v1 ], geometry.vertices[ v2 ], v1, v2 ) );

    			}

    		}

    	};
    }

    return load;
})();

<commit_msg>Missing = with "onLoadContext" in GLOW.Load constructor<commit_after>GLOW.Load = (function() {

    "use strict"; "use restrict";

    // constructor
    function load( parameters ) {
        this.parameters         = parameters;
        this.onLoadComplete     = undefined;
        this.onLoadContext      = null;
        this.onLoadItem         = undefined;
        this.numItemsToLoad     = 0;
        this.numItemsLeftToLoad = 0;

        for( var p in parameters ) {
            if( p !== "onLoadComplete" && p !== "onLoadItem" && p!== "dontParseJS" && p !== "onLoadContext" ) {
                this.numItemsToLoad++;
            } else {
                this[ p ] = parameters[ p ];
                delete parameters[ p ];
            }
        }
        this.numItemsLeftToLoad = this.numItemsToLoad;

        for( var p in parameters ) {
            var originalURL  = parameters[ p ];
            var lowerCaseURL = parameters[ p ];
            if( lowerCaseURL.indexOf( ".png" ) !== -1 ||
                lowerCaseURL.indexOf( ".gif" ) !== -1 ||
                lowerCaseURL.indexOf( ".jpg" ) !== -1 ||
                lowerCaseURL.indexOf( "jpeg" ) !== -1 ) {
                parameters[ p ] = new Image();
                parameters[ p ].scope = this;
                parameters[ p ].onload = this.onLoadImage;
                parameters[ p ].onerror = this.onLoadError;
                parameters[ p ].onabort = this.onLoadError;
                parameters[ p ].src = originalURL;
            } else if( lowerCaseURL.indexOf( ".glsl" ) !== -1 ) {
                parameters[ p ] = new XMLHttpRequest();
                parameters[ p ].scope = this;
                parameters[ p ].parametersProperty = p;
                parameters[ p ].open( "GET", originalURL );
                parameters[ p ].onreadystatechange = this.onLoadGLSL;
                parameters[ p ].onerror = this.onLoadError;
                parameters[ p ].onabort = this.onLoadError;
                parameters[ p ].send();
            } else if( lowerCaseURL.indexOf( ".js" ) !== -1 || lowerCaseURL.indexOf( ".json" ) !== -1 ) {
                parameters[ p ] = new XMLHttpRequest();
                parameters[ p ].scope = this;
                parameters[ p ].parametersProperty = p;
                parameters[ p ].open( "GET", originalURL );
                parameters[ p ].onreadystatechange = this.onLoadJSON;
                parameters[ p ].onerror = this.onLoadError;
                parameters[ p ].onabort = this.onLoadError;
                parameters[ p ].send();
            } else {
                parameters[ p ] = document.createElement( "video" );
                parameters[ p ].scope = this;
                parameters[ p ].addEventListener( "loadeddata", this.onLoadVideo, false );
                parameters[ p ].src = originalURL;
            }
        }
    }

    // methods
    load.prototype.handleLoadedItem = function() {
        this.numItemsLeftToLoad--;
        if( this.onLoadItem !== undefined ) {
            this.onLoadItem.call( this.onLoadContext, 1 - this.numItemsLeftToLoad / this.numItemsToLoad );
        }
        if( this.numItemsLeftToLoad <= 0 ) {
            this.onLoadComplete.call( this.onLoadContext, this.parameters );
        }
    };

    load.prototype.onLoadJSON = function() {
        if( this.readyState === 4 ) {
   /*         var originalData;
            var data = {};

            // Three.js
            if( this.scope.dontParseJS !== true ) {
                if( this.responseText.indexOf( "var model = {" ) !== -1 ) {
                    var dataString = this.responseText.slice( this.responseText.indexOf( "var model = {" ) + 12,
                                                              this.responseText.indexOf( "};" ) + 1 );
                    originalData = JSON.parse( dataString );
                    data = this.scope.parseThreeJS( originalData );
                // J3D
                } else {
                    originalData = JSON.parse( this.responseText );

                    if( originalData.vertices && originalData.vertices.length > 0 ) data.vertices = new Float32Array( originalData.vertices );
                    if( originalData.normals && originalData.normals.length > 0 ) data.normals = new Float32Array( originalData.normals );
                    if( originalData.uv1 && originalData.uv1.length > 0 ) data.uv1 = new Float32Array( originalData.uv1 );
                    if( originalData.uv2 && originalData.uv2.length > 0 ) data.uv2 = new Float32Array( originalData.uv2 );
                    if( originalData.colors && originalData.colors.length > 0 ) data.colors = new Float32Array( originalData.colors );
                    if( originalData.tris && originalData.tris.length > 0 ) data.triangles = new Uint16Array( originalData.tris );
                }
            } else {
                data = JSON.parse( this.responseText );
            }*/

            this.scope.parameters[ this.parametersProperty ] = JSON.parse( this.responseText );;
            this.scope.handleLoadedItem();
        }
    };

    load.prototype.onLoadImage = function() {
        this.scope.handleLoadedItem();
    };

    load.prototype.onLoadVideo = function() {
        this.removeEventListener( "loadeddata", this.scope.onLoadVideo, false );
        this.scope.handleLoadedItem();
    };

    /*
    * GLSL parser by Bartek Drozyz
    * Slightly modified to suit GLOW by Mikael Emtinger
    */

    load.prototype.onLoadGLSL = function() {
        if( this.readyState === 4 ) {
            // glsl parser by Bartek Drozyz
        	var vs = "";
        	var fs = "";
        	var ls = this.responseText.split( "\n" );
        	var buf = "";
        	for( var i = 0; i < ls.length; i++ ) {
        		if( ls[ i ].indexOf( "//#" ) > -1 ) {
        			if( ls[ i ].indexOf( "Fragment" ) > -1 ) {
        				vs = buf;
        				buf = "";
        			}
        		} else {
        			var l = ls[ i ];
        			if( l.indexOf( "//" ) > -1 ) {
        			    l = l.substring( 0, l.indexOf( "//" ));
    			    }
                    if( l.indexOf( ";" ) === -1 ) {
                        l += "\n";
                    }
        			buf += l;
        		}
        	}
        	fs = buf;

            this.scope.parameters[ this.parametersProperty ] = { fragmentShader: "#ifdef GL_ES\nprecision highp float;\n#endif\n" + fs, vertexShader: vs };
            this.scope.handleLoadedItem();
        }
    };

    load.prototype.onLoadError = function( event ) {
        GLOW.error( "GLOW.Load.onLoadError: Error " + event.target.status );
    };

    /*
     * Three.js file format parser by
     * @author mrdoob / http://mrdoob.com/
     * @author alteredq / http://alteredqualia.com/
     * Slightly modified to suit GLOW by Mikael Emtinger
     */

    load.prototype.parseThreeJS = function( json ) {
        var geometry = {};
    	var scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;

    	parseModel( scale );
    	parseSkin();
    	parseMorphing( scale );
    	parseEdges();

    	function parseModel( scale ) {
    		if( json.version === undefined || json.version != 2 ) {
    			GLOW.error( 'Deprecated file format.' );
    			return;
    		}

    		function isBitSet( value, position ) {
    			return value & ( 1 << position );
    		};

    		var i, j, fi,
    		offset, zLength, nVertices,
    		colorIndex, normalIndex, uvIndex, materialIndex,
    		type,
    		isQuad,
    		hasMaterial,
    		hasFaceUv, hasFaceVertexUv,
    		hasFaceNormal, hasFaceVertexNormal,
    		hasFaceColor, hasFaceVertexColor,
    		vertex, face, color, normal,
    		uvLayer, uvs, u, v,
    		faces = json.faces,
    		vertices = json.vertices,
    		normals = json.normals,
    		colors = json.colors,
    		nUvLayers = 0;

    		// disregard empty arrays

    		for( i = 0; i < json.uvs.length; i++ ) {
    			if ( json.uvs[ i ].length ) nUvLayers ++;
    		}

    		for( i = 0; i < nUvLayers; i++ ) {
    			geometry.faceUvs[ i ] = [];
    			geometry.faceVertexUvs[ i ] = [];

    		}

    		offset = 0;
    		zLength = vertices.length;

    		while( offset < zLength ) {

    			vertex = new THREE.Vertex();

    			vertex.position.x = vertices[ offset ++ ] * scale;
    			vertex.position.y = vertices[ offset ++ ] * scale;
    			vertex.position.z = vertices[ offset ++ ] * scale;

    			geometry.vertices.push( vertex );

    		}

    		offset = 0;
    		zLength = faces.length;

    		while ( offset < zLength ) {

    			type = faces[ offset ++ ];

    			isQuad          	= isBitSet( type, 0 );
    			hasMaterial         = isBitSet( type, 1 );
    			hasFaceUv           = isBitSet( type, 2 );
    			hasFaceVertexUv     = isBitSet( type, 3 );
    			hasFaceNormal       = isBitSet( type, 4 );
    			hasFaceVertexNormal = isBitSet( type, 5 );
    			hasFaceColor	    = isBitSet( type, 6 );
    			hasFaceVertexColor  = isBitSet( type, 7 );

    			//GLOW.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);

    			if ( isQuad ) {

    				face = new THREE.Face4();

    				face.a = faces[ offset ++ ];
    				face.b = faces[ offset ++ ];
    				face.c = faces[ offset ++ ];
    				face.d = faces[ offset ++ ];

    				nVertices = 4;

    			} else {

    				face = new THREE.Face3();

    				face.a = faces[ offset ++ ];
    				face.b = faces[ offset ++ ];
    				face.c = faces[ offset ++ ];

    				nVertices = 3;

    			}

    			if ( hasMaterial ) {

    				materialIndex = faces[ offset ++ ];
    				face.materials = geometry.materials[ materialIndex ];

    			}

    			// to get face <=> uv index correspondence

    			fi = geometry.faces.length;

    			if ( hasFaceUv ) {

    				for ( i = 0; i < nUvLayers; i++ ) {

    					uvLayer = json.uvs[ i ];

    					uvIndex = faces[ offset ++ ];

    					u = uvLayer[ uvIndex * 2 ];
    					v = uvLayer[ uvIndex * 2 + 1 ];

    					geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );

    				}

    			}

    			if ( hasFaceVertexUv ) {

    				for ( i = 0; i < nUvLayers; i++ ) {

    					uvLayer = json.uvs[ i ];

    					uvs = [];

    					for ( j = 0; j < nVertices; j ++ ) {

    						uvIndex = faces[ offset ++ ];

    						u = uvLayer[ uvIndex * 2 ];
    						v = uvLayer[ uvIndex * 2 + 1 ];

    						uvs[ j ] = new THREE.UV( u, v );

    					}

    					geometry.faceVertexUvs[ i ][ fi ] = uvs;

    				}

    			}

    			if ( hasFaceNormal ) {

    				normalIndex = faces[ offset ++ ] * 3;

    				normal = new THREE.Vector3();

    				normal.x = normals[ normalIndex ++ ];
    				normal.y = normals[ normalIndex ++ ];
    				normal.z = normals[ normalIndex ];

    				face.normal = normal;

    			}

    			if ( hasFaceVertexNormal ) {

    				for ( i = 0; i < nVertices; i++ ) {

    					normalIndex = faces[ offset ++ ] * 3;

    					normal = new THREE.Vector3();

    					normal.x = normals[ normalIndex ++ ];
    					normal.y = normals[ normalIndex ++ ];
    					normal.z = normals[ normalIndex ];

    					face.vertexNormals.push( normal );

    				}

    			}

    			if ( hasFaceColor ) {

    				colorIndex = faces[ offset ++ ];

    				color = new THREE.Color( colors[ colorIndex ] );
    				face.color = color;

    			}

    			if ( hasFaceVertexColor ) {

    				for ( i = 0; i < nVertices; i++ ) {

    					colorIndex = faces[ offset ++ ];

    					color = new THREE.Color( colors[ colorIndex ] );
    					face.vertexColors.push( color );

    				}

    			}

    			geometry.faces.push( face );

    		}

    	};

    	function parseSkin() {

    		var i, l, x, y, z, w, a, b, c, d;

    		if ( json.skinWeights ) {

    			for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {

    				x = json.skinWeights[ i     ];
    				y = json.skinWeights[ i + 1 ];
    				z = 0;
    				w = 0;

    				geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );

    			}

    		}

    		if ( json.skinIndices ) {

    			for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {

    				a = json.skinIndices[ i     ];
    				b = json.skinIndices[ i + 1 ];
    				c = 0;
    				d = 0;

    				geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );

    			}

    		}

    		geometry.bones = json.bones;
    		geometry.animation = json.animation;

    	};

    	function parseMorphing( scale ) {

    		if ( json.morphTargets !== undefined ) {

    			var i, l, v, vl, x, y, z, dstVertices, srcVertices;

    			for ( i = 0, l = json.morphTargets.length; i < l; i++ ) {

    				geometry.morphTargets[ i ] = {};
    				geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
    				geometry.morphTargets[ i ].vertices = [];

    				dstVertices = geometry.morphTargets[ i ].vertices;
    				srcVertices = json.morphTargets [ i ].vertices;

    				for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {

    					x = srcVertices[ v ] * scale;
    					y = srcVertices[ v + 1 ] * scale;
    					z = srcVertices[ v + 2 ] * scale;

    					dstVertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );

    				}

    			}

    		}

    		if ( json.morphColors !== undefined ) {

    			var i, l, c, cl, dstColors, srcColors, color;

    			for ( i = 0, l = json.morphColors.length; i < l; i++ ) {

    				geometry.morphColors[ i ] = {};
    				geometry.morphColors[ i ].name = json.morphColors[ i ].name;
    				geometry.morphColors[ i ].colors = [];

    				dstColors = geometry.morphColors[ i ].colors;
    				srcColors = json.morphColors [ i ].colors;

    				for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {

    					color = new THREE.Color( 0xffaa00 );
    					color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
    					dstColors.push( color );

    				}

    			}

    		}

    	};

    	function parseEdges() {

    		if( json.edges !== undefined ) {

    			var i, il, v1, v2;

    			for ( i = 0; i < json.edges.length; i+= 2 ) {

    				v1 = json.edges[ i ];
    				v2 = json.edges[ i + 1 ];

    				geometry.edges.push( new THREE.Edge( geometry.vertices[ v1 ], geometry.vertices[ v2 ], v1, v2 ) );

    			}

    		}

    	};
    }

    return load;
})();

<|endoftext|>