<commit_before>

var http = require( 'http' ),
    formaline = require( '../../lib/formaline' ).formaline,
    connect = require( 'connect' ),
    server,
    log = console.log,
    dir =  '/tmp/';
    getHtmlForm = function( req, res, next ) {
        if (req.url === '/test/') {
        log( ' -> req url :', req.url );
        res.writeHead( 200, { 'content-type': 'text/html' } );
        res.end( '\
                 Multiple File Upload:

\
                 <form action="/test/upload" enctype="multipart/form-data" method="post">\
                 <input type="text" name="demotitle1"/>
\
                 <input type="file" name="multiplefield1" multiple="multiple">
\
                 <input type="text" name="demotitle2/">
\
                 <input type="file" name="multiplefield2" multiple="multiple">
\
                 <input type="text" name="demotitle3"/>
\
                 <input type="file" name="multiplefield3" multiple="multiple">
\
                 <input type="submit" value="Upload"/>\
                 </form>
\
                 Simple Post:

\
                 <form action="/test/post" method="post">\
                 <input type="text" name="simplefield1"/>
\
                 <input type="text" name="simplefield2"/>
\
                 <input type="text" name="simplefield3"/>
\
                 <input type="submit" value="Submit">\
                 </form>
\
                 Iframe Multiple File Upload:

\
                 <form action="/test/upload" method="post" enctype="multipart/form-data" target="iframe">\
                 <input type="text" name="iframefield1"/>
\
                 <input type="file" name="iframefile1" multiple  src="" frameborder="1" />
\
                 <input type="text" name="iframefield2"/>
\
                 <input type="file" name="iframefile2" multiple  src="" frameborder="1" />
\
                 <input type="submit" />\
                 </form>\
                 \
                 </form>\
                 '
            );
        } else {
            next();
        }
    },
    handleFormRequest = function( req, res, next ){
        var receivedFiles = {},
            removedFiles = {},
            receivedFields = {},
            form = null,
            config = {

                    // default is true -->
                holdFilesExtensions : true,

                    // default is /tmp/ -->
                uploadRootDir: dir,

                    // retrieve session ID for creating unique upload directory for authenticated users
                    // the upload directory gets its name from the returned session identifier,
                    // and will remain the same across multiple posts ( for the authenticated user with this session identifier )
                    // this function have to return the request property that holds session id
                    // session id param returned must contains a String, not a function or an object
                    // the function takes http request as a parameter at run-time
                getSessionID: function( req ){
                    return ( req.session && req.session.id ) ? req.session.id : null;
                },

                    // default is false
                    // return sha1 digests for files received?
                sha1sum: true,

                    // default is false, or integer chunk factor,
                    // every n chunk emits a dataprogress event:  1 + ( 0 * n ) 1 + ( 1 * n ), 1 + ( 2 * n ), 1 + ( 3 * n ),
                    // minimum factor value is 2
                emitDataProgress: false, // 3, 10, 100

                    // max bytes allowed, this is the max bytes written to disk before stop to write
                    // this is also true for serialzed fields not only for files upload
                uploadThreshold: 1024 * 4 * 1024, // bytes ex.: 1024*1024*1024, 512

                    // default false, bypass headers value, continue to write to disk
                    // until uploadThreshold bytes are written.
                    // if true -> stop receiving data, when headers content length exceeds uploadThreshold
                checkContentLength: false,

                    // remove file not completed due to uploadThreshold,
                    // if true formaline emit fileremoved event,
                    // otherwise return a path array of incomplete files
                removeIncompleteFiles : true,

                    // default is 'debug:off,1:on,2:on,3:off';
                    // enable various logging levels
                    // it is possible to switch on/off one or more levels at the same time
                    // debug: 'off' turn off logging
                logging: 'debug:on,1:on,2:on,3:off',

                    // listeners
                listeners: {
                    'exception': function( etype, isupload, errmsg, isfatal ){
                    },
                    'dataprogress': function( bytesReceived, chunksReceived, ratio ) {
                    },
                    'field': function( fname, fvalue ){
                        receivedFields[ fname ] = fvalue;
                    },
                    'filereceived': function( sha1filename, origfilename, filedir, filetype, filesize, filefield, filesha1sum ) {
                        receivedFiles[ sha1filename ] = { path: filedir, origName: origfilename, type: filetype, size: filesize, field: filefield, sha1sum: filesha1sum  };
                        },
                    'fileremoved': function( sha1filename, origfilename, filedir, filetype, filesize, filefield ) {
                        removedFiles[ sha1filename ] = { path: filedir, origName: origfilename, type: filetype, filesize: filesize, field: filefield };
                    },
                    'end': function( incompleteFiles, stats, res, next ) {
                        log( '\n-> Post Done' );
                        res.writeHead( 200, { 'content-type': 'text/plain' } );
                        res.write( '-> ' + new Date() + '\n' );
                        res.write( '-> request processed! \n')
                        res.write( '\n-> stats -> ' + JSON.stringify( stats ) + '\n' );
                        res.write( '\n-> upload dir: ' + form.uploadRootDir + ' \n');
                        res.write( '-> upload threshold : ' + ( form.uploadThreshold ) + ' bytes \n');
                        res.write( '-> checkContentLength: ' + form.checkContentLength + '\n');
                        res.write( '-> holdFilesExtensions: ' + form.holdFilesExtensions + '\n');
                        res.write( '-> sha1sum: ' + form.sha1sum + '\n');
                        res.write( '-> removeIncompleteFiles: ' + form.removeIncompleteFiles + '\n');
                        res.write( '-> emitDataProgress: ' + form.emitDataProgress + '\n');

                        res.write( '\n-> fields received: \n   ****************\n' + JSON.stringify(receivedFields) + '\n');
                        res.write( '\n-> files received: ( { sha1name: {..} }, { .. } )\n   ***************\n ' + JSON.stringify(receivedFiles) + '\n');
                        if( form.removeIncompleteFiles ){
                            res.write( '\n-> files removed: ( { sha1name: {..} }, { .. } )\n   **************\n' + JSON.stringify(removedFiles) + '\n');
                        }else{
                            if( incompleteFiles.length !== 0 ){
                                res.write( '-> incomplete files (not removed) : ' + incompleteFiles + '\n');
                            }
                        }
                        receivedFiles = {};
                        removedFiles = {};
                        receivedFields = {};
                        res.end();
                        next(); //test
                    }
                }
            };//end config obj

        if ( (req.url === '/test/upload') || (req.url === '/test/post') ){
            log( ' -> req url :', req.url );
            form = new formaline( config ) ;
            form.parse( req, res, next );

        } else {
            log( ' -> req url 404 error :', req.url );
            res.writeHead( 404, { 'content-type': 'text/plain' } );
            res.end( '404' );
        }
};

server = connect( getHtmlForm , handleFormRequest, function(){ console.log( '\nHi!, I\'m the next() callback function!'); } );

server.listen( 3000 );

log( '\nlistening on http://localhost:3000/' );
log( ' -> upload directory is:', dir );

<commit_msg>Added better return value in getSessionId config param in example modified:   examples/simple/simpleUpload.js<commit_after>

var http = require( 'http' ),
    formaline = require( '../../lib/formaline' ).formaline,
    connect = require( 'connect' ),
    server,
    log = console.log,
    dir =  '/tmp/';
    getHtmlForm = function( req, res, next ) {
        if (req.url === '/test/') {
        log( ' -> req url :', req.url );
        res.writeHead( 200, { 'content-type': 'text/html' } );
        res.end( '\
                 Multiple File Upload:

\
                 <form action="/test/upload" enctype="multipart/form-data" method="post">\
                 <input type="text" name="demotitle1"/>
\
                 <input type="file" name="multiplefield1" multiple="multiple">
\
                 <input type="text" name="demotitle2/">
\
                 <input type="file" name="multiplefield2" multiple="multiple">
\
                 <input type="text" name="demotitle3"/>
\
                 <input type="file" name="multiplefield3" multiple="multiple">
\
                 <input type="submit" value="Upload"/>\
                 </form>
\
                 Simple Post:

\
                 <form action="/test/post" method="post">\
                 <input type="text" name="simplefield1"/>
\
                 <input type="text" name="simplefield2"/>
\
                 <input type="text" name="simplefield3"/>
\
                 <input type="submit" value="Submit">\
                 </form>
\
                 Iframe Multiple File Upload:

\
                 <form action="/test/upload" method="post" enctype="multipart/form-data" target="iframe">\
                 <input type="text" name="iframefield1"/>
\
                 <input type="file" name="iframefile1" multiple  src="" frameborder="1" />
\
                 <input type="text" name="iframefield2"/>
\
                 <input type="file" name="iframefile2" multiple  src="" frameborder="1" />
\
                 <input type="submit" />\
                 </form>\
                 \
                 </form>\
                 '
            );
        } else {
            next();
        }
    },
    handleFormRequest = function( req, res, next ){
        var receivedFiles = {},
            removedFiles = {},
            receivedFields = {},
            form = null,
            config = {

                    // default is true -->
                holdFilesExtensions : true,

                    // default is /tmp/ -->
                uploadRootDir: dir,

                    // retrieve session ID for creating unique upload directory for authenticated users
                    // the upload directory gets its name from the returned session identifier,
                    // and will remain the same across multiple posts ( for the authenticated user with this session identifier )
                    // this function have to return the request property that holds session id
                    // session id param returned must contains a String, not a function or an object
                    // the function takes http request as a parameter at run-time
                getSessionID: function( req ){
                    return ( ( req.sessionID ) || ( req.sid ) || ( ( req.session && req.session.id ) ? req.session.id : null ) );
                },

                    // default is false
                    // return sha1 digests for files received?
                sha1sum: true,

                    // default is false, or integer chunk factor,
                    // every n chunk emits a dataprogress event:  1 + ( 0 * n ) 1 + ( 1 * n ), 1 + ( 2 * n ), 1 + ( 3 * n ),
                    // minimum factor value is 2
                emitDataProgress: false, // 3, 10, 100

                    // max bytes allowed, this is the max bytes written to disk before stop to write
                    // this is also true for serialzed fields not only for files upload
                uploadThreshold: 1024 * 4 * 1024, // bytes ex.: 1024*1024*1024, 512

                    // default false, bypass headers value, continue to write to disk
                    // until uploadThreshold bytes are written.
                    // if true -> stop receiving data, when headers content length exceeds uploadThreshold
                checkContentLength: false,

                    // remove file not completed due to uploadThreshold,
                    // if true formaline emit fileremoved event,
                    // otherwise return a path array of incomplete files
                removeIncompleteFiles : true,

                    // default is 'debug:off,1:on,2:on,3:off';
                    // enable various logging levels
                    // it is possible to switch on/off one or more levels at the same time
                    // debug: 'off' turn off logging
                logging: 'debug:on,1:on,2:on,3:off',

                    // listeners
                listeners: {
                    'exception': function( etype, isupload, errmsg, isfatal ){
                    },
                    'dataprogress': function( bytesReceived, chunksReceived, ratio ) {
                    },
                    'field': function( fname, fvalue ){
                        receivedFields[ fname ] = fvalue;
                    },
                    'filereceived': function( sha1filename, origfilename, filedir, filetype, filesize, filefield, filesha1sum ) {
                        receivedFiles[ sha1filename ] = { path: filedir, origName: origfilename, type: filetype, size: filesize, field: filefield, sha1sum: filesha1sum  };
                        },
                    'fileremoved': function( sha1filename, origfilename, filedir, filetype, filesize, filefield ) {
                        removedFiles[ sha1filename ] = { path: filedir, origName: origfilename, type: filetype, filesize: filesize, field: filefield };
                    },
                    'end': function( incompleteFiles, stats, res, next ) {
                        log( '\n-> Post Done' );
                        res.writeHead( 200, { 'content-type': 'text/plain' } );
                        res.write( '-> ' + new Date() + '\n' );
                        res.write( '-> request processed! \n')
                        res.write( '\n-> stats -> ' + JSON.stringify( stats ) + '\n' );
                        res.write( '\n-> upload dir: ' + form.uploadRootDir + ' \n');
                        res.write( '-> upload threshold : ' + ( form.uploadThreshold ) + ' bytes \n');
                        res.write( '-> checkContentLength: ' + form.checkContentLength + '\n');
                        res.write( '-> holdFilesExtensions: ' + form.holdFilesExtensions + '\n');
                        res.write( '-> sha1sum: ' + form.sha1sum + '\n');
                        res.write( '-> removeIncompleteFiles: ' + form.removeIncompleteFiles + '\n');
                        res.write( '-> emitDataProgress: ' + form.emitDataProgress + '\n');

                        res.write( '\n-> fields received: \n   ****************\n' + JSON.stringify(receivedFields) + '\n');
                        res.write( '\n-> files received: ( { sha1name: {..} }, { .. } )\n   ***************\n ' + JSON.stringify(receivedFiles) + '\n');
                        if( form.removeIncompleteFiles ){
                            res.write( '\n-> files removed: ( { sha1name: {..} }, { .. } )\n   **************\n' + JSON.stringify(removedFiles) + '\n');
                        }else{
                            if( incompleteFiles.length !== 0 ){
                                res.write( '-> incomplete files (not removed) : ' + incompleteFiles + '\n');
                            }
                        }
                        receivedFiles = {};
                        removedFiles = {};
                        receivedFields = {};
                        res.end();
                        next(); //test
                    }
                }
            };//end config obj

        if ( (req.url === '/test/upload') || (req.url === '/test/post') ){
            log( ' -> req url :', req.url );
            form = new formaline( config ) ;
            form.parse( req, res, next );

        } else {
            log( ' -> req url 404 error :', req.url );
            res.writeHead( 404, { 'content-type': 'text/plain' } );
            res.end( '404' );
        }
};

server = connect( getHtmlForm , handleFormRequest, function(){ console.log( '\nHi!, I\'m the next() callback function!'); } );

server.listen( 3000 );

log( '\nlistening on http://localhost:3000/' );
log( ' -> upload directory is:', dir );

<|endoftext|>


<commit_before>(function($) {

	Editor = function() {
		this.$element_;
		inst = inst || {};
		this.events_ = [];
		this.enterDocument();

	};

	Editor.EventType = {
		EDITOR : 'editor'
	};

	Editor.prototype.getElement = function() {
		return this.$element_;
	};

	Editor.prototype.enterDocument = function() {
		sessionStorage.clear();
		this.$element_ = $(".contents-root");
		this.bindEvents_();
	}

	Editor.prototype.exitDocument = function() {
		if (!this.$element_) {
			return;
		}
		if (this.events_.length > 0) {
			$.each(this.events_, function(idx, args) {
				this.$element_.off.apply(this.$element_, args);
			}.bind(this));
			this.events_ = [];
		}
		this.unbindEvents_();
		this.$element_ = null;
	}

	Editor.prototype.bindEvents_ = function() {
		this.$element_.on('click', '.text-strage-btn', this.saveModal_.bind(this));
		this.$element_.on('keydown', this.keydownFunction_.bind(this));
		this.$element_.on('click', '.reading-btn',this.readingText_.bind(this));
		this.$element_.on('click', '.dummy-file-btn',this.clickFilebtn_.bind(this));
		this.$element_.on('click', '.save-file-btn',this.clickSaveBtn_.bind(this));
		this.$element_.on('beforeunload',this.beforUnloadEvent_.bind(this));
		this.$element_.on('click','.upload-minutes',this.uploadEvent_.bind(this));
	}

	Editor.prototype.keydownFunction_ = function(e) {
		var target = e.target;
		if (e.ctrlKey === true && e.keyCode === 83) {
			event.preventDefault();
			var textData = this.inputTextData_(textData);

		} else if (e.ctrlKey === true) {

		} else {
			$(window).on('beforeunload', function(e) {
				return 'jquery beforeunload';
			});
		}
	}

	Editor.prototype.inputTextData_ = function(textData) {
		var title = $(".minutes-editor-title").val()
		var text = $("#minutes-textarea").val()
		text = text.split("<").join("<");
		text = text.split(">").join(">");
		text = text.split("\n").join("\r\n");
		textData = {
			text : text,
			title : title
		}
		var confirmed = false
		this.checkData(textData);
	}

	Editor.prototype.checkData = function(textData, confirmed) {
		var status = null;
		if (confirmed === true) {
			this.saveTextData_(textData);
		} else {

			if (textData.title === "" && textData.text === "") {
				status = "both";
				this.showConfirmDialog_(textData, status);
				event.stopPropagation();
			}
			else if(textData.title === ""){
				status = "title";
				this.showConfirmDialog_(textData, status);
				event.stopPropagation();
			}
			else if(textData.text === ""){
				status = "text"
				this.showConfirmDialog_(textData, status);
				event.stopPropagation();
			}
			else {
				this.saveTextData_(textData);
			}
		}
	}

	Editor.prototype.saveTextData_ = function(textData) {
		if (textData === undefined) {
			textData = {
				text : "",
				title : "無題"
			}

		}
		else if (textData.title === "") {
			textData = {
				text : textData.text,
				title : "無題"
			}

		}

		var blob = new Blob([ textData.text ], {
			type : "text/plain"
		});
		var a = document.createElement("a");
		a.href = URL.createObjectURL(blob);
		a.target = '_blank';
		a.download = textData.title;
		a.click();
		event.stopPropagation();
	}

	Editor.prototype.showConfirmDialog_ = function(textData, status) {
		$('#staticModal').modal('show');
		if(status === "both"){
			$(".confirm-text").text("何も入力されていませんがよろしいでしょうか？")
		}
		else if(status === "title"){
			$(".confirm-text").text("タイトルが入力されていませんが保存してもいいでしょうか？")

		}
		else if(status === "text"){

			$(".confirm-text").text("本文が入力されていませんが保存してもいいでしょうか？")
		}

		var strage = document.getElementById("text-strage-btn");
		$("#text-strage-btn").unbind('click')
		$("#text-strage-btn").bind('click',function(){
			Editor.prototype.saveModal_(textData);
		})
	}
	Editor.prototype.saveModal_ = function(textData) {
		$('#staticModal').modal('hide');
		window.alert("保存しました");
		this.saveTextData_(textData);
		 $(window).off('beforeunload');
	}

	Editor.prototype.validateText_ = function(data) {
		var lastPart = null;
		var lastDetail = null;
		var lastDetailTwo = null;
		var lastType = null;
		var lastValidate = null;
		var lastLineNum = null;
		var count = 0
		this.initializeAlertarea_();
		var lineNum = 1;
		var i = 0

		while (i <data.length) {

			var part = data[i].pos;
			var word = data[i].surface_form;
			var detail = data[i].pos_detail_1;
			var detailTwo = data[i].pos_detail_2;
			var type = data[i].word_type;
			var position = data[i].ward_position;

			if (type === 'UNKNOWN') {
				if (part === '記号') {
					if(word.match(/\r\n|\n/g)){
						var num = word.match(/\r\n|\n/g).length;
						lineNum = lineNum + num ;
					}
				}
				else if(word.match("-")){

				}
				else if(!isNaN(word)){

				}
				else {
					if(lastType !== 'UNKNOWN'){
					$(".alert-list").append('
辞書に登録されていない文字です。' + lineNum  +  "行目" +  '
')
					$(".minutes-lines").eq(lineNum-1).addClass("yellow");
					}
				}

			} else if (type == 'KNOWN') {
				if (part === '記号') {

					if (detail === 'アルファベット') {
						$(".alert-list").append('
アルファベットが含まれています。' + lineNum  +  "行目" +  '
')
						$(".minutes-lines").eq(lineNum-1).addClass("yellow");
					} else if (lastDetail === '句点') {
						$(".alert-list").append('
句点の位置がおかしい可能性があります。' + lineNum  +  "行目" +  '
')
						$(".minutes-lines").eq(lineNum-1).addClass("yellow");
					}
					else if (lastDetailTwo === '人名') {
						$(".alert-list").append('
句点の位置がおかしい可能性があります。' + lineNum  +  "行目" +  '
')
						$(".minutes-lines").eq(lineNum-1).addClass("yellow");
					}
				} else if (part === '動詞') {
					if (lastPart === "動詞") {
//						$(".alert-list").append('
動詞が続いています。' + lineNum  +  "行目" +  '
')
//					} else if (detail === '非自立') {
//						if (lastPart === '名詞') {
//							$(".alert-list").append(
//									'
名詞の後に非自立品詞が入っています。' + lineNum  +  "行目" +  '
')
//						}
					}
					else if(lastDetailTwo === '人名'){
						$(".alert-list").append(
							'
動詞の位置がおかしい可能性があります。' + lineNum  +  "行目" +  '
')
							$(".minutes-lines").eq(lineNum-1).addClass("yellow");
					}

				} else if (part === '名詞') {
					if(detail === '固有名詞'){
						if(detailTwo === '人名'){
							//$(".alert-list").append(
								//	'
人名が含まれています。' + lineNum  +  "行目" +  '
')
						}
					}

				}
			}
			lastType = type;
			lastPart = part;
			lastDetail = detail;
			lastDetailTwo = detailTwo;
			lastLineNum = lineNum;
			i=(i+1)|0

		}
	}

	Editor.prototype.getStorageItem_ = function(count){
		var allData = JSON.parse(sessionStorage.getItem(count + "allData"))
		if(allData == null){
			if(count== 0){
				return 1;
			}
			else{

			return ;
			}
		}
		count++;
		this.getStorageItem_(count);
	}

	Editor.prototype.initializeAlertarea_ = function() {
		$(".alert-list").children("li").remove();
		$("#minutes-textarea").parents(".editor-field").find(".lineno").addClass("minutes-lines")

		$(".minutes-lines").removeClass("yellow");
	}

	Editor.prototype.readingText_ = function(){

		var filebtn = document.getElementById("selfile");
		var newFilebtn = document.getElementById("new-selfile");

		//ダイアログでファイルが選択された時
		filebtn.addEventListener("change",function(evt){

		  var file = evt.target.files;

		  //FileReaderの作成
		  var reader = new FileReader();

		    reader.readAsArrayBuffer(file[0]);

		  //読込終了後の処理
		  reader.onload = function(ev){
			    var array = new Uint8Array(reader.result);

			    // 文字コードを取得
			    switch (Encoding.detect(array)) {
			    case 'UTF16':
			        // 16ビット符号なし整数値配列と見なす
			        array = new Uint16Array(e.target.result);
			        break;
			    case 'UTF32':
			        // 32ビット符号なし整数値配列と見なす
			        array = new Uint32Array(e.target.result);
			        break;
			    }

			    // Unicodeの数値配列に変換
			    var unicodeArray = Encoding.convert(array, 'UNICODE');
			    // Unicodeの数値配列を文字列に変換
			    var text = Encoding.codeToString(unicodeArray);

		    //テキストエリアに表示する
			$(".origin-editor-title").val(file[0].name);
		    document.test.txt.value = text;
		  }
		},false);

		newFilebtn.addEventListener("change",function(evt){

			  var file = evt.target.files;

			  //FileReaderの作成
			  var reader = new FileReader();
			  //テキスト形式で読み込む
			   reader.readAsArrayBuffer(file[0]);

			  //読込終了後の処理
			  reader.onload = function(ev){
				  var array = new Uint8Array(reader.result);

				    // 文字コードを取得
				    switch (Encoding.detect(array)) {
				    case 'UTF16':
				        // 16ビット符号なし整数値配列と見なす
				        array = new Uint16Array(e.target.result);
				        break;
				    case 'UTF32':
				        // 32ビット符号なし整数値配列と見なす
				        array = new Uint32Array(e.target.result);
				        break;
				    }

				    // Unicodeの数値配列に変換
				    var unicodeArray = Encoding.convert(array, 'UNICODE');
				    // Unicodeの数値配列を文字列に変換
				    var text = Encoding.codeToString(unicodeArray);
			    //テキストエリアに表示する
				$(".minutes-editor-title").val(file[0].name);
			    $("#minutes-textarea").val(text);
			  }
			},false);

	}

	Editor.prototype.clickFilebtn_ = function(e) {
		var target = e.target;
		if($(target).hasClass("new-dummy")){
			$("#new-selfile").click();
		}
		else{
		$("#selfile").click();
		}
	}
	Editor.prototype.clickSaveBtn_ = function(e) {
		var textData = this.inputTextData_(textData);
	}
	Editor.prototype.beforUnloadEvent_ = function(){

	}

	Editor.prototype.uploadEvent_ = function(){

	}
	Editor.prototype.enterDocument();

}(jQuery));
<commit_msg>refs #0000<commit_after>(function($) {

	Editor = function() {
		this.$element_;
		inst = inst || {};
		this.events_ = [];
		this.enterDocument();

	};

	Editor.EventType = {
		EDITOR : 'editor'
	};

	Editor.prototype.getElement = function() {
		return this.$element_;
	};

	Editor.prototype.enterDocument = function() {
		sessionStorage.clear();
		this.$element_ = $(".contents-root");
		this.bindEvents_();
	}

	Editor.prototype.exitDocument = function() {
		if (!this.$element_) {
			return;
		}
		if (this.events_.length > 0) {
			$.each(this.events_, function(idx, args) {
				this.$element_.off.apply(this.$element_, args);
			}.bind(this));
			this.events_ = [];
		}
		this.unbindEvents_();
		this.$element_ = null;
	}

	Editor.prototype.bindEvents_ = function() {
		this.$element_.on('click', '.text-strage-btn', this.saveModal_.bind(this));
		this.$element_.on('keydown', this.keydownFunction_.bind(this));
		this.$element_.on('click', '.reading-btn',this.readingText_.bind(this));
		this.$element_.on('click', '.dummy-file-btn',this.clickFilebtn_.bind(this));
		this.$element_.on('click', '.save-file-btn',this.clickSaveBtn_.bind(this));
		this.$element_.on('beforeunload',this.beforUnloadEvent_.bind(this));
		this.$element_.on('click','.upload-minutes',this.uploadEvent_.bind(this));
	}

	Editor.prototype.keydownFunction_ = function(e) {
		var target = e.target;
		if (e.ctrlKey === true && e.keyCode === 83) {
			event.preventDefault();
			var textData = this.inputTextData_(textData);

		} else if (e.ctrlKey === true) {

		} else {
			$(window).on('beforeunload', function(e) {
				return 'jquery beforeunload';
			});
		}
	}

	Editor.prototype.inputTextData_ = function(textData) {
		var title = $(".minutes-editor-title").val()
		var text = $("#minutes-textarea").val()
		text = text.split("<").join("<");
		text = text.split(">").join(">");
		text = text.split("\n").join("\r\n");
		textData = {
			text : text,
			title : title
		}
		var confirmed = false
		this.checkData(textData);
	}

	Editor.prototype.checkData = function(textData, confirmed) {
		var status = null;
		if (confirmed === true) {
			this.saveTextData_(textData);
		} else {

			if (textData.title === "" && textData.text === "") {
				status = "both";
				this.showConfirmDialog_(textData, status);
				event.stopPropagation();
			}
			else if(textData.title === ""){
				status = "title";
				this.showConfirmDialog_(textData, status);
				event.stopPropagation();
			}
			else if(textData.text === ""){
				status = "text"
				this.showConfirmDialog_(textData, status);
				event.stopPropagation();
			}
			else {
				this.saveTextData_(textData);
			}
		}
	}

	Editor.prototype.saveTextData_ = function(textData) {
		if (textData === undefined) {
			textData = {
				text : "",
				title : "無題"
			}

		}
		else if (textData.title === "") {
			textData = {
				text : textData.text,
				title : "無題"
			}

		}

		var blob = new Blob([ textData.text ], {
			type : "text/plain"
		});
		var a = document.createElement("a");
		a.href = URL.createObjectURL(blob);
		a.target = '_blank';
		a.download = textData.title;
		a.click();
		event.stopPropagation();
	}

	Editor.prototype.showConfirmDialog_ = function(textData, status) {
		$('#staticModal').modal('show');
		if(status === "both"){
			$(".confirm-text").text("何も入力されていませんがよろしいでしょうか？")
		}
		else if(status === "title"){
			$(".confirm-text").text("タイトルが入力されていませんが保存してもいいでしょうか？")

		}
		else if(status === "text"){

			$(".confirm-text").text("本文が入力されていませんが保存してもいいでしょうか？")
		}

		var strage = document.getElementById("text-strage-btn");
		$("#text-strage-btn").unbind('click')
		$("#text-strage-btn").bind('click',function(){
			Editor.prototype.saveModal_(textData);
		})
	}
	Editor.prototype.saveModal_ = function(textData) {
		$('#staticModal').modal('hide');
		window.alert("保存しました");
		this.saveTextData_(textData);
		 $(window).off('beforeunload');
	}

	Editor.prototype.validateText_ = function(data) {
		var lastPart = null;
		var lastDetail = null;
		var lastDetailTwo = null;
		var lastType = null;
		var lastValidate = null;
		var lastLineNum = null;
		var count = 0
		this.initializeAlertarea_();
		var lineNum = 1;
		var i = 0

		while (i <data.length) {

			var part = data[i].pos;
			var word = data[i].surface_form;
			var detail = data[i].pos_detail_1;
			var detailTwo = data[i].pos_detail_2;
			var type = data[i].word_type;
			var position = data[i].ward_position;

			if (type === 'UNKNOWN') {
				if (part === '記号') {
					if(word.match(/\r\n|\n/g)){
						var num = word.match(/\r\n|\n/g).length;
						lineNum = lineNum + num ;
					}
				}
				else if(word.match("-")){

				}
				else if(!isNaN(word)){

				}
				else {
					//if(lastType !== 'UNKNOWN'){
					//$(".alert-list").append('
辞書に登録されていない文字です。' + lineNum  +  "行目" +  '
')
					//$(".minutes-lines").eq(lineNum-1).addClass("yellow");
					//}
				}

			} else if (type == 'KNOWN') {
				if (part === '記号') {

					if (detail === 'アルファベット') {
						$(".alert-list").append('
アルファベットが含まれています。' + lineNum  +  "行目" +  '
')
						$(".minutes-lines").eq(lineNum-1).addClass("yellow");
					} else if (detail === '句点') {
					if (lastDetail === '句点' || lastDetail === '人名') {
						$(".alert-list").append('
句点の位置がおかしい可能性があります。' + lineNum  +  "行目" +  '
')
						$(".minutes-lines").eq(lineNum-1).addClass("yellow");
					}
				} else if (part === '動詞') {
					if (lastPart === "動詞") {
//						$(".alert-list").append('
動詞が続いています。' + lineNum  +  "行目" +  '
')
//					} else if (detail === '非自立') {
//						if (lastPart === '名詞') {
//							$(".alert-list").append(
//									'
名詞の後に非自立品詞が入っています。' + lineNum  +  "行目" +  '
')
//						}
					}
					else if(lastDetailTwo === '人名'){
						$(".alert-list").append(
							'
動詞の位置がおかしい可能性があります。' + lineNum  +  "行目" +  '
')
							$(".minutes-lines").eq(lineNum-1).addClass("yellow");
					}

				} else if (part === '名詞') {
					if(detail === '固有名詞'){
						if(detailTwo === '人名'){
							//$(".alert-list").append(
								//	'
人名が含まれています。' + lineNum  +  "行目" +  '
')
						}
					}

				}
			}
			lastType = type;
			lastPart = part;
			lastDetail = detail;
			lastDetailTwo = detailTwo;
			lastLineNum = lineNum;
			i=(i+1)|0

		}
	}

	Editor.prototype.getStorageItem_ = function(count){
		var allData = JSON.parse(sessionStorage.getItem(count + "allData"))
		if(allData == null){
			if(count== 0){
				return 1;
			}
			else{

			return ;
			}
		}
		count++;
		this.getStorageItem_(count);
	}

	Editor.prototype.initializeAlertarea_ = function() {
		$(".alert-list").children("li").remove();
		$("#minutes-textarea").parents(".editor-field").find(".lineno").addClass("minutes-lines")

		$(".minutes-lines").removeClass("yellow");
	}

	Editor.prototype.readingText_ = function(){

		var filebtn = document.getElementById("selfile");
		var newFilebtn = document.getElementById("new-selfile");

		//ダイアログでファイルが選択された時
		filebtn.addEventListener("change",function(evt){

		  var file = evt.target.files;

		  //FileReaderの作成
		  var reader = new FileReader();

		    reader.readAsArrayBuffer(file[0]);

		  //読込終了後の処理
		  reader.onload = function(ev){
			    var array = new Uint8Array(reader.result);

			    // 文字コードを取得
			    switch (Encoding.detect(array)) {
			    case 'UTF16':
			        // 16ビット符号なし整数値配列と見なす
			        array = new Uint16Array(e.target.result);
			        break;
			    case 'UTF32':
			        // 32ビット符号なし整数値配列と見なす
			        array = new Uint32Array(e.target.result);
			        break;
			    }

			    // Unicodeの数値配列に変換
			    var unicodeArray = Encoding.convert(array, 'UNICODE');
			    // Unicodeの数値配列を文字列に変換
			    var text = Encoding.codeToString(unicodeArray);

		    //テキストエリアに表示する
			$(".origin-editor-title").val(file[0].name);
		    document.test.txt.value = text;
		  }
		},false);

		newFilebtn.addEventListener("change",function(evt){

			  var file = evt.target.files;

			  //FileReaderの作成
			  var reader = new FileReader();
			  //テキスト形式で読み込む
			   reader.readAsArrayBuffer(file[0]);

			  //読込終了後の処理
			  reader.onload = function(ev){
				  var array = new Uint8Array(reader.result);

				    // 文字コードを取得
				    switch (Encoding.detect(array)) {
				    case 'UTF16':
				        // 16ビット符号なし整数値配列と見なす
				        array = new Uint16Array(e.target.result);
				        break;
				    case 'UTF32':
				        // 32ビット符号なし整数値配列と見なす
				        array = new Uint32Array(e.target.result);
				        break;
				    }

				    // Unicodeの数値配列に変換
				    var unicodeArray = Encoding.convert(array, 'UNICODE');
				    // Unicodeの数値配列を文字列に変換
				    var text = Encoding.codeToString(unicodeArray);
			    //テキストエリアに表示する
				$(".minutes-editor-title").val(file[0].name);
			    $("#minutes-textarea").val(text);
			  }
			},false);

	}

	Editor.prototype.clickFilebtn_ = function(e) {
		var target = e.target;
		if($(target).hasClass("new-dummy")){
			$("#new-selfile").click();
		}
		else{
		$("#selfile").click();
		}
	}
	Editor.prototype.clickSaveBtn_ = function(e) {
		var textData = this.inputTextData_(textData);
	}
	Editor.prototype.beforUnloadEvent_ = function(){

	}

	Editor.prototype.uploadEvent_ = function(){

	}
	Editor.prototype.enterDocument();

}(jQuery));
<|endoftext|>


<commit_before>#!/usr/bin/env node
var convert = require('../lib/convert');
var loadJSON = require('../lib/load_json');
var extension = require('./extension');

main();

function main() {
    loadJSON('demo.json', function(err, json) {
        if(err) {
            return console.error(err);
        }

        console.log(JSON.stringify(convert(json, extension)));
    });
}

<commit_msg>Fix API demo<commit_after>#!/usr/bin/env node
var convert = require('../lib/convert');
var loadJSON = require('../lib/load_json');
var extension = require('./extension');

main();

function main() {
    loadJSON('demo.json', function(err, json) {
        if(err) {
            return console.error(err);
        }

        console.log(JSON.stringify(convert(json, {}, extension)));
    });
}

<|endoftext|>


<commit_before>import React from 'react';
import separate from './separate';

export default class Snippet {
  constructor(props) {
    this.key = getUniqueId();
    this.props = Object.freeze(props);
    this._separate = separate(props.name);
  }

  get text() {
    return this.props.body;
  }

  get prefix() {
    return this.props.prefix;
  }

  get description() {
    return this.props.description;
  }

  get leftLabel() {
    const { leftLabel, leftLabelHTML } = this.props;
    if (!this._leftLabel) {
      if (leftLabelHTML) {
        this._leftLabel = parseElement(leftLabelHTML);
      } else {
        this._leftLabel = leftLabel || null;
      }
    }
    return this._leftLabel;
  }

  get rightLabel() {
    const { rightLabel, rightLabelHTML } = this.props;
    if (!this._rightLabel) {
      if (rightLabelHTML) {
        this._rightLabel = parseElement(rightLabelHTML);
      } else {
        this._rightLabel = rightLabel || null;
      }
    }
    return this._rightLabel;
  }

  get plane() {
    return this._separate.plane;
  }

  renderLeftLabel(findFile) {
    if (React.isValidElement(this.leftLabel) && this.leftLabel.props.src) {
      const file = findFile(this.leftLabel.props.src);
      if (file) {
        return React.cloneElement(this.leftLabel, {
          src: file.blobURL,
        });
      }
    }
    return this.leftLabel;
  }

  renderRightLabel(findFile) {
    if (React.isValidElement(this.rightLabel) && this.rightLabel.props.src) {
      const file = findFile(this.rightLabel.props.src);
      if (file) {
        return React.cloneElement(this.rightLabel, {
          src: file.blobURL,
        });
      }
    }
    return this.rightLabel;
  }

  test(tokenString) {
    const prefix = this.props.prefix.toLowerCase();
    return prefix.indexOf(tokenString.toLowerCase()) === 0;
  }

  render(element, self, data) {
    element.textContent = this.props.prefix + ' ' + this.props.description;
    return element;
  }

  hint(instance, self, data) {
    const { from, to } = self;
    instance.replaceRange(data.text, from, to, 'complete');

    const length = data.text.split('\n').length;
    Array.from({ length }).forEach((v, i) => instance.indentLine(i + self.from.line));
  }

}

const getUniqueId = ((id) => () => 'Snippet__' + ++id)(0);

const parseElement = (html) => {
  const span = document.createElement('span');
  span.innerHTML = html;
  const { tagName, attributes } = span.firstChild;
  const props = Array.from(attributes)
    .map((attr) => ({ [attr.name]: attr.value }))
    .reduce((p, c) => Object.assign(p, c), {});
  return React.createElement(tagName, props);
};
<commit_msg>bug fixes<commit_after>import React from 'react';
import separate from './separate';

export default class Snippet {
  constructor(props) {
    this.key = getUniqueId();
    this.props = Object.freeze(props);
    this._separate = separate(props.name);
  }

  get text() {
    return this.props.body;
  }

  get prefix() {
    return this.props.prefix || '';
  }

  get description() {
    return this.props.description;
  }

  get leftLabel() {
    const { leftLabel, leftLabelHTML } = this.props;
    if (!this._leftLabel) {
      if (leftLabelHTML) {
        this._leftLabel = parseElement(leftLabelHTML);
      } else {
        this._leftLabel = leftLabel || null;
      }
    }
    return this._leftLabel;
  }

  get rightLabel() {
    const { rightLabel, rightLabelHTML } = this.props;
    if (!this._rightLabel) {
      if (rightLabelHTML) {
        this._rightLabel = parseElement(rightLabelHTML);
      } else {
        this._rightLabel = rightLabel || null;
      }
    }
    return this._rightLabel;
  }

  get plane() {
    return this._separate.plane;
  }

  renderLeftLabel(findFile) {
    if (React.isValidElement(this.leftLabel) && this.leftLabel.props.src) {
      const file = findFile(this.leftLabel.props.src);
      if (file) {
        return React.cloneElement(this.leftLabel, {
          src: file.blobURL,
        });
      }
    }
    return this.leftLabel;
  }

  renderRightLabel(findFile) {
    if (React.isValidElement(this.rightLabel) && this.rightLabel.props.src) {
      const file = findFile(this.rightLabel.props.src);
      if (file) {
        return React.cloneElement(this.rightLabel, {
          src: file.blobURL,
        });
      }
    }
    return this.rightLabel;
  }

  test(tokenString) {
    const prefix = this.props.prefix.toLowerCase();
    return prefix.indexOf(tokenString.toLowerCase()) === 0;
  }

  render(element, self, data) {
    element.textContent = this.props.prefix + ' ' + this.props.description;
    return element;
  }

  hint(instance, self, data) {
    const { from, to } = self;
    instance.replaceRange(data.text, from, to, 'complete');

    const length = data.text.split('\n').length;
    Array.from({ length }).forEach((v, i) => instance.indentLine(i + self.from.line));
  }

}

const getUniqueId = ((id) => () => 'Snippet__' + ++id)(0);

const parseElement = (html) => {
  const span = document.createElement('span');
  span.innerHTML = html;
  if (span.firstChild) {
    const { tagName, attributes } = span.firstChild;
    const props = Array.from(attributes)
      .map((attr) => ({ [attr.name]: attr.value }))
      .reduce((p, c) => Object.assign(p, c), {});
    return React.createElement(tagName, props);
  }
  return null;
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import styles from './circleprogressbar.scss';
import settings from 'settings';
import ProgressBar from 'progressbar.js';

const CircleProgressBar = React.createClass({

  getDefaultProps () {
    return {
      percentage: 0,
      animated: false,
      size: 'small',
      color: settings.colors.primary,
      trailColor: settings.colors.greyLite,
      aria: {}
    };
  },

  componentDidMount () {
    this.initProgressBar();
    this.updateProgressBar(this.props.percentage);
  },

  initProgressBar () {
    const canvasElement = ReactDOM.findDOMNode(this.refs.canvas);

    this.progressBar = new ProgressBar.Circle(canvasElement, {
      strokeWidth: 10,
      easing: 'easeInOut',
      duration: 800,
      color: this.props.color,
      trailColor: this.props.trailColor,
      trailWidth: 10,
      svgStyle: {
        width: '100%',
        display: 'block',
        strokeLinecap: 'round'
      }
    });
  },

  updateProgressBar (percentage) {
    const progress = percentage / 100;

    if (this.props.animated) {
      this.progressBar.animate(progress);
    } else {
      this.progressBar.set(progress);
    }
  },

  render () {
    return (

          {this.props.children}

    );
  }
});

export default CircleProgressBar;

<commit_msg>improve CircleProgressbar component based on PR feedback<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import styles from './circleprogressbar.scss';
import settings from 'settings';
import ProgressBar from 'progressbar.js';

const CircleProgressBar = React.createClass({

  getDefaultProps: () => ({
    percentage: 0,
    animated: false,
    size: 'small',
    color: settings.colors.primary,
    trailColor: settings.colors.greyLite,
    aria: {}
  }),

  componentDidMount () {
    this.initProgressBar();
    this.updateProgressBar(this.props.percentage);
  },

  initProgressBar () {
    const canvasElement = ReactDOM.findDOMNode(this.refs.canvas);

    this.progressBar = new ProgressBar.Circle(canvasElement, {
      strokeWidth: 10,
      easing: 'easeInOut',
      duration: 800,
      color: this.props.color,
      trailColor: this.props.trailColor,
      trailWidth: 10,
      svgStyle: {
        width: '100%',
        display: 'block',
        strokeLinecap: 'round'
      }
    });
  },

  updateProgressBar (percentage) {
    const progress = percentage / 100;

    if (this.props.animated) {
      this.progressBar.animate(progress);
    } else {
      this.progressBar.set(progress);
    }
  },

  render () {
    return (

          {this.props.children}

    );
  }
});

export default CircleProgressBar;

<|endoftext|>


<commit_before>import React from 'react';

import Template from '../Template.js';
import PriceRangesForm from './PriceRangesForm.js';
import cx from 'classnames';
import isEqual from 'lodash/isEqual';

import autoHideContainerHOC from '../../decorators/autoHideContainer.js';
import headerFooterHOC from '../../decorators/headerFooter.js';

export class RawPriceRanges extends React.Component {
  componentWillMount() {
    this.refine = this.refine.bind(this);
  }

  shouldComponentUpdate(nextProps) {
    return !isEqual(this.props.facetValues, nextProps.facetValues);
  }

  getForm() {
    const labels = {
      currency: this.props.currency,
      ...this.props.labels,
    };

    let currentRefinement;
    if (this.props.facetValues.length === 1) {
      currentRefinement = {
        from: this.props.facetValues[0].from !== undefined ? this.props.facetValues[0].from : '',
        to: this.props.facetValues[0].to !== undefined ? this.props.facetValues[0].to : '',
      };
    } else {
      currentRefinement = {from: '', to: ''};
    }

    return (
      <PriceRangesForm
        cssClasses={this.props.cssClasses}
        currentRefinement={currentRefinement}
        labels={labels}
        refine={this.refine}
      />
    );
  }

  getItemFromFacetValue(facetValue) {
    const cssClassItem = cx(
      this.props.cssClasses.item,
      {[this.props.cssClasses.active]: facetValue.isRefined}
    );
    const key = `${facetValue.from}_${facetValue.to}`;
    const handleClick = this.refine.bind(this, {from: facetValue.from, to: facetValue.to});
    const data = {
      currency: this.props.currency,
      ...facetValue,
    };
    return (

          <Template data={data} templateKey="item" {...this.props.templateProps} />

    );
  }

  refine(from, to, event) {
    event.preventDefault();
    this.props.refine({from, to});
  }

  render() {
    return (

          {this.props.facetValues.map(facetValue => this.getItemFromFacetValue(facetValue))}

        {this.getForm()}

    );
  }
}

RawPriceRanges.propTypes = {
  cssClasses: React.PropTypes.shape({
    active: React.PropTypes.string,
    button: React.PropTypes.string,
    form: React.PropTypes.string,
    input: React.PropTypes.string,
    item: React.PropTypes.string,
    label: React.PropTypes.string,
    link: React.PropTypes.string,
    list: React.PropTypes.string,
    separator: React.PropTypes.string,
  }),
  currency: React.PropTypes.string,
  facetValues: React.PropTypes.array,
  labels: React.PropTypes.shape({
    button: React.PropTypes.string,
    to: React.PropTypes.string,
  }),
  refine: React.PropTypes.func.isRequired,
  templateProps: React.PropTypes.object.isRequired,
};

RawPriceRanges.defaultProps = {
  cssClasses: {},
};

export default autoHideContainerHOC(headerFooterHOC(RawPriceRanges));
<commit_msg>fix(price-ranges): New API uses ranges<commit_after>import React from 'react';

import Template from '../Template.js';
import PriceRangesForm from './PriceRangesForm.js';
import cx from 'classnames';
import isEqual from 'lodash/isEqual';

import autoHideContainerHOC from '../../decorators/autoHideContainer.js';
import headerFooterHOC from '../../decorators/headerFooter.js';

export class RawPriceRanges extends React.Component {
  componentWillMount() {
    this.refine = this.refine.bind(this);
  }

  shouldComponentUpdate(nextProps) {
    return !isEqual(this.props.facetValues, nextProps.facetValues);
  }

  getForm() {
    const labels = {
      currency: this.props.currency,
      ...this.props.labels,
    };

    let currentRefinement;
    if (this.props.facetValues.length === 1) {
      currentRefinement = {
        from: this.props.facetValues[0].from !== undefined ? this.props.facetValues[0].from : '',
        to: this.props.facetValues[0].to !== undefined ? this.props.facetValues[0].to : '',
      };
    } else {
      currentRefinement = {from: '', to: ''};
    }

    return (
      <PriceRangesForm
        cssClasses={this.props.cssClasses}
        currentRefinement={currentRefinement}
        labels={labels}
        refine={this.refine}
      />
    );
  }

  getItemFromFacetValue(facetValue) {
    const cssClassItem = cx(
      this.props.cssClasses.item,
      {[this.props.cssClasses.active]: facetValue.isRefined}
    );
    const key = `${facetValue.from}_${facetValue.to}`;
    const handleClick = this.refine.bind(this, facetValue);
    const data = {
      currency: this.props.currency,
      ...facetValue,
    };
    return (

          <Template data={data} templateKey="item" {...this.props.templateProps} />

    );
  }

  refine(range, event) {
    event.preventDefault();
    this.props.refine(range);
  }

  render() {
    return (

          {this.props.facetValues.map(facetValue => this.getItemFromFacetValue(facetValue))}

        {this.getForm()}

    );
  }
}

RawPriceRanges.propTypes = {
  cssClasses: React.PropTypes.shape({
    active: React.PropTypes.string,
    button: React.PropTypes.string,
    form: React.PropTypes.string,
    input: React.PropTypes.string,
    item: React.PropTypes.string,
    label: React.PropTypes.string,
    link: React.PropTypes.string,
    list: React.PropTypes.string,
    separator: React.PropTypes.string,
  }),
  currency: React.PropTypes.string,
  facetValues: React.PropTypes.array,
  labels: React.PropTypes.shape({
    button: React.PropTypes.string,
    to: React.PropTypes.string,
  }),
  refine: React.PropTypes.func.isRequired,
  templateProps: React.PropTypes.object.isRequired,
};

RawPriceRanges.defaultProps = {
  cssClasses: {},
};

export default autoHideContainerHOC(headerFooterHOC(RawPriceRanges));
<|endoftext|>


<commit_before><commit_msg>Update project vquery to v4.2.1<commit_after><|endoftext|>


<commit_before>(function() {
	var ThreeMeshPlugin = E2.plugins.three_mesh = function(core) {
		ThreeObject3DPlugin.apply(this, arguments)

		this.desc = 'THREE.js Mesh'

		this.input_slots = [
			{
				name: 'geometry',
				dt: core.datatypes.GEOMETRY,
				array: true,
				def: [new THREE.Geometry()]
			},
			{
				name: 'material',
				dt: core.datatypes.MATERIAL,
				array: true,
				def: [new THREE.MeshBasicMaterial({color: 0x00FF00})]
			}
		].concat(this.input_slots)
	}

	ThreeMeshPlugin.prototype = Object.create(ThreeObject3DPlugin.prototype)

	ThreeMeshPlugin.prototype.reset = function() {
		ThreeObject3DPlugin.prototype.reset.apply(this)

		this.object3d = new THREE.Object3D()

		this.geoms = [new THREE.Geometry()]
		this.mats = [new THREE.MeshBasicMaterial({color: 0x00ff00})]

		var mesh = new THREE.Mesh(this.geoms[0], this.mats[0])
		this.object3d.add(mesh)

		// back reference for object picking
		this.object3d.backReference = this
	}

	ThreeMeshPlugin.prototype.update_mesh = function()
	{
		var i
		var mesh

		// tbd: optimize this so that we don't always reconstruct meshes
		// but update the ones we can just update
		if (this.geoms_dirty && this.geoms) {
			this.always_update = false
			this.object3d = new THREE.Object3D()

			for (i = 0; i < this.geoms.length; ++i) {
				if (this.geoms[i].morphTargets && this.geoms[i].morphTargets.length > 0) {
					// clone the material, because we don't want to edit properties on some random material
					var mat = (this.mats && this.mats.length > 0) ? this.mats[i % this.mats.length].clone() : undefined
					mesh = new THREE.MorphAnimMesh(this.geoms[i], mat)
					mesh.material.morphTargets = true
					this.always_update = true
				}
				else {
					mesh = new THREE.Mesh(this.geoms[i], this.mats[i % this.mats.length])
				}
				mesh.backReference = this

				this.object3d.add(mesh)
			}

			this.geoms_dirty = this.mats_dirty = false
		}

		if (this.mats_dirty && this.mats && this.mats.length > 0) {
			for (i = 0; i < this.object3d.children.length; ++i) {
				if (this.object3d.children[i] instanceof THREE.MorphAnimMesh) {
					this.object3d.children[i].material = this.mats[i % this.mats.length].clone()
					this.object3d.children[i].material.morphTargets = true
				}
				else {
					this.object3d.children[i].material = this.mats[i % this.mats.length]
				}
			}

			this.mats_dirty = false
		}
	}

	ThreeMeshPlugin.prototype.update_input = function(slot, data) {
		if (slot.index === 0) { // geometry
			this.geoms = data
			this.geoms_dirty = true
		}
		else if (slot.index === 1) { // material
			this.mats = data
			this.mats_dirty = true
		}
		else {
			ThreeObject3DPlugin.prototype.update_input.apply(this, arguments)
		}
	}

	ThreeMeshPlugin.prototype.update_state = function() {
		this.update_mesh()

		var delta = this.core.delta_t
		for(var i = 0; i < this.object3d.children.length; ++i) {
			if (this.object3d.children[i] instanceof THREE.MorphAnimMesh) {
				this.object3d.children[i].updateAnimation(delta * 1000)
			}
		}
	}

})()

<commit_msg>fix a bug where model root transformation was overridden (position, rotation etc set first but the mesh root reconstructed afterwards overwriting the good transform values)<commit_after>(function() {
	var ThreeMeshPlugin = E2.plugins.three_mesh = function(core) {
		ThreeObject3DPlugin.apply(this, arguments)

		this.desc = 'THREE.js Mesh'

		this.input_slots = [
			{
				name: 'geometry',
				dt: core.datatypes.GEOMETRY,
				array: true,
				def: [new THREE.Geometry()]
			},
			{
				name: 'material',
				dt: core.datatypes.MATERIAL,
				array: true,
				def: [new THREE.MeshBasicMaterial({color: 0x00FF00})]
			}
		].concat(this.input_slots)
	}

	ThreeMeshPlugin.prototype = Object.create(ThreeObject3DPlugin.prototype)

	ThreeMeshPlugin.prototype.reset = function() {
		ThreeObject3DPlugin.prototype.reset.apply(this)

		this.object3d = new THREE.Object3D()

		this.geoms = [new THREE.Geometry()]
		this.mats = [new THREE.MeshBasicMaterial({color: 0x00ff00})]

		var mesh = new THREE.Mesh(this.geoms[0], this.mats[0])
		this.object3d.add(mesh)

		// back reference for object picking
		this.object3d.backReference = this
	}

	ThreeMeshPlugin.prototype.update_mesh = function()
	{
		var i
		var mesh

		// tbd: optimize this so that we don't always reconstruct meshes
		// but update the ones we can just update
		if (this.geoms_dirty && this.geoms) {
			this.always_update = false

			// non-recursive clone of the root, preserve transform
			this.object3d = this.object3d.clone(/*recursive = */false)

			for (i = 0; i < this.geoms.length; ++i) {
				if (this.geoms[i].morphTargets && this.geoms[i].morphTargets.length > 0) {
					// clone the material, because we don't want to edit properties on some random material
					var mat = (this.mats && this.mats.length > 0) ? this.mats[i % this.mats.length].clone() : undefined
					mesh = new THREE.MorphAnimMesh(this.geoms[i], mat)
					mesh.material.morphTargets = true
					this.always_update = true
				}
				else {
					mesh = new THREE.Mesh(this.geoms[i], this.mats[i % this.mats.length])
				}
				mesh.backReference = this

				this.object3d.add(mesh)
			}

			this.geoms_dirty = this.mats_dirty = false
		}

		if (this.mats_dirty && this.mats && this.mats.length > 0) {
			for (i = 0; i < this.object3d.children.length; ++i) {
				if (this.object3d.children[i] instanceof THREE.MorphAnimMesh) {
					this.object3d.children[i].material = this.mats[i % this.mats.length].clone()
					this.object3d.children[i].material.morphTargets = true
				}
				else {
					this.object3d.children[i].material = this.mats[i % this.mats.length]
				}
			}

			this.mats_dirty = false
		}
	}

	ThreeMeshPlugin.prototype.update_input = function(slot, data) {
		if (slot.index === 0) { // geometry
			this.geoms = data
			this.geoms_dirty = true
		}
		else if (slot.index === 1) { // material
			this.mats = data
			this.mats_dirty = true
		}
		else {
			ThreeObject3DPlugin.prototype.update_input.apply(this, arguments)
		}
	}

	ThreeMeshPlugin.prototype.update_state = function() {
		this.update_mesh()

		var delta = this.core.delta_t
		for(var i = 0; i < this.object3d.children.length; ++i) {
			if (this.object3d.children[i] instanceof THREE.MorphAnimMesh) {
				this.object3d.children[i].updateAnimation(delta * 1000)
			}
		}
	}

})()

<|endoftext|>


<commit_before>(function() {
  var firstPaint,
    timing = window.performance.timing;

  if (window.chrome && window.chrome.loadTimes) {
    var loadTimes = window.chrome.loadTimes();
    firstPaint = (loadTimes.firstPaintTime - loadTimes.requestTime) * 1000;

    if (firstPaint > 0) {
      return Number(firstPaint.toFixed(0));
    }
  } else if (typeof timing.msFirstPaint === 'number') {
    firstPaint = timing.msFirstPaint - timing.navigationStart;

    if (firstPaint > 0) {
      return firstPaint;
    }
  } else if (timing.timeToNonBlankPaint) {
    return timing.timeToNonBlankPaint - timing.navigationStart;
  }

  return undefined;
})();
<commit_msg>remove soon deprecated loadTimes #417 (#418)<commit_after>(function() {
  var firstPaint,
    p = window.performance,
    timing = p.timing,
    entries = p.getEntriesByType('paint');

    if (entries.length > 0) {
      for (var entry of entries) {
        if (entry.name === 'first-paint')
        return entry.startTime;
      }
     } else if (typeof timing.msFirstPaint === 'number') {
    firstPaint = timing.msFirstPaint - timing.navigationStart;

    if (firstPaint > 0) {
      return firstPaint;
    }
  } else if (timing.timeToNonBlankPaint) {
    return timing.timeToNonBlankPaint - timing.navigationStart;
  }

  return undefined;
})();
<|endoftext|>


<commit_before>var update = {
    player : null,
    enemyTimer: null,
    status: null,
    score: 0 ,

    update : function(){
        // fazer o angulo apontar para baixo quando o jogador n������o esta pulando
        if(this.player.angle < 20){
            this.player.angle += 1;
        }
        if(this.player.x > game.world.bounds.height){
            // no need to fall anymore
            this.player.body.gravity.y = 0;
        }
        update.collisionEnemyGroup();
        game.physics.arcade.overlap(this.player, create.enemy_group, update.collisionEnemyGroup);
        update.collisionFloor();
        if(this.player.y < 200) this.player.y = 200;

        var style = { font: "40px helvetica", fill: "#ffffff" };
        this.score = game.add.text(20, 20, "Pontos:" + create.score, style);

    },
    collisionEnemyGroup : function(player, enemy){
        if(player && player.alive){
            var style = { font: "40px helvetica", fill: "#000000" };
            if(enemy.enemyType === 'ariranha'){
                update.status = game.add.text(100, 400, "Pressione R para reiniciar", style);
                player.destroy();
                enemy.animations.stop();
                enemy.frame = 2;
            }
            else if(enemy.enemyType === 'barco') {
                update.status = game.add.text(100, 400, "Pressione R para reiniciar", style);
                player.destroy();
                enemy.animations.stop();
                enemy.frame = 2;
            }
            else {
                update.status = game.add.text(100, 400, "Pressione R para reiniciar", style);
                player.alive = false;
                player.animations.play('shock');
                player.body.gravity.y = 500;
                player.body.velocity.y = 0;
            }
        }
    },
    collisionFloor : function(){
        if (this.player.alive && this.player.y > game.world.bounds.height){
            var style = { font: "40px helvetica", fill: "#000000" };
            this.status = game.add.text(100, 400, "Pressione R para reiniciar", style);
            this.player.alive = false;
            this.player.animations.stop();
            this.player.frame = 4;
            this.player.body.velocity.y = 0;
        }
    }
};
<commit_msg> ajustes pontuacao<commit_after>var update = {
    player : null,
    enemyTimer: null,
    status: null,
    score: 0 ,

    update : function(){
        // fazer o angulo apontar para baixo quando o jogador n������o esta pulando
        if(this.player.angle < 20){
            this.player.angle += 1;
        }
        if(this.player.x > game.world.bounds.height){
            // no need to fall anymore
            this.player.body.gravity.y = 0;
        }
        update.collisionEnemyGroup();
        game.physics.arcade.overlap(this.player, create.enemy_group, update.collisionEnemyGroup);
        update.collisionFloor();
        if(this.player.y < 200) this.player.y = 200;

        var style = { font: "40px helvetica", fill: "#ffffff" };
        this.score = game.add.text(20, 20, "Pontos:" + create.score, style);

    },
    collisionEnemyGroup : function(player, enemy){
        if(player && player.alive){
            var style = { font: "40px helvetica", fill: "#ffffff" };
            if(enemy.enemyType === 'ariranha'){
                update.status = game.add.text(100, 400, "Pressione R para reiniciar", style);
                player.destroy();
                enemy.animations.stop();
                enemy.frame = 2;
            }
            else if(enemy.enemyType === 'barco') {
                update.status = game.add.text(100, 400, "Pressione R para reiniciar", style);
                player.destroy();
                enemy.animations.stop();
                enemy.frame = 2;
            }
            else {
                update.status = game.add.text(100, 400, "Pressione R para reiniciar", style);
                player.alive = false;
                player.animations.play('shock');
                player.body.gravity.y = 500;
                player.body.velocity.y = 0;
            }
        }
    },
    collisionFloor : function(){
        if (this.player.alive && this.player.y > game.world.bounds.height){
            var style = { font: "40px helvetica", fill: "#000000" };
            this.status = game.add.text(100, 400, "Pressione R para reiniciar", style);
            this.player.alive = false;
            this.player.animations.stop();
            this.player.frame = 4;
            this.player.body.velocity.y = 0;
        }
    }
};
<|endoftext|>


<commit_before>// eslint-disable react/jsx-indent rule added for proper <Markdown /> formatting
/* eslint-disable react/jsx-indent */
const React = require('react');
const { Link } = require('react-router');

const { SimpleInput } = require('mx-react-components');

const Code = require('components/Code');
const Markdown = require('components/Markdown');

class SimpleInputDocs extends React.Component {
  render () {
    return (

          Simple Input
          A simple input field used in forms

Demo

            My Simple Input

        <SimpleInput
          elementProps={{
            id: 'inputOne',
            placeholder: 'Type something'
          }}
        />

            My Simple Input with prefix and suffix

        <SimpleInput
          elementProps={{
            id: 'inputTwo',
            placeholder: 'Type something'
          }}
          elementRef={ref => this.myInput = ref}
          prefix={( this.myInput.focus()} style={{ paddingRight: 5 }}>Prefix)}
          suffix={( this.myInput.focus()} style={{ paddingRight: 5 }}>Suffix)}
        />

Usage

baseColor String

The color of the input border on focus.

*This prop is deprecated, please use themes instead.

elementProps Object

Pass props directly to the input element. ie. placeholder, value, onchange, etc.

elementRefFunction

A callback function used to get the ref of the input for things like handling focus.

focusOnLoad Boolean

Focus input on load, default of false.

handleResetClick Function

The function that will execute when rightIcon is clicked. This prop will not work properly unless rightIcon is also declared.

*This prop is deprecated, please use prefix by passing an element with a click handler instead.

icon String || Object

The type of icon as a string or an object describing the props passed to the Icon component to display on the left side of the input

*This prop is deprecated, please use prefix instead.

prefix Node

Anything that can be rendered: numbers, strings, elements or an array(or fragment) containing these types that is placed on the left side of the input.

rightIcon String || Object

The type of icon as a string or an object describing the props passed to the Icon component to display on the right side of the input

*This prop is deprecated, please use suffix instead.

styles Object

Allows style additions or overrides to specific component elements including:

wrapper: the outermost element of the component.

activeWrapper: the outermost element of the component when active.

input: the component's input element.

icon: the icon located in the left side of the input element.

rightIcon: the icon located in the right side of the input element.

*styles will override defaults and conflicting themes

suffix Node

Anything that can be rendered: numbers, strings, elements or an array(or fragment) containing these types that is placed on the right side of the input.

theme Object

Customize the component's look. See <Link to='/components/theme'>Theme</Link> for more information. Themes will be overridden by conflicting styles

type String

Specifies the input type. Default type is text.

valid Boolean

Indicates whether the value of Input field is valid. If it is not valid, the input field will have a red border.

Example

        <Markdown>
          {`
          <SimpleInput
            baseColor={'red'}
            elementProps={{
              placeholder: 'Type something'
            }}
            elementRef={ref => this.myInput = ref}
            focusOnLoad={true}
            handleResetClick={myRightIconClickCallbackFunction}
            icon={'bike'}
            prefix={( this.myInput.focus()} style={{ paddingRight: 5 }}>Prefix)}
            rightIcon={'close-solid'}
            styles={{
              wrapper: { backgroundColor: 'red', border: '4px solid green' },
              activeWrapper: { backgroundColor: 'blue', border: '4px solid red' },
              input: { color: 'purple' },
              icon: { paddingLeft: '40px' },
              rightIcon: { paddingRight: '40px' }
            }}
            suffix={( this.myInput.focus()} style={{ paddingRight: 5 }}>Suffix)}
            theme={{ Colors: { PRIMARY: 'orange' } }}
            valid={false}
          />
        `}
        </Markdown>

    );
  }
}

module.exports = SimpleInputDocs;
<commit_msg>Update example code<commit_after>// eslint-disable react/jsx-indent rule added for proper <Markdown /> formatting
/* eslint-disable react/jsx-indent */
const React = require('react');
const { Link } = require('react-router');

const { SimpleInput } = require('mx-react-components');

const Code = require('components/Code');
const Markdown = require('components/Markdown');

class SimpleInputDocs extends React.Component {
  render () {
    return (

          Simple Input
          A simple input field used in forms

Demo

            My Simple Input

        <SimpleInput
          elementProps={{
            id: 'inputOne',
            placeholder: 'Type something'
          }}
        />

            My Simple Input with prefix and suffix

        <SimpleInput
          elementProps={{
            id: 'inputTwo',
            placeholder: 'Type something'
          }}
          elementRef={ref => this.myInput = ref}
          prefix={( this.myInput.focus()} style={{ paddingRight: 5 }}>Prefix)}
          suffix={( this.myInput.focus()} style={{ paddingRight: 5 }}>Suffix)}
        />

Usage

baseColor String

The color of the input border on focus.

*This prop is deprecated, please use themes instead.

elementProps Object

Pass props directly to the input element. ie. placeholder, value, onchange, etc.

elementRefFunction

A callback function used to get the ref of the input for things like handling focus.

focusOnLoad Boolean

Focus input on load, default of false.

handleResetClick Function

The function that will execute when rightIcon is clicked. This prop will not work properly unless rightIcon is also declared.

*This prop is deprecated, please use prefix by passing an element with a click handler instead.

icon String || Object

The type of icon as a string or an object describing the props passed to the Icon component to display on the left side of the input

*This prop is deprecated, please use prefix instead.

prefix Node

Anything that can be rendered: numbers, strings, elements or an array(or fragment) containing these types that is placed on the left side of the input.

rightIcon String || Object

The type of icon as a string or an object describing the props passed to the Icon component to display on the right side of the input

*This prop is deprecated, please use suffix instead.

styles Object

Allows style additions or overrides to specific component elements including:

wrapper: the outermost element of the component.

activeWrapper: the outermost element of the component when active.

input: the component's input element.

icon: the icon located in the left side of the input element.

rightIcon: the icon located in the right side of the input element.

*styles will override defaults and conflicting themes

suffix Node

Anything that can be rendered: numbers, strings, elements or an array(or fragment) containing these types that is placed on the right side of the input.

theme Object

Customize the component's look. See <Link to='/components/theme'>Theme</Link> for more information. Themes will be overridden by conflicting styles

type String

Specifies the input type. Default type is text.

valid Boolean

Indicates whether the value of Input field is valid. If it is not valid, the input field will have a red border.

Example

        <Markdown>
          {`
          <SimpleInput
            baseColor={'red'}
            elementProps={{
              placeholder: 'Type something'
            }}
            elementRef={ref => this.myInput = ref}
            focusOnLoad={true}
            prefix={( this.myInput.focus()} style={{ paddingRight: 5 }}>Prefix)}
            styles={{
              wrapper: { backgroundColor: 'red', border: '4px solid green' },
              activeWrapper: { backgroundColor: 'blue', border: '4px solid red' },
              input: { color: 'purple' },
              icon: { paddingLeft: '40px' },
              rightIcon: { paddingRight: '40px' }
            }}
            suffix={( this.myInput.focus()} style={{ paddingRight: 5 }}>Suffix)}
            theme={{ Colors: { PRIMARY: 'orange' } }}
            valid={false}
          />
        `}
        </Markdown>

    );
  }
}

module.exports = SimpleInputDocs;
<|endoftext|>


<commit_before>var _ = require('underscore');
var Backbone = require('backbone');
var LegendDefinitionsCollection = require('../../../../../../../javascripts/cartodb3/data/legends/legend-definitions-collection');
var LayerDefinitionModel = require('../../../../../../../javascripts/cartodb3/data/layer-definition-model');
var LegendFactory = require('../../../../../../../javascripts/cartodb3/editor/layers/layer-content-views/legend/legend-factory');
var ConfigModel = require('../../../../../../../javascripts/cartodb3/data/config-model');

function getSuccessResponse (id, type) {
  var success = _.clone(TestResponses.save.success);
  success.responseText = _.template(success.responseText)({
    id: id,
    type: type
  });

  return success;
}

var TestResponses = {
  save: {
    success: {
      'status': '200',
      'content-type': 'application/json',
      responseText: '{"created_at":"2016-09-30T07:57:15+00:00","id":"<%= id %>","layer_id":"l-1","title":"","type":"<%= type %>","definition": {"color":"#fabada", "prefix":"", "suffix": "" }}'
    }
  },
  destroy: {
    success: {
      status: 204
    }
  }
};

describe('editor/layers/layer-content-view/legend/legend-factory', function () {

  beforeEach(function () {
    jasmine.Ajax.install();

    this.configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.layerDefinitionModel = new LayerDefinitionModel({
      id: 'l-1',
      fetched: true,
      options: {
        type: 'CartoDB',
        table_name: 'foo',
        cartocss: 'asd',
        source: 'a0'
      }
    }, {
      parse: true,
      configModel: this.configModel
    });

    this.layerDefinitionsCollection = new Backbone.Collection();
    this.layerDefinitionsCollection.add(this.layerDefinitionModel);

    this.legendDefinitionsCollection = new LegendDefinitionsCollection([], {
      layerDefinitionsCollection: this.layerDefinitionsCollection,
      configModel: this.configModel,
      vizId: 'v-123'
    });

    LegendFactory.init(this.legendDefinitionsCollection);
  });

  afterEach(function () {
    jasmine.Ajax.uninstall();
  });

  it('create legend', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    expect(this.legendDefinitionsCollection.length).toBe(3);
    expect(this.legendDefinitionsCollection.at(0).get('type')).toBe('bubble');
    expect(this.legendDefinitionsCollection.at(1).get('type')).toBe('choropleth');
    expect(this.legendDefinitionsCollection.at(2).get('type')).toBe('category');
  });

  it('remove legend', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    LegendFactory.removeLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(TestResponses.destroy.success);

    expect(this.legendDefinitionsCollection.length).toBe(2);
    expect(this.legendDefinitionsCollection.at(0).get('type')).toBe('choropleth');
    expect(this.legendDefinitionsCollection.at(1).get('type')).toBe('category');
  });

  it('remove all legends', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    LegendFactory.removeAllLegend(this.layerDefinitionModel);
    expect(this.legendDefinitionsCollection.length).toBe(0);
  });
});
<commit_msg>Lint error.<commit_after>var _ = require('underscore');
var Backbone = require('backbone');
var LegendDefinitionsCollection = require('../../../../../../../javascripts/cartodb3/data/legends/legend-definitions-collection');
var LayerDefinitionModel = require('../../../../../../../javascripts/cartodb3/data/layer-definition-model');
var LegendFactory = require('../../../../../../../javascripts/cartodb3/editor/layers/layer-content-views/legend/legend-factory');
var ConfigModel = require('../../../../../../../javascripts/cartodb3/data/config-model');

function getSuccessResponse (id, type) {
  var success = _.clone(TestResponses.save.success);
  success.responseText = _.template(success.responseText)({
    id: id,
    type: type
  });

  return success;
}

var TestResponses = {
  save: {
    success: {
      'status': '200',
      'content-type': 'application/json',
      responseText: '{"created_at":"2016-09-30T07:57:15+00:00","id":"<%= id %>","layer_id":"l-1","title":"","type":"<%= type %>","definition": {"color":"#fabada", "prefix":"", "suffix": "" }}'
    }
  },
  destroy: {
    success: {
      status: 204
    }
  }
};

describe('editor/layers/layer-content-view/legend/legend-factory', function () {
  beforeEach(function () {
    jasmine.Ajax.install();

    this.configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.layerDefinitionModel = new LayerDefinitionModel({
      id: 'l-1',
      fetched: true,
      options: {
        type: 'CartoDB',
        table_name: 'foo',
        cartocss: 'asd',
        source: 'a0'
      }
    }, {
      parse: true,
      configModel: this.configModel
    });

    this.layerDefinitionsCollection = new Backbone.Collection();
    this.layerDefinitionsCollection.add(this.layerDefinitionModel);

    this.legendDefinitionsCollection = new LegendDefinitionsCollection([], {
      layerDefinitionsCollection: this.layerDefinitionsCollection,
      configModel: this.configModel,
      vizId: 'v-123'
    });

    LegendFactory.init(this.legendDefinitionsCollection);
  });

  afterEach(function () {
    jasmine.Ajax.uninstall();
  });

  it('create legend', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    expect(this.legendDefinitionsCollection.length).toBe(3);
    expect(this.legendDefinitionsCollection.at(0).get('type')).toBe('bubble');
    expect(this.legendDefinitionsCollection.at(1).get('type')).toBe('choropleth');
    expect(this.legendDefinitionsCollection.at(2).get('type')).toBe('category');
  });

  it('remove legend', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    LegendFactory.removeLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(TestResponses.destroy.success);

    expect(this.legendDefinitionsCollection.length).toBe(2);
    expect(this.legendDefinitionsCollection.at(0).get('type')).toBe('choropleth');
    expect(this.legendDefinitionsCollection.at(1).get('type')).toBe('category');
  });

  it('remove all legends', function () {
    LegendFactory.createLegend(this.layerDefinitionModel, 'bubble');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(1, 'bubble'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'choropleth');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(2, 'choropleth'));

    LegendFactory.createLegend(this.layerDefinitionModel, 'category');
    jasmine.Ajax.requests.mostRecent().respondWith(getSuccessResponse(3, 'category'));

    LegendFactory.removeAllLegend(this.layerDefinitionModel);
    expect(this.legendDefinitionsCollection.length).toBe(0);
  });
});
<|endoftext|>


<commit_before>var GeoreferenceOnboardingView = require('./georeference-view');

var GEOREFERENCE_KEY = 'georeference';

var launcher = (function () {
  var onboardings;
  var onboardingNotification;
  var notificationKey;

  function init (opts) {
    if (!onboardings && !opts) {
      throw new Error('onboardings is required');
    }
    if (!onboardingNotification && !opts) {
      throw new Error('onboardingNotification is required');
    }
    if (!notificationKey && !opts) {
      throw new Error('notificationKey is required');
    }

    if (!onboardings && opts && opts.onboardings) {
      onboardings = opts.onboardings;
    }
    if (!onboardingNotification && opts && opts.onboardingNotification) {
      onboardingNotification = opts.onboardingNotification;
    }
    if (!notificationKey && opts && opts.notificationKey) {
      notificationKey = opts.notificationKey;
    }
  }

  return {
    init: function (opts) {
      init(opts);
    },

    launch: function (launchOpts) {
      if (!onboardingNotification.getKey(GEOREFERENCE_KEY)) {
        onboardings.create(function () {
          return new GeoreferenceOnboardingView({
            onboardingNotification: onboardingNotification,
            name: launchOpts.name,
            source: launchOpts.source,
            notificationKey: notificationKey

          });
        });
      }
    }
  };
})();

module.exports = launcher;
<commit_msg>notificationkey<commit_after>var GeoreferenceOnboardingView = require('./georeference-view');

var GEOREFERENCE_KEY = 'georeference';

var launcher = (function () {
  var onboardings;
  var onboardingNotification;

  function init (opts) {
    if (!onboardings && !opts) {
      throw new Error('onboardings is required');
    }
    if (!onboardingNotification && !opts) {
      throw new Error('onboardingNotification is required');
    }

    if (!onboardings && opts && opts.onboardings) {
      onboardings = opts.onboardings;
    }
    if (!onboardingNotification && opts && opts.onboardingNotification) {
      onboardingNotification = opts.onboardingNotification;
    }
  }

  return {
    init: function (opts) {
      init(opts);
    },

    launch: function (launchOpts) {
      if (!onboardingNotification.getKey(GEOREFERENCE_KEY)) {
        onboardings.create(function () {
          return new GeoreferenceOnboardingView({
            onboardingNotification: onboardingNotification,
            name: launchOpts.name,
            source: launchOpts.source,
            notificationKey: GEOREFERENCE_KEY
          });
        });
      }
    }
  };
})();

module.exports = launcher;
<|endoftext|>