<commit_before>function clearField(input) {
  input.value = "";
};

function remove_post(key) {
	var firebase_ref = firebase.database().ref().child("Posts").child(key);
  firebase_ref.child("comments").once('value').then(function(snapshot) {
    // console.log(snapshot.val());
    for (var i in snapshot.val()) {
      firebase.database().ref().child("Comments").child(i).remove();
    }
  });
	firebase_ref.remove();
  // var firebase_comments = firebase.database().ref().child("Comments");
	// how to remove the html depends on whether we want it to refresh or not
	window.location.replace("main.html");
};

window.onload = function() {

	var data = [];

  firebase.database().ref("Tags").on("child_added", snap => {
    data.push({ id: data.length, text: snap.child("company").val() });
    $("#selectBox").select2({
  		width: '100%',
  		data: data,
  		placeholder: "Tags",
  		allowclear: true,
  	});
  });

	/*
	 * Switching tabs
	 */

 // var ref = firebase.database().ref();
 // var authData = ref.getAuth();
 // if (authData) {
 //   console.log("Authenticated user with uid:", authData.uid);
 // }
 // var curr_user = firebase.auth().currentUser;
 var curr_user = "J3DwxCADIIdGNlvCGeh5nbjKhYc2";
 //  console.log(curr_user);
 firebase.auth().onAuthStateChanged(user => {
 	if (user){
 	// 	console.log(user.uid);
 		curr_user = user.uid;
 	} else {
 		window.location.replace("index.html");
 	}
 });
 // console.log(window.user);
  // console.log(window.user);
  // console.log(curr_user);
	// console.log(curr_user);
	var arr = document.getElementsByClassName("nav_el");
	var names = ["post", "announcement", "meeting", "user"];
	var last_active = 0;

	for (var i = arr.length-1; i >=0; --i) {
		arr[i].onclick = function() {
			arr[last_active].classList.remove("nav_active");
			document.getElementById(names[last_active]).style.display = "none";
			last_active = this.getAttribute('value');
			document.getElementById(names[this.getAttribute('value')]).style.display = "block";
			this.className += " nav_active";
		}
	}

	/*
	 * Add post functionality
	 */

	var add = document.getElementById("add");
	var add_wrap = document.getElementById("add_wrap");
	var outer_wrap = document.getElementById("outer_wrap");
	var add_exit = document.getElementById("add_exit");
	add.onclick = function() {
		add_wrap.style.display = "block";
		outer_wrap.style.webkitFilter = "blur(3px)";
	}
	add_exit.onclick = function() {
		add_wrap.style.display = "none";
		outer_wrap.style.webkitFilter = "";
	}

	/*
	 *
	 * Database stuff
	 *
	 */

	/*
	 * Sending stuff to Firebase
	 */

	var firebase_ref = firebase.database().ref();
	var submit = document.getElementById("add_submit");
	submit.onclick = function() {
		var add_title = document.getElementById("add_title").value;
		var add_text = document.getElementById("add_text").value;
		var add_select = document.getElementById("add_select").value;
		var add_tags = $("#selectBox").val();
		firebase_ref.child("Posts").push().set({
	    title: add_title,
	    text: add_text,
	    select: add_select,
			tags: add_tags,
			user: curr_user,
	  });

	  // Clear
		add_wrap.style.display = "none";
		outer_wrap.style.webkitFilter = "";
		clearField(document.getElementById("add_title"));
		clearField(document.getElementById("add_text"));
		clearField(document.getElementById("add_tags"));
	}

  var comment_submit = document.getElementById("comment_submit");
  comment_submit.onclick = function() {
    var add_comment = document.getElementById("comment_text").value;
    var post_key = document.getElementById("post_id").value;
    var new_key = firebase_ref.child("Posts").child(post_key).child("comments").push(true).getKey();
    firebase_ref.child("Comments").child(new_key).set({
      post: post_key,
      comment: add_comment
    });
    document.getElementById("comment_text").value = "";
  };

	/*
	 * Receiving data
	 */

	// Triggers when a value changes
	// Receive snapshot which includes whole list of posts
	// firebase_ref.child("Comments").on('child_added', snap => {
  //   var post_key = snap.child("post");
  //   if (post_key.val() == document.getElementById("post_id").value) {
  //     var comments = document.getElementById("comment");
  //     // comments.innerHTML = "";
  //     comments.innerHTML += snap.child("comment").val() + "\n";
  //     // console.log(snap.val());
  //   }
	// });

  // function update_comments(snap) {
  //   var comments = snap.child("comments").val();
  //   var commentHTML = document.getElementById("comment");
  //   commentHTML.innerHTML = "";
  //   for (var key in comments) {
  //     firebase_ref.child("Comments").child(key).child("comment").once('value').then(function(snapshot) {
  //       commentHTML.innerHTML += "

" + snapshot.val() + "

";
  //     });
  //   }
  // }

	// Triggers when a post is added
	// Receive a snap which is one post
	firebase_ref.child("Posts").on('child_added', snap => {
		var title = snap.child("title").val();
		var text = snap.child("text").val();
		var select = snap.child("select").val();
		var tags = snap.child("tags").val();
    var user = snap.child("user").val();
		// console.log(tags);
		var tags_string = "";
		for (var i = 0; i < snap.child("tags").numChildren() - 1; i++) {
			tags_string += data[snap.child("tags").child(i).val()]['text'] + ", ";
		}
		if (snap.child("tags").numChildren() > 0) {
			tags_string += data[snap.child("tags").child(snap.child("tags").numChildren() - 1).val()]['text'];
		}
    var commentHTML = document.getElementById("comment");
    var commentTA = document.getElementById("comment_text");

		/********************************************************/

		// var posts_ref = firebase.database().ref("Posts");
		// var user_li = document.createElement("li");
		// firebase.database().ref("Posts").orderByChild("user").equalTo(curr_user).on("child_added", function(snapshot) {
    //   console.log(snapshot.val());
		// 	user_li.addEventListener('click', function(e) {
    //     commentHTML.innerHTML = "";
    //     commentTA.value = "";
		// 		window.scrollTo(0, 0);
		// 		document.getElementById("msg_info_title").innerHTML = snapshot.child("title").val();
		// 		document.getElementById("msg_info_text").innerHTML = snapshot.child("text").val();
		// 		document.getElementById("msg_info").style.display = "block";
		// 		outer_wrap.style.webkitFilter = "blur(3px)";
    //     document.getElementById("post_id").value = snap.key;
		// 	}, false);
    //   // // console.log(title);
		// 	user_li.innerHTML = "
" + snapshot.child("title").val() + "
\n
" + snapshot.child("text").val() + "
\n
Tags: " + tags_string + "
<button onclick='remove_post(\"" + snapshot.key + "\")' value='" + snapshot.key + "' class='remove_post'></button>";
    //   document.getElementById("user").insertBefore(user_li, document.getElementById("user").firstChild);
		// });
		/***********************************************************/

		if (select != "post") {
			var new_msg = document.createElement("li");
			new_msg.addEventListener('click', function(e) {
        commentHTML.innerHTML = "";
        commentTA.value = "";
				window.scrollTo(0, 0);
				document.getElementById("msg_info_title").innerHTML = title;
				document.getElementById("msg_info_text").innerHTML = text;
				document.getElementById("msg_info").style.display = "block";
				outer_wrap.style.webkitFilter = "blur(3px)";
        document.getElementById("post_id").value = snap.key;
        // update_comments(snap);
        firebase.database().ref("Comments").off();
        firebase.database().ref("Comments").orderByChild("post").equalTo(snap.key).on("child_added", function(snapshot) {
          commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
        });
			}, false);
      if (user == curr_user) {
        new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
<button onclick='remove_post(\"" + snap.key + "\")' value='" + snap.key + "' class='remove_post'></button>";
      } else {
        new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
      }
      document.getElementById(select).insertBefore(new_msg, document.getElementById(select).firstChild);
		}
		var new_msg = document.createElement("li");
		new_msg.addEventListener('click', function(e) {
      commentHTML.innerHTML = "";
      commentTA.value = "";
			window.scrollTo(0, 0);
			document.getElementById("msg_info_title").innerHTML = title;
			document.getElementById("msg_info_text").innerHTML = text;
			document.getElementById("msg_info").style.display = "block";
			outer_wrap.style.webkitFilter = "blur(3px)";
      document.getElementById("post_id").value = snap.key;
      // update_comments(snap);
      firebase.database().ref("Comments").off();
      firebase.database().ref("Comments").orderByChild("post").equalTo(snap.key).on("child_added", function(snapshot) {
        commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
      });
		}, false);
    if (user == curr_user) {
      new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
<button onclick='remove_post(\"" + snap.key + "\")' value='" + snap.key + "' class='remove_post'></button>";
    } else {
      new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
    }
		document.getElementById("post").insertBefore(new_msg, document.getElementById("post").firstChild);
	});

  firebase.database().ref("Posts").orderByChild("user").equalTo(curr_user).on("child_added", function(snapshot) {
    // console.log(snapshot.val());
    var tags = snapshot.child("tags").val();
		var tags_string = "";
		for (var i = 0; i < snapshot.child("tags").numChildren() - 1; i++) {
			tags_string += data[snapshot.child("tags").child(i).val()]['text'] + ", ";
		}
		if (snapshot.child("tags").numChildren() > 0) {
			tags_string += data[snapshot.child("tags").child(snapshot.child("tags").numChildren() - 1).val()]['text'];
		}
    // console.log(snapshot.val());
    var commentHTML = document.getElementById("comment");
    var commentTA = document.getElementById("comment_text");
    var user_li = document.createElement("li");
    user_li.addEventListener('click', function(e) {
      commentHTML.innerHTML = "";
      commentTA.value = "";
      window.scrollTo(0, 0);
      document.getElementById("msg_info_title").innerHTML = snapshot.child("title").val();
      document.getElementById("msg_info_text").innerHTML = snapshot.child("text").val();
      document.getElementById("msg_info").style.display = "block";
      outer_wrap.style.webkitFilter = "blur(3px)";
      document.getElementById("post_id").value = snapshot.key;
      //
      firebase.database().ref("Comments").off();
      firebase.database().ref("Comments").orderByChild("post").equalTo(snapshot.key).on("child_added", function(snapshot) {
        commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
      });
    }, false);
    // console.log(snapshot.key);
    user_li.innerHTML = "
" + snapshot.child("title").val() + "
\n
" + snapshot.child("text").val() + "
\n
Tags: " + tags_string + "
<button onclick='remove_post(\"" + snapshot.key + "\")' value='" + snapshot.key + "' class='remove_post'></button>";
    document.getElementById("user").insertBefore(user_li, document.getElementById("user").firstChild);
  });

  firebase_ref.child("Posts").on('child_removed', snap => {
    $("#" + snap.key).remove();
  });

	var logout = document.getElementById("logout");
	logout.addEventListener('click', e => {
		firebase.auth().signOut();
	});

	/*
	 * Shifting return
	 */
	document.getElementById("msg_info_return").onclick = function() {
		document.getElementById("msg_info").style.display = "none";
		outer_wrap.style.webkitFilter = "";
		window.scrollTo(0, 0);
	};

}
<commit_msg>Fixed the clicking thing<commit_after>function clearField(input) {
	if (input) {
	  input.value = "";
	}
};

function remove_post(key) {
	if (confirm("Are you sure?")) {
		var firebase_ref = firebase.database().ref().child("Posts").child(key);
	  firebase_ref.child("comments").once('value').then(function(snapshot) {
	    // console.log(snapshot.val());
	    for (var i in snapshot.val()) {
	      firebase.database().ref().child("Comments").child(i).remove();
	    }
	  });
		firebase_ref.remove();
	  // var firebase_comments = firebase.database().ref().child("Comments");
		// how to remove the html depends on whether we want it to refresh or not
		window.location.replace("main.html");
	}
};

window.onload = function() {

	var data = [];

  firebase.database().ref("Tags").on("child_added", snap => {
    data.push({ id: data.length, text: snap.child("company").val() });
    $("#selectBox").select2({
  		width: '100%',
  		data: data,
  		placeholder: "Tags",
  		allowclear: true,
  	});
  });

	/*
	 * Switching tabs
	 */

 // var ref = firebase.database().ref();
 // var authData = ref.getAuth();
 // if (authData) {
 //   console.log("Authenticated user with uid:", authData.uid);
 // }
 // var curr_user = firebase.auth().currentUser;
 var curr_user = "J3DwxCADIIdGNlvCGeh5nbjKhYc2";
 //  console.log(curr_user);
 firebase.auth().onAuthStateChanged(user => {
 	if (user){
 	// 	console.log(user.uid);
 		curr_user = user.uid;
 	} else {
 		window.location.replace("index.html");
 	}
 });
 // console.log(window.user);
  // console.log(window.user);
  // console.log(curr_user);
	// console.log(curr_user);
	var arr = document.getElementsByClassName("nav_el");
	var names = ["post", "announcement", "meeting", "user"];
	var last_active = 0;

	for (var i = arr.length-1; i >=0; --i) {
		arr[i].onclick = function() {
			arr[last_active].classList.remove("nav_active");
			document.getElementById(names[last_active]).style.display = "none";
			last_active = this.getAttribute('value');
			document.getElementById(names[this.getAttribute('value')]).style.display = "block";
			this.className += " nav_active";
		}
	}

	/*
	 * Add post functionality
	 */

	var add = document.getElementById("add");
	var add_wrap = document.getElementById("add_wrap");
	var outer_wrap = document.getElementById("outer_wrap");
	var add_exit = document.getElementById("add_exit");
	add.onclick = function() {
		add_wrap.style.display = "block";
		outer_wrap.style.webkitFilter = "blur(3px)";
	}
	add_exit.onclick = function() {
		add_wrap.style.display = "none";
		outer_wrap.style.webkitFilter = "";
	}

	/*
	 *
	 * Database stuff
	 *
	 */

	/*
	 * Sending stuff to Firebase
	 */

	var firebase_ref = firebase.database().ref();
	var submit = document.getElementById("add_submit");
	submit.onclick = function() {
		var add_title = document.getElementById("add_title").value;
		var add_text = document.getElementById("add_text").value;
		var add_select = document.getElementById("add_select").value;
		var add_tags = $("#selectBox").val();
		firebase_ref.child("Posts").push().set({
	    title: add_title,
	    text: add_text,
	    select: add_select,
			tags: add_tags,
			user: curr_user,
	  });

	  // Clear
		add_wrap.style.display = "none";
		outer_wrap.style.webkitFilter = "";
		clearField(document.getElementById("add_title"));
		clearField(document.getElementById("add_text"));
		clearField(document.getElementById("add_tags"));
	}

  var comment_submit = document.getElementById("comment_submit");
  comment_submit.onclick = function() {
    var add_comment = document.getElementById("comment_text").value;
    var post_key = document.getElementById("post_id").value;
    var new_key = firebase_ref.child("Posts").child(post_key).child("comments").push(true).getKey();
    firebase_ref.child("Comments").child(new_key).set({
      post: post_key,
      comment: add_comment
    });
    document.getElementById("comment_text").value = "";
  };

	/*
	 * Receiving data
	 */

	// Triggers when a value changes
	// Receive snapshot which includes whole list of posts
	// firebase_ref.child("Comments").on('child_added', snap => {
  //   var post_key = snap.child("post");
  //   if (post_key.val() == document.getElementById("post_id").value) {
  //     var comments = document.getElementById("comment");
  //     // comments.innerHTML = "";
  //     comments.innerHTML += snap.child("comment").val() + "\n";
  //     // console.log(snap.val());
  //   }
	// });

  // function update_comments(snap) {
  //   var comments = snap.child("comments").val();
  //   var commentHTML = document.getElementById("comment");
  //   commentHTML.innerHTML = "";
  //   for (var key in comments) {
  //     firebase_ref.child("Comments").child(key).child("comment").once('value').then(function(snapshot) {
  //       commentHTML.innerHTML += "

" + snapshot.val() + "

";
  //     });
  //   }
  // }

	// Triggers when a post is added
	// Receive a snap which is one post
	firebase_ref.child("Posts").on('child_added', snap => {
		var title = snap.child("title").val();
		var text = snap.child("text").val();
		var select = snap.child("select").val();
		var tags = snap.child("tags").val();
    var user = snap.child("user").val();
		// console.log(tags);
		var tags_string = "";
		for (var i = 0; i < snap.child("tags").numChildren() - 1; i++) {
			tags_string += data[snap.child("tags").child(i).val()]['text'] + ", ";
		}
		if (snap.child("tags").numChildren() > 0) {
			tags_string += data[snap.child("tags").child(snap.child("tags").numChildren() - 1).val()]['text'];
		}
    var commentHTML = document.getElementById("comment");
    var commentTA = document.getElementById("comment_text");

		/********************************************************/

		// var posts_ref = firebase.database().ref("Posts");
		// var user_li = document.createElement("li");
		// firebase.database().ref("Posts").orderByChild("user").equalTo(curr_user).on("child_added", function(snapshot) {
    //   console.log(snapshot.val());
		// 	user_li.addEventListener('click', function(e) {
    //     commentHTML.innerHTML = "";
    //     commentTA.value = "";
		// 		window.scrollTo(0, 0);
		// 		document.getElementById("msg_info_title").innerHTML = snapshot.child("title").val();
		// 		document.getElementById("msg_info_text").innerHTML = snapshot.child("text").val();
		// 		document.getElementById("msg_info").style.display = "block";
		// 		outer_wrap.style.webkitFilter = "blur(3px)";
    //     document.getElementById("post_id").value = snap.key;
		// 	}, false);
    //   // // console.log(title);
		// 	user_li.innerHTML = "
" + snapshot.child("title").val() + "
\n
" + snapshot.child("text").val() + "
\n
Tags: " + tags_string + "
<button onclick='remove_post(\"" + snapshot.key + "\")' value='" + snapshot.key + "' class='remove_post'></button>";
    //   document.getElementById("user").insertBefore(user_li, document.getElementById("user").firstChild);
		// });
		/***********************************************************/

		if (select != "post") {
			var new_msg = document.createElement("li");
			new_msg.addEventListener('click', function(e) {
        commentHTML.innerHTML = "";
        commentTA.value = "";
				window.scrollTo(0, 0);
				document.getElementById("msg_info_title").innerHTML = title;
				document.getElementById("msg_info_text").innerHTML = text;
				document.getElementById("msg_info").style.display = "block";
				outer_wrap.style.webkitFilter = "blur(3px)";
        document.getElementById("post_id").value = snap.key;
        // update_comments(snap);
        firebase.database().ref("Comments").off();
        firebase.database().ref("Comments").orderByChild("post").equalTo(snap.key).on("child_added", function(snapshot) {
          commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
        });
			}, false);
      if (user == curr_user) {
        new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";

        var but = document.createElement("button");
        but.addEventListener('click', function(e) {
        	remove_post(snap.key);
        	e.stopPropagation();
        }, false);
        but.className += "remove_post";
        but.innerHTML = "";
        new_msg.appendChild(but);
      } else {
        new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
      }
      document.getElementById(select).insertBefore(new_msg, document.getElementById(select).firstChild);
		}
		var new_msg = document.createElement("li");
		new_msg.addEventListener('click', function(e) {
      commentHTML.innerHTML = "";
      commentTA.value = "";
			window.scrollTo(0, 0);
			document.getElementById("msg_info_title").innerHTML = title;
			document.getElementById("msg_info_text").innerHTML = text;
			document.getElementById("msg_info").style.display = "block";
			outer_wrap.style.webkitFilter = "blur(3px)";
      document.getElementById("post_id").value = snap.key;
      // update_comments(snap);
      firebase.database().ref("Comments").off();
      firebase.database().ref("Comments").orderByChild("post").equalTo(snap.key).on("child_added", function(snapshot) {
        commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
      });
		}, false);
    if (user == curr_user) {
      new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";

        var but = document.createElement("button");
        but.addEventListener('click', function(e) {
        	remove_post(snap.key);
        	e.stopPropagation();
        }, false);
        but.className += "remove_post";
        but.innerHTML = "";
        new_msg.appendChild(but);
    } else {
      new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";
    }
		document.getElementById("post").insertBefore(new_msg, document.getElementById("post").firstChild);
	});

  firebase.database().ref("Posts").orderByChild("user").equalTo(curr_user).on("child_added", function(snapshot) {
    // console.log(snapshot.val());
    var tags = snapshot.child("tags").val();
		var tags_string = "";
		for (var i = 0; i < snapshot.child("tags").numChildren() - 1; i++) {
			tags_string += data[snapshot.child("tags").child(i).val()]['text'] + ", ";
		}
		if (snapshot.child("tags").numChildren() > 0) {
			tags_string += data[snapshot.child("tags").child(snapshot.child("tags").numChildren() - 1).val()]['text'];
		}
    // console.log(snapshot.val());
    var commentHTML = document.getElementById("comment");
    var commentTA = document.getElementById("comment_text");
    var user_li = document.createElement("li");
    user_li.addEventListener('click', function(e) {
      commentHTML.innerHTML = "";
      commentTA.value = "";
      window.scrollTo(0, 0);
      document.getElementById("msg_info_title").innerHTML = snapshot.child("title").val();
      document.getElementById("msg_info_text").innerHTML = snapshot.child("text").val();
      document.getElementById("msg_info").style.display = "block";
      outer_wrap.style.webkitFilter = "blur(3px)";
      document.getElementById("post_id").value = snapshot.key;
      //
      firebase.database().ref("Comments").off();
      firebase.database().ref("Comments").orderByChild("post").equalTo(snapshot.key).on("child_added", function(snapshot) {
        commentHTML.innerHTML += "

" + snapshot.child("comment").val() + "

";
      });
    }, false);
    // console.log(snapshot.key);
    new_msg.innerHTML = "
" + title + "
\n
" + text + "
\n
Tags: " + tags_string + "
";

        var but = document.createElement("button");
        but.addEventListener('click', function(e) {
        	remove_post(snap.key);
        	e.stopPropagation();
        }, false);
        but.className += "remove_post";
        but.innerHTML = "";
        new_msg.appendChild(but);
    document.getElementById("user").insertBefore(user_li, document.getElementById("user").firstChild);
  });

  firebase_ref.child("Posts").on('child_removed', snap => {
    $("#" + snap.key).remove();
  });

	var logout = document.getElementById("logout");
	logout.addEventListener('click', e => {
		firebase.auth().signOut();
	});

	/*
	 * Shifting return
	 */
	document.getElementById("msg_info_return").onclick = function() {
		document.getElementById("msg_info").style.display = "none";
		outer_wrap.style.webkitFilter = "";
		window.scrollTo(0, 0);
	};

}
<|endoftext|>


<commit_before>describe('smokeTest', function() {
    it('returns the page title', function() {
        browser.url('http://localhost:8080/');
        var title = browser.getTitle();
        console.log('Title is: ' + title);
    });
});
<commit_msg>removed smoke<commit_after><|endoftext|>


<commit_before>// Load Gulp and all of our Gulp plugins
const gulp = require('gulp');
const $ = require('gulp-load-plugins')();

// Load other npm modules
const del = require('del');
const glob = require('glob');
const path = require('path');
const isparta = require('isparta');
const babelify = require('babelify');
const watchify = require('watchify');
const buffer = require('vinyl-buffer');
const rollup = require('rollup');
const browserify = require('browserify');
const runSequence = require('run-sequence');
const source = require('vinyl-source-stream');
const awspublish = require('gulp-awspublish');
const browserSync = require('browser-sync').create();
const KarmaServer = require('karma').Server;
const shell = require('gulp-shell');
const bump = require('gulp-bump');
const _ = require('lodash');
const esdoc = require("gulp-esdoc");

// Gather the library data from `package.json`
const manifest = require('./package.json');
const config = manifest.babelBoilerplateOptions;
const mainFile = manifest.main;
const destinationFolder = path.dirname(mainFile);
const exportFileName = path.basename(mainFile, path.extname(mainFile));
const conf = require('./config.json');

// JS files that should be watched
const jsWatchFiles = ['src/**/*', 'test/**/*'];

// These are files other than JS files which are to be watched.
const otherWatchFiles = ['package.json', '**/.eslintrc', '.jscsrc'];

//Create CDN Publisher
var publisher = CDNPublisher();

// Build main and minified versions of the library
gulp.task('build:main', ['lint-src', 'clean'], function (done) {
  rollup.rollup({
    entry: config.entryFileName,
    external:['lodash','superagent', 'jwt-decode'],
  }).then(function (bundle) {
    var res = bundle.generate({
      // Don't worry about the fact that the source map is inlined at this step.
      // `gulp-sourcemaps`, which comes next, will externalize them.
      format:'umd',
      sourceMap: 'inline',
      moduleName: config.mainVarName
    });
    $.file(exportFileName + '.js', res.code, { src: true })
      .pipe($.plumber())
      .pipe($.sourcemaps.init({ loadMaps: true }))
      .pipe($.babel())
      .pipe($.sourcemaps.write('./'))
      .pipe(gulp.dest(destinationFolder))
      .pipe($.filter(['*', '!**/*.js.map']))
      .pipe($.rename(exportFileName + '.min.js'))
      .pipe($.sourcemaps.init({ loadMaps: true }))
      .pipe($.uglify())
      .pipe($.sourcemaps.write('./'))
      .pipe(gulp.dest(destinationFolder))
      .on('end', done);
  })
  .catch(done);
});
//Build bundle version
gulp.task('build:bundle', function (callback) {
  runSequence('addExternals', callback);
});

// Ensure that linting occurs before browserify runs. This prevents
// the build from breaking due to poorly formatted code.
gulp.task('build', function (callback) {
  runSequence(['lint-src', 'lint-test'], 'test', 'build:main', 'build:bundle', 'watch', callback);
});

//Browserify with external modules included
gulp.task('addExternals', function() {
  return bundle(browserifyAndWatchBundler());
});

//Run test once using Karma and exit
gulp.task('test', function (done) {
  require('babel-core/register');
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});

// Release a new version of the package
gulp.task('release', function(callback) {
  const tagCreate = 'git tag -a v' + manifest.version + ' -m ' + 'Version v' + manifest.version;
  const tagPush = 'git push --tags';
  //Bump package version
  //Unlink local modules
  //Build (test/build:main/build:bundle)
  //Upload to CDN locations
  //Create a git tag and push the tag
  //TODO: Look into what should be moved to happening after travis build
  //TODO: Include 'npm publish', 'git commit' and 'git push'?
  runSequence('bump', 'unlink', 'build', 'upload',  shell.task([tagCreate, tagPush]), callback);
});

// Basic usage:
// Will patch the version
gulp.task('bump', function(){
  gulp.src('./component.json')
  .pipe(bump())
  .pipe(gulp.dest('./'));
});

//Watch files and trigger a rebuild on change
gulp.task('watch', function() {
  const watchFiles = jsWatchFiles.concat(otherWatchFiles);
  gulp.watch(watchFiles, ['build']);
});

//Upload to both locations of CDN
gulp.task('upload', function (callback) {
  runSequence('upload:version', 'upload:latest', callback);
});

//Upload to CDN under version
gulp.task('upload:version', function() {
  return gulp.src('./' + conf.distFolder + '/**')
    .pipe($.rename(function (path) {
      path.dirname = conf.cdn.path + '/' + manifest.version + '/' + path.dirname;
    }))
    .pipe(publisher.publish())
    .pipe(awspublish.reporter());
});
//Upload to CDN under "/latest"
gulp.task('upload:latest', function() {
  return gulp.src('./' + conf.distFolder + '/**')
    .pipe($.rename(function (path) {
      path.dirname = conf.cdn.path + '/latest/' + path.dirname;
    }))
    .pipe(publisher.publish())
    .pipe(awspublish.reporter());
});
//Upload to CDN under "/latest"
gulp.task('upload:docs', function() {
  return gulp.src('./' + conf.folders.docs + '/**')
    .pipe($.rename(function (path) {
      path.dirname = conf.cdn.path + '/latest/' + path.dirname + '/docs';
    }))
    .pipe(publisher.publish())
    .pipe(awspublish.reporter());
});
// Generate docs based on comments
const esdocConfig = require('./esdoc.json');
gulp.task('docs', function() {
  gulp.src('./src')
  .pipe(esdoc(esdocConfig));
});

// Static server
gulp.task('browser-sync', function() {
  browserSync.init({
    server: {
      baseDir: "./"
    }
  });
});

// Remove the built files
gulp.task('clean', function(cb) {
  del([destinationFolder], cb);
});

// Remove our temporary files
gulp.task('clean-tmp', function(cb) {
  del(['tmp'], cb);
});

// Lint our source code
createLintTask('lint-src', ['src/**/*.js']);

// Lint our test code
createLintTask('lint-test', ['test/**/*.js', '!test/coverage/**']);

//Link list of modules
gulp.task('link', shell.task(buildLinkCommands('link')));

//Unlink list of modules
gulp.task('unlink', shell.task(buildLinkCommands('unlink')));

// An alias of test
gulp.task('default', ['test', 'build-bundle']);

//----------------------- Utility Functions -------------------------------\\
//Build an array of commands to link/unlink modules
function buildLinkCommands(linkAction){
  //TODO: Don't allow package types that don't follow standard link/unlink pattern
  // const allowedPackageLinkTypes = ['bower', 'npm'];
  if(!linkAction){
    linkAction = 'link';
  }
  const linkTypes = _.keys(config.linkedModules);
  const messageCommand = 'echo ' + linkAction + 'ing local modules';
  var commands = [messageCommand];
  //Each type of packages to link
  _.each(linkTypes, function (packageType){
    //Check that package link patter is supported
    // if(!_.contains(allowedPackageLinkTypes, packageType)){
    //   console.error('Invalid package link packageType');
    //   return;
    // }
    //Each package of that packageType
    _.each(conf.linkedModules[packageType], function (packageName){
      commands.push(packageType + ' ' + linkAction  + ' ' + packageName);
      if(linkAction === 'unlink'){
        commands.push(packageType + ' install ' + packageName);
      }
    });
  });
  return commands;
}

function CDNPublisher () {
  var s3Config = {
    accessKeyId:process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,
    params:{
      Bucket:conf.cdn.bucketName
    }
  };
  return awspublish.create(s3Config);
}

function bundle(bundler) {
  return bundler.bundle()
    .on('error', function(err) {
      console.log(err.message);
      this.emit('end');
    })
    .pipe($.plumber())
    .pipe(source('./tmp/__matter.bundle.js'))
    .pipe(buffer())
    .pipe($.rename(exportFileName + '.bundle.js'))
    .pipe(gulp.dest(destinationFolder))
    .pipe($.livereload());
}
function browserifyAndWatchBundler(code) {
  // Create our bundler, passing in the arguments required for watchify
  var bundler = browserify('src/' + exportFileName + '.js', {standalone: config.mainVarName});

  // Watch the bundler, and re-bundle it whenever files change
  bundler = watchify(bundler);
  bundler.on('update', function() {
    bundle(bundler);
  });

  // // Set up Babelify so that ES6 works in the tests
  bundler.transform(babelify.configure({
    ignore: /(bower_components)|(node_modules)/,
    sourceMapRelative: __dirname + '/src',
    optional: ["es7.asyncFunctions"],
    stage:2
  }));
  return bundler;
};

// Send a notification when JSCS fails,
// so that you know your changes didn't build
function jscsNotify(file) {
  if (!file.jscs) { return; }
  return file.jscs.success ? false : 'JSCS failed';
}

function createLintTask(taskName, files) {
  gulp.task(taskName, function() {
    return gulp.src(files)
      .pipe($.plumber())
      .pipe($.eslint())
      .pipe($.eslint.format())
      .pipe($.eslint.failOnError())
      .pipe($.jscs())
      .pipe($.notify(jscsNotify));
  });
}
<commit_msg>Fixed incorrect reference in gulp upload:docs task. [ci skip]<commit_after>// Load Gulp and all of our Gulp plugins
const gulp = require('gulp');
const $ = require('gulp-load-plugins')();

// Load other npm modules
const del = require('del');
const glob = require('glob');
const path = require('path');
const isparta = require('isparta');
const babelify = require('babelify');
const watchify = require('watchify');
const buffer = require('vinyl-buffer');
const rollup = require('rollup');
const browserify = require('browserify');
const runSequence = require('run-sequence');
const source = require('vinyl-source-stream');
const awspublish = require('gulp-awspublish');
const browserSync = require('browser-sync').create();
const KarmaServer = require('karma').Server;
const shell = require('gulp-shell');
const bump = require('gulp-bump');
const _ = require('lodash');
const esdoc = require("gulp-esdoc");

// Gather the library data from `package.json`
const manifest = require('./package.json');
const config = manifest.babelBoilerplateOptions;
const mainFile = manifest.main;
const destinationFolder = path.dirname(mainFile);
const exportFileName = path.basename(mainFile, path.extname(mainFile));
const conf = require('./config.json');

// JS files that should be watched
const jsWatchFiles = ['src/**/*', 'test/**/*'];

// These are files other than JS files which are to be watched.
const otherWatchFiles = ['package.json', '**/.eslintrc', '.jscsrc'];

//Create CDN Publisher
var publisher = CDNPublisher();

// Build main and minified versions of the library
gulp.task('build:main', ['lint-src', 'clean'], function (done) {
  rollup.rollup({
    entry: config.entryFileName,
    external:['lodash','superagent', 'jwt-decode'],
  }).then(function (bundle) {
    var res = bundle.generate({
      // Don't worry about the fact that the source map is inlined at this step.
      // `gulp-sourcemaps`, which comes next, will externalize them.
      format:'umd',
      sourceMap: 'inline',
      moduleName: config.mainVarName
    });
    $.file(exportFileName + '.js', res.code, { src: true })
      .pipe($.plumber())
      .pipe($.sourcemaps.init({ loadMaps: true }))
      .pipe($.babel())
      .pipe($.sourcemaps.write('./'))
      .pipe(gulp.dest(destinationFolder))
      .pipe($.filter(['*', '!**/*.js.map']))
      .pipe($.rename(exportFileName + '.min.js'))
      .pipe($.sourcemaps.init({ loadMaps: true }))
      .pipe($.uglify())
      .pipe($.sourcemaps.write('./'))
      .pipe(gulp.dest(destinationFolder))
      .on('end', done);
  })
  .catch(done);
});
//Build bundle version
gulp.task('build:bundle', function (callback) {
  runSequence('addExternals', callback);
});

// Ensure that linting occurs before browserify runs. This prevents
// the build from breaking due to poorly formatted code.
gulp.task('build', function (callback) {
  runSequence(['lint-src', 'lint-test'], 'test', 'build:main', 'build:bundle', 'watch', callback);
});

//Browserify with external modules included
gulp.task('addExternals', function() {
  return bundle(browserifyAndWatchBundler());
});

//Run test once using Karma and exit
gulp.task('test', function (done) {
  require('babel-core/register');
  new KarmaServer({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});

// Release a new version of the package
gulp.task('release', function(callback) {
  const tagCreate = 'git tag -a v' + manifest.version + ' -m ' + 'Version v' + manifest.version;
  const tagPush = 'git push --tags';
  //Bump package version
  //Unlink local modules
  //Build (test/build:main/build:bundle)
  //Upload to CDN locations
  //Create a git tag and push the tag
  //TODO: Look into what should be moved to happening after travis build
  //TODO: Include 'npm publish', 'git commit' and 'git push'?
  runSequence('bump', 'unlink', 'build', 'upload',  shell.task([tagCreate, tagPush]), callback);
});

// Basic usage:
// Will patch the version
gulp.task('bump', function(){
  gulp.src('./component.json')
  .pipe(bump())
  .pipe(gulp.dest('./'));
});

//Watch files and trigger a rebuild on change
gulp.task('watch', function() {
  const watchFiles = jsWatchFiles.concat(otherWatchFiles);
  gulp.watch(watchFiles, ['build']);
});

//Upload to both locations of CDN
gulp.task('upload', function (callback) {
  runSequence('upload:version', 'upload:latest', callback);
});

//Upload to CDN under version
gulp.task('upload:version', function() {
  return gulp.src('./' + conf.distFolder + '/**')
    .pipe($.rename(function (path) {
      path.dirname = conf.cdn.path + '/' + manifest.version + '/' + path.dirname;
    }))
    .pipe(publisher.publish())
    .pipe(awspublish.reporter());
});
//Upload to CDN under "/latest"
gulp.task('upload:latest', function() {
  return gulp.src('./' + conf.distFolder + '/**')
    .pipe($.rename(function (path) {
      path.dirname = conf.cdn.path + '/latest/' + path.dirname;
    }))
    .pipe(publisher.publish())
    .pipe(awspublish.reporter());
});
//Upload to CDN under "/latest"
gulp.task('upload:docs', function() {
  return gulp.src('./' + conf.folders.docs + '/**')
    .pipe($.rename(function (path) {
      path.dirname = conf.cdn.path + '/latest/docs/' + path.dirname;
    }))
    .pipe(publisher.publish())
    .pipe(awspublish.reporter());
});
// Generate docs based on comments
const esdocConfig = require('./esdoc.json');
gulp.task('docs', function() {
  gulp.src('./src')
  .pipe(esdoc(esdocConfig));
});

// Static server
gulp.task('browser-sync', function() {
  browserSync.init({
    server: {
      baseDir: "./"
    }
  });
});

// Remove the built files
gulp.task('clean', function(cb) {
  del([destinationFolder], cb);
});

// Remove our temporary files
gulp.task('clean-tmp', function(cb) {
  del(['tmp'], cb);
});

// Lint our source code
createLintTask('lint-src', ['src/**/*.js']);

// Lint our test code
createLintTask('lint-test', ['test/**/*.js', '!test/coverage/**']);

//Link list of modules
gulp.task('link', shell.task(buildLinkCommands('link')));

//Unlink list of modules
gulp.task('unlink', shell.task(buildLinkCommands('unlink')));

// An alias of test
gulp.task('default', ['test', 'build-bundle']);

//----------------------- Utility Functions -------------------------------\\
//Build an array of commands to link/unlink modules
function buildLinkCommands(linkAction){
  //TODO: Don't allow package types that don't follow standard link/unlink pattern
  // const allowedPackageLinkTypes = ['bower', 'npm'];
  if(!linkAction){
    linkAction = 'link';
  }
  const linkTypes = _.keys(config.linkedModules);
  const messageCommand = 'echo ' + linkAction + 'ing local modules';
  var commands = [messageCommand];
  //Each type of packages to link
  _.each(linkTypes, function (packageType){
    //Check that package link patter is supported
    // if(!_.contains(allowedPackageLinkTypes, packageType)){
    //   console.error('Invalid package link packageType');
    //   return;
    // }
    //Each package of that packageType
    _.each(conf.linkedModules[packageType], function (packageName){
      commands.push(packageType + ' ' + linkAction  + ' ' + packageName);
      if(linkAction === 'unlink'){
        commands.push(packageType + ' install ' + packageName);
      }
    });
  });
  return commands;
}

function CDNPublisher () {
  var s3Config = {
    accessKeyId:process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,
    params:{
      Bucket:conf.cdn.bucketName
    }
  };
  return awspublish.create(s3Config);
}

function bundle(bundler) {
  return bundler.bundle()
    .on('error', function(err) {
      console.log(err.message);
      this.emit('end');
    })
    .pipe($.plumber())
    .pipe(source('./tmp/__matter.bundle.js'))
    .pipe(buffer())
    .pipe($.rename(exportFileName + '.bundle.js'))
    .pipe(gulp.dest(destinationFolder))
    .pipe($.livereload());
}
function browserifyAndWatchBundler(code) {
  // Create our bundler, passing in the arguments required for watchify
  var bundler = browserify('src/' + exportFileName + '.js', {standalone: config.mainVarName});

  // Watch the bundler, and re-bundle it whenever files change
  bundler = watchify(bundler);
  bundler.on('update', function() {
    bundle(bundler);
  });

  // // Set up Babelify so that ES6 works in the tests
  bundler.transform(babelify.configure({
    ignore: /(bower_components)|(node_modules)/,
    sourceMapRelative: __dirname + '/src',
    optional: ["es7.asyncFunctions"],
    stage:2
  }));
  return bundler;
};

// Send a notification when JSCS fails,
// so that you know your changes didn't build
function jscsNotify(file) {
  if (!file.jscs) { return; }
  return file.jscs.success ? false : 'JSCS failed';
}

function createLintTask(taskName, files) {
  gulp.task(taskName, function() {
    return gulp.src(files)
      .pipe($.plumber())
      .pipe($.eslint())
      .pipe($.eslint.format())
      .pipe($.eslint.failOnError())
      .pipe($.jscs())
      .pipe($.notify(jscsNotify));
  });
}
<|endoftext|>


<commit_before>define(function(require) {
    'use strict';

    var angular = require('angular'),
        appController = require('js/app-controller'),
        aes = require('cryptoLib/aes-cbc'),
        util = require('cryptoLib/util'),
        str = require('js/app-config').string,
        emailDao;

    //
    // Controller
    //

    var WriteCtrl = function($scope, $routeParams) {
        $scope.signature = str.signature;

        //
        // Init
        //

        // start the main app controller
        appController.start(function(err) {
            if (err) {
                console.error(err);
                return;
            }

            if (window.chrome && chrome.identity) {
                init('passphrase', function() {
                    emailDao = appController._emailDao;
                    getReplyTo($routeParams.folder, $routeParams.id, function() {
                        $scope.$apply();
                    });
                });
                return;
            }
        });

        function init(passphrase, callback) {
            appController.fetchOAuthToken(passphrase, function(err) {
                if (err) {
                    console.error(err);
                    return;
                }

                callback();
            });
        }

        function getReplyTo(folder, id, callback) {
            if (!folder || !id) {
                callback();
            }

            emailDao.listMessages({
                folder: folder + '_' + id
            }, function(err, list) {
                if (err) {
                    console.error(err);
                    return;
                }

                if (list.length > 0) {
                    fillFields(list[0]);
                }
                callback();
            });
        }

        function fillFields(re) {
            if (!re) {
                return;
            }

            // fille title
            $scope.title = 'Reply';
            // fill recipient field
            $scope.to = re.from[0].address;
            // fill subject
            $scope.subject = 'Re: ' + ((re.subject) ? re.subject.replace('Re: ', '') : '');

            // fill text body
            var body = '

' + re.sentDate + ' ' + re.from[0].name + ' <' + re.from[0].address + '>';
            var bodyRows = re.body.split('\n');
            bodyRows.forEach(function(row) {
                body += (!re.html) ? '
 > ' + row : '';
            });
            $scope.body = body;
        }

        //
        // Editing
        //

        // generate key,iv for encryption preview
        var key = util.random(128),
            iv = util.random(128);

        $scope.updatePreview = function() {
            var body = $scope.body;
            // remove generated html from body
            body = parseBody(body);

            // Although this does encrypt live using AES, this is just for show. The plaintext is encrypted seperately before sending the email.
            var plaintext = ($scope.subject) ? $scope.subject + body : body;
            $scope.ciphertextPreview = (plaintext) ? aes.encrypt(plaintext, key, iv) : '';
        };

        $scope.sendEmail = function() {
            var to, body, email;

            // validate recipients
            to = $scope.to.replace(/\s/g, '').split(/[,;]/);
            if (!to || to.length < 1) {
                console.log('Seperate recipients with a comma!');
                return;
            }

            body = $scope.body;
            // remove generated html from body
            body = parseBody(body);

            email = {
                to: [], // list of receivers
                subject: $scope.subject, // Subject line
                body: body // plaintext body
            };
            email.from = [{
                name: '',
                address: emailDao._account.emailAddress
            }];
            to.forEach(function(address) {
                email.to.push({
                    name: '',
                    address: address
                });
            });

            emailDao.smtpSend(email, function(err) {
                if (err) {
                    console.log(err);
                    return;
                }

                if (window.chrome && chrome.app.window) {
                    // close the chrome window
                    chrome.app.window.current().close();
                    return;
                }
            });
        };
    };

    function parseBody(body) {
        function has(substr) {
            return (body.indexOf(substr) !== -1);
        }
        while (has('
')) {
            body = body.replace('
', '\n');
        }
        while (has('
')) {
            body = body.replace('
', '\n');
        }
        while (has('
')) {
            body = body.replace('
', '');
        }

        return body;
    }

    //
    // Directives
    //

    var ngModule = angular.module('write', []);
    ngModule.directive('contenteditable', function() {
        return {
            require: 'ngModel',
            link: function(scope, elm, attrs, ctrl) {
                // view -> model
                elm.on('keyup keydown focus', function() {
                    scope.$apply(function() {
                        ctrl.$setViewValue(elm.html());
                    });
                });

                // model -> view
                ctrl.$render = function() {
                    elm.html(ctrl.$viewValue);
                };

                // load init value from DOM
                ctrl.$setViewValue(elm.html());
            }
        };
    });

    ngModule.directive('focusMe', function($timeout) {
        return {
            link: function(scope, element) {
                $timeout(function() {
                    element[0].focus();
                });
            }
        };
    });

    return WriteCtrl;
});<commit_msg>fix > in reply<commit_after>define(function(require) {
    'use strict';

    var angular = require('angular'),
        appController = require('js/app-controller'),
        aes = require('cryptoLib/aes-cbc'),
        util = require('cryptoLib/util'),
        str = require('js/app-config').string,
        emailDao;

    //
    // Controller
    //

    var WriteCtrl = function($scope, $routeParams, $filter) {
        $scope.signature = str.signature;

        //
        // Init
        //

        // start the main app controller
        appController.start(function(err) {
            if (err) {
                console.error(err);
                return;
            }

            if (window.chrome && chrome.identity) {
                init('passphrase', function() {
                    emailDao = appController._emailDao;
                    getReplyTo($routeParams.folder, $routeParams.id, function() {
                        $scope.$apply();
                    });
                });
                return;
            }
        });

        function init(passphrase, callback) {
            appController.fetchOAuthToken(passphrase, function(err) {
                if (err) {
                    console.error(err);
                    return;
                }

                callback();
            });
        }

        function getReplyTo(folder, id, callback) {
            if (!folder || !id) {
                callback();
            }

            emailDao.listMessages({
                folder: folder + '_' + id
            }, function(err, list) {
                if (err) {
                    console.error(err);
                    return;
                }

                if (list.length > 0) {
                    fillFields(list[0]);
                }
                callback();
            });
        }

        function fillFields(re) {
            var from, body, bodyRows;

            if (!re) {
                return;
            }

            // fille title
            $scope.title = 'Reply';
            // fill recipient field
            $scope.to = re.from[0].address;
            // fill subject
            $scope.subject = 'Re: ' + ((re.subject) ? re.subject.replace('Re: ', '') : '');

            // fill text body
            from = re.from[0].name || re.from[0].address;
            body = '

' + $filter('date')(re.sentDate, 'EEEE, MMM d, yyyy h:mm a') + ' ' + from + ' wrote:';
            bodyRows = re.body.split('\n');
            bodyRows.forEach(function(row) {
                body += (!re.html) ? '
' + row : '';
            });
            $scope.body = body;
        }

        //
        // Editing
        //

        // generate key,iv for encryption preview
        var key = util.random(128),
            iv = util.random(128);

        $scope.updatePreview = function() {
            var body = $scope.body;
            // remove generated html from body
            body = parseBody(body);

            // Although this does encrypt live using AES, this is just for show. The plaintext is encrypted seperately before sending the email.
            var plaintext = ($scope.subject) ? $scope.subject + body : body;
            $scope.ciphertextPreview = (plaintext) ? aes.encrypt(plaintext, key, iv) : '';
        };

        $scope.sendEmail = function() {
            var to, body, email;

            // validate recipients
            to = $scope.to.replace(/\s/g, '').split(/[,;]/);
            if (!to || to.length < 1) {
                console.log('Seperate recipients with a comma!');
                return;
            }

            body = $scope.body;
            // remove generated html from body
            body = parseBody(body);

            email = {
                to: [], // list of receivers
                subject: $scope.subject, // Subject line
                body: body // plaintext body
            };
            email.from = [{
                name: '',
                address: emailDao._account.emailAddress
            }];
            to.forEach(function(address) {
                email.to.push({
                    name: '',
                    address: address
                });
            });

            emailDao.smtpSend(email, function(err) {
                if (err) {
                    console.log(err);
                    return;
                }

                if (window.chrome && chrome.app.window) {
                    // close the chrome window
                    chrome.app.window.current().close();
                    return;
                }
            });
        };
    };

    function parseBody(body) {
        function has(substr) {
            return (body.indexOf(substr) !== -1);
        }
        while (has('
')) {
            body = body.replace('
', '\n');
        }
        while (has('
')) {
            body = body.replace('
', '\n');
        }
        while (has('
')) {
            body = body.replace('
', '');
        }

        return body;
    }

    //
    // Directives
    //

    var ngModule = angular.module('write', []);
    ngModule.directive('contenteditable', function() {
        return {
            require: 'ngModel',
            link: function(scope, elm, attrs, ctrl) {
                // view -> model
                elm.on('keyup keydown', function() {
                    scope.$apply(function() {
                        ctrl.$setViewValue(elm.html());
                    });
                });

                // model -> view
                ctrl.$render = function() {
                    elm.html(ctrl.$viewValue);
                };

                // load init value from DOM
                ctrl.$setViewValue(elm.html());
            }
        };
    });

    ngModule.directive('focusMe', function($timeout) {
        return {
            link: function(scope, element) {
                $timeout(function() {
                    element[0].focus();
                });
            }
        };
    });

    return WriteCtrl;
});<|endoftext|>


<commit_before>define(
[
  'underscore',
  'jQuery'
],
function(_, $) { 'use strict';

/*
* Application controller.
*/
var MainController = function($scope, $filter, $modal, bookmarksStorage, appSettings, booleanSearchEngine1, omniboxEngine) {

  // Constant: default value of how many items we want to display on main page.
  var defaultTotalDisplayed = 20;

  $scope.searchText = ''; // Search text
  $scope.bookmarks = []; // All bookmarks
  $scope.filteredBookmarks = [];
  $scope.tags = []; // All tags
  $scope.orders = [ // Different sorting orders
                    {title:'Date', value: '-date'},
                    {title:'Title', value: 'title'},
                    {title:'URL', value: 'url'}
                  ];
  $scope.currentOrder = $scope.orders[0]; // date is default sorting order

  // Maximum number of items currently displayed
  $scope.totalDisplayed = defaultTotalDisplayed;

  $scope.selectedIndex = 0;

  $scope.hideTopLevelFolders = false;
  $scope.showThumbnails = true;

  omniboxEngine.init();

  // Auto add showing bookmarks when user scroll to page down
  var loadMorePlaceholder = $('#loadMorePlaceholder').get(0);
  $(window).scroll(function () {
    if ($scope.filteredBookmarks.length > $scope.totalDisplayed) {
      if (loadMorePlaceholder.getBoundingClientRect().top <= window.innerHeight) {
        $scope.totalDisplayed += defaultTotalDisplayed;
        $scope.$apply();
      }
    }
  });

  $(window).resize(function(){
    countItemsPerRow();
  });

  var getAllPanels = function() {
    return $('.list-bookmarks div.panel');
  };

  var countItemsPerRow = function() {
    var bookmarksList = angular.element('.list-bookmarks'),
    boxSize = bookmarksList.find('li:first-child').width(),
    bookmarksListW = bookmarksList.width(),
    perRow = Math.floor( bookmarksListW / boxSize);

    $scope.itemsPerRow = perRow;
  };

  // var isElementInViewport = function(el) {
  //   var rect = el.getBoundingClientRect();
  //   return rect.top >= 0 && rect.left >= 0 && rect.bottom <= $(window).height() && rect.right <= $(window).width();
  // };

  // Key down events handlers
  $('#mainContent').keydown(function(e) {
    if (e.isDefaultPrevented()) {
      return;
    }

    var updated = false;
    if (e.keyCode == 13 && e.metaKey) { // Enter press on page - go to the selected bookmark
      _gaq.push(['_trackEvent', 'Navigation', 'keydown', 'Navigation via enter']);

      // If first pattern is not our filter let's assume that user wants to search on this domain
      var match = /^(\w+)(\.\w+)?:(.+)/i.exec($scope.searchText);
      if (match && !_(['tag', 'url', 'title']).contains(match[1])) {
        window.location = 'https://' + match[1] + (match[2] || '.com') + '/?q=' + encodeURIComponent(match[3].trim());
      } else {
        var result = $scope.filteredBookmarks;
        if (result.length > $scope.selectedIndex) {
          window.location.href = $filter('orderBy')(result, $scope.currentOrder.value)[$scope.selectedIndex].url;
        }
      }
    } else if (e.which === 37) { // left arrow key
      if ($scope.selectedIndex > 0) {
        $scope.selectedIndex--;
        updated = true;
      }
    } else if (e.which === 39) { // right arrow key
      if (getAllPanels().length > $scope.selectedIndex + 1) {
        $scope.selectedIndex++;
        updated = true;
      }

    } else if (e.which === 9 && e.shiftKey) { // shift+tab key
      if ($scope.selectedIndex > 0) {
        $scope.selectedIndex--;
        updated = true;
      }

    } else if (e.which === 9) { // tab key
      if (getAllPanels().length > $scope.selectedIndex + 1) {
        $scope.selectedIndex++;
        updated = true;
      }
    } else if (e.which === 40) { // down key
      if (getAllPanels().length > $scope.selectedIndex + $scope.itemsPerRow) {
        $scope.selectedIndex += $scope.itemsPerRow;
        updated = true;
      }
    } else if (e.which === 38) { // up key
      if ($scope.selectedIndex - $scope.itemsPerRow >= 0) {
        $scope.selectedIndex -= $scope.itemsPerRow;
        updated = true;
      }
    }
    if (updated) { // right arrow, left arrow, down arrow, up arrow, tab, and shift+tab key pressed - select next element
      $scope.$apply();
      var panels = getAllPanels();
      var selectedElement = panels.get($scope.selectedIndex);
      if (selectedElement) {
        var rect = selectedElement.getBoundingClientRect(); // If element is not visible - scroll to it
        if (!(rect.top >= 0 && rect.left >= 0 && rect.bottom <= $(window).height() && rect.right <= $(window).width())) {
          $("body").stop().animate({
            scrollTop: ($(panels.get($scope.selectedIndex)).offset().top - $(panels.get(0)).offset().top)
          }, 500);
        }
      }
      return false;
    }
  });

  var loadBookmarks = function() {
    bookmarksStorage.getAll(function(bookmarks, setttings) {
      $scope.hideTopLevelFolders = appSettings.hideTopLevelFolders = setttings.hideTopLevelFolders;
      $scope.showThumbnails = appSettings.showThumbnails = setttings.showThumbnails;
      $scope.bookmarks = bookmarks;
      $scope.filteredBookmarks = bookmarks;

      $scope.tags = _.chain(bookmarks)
                      .map(function (item) { return item.tag; })
                      .flatten()
                      .groupBy(function(t){ return t.text; })
                      .map(function(tagsArray, text) {
                          return {tagText: text,  numberOfTags: tagsArray.length };
                      })
                      .value();

      // ARG: improve in future
      // applyTagsAsString(bookmarks);

      $scope.$apply();
      countItemsPerRow();
    }.bind(this));
  }.bind(this);
  loadBookmarks();

  // var applyTagsAsString = function(bookmarks){

  //     var separator = '|';
  //     _.each(bookmarks, function(item){

  //         item.tagsAsString = _.chain(item.tag)
  //                               .map(function(tag) { return tag.text; })
  //                               .join(separator)
  //                               .value();
  //         item.tagsAsString += separator;
  //     });
  // };

  // Set maximum total displayed items to default and scroll to top of the page
  var resetView = function() {
    $scope.totalDisplayed = defaultTotalDisplayed;
    $scope.selectedIndex = 0;
    setTimeout(function() {
      window.scroll(0, 0);
    }, 10);
  };

  var updateTagsInfo = function(updatedTags, originalTags){
    var newTags = _.difference(updatedTags, originalTags);
    var deletedTags = _.difference(originalTags, updatedTags);

    _.each(newTags, function(item){
        var existingTag = _.find($scope.tags, function(t){return t.tagText == item; });
        if(_.isUndefined(existingTag)){
            $scope.tags.push({tagText: item, numberOfTags: 1, custom: true});
        }
        else{
            existingTag.numberOfTags++;
        }
    });

    _.each(deletedTags, function(item){
        var existingTag = _.find($scope.tags, function(t){return t.tagText == item; });
        if(!_.isUndefined(existingTag)){
          if(existingTag.numberOfTags > 1) {
              existingTag.numberOfTags--;
          }
          else{
              $scope.tags.splice(_.indexOf($scope.tags, existingTag), 1);
          }
        }
    });
  };

  // When user change search string we scroll to top of the page and set total displayed items to default
  $scope.$watch('searchText', function() {
    $scope.filteredBookmarks =
      _.filter(
        $scope.bookmarks,
        function(bookmark){
          return booleanSearchEngine.filterBookmark(bookmark, $scope.searchText);
        }
      );
    resetView();
  });

  // On tag click we set search text
  $scope.selectTag = function(tag) {
    _gaq.push(['_trackEvent', 'Navigation', 'selectTag']);
    $scope.searchText = 'tag:' + tag;
  };

  // Change sorting order
  $scope.changeOrder = function(order) {
    _gaq.push(['_trackEvent', 'Navigation', 'changeOrder',  'Change order to ' + order]);
    $scope.currentOrder = order;
    resetView();
  };

  // Show modal dialog for adding tags
  $scope.editBookmark = function(bookmark) {
    _gaq.push(['_trackEvent', 'Navigation', 'editBookmark']);

    var originalBookmark = _.clone(bookmark);

    $(".nav-wrap, .grid").addClass("scale-blur");

    var modalInstance = $modal.open({
      templateUrl: 'partials/editBookmark.tpl.html',
      controller: 'editBookmarkController',
      resolve: {
        bookmark: function() {
          return bookmark;
        }
      },
      keyboard: true,
      backdrop: false
    });

    modalInstance.result.then(function (updatedBookmark) {
      var updatedTags = [];
      if(!_.isNull(updatedBookmark)){
        updatedTags = _.map(updatedBookmark.tag, function(item) { return item.text; });
      }
      var originalTags = _.map(originalBookmark.tag, function(item) { return item.text; });
      updateTagsInfo(updatedTags, originalTags);

      if (!updatedBookmark) {
        // Bookmark was deleted
        $scope.bookmarks.splice(_.indexOf($scope.bookmarks, bookmark), 1);
      }
       $(".nav-wrap, .grid").removeClass("scale-blur");
    }, function() {
       $(".nav-wrap, .grid").removeClass("scale-blur");
    });

    return false;
  };

  $scope.selectBookmark = function(index) {
    $scope.selectedIndex = index;
  };

  $scope.setHideTopLevelFolders = function() {
    _gaq.push(['_trackEvent', 'ChangeSettings', 'HideTopLevelFolders changed to ' + !$scope.hideTopLevelFolders]);
    bookmarksStorage.setHideTopLevelFolders(!$scope.hideTopLevelFolders, loadBookmarks);
  };

  $scope.setShowThumbnails = function() {
    _gaq.push(['_trackEvent', 'ChangeSettings', 'ShowThumbnails changed to ' + !$scope.showThumbnails]);
    bookmarksStorage.setShowThumbnails(!$scope.showThumbnails, loadBookmarks);
  };

  $scope.getTypeheadSuggestions = function($viewValue) {

    return booleanSearchEngine.getFilteredBookmarks($scope.bookmarks, $viewValue, $scope.tags);
  };

  $scope.toggleSettings = function() {
    $( ".grid, .nav-wrap" ).toggleClass( "scale-blur" );
    $( ".settings" ).toggleClass( "open" );
    $( "body" ).toggleClass( "no-scroll" );
  };
};

return [
  '$scope',
  '$filter',
  '$modal',
  'bookmarksStorage',
  'appSettings',
  'booleanSearchEngine',
  'omniboxEngine',
  MainController
];

});

<commit_msg>fix bug at main ctrl with incorrect service name<commit_after>define(
[
  'underscore',
  'jQuery'
],
function(_, $) { 'use strict';

/*
* Application controller.
*/
var MainController = function($scope, $filter, $modal, bookmarksStorage, appSettings, booleanSearchEngine, omniboxEngine) {

  // Constant: default value of how many items we want to display on main page.
  var defaultTotalDisplayed = 20;

  $scope.searchText = ''; // Search text
  $scope.bookmarks = []; // All bookmarks
  $scope.filteredBookmarks = [];
  $scope.tags = []; // All tags
  $scope.orders = [ // Different sorting orders
                    {title:'Date', value: '-date'},
                    {title:'Title', value: 'title'},
                    {title:'URL', value: 'url'}
                  ];
  $scope.currentOrder = $scope.orders[0]; // date is default sorting order

  // Maximum number of items currently displayed
  $scope.totalDisplayed = defaultTotalDisplayed;

  $scope.selectedIndex = 0;

  $scope.hideTopLevelFolders = false;
  $scope.showThumbnails = true;

  omniboxEngine.init();

  // Auto add showing bookmarks when user scroll to page down
  var loadMorePlaceholder = $('#loadMorePlaceholder').get(0);
  $(window).scroll(function () {
    if ($scope.filteredBookmarks.length > $scope.totalDisplayed) {
      if (loadMorePlaceholder.getBoundingClientRect().top <= window.innerHeight) {
        $scope.totalDisplayed += defaultTotalDisplayed;
        $scope.$apply();
      }
    }
  });

  $(window).resize(function(){
    countItemsPerRow();
  });

  var getAllPanels = function() {
    return $('.list-bookmarks div.panel');
  };

  var countItemsPerRow = function() {
    var bookmarksList = angular.element('.list-bookmarks'),
    boxSize = bookmarksList.find('li:first-child').width(),
    bookmarksListW = bookmarksList.width(),
    perRow = Math.floor( bookmarksListW / boxSize);

    $scope.itemsPerRow = perRow;
  };

  // var isElementInViewport = function(el) {
  //   var rect = el.getBoundingClientRect();
  //   return rect.top >= 0 && rect.left >= 0 && rect.bottom <= $(window).height() && rect.right <= $(window).width();
  // };

  // Key down events handlers
  $('#mainContent').keydown(function(e) {
    if (e.isDefaultPrevented()) {
      return;
    }

    var updated = false;
    if (e.keyCode == 13 && e.metaKey) { // Enter press on page - go to the selected bookmark
      _gaq.push(['_trackEvent', 'Navigation', 'keydown', 'Navigation via enter']);

      // If first pattern is not our filter let's assume that user wants to search on this domain
      var match = /^(\w+)(\.\w+)?:(.+)/i.exec($scope.searchText);
      if (match && !_(['tag', 'url', 'title']).contains(match[1])) {
        window.location = 'https://' + match[1] + (match[2] || '.com') + '/?q=' + encodeURIComponent(match[3].trim());
      } else {
        var result = $scope.filteredBookmarks;
        if (result.length > $scope.selectedIndex) {
          window.location.href = $filter('orderBy')(result, $scope.currentOrder.value)[$scope.selectedIndex].url;
        }
      }
    } else if (e.which === 37) { // left arrow key
      if ($scope.selectedIndex > 0) {
        $scope.selectedIndex--;
        updated = true;
      }
    } else if (e.which === 39) { // right arrow key
      if (getAllPanels().length > $scope.selectedIndex + 1) {
        $scope.selectedIndex++;
        updated = true;
      }

    } else if (e.which === 9 && e.shiftKey) { // shift+tab key
      if ($scope.selectedIndex > 0) {
        $scope.selectedIndex--;
        updated = true;
      }

    } else if (e.which === 9) { // tab key
      if (getAllPanels().length > $scope.selectedIndex + 1) {
        $scope.selectedIndex++;
        updated = true;
      }
    } else if (e.which === 40) { // down key
      if (getAllPanels().length > $scope.selectedIndex + $scope.itemsPerRow) {
        $scope.selectedIndex += $scope.itemsPerRow;
        updated = true;
      }
    } else if (e.which === 38) { // up key
      if ($scope.selectedIndex - $scope.itemsPerRow >= 0) {
        $scope.selectedIndex -= $scope.itemsPerRow;
        updated = true;
      }
    }
    if (updated) { // right arrow, left arrow, down arrow, up arrow, tab, and shift+tab key pressed - select next element
      $scope.$apply();
      var panels = getAllPanels();
      var selectedElement = panels.get($scope.selectedIndex);
      if (selectedElement) {
        var rect = selectedElement.getBoundingClientRect(); // If element is not visible - scroll to it
        if (!(rect.top >= 0 && rect.left >= 0 && rect.bottom <= $(window).height() && rect.right <= $(window).width())) {
          $("body").stop().animate({
            scrollTop: ($(panels.get($scope.selectedIndex)).offset().top - $(panels.get(0)).offset().top)
          }, 500);
        }
      }
      return false;
    }
  });

  var loadBookmarks = function() {
    bookmarksStorage.getAll(function(bookmarks, setttings) {
      $scope.hideTopLevelFolders = appSettings.hideTopLevelFolders = setttings.hideTopLevelFolders;
      $scope.showThumbnails = appSettings.showThumbnails = setttings.showThumbnails;
      $scope.bookmarks = bookmarks;
      $scope.filteredBookmarks = bookmarks;

      $scope.tags = _.chain(bookmarks)
                      .map(function (item) { return item.tag; })
                      .flatten()
                      .groupBy(function(t){ return t.text; })
                      .map(function(tagsArray, text) {
                          return {tagText: text,  numberOfTags: tagsArray.length };
                      })
                      .value();

      // ARG: improve in future
      // applyTagsAsString(bookmarks);

      $scope.$apply();
      countItemsPerRow();
    }.bind(this));
  }.bind(this);
  loadBookmarks();

  // var applyTagsAsString = function(bookmarks){

  //     var separator = '|';
  //     _.each(bookmarks, function(item){

  //         item.tagsAsString = _.chain(item.tag)
  //                               .map(function(tag) { return tag.text; })
  //                               .join(separator)
  //                               .value();
  //         item.tagsAsString += separator;
  //     });
  // };

  // Set maximum total displayed items to default and scroll to top of the page
  var resetView = function() {
    $scope.totalDisplayed = defaultTotalDisplayed;
    $scope.selectedIndex = 0;
    setTimeout(function() {
      window.scroll(0, 0);
    }, 10);
  };

  var updateTagsInfo = function(updatedTags, originalTags){
    var newTags = _.difference(updatedTags, originalTags);
    var deletedTags = _.difference(originalTags, updatedTags);

    _.each(newTags, function(item){
        var existingTag = _.find($scope.tags, function(t){return t.tagText == item; });
        if(_.isUndefined(existingTag)){
            $scope.tags.push({tagText: item, numberOfTags: 1, custom: true});
        }
        else{
            existingTag.numberOfTags++;
        }
    });

    _.each(deletedTags, function(item){
        var existingTag = _.find($scope.tags, function(t){return t.tagText == item; });
        if(!_.isUndefined(existingTag)){
          if(existingTag.numberOfTags > 1) {
              existingTag.numberOfTags--;
          }
          else{
              $scope.tags.splice(_.indexOf($scope.tags, existingTag), 1);
          }
        }
    });
  };

  // When user change search string we scroll to top of the page and set total displayed items to default
  $scope.$watch('searchText', function() {
    $scope.filteredBookmarks =
      _.filter(
        $scope.bookmarks,
        function(bookmark){
          return booleanSearchEngine.filterBookmark(bookmark, $scope.searchText);
        }
      );
    resetView();
  });

  // On tag click we set search text
  $scope.selectTag = function(tag) {
    _gaq.push(['_trackEvent', 'Navigation', 'selectTag']);
    $scope.searchText = 'tag:' + tag;
  };

  // Change sorting order
  $scope.changeOrder = function(order) {
    _gaq.push(['_trackEvent', 'Navigation', 'changeOrder',  'Change order to ' + order]);
    $scope.currentOrder = order;
    resetView();
  };

  // Show modal dialog for adding tags
  $scope.editBookmark = function(bookmark) {
    _gaq.push(['_trackEvent', 'Navigation', 'editBookmark']);

    var originalBookmark = _.clone(bookmark);

    $(".nav-wrap, .grid").addClass("scale-blur");

    var modalInstance = $modal.open({
      templateUrl: 'partials/editBookmark.tpl.html',
      controller: 'editBookmarkController',
      resolve: {
        bookmark: function() {
          return bookmark;
        }
      },
      keyboard: true,
      backdrop: false
    });

    modalInstance.result.then(function (updatedBookmark) {
      var updatedTags = [];
      if(!_.isNull(updatedBookmark)){
        updatedTags = _.map(updatedBookmark.tag, function(item) { return item.text; });
      }
      var originalTags = _.map(originalBookmark.tag, function(item) { return item.text; });
      updateTagsInfo(updatedTags, originalTags);

      if (!updatedBookmark) {
        // Bookmark was deleted
        $scope.bookmarks.splice(_.indexOf($scope.bookmarks, bookmark), 1);
      }
       $(".nav-wrap, .grid").removeClass("scale-blur");
    }, function() {
       $(".nav-wrap, .grid").removeClass("scale-blur");
    });

    return false;
  };

  $scope.selectBookmark = function(index) {
    $scope.selectedIndex = index;
  };

  $scope.setHideTopLevelFolders = function() {
    _gaq.push(['_trackEvent', 'ChangeSettings', 'HideTopLevelFolders changed to ' + !$scope.hideTopLevelFolders]);
    bookmarksStorage.setHideTopLevelFolders(!$scope.hideTopLevelFolders, loadBookmarks);
  };

  $scope.setShowThumbnails = function() {
    _gaq.push(['_trackEvent', 'ChangeSettings', 'ShowThumbnails changed to ' + !$scope.showThumbnails]);
    bookmarksStorage.setShowThumbnails(!$scope.showThumbnails, loadBookmarks);
  };

  $scope.getTypeheadSuggestions = function($viewValue) {

    return booleanSearchEngine.getFilteredBookmarks($scope.bookmarks, $viewValue, $scope.tags);
  };

  $scope.toggleSettings = function() {
    $( ".grid, .nav-wrap" ).toggleClass( "scale-blur" );
    $( ".settings" ).toggleClass( "open" );
    $( "body" ).toggleClass( "no-scroll" );
  };
};

return [
  '$scope',
  '$filter',
  '$modal',
  'bookmarksStorage',
  'appSettings',
  'booleanSearchEngine',
  'omniboxEngine',
  MainController
];

});

<|endoftext|>


<commit_before>Ext.namespace('Gemma');

/**
 * need to set geneId as config
 */
Gemma.GeneDetails =  Ext.extend(Ext.Panel, {

	height: 600,
	padding:10,
	defaults:{
		border:false,
		flex:0
	},
	layoutConfig:{
		align:'stretch'
	},
	layout:'vbox',
	renderHomologues: function(homologues, mainGeneSymbol){
		var homologueStr = '';
		var j, homologue;
		for (j = 0; j < homologues.length; j++) {
			homologue = homologues[j];
				homologueStr += "" +
				homologue.officialSymbol +
				" [" +
				homologue.taxonCommonName +
				"]   ";
		}
		if(homologueStr === ''){
			homologueStr = "No aliases defined";
		}
		return homologueStr;
	},
	renderGeneSets:function(geneSets){
		var geneSetBtns = [];
		var i, geneSet;
		for(i=0;i<geneSets.length;i++){
			geneSet = geneSets[i];
			geneSetBtns.push({
				xtype:'button',
				text: geneSet.name,
				ctCls : 'right-align-btn transparent-btn transparent-btn-link',
				handler: function(){
					console.log(geneSet);
					var grid = new Gemma.GeneMembersSaveGrid({
						geneGroupId : geneSet.id,
						selectedGeneGroup : geneSet,
						groupName : geneSet.name,
						taxonId : geneSet.taxonId,
						taxonName : geneSet.taxonName,
						geneIds: geneSet.geneIds,
						hideHeaders: true,
						frame:false,
						allowSaveToSession:false
					});

					var win = new Ext.Window({
								// id : 'geneSelectionEditorWindow',
								// closeAction: 'hide',
								closable : false,
								layout : 'fit',
								width : 450,
								height : 500,
								items : grid,
								title : geneSet.name
							});
					grid.on('doneModification', function() {
						win.hide();
					}, this);
					win.show();

				}.createDelegate(this)
			});
		}
		if(geneSetBtns.length === 0){
			geneSetBtns.push({html: 'Not currently a member of any gene group', border:false});
		}
		return geneSetBtns;
	},
	initComponent: function(){
		Gemma.GeneDetails.superclass.initComponent.call(this);

		this.on('render', function(){
			if (!this.loadMask) {
				this.loadMask = new Ext.LoadMask(this.getEl(), {
					msg: "Loading ...",
					msgCls: 'absolute-position-loading-mask ext-el-mask-msg x-mask-loading'
				});
			}
			this.loadMask.show();
			GeneController.loadGeneDetails(this.geneId, function(geneDetails){

			this.loadMask.hide();
				this.add([
				{
						html: '
' + geneDetails.name + '
' +
						geneDetails.officialName +
						'

'
					}, {
						layout: 'form',
						defaults: {
							border: false
						},
						items: [{
							fieldLabel: 'Taxon',
							html: geneDetails.taxonCommonName
						}, {
							fieldLabel: 'Aliases',
							html: geneDetails.aliases.join(', ') + ' '
						}, {
							fieldLabel: 'Homolgues',
							html: this.renderHomologues(geneDetails.homologues, geneDetails.name)
						}, {
							fieldLabel: 'Gene Groups',
							layout:'hbox',
							items: this.renderGeneSets(geneDetails.geneSets)
						}, {
							fieldLabel: 'Probes' + '' +
							' ',
							html: geneDetails.compositeSequenceCount + ' ' +
							' '
						}, {
							fieldLabel: 'Notes',
							html: geneDetails.description
						}]
					}, {
						html: '
Gene Ontology Terms
'
					}, {
						layout: 'fit', // need extra panel level to make grid resize with window
						flex:1,
						items: {
							xtype: 'genegogrid',
							border: true,
							geneid: this.geneId
						//,height: 200
						}
				}]);
				this.doLayout();
			}.createDelegate(this));
		});
	}
});<commit_msg>trying to fix bug where gene set pop-up windows from gene details page always show the same group<commit_after>Ext.namespace('Gemma');

/**
 * need to set geneId as config
 */
Gemma.GeneDetails =  Ext.extend(Ext.Panel, {

	height: 600,
	padding:10,
	defaults:{
		border:false,
		flex:0
	},
	layoutConfig:{
		align:'stretch'
	},
	layout:'vbox',
	renderHomologues: function(homologues, mainGeneSymbol){
		var homologueStr = '';
		var j, homologue;
		for (j = 0; j < homologues.length; j++) {
			homologue = homologues[j];
				homologueStr += "" +
				homologue.officialSymbol +
				" [" +
				homologue.taxonCommonName +
				"]   ";
		}
		if(homologueStr === ''){
			homologueStr = "No aliases defined";
		}
		return homologueStr;
	},

	renderGeneSets:function(geneSets){
		var geneSetBtns = [];
		var i, geneSet;
		for(i=0;i<geneSets.length;i++){
			geneSetBtns.push({
				xtype:'button',
				text: geneSet.name,
				ctCls : 'right-align-btn transparent-btn transparent-btn-link',
				geneSet: geneSets[i],
				listeners: {
					click: function(){
						var grid = new Gemma.GeneMembersSaveGrid({
							geneGroupId: this.geneSet.id,
							selectedGeneGroup: this.geneSet,
							groupName: this.geneSet.name,
							taxonId: this.geneSet.taxonId,
							taxonName: this.geneSet.taxonName,
							geneIds: this.geneSet.geneIds,
							hideHeaders: true,
							frame: false,
							allowSaveToSession: false
						});

						var win = new Ext.Window({
							closable: false,
							layout: 'fit',
							width: 450,
							height: 500,
							items: grid,
							title: this.geneSet.name
						});
						grid.on('doneModification', function(){
							win.close();
						}, this);
						win.show();
					}
				}
			});
		}
		if(geneSetBtns.length === 0){
			geneSetBtns.push({html: 'Not currently a member of any gene group', border:false});
		}
		return geneSetBtns;
	},
	initComponent: function(){
		Gemma.GeneDetails.superclass.initComponent.call(this);

		this.on('render', function(){
			if (!this.loadMask) {
				this.loadMask = new Ext.LoadMask(this.getEl(), {
					msg: "Loading ...",
					msgCls: 'absolute-position-loading-mask ext-el-mask-msg x-mask-loading'
				});
			}
			this.loadMask.show();
			GeneController.loadGeneDetails(this.geneId, function(geneDetails){

			this.loadMask.hide();
				this.add([
				{
						html: '
' + geneDetails.name + '
' +
						geneDetails.officialName +
						'

'
					}, {
						layout: 'form',
						defaults: {
							border: false
						},
						items: [{
							fieldLabel: 'Taxon',
							html: geneDetails.taxonCommonName
						}, {
							fieldLabel: 'Aliases',
							html: geneDetails.aliases.join(', ') + ' '
						}, {
							fieldLabel: 'Homolgues',
							html: this.renderHomologues(geneDetails.homologues, geneDetails.name)
						}, {
							fieldLabel: 'Gene Groups',
							layout:'hbox',
							items: this.renderGeneSets(geneDetails.geneSets)
						}, {
							fieldLabel: 'Probes' + '' +
							' ',
							html: geneDetails.compositeSequenceCount + ' ' +
							' '
						}, {
							fieldLabel: 'Notes',
							html: geneDetails.description
						}]
					}, {
						html: '
Gene Ontology Terms
'
					}, {
						layout: 'fit', // need extra panel level to make grid resize with window
						flex:1,
						items: {
							xtype: 'genegogrid',
							border: true,
							geneid: this.geneId
						//,height: 200
						}
				}]);
				this.doLayout();
			}.createDelegate(this));
		});
	}
});<|endoftext|>


<commit_before>// Start here.

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;

var onInitFs = function(fs) {

  	fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
	    fileEntry.createWriter(function(fileWriter) {
	      	var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});

	      	fileWriter.write(blob);
  		});
  	}, errorHandler);
};

$('#writeToFile').on('click', function() {
	window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorHandler);
});

var errorHandler = function(e) {
	var msg = '';

  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  alert('Error: ' + msg);

};<commit_msg>display url.<commit_after>// Start here.

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;

var onInitFs = function(fs) {

  	fs.root.getFile('log.txt', {create: true, exclusive: false}, function(fileEntry) {
	    fileEntry.createWriter(function(fileWriter) {
	      	var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});

	      	fileWriter.write(blob);
  		});
  		alert("url:" + fileEntry.toURL());
  	}, errorHandler);
};

$('#writeToFile').on('click', function() {
	window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorHandler);
});

var errorHandler = function(e) {
	var msg = '';

  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  	alert('Error: ' + msg);

};<|endoftext|>


<commit_before>;(function() {
"use strict"

var $ = document.querySelectorAll.bind(document)

// --- DOM elements ---------------------------------------

var $diskSlot = $('#slot')[0]
var $powerSwitch = $('#power-switch')[0]
var $filesScript = $('#files')[0]
var $groveWorkerScript = $('#grove-worker')[0]
var $modalOverlay = $('#overlay')[0]
var $hideDataEditorButton = $('#file-modal .close-button button')[0]
var $showDataEditorButton = $('#data-editor-button')[0]
var $entryNameInput = $('#file-modal .file-selector input')[0]
var $entryContentInput = $('#file-modal textarea')[0]
var $dataEditorSaveButton = $('#file-modal .save')[0]
var $title = $('head title')[0]

// --- Initial state --------------------------------------

var dataRecords = FILES
var lastSaveTimestamp = +(new Date())
var groveWorker = GroveWorker(
  dataRecords,
  handleMessageFromWorker)

setTitleTo(getComputerName(dataRecords))

// --- Event handler setup --------------------------------

click($diskSlot, function() {
  $filesScript.innerText
    = 'var FILES = ' + JSON.stringify(dataRecords)

  var pageData = document.documentElement.outerHTML
  var blob = new Blob([pageData], {type: 'text/html'})
  saveAs(blob, createFilename(getComputerName(dataRecords)))
  lastSaveTimestamp = +(new Date())
})

click($showDataEditorButton, function() {
  $modalOverlay.style.display = 'block';
  $entryNameInput.focus()
})

click($hideDataEditorButton, function() {
  $modalOverlay.style.display = 'none';
})

click($dataEditorSaveButton, function() {
  var name    = $entryNameInput.value
  var content = $entryContentInput.value

  if (!name) return

  dataRecords[name] = content

  groveWorker.postMessage({
    type: 'updateDataRecord',
    name: name,
    content: content
  })
})

click($powerSwitch, function() {
  if (groveWorker) {
    // turn off
    groveWorker.terminate()
    groveWorker = null
    redraw([])
  } else {
    // turn on
    groveWorker = GroveWorker(dataRecords, handleMessageFromWorker)
  }
})

window.addEventListener('beforeunload', function(e) {
  if (shouldWarnAboutUnsavedChanges()) {
    // This message isn't shown in Chrome but it might be in other browsers.
    return e.returnValue = "You have unsaved changes. Are you sure you want to leave?"
  }
})

window.addEventListener('keydown', function(e) {
  if (groveWorker) { // TODO refactor to null object pattern
    groveWorker.postMessage({type: 'keyDown', event: {keyCode: e.keyCode}})
  }
})

window.addEventListener('keyup', function(e) {
  if (groveWorker) {
    groveWorker.postMessage({type: 'keyUp', event: {keyCode: e.keyCode}})
  }
})

// --- Function definitions -------------------------------

function handleMessageFromWorker(msg) {
  switch (msg.data.type) {
    case 'redraw':
      redraw(msg.data.value)
      break
    case 'dataRecordChange':
      dataRecords[msg.data.name] = msg.data.content
      setTitleTo(getComputerName(dataRecords))
      break
  }
}

function GroveWorker(dataRecords, messageCallback) {
  var scriptBlob = new Blob([
    'var FILES = ',
    JSON.stringify(dataRecords),
    ';',
    $groveWorkerScript.innerText
  ])

  var worker = new Worker(URL.createObjectURL(scriptBlob))
  worker.addEventListener('message', messageCallback)
  return worker
}

function click(elem, callback) {
  elem.addEventListener('click', callback)
}

function setTitleTo(title) {
  $title.innerText = title
}

function redraw(text) {
  var lines = $('#terminal p')
  for (var i = 0; i < lines.length; i++) {
    lines[i].innerHTML = text[i] || ''
  }
}

function createFilename(computerName) {
  var date = new Date()
  return computerName + '-' + formatDateForFilename(date)
}

function shouldWarnAboutUnsavedChanges() {
  return +(new Date()) - lastSaveTimestamp > 30 * 1000
}

})();
<commit_msg>Remove TODO comment<commit_after>;(function() {
"use strict"

var $ = document.querySelectorAll.bind(document)

// --- DOM elements ---------------------------------------

var $diskSlot = $('#slot')[0]
var $powerSwitch = $('#power-switch')[0]
var $filesScript = $('#files')[0]
var $groveWorkerScript = $('#grove-worker')[0]
var $modalOverlay = $('#overlay')[0]
var $hideDataEditorButton = $('#file-modal .close-button button')[0]
var $showDataEditorButton = $('#data-editor-button')[0]
var $entryNameInput = $('#file-modal .file-selector input')[0]
var $entryContentInput = $('#file-modal textarea')[0]
var $dataEditorSaveButton = $('#file-modal .save')[0]
var $title = $('head title')[0]

// --- Initial state --------------------------------------

var dataRecords = FILES
var lastSaveTimestamp = +(new Date())
var groveWorker = GroveWorker(
  dataRecords,
  handleMessageFromWorker)

setTitleTo(getComputerName(dataRecords))

// --- Event handler setup --------------------------------

click($diskSlot, function() {
  $filesScript.innerText
    = 'var FILES = ' + JSON.stringify(dataRecords)

  var pageData = document.documentElement.outerHTML
  var blob = new Blob([pageData], {type: 'text/html'})
  saveAs(blob, createFilename(getComputerName(dataRecords)))
  lastSaveTimestamp = +(new Date())
})

click($showDataEditorButton, function() {
  $modalOverlay.style.display = 'block';
  $entryNameInput.focus()
})

click($hideDataEditorButton, function() {
  $modalOverlay.style.display = 'none';
})

click($dataEditorSaveButton, function() {
  var name    = $entryNameInput.value
  var content = $entryContentInput.value

  if (!name) return

  dataRecords[name] = content

  groveWorker.postMessage({
    type: 'updateDataRecord',
    name: name,
    content: content
  })
})

click($powerSwitch, function() {
  if (groveWorker) {
    // turn off
    groveWorker.terminate()
    groveWorker = null
    redraw([])
  } else {
    // turn on
    groveWorker = GroveWorker(dataRecords, handleMessageFromWorker)
  }
})

window.addEventListener('beforeunload', function(e) {
  if (shouldWarnAboutUnsavedChanges()) {
    // This message isn't shown in Chrome but it might be in other browsers.
    return e.returnValue = "You have unsaved changes. Are you sure you want to leave?"
  }
})

window.addEventListener('keydown', function(e) {
  if (groveWorker) {
    groveWorker.postMessage({type: 'keyDown', event: {keyCode: e.keyCode}})
  }
})

window.addEventListener('keyup', function(e) {
  if (groveWorker) {
    groveWorker.postMessage({type: 'keyUp', event: {keyCode: e.keyCode}})
  }
})

// --- Function definitions -------------------------------

function handleMessageFromWorker(msg) {
  switch (msg.data.type) {
    case 'redraw':
      redraw(msg.data.value)
      break
    case 'dataRecordChange':
      dataRecords[msg.data.name] = msg.data.content
      setTitleTo(getComputerName(dataRecords))
      break
  }
}

function GroveWorker(dataRecords, messageCallback) {
  var scriptBlob = new Blob([
    'var FILES = ',
    JSON.stringify(dataRecords),
    ';',
    $groveWorkerScript.innerText
  ])

  var worker = new Worker(URL.createObjectURL(scriptBlob))
  worker.addEventListener('message', messageCallback)
  return worker
}

function click(elem, callback) {
  elem.addEventListener('click', callback)
}

function setTitleTo(title) {
  $title.innerText = title
}

function redraw(text) {
  var lines = $('#terminal p')
  for (var i = 0; i < lines.length; i++) {
    lines[i].innerHTML = text[i] || ''
  }
}

function createFilename(computerName) {
  var date = new Date()
  return computerName + '-' + formatDateForFilename(date)
}

function shouldWarnAboutUnsavedChanges() {
  return +(new Date()) - lastSaveTimestamp > 30 * 1000
}

})();
<|endoftext|>


<commit_before>function showLegend() {
	document.getElementById("legend").className = "show-legend";
	}
function hideLegend() {
	document.getElementById("legend").className = "hide-legend";
	}
<commit_msg>Delete legend.js<commit_after><|endoftext|>


<commit_before>(function () {
  'use strict';
  var gulp = require('gulp');
  var $ = require('gulp-load-plugins')();
  var opn = require('opn');
  var del = require('del');

  var lintSrc = ['./gulpfile.js', './index.js', 'test/**/*.js', 'bin/*.js'];
  var testSrc = ['test/*helper.js', 'test/*spec.js'];

  function runCoverage (opts) {
    return gulp.src(testSrc, { read: false })
      .pipe($.coverage.instrument({
        pattern: ['./index.js'],
        debugDirectory: 'debug'}))
      .pipe($.plumber())
      .pipe($.mocha({reporter: 'dot'})
            .on('error', function () { this.emit('end'); })) // test errors dropped
      .pipe($.plumber.stop())
      .pipe($.coverage.gather())
      .pipe($.coverage.format(opts));
  }

  gulp.task("clean", function (done) {
    del(["coverage.html", "debug/**/*", "debug"], done);
  });

  gulp.task("lint", function () {
    return gulp.src(lintSrc)
      .pipe($.jshint())
      .pipe($.jshint.reporter(require('jshint-table-reporter')));
  });

  gulp.task('coveralls', ['clean'], function () {
    return runCoverage({reporter: 'lcov'})
      .pipe($.coveralls());
  });

  gulp.task('coverage', ['clean'], function () {
    return runCoverage({outFile: './coverage.html'})
      .pipe(gulp.dest('./'))
      .on('end', function () {
        opn('./coverage.html');
      });
  });

  gulp.task("test", ['clean', 'lint'], function () {
    return gulp.src(testSrc, { read: false })
      .pipe($.plumber())
      .pipe($.mocha({reporter: 'spec', globals: ['expect', 'should']}))
      .pipe($.plumber.stop());
  });

  gulp.task("watch", function () {
    gulp.watch(lintSrc, ['test']);
  });

  gulp.task("default", ["test"]);
})();
<commit_msg>add onerror for test, failing tests would not move to rebuild when watching.<commit_after>(function () {
  'use strict';
  var gulp = require('gulp');
  var $ = require('gulp-load-plugins')();
  var opn = require('opn');
  var del = require('del');

  var lintSrc = ['./gulpfile.js', './index.js', 'test/**/*.js', 'bin/*.js'];
  var testSrc = ['test/*helper.js', 'test/*spec.js'];

  function runCoverage (opts) {
    return gulp.src(testSrc, { read: false })
      .pipe($.coverage.instrument({
        pattern: ['./index.js'],
        debugDirectory: 'debug'}))
      .pipe($.plumber())
      .pipe($.mocha({reporter: 'dot'})
            .on('error', function () { this.emit('end'); })) // test errors dropped
      .pipe($.plumber.stop())
      .pipe($.coverage.gather())
      .pipe($.coverage.format(opts));
  }

  gulp.task("clean", function (done) {
    del(["coverage.html", "debug/**/*", "debug"], done);
  });

  gulp.task("lint", function () {
    return gulp.src(lintSrc)
      .pipe($.jshint())
      .pipe($.jshint.reporter(require('jshint-table-reporter')));
  });

  gulp.task('coveralls', ['clean'], function () {
    return runCoverage({reporter: 'lcov'})
      .pipe($.coveralls());
  });

  gulp.task('coverage', ['clean'], function () {
    return runCoverage({outFile: './coverage.html'})
      .pipe(gulp.dest('./'))
      .on('end', function () {
        opn('./coverage.html');
      });
  });

  gulp.task("test", ['clean', 'lint'], function () {
    return gulp.src(testSrc, { read: false })
      .pipe($.plumber())
      .pipe($.mocha({reporter: 'spec', globals: ['expect', 'should']})
           .on('error', function () { this.emit('end'); }))
      .pipe($.plumber.stop());
  });

  gulp.task("watch", function () {
    gulp.watch(lintSrc, ['test']);
  });

  gulp.task("default", ["test"]);
})();
<|endoftext|>