<commit_before>'use babel'
/** @jsx vanilla.jsx */
import vanilla from 'vanilla-jsx'
import Clipboard from 'clipboard'
// TODO: ^- when atom updates to a never version of Electron, change this to `require('electron').Clipboard`

export function createPanel() {
  const icons = {
    MIN: '🗕',
    MAX: '🗖'
  }
  let el

  const toggleContent = function() {
    if (el.refs.content.classList.contains('hidden')) {
      this.textContent = icons.MIN
      el.refs.content.classList.remove('hidden')
    } else {
      this.textContent = icons.MAX
      el.refs.content.classList.add('hidden')
    }
  }
  const setCount = function(count) {
    if (count) {
      this.classList.remove('status-success')
      this.classList.add('status-error')
      this.childNodes[0].classList.remove('icon-check')
      this.childNodes[0].classList.add('icon-x')

      this.childNodes[1].textContent = count === 1 ? '1 Issue' : `${count} Issues`
    } else {
      this.classList.remove('status-error')
      this.classList.add('status-success')
      this.childNodes[0].classList.remove('icon-x')
      this.childNodes[0].classList.add('icon-check')

      this.childNodes[1].textContent = 'No Issues'
    }
  }

  el = <linter-new-panel tabindex="-1">

          Linter

          <linter-bottom-status class="status-success">
             No Issues
          </linter-bottom-status>

          {icons.MIN}
          ✖

  </linter-new-panel>

  el.refs = {}
  el.refs.content = el.querySelector('.panel-body')
  el.refs.counts = el.querySelector('.heading-status')
  el.refs.status = el.querySelector('linter-bottom-status')
  el.refs.hide = el.querySelector('.panel-button-hide')

  el.addEventListener('keydown', function(e) {
    if (e.which === 67 && e.ctrlKey) {
      Clipboard.writeText(getSelection().toString())
    }
  })
  el.refs.status.setCount = setCount

  return el
}
<commit_msg>:new: Use the new vanilla-jsx feature<commit_after>'use babel'
/** @jsx vanilla.jsx */
import vanilla from 'vanilla-jsx'
import Clipboard from 'clipboard'
// TODO: ^- when atom updates to a never version of Electron, change this to `require('electron').Clipboard`

export function createPanel() {
  const icons = {
    MIN: '🗕',
    MAX: '🗖'
  }
  let el

  const toggleContent = function() {
    if (el.refs.content.classList.contains('hidden')) {
      this.textContent = icons.MIN
      el.refs.content.classList.remove('hidden')
    } else {
      this.textContent = icons.MAX
      el.refs.content.classList.add('hidden')
    }
  }
  const setCount = function(count) {
    if (count) {
      this.classList.remove('status-success')
      this.classList.add('status-error')
      this.childNodes[0].classList.remove('icon-check')
      this.childNodes[0].classList.add('icon-x')

      this.childNodes[1].textContent = count === 1 ? '1 Issue' : `${count} Issues`
    } else {
      this.classList.remove('status-error')
      this.classList.add('status-success')
      this.childNodes[0].classList.remove('icon-x')
      this.childNodes[0].classList.add('icon-check')

      this.childNodes[1].textContent = 'No Issues'
    }
  }

  el = <linter-new-panel tabindex="-1">

          Linter

          <linter-bottom-status $setCount={setCount} class="status-success">
             No Issues
          </linter-bottom-status>

          {icons.MIN}
          ✖

  </linter-new-panel>

  el.refs = {}
  el.refs.content = el.querySelector('.panel-body')
  el.refs.counts = el.querySelector('.heading-status')
  el.refs.status = el.querySelector('linter-bottom-status')
  el.refs.hide = el.querySelector('.panel-button-hide')

  el.addEventListener('keydown', function(e) {
    if (e.which === 67 && e.ctrlKey) {
      Clipboard.writeText(getSelection().toString())
    }
  })

  return el
}
<|endoftext|>


<commit_before>var keystone = require('keystone');

var Post = keystone.list('Post');
var PostComment = keystone.list('PostComment');

exports = module.exports = function(req, res) {

	var view = new keystone.View(req, res),
		locals = res.locals;

	// Init locals
	locals.section = 'News';
	locals.filters = {
		post: req.params.post
	};

	view.on('init', function(next) {

		Post.model.findOne()
			.where('slug', locals.filters.post)
			.populate('author categories')
			.exec(function(err, post) {

				if (err) return res.err(err);
				if (!post) return res.notfound('Post not found');

				// Allow admins or the author to see draft posts
				if (post.state == 'published' || (req.user && req.user.isAdmin) || (req.user && post.author && (req.user.id == post.author.id))) {
					locals.post = post;
					locals.post.populateRelated('comments[author]', next);
					locals.page.title = post.title + ' - News - Babylon';
				} else {
					return res.notfound('Post not found');
				}

			});

	});

	// Load recent posts
	view.query('data.posts',
		Post.model.find()
			.where('state', 'published')
			.sort('-publishedDate')
			.populate('author')
			.limit('4')
	);

	view.on('post', { action: 'create-comment' }, function(next) {

		// handle form
		var newPostComment = new PostComment.model({
				post: locals.post.id,
				author: locals.user.id
			}),
			updater = newPostComment.getUpdateHandler(req, res, {
				errorMessage: 'There was an error creating your comment:'
			});

		updater.process(req.body, {
			flashErrors: true,
			logErrors: true,
			fields: 'content'
		}, function(err) {
			if (err) {
				locals.validationErrors = err.errors;
			} else {
				req.flash('success', 'Your comment has been added successfully.');
			//	return res.redirect('/blog/post/' + locals.post.slug);
			}
			next();
		});

	});

	// Render the view
	view.render(keystone.lang + '/site/post');

}
<commit_msg>Create Comment redirect url when submit (fixed)<commit_after>var keystone = require('keystone');

var Post = keystone.list('Post');
var PostComment = keystone.list('PostComment');

exports = module.exports = function(req, res) {

	var view = new keystone.View(req, res),
		locals = res.locals;

	// Init locals
	locals.section = 'News';
	locals.filters = {
		post: req.params.post
	};

	view.on('init', function(next) {

		Post.model.findOne()
			.where('slug', locals.filters.post)
			.populate('author categories')
			.exec(function(err, post) {

				if (err) return res.err(err);
				if (!post) return res.notfound('Post not found');

				// Allow admins or the author to see draft posts
				if (post.state == 'published' || (req.user && req.user.isAdmin) || (req.user && post.author && (req.user.id == post.author.id))) {
					locals.post = post;
					locals.post.populateRelated('comments[author]', next);
					locals.page.title = post.title + ' - News - Babylon';
				} else {
					return res.notfound('Post not found');
				}

			});

	});

	// Load recent posts
	view.query('data.posts',
		Post.model.find()
			.where('state', 'published')
			.sort('-publishedDate')
			.populate('author')
			.limit('4')
	);

	view.on('post', { action: 'create-comment' }, function(next) {

		// handle form
		var newPostComment = new PostComment.model({
				post: locals.post.id,
				author: locals.user.id
			}),
			updater = newPostComment.getUpdateHandler(req, res, {
				errorMessage: 'There was an error creating your comment:'
			});

		updater.process(req.body, {
			flashErrors: true,
			logErrors: true,
			fields: 'content'
		}, function(err) {
			if (err) {
				locals.validationErrors = err.errors;
			} else {
				req.flash('success', 'Your comment has been added successfully.');
				return res.redirect('/news/post/' + locals.post.slug);
			}
			next();
		});

	});

	// Render the view
	view.render(keystone.lang + '/site/post');

}
<|endoftext|>


<commit_before>'use babel'

/** @jsx jsx */
import {createClass, jsx} from 'vanilla-jsx'

export default createClass({
  renderView(suggestions, dispose) {
    let className = 'select-list popover-list'
    if (suggestions.length > 7) {
      className += ' intentions-scroll'
    }

    this.suggestions = suggestions
    this.suggestionsCount = suggestions.length
    this.suggestionsIndex = -1

    return <intentions-list class={className} id="intentions-list">

        {suggestions.map(function(suggestion) {
          return

            {suggestion.title}

        })}

    </intentions-list>
  },
  moveDown() {
    this.suggestionsIndex++
    this.selectOption(this.suggestionsIndex)
  },
  moveUp() {
    this.suggestionsIndex--
    if (this.suggestionsIndex < 0) {
      this.suggestionsIndex = this.suggestionsCount - 1
    }
    this.selectOption(this.suggestionsIndex)
  },
  selectOption(suggestionsIndex) {
    const index = suggestionsIndex % this.suggestionsCount

    if (this.refs.active) {
      this.refs.active.classList.remove('selected')
    }

    this.refs.active = this.refs.list.children[index]
    this.refs.active.classList.add('selected')

    this.refs.active.scrollIntoViewIfNeeded(false)
  },
  getActive() {
    return this.suggestions[this.suggestionsIndex]
  }
})
<commit_msg>:bug: Fix out-of-bounds suggestionsIndex<commit_after>'use babel'

/** @jsx jsx */
import {createClass, jsx} from 'vanilla-jsx'

export default createClass({
  renderView(suggestions, dispose) {
    let className = 'select-list popover-list'
    if (suggestions.length > 7) {
      className += ' intentions-scroll'
    }

    this.suggestions = suggestions
    this.suggestionsCount = suggestions.length
    this.suggestionsIndex = -1

    return <intentions-list class={className} id="intentions-list">

        {suggestions.map(function(suggestion) {
          return

            {suggestion.title}

        })}

    </intentions-list>
  },
  moveDown() {
    this.suggestionsIndex = (this.suggestionsIndex + 1) % this.suggestionsCount
    this.selectOption(this.suggestionsIndex)
  },
  moveUp() {
    this.suggestionsIndex--
    if (this.suggestionsIndex < 0) {
      this.suggestionsIndex = this.suggestionsCount - 1
    } else {
      this.suggestionsIndex = this.suggestionsIndex % this.suggestionsCount
    }
    this.selectOption(this.suggestionsIndex)
  },
  selectOption(index) {

    if (this.refs.active) {
      this.refs.active.classList.remove('selected')
    }

    this.refs.active = this.refs.list.children[index]
    this.refs.active.classList.add('selected')

    this.refs.active.scrollIntoViewIfNeeded(false)
  },
  getActive() {
    return this.suggestions[this.suggestionsIndex]
  }
})
<|endoftext|>


<commit_before>//	***********************************************
//	WINE LIFE
//	PROFILE WINDOW  - ProfileWindow.js
//
//	MEN+1
//	Programmer:  David Wells
//	***********************************************

function ProfileWindow(title) {
	var global = require('ui/common/globals');
	var dropdown = require('ui/common/elements/dropdown');
	// Creates the default window with global color scheme
	var self = global.createWindow(title);
	self.barImage='images/iPhone_Nav_Bar_Bkgrd_With_Black.png';
	var loading = global.loading_animation();

	self.add(loading);
	loading.show();
	loading.top = 40;

//	EDIT PROFILE VIEW
//	***********************************************
	var edit_prof = Ti.UI.createView(
		{
			width: Ti.UI.FILL,
			height: Ti.UI.SIZE,
			layout: 'horizontal',
			left: 10,
			right: 10
		}
	);

	//	***********************************************
	//	PROFILE INFO VIEWS & SUBVIEWS
	//	***********************************************
	var profile_info = Ti.UI.createView({
		layout: 'vertical',
		height: Ti.UI.SIZE,
		width: Ti.UI.FILL,
		top: 35,
	});

	var header = Ti.UI.createView({
		layout: 'horizontal',
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		left: 10,
		right: 10,

	});
	profile_info.add(header);
	header.hide();
	//	***********************************************
	//  USER IMAGE - upper left of view
	//	***********************************************
	var user_image = Ti.UI.createImageView({

  		height: Ti.UI.SIZE,
  		width: '30%',
		top: 0,
		borderWidth: 1,
		borderRadius: 10,

	});
	var progressbar = Ti.UI.createProgressBar({width: Ti.UI.FILL, height: 20, bottom: 0});
	header.add(user_image);

	user_image.addEventListener('click', add_image);

	var content = Ti.UI.createView({
		layout: 'vertical',
		width: '70%',
		height: Ti.UI.SIZE
	});
	header.add(content);
	self.add(progressbar);
	//  ADD IMAGE
	//	***********************************************
	function add_image(){

		//Create a dialog with options
		var dialog = Titanium.UI.createOptionDialog({
		    //title of dialog
		    title: 'Choose an image source...',
		    //options
		    options: ['Camera','Photo Gallery', 'Cancel'],
		    //index of cancel button
		    cancel:2
		});
		function upload_image(img){
			progressbar.show();
            var xhr = Titanium.Network.createHTTPClient();
            xhr.onsendstream = function(e){
			        progressbar.value = e.progress ;
			};
            xhr.onload = function(){
            	progressbar.hide();
            	Ti.API.info(this.responseText);

            	res = JSON.parse(this.responseText);
            	if(!res.success)
            		alert("Server Error: \""+res.error+"\" Please try again later.");
            }
			xhr.open('POST', "http://winelife.ericwooley.com/user/upload");
			//f1 = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,filename);
			//iamge=f1.read(image);
			xhr.send({profile_image: img});
		}
		//add event listener
		dialog.addEventListener('click', function(e) {

		    //if first option was selected
		    if(e.index == 0)
		    {
		        //then we are getting image from camera
		        Titanium.Media.showCamera({
		            //we got something
		            success:function(event)
		            {
		                //getting media
		                var image = event.media;
		                user_image.image = image;
		               	upload_image(image);

		                //checking if it is photo
		                if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
		                {
		                    //we may create image view with contents from image variable
		                    //or simply save path to image
		                    Ti.App.Properties.setString("image", image.nativePath);
		                }
		            },
		            cancel:function()
		            {
		                //do somehting if user cancels operation
		            },
		            error:function(error)
		            {
		                //error happend, create alert
		                var a = Titanium.UI.createAlertDialog({title:'Camera'});
		                //set message
		                if (error.code == Titanium.Media.NO_CAMERA)
		                {
		                    a.setMessage('Device does not have camera');
		                }
		                else
		                {
		                    a.setMessage('Unexpected error: ' + error.code);
		                }

		                // show alert
		                a.show();
		            },
		            allowImageEditing:true,
		            saveToPhotoGallery:true
		        });
		    }

		    else if(e.index == 1)
		    {
		        //obtain an image from the gallery
		        Titanium.Media.openPhotoGallery({
		            success:function(event)
		            {
		                //getting media
		                var image = event.media;
		                user_image.image = image;
		                // set image view
		                upload_image(image);
		                //checking if it is photo
		                if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
		                {
		                    //we may create image view with contents from image variable
		                    //or simply save path to image
		                    Ti.App.Properties.setString("image", image.nativePath);
		                }
		            },
		            cancel:function()
		            {
		                //user cancelled the action fron within
		                //the photo gallery
		            }
		        });
		    }
		    else
		    {
		        //cancel was tapped
		        //user opted not to choose a photo
		    }
		});
		dialog.show();
	}

//***********************************************************
//EDIT PROFILE POP-DOWN
//***********************************************************

	//  ADD FIRST NAME - FIELD
	var fname = Ti.UI.createTextField({
		hintText: 'First Name',
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED
	});
	edit_prof.add(fname);

	//  ADD LAST NAME - FIELD
	var lname = Ti.UI.createTextField({
		hintText: 'Last Name',
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED
	});
	edit_prof.add(lname);

	//  USER NAME TEXT FIELD
	var userName = Ti.UI.createLabel({
  		color: global.colors.dark,
  		font: { fontSize:24 },
  		text: 'Loading',
  		top: 0,
  		left: 10,
  		height: Ti.UI.SIZE,
  		width: Ti.UI.FILL
	});
	content.add(userName);

	// //  CHECK-INS FIELD
	// var check_ins = Ti.UI.createLabel({
  		// color: global.colors.dark,
  		// font: { fontSize: 12 },
  		// left: 10,
  		// height: Ti.UI.SIZE,
  		// width: Ti.UI.FILL
	// });
	// content.add(check_ins);
//
	// //  FOLLOWERS TEXT FIELD
	// var followers = Ti.UI.createLabel({
  		// color: global.colors.dark,
  		// font: { fontSize: 12 },
  		// left: 10,
  		// height: Ti.UI.SIZE,
  		// width: Ti.UI.FILL
	// });
	// content.add(followers);
//
	// //  FOLLOWING TEXT FIELD
	// var following = Ti.UI.createLabel({
  		// color: global.colors.dark,
  		// font: { fontSize: 12 },
  		// text: 'Following: 4',
  		// top: 0,
  		// left: 10,
  		// height: Ti.UI.SIZE,
  		// width: Ti.UI.FILL
	// });
	// content.add(following);

	// RECENT CHECK-INS LABEL
	// var recent_check_ins = Ti.UI.createLabel({
		// top: 10,
  		// color: global.colors.dark,
  		// font: { fontFamily: 'Helvetica Neue', fontSize:20, fontWeight: 'bold'},
  		// text: 'My Cellar',
  		// height: Ti.UI.SIZE,
  		// width: Ti.UI.FILL
//
	// });

	/*
	var sep_line=Ti.UI.createLabel({
	    height: 2,
	    width: Ti.UI.FILL,
	    top: 4,
	    bottom: 5,
	    //left: 10,
	    //right: 10,
	    backgroundColor: global.colors.dark
	});*/

	//header.add(recent_check_ins);
	//header.add(sep_line);
	var followers = false;
	function load_followers(){
		global.api.follower_table(function(table){
				followers = table;
				profile_info.add(followers);
				table.setLeft(10);
			},
			function(data){
				var fw = require('ui/handheld/FriendWindow');
				w = fw(data);
				w.containingTab = self.containingTab;
				self.containingTab.open(w);
			}
		);
	};
	var following = false;
	function load_following(){
		global.api.load_friend_list(
			function(list){
				following = list;
				profile_info.add(following);
				list.setLeft(10);
			},
			function(data){
				var fw = require('ui/handheld/FriendWindow');
				w = fw(data);
				w.containingTab = self.containingTab;
				self.containingTab.open(w);
			}
		);
	};
	var table = false;

	var select_bar = null;
	var index_selected = 0;
	function load_data(){
		self.removeEventListener('focus', load_data);
		global.api.profileInformation(function(data){
			userName.text = data.fname + ' ' + data.lname;
			fname.value = data.fname;
			lname.value = data.lname;
			// check_ins.text= "Total Check-Ins: " + data.chcount;
			// followers.text = "Followers: "+data.follower;
			// following.text = "Following: "+data.following;
			if(select_bar)
				profile_info.remove(select_bar);
			var options = ['Check-Ins ('+data.chcount+')','Following (' + +data.following+')', 'Followers (' + +data.follower+')' ];
			select_bar = global.TU.UI.createSelectBar ({
				width: Ti.UI.FILL,
				top:10,
				left: 10,
				right: 10,
				backgroundColor: global.colors.dark,
				allow_deselect: false,
				borderRadius: 0,
				labels: options
			});
			select_bar.xsetSelectedIndex(index_selected);
			select_bar.addEventListener ('TUchange', function (e) {
				index_selected = e.index;
				profile_info.remove(table);
				if(followers)
					profile_info.remove(followers);
				if(following)
					profile_info.remove(following);

				if(e.index == 0){
					if(table)
						profile_info.add(table);
				}else if(e.index == 1){
					if(!following)
						load_following();
					else
						profile_info.add(following);
				}else if(e.index == 2){
					if(!followers)
						load_followers();
					else
						profile_info.add(following);
				}
			});
			profile_info.add(select_bar);

			user_image.image = data.picture_url;
			if(table){
					profile_info.remove(table);

				}
			global.api.recent_checkins(function(data){
				header.show();
				self.remove(loading);

				table = global.api.search_results(data, function(wine){
					var wine_review = require('ui/handheld/WineReview');
					var wr = wine_review(wine);
					wr.containingTab = self.containingTab;
					self.containingTab.open(wr);
				});
				table.addEventListener('refresh_page_data', load_data);
				profile_info.add(table);
			});
 		});

	};

	self.addEventListener('focus', load_data);
	// self.addEventListener('blur', function(){
		// self.addEventListener('focus', load_data);
	// });

	self.add(profile_info);

	dropdown(edit_prof, self, "Save Changes", "Edit Profile", "up", function(){
		if(fname.value.length < 1 || lname.value.lengh < 1 /*|| about_me.value == about_me._hintText*/){
			alert('Profile was not updated, a field was blank');
			return;
		}
		global.api.editProfile(fname.value, lname.value, ''/*about_me.value*/, function(data){
			userName.text = data.user_info.fname + ' ' + data.user_info.lname;
		});

	});

	global.outputHook(self);
	return self;
};

module.exports = ProfileWindow;<commit_msg>profile fix<commit_after>//	***********************************************
//	WINE LIFE
//	PROFILE WINDOW  - ProfileWindow.js
//
//	MEN+1
//	Programmer:  David Wells
//	***********************************************

function ProfileWindow(title) {
	var global = require('ui/common/globals');
	var dropdown = require('ui/common/elements/dropdown');
	// Creates the default window with global color scheme
	var self = global.createWindow(title);
	self.barImage='images/iPhone_Nav_Bar_Bkgrd_With_Black.png';
	var loading = global.loading_animation();

	self.add(loading);
	loading.show();
	loading.top = 40;

//	EDIT PROFILE VIEW
//	***********************************************
	var edit_prof = Ti.UI.createView(
		{
			width: Ti.UI.FILL,
			height: Ti.UI.SIZE,
			layout: 'horizontal',
			left: 10,
			right: 10
		}
	);

	//	***********************************************
	//	PROFILE INFO VIEWS & SUBVIEWS
	//	***********************************************
	var profile_info = Ti.UI.createView({
		layout: 'vertical',
		height: Ti.UI.SIZE,
		width: Ti.UI.FILL,
		top: 35,
	});

	var header = Ti.UI.createView({
		layout: 'horizontal',
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		left: 10,
		right: 10,

	});
	profile_info.add(header);
	header.hide();
	//	***********************************************
	//  USER IMAGE - upper left of view
	//	***********************************************
	var user_image = Ti.UI.createImageView({

  		height: Ti.UI.SIZE,
  		width: '30%',
		top: 0,
		borderWidth: 1,
		borderRadius: 10,

	});
	var progressbar = Ti.UI.createProgressBar({width: Ti.UI.FILL, height: 20, bottom: 0});
	header.add(user_image);

	user_image.addEventListener('click', add_image);

	var content = Ti.UI.createView({
		layout: 'vertical',
		width: '70%',
		height: Ti.UI.SIZE
	});
	header.add(content);
	self.add(progressbar);
	//  ADD IMAGE
	//	***********************************************
	function add_image(){

		//Create a dialog with options
		var dialog = Titanium.UI.createOptionDialog({
		    //title of dialog
		    title: 'Choose an image source...',
		    //options
		    options: ['Camera','Photo Gallery', 'Cancel'],
		    //index of cancel button
		    cancel:2
		});
		function upload_image(img){
			progressbar.show();
            var xhr = Titanium.Network.createHTTPClient();
            xhr.onsendstream = function(e){
			        progressbar.value = e.progress ;
			};
            xhr.onload = function(){
            	progressbar.hide();
            	Ti.API.info(this.responseText);

            	res = JSON.parse(this.responseText);
            	if(!res.success)
            		alert("Server Error: \""+res.error+"\" Please try again later.");
            }
			xhr.open('POST', "http://winelife.ericwooley.com/user/upload");
			//f1 = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,filename);
			//iamge=f1.read(image);
			xhr.send({profile_image: img});
		}
		//add event listener
		dialog.addEventListener('click', function(e) {

		    //if first option was selected
		    if(e.index == 0)
		    {
		        //then we are getting image from camera
		        Titanium.Media.showCamera({
		            //we got something
		            success:function(event)
		            {
		                //getting media
		                var image = event.media;
		                user_image.image = image;
		               	upload_image(image);

		                //checking if it is photo
		                if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
		                {
		                    //we may create image view with contents from image variable
		                    //or simply save path to image
		                    Ti.App.Properties.setString("image", image.nativePath);
		                }
		            },
		            cancel:function()
		            {
		                //do somehting if user cancels operation
		            },
		            error:function(error)
		            {
		                //error happend, create alert
		                var a = Titanium.UI.createAlertDialog({title:'Camera'});
		                //set message
		                if (error.code == Titanium.Media.NO_CAMERA)
		                {
		                    a.setMessage('Device does not have camera');
		                }
		                else
		                {
		                    a.setMessage('Unexpected error: ' + error.code);
		                }

		                // show alert
		                a.show();
		            },
		            allowImageEditing:true,
		            saveToPhotoGallery:true
		        });
		    }

		    else if(e.index == 1)
		    {
		        //obtain an image from the gallery
		        Titanium.Media.openPhotoGallery({
		            success:function(event)
		            {
		                //getting media
		                var image = event.media;
		                user_image.image = image;
		                // set image view
		                upload_image(image);
		                //checking if it is photo
		                if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO)
		                {
		                    //we may create image view with contents from image variable
		                    //or simply save path to image
		                    Ti.App.Properties.setString("image", image.nativePath);
		                }
		            },
		            cancel:function()
		            {
		                //user cancelled the action fron within
		                //the photo gallery
		            }
		        });
		    }
		    else
		    {
		        //cancel was tapped
		        //user opted not to choose a photo
		    }
		});
		dialog.show();
	}

//***********************************************************
//EDIT PROFILE POP-DOWN
//***********************************************************

	//  ADD FIRST NAME - FIELD
	var fname = Ti.UI.createTextField({
		hintText: 'First Name',
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED
	});
	edit_prof.add(fname);

	//  ADD LAST NAME - FIELD
	var lname = Ti.UI.createTextField({
		hintText: 'Last Name',
		width: Ti.UI.FILL,
		height: Ti.UI.SIZE,
		borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED
	});
	edit_prof.add(lname);

	//  USER NAME TEXT FIELD
	var userName = Ti.UI.createLabel({
  		color: global.colors.dark,
  		font: { fontSize:24 },
  		text: 'Loading',
  		top: 0,
  		left: 10,
  		height: Ti.UI.SIZE,
  		width: Ti.UI.FILL
	});
	content.add(userName);

	// //  CHECK-INS FIELD
	// var check_ins = Ti.UI.createLabel({
  		// color: global.colors.dark,
  		// font: { fontSize: 12 },
  		// left: 10,
  		// height: Ti.UI.SIZE,
  		// width: Ti.UI.FILL
	// });
	// content.add(check_ins);
//
	// //  FOLLOWERS TEXT FIELD
	// var followers = Ti.UI.createLabel({
  		// color: global.colors.dark,
  		// font: { fontSize: 12 },
  		// left: 10,
  		// height: Ti.UI.SIZE,
  		// width: Ti.UI.FILL
	// });
	// content.add(followers);
//
	// //  FOLLOWING TEXT FIELD
	// var following = Ti.UI.createLabel({
  		// color: global.colors.dark,
  		// font: { fontSize: 12 },
  		// text: 'Following: 4',
  		// top: 0,
  		// left: 10,
  		// height: Ti.UI.SIZE,
  		// width: Ti.UI.FILL
	// });
	// content.add(following);

	// RECENT CHECK-INS LABEL
	// var recent_check_ins = Ti.UI.createLabel({
		// top: 10,
  		// color: global.colors.dark,
  		// font: { fontFamily: 'Helvetica Neue', fontSize:20, fontWeight: 'bold'},
  		// text: 'My Cellar',
  		// height: Ti.UI.SIZE,
  		// width: Ti.UI.FILL
//
	// });

	/*
	var sep_line=Ti.UI.createLabel({
	    height: 2,
	    width: Ti.UI.FILL,
	    top: 4,
	    bottom: 5,
	    //left: 10,
	    //right: 10,
	    backgroundColor: global.colors.dark
	});*/

	//header.add(recent_check_ins);
	//header.add(sep_line);
	var followers = false;
	function load_followers(){
		global.api.follower_table(function(table){
				followers = table;
				profile_info.add(followers);
				table.setLeft(10);
			},
			function(data){
				var fw = require('ui/handheld/FriendWindow');
				w = fw(data);
				w.containingTab = self.containingTab;
				self.containingTab.open(w);
			}
		);
	};
	var following = false;
	function load_following(){
		global.api.load_friend_list(
			function(list){
				following = list;
				profile_info.add(following);
				list.setLeft(10);
			},
			function(data){
				var fw = require('ui/handheld/FriendWindow');
				w = fw(data);
				w.containingTab = self.containingTab;
				self.containingTab.open(w);
			}
		);
	};
	var table = false;

	var select_bar = null;
	var index_selected = 0;
	function load_data(){
		self.removeEventListener('focus', load_data);
		global.api.profileInformation(function(data){
			userName.text = data.fname + ' ' + data.lname;
			fname.value = data.fname;
			lname.value = data.lname;
			// check_ins.text= "Total Check-Ins: " + data.chcount;
			// followers.text = "Followers: "+data.follower;
			// following.text = "Following: "+data.following;
			if(select_bar)
				profile_info.remove(select_bar);
			var options = ['Check-Ins','Following', 'Followers' ];
			select_bar = global.TU.UI.createSelectBar ({
				width: Ti.UI.FILL,
				top:10,
				left: 10,
				right: 10,
				backgroundColor: global.colors.dark,
				allow_deselect: false,
				borderRadius: 0,
				labels: options
			});
			select_bar.xsetSelectedIndex(index_selected);
			select_bar.addEventListener ('TUchange', function (e) {
				index_selected = e.index;
				profile_info.remove(table);
				if(followers)
					profile_info.remove(followers);
				if(following)
					profile_info.remove(following);

				if(e.index == 0){
					if(table)
						profile_info.add(table);
				}else if(e.index == 1){
					//if(!following)
						load_following();
					//else
						//profile_info.add(following);
				}else if(e.index == 2){
					//if(!followers)
						load_followers();
					//else
						//rofile_info.add(following);
				}
			});
			profile_info.add(select_bar);

			user_image.image = data.picture_url;
			if(table){
					profile_info.remove(table);

				}
			global.api.recent_checkins(function(data){
				header.show();
				self.remove(loading);

				table = global.api.search_results(data, function(wine){
					var wine_review = require('ui/handheld/WineReview');
					var wr = wine_review(wine);
					wr.containingTab = self.containingTab;
					self.containingTab.open(wr);
				});
				table.addEventListener('refresh_page_data', load_data);
				profile_info.add(table);
			});
 		});

	};

	self.addEventListener('focus', load_data);
	// self.addEventListener('blur', function(){
		// self.addEventListener('focus', load_data);
	// });

	self.add(profile_info);

	dropdown(edit_prof, self, "Save Changes", "Edit Profile", "up", function(){
		if(fname.value.length < 1 || lname.value.lengh < 1 /*|| about_me.value == about_me._hintText*/){
			alert('Profile was not updated, a field was blank');
			return;
		}
		global.api.editProfile(fname.value, lname.value, ''/*about_me.value*/, function(data){
			userName.text = data.user_info.fname + ' ' + data.user_info.lname;
		});

	});

	global.outputHook(self);
	return self;
};

module.exports = ProfileWindow;<|endoftext|>


<commit_before>/**
 * User interface functionalities
 * @package zork
 * @subpackage user
 * @author David Pozsar <david.pozsar@megaweb.hu>
 */
( function ( global, $, js )
{
    "use strict";

    if ( typeof js.customize !== "undefined" )
    {
        return;
    }

    var customCssSelector = "head link.customize-stylesheet[data-customize]";

    /**
     * @class Customize module
     * @constructor
     * @memberOf Zork
     */
    global.Zork.Customize = function ()
    {
        this.version = "1.0";
        this.modulePrefix = [ "zork", "customize" ];
    };

    global.Zork.prototype.customize = new global.Zork.Customize();

    global.Zork.Customize.prototype.reload = function ()
    {
        $( customCssSelector ).each( function () {
            var css     = $( this ),
                id      = css.data( "customize" ),
                href    = js.core.uploadsUrl
                        + "/customize/custom." + id + "."
                        + Number( new Date() ).toString(36)
                        + ".css",
                link    = $( "<link />" )
                            .one( "ready load", function () {
                                css.remove();
                            } )
                            .attr( {
                                "href"              : href,
                                "type"              : "text/css",
                                "rel"               : "stylesheet",
                                "class"             : "customize-stylesheet",
                                "data-customize"    : id
                            } )
                            .data( "customize", id );

                css.removeClass( "customize-stylesheet" );
                $( "head" ).append( link );
        } );
    };

    global.Zork.Customize.prototype.properties = function ( element )
    {
        js.require( "js.ui.dialog" );
        element = $( element );

        var addButton = $( "<button type='button' />" ).text(
                element.data( "jsPropertiesAddLabel" ) ||
                    js.core.translate( "customize.form.rules.addProperty" )
            );

        addButton.click( function () {
            js.ui.dialog.prompt( {
                "message": js.core.translate( "customize.form.rules.addMessage" ),
                "input": function ( prop ) {
                    if ( prop && ( prop = String( prop ).replace( /[^a-zA-Z0-9\-]/, "" ) ) ) {

                        element
                            .prepend(
                                $( "<dd />" )
                                    .append(
                                        $( "<input type='text'>" )
                                            .attr( {
                                                "name": "properties[" + prop + "][value]"
                                            } )
                                    )
                                    .append(
                                        $( "<label />" )
                                            .append(
                                                $( "<input type='checkbox' value='important'>" )
                                                    .attr( {
                                                        "name": "properties[" + prop + "][priority]"
                                                    } )
                                            )
                                            .append( js.core.translate( "customize.form.rules.important" ) )
                                    )
                            )
                            .prepend(
                                $( "<dt />" )
                                    .append(
                                        $( "<label />" )
                                            .attr( "for", "properties[" + prop + "][value]" )
                                            .text( prop )
                                    )
                            );
                    }
                }
            } );
        } );

        element.before( addButton );
    };

    global.Zork.Customize.prototype.properties.isElementConstructor = true;

    global.Zork.Customize.prototype.preview = function ( element )
    {
        element  = $( element );

        var form = element.length
                 ? $( element[0].form || element.closest( "form" ) )
                 : null,
            previewButton = $( "<input type='submit' />" ).val(
                element.data( "jsCustomizePreviewLabel" ) ||
                    js.core.translate( "customize.preview.label" )
            ),
            cancelButton = $( "<input type='submit' />" ).val(
                element.data( "jsCustomizeCancelLabel" ) ||
                    js.core.translate( "default.cancel" )
            ),
            click = function ( url ) {
                var newact = String( url );
                return function () {
                    var action = form.prop( "action" ) || form.attr( "action" ) || "",
                        target = form.prop( "target" ) || form.attr( "target" ) || "_self";

                    form.attr( "action", newact )
                        .prop( "action", newact )
                        .attr( "target", "_blank" )
                        .prop( "target", "_blank" );

                    setTimeout( function () {

                        form.attr( "action", action )
                            .prop( "action", action )
                            .attr( "target", target )
                            .prop( "target", target );

                    }, 500 );
                };
            };

        if ( form && form.length )
        {
            var rootId  = form.find( ':input[name="rootId"]' ).val(),
                id      = parseInt( rootId, 10 ) || "global";

            previewButton.click( click(
                "/app/" + js.core.defaultLocale +
                "/admin/customize-css/preview/" + id
            ) );

            cancelButton.click( click(
                "/app/" + js.core.defaultLocale +
                "/admin/customize-css/cancel/" + id
            ) );

            cancelButton.css( "margin-left", "2em" );

            element.after( cancelButton )
                   .after( previewButton );
        }
    };

    global.Zork.Customize.prototype.preview.isElementConstructor = true;

} ( window, jQuery, zork ) );
<commit_msg>Customize: edit custom css: design enhancements<commit_after>/**
 * User interface functionalities
 * @package zork
 * @subpackage user
 * @author David Pozsar <david.pozsar@megaweb.hu>
 */
( function ( global, $, js )
{
    "use strict";

    if ( typeof js.customize !== "undefined" )
    {
        return;
    }

    var customCssSelector = "head link.customize-stylesheet[data-customize]";

    /**
     * @class Customize module
     * @constructor
     * @memberOf Zork
     */
    global.Zork.Customize = function ()
    {
        this.version = "1.0";
        this.modulePrefix = [ "zork", "customize" ];
    };

    global.Zork.prototype.customize = new global.Zork.Customize();

    global.Zork.Customize.prototype.reload = function ()
    {
        $( customCssSelector ).each( function () {
            var css     = $( this ),
                id      = css.data( "customize" ),
                href    = js.core.uploadsUrl
                        + "/customize/custom." + id + "."
                        + Number( new Date() ).toString(36)
                        + ".css",
                link    = $( "<link />" )
                            .one( "ready load", function () {
                                css.remove();
                            } )
                            .attr( {
                                "href"              : href,
                                "type"              : "text/css",
                                "rel"               : "stylesheet",
                                "class"             : "customize-stylesheet",
                                "data-customize"    : id
                            } )
                            .data( "customize", id );

                css.removeClass( "customize-stylesheet" );
                $( "head" ).append( link );
        } );
    };

    global.Zork.Customize.prototype.properties = function ( element )
    {
        js.require( "js.ui.dialog" );
        element = $( element );

        var addButton = $( "<button type='button' />" ).text(
                element.data( "jsPropertiesAddLabel" ) ||
                    js.core.translate( "customize.form.rules.addProperty" )
            );

        addButton.click( function () {
            js.ui.dialog.prompt( {
                "message": js.core.translate( "customize.form.rules.addMessage" ),
                "input": function ( prop ) {
                    if ( prop && ( prop = String( prop ).replace( /[^a-zA-Z0-9\-]/, "" ) ) ) {

                        element
                            .prepend(
                                $( "<dd />" )
                                    .append(
                                        $( "<input type='text'>" )
                                            .attr( {
                                                "name": "properties[" + prop + "][value]"
                                            } )
                                    )
                                    .append(
                                        $( "<label />" )
                                            .append(
                                                $( "<input type='checkbox' value='important'>" )
                                                    .attr( {
                                                        "name": "properties[" + prop + "][priority]"
                                                    } )
                                            )
                                            .append( js.core.translate( "customize.form.rules.important" ) )
                                    )
                            )
                            .prepend(
                                $( "<dt />" )
                                    .append(
                                        $( "<label />" )
                                            .attr( "for", "properties[" + prop + "][value]" )
                                            .text( prop )
                                    )
                            );
                    }
                }
            } );
        } );

        element.before( addButton );
    };

    global.Zork.Customize.prototype.properties.isElementConstructor = true;

    global.Zork.Customize.prototype.preview = function ( element )
    {
        element  = $( element );

        var form = element.length
                 ? $( element[0].form || element.closest( "form" ) )
                 : null,
            previewButton = $( "<input type='submit' />" ).val(
                element.data( "jsCustomizePreviewLabel" ) ||
                    js.core.translate( "customize.preview.label" )
            ),
            cancelButton = $( "<input type='submit' />" ).val(
                element.data( "jsCustomizeCancelLabel" ) ||
                    js.core.translate( "default.cancel" )
            ),
            click = function ( newAction, newTarget ) {
                var newact = String( newAction || "/" ),
                    newtar = String( newTarget || "_blank" );
                return function () {
                    var action = form.prop( "action" ) || form.attr( "action" ) || "",
                        target = form.prop( "target" ) || form.attr( "target" ) || "_self";

                    form.attr( "action", newact )
                        .prop( "action", newact )
                        .attr( "target", newtar )
                        .prop( "target", newtar );

                    setTimeout( function () {

                        form.attr( "action", action )
                            .prop( "action", action )
                            .attr( "target", target )
                            .prop( "target", target );

                    }, 500 );
                };
            };

        if ( form && form.length )
        {
            var rootId  = form.find( ':input[name="rootId"]' ).val(),
                id      = parseInt( rootId, 10 ) || "global";

            previewButton.click( click(
                "/app/" + js.core.defaultLocale +
                "/admin/customize-css/preview/" + id,
                "_blank"
            ) );

            cancelButton.click( click(
                "/app/" + js.core.defaultLocale +
                "/admin/customize-css/cancel/" + id,
                "_top"
            ) );

            cancelButton.css( "margin-left", "2em" );

            element.after( cancelButton )
                   .after( previewButton );
        }
    };

    global.Zork.Customize.prototype.preview.isElementConstructor = true;

} ( window, jQuery, zork ) );
<|endoftext|>


<commit_before>/*
 * grunt-tree
 * https://github.com/yss/grunt-tree
 *
 * Copyright (c) 2013 yansong
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path'),
    fs = require('fs'),
    crypto = require('crypto');

/**
 * parse a path object to a tree object
 * @param {Object} obj
 * @param {Number|Boolean} md5
 * @return {Object}
 */
function parseToTree(obj, md5) {
    var key, i, arr, len, tmp, fileArr,
        tree = {};
    for (key in obj) {
        tmp = tree;
        arr = obj[key].split(path.sep);

        for (i = 0, len = arr.length - 1; i < len; i++) {
            if (!tmp[arr[i]]) {
                tmp[arr[i]] = {};
            }
            tmp = tmp[arr[i]];
        }

        // handle last one
        fileArr = arr[i].split('.');
        if (md5) {
            fileArr.pop();
        }
        // if has postfix, remove it
        if (fileArr.length > 1) {
            fileArr.pop();
        }
        // get the origin value
        tmp[fileArr.join('.')] = obj[key];
    }

    return tree;
}

// file with lost postfix
function getFileName(filename, version) {
    var pos = filename.lastIndexOf('.');
    if (version) {
        version = '.' + version;
        return ~pos ? filename.substring(0, pos) + version + filename.slice(pos) : filename + version;
    } else {
        return ~pos ? filename.substring(0, pos) : filename;
    }
}

// get md5 version of file
function getMd5Version(str, encoding, len) {
    str = str || Math.random().toString();
    str = crypto.createHash('md5').update(str).digest(encoding || 'hex');
    return len ? str.slice(0, len) : str;
}

function getMd5Name(abspath, filename, md5) {
    if (md5) {
        var len = typeof md5 === 'number' ? md5 : 0,
            version = getMd5Version(fs.readFileSync(abspath), '', len);
        return getFileName(filename, version);
    }
    return filename;
}

module.exports = function(grunt) {
    grunt.registerMultiTask('tree', 'Parse a directory to a tree with json format.', function() {
        var options = this.options({
            recurse: true,
            // type: [],
            md5: false,
            format: false
        }), typeReg;

        if (grunt.util.kindOf(options.type) === 'array') {
            typeReg = new RegExp('\\.(?:' + options.type.join('|') + ')$');
        } else {
            typeReg = false;
        }

        this.files.forEach(function(f) {
            var tree = {};
            f.src.filter(function(filepath) {
                if (!grunt.file.exists(filepath)) {
                    grunt.log.warn('Source file "' + filepath + '" not found.');
                    return false;
                } else {
                    return true;
                }
            }).forEach(function(filepath) {
                if (options.recurse) {
                    grunt.file.recurse(filepath, function(abspath, rootdir, subdir, filename) {
                        toTree(abspath, subdir, filename);
                    });
                } else {
                    var files = fs.readdirSync(filepath);
                    files.forEach(function(filename) {
                        toTree(path.join(filepath, filename), './', filename);
                    });
                }
            });

            function toTree(abspath, subdir, filename) {
                // ignore hidden file
                if (filename.indexOf('.') === 0) {
                    grunt.log.writeln('Ignore file: ' + filename);
                    return;
                }
                if (grunt.file.isFile(abspath)) {
                    // not the given type
                    if (typeReg && !typeReg.test(filename)) {
                        return;
                    }
                    tree[getFileName(filename)] = path.join(subdir, getMd5Name(abspath, filename, options.md5));
                }
            }

            if (!options.format) {
                tree = parseToTree(tree, options.md5);
            }

            grunt.file.write(f.dest, JSON.stringify(tree));
            grunt.log.writeln('File "' + f.dest + '" created.');
        });
    });

};
<commit_msg>compatibility fix for node 0.10+<commit_after>/*
 * grunt-tree
 * https://github.com/yss/grunt-tree
 *
 * Copyright (c) 2013 yansong
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path'),
    fs = require('fs'),
    crypto = require('crypto');

/**
 * parse a path object to a tree object
 * @param {Object} obj
 * @param {Number|Boolean} md5
 * @return {Object}
 */
function parseToTree(obj, md5) {
    var key, i, arr, len, tmp, fileArr,
        tree = {};
    for (key in obj) {
        tmp = tree;
        arr = obj[key].split(path.sep);

        for (i = 0, len = arr.length - 1; i < len; i++) {
            if (!tmp[arr[i]]) {
                tmp[arr[i]] = {};
            }
            tmp = tmp[arr[i]];
        }

        // handle last one
        fileArr = arr[i].split('.');
        if (md5) {
            fileArr.pop();
        }
        // if has postfix, remove it
        if (fileArr.length > 1) {
            fileArr.pop();
        }
        // get the origin value
        tmp[fileArr.join('.')] = obj[key];
    }

    return tree;
}

// file with lost postfix
function getFileName(filename, version) {
    var pos = filename.lastIndexOf('.');
    if (version) {
        version = '.' + version;
        return ~pos ? filename.substring(0, pos) + version + filename.slice(pos) : filename + version;
    } else {
        return ~pos ? filename.substring(0, pos) : filename;
    }
}

// get md5 version of file
function getMd5Version(str, encoding, len) {
    str = str || Math.random().toString();
    str = crypto.createHash('md5').update(str).digest(encoding || 'hex');
    return len ? str.slice(0, len) : str;
}

function getMd5Name(abspath, filename, md5) {
    if (md5) {
        var len = typeof md5 === 'number' ? md5 : 0,
            version = getMd5Version(fs.readFileSync(abspath), '', len);
        return getFileName(filename, version);
    }
    return filename;
}

module.exports = function(grunt) {
    grunt.registerMultiTask('tree', 'Parse a directory to a tree with json format.', function() {
        var options = this.options({
            recurse: true,
            // type: [],
            md5: false,
            format: false
        }), typeReg;

        if (grunt.util.kindOf(options.type) === 'array') {
            typeReg = new RegExp('\\.(?:' + options.type.join('|') + ')$');
        } else {
            typeReg = false;
        }

        this.files.forEach(function(f) {
            var tree = {};
            f.src.filter(function(filepath) {
                if (!grunt.file.exists(filepath)) {
                    grunt.log.warn('Source file "' + filepath + '" not found.');
                    return false;
                } else {
                    return true;
                }
            }).forEach(function(filepath) {
                if (options.recurse) {
                    grunt.file.recurse(filepath, function(abspath, rootdir, subdir, filename) {
                        toTree(abspath, subdir, filename);
                    });
                } else {
                    var files = fs.readdirSync(filepath);
                    files.forEach(function(filename) {
                        toTree(path.join(filepath, filename), './', filename);
                    });
                }
            });

            function toTree(abspath, subdir, filename) {
                // ensure subdir is not undefined
                subdir = subdir || "";
                // ignore hidden file
                if (filename.indexOf('.') === 0) {
                    grunt.log.writeln('Ignore file: ' + filename);
                    return;
                }
                if (grunt.file.isFile(abspath)) {
                    // not the given type
                    if (typeReg && !typeReg.test(filename)) {
                        return;
                    }
                    tree[getFileName(filename)] = path.join(subdir, getMd5Name(abspath, filename, options.md5));
                }
            }

            if (!options.format) {
                tree = parseToTree(tree, options.md5);
            }

            grunt.file.write(f.dest, JSON.stringify(tree));
            grunt.log.writeln('File "' + f.dest + '" created.');
        });
    });

};
<|endoftext|>


<commit_before>Vps.EyeCandy.List.Plugins.StateChanger.Click = Ext.extend(Vps.EyeCandy.List.Plugins.Abstract, {
    state: 'active',
    stateUnique: true,
    init: function() {
        this.list.on('childClick', function(item, ev) {
            if (this.stateUnique) {
                this.list.getItems().forEach(function(i) {
                    if (i!= item) item.removeState(this.state, this);
                }, this);
            }
            item.pushState(this.state, this);
            ev.stopEvent();
        }, this);
    }
});
<commit_msg>correctly remove state<commit_after>Vps.EyeCandy.List.Plugins.StateChanger.Click = Ext.extend(Vps.EyeCandy.List.Plugins.Abstract, {
    state: 'active',
    stateUnique: true,
    init: function() {
        this.list.on('childClick', function(item, ev) {
            if (this.stateUnique) {
                this.list.getItems().forEach(function(i) {
                    if (i != item) i.removeState(this.state, this);
                }, this);
            }
            item.pushState(this.state, this);
            ev.stopEvent();
        }, this);
    }
});
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

Blend.defineClass('Builder.commands.build.webapp.Builder', {
    extend: 'Builder.commands.build.AnalyzerBase',
    /**
     * Build the Development version of the application
     * @returns {undefined}
     */
    buildDevelVersion: function () {
        var me = this;
        /**
         * Build steps:
         * [1] Clean the build folder. This is done by the base before getting here.
         * [2] Deploy the mandatory blend resources, font icons and images. (blend folder)
         * [3] Deploy blend's JavaScript files (blend folder)
         * [4] Deploy application's js files
         * @returns {Boolean}
         */
        me.deployIconFonts();
        if (me.deployDevScriptsAndStyleSheets()) {
            me.createDevIndex();
            return true;
        } else {
            return false;
        }

    },
    /**
     * Created the index file for the development mode
     * @returns {undefined}
     */
    createDevIndex: function () {
        var me = this,
                headers = Template.renderDevHeaders(
                        Template.renderMetaTags(me.project.meta),
                        Template.renderStyleSheets(me._stylesheets.concat(me.project.stylesheets)),
                        Template.renderScripts(me._scripts.concat(me.project.scripts))
                        ),
                index = Template.renderIndex(me.project.getProjectFolder(me.project.indexTemplate), {
                    name: me.project.name,
                    headers: headers
                }),
                indexFile = me.project.getBuildFolder(me.project.indexTemplate);
        Logger.info('Deploying: ' + indexFile);
        fs.writeFileSync(indexFile, index);
    },
    /**
     * Deploys the scripts and stylesheets in the dev mode
     */
    deployDevScriptsAndStyleSheets: function () {
        var me = this, target, scripts = [], stylesheets = [], status = true;

        Blend.foreach(me.depMap, function (item, cname) {
            target = me.getTargetPathAndUrl(item.classFile);
            if (target) {
                FileUtils.copyFile(target.srcFile, target.destFile);
                scripts.push({
                    src: target.url
                });
                Logger.info('Deploying: ', target.url);
            }
            if (item.cssFile) {
                target = me.getTargetPathAndUrl(item.cssFile);
                FileUtils.copyFile(target.srcFile, target.destFile);
                stylesheets.push({
                    src: target.url
                })
                Logger.info('Deploying: ', target.url);
            }
        });

        Blend.foreach([].concat(me.project.scripts, me.project.stylesheets), function (item) {
            if (fs.existsSync(item.src)) {
                target = me.getTargetPathAndUrl(item.src);

                if (target) {
                    FileUtils.copyFile(target.srcFile, target.destFile);
                    scripts.push({
                        src: target.url
                    });
                    Logger.info('Deploying: ', target.url);
                }
            } else {
                Logger.error('Unable to deploy:' + item.src);
                return (status = false);
            }
        });

        me._scripts = scripts;
        me._stylesheets = stylesheets;

        target = me.getTargetPathAndUrl(me.project.getSourceFolder('bootstrap.js'));
        FileUtils.copyFile(target.srcFile, target.destFile);

        return status;
    },
    /**
     * Translates the deployment path
     */
    getTargetPathAndUrl: function (file) {
        var me = this, dst, srcFile, destFile,
                sdkPath = Blend.getSDKFolder(),
                prjPath = me.project.getProjectFolder();
        if (file.startsWith(sdkPath)) {
            dst = file.replace(Blend.fixPath(sdkPath + '/'), 'blend/');
            srcFile = file;
            destFile = me.project.getBuildFolder(dst);
        } else {
            dst = file.replace(Blend.fixPath(prjPath), '');
            srcFile = file;
            destFile = me.project.getBuildFolder(dst);
        }
        return {
            srcFile: srcFile,
            destFile: destFile,
            url: dst.split(path.sep).join('/')
        }
    }
});

<commit_msg>Fixed incorrect script and style inclusion<commit_after>var fs = require('fs');
var path = require('path');

Blend.defineClass('Builder.commands.build.webapp.Builder', {
    extend: 'Builder.commands.build.AnalyzerBase',
    /**
     * Build the Development version of the application
     * @returns {undefined}
     */
    buildDevelVersion: function () {
        var me = this;
        /**
         * Build steps:
         * [1] Clean the build folder. This is done by the base before getting here.
         * [2] Deploy the mandatory blend resources, font icons and images. (blend folder)
         * [3] Deploy blend's JavaScript files (blend folder)
         * [4] Deploy application's js files
         * @returns {Boolean}
         */
        me.deployIconFonts();
        if (me.deployDevScriptsAndStyleSheets()) {
            me.createDevIndex();
            return true;
        } else {
            return false;
        }

    },
    /**
     * Created the index file for the development mode
     * @returns {undefined}
     */
    createDevIndex: function () {
        var me = this,
                buildNumber = me.project.bumpBuildNumber(true),
                headers = Template.renderDevHeaders(
                        Template.renderMetaTags(me.project.meta),
                        Template.renderStyleSheets([].concat(me._stylesheets, me.project.stylesheets)),
                        Template.renderScripts([].concat(me._scripts, me.project.scripts))
                        ),
                index = Template.renderIndex(me.project.getProjectFolder(me.project.indexTemplate), {
                    name: me.project.name,
                    headers: headers,
                    project: me.project,
                    build_number: buildNumber
                }),
                indexFile = me.project.getBuildFolder(me.project.indexTemplate);
        Logger.info('Deploying: ' + indexFile);
        fs.writeFileSync(indexFile, index);
    },
    /**
     * Deploys the scripts and stylesheets in the dev mode
     */
    deployDevScriptsAndStyleSheets: function () {
        var me = this, target, scripts = [], stylesheets = [], status = true;
        Blend.foreach(me.depMap, function (item, cname) {
            target = me.getTargetPathAndUrl(item.classFile);
            if (target) {
                FileUtils.copyFile(target.srcFile, target.destFile);
                scripts.push({
                    src: target.url
                });
                Logger.info('Deploying: ', target.url);
            }
            if (item.cssFile) {
                target = me.getTargetPathAndUrl(item.cssFile);
                FileUtils.copyFile(target.srcFile, target.destFile);
                stylesheets.push({
                    src: target.url
                });
                Logger.info('Deploying: ', target.url);
            }
        });

        Blend.foreach([].concat(me.project.scripts, me.project.stylesheets), function (item) {
            if (fs.existsSync(item.src)) {
                target = me.getTargetPathAndUrl(item.src);
                if (target) {
                    FileUtils.copyFile(target.srcFile, target.destFile);
                    Logger.info('Deploying: ', target.url);
                }
            } else {
                Logger.error('Unable to deploy:' + item.src);
                return (status = false);
            }
        });

        me._scripts = scripts;
        me._stylesheets = stylesheets;

        target = me.getTargetPathAndUrl(me.project.getSourceFolder('bootstrap.js'));
        FileUtils.copyFile(target.srcFile, target.destFile);

        return status;
    },
    /**
     * Translates the deployment path
     */
    getTargetPathAndUrl: function (file) {
        var me = this, dst, srcFile, destFile,
                sdkPath = Blend.getSDKFolder(),
                prjPath = me.project.getProjectFolder();
        if (file.startsWith(sdkPath)) {
            dst = file.replace(Blend.fixPath(sdkPath + '/'), 'blend/');
            srcFile = file;
            destFile = me.project.getBuildFolder(dst);
        } else {
            dst = file.replace(Blend.fixPath(prjPath), '');
            srcFile = file;
            destFile = me.project.getBuildFolder(dst);
        }
        return {
            srcFile: srcFile,
            destFile: destFile,
            url: dst.split(path.sep).join('/')
        }
    }
});

<|endoftext|>


<commit_before>/* global window, console */

(function (window) {
    'use strict';

    var localStore = window.localStorage,
        validTypes = ["string", "number", "object", "date", "boolean"],
        rootAppState,
        FloppyDisk;

    function extractValue(val) {
        var returnVal;
        switch (val.type) {
        case "number":
            returnVal = parseFloat(val.value);
            break;
        case "date":
            returnVal = new Date(val.value);
            break;
        case "string":
        case "object":
        case "boolean":
            returnVal = val.value;
            break;
        default:
            returnVal = val;
        }
        return returnVal;
    }

    function isObjectOrArray(v) {
        var toClass = {}.toString;
        var classType = toClass.call(v);
        return classType === "[object Object]" || classType === "[object Array]";
    }

    function Value(val, type) {
        if (type && validTypes.indexOf(type) === -1) {
            throw new Error("Unsupported type. Not saved. Condemned.");
        }
        this.type = (type || typeof val);
        this.value = val;
    }

    function writeProperties(stateObj) {
        for (let key in stateObj) {
            writeProperty(key, stateObj[key]);
        }
        return FloppyDisk;
    }

    function writeProperty(key, val, type) {
        localStore.setItem(key, typeSerializer(val, type) );
        return FloppyDisk;
    }

    function readProperties() {
        var obj = {};
        for (let i =0, ilength = localStore.length; i < ilength; i++) {
            let key = localStore.key(i);
            obj[key] = jsonDeserializer(localStore.getItem(key));
        }
        return obj;
    }

    function readProperty(key) {
        var serialProp = localStore.getItem(key);
        return jsonDeserializer(serialProp);
    }

    function deleteProperty(key) {
        localStore.removeItem(key);
        return FloppyDisk;
    }

    function clearState() {
        clearRootAppState();
        localStore.clear();
        return FloppyDisk;
    }

    function clearRootAppState() {
        rootAppState = undefined;
    }

    function typeSerializer(val, type) {
        return jsonSerializer(new Value(val, type));
    }

    function jsonSerializer(obj) {
        return JSON.stringify(obj);
    }

    function jsonDeserializer(str) {
        var deserializedObj;
        try {
            deserializedObj = JSON.parse(str);
        } catch (e) {
            console.error("Failed to parse text as JSON. Must not be valid JSON.");
        }
        return extractValue(deserializedObj);
    }

    function observe(appState) {
        var handler = {
            set: function (origObj, key, value) {
                origObj[key] = value;
                writeProperties(rootAppState); // clobber everything since we don't know how deep we are
            },
            deleteProperty: function (origObj, key) {
                delete origObj[key];
                deleteProperty(key); //doesn't matter if this isn't top level property - about to clobber anyway - but must in case it is.
                writeProperties(rootAppState);
            }
        };
        for (let key in appState) {
            if (isObjectOrArray(appState[key])) {
                appState[key] = observe(appState[key]);
            }
        }
        return new Proxy(appState, handler);
    }

    FloppyDisk = {
        saveFiles: writeProperties,
        saveFile: writeProperty,
        loadFiles: readProperties,
        loadFile: readProperty,
        deleteFile: deleteProperty,
        format: clearState,
        autoSave: function(appState) {
            if (rootAppState) {throw new Error('Autosave already initiated. Specify one root object only.');}
            rootAppState = appState;
            writeProperties(appState);
            return observe(appState);
        },
        eject: function () {clearRootAppState(); window.FloppyDisk = DF0; return DF0;}
    };

    var DF0 = {
        insert: function() {window.FloppyDisk = FloppyDisk; return FloppyDisk;}
    };

    window.FloppyDisk = DF0;

}(window));<commit_msg>Fix proxy handler, handle existing localstorage values as strings.<commit_after>/* global window, console */

(function (window) {
    'use strict';

    var localStore = window.localStorage,
        validTypes = ["string", "number", "object", "date", "boolean"],
        toClass = {}.toString,
        rootAppState,
        FloppyDisk;

    function extractValue(val) {
        var returnVal;
        switch (val.type) {
        case "number":
            returnVal = parseFloat(val.value);
            break;
        case "date":
            returnVal = new Date(val.value);
            break;
        case "string":
        case "object":
        case "boolean":
            returnVal = val.value;
            break;
        default:
            returnVal = val;
        }
        return returnVal;
    }

    function isObjectOrArray(v) {
        var classType = toClass.call(v);
        return classType === "[object Object]" || classType === "[object Array]";
    }

    function Value(val, type) {
        if (type && validTypes.indexOf(type) === -1) {
            throw new Error("Unsupported type. Not saved. Condemned.");
        }
        this.type = (type || typeof val);
        this.value = val;
    }

    function writeProperties(stateObj) {
        for (let key in stateObj) {
            writeProperty(key, stateObj[key]);
        }
        return FloppyDisk;
    }

    function writeProperty(key, val, type) {
        localStore.setItem(key, typeSerializer(val, type) );
        return FloppyDisk;
    }

    function readProperties() {
        var obj = {};
        for (let i =0, ilength = localStore.length; i < ilength; i++) {
            let key = localStore.key(i);
            obj[key] = jsonDeserializer(localStore.getItem(key));
        }
        return obj;
    }

    function readProperty(key) {
        var serialProp = localStore.getItem(key);
        return jsonDeserializer(serialProp);
    }

    function deleteProperty(key) {
        localStore.removeItem(key);
        return FloppyDisk;
    }

    function clearState() {
        clearRootAppState();
        localStore.clear();
        return FloppyDisk;
    }

    function clearRootAppState() {
        rootAppState = undefined;
    }

    function typeSerializer(val, type) {
        return jsonSerializer(new Value(val, type));
    }

    function jsonSerializer(obj) {
        return JSON.stringify(obj);
    }

    function jsonDeserializer(str) {
        var deserializedObj;
        try {
            deserializedObj = JSON.parse(str);
        } catch (e) {
            console.error("Failed to parse text '"+ str + "' as JSON. Probably an existing string in local storage. Returning plain text value.");
            deserializedObj = {type:"string", value:str};
        }
        return extractValue(deserializedObj);
    }

    function observe(appState) {
        var handler = {
            set: function (origObj, key, value) {
                if (isObjectOrArray(value)) {
                    value = observe(value);
                }
                origObj[key] = value;
                writeProperties(rootAppState); // clobber everything since we don't know how deep we are
                return true;
            },
            deleteProperty: function (origObj, key) {
                delete origObj[key];
                deleteProperty(key); //doesn't matter if this isn't top level property - about to clobber anyway - but must in case it is.
                writeProperties(rootAppState);
                return true;
            }
        };
        for (let key in appState) {
            if (isObjectOrArray(appState[key])) {
                appState[key] = observe(appState[key]);
            }
        }
        return new Proxy(appState, handler);
    }

    FloppyDisk = {
        saveFiles: writeProperties,
        saveFile: writeProperty,
        loadFiles: readProperties,
        loadFile: readProperty,
        deleteFile: deleteProperty,
        format: clearState,
        autoSave: function(appState) {
            if (rootAppState) {throw new Error('Autosave already initiated. Specify one root object only.');}
            rootAppState = appState;
            writeProperties(appState);
            return observe(appState);
        },
        eject: function () {clearRootAppState(); window.FloppyDisk = DF0; return DF0;}
    };

    var DF0 = {
        insert: function() {window.FloppyDisk = FloppyDisk; return FloppyDisk;}
    };

    window.FloppyDisk = DF0;

}(window));<|endoftext|>


<commit_before>var propertiesKey = "properties";
var indentation = "    ";
var propertyValueStats = {};
var valueStats = {};

function updatePropertyValueStats(property, values) {
  if (propertyValueStats[property] === undefined) {
    propertyValueStats[property] = {};
  }

  $.each(values, function(idx, value) {
    if (propertyValueStats[property][value] === undefined) {
      propertyValueStats[property][value] = 0;
    }

    propertyValueStats[property][value] += 1;

    if (valueStats[value] === undefined) {
      valueStats[value] = 0;
    }

    valueStats[value] += 1;
  });
}

function typeOfValue(value) {
  if ($.inArray(value, colors) > 0) {
    return "color";
  }

  if (value.match(/^#/) || value.match(/^rgb\(/)) {
    return "color";
  }

  var maybeType = value.match(/(px|em|rem|%)$/);
  if ($.isArray(maybeType)) {
    if (maybeType[0] === "%") {
      return "percentage";
    }
    return maybeType[0];
  };

  return "other";
}

function leafToHTML(leaf) {
  var result = [];

  $.each(leaf, function(idx, line) {
    var values = line.substring(line.indexOf(":") + 1, line.indexOf(";")).match(/\S+/g);
    var property = line.substring(0, line.indexOf(":"));
    var newLine = "" + property + ":";
    $.each(values, function(idx, value) {
      newLine += " " + value + "";
    });

    result.push(newLine + ";
");
    updatePropertyValueStats(property, values);
  });

  return result;
}

function treeToHTMLHelper(selector, tree) {
  if (selector === propertiesKey) {
    return leafToHTML(tree);
  }

  var treeKeys = Object.keys(tree).filter(function(key) { return key !== propertiesKey; });
  treeKeys.unshift(propertiesKey);
  var result = ["
" + selector + " {", indentation + "
"];
  $.each(treeKeys, function(idx, subtreeSelector) {
    if (subtreeSelector !== propertiesKey) {
      result.push("");
    }
    var subtree = tree[subtreeSelector];
    if (subtree === undefined) {
      subtree = {};
    }
    $.each(treeToHTMLHelper(subtreeSelector, subtree), function(idx, line) {
      result.push(indentation + line);
    });
  });

  result.push(indentation + "
");
  result.push("}
");
  return result;
}

function mixinsToHTML(mixins) {
  $.each(mixins, function(selector, subtree) {
    html += mixinsKey + " " + treeToHTMLHelper(selector, subtree).join("\n");
    html += "\n\n";
  });
}

function variablesToHTML(variables) {
  return "";
}

var mixinsKey = "@mixin";
var variablesKey = "variables";

function treeToHTML(tree) {
  var html = "";
  html += mixinsToHTML(tree[mixinsKey]);
  html += variablesToHTML(tree[variablesKey]);
  delete tree[mixinsKey];
  delete tree[variablesKey];

  $.each(tree, function(idx, val) {
    html += treeToHTMLHelper(idx, val).join("\n");
    html += "\n\n";
  });
  return html;
}

var colors = ['AliceBlue',
'AntiqueWhite',
'Aqua',
'Aquamarine',
'Azure',
'Beige',
'Bisque',
'Black',
'BlanchedAlmond',
'Blue',
'BlueViolet',
'Brown',
'BurlyWood',
'CadetBlue',
'Chartreuse',
'Chocolate',
'Coral',
'CornflowerBlue',
'Cornsilk',
'Crimson',
'Cyan',
'DarkBlue',
'DarkCyan',
'DarkGoldenRod',
'DarkGray',
'DarkGreen',
'DarkKhaki',
'DarkMagenta',
'DarkOliveGreen',
'DarkOrange',
'DarkOrchid',
'DarkRed',
'DarkSalmon',
'DarkSeaGreen',
'DarkSlateBlue',
'DarkSlateGray',
'DarkTurquoise',
'DarkViolet',
'DeepPink',
'DeepSkyBlue',
'DimGray',
'DodgerBlue',
'FireBrick',
'FloralWhite',
'ForestGreen',
'Fuchsia',
'Gainsboro',
'GhostWhite',
'Gold',
'GoldenRod',
'Gray',
'Green',
'GreenYellow',
'HoneyDew',
'HotPink',
'IndianRed',
'Indigo',
'Ivory',
'Khaki',
'Lavender',
'LavenderBlush',
'LawnGreen',
'LemonChiffon',
'LightBlue',
'LightCoral',
'LightCyan',
'LightGoldenRodYellow',
'LightGray',
'LightGreen',
'LightPink',
'LightSalmon',
'LightSeaGreen',
'LightSkyBlue',
'LightSlateGray',
'LightSteelBlue',
'LightYellow',
'Lime',
'LimeGreen',
'Linen',
'Magenta',
'Maroon',
'MediumAquaMarine',
'MediumBlue',
'MediumOrchid',
'MediumPurple',
'MediumSeaGreen',
'MediumSlateBlue',
'MediumSpringGreen',
'MediumTurquoise',
'MediumVioletRed',
'MidnightBlue',
'MintCream',
'MistyRose',
'Moccasin',
'NavajoWhite',
'Navy',
'OldLace',
'Olive',
'OliveDrab',
'Orange',
'OrangeRed',
'Orchid',
'PaleGoldenRod',
'PaleGreen',
'PaleTurquoise',
'PaleVioletRed',
'PapayaWhip',
'PeachPuff',
'Peru',
'Pink',
'Plum',
'PowderBlue',
'Purple',
'Red',
'RosyBrown',
'RoyalBlue',
'SaddleBrown',
'Salmon',
'SandyBrown',
'SeaGreen',
'SeaShell',
'Sienna',
'Silver',
'SkyBlue',
'SlateBlue',
'SlateGray',
'Snow',
'SpringGreen',
'SteelBlue',
'Tan',
'Teal',
'Thistle',
'Tomato',
'Turquoise',
'Violet',
'Wheat',
'White',
'WhiteSmoke',
'Yellow',
'YellowGreen']
<commit_msg>bug fix<commit_after>var propertiesKey = "properties";
var indentation = "    ";
var propertyValueStats = {};
var valueStats = {};

function updatePropertyValueStats(property, values) {
  if (propertyValueStats[property] === undefined) {
    propertyValueStats[property] = {};
  }

  $.each(values, function(idx, value) {
    if (propertyValueStats[property][value] === undefined) {
      propertyValueStats[property][value] = 0;
    }

    propertyValueStats[property][value] += 1;

    if (valueStats[value] === undefined) {
      valueStats[value] = 0;
    }

    valueStats[value] += 1;
  });
}

function typeOfValue(value) {
  if ($.inArray(value, colors) > 0) {
    return "color";
  }

  if (value.match(/^#/) || value.match(/^rgb\(/)) {
    return "color";
  }

  var maybeType = value.match(/(px|em|rem|%)$/);
  if ($.isArray(maybeType)) {
    if (maybeType[0] === "%") {
      return "percentage";
    }
    return maybeType[0];
  };

  return "other";
}

function leafToHTML(leaf) {
  var result = [];

  $.each(leaf, function(idx, line) {
    var values = line.substring(line.indexOf(":") + 1, line.indexOf(";")).match(/\S+/g);
    var property = line.substring(0, line.indexOf(":"));
    var newLine = "" + property + ":";
    $.each(values, function(idx, value) {
      newLine += " " + value + "";
    });

    result.push(newLine + ";
");
    updatePropertyValueStats(property, values);
  });

  return result;
}

function treeToHTMLHelper(selector, tree) {
  if (selector === propertiesKey) {
    return leafToHTML(tree);
  }

  var treeKeys = Object.keys(tree).filter(function(key) { return key !== propertiesKey; });
  treeKeys.unshift(propertiesKey);
  var result = ["
" + selector + " {", indentation + "
"];
  $.each(treeKeys, function(idx, subtreeSelector) {
    if (subtreeSelector !== propertiesKey) {
      result.push("");
    }
    var subtree = tree[subtreeSelector];
    if (subtree === undefined) {
      subtree = {};
    }
    $.each(treeToHTMLHelper(subtreeSelector, subtree), function(idx, line) {
      result.push(indentation + line);
    });
  });

  result.push(indentation + "
");
  result.push("}
");
  return result;
}

function mixinsToHTML(mixins) {
  var html "";
  $.each(mixins, function(selector, subtree) {
    html += mixinsKey + " " + treeToHTMLHelper(selector, subtree).join("\n");
    html += "\n\n";
  });
  return html;
}

function variablesToHTML(variables) {
  return "";
}

var mixinsKey = "@mixin";
var variablesKey = "variables";

function treeToHTML(tree) {
  var html = "";
  html += mixinsToHTML(tree[mixinsKey]);
  html += variablesToHTML(tree[variablesKey]);
  delete tree[mixinsKey];
  delete tree[variablesKey];

  $.each(tree, function(idx, val) {
    html += treeToHTMLHelper(idx, val).join("\n");
    html += "\n\n";
  });
  return html;
}

var colors = ['AliceBlue',
'AntiqueWhite',
'Aqua',
'Aquamarine',
'Azure',
'Beige',
'Bisque',
'Black',
'BlanchedAlmond',
'Blue',
'BlueViolet',
'Brown',
'BurlyWood',
'CadetBlue',
'Chartreuse',
'Chocolate',
'Coral',
'CornflowerBlue',
'Cornsilk',
'Crimson',
'Cyan',
'DarkBlue',
'DarkCyan',
'DarkGoldenRod',
'DarkGray',
'DarkGreen',
'DarkKhaki',
'DarkMagenta',
'DarkOliveGreen',
'DarkOrange',
'DarkOrchid',
'DarkRed',
'DarkSalmon',
'DarkSeaGreen',
'DarkSlateBlue',
'DarkSlateGray',
'DarkTurquoise',
'DarkViolet',
'DeepPink',
'DeepSkyBlue',
'DimGray',
'DodgerBlue',
'FireBrick',
'FloralWhite',
'ForestGreen',
'Fuchsia',
'Gainsboro',
'GhostWhite',
'Gold',
'GoldenRod',
'Gray',
'Green',
'GreenYellow',
'HoneyDew',
'HotPink',
'IndianRed',
'Indigo',
'Ivory',
'Khaki',
'Lavender',
'LavenderBlush',
'LawnGreen',
'LemonChiffon',
'LightBlue',
'LightCoral',
'LightCyan',
'LightGoldenRodYellow',
'LightGray',
'LightGreen',
'LightPink',
'LightSalmon',
'LightSeaGreen',
'LightSkyBlue',
'LightSlateGray',
'LightSteelBlue',
'LightYellow',
'Lime',
'LimeGreen',
'Linen',
'Magenta',
'Maroon',
'MediumAquaMarine',
'MediumBlue',
'MediumOrchid',
'MediumPurple',
'MediumSeaGreen',
'MediumSlateBlue',
'MediumSpringGreen',
'MediumTurquoise',
'MediumVioletRed',
'MidnightBlue',
'MintCream',
'MistyRose',
'Moccasin',
'NavajoWhite',
'Navy',
'OldLace',
'Olive',
'OliveDrab',
'Orange',
'OrangeRed',
'Orchid',
'PaleGoldenRod',
'PaleGreen',
'PaleTurquoise',
'PaleVioletRed',
'PapayaWhip',
'PeachPuff',
'Peru',
'Pink',
'Plum',
'PowderBlue',
'Purple',
'Red',
'RosyBrown',
'RoyalBlue',
'SaddleBrown',
'Salmon',
'SandyBrown',
'SeaGreen',
'SeaShell',
'Sienna',
'Silver',
'SkyBlue',
'SlateBlue',
'SlateGray',
'Snow',
'SpringGreen',
'SteelBlue',
'Tan',
'Teal',
'Thistle',
'Tomato',
'Turquoise',
'Violet',
'Wheat',
'White',
'WhiteSmoke',
'Yellow',
'YellowGreen']
<|endoftext|>


<commit_before>'use strict';

var plurals = require('./plurals');
var gettextParser = require('gettext-parser');

module.exports = Gettext;

/**
 * Gettext function
 *
 * @constructor
 */
function Gettext() {
    this.domains = {};
    this._currentDomain = false;
}

/**
 * Adds a gettext to the domains list. If default textdomain is not set, uses it
 * as default
 *
 * @param {String} domain Case insensitive language identifier (domain)
 * @param {Buffer} fileContents Translations file (*.mo) contents as a Buffer object
 */
Gettext.prototype.addTextdomain = function(domain, file) {
    domain = this._normalizeDomain(domain);
    var translation;

    if (file && typeof file !== 'string') {
        translation = gettextParser.mo.parse(file, 'utf-8');
    }

    if (!translation) {
        translation = gettextParser.po.parse(file || '', 'utf-8');
    }

    // We do not want to parse and compile stuff from unknown sources
    // so we only use precompiled plural definitions
    var pluralsInfo = plurals[this._normalizeDomain(domain, true)];
    if (pluralsInfo) {
        translation.headers['plural-forms'] = pluralsInfo.pluralsText;
        translation.pluralsFunc = pluralsInfo.pluralsFunc;
    } else {
        // default plurals to EN rules
        translation.pluralsFunc = plurals.en.pluralsFunc;
    }

    this.domains[domain] = translation;

    if (!this._currentDomain) {
        this._currentDomain = domain;
    }
};

/**
 * Changes the current default textdomain
 *
 * @param {String} [domain] Case insensitive language identifier
 * @return {String} cuurent textdomain
 */
Gettext.prototype.textdomain = function(updatedDomain) {
    if (!arguments.length) {
        return this._currentDomain;
    }

    updatedDomain = this._normalizeDomain(updatedDomain);
    if (this._currentDomain !== updatedDomain && this.domains.hasOwnProperty(updatedDomain)) {
        this._currentDomain = updatedDomain;
        return true;
    } else {
        return false;
    }
};

/**
 * Translates a string using the default textdomain
 *
 * @param {String} msgid String to be translated
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.gettext = function(msgid) {
    return this.dnpgettext(this._currentDomain, '', msgid);
};

/**
 * Translates a string using a specific domain
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgid String to be translated
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.dgettext = function(domain, msgid) {
    return this.dnpgettext(domain, '', msgid);
};

/**
 * Translates a plural string using the default textdomain
 *
 * @param {String} msgid String to be translated
 * @param {String} msgidPlural If no translation was found, return this on count!=1
 * @param {Number} count Number count for the plural
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.ngettext = function(msgid, msgidPlural, count) {
    return this.dnpgettext(this._currentDomain, '', msgid, msgidPlural, count);
};

/**
 * Translates a plural string using a specific textdomain
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgid String to be translated
 * @param {String} msgidPlural If no translation was found, return this on count!=1
 * @param {Number} count Number count for the plural
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.dngettext = function(domain, msgid, msgidPlural, count) {
    return this.dnpgettext(domain, '', msgid, msgidPlural, count);
};

/**
 * Translates a string from a specific context using the default textdomain
 *
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.pgettext = function(msgctxt, msgid) {
    return this.dnpgettext(this._currentDomain, msgctxt, msgid);
};

/**
 * Translates a string from a specific context using s specific textdomain
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.dpgettext = function(domain, msgctxt, msgid) {
    return this.dnpgettext(domain, msgctxt, msgid);
};

/**
 * Translates a plural string from a specifi context using the default textdomain
 *
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @param {String} msgidPlural If no translation was found, return this on count!=1
 * @param {Number} count Number count for the plural
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.npgettext = function(msgctxt, msgid, msgidPlural, count) {
    return this.dnpgettext(this._currentDomain, msgctxt, msgid, msgidPlural, count);
};

/**
 * Translates a plural string from a specifi context using a specific textdomain
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @param {String} msgidPlural If no translation was found, return this on count!=1
 * @param {Number} count Number count for the plural
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.dnpgettext = function(domain, msgctxt, msgid, msgidPlural, count) {
    var defaultTranslation = msgid;
    var translation;
    var index;

    domain = this._normalizeDomain(domain);
    msgctxt = msgctxt || '';

    if (!isNaN(count) && count !== 1) {
        defaultTranslation = msgidPlural || msgid;
    }

    translation = this._getTranslation(domain, msgctxt, msgid);
    if (translation) {
        if (typeof count === 'number') {
            index = this.domains[domain].pluralsFunc(count);
            if (typeof index === 'boolean') {
                index = index ? 1 : 0;
            }
        } else {
            index = 0;
        }

        return translation.msgstr[index] || defaultTranslation;
    }
    return defaultTranslation;
};

/**
 * Retrieves comments object for a translation
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @return {Object} comments object or false if not found
 */
Gettext.prototype.getComment = function(domain, msgctxt, msgid) {
    var translation;

    domain = this._normalizeDomain(domain);

    translation = this._getTranslation(domain, msgctxt, msgid);
    if (translation) {
        return translation.comments || {};
    }

    return {};
};

/**
 * Retrieves translation object from the domain and context
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @return {Object} translation object or false if not found
 */
Gettext.prototype._getTranslation = function(domain, msgctxt, msgid) {
    var translation;

    msgctxt = msgctxt || '';
    domain = this._normalizeDomain(domain);

    if (this.domains.hasOwnProperty(domain)) {
        if (this.domains[domain].translations && this.domains[domain].translations[msgctxt]) {
            if ((translation = this.domains[domain].translations[msgctxt][msgid])) {
                return translation;
            }
        }
    }

    return false;
};

/**
 * Normalizes textdomain value
 *
 * @param {String} domain Textdomain
 * @param {Boolean} [isShort] If true then returns only language
 * @returns {String} Normalized textdomain
 */
Gettext.prototype._normalizeDomain = function(domain, isShort) {
    var parts = (domain || '').toString().split('.').shift().split(/[\-_]/);
    var language = (parts.shift() || '').toLowerCase();
    var locale = (parts.join('-') || '').toUpperCase();

    if (isShort) {
        return language;
    } else {
        return [].concat(language || []).concat(locale || []).join('_');
    }
};<commit_msg>Solves TypeError: Cannot set property 'plural-forms' of undefined on node v0.10.25<commit_after>'use strict';

var plurals = require('./plurals');
var gettextParser = require('gettext-parser');

module.exports = Gettext;

/**
 * Gettext function
 *
 * @constructor
 */
function Gettext() {
    this.domains = {};
    this._currentDomain = false;
}

/**
 * Adds a gettext to the domains list. If default textdomain is not set, uses it
 * as default
 *
 * @param {String} domain Case insensitive language identifier (domain)
 * @param {Buffer} fileContents Translations file (*.mo) contents as a Buffer object
 */
Gettext.prototype.addTextdomain = function(domain, file) {
    domain = this._normalizeDomain(domain);
    var translation;

    if (file && typeof file !== 'string') {
        translation = gettextParser.mo.parse(file, 'utf-8');
    }

    if (!translation) {
        translation = gettextParser.po.parse(file || '', 'utf-8');
    }

    // We do not want to parse and compile stuff from unknown sources
    // so we only use precompiled plural definitions
    var pluralsInfo = plurals[this._normalizeDomain(domain, true)];
    if (pluralsInfo && translation.headers) {
        translation.headers['plural-forms'] = pluralsInfo.pluralsText;
        translation.pluralsFunc = pluralsInfo.pluralsFunc;
    } else {
        // default plurals to EN rules
        translation.pluralsFunc = plurals.en.pluralsFunc;
    }

    this.domains[domain] = translation;

    if (!this._currentDomain) {
        this._currentDomain = domain;
    }
};

/**
 * Changes the current default textdomain
 *
 * @param {String} [domain] Case insensitive language identifier
 * @return {String} cuurent textdomain
 */
Gettext.prototype.textdomain = function(updatedDomain) {
    if (!arguments.length) {
        return this._currentDomain;
    }

    updatedDomain = this._normalizeDomain(updatedDomain);
    if (this._currentDomain !== updatedDomain && this.domains.hasOwnProperty(updatedDomain)) {
        this._currentDomain = updatedDomain;
        return true;
    } else {
        return false;
    }
};

/**
 * Translates a string using the default textdomain
 *
 * @param {String} msgid String to be translated
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.gettext = function(msgid) {
    return this.dnpgettext(this._currentDomain, '', msgid);
};

/**
 * Translates a string using a specific domain
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgid String to be translated
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.dgettext = function(domain, msgid) {
    return this.dnpgettext(domain, '', msgid);
};

/**
 * Translates a plural string using the default textdomain
 *
 * @param {String} msgid String to be translated
 * @param {String} msgidPlural If no translation was found, return this on count!=1
 * @param {Number} count Number count for the plural
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.ngettext = function(msgid, msgidPlural, count) {
    return this.dnpgettext(this._currentDomain, '', msgid, msgidPlural, count);
};

/**
 * Translates a plural string using a specific textdomain
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgid String to be translated
 * @param {String} msgidPlural If no translation was found, return this on count!=1
 * @param {Number} count Number count for the plural
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.dngettext = function(domain, msgid, msgidPlural, count) {
    return this.dnpgettext(domain, '', msgid, msgidPlural, count);
};

/**
 * Translates a string from a specific context using the default textdomain
 *
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.pgettext = function(msgctxt, msgid) {
    return this.dnpgettext(this._currentDomain, msgctxt, msgid);
};

/**
 * Translates a string from a specific context using s specific textdomain
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.dpgettext = function(domain, msgctxt, msgid) {
    return this.dnpgettext(domain, msgctxt, msgid);
};

/**
 * Translates a plural string from a specifi context using the default textdomain
 *
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @param {String} msgidPlural If no translation was found, return this on count!=1
 * @param {Number} count Number count for the plural
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.npgettext = function(msgctxt, msgid, msgidPlural, count) {
    return this.dnpgettext(this._currentDomain, msgctxt, msgid, msgidPlural, count);
};

/**
 * Translates a plural string from a specifi context using a specific textdomain
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @param {String} msgidPlural If no translation was found, return this on count!=1
 * @param {Number} count Number count for the plural
 * @return {String} translation or the original string if no translation was found
 */
Gettext.prototype.dnpgettext = function(domain, msgctxt, msgid, msgidPlural, count) {
    var defaultTranslation = msgid;
    var translation;
    var index;

    domain = this._normalizeDomain(domain);
    msgctxt = msgctxt || '';

    if (!isNaN(count) && count !== 1) {
        defaultTranslation = msgidPlural || msgid;
    }

    translation = this._getTranslation(domain, msgctxt, msgid);
    if (translation) {
        if (typeof count === 'number') {
            index = this.domains[domain].pluralsFunc(count);
            if (typeof index === 'boolean') {
                index = index ? 1 : 0;
            }
        } else {
            index = 0;
        }

        return translation.msgstr[index] || defaultTranslation;
    }
    return defaultTranslation;
};

/**
 * Retrieves comments object for a translation
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @return {Object} comments object or false if not found
 */
Gettext.prototype.getComment = function(domain, msgctxt, msgid) {
    var translation;

    domain = this._normalizeDomain(domain);

    translation = this._getTranslation(domain, msgctxt, msgid);
    if (translation) {
        return translation.comments || {};
    }

    return {};
};

/**
 * Retrieves translation object from the domain and context
 *
 * @param {String} domain Case insensitive language identifier
 * @param {String} msgctxt Translation context
 * @param {String} msgid String to be translated
 * @return {Object} translation object or false if not found
 */
Gettext.prototype._getTranslation = function(domain, msgctxt, msgid) {
    var translation;

    msgctxt = msgctxt || '';
    domain = this._normalizeDomain(domain);

    if (this.domains.hasOwnProperty(domain)) {
        if (this.domains[domain].translations && this.domains[domain].translations[msgctxt]) {
            if ((translation = this.domains[domain].translations[msgctxt][msgid])) {
                return translation;
            }
        }
    }

    return false;
};

/**
 * Normalizes textdomain value
 *
 * @param {String} domain Textdomain
 * @param {Boolean} [isShort] If true then returns only language
 * @returns {String} Normalized textdomain
 */
Gettext.prototype._normalizeDomain = function(domain, isShort) {
    var parts = (domain || '').toString().split('.').shift().split(/[\-_]/);
    var language = (parts.shift() || '').toLowerCase();
    var locale = (parts.join('-') || '').toUpperCase();

    if (isShort) {
        return language;
    } else {
        return [].concat(language || []).concat(locale || []).join('_');
    }
};
<|endoftext|>