<commit_before>/**
 * This kind provides:
 * - the project toolbars (with create .. delete)
 * - the project list
 *
 * The project list is a simple kind that only holds project names. It does not
 * hold project objects or kinds.
 */
enyo.kind({
	name: "ProjectList",
	classes: "enyo-unselectable ares_projectList",
	events: {
		onCreateProject: "",
		onProjectSelected: "",
		onScanProject: "",
		onProjectRemoved: "",
		onModifySettings: "",
		onPhonegapBuild: ""
	},
	handlers: {
	},
	projects: [],
	debug: false,
	components: [
		{kind: "LocalStorage"},
		{kind: "onyx.MoreToolbar", classes: "onyx-menu-toolbar ares_harmonia_toolBar ares-no-padding", isContainer: true, name: "toolbar", components: [
			{kind: "onyx.MenuDecorator", onSelect: "aresMenuItemSelected", components: [
				{content: "Ares"},
				{kind: "onyx.Menu", components: [
					{value: "showAccountConfigurator", components: [
						{kind: "onyx.IconButton", src: "$project-view/assets/images/ares_accounts.png"},
						{content: "Accounts..."}
					]},
					{classes: "onyx-menu-divider"},
					{content: "Properties..."}
				]}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", classes: "ares-scale-background", src: "$project-view/assets/images/project_settings.png", onclick: "doModifySettings"},
				{kind: "onyx.Tooltip", content: "Settings..."}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", src: "$project-view//assets/images/project_view_build.png", onclick: "doPhonegapBuild"},
				{kind: "onyx.Tooltip", content: "Phonegap build"}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", src: "$project-view//assets/images/project_preview.png", onclick: "doPreview"},
				{kind: "onyx.Tooltip", content: "Preview Project..."}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", src: "$project-view//assets/images/project_view_new.png", onclick: "doCreateProject"},
				{kind: "onyx.Tooltip", content: "Create or Import Project..."}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", src: "$project-view//assets/images/project_view_edit.png", onclick: "doScanProject"},
				{kind: "onyx.Tooltip", content: "Scan for Projects..."}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", src: "$project-view//assets/images/project_view_delete.png", onclick: "removeProjectAction"},
				// FIXME: tooltip goes under File Toolbar, there's an issue with z-index stuff
				{kind: "onyx.Tooltip", content: "Remove Project..."}
			]}
		]},
		{kind: "enyo.Scroller", components: [
			{kind: "enyo.Repeater", controlParentName: "client", fit: true, name: "projectList", onSetupItem: "projectListSetupItem", ontap: "projectListTap", components: [
				{kind: "ProjectList.Project", name: "item", classes: "enyo-children-inline ares_projectView_projectList_item"}
			]}
		]},
		{name: "removeProjectPopup", kind: "ProjectDeletePopup", onConfirmDeleteProject: "confirmRemoveProject"},
		{name: "errorPopup", kind: "Ares.ErrorPopup", msg: "unknown error"},
		{kind: "AccountsConfigurator"},
		{kind: "Signals", onServicesChange: "handleServicesChange"}
	],
	PROJECTS_STORAGE_KEY: "com.enyojs.ares.projects",
	selected: null,
	debug: false,
	create: function() {
		this.inherited(arguments);
		if (ProjectList.underTest) {
			this.PROJECTS_STORAGE_KEY = "com.enyojs.ares.tests";
		} else
			this.$.localStorage.get(this.PROJECTS_STORAGE_KEY, enyo.bind(this, this.projectListAvailable));
	},
	/**
	 * Callback functions which receives the project list data read from the storage
	 * @protected
	 * @param data: the project list in json format
	 */
	projectListAvailable: function(data) {
		try {
			if (data && data !== "") {
				this.projects = JSON.parse(data);
				if (this.debug) console.dir(this.projects);
			}
			this.$.projectList.setCount(this.projects.length);
		} catch(error) {
			this.error("Unable to retrieve projects information: " + error);	// TODO ENYO-1105
			console.dir(data);	// Display the offending data in the console
			this.$.localStorage.remove(this.PROJECTS_STORAGE_KEY); // Remove incorrect projects information
			this.projects = [];
		}
	},
	storeProjectsInLocalStorage: function() {
		var projectsString;
		if (this.debug) console.dir(this.projects);
		try {
			projectsString = JSON.stringify(this.projects, enyo.bind(this, this.stringifyReplacer));
		} catch(error) {
			this.error("Unable to store the project information: " + error);	// TODO ENYO-1105
			console.dir(this.projects);		// Display the offending object in the console
			return;
		}
		this.$.localStorage.set(this.PROJECTS_STORAGE_KEY, projectsString, function() {
			// WARNING: LocalStorage does not return any information about operation status (success or error)
			enyo.log("Project list saved");
		});
	},
	addProject: function(name, folderId, service) {
		var project = {
			name: name,
			folderId: folderId,
			serviceId: service.getConfig().id
		};
		if (!project.serviceId) {
			throw new Error("Cannot add a project in service=" + service);
		}
		var known = 0;
		var match = function(proj) {
			if ( proj.name === name) {
				known = 1;
			}
		} ;
		enyo.forEach(this.projects, match) ;
		if (known) {
			this.log("Skipped project " + name + " as it is already listed") ;
		}
		else {
			this.projects.push(project);
			this.storeProjectsInLocalStorage();
			this.$.projectList.setCount(this.projects.length);
			this.$.projectList.render();
		}
	},
	renameSelectedProject: function(newName) {
		var old = this.selected.getProjectName;
		var p;
		for (p in this.projects) {
			if (this.projects[p].name === old ) {
				this.projects[p].name = newName ;
			}
		}
		this.selected.setProjectName(newName) ;
		this.storeProjectsInLocalStorage();
	},
	removeProjectAction: function(inSender, inEvent) {
		var popup = this.$.removeProjectPopup;
		if (this.selected) {
			popup.setName("Delete project '" + this.selected.getProjectName() + "' ?");
			popup.$.nukeFiles.setValue(false) ;
			popup.show();
		}
	},
	confirmRemoveProject: function(inSender, inEvent) {
		// use file system service to remove project files (which behaves like a 'rm -rf')
		// once done,  call removeSelectedProjectData to mop up the remains.
		var project, nukeFiles ;
		if (this.selected) {
			project = this.projects[this.selected.index] ;
			nukeFiles = this.$.removeProjectPopup.$.nukeFiles.getValue() ;
			this.log("removing project" +  project.name + ( nukeFiles ? " and its files" : "" )) ;
			this.debug && this.log(project) ;
			if (nukeFiles) {
				project.service.remove( project.folderId )
					.response(this, function(){this.removeSelectedProjectData();})
					.error(this, function(inError){
						this.showErrorPopup("Error removing files of project " + project.name + ": " + inError);
					}) ;
			}
			else {
				this.removeSelectedProjectData() ;
			}
		}
	},
	removeSelectedProjectData: function() {
		if (this.selected) {
			// remove the project from list of project config
			this.projects.splice(this.selected.index, 1);
			this.storeProjectsInLocalStorage();
			this.selected = null;
			this.$.projectList.setCount(this.projects.length);
			this.$.projectList.render();
			this.doProjectRemoved();
		}
	},
	projectListSetupItem: function(inSender, inEvent) {
		var project = this.projects[inEvent.index];
		var item = inEvent.item;
		// setup the controls for this item.
		item = item.$.item;
		item.setProjectName(project.name);
		item.setIndex(inEvent.index);
	},
	projectListTap: function(inSender, inEvent) {
		var project, msg;
		// Un-highlight former selection, if any
		if (this.selected) {
			this.selected.removeClass("ares_projectView_projectList_item_selected");
		}
		project = this.projects[inEvent.index];
		project.service = ServiceRegistry.instance.resolveServiceId(project.serviceId);
		if (project.service) {
			// Highlight a project item if & only if its
			// filesystem service provider exists.
			if (inEvent.originator.kind === 'ProjectList.Project') {
				this.selected = inEvent.originator;
			} else {
				this.selected = inEvent.originator.owner;
			}
			this.selected.addClass("ares_projectView_projectList_item_selected");
			this.doProjectSelected({project: project});
		} else {
			// ...otherwise let
			msg = "Service " + project.serviceId + " not found";
			this.showErrorPopup(msg);
			this.error(msg);
		}
	},
	showAccountConfigurator: function() {
		this.$.accountsConfigurator.show();
	},
	aresMenuItemSelected: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		if (typeof this[inEvent.selected.value] === 'function') {
			this[inEvent.selected.value]();
		}
	},
	showErrorPopup : function(msg) {
		this.$.errorPopup.setErrorMsg(msg);
		this.$.errorPopup.show();
	},
	stringifyReplacer: function(key, value) {
		if (key === "originator") {
			return undefined;	// Exclude
		}
		return value;	// Accept
	},
	statics: {
		underTest: false
	}
});

enyo.kind({
	name: "ProjectList.Project",
	published: {
		projectName: "",
		index: -1
	},
	components: [
		{name: "name"}
	],
	projectNameChanged: function(inOldValue) {
		this.$.name.setContent(this.projectName);
	}
});

enyo.kind({
	name: "ProjectDeletePopup",
	kind: "Ares.ActionPopup",
	components: [
		{kind: "Control", tag: "h3", content: " ", name: "title"},
		{kind: "Control", tag: "br"},
		{kind: "onyx.Checkbox", checked: false, name: "nukeFiles"},
		{kind: "Control", tag: "span", style: "padding: 0 4px; vertical-align: middle;", content: "also delete files", fit: true},
		{kind: "FittableColumns", name: "buttons", components: [
			{kind: "onyx.Button", classes: "onyx-negative", content: "Cancel", name: "cancelButton", ontap: "actionCancel"},
			{kind: "onyx.Button", classes: "onyx-affirmative", content: "Delete", name: "actionButton", ontap: "actionConfirm"}
		]}
	]
});
<commit_msg>ENYO-992: put back project create on the front<commit_after>/**
 * This kind provides:
 * - the project toolbars (with create .. delete)
 * - the project list
 *
 * The project list is a simple kind that only holds project names. It does not
 * hold project objects or kinds.
 */
enyo.kind({
	name: "ProjectList",
	classes: "enyo-unselectable ares_projectList",
	events: {
		onCreateProject: "",
		onProjectSelected: "",
		onScanProject: "",
		onProjectRemoved: "",
		onModifySettings: "",
		onPhonegapBuild: ""
	},
	handlers: {
	},
	projects: [],
	debug: false,
	components: [
		{kind: "LocalStorage"},
		{kind: "onyx.MoreToolbar", classes: "onyx-menu-toolbar ares_harmonia_toolBar ares-no-padding", isContainer: true, name: "toolbar", components: [
			{kind: "onyx.MenuDecorator", onSelect: "aresMenuItemSelected", components: [
				{content: "Ares"},
				{kind: "onyx.Menu", components: [
					{value: "showAccountConfigurator", components: [
						{kind: "onyx.IconButton", src: "$project-view/assets/images/ares_accounts.png"},
						{content: "Accounts..."}
					]},
					{classes: "onyx-menu-divider"},
					{content: "Properties..."}
				]}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", src: "$project-view//assets/images/project_view_new.png", onclick: "doCreateProject"},
				{kind: "onyx.Tooltip", content: "Create or Import Project..."}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", src: "$project-view//assets/images/project_view_build.png", onclick: "doPhonegapBuild"},
				{kind: "onyx.Tooltip", content: "Phonegap build"}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", src: "$project-view//assets/images/project_preview.png", onclick: "doPreview"},
				{kind: "onyx.Tooltip", content: "Preview Project..."}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", classes: "ares-scale-background",
				 src: "$project-view/assets/images/project_settings.png", onclick: "doModifySettings"},
				{kind: "onyx.Tooltip", content: "Settings..."}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", src: "$project-view//assets/images/project_view_edit.png", onclick: "doScanProject"},
				{kind: "onyx.Tooltip", content: "Scan for Projects..."}
			]},
			{kind: "onyx.TooltipDecorator", components: [
				{kind: "onyx.IconButton", src: "$project-view//assets/images/project_view_delete.png", onclick: "removeProjectAction"},
				// FIXME: tooltip goes under File Toolbar, there's an issue with z-index stuff
				{kind: "onyx.Tooltip", content: "Remove Project..."}
			]}
		]},
		{kind: "enyo.Scroller", components: [
			{kind: "enyo.Repeater", controlParentName: "client", fit: true, name: "projectList", onSetupItem: "projectListSetupItem", ontap: "projectListTap", components: [
				{kind: "ProjectList.Project", name: "item", classes: "enyo-children-inline ares_projectView_projectList_item"}
			]}
		]},
		{name: "removeProjectPopup", kind: "ProjectDeletePopup", onConfirmDeleteProject: "confirmRemoveProject"},
		{name: "errorPopup", kind: "Ares.ErrorPopup", msg: "unknown error"},
		{kind: "AccountsConfigurator"},
		{kind: "Signals", onServicesChange: "handleServicesChange"}
	],
	PROJECTS_STORAGE_KEY: "com.enyojs.ares.projects",
	selected: null,
	debug: false,
	create: function() {
		this.inherited(arguments);
		if (ProjectList.underTest) {
			this.PROJECTS_STORAGE_KEY = "com.enyojs.ares.tests";
		} else
			this.$.localStorage.get(this.PROJECTS_STORAGE_KEY, enyo.bind(this, this.projectListAvailable));
	},
	/**
	 * Callback functions which receives the project list data read from the storage
	 * @protected
	 * @param data: the project list in json format
	 */
	projectListAvailable: function(data) {
		try {
			if (data && data !== "") {
				this.projects = JSON.parse(data);
				if (this.debug) console.dir(this.projects);
			}
			this.$.projectList.setCount(this.projects.length);
		} catch(error) {
			this.error("Unable to retrieve projects information: " + error);	// TODO ENYO-1105
			console.dir(data);	// Display the offending data in the console
			this.$.localStorage.remove(this.PROJECTS_STORAGE_KEY); // Remove incorrect projects information
			this.projects = [];
		}
	},
	storeProjectsInLocalStorage: function() {
		var projectsString;
		if (this.debug) console.dir(this.projects);
		try {
			projectsString = JSON.stringify(this.projects, enyo.bind(this, this.stringifyReplacer));
		} catch(error) {
			this.error("Unable to store the project information: " + error);	// TODO ENYO-1105
			console.dir(this.projects);		// Display the offending object in the console
			return;
		}
		this.$.localStorage.set(this.PROJECTS_STORAGE_KEY, projectsString, function() {
			// WARNING: LocalStorage does not return any information about operation status (success or error)
			enyo.log("Project list saved");
		});
	},
	addProject: function(name, folderId, service) {
		var project = {
			name: name,
			folderId: folderId,
			serviceId: service.getConfig().id
		};
		if (!project.serviceId) {
			throw new Error("Cannot add a project in service=" + service);
		}
		var known = 0;
		var match = function(proj) {
			if ( proj.name === name) {
				known = 1;
			}
		} ;
		enyo.forEach(this.projects, match) ;
		if (known) {
			this.log("Skipped project " + name + " as it is already listed") ;
		}
		else {
			this.projects.push(project);
			this.storeProjectsInLocalStorage();
			this.$.projectList.setCount(this.projects.length);
			this.$.projectList.render();
		}
	},
	renameSelectedProject: function(newName) {
		var old = this.selected.getProjectName;
		var p;
		for (p in this.projects) {
			if (this.projects[p].name === old ) {
				this.projects[p].name = newName ;
			}
		}
		this.selected.setProjectName(newName) ;
		this.storeProjectsInLocalStorage();
	},
	removeProjectAction: function(inSender, inEvent) {
		var popup = this.$.removeProjectPopup;
		if (this.selected) {
			popup.setName("Delete project '" + this.selected.getProjectName() + "' ?");
			popup.$.nukeFiles.setValue(false) ;
			popup.show();
		}
	},
	confirmRemoveProject: function(inSender, inEvent) {
		// use file system service to remove project files (which behaves like a 'rm -rf')
		// once done,  call removeSelectedProjectData to mop up the remains.
		var project, nukeFiles ;
		if (this.selected) {
			project = this.projects[this.selected.index] ;
			nukeFiles = this.$.removeProjectPopup.$.nukeFiles.getValue() ;
			this.log("removing project" +  project.name + ( nukeFiles ? " and its files" : "" )) ;
			this.debug && this.log(project) ;
			if (nukeFiles) {
				project.service.remove( project.folderId )
					.response(this, function(){this.removeSelectedProjectData();})
					.error(this, function(inError){
						this.showErrorPopup("Error removing files of project " + project.name + ": " + inError);
					}) ;
			}
			else {
				this.removeSelectedProjectData() ;
			}
		}
	},
	removeSelectedProjectData: function() {
		if (this.selected) {
			// remove the project from list of project config
			this.projects.splice(this.selected.index, 1);
			this.storeProjectsInLocalStorage();
			this.selected = null;
			this.$.projectList.setCount(this.projects.length);
			this.$.projectList.render();
			this.doProjectRemoved();
		}
	},
	projectListSetupItem: function(inSender, inEvent) {
		var project = this.projects[inEvent.index];
		var item = inEvent.item;
		// setup the controls for this item.
		item = item.$.item;
		item.setProjectName(project.name);
		item.setIndex(inEvent.index);
	},
	projectListTap: function(inSender, inEvent) {
		var project, msg;
		// Un-highlight former selection, if any
		if (this.selected) {
			this.selected.removeClass("ares_projectView_projectList_item_selected");
		}
		project = this.projects[inEvent.index];
		project.service = ServiceRegistry.instance.resolveServiceId(project.serviceId);
		if (project.service) {
			// Highlight a project item if & only if its
			// filesystem service provider exists.
			if (inEvent.originator.kind === 'ProjectList.Project') {
				this.selected = inEvent.originator;
			} else {
				this.selected = inEvent.originator.owner;
			}
			this.selected.addClass("ares_projectView_projectList_item_selected");
			this.doProjectSelected({project: project});
		} else {
			// ...otherwise let
			msg = "Service " + project.serviceId + " not found";
			this.showErrorPopup(msg);
			this.error(msg);
		}
	},
	showAccountConfigurator: function() {
		this.$.accountsConfigurator.show();
	},
	aresMenuItemSelected: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		if (typeof this[inEvent.selected.value] === 'function') {
			this[inEvent.selected.value]();
		}
	},
	showErrorPopup : function(msg) {
		this.$.errorPopup.setErrorMsg(msg);
		this.$.errorPopup.show();
	},
	stringifyReplacer: function(key, value) {
		if (key === "originator") {
			return undefined;	// Exclude
		}
		return value;	// Accept
	},
	statics: {
		underTest: false
	}
});

enyo.kind({
	name: "ProjectList.Project",
	published: {
		projectName: "",
		index: -1
	},
	components: [
		{name: "name"}
	],
	projectNameChanged: function(inOldValue) {
		this.$.name.setContent(this.projectName);
	}
});

enyo.kind({
	name: "ProjectDeletePopup",
	kind: "Ares.ActionPopup",
	components: [
		{kind: "Control", tag: "h3", content: " ", name: "title"},
		{kind: "Control", tag: "br"},
		{kind: "onyx.Checkbox", checked: false, name: "nukeFiles"},
		{kind: "Control", tag: "span", style: "padding: 0 4px; vertical-align: middle;", content: "also delete files", fit: true},
		{kind: "FittableColumns", name: "buttons", components: [
			{kind: "onyx.Button", classes: "onyx-negative", content: "Cancel", name: "cancelButton", ontap: "actionCancel"},
			{kind: "onyx.Button", classes: "onyx-affirmative", content: "Delete", name: "actionButton", ontap: "actionConfirm"}
		]}
	]
});
<|endoftext|>


<commit_before>"use strict";

module.exports = function Signalements(db) {

    var signals = db.collection("signals");

    return {
        addSignals: function(zone, direction, type, username, description, done) {
            var entry = {
                date_added: new Date().getTime(),
                zone: zone,
                direction: direction,
                type: type,
                rating: 1,
                description: description,
                author: username //put the current user here!
            };
            posts.insert(entry, function (error, result) {
                if (error) return done(error, null);
                console.log("DB: inserted post " + entry.title);
                return done(error, permalink);
            });
        },
        getPosts: function(count, done) {
            posts.find().sort('date', -1).limit(count).toArray(function(error, items) {
                if (error) return done(error, null);
                console.log("Found " + items.length + " posts");
                return done(error, items);
            });
        },
        getSignalsByZone: function(zone, count, done) {
            signals.find({ zone : zone }).sort('date_added').limit(count).toArray(function(error, items) {
                if (error) return done(error, null);
                console.log("Found " + items.length + " posts");
                return done(error, items);
            });
        },
        getPostByPermalink: function(permalink, done) {
            posts.findOne({'permalink': permalink}, function(error, post) {
                if (error) return done(error, null);
                return done(error, post);
            });
        },
        addComment: function(permalink, name, email, body, done) {
            var comment = { author: name, body: body };
            if (email) comment.email = email;
            posts.update({permalink: permalink}, {'$push': {comments: comment}}, function(error, count) {
                if (error) return done(error, null);
                return done(error, count);
            });
        }
    };
};
<commit_msg>signal up-to-date<commit_after>"use strict";

module.exports = function Signals(db) {

    var signals = db.collection("signals");

    return {
        addSignals: function(zone, direction, type, username, description, done) {
            var entry = {
                date_added: new Date().getTime(),
                zone: zone,
                direction: direction,
                type: type,
                rating: 1,
                description: description,
                author: username //put the current user here!
            };
            signals.insert(entry, function (error, result) {
                if (error) return done(error, null);
                console.log("DB: inserted signals ");
                return done(error, items);
            });
        },
        getSignals: function(count, done) {
            signals.find().sort('date_added').limit(count).toArray(function(error, items) {
                if (error) return done(error, null);
                console.log("Found " + items.length + " signals");
                return done(error, items);
            });
        },
        getSignalsByZone: function(zone, count, done) {
            signals.find({ zone : zone }).sort('date_added').limit(count).toArray(function(error, items) {
                if (error) return done(error, null);
                console.log("Found " + items.length + " signals");
                return done(error, items);
            });
        },
        incrementRating: function(_id, rating, done) {
            signals.update({_id: _id}, { $inc: {rating: 1}, function(error, items) {
                if (error) return done(error, null);
                console.log("incremented" + items.length + " signals");
                return done(error, items);
            });
        },
        incrementRating: function(_id, rating, done) {
            signals.update({_id: _id}, { $inc: {rating: -1}, function(error, items) {
                if (error) return done(error, null);
                console.log("decremented" + items.length + " signals");
                return done(error, items);
            });
        }

    };
};
<|endoftext|>


<commit_before>//main.js
/*var flights = [[{dest: "Poland", price: "242", carrier: "Ryan Air"},
                    {dest: "Poland", price: "60", carrier: "British Airways"},
                    {dest: "Poland", price: "260", carrier: "Joe's Hardware"}],
            [ {dest: "Bristol", price: "160", carrier: "British Airways"},
                    {dest: "Bristol", price: "20", carrier: "Joe's Hardware"}]];
*/
var flights;
var ready = false;
//get flight data
$.get( "/top_flights", function( data ) {
    flights = JSON.parse(data);
    populate_data();
});
$(document).ready( function () {

    $('#chooser a').click(function (e) {
	e.preventDefault();
	$(this).tab('show');
    if(!$("#tab-main").hasClass("active")){ $("#tab-main").removeClass("hide");}
        else { $("#tab-main").addClass("hide"); }
    if(!$("#tab-friends").hasClass("active")){ $("#tab-friends").removeClass("hide");}
        else { $("#tab-friends").addClass("hide"); }
    });

    $(".btn-modal").on("click", function () {
        //set modal to loading!
        if(ready) {
            reset_modal();
            $('#myModal').modal('toggle');
            //populate the modal here!!!
            populate_modal($(this).attr("location"));
        }
    });

    $(".friendlist tr").on("click", function() {
        var any_selected = false;
        var q = $(this).children(":last").children(".friend-location").text();
        $(".friend-location").each(function () {
            if($(this).hasClass("selected")) {any_selected = true; }
            if($(this).text().toLowerCase().indexOf(q.toLowerCase()) != -1) {
                $(this).parent().parent().show();
            } else {
                $(this).parent().parent().hide();
            }
            console.log(any_selected);
        });
        $(this).toggleClass("selected");
    });
    $('#search').on("keyup", function () {
        var q = $('#search').val();
        $(".friend-name").each(function () {
            if ($(this).text().toLowerCase().indexOf(q.toLowerCase()) != -1) {
                $(this).parent().parent().show();
            }
            else {
                $(this).parent().parent().hide();
            }
        });
    });
});
function reset_modal() {
    //resets the modal to a loading screen
    $("#modalTitle").text("Loading...");
    $("#flight-data tr").remove();
    $("#flight-data").html("
Date	Airline	Fly Now!
");
}
function populate_modal(city_id) {
    //this gets all relevant data for the modal
    var data = flights[city_id];
    $("#modalTitle").text(data.name[0]+", "+data.name[1]+", "+data.name[2]);
    $("#skyscanner-url").attr('href', flights[city_id]['url']);
    $("#flight-data tr:last").after(prepare_flight(data.cheapest_quote));
    data.quotes.forEach(function (entry) {
        $("#flight-data tr:last").after(prepare_flight(entry));
    });
    $(".date-tooltip").tooltip();
}
function populate_data() {
    ready = true;
    $("#Loading-Content").addClass("hidden");
    $("#first-location h1").html(flights[0].name[1] + "
£"+flights[0].cheapest_quote.MinPrice);
    $("#first-location p").html("Go and see "+flights[0].friends[0].name+", "+flights[0].friends[1].name+" and "+(flights[0].friends.length - 2)+" others in "+flights[0].name[1]+", "+flights[0].name[2]);
    $("#first-location button").attr("location", 0);
    $("#first-location").removeClass("hidden");
    $("#second-location h1").html(flights[1].name[1] + "
£"+flights[1].cheapest_quote.MinPrice);
    $("#second-location p").html("You have "+flights[1].friends.length+" friends near "+flights[1].name[1]+", including "+flights[1].friends[0].name+"");
    $("#second-location button").attr("location", 1);
    $("#second-location").removeClass("hidden");
    $("#third-location h1").html(flights[2].name[1] + "
£"+flights[2].cheapest_quote.MinPrice);
    $("#third-location p").html("Flights available to go and see "+flights[2].friends[0].name+" and "+(flights[2].friends.length -1)+" others in "+flights[2].name[1]);
    $("#third-location button").attr("location", 2);
    $("#third-location").removeClass("hidden");
}
function prepare_flight(dest) {
    var date = moment(dest.OutboundLeg.DepartureDate).format('ll');
    var ret_date = moment(dest.InboundLeg.DepartureDate).format('ll');
    var rel_date = moment(dest.OutboundLeg.DepartureDate).fromNow();
    //add a 'time until' event using .fromNow() as a tooltip
    var r = "
";
    r += "

"+date+" to "+ret_date+"	";
    r += ""+dest.InboundLeg.Carrier+"	";
    r += "£"+dest.MinPrice+"	";
    r += "
";
    return r;
}
<commit_msg>Unbroke; needs fix<commit_after>//main.js
/*var flights = [[{dest: "Poland", price: "242", carrier: "Ryan Air"},
                    {dest: "Poland", price: "60", carrier: "British Airways"},
                    {dest: "Poland", price: "260", carrier: "Joe's Hardware"}],
            [ {dest: "Bristol", price: "160", carrier: "British Airways"},
                    {dest: "Bristol", price: "20", carrier: "Joe's Hardware"}]];
*/
var flights;
var ready = false;
//get flight data
$.get( "/top_flights", function( data ) {
    flights = JSON.parse(data);
    populate_data();
});
$(document).ready( function () {

    $('#chooser a').click(function (e) {
	e.preventDefault();
	$(this).tab('show');
    if(!$("#tab-main").hasClass("active")){ $("#tab-main").removeClass("hide");}
        else { $("#tab-main").addClass("hide"); }
    if(!$("#tab-friends").hasClass("active")){ $("#tab-friends").removeClass("hide");}
        else { $("#tab-friends").addClass("hide"); }
    });

    $(".btn-modal").on("click", function () {
        //set modal to loading!
        if(ready) {
            reset_modal();
            $('#myModal').modal('toggle');
            //populate the modal here!!!
            populate_modal($(this).attr("location"));
        }
    });

    $(".friendlist tr").on("click", function() {
        var any_selected = false;
        var q = $(this).children(":last").children(".friend-location").text();
        $(".friend-location").each(function () {
            if($(this).hasClass("selected")) {any_selected = true; }
            if($(this).text().toLowerCase().indexOf(q.toLowerCase()) != -1) {
                $(this).parent().parent().show();
            } else {
                $(this).parent().parent().hide();
            }
            console.log(any_selected);
        });
        $(this).toggleClass("selected");
    });
    $('#search').on("keyup", function () {
        var q = $('#search').val();
        $(".friend-name").each(function () {
            if ($(this).text().toLowerCase().indexOf(q.toLowerCase()) != -1) {
                $(this).parent().parent().show();
            }
            else {
                $(this).parent().parent().hide();
            }
        });
    });
});
function reset_modal() {
    //resets the modal to a loading screen
    $("#modalTitle").text("Loading...");
    $("#flight-data tr").remove();
    $("#flight-data").html("
Date	Airline	Fly Now!
");
}
function populate_modal(city_id) {
    //this gets all relevant data for the modal
    var data = flights[city_id];
    $("#modalTitle").text(data.name[0]+", "+data.name[1]+", "+data.name[2]);
    $("#skyscanner-url").attr('href', flights[city_id]['url']);
    $("#flight-data tr:last").after(prepare_flight(data.cheapest_quote));
    data.quotes.forEach(function (entry) {
        $("#flight-data tr:last").after(prepare_flight(entry));
    });
    $(".date-tooltip").tooltip();
}
function populate_data() {
    ready = true;
    $("#Loading-Content").addClass("hidden");
    $("#first-location h1").html(flights[0].name[1] + "
£"+flights[0].cheapest_quote.MinPrice);
    $("#first-location p").html("Go and see "+flights[0].friends[0].name+", "+flights[0].friends[1].name+" and "+(flights[0].friends.length - 2)+" others in "+flights[0].name[1]+", "+flights[0].name[2]);
    $("#first-location button").attr("location", 0);
    $("#first-location").removeClass("hidden");
    $("#second-location h1").html(flights[1].name[1] + "
£"+flights[1].cheapest_quote.MinPrice);
    $("#second-location p").html("You have "+flights[1].friends.length+" friends near "+flights[1].name[1]+", including "+flights[1].friends[0].name+"");
    $("#second-location button").attr("location", 1);
    $("#second-location").removeClass("hidden");
    $("#third-location h1").html(flights[2].name[1] + "
£"+flights[2].cheapest_quote.MinPrice);
    $("#third-location p").html("Flights available to go and see "+flights[2].friends[0].name+" and "+(flights[2].friends.length -1)+" others in "+flights[2].name[1]);
    $("#third-location button").attr("location", 2);
    $("#third-location").removeClass("hidden");
}
function prepare_flight(dest) {
    var date = moment(dest.OutboundLeg.DepartureDate).format('ll');
    var ret_date = moment(dest.InboundLeg.DepartureDate).format('ll');
    var rel_date = moment(dest.OutboundLeg.DepartureDate).fromNow();
    //add a 'time until' event using .fromNow() as a tooltip
    var r = "
";
    r += "

"+date+" to "+ret_date+"	";
    r += ""+dest.InboundLeg.Carrier+"	";
    r += "£"+dest.MinPrice+"	";
    r += "
";
    return r;
}
<|endoftext|>


<commit_before>const config = require('../config');
const util = require('../utils/util');
const path = require('path');
const _ = require('lodash');
const Concat = require('concat-with-sourcemaps');

module.exports = function concat(assets) {
  const groupWebPaths = _(assets).map('groupWebPath').uniq().value();

  return _.reduce(groupWebPaths, (acc, groupWebPath) => {
    const group = _.filter(assets, {groupWebPath});
    return _.concat(acc, concatenate(group));
  }, []);

  function concatenate(group) {
    const sample = group[0];
    const result = {
      dirDest: sample.groupDestDir,
      destFilename: sample.groupDestFilename,
      groupKey: sample.groupKey,
      destType: sample.typeDest,
      destFilenameMin: sample.groupDestFilename,
      dest: sample.dest,
      webPath: sample.groupDestPath,
      sourcemapPath: sample.groupSourcemapPath
    };

    const c = new Concat(true, result.dest, '\n');
    _.forEach(group, asset => {
      const mappedPath = util.stripIgnoredBasePath(asset.srcPath, config.templateIgnoredBasePaths);
      c.add(mappedPath, asset.content, asset.map);
    });

    result.content = c.content.toString();
    result.map = c.sourceMap;

    return result;
  }
}
<commit_msg>fix concat plugin<commit_after>const config = require('../config');
const util = require('../utils/util');
const path = require('path');
const _ = require('lodash');
const Concat = require('concat-with-sourcemaps');

module.exports = function concat(assets) {
  const groupWebPaths = _(assets).map('groupWebPath').uniq().value();

  return _.reduce(groupWebPaths, (acc, groupWebPath) => {
    const group = _.filter(assets, {groupWebPath});
    return _.concat(acc, concatenate(group));
  }, []);

  function concatenate(group) {
    const sample = group[0];
    const result = {
      dirDest: sample.groupDestDir,
      destFilename: sample.groupDestFilename,
      groupKey: sample.groupKey,
      destType: sample.typeDest,
      destFilenameMin: sample.groupDestFilename,
      dest: sample.dest,
      webPath: sample.groupDestPath,
      sourcemapPath: sample.groupSourcemapPath
    };

    const c = new Concat(true, result.dest, '\n');
    _.forEach(group, asset => {
      const mappedPath = util.stripIgnoredBasePath(asset.src, config.templateIgnoredBasePaths);
      c.add(mappedPath, asset.content, asset.map);
    });

    result.content = c.content.toString();
    result.map = c.sourceMap;

    return result;
  }
}
<|endoftext|>


<commit_before>Ui.Element.extend('Ui.TextArea',
/**@lends Ui.TextArea#*/
{
	textareaDrawing: undefined,
	fontSize: 14,
	fontFamily: 'sans-serif',
	fontWeight: 'normal',
	color: 'black',
	value: '',

	/**
	 * @constructs
	 * @class
	 * @extends Ui.Element
	 */
	constructor: function(config) {
		this.addEvents('change', 'scroll');
		this.setSelectable(true);

//		this.connect(this.textareaDrawing, 'mousedown', function(event) {
//			this.textareaDrawing.focus();
//		});
		this.connect(this.textareaDrawing, 'keyup', this.onKeyUp);

		this.connect(this.textareaDrawing, 'fingerup', function(event) {
			this.textareaDrawing.focus();
		});

		this.connect(this.textareaDrawing, 'scroll', function() {
//			console.log('textarea scroll');
//			console.log(this+' scroll event ('+this.textareaDrawing.scrollLeft+','+this.textareaDrawing.scrollTop+')');
			if((this.getMeasureWidth() != this.textareaDrawing.scrollWidth) || (this.getMeasureHeight() != this.textareaDrawing.scrollHeight)) {
//				console.log('invalidateMeasure');
				this.invalidateMeasure();
			}
			this.fireEvent('scroll', this, this.textareaDrawing.scrollLeft, this.textareaDrawing.scrollTop);
		});
	},

	setFontSize: function(fontSize) {
		if(this.fontSize != fontSize) {
			this.fontSize = fontSize;
			this.textareaDrawing.style.fontSize = this.fontSize+'px';
			this.invalidateMeasure();
		}
	},

	getFontSize: function() {
		return this.fontSize;
	},

	setFontFamily: function(fontFamily) {
		if(this.fontFamily != fontFamily) {
			this.fontFamily = fontFamily;
			this.textareaDrawing.style.fontFamily = this.fontFamily;
			this.invalidateMeasure();
		}
	},

	getFontFamily: function() {
		return this.fontFamily;
	},

	setFontWeight: function(fontWeight) {
		if(this.fontWeight != fontWeight) {
			this.fontWeight = fontWeight;
			this.textareaDrawing.style.fontWeight = this.fontWeight;
			this.invalidateMeasure();
		}
	},

	getFontWeight: function() {
		return this.fontWeight;
	},

	setColor: function(color) {
		if(this.color != color) {
			this.color = color;
			this.textareaDrawing.style.color = this.color;
			this.invalidateMeasure();
		}
	},

	getColor: function() {
		return this.color;
	},

	getValue: function() {
		return this.textareaDrawing.value;
	},

	setValue: function(value) {
		this.textareaDrawing.value = value;
	},

	setOffset: function(offsetX, offsetY) {
//		console.log(this+'.setOffset('+offsetX+','+offsetY+')');

		this.textareaDrawing.scrollLeft = offsetX;
		this.textareaDrawing.scrollTop = offsetY;
	},

	getOffsetX: function() {
		return this.textareaDrawing.scrollLeft;
	},

	getOffsetY: function() {
		return this.textareaDrawing.scrollTop;
	},

	//
	// Private
	//

	onMouseDown: function(event) {
	},

	onKeyUp: function(event) {
//		console.log(this+'.onKeyUp');
//		console.log(this+'.onKeyUp '+this.textareaDrawing.scrollHeight+' / '+this.getLayoutHeight());

		if(this.textareaDrawing.value != this.value) {
			this.value = this.textareaDrawing.value;
			this.fireEvent('change', this, this.value);
		}
//		if(this.textareaDrawing.scrollHeight != this.getLayoutHeight())
			this.invalidateMeasure();
	}
},
/**@lends Ui.TextArea#*/
{
	render: function() {
		this.textareaDrawing = document.createElement('textarea');
		this.textareaDrawing.setAttribute('rows', 1);
		this.textareaDrawing.setAttribute('cols', 1);

		this.textareaDrawing.style.display = 'block';
		this.textareaDrawing.style.resize = 'none';
		this.textareaDrawing.style.overflow = 'hidden';
		this.textareaDrawing.style.border = '0px';
		this.textareaDrawing.style.margin = '0px';
		this.textareaDrawing.style.padding = '0px';
		this.textareaDrawing.style.outline = 'none';
		if(!navigator.isIE7 && !navigator.isIE8)
			this.textareaDrawing.style.background = 'none';
		if(navigator.isWebkit)
			this.textareaDrawing.style.webkitAppearance = 'none'
		this.textareaDrawing.style.fontSize = this.fontSize+'px';
		this.textareaDrawing.style.fontFamily = this.fontFamily;
		this.textareaDrawing.style.fontWeight = this.fontWeight;
		this.textareaDrawing.style.color = this.color;
		return this.textareaDrawing;
	},

	measureCore: function(width, height) {
		this.textareaDrawing.style.width = width+'px';
		this.textareaDrawing.style.height = '0px';
		var size = { width: this.textareaDrawing.scrollWidth, height: this.textareaDrawing.scrollHeight };
		this.textareaDrawing.style.width = this.getLayoutWidth()+'px';
		this.textareaDrawing.style.height = this.getLayoutHeight()+'px';
		return size;
	},

	arrangeCore: function(width, height) {
		this.textareaDrawing.style.width = width+'px';
		this.textareaDrawing.style.height = height+'px';
	}
},
/**@lends Ui.TextArea*/
{
/*	measureBox: undefined,

	constructor: function() {
		if(document.body === undefined) {
			var body = document.createElement('body');
			document.body = body;
		}
		Ui.TextArea.measureBox = document.createElement('textarea');
		Ui.TextArea.measureBox.style.display = 'block';
		Ui.TextArea.measureBox.style.width = '0px';
		Ui.TextArea.measureBox.style.height = '0px';
		Ui.TextArea.measureBox.style.visibility = 'hidden';
		document.body.appendChild(Ui.TextArea.measureBox);
	},

	measureArea: function(text, fontSize, fontFamily, fontWeight) {
		Ui.Label.measureBox.style.fontSize = fontSize+'px';
		Ui.Label.measureBox.style.fontFamily = fontFamily;
		Ui.Label.measureBox.style.fontWeight = fontWeight;
		Ui.Label.measureBox.style.fontWeight = fontWeight;
		Ui.Label.measureBox.textContent = text;
		return { width: Ui.Label.measureBox.offsetWidth, height: Ui.Label.measureBox.offsetHeight };
	},*/
});

<commit_msg>handle Ui.TextArea like Ui.Entry<commit_after>Ui.Element.extend('Ui.TextArea',
/**@lends Ui.TextArea#*/
{
	textareaDrawing: undefined,
	fontSize: 14,
	fontFamily: 'sans-serif',
	fontWeight: 'normal',
	color: 'black',
	value: '',
	isDown: false,
	mouseStartX: undefined,
	mouseStartY: undefined,
	touchStartX: undefined,
	touchStartY: undefined,

	/**
	 * @constructs
	 * @class
	 * @extends Ui.Element
	 */
	constructor: function(config) {
		this.addEvents('down', 'up', 'change', 'scroll');
		this.setSelectable(true);
		this.setFocusable(true);

		// handle mouse
		this.connect(this.getDrawing(), 'mousedown', this.onMouseDown);

		// handle touches
		this.connect(this.getDrawing(), 'fingerdown', this.onFingerDown);

		// handle keyboard
		this.connect(this.textareaDrawing, 'keyup', this.onKeyUp);

		this.connect(this.textareaDrawing, 'scroll', function() {
//			console.log('textarea scroll');
//			console.log(this+' scroll event ('+this.textareaDrawing.scrollLeft+','+this.textareaDrawing.scrollTop+')');
			if((this.getMeasureWidth() != this.textareaDrawing.scrollWidth) || (this.getMeasureHeight() != this.textareaDrawing.scrollHeight)) {
//				console.log('invalidateMeasure');
				this.invalidateMeasure();
			}
			this.fireEvent('scroll', this, this.textareaDrawing.scrollLeft, this.textareaDrawing.scrollTop);
		});
	},

	setFontSize: function(fontSize) {
		if(this.fontSize != fontSize) {
			this.fontSize = fontSize;
			this.textareaDrawing.style.fontSize = this.fontSize+'px';
			this.invalidateMeasure();
		}
	},

	getFontSize: function() {
		return this.fontSize;
	},

	setFontFamily: function(fontFamily) {
		if(this.fontFamily != fontFamily) {
			this.fontFamily = fontFamily;
			this.textareaDrawing.style.fontFamily = this.fontFamily;
			this.invalidateMeasure();
		}
	},

	getFontFamily: function() {
		return this.fontFamily;
	},

	setFontWeight: function(fontWeight) {
		if(this.fontWeight != fontWeight) {
			this.fontWeight = fontWeight;
			this.textareaDrawing.style.fontWeight = this.fontWeight;
			this.invalidateMeasure();
		}
	},

	getFontWeight: function() {
		return this.fontWeight;
	},

	setColor: function(color) {
		if(this.color != color) {
			this.color = color;
			this.textareaDrawing.style.color = this.color;
			this.invalidateMeasure();
		}
	},

	getColor: function() {
		return this.color;
	},

	getValue: function() {
		return this.textareaDrawing.value;
	},

	setValue: function(value) {
		this.textareaDrawing.value = value;
	},

	setOffset: function(offsetX, offsetY) {
//		console.log(this+'.setOffset('+offsetX+','+offsetY+')');

		this.textareaDrawing.scrollLeft = offsetX;
		this.textareaDrawing.scrollTop = offsetY;
	},

	getOffsetX: function() {
		return this.textareaDrawing.scrollLeft;
	},

	getOffsetY: function() {
		return this.textareaDrawing.scrollTop;
	},

	/**#@+
	 * @private
	 */

	onMouseDown: function(event) {
		if(this.getHasFocus()) {
			event.stopPropagation();
			return;
		}

		if((event.button != 0) || this.getIsDisabled())
			return;

		event.preventDefault();
		event.stopPropagation();

		this.mouseStartX = event.screenX;
		this.mouseStartY = event.screenY;

		this.connect(window, 'mousemove', this.onMouseMove, true);
		this.connect(window, 'mouseup', this.onMouseUp, true);

		this.onDown();
	},

	onMouseMove: function(event) {
		var deltaX = event.screenX - this.mouseStartX;
		var deltaY = event.screenY - this.mouseStartY;
		var delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

		event.preventDefault();
		event.stopPropagation();

		// if the user move to much, release the touch event
		if(delta > 10) {
			this.onUp();
			if('createEvent' in document) {
				this.disconnect(this.getDrawing(), 'mousedown', this.onMouseDown);

				var mouseDownEvent = document.createEvent('MouseEvents');
				mouseDownEvent.initMouseEvent('mousedown', true, true, window, 1, event.screenX, event.screenY,
					event.clientX, event.clientY,
					event.ctrlKey, event.altKey, event.shiftKey,
					event.metaKey, 0, event.target);
				event.target.dispatchEvent(mouseDownEvent);

				this.connect(this.getDrawing(), 'mousedown', this.onMouseDown);
			}
		}
	},

	onMouseUp: function(event) {
		if(!this.isDown)
			return;
		event.preventDefault();
		event.stopPropagation();
		if(event.button == 0) {
			this.onUp();
			this.getDrawing().focus();
		}
	},

	onFingerDown: function(event) {
		if(this.getHasFocus()) {
			event.stopPropagation();
			return;
		}

		if(this.getIsDisabled() || this.isDown)
			return;

		this.connect(event.finger, 'fingermove', this.onFingerMove);
		this.connect(event.finger, 'fingerup', this.onFingerUp);

		event.finger.capture(this.getDrawing());

		event.preventDefault();
		event.stopPropagation();

		this.touchStartX = event.finger.getX();
		this.touchStartY = event.finger.getY();
		this.onDown();
	},

	onFingerMove: function(event) {
		event.preventDefault();
		event.stopPropagation();

		var deltaX = event.finger.getX() - this.touchStartX;
		var deltaY = event.finger.getY() - this.touchStartY;
		var delta = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

		// if the user move to much, release the touch event
		if(delta > 10) {
			this.disconnect(event.finger, 'fingermove', this.onFingerMove);
			this.disconnect(event.finger, 'fingerup', this.onFingerUp);
			this.onUp();

			this.disconnect(this.getDrawing(), 'fingerdown', this.onFingerDown);
			event.finger.release();
			this.connect(this.getDrawing(), 'fingerdown', this.onFingerDown);
		}
	},

	onFingerUp: function(event) {
		this.disconnect(event.finger, 'fingermove', this.onFingerMove);
		this.disconnect(event.finger, 'fingerup', this.onFingerUp);

		event.preventDefault();
		event.stopPropagation();

		this.onUp();
		this.getDrawing().focus();
	},

	onDown: function() {
		this.isDown = true;
		this.fireEvent('down', this);
	},

	onUp: function() {
		this.disconnect(window, 'mousemove', this.onMouseMove, true);
		this.disconnect(window, 'mouseup', this.onMouseUp, true);
 		this.isDown = false;
		this.fireEvent('up', this);
	},

	onKeyUp: function(event) {
//		console.log(this+'.onKeyUp');
//		console.log(this+'.onKeyUp '+this.textareaDrawing.scrollHeight+' / '+this.getLayoutHeight());

		if(this.textareaDrawing.value != this.value) {
			this.value = this.textareaDrawing.value;
			this.fireEvent('change', this, this.value);
		}
//		if(this.textareaDrawing.scrollHeight != this.getLayoutHeight())
			this.invalidateMeasure();
	}
	/**#@-*/
},
/**@lends Ui.TextArea#*/
{
	renderDrawing: function() {
		this.textareaDrawing = document.createElement('textarea');
		this.textareaDrawing.setAttribute('rows', 1);
		this.textareaDrawing.setAttribute('cols', 1);

		this.textareaDrawing.style.display = 'block';
		this.textareaDrawing.style.resize = 'none';
		this.textareaDrawing.style.overflow = 'hidden';
		this.textareaDrawing.style.border = '0px';
		this.textareaDrawing.style.margin = '0px';
		this.textareaDrawing.style.padding = '0px';
		this.textareaDrawing.style.outline = 'none';
		if(!navigator.isIE7 && !navigator.isIE8)
			this.textareaDrawing.style.background = 'none';
		if(navigator.isWebkit)
			this.textareaDrawing.style.webkitAppearance = 'none'
		this.textareaDrawing.style.fontSize = this.fontSize+'px';
		this.textareaDrawing.style.fontFamily = this.fontFamily;
		this.textareaDrawing.style.fontWeight = this.fontWeight;
		this.textareaDrawing.style.color = this.color;
		return this.textareaDrawing;
	},

	measureCore: function(width, height) {
		this.textareaDrawing.style.width = width+'px';
		this.textareaDrawing.style.height = '0px';
		var size = { width: this.textareaDrawing.scrollWidth, height: this.textareaDrawing.scrollHeight };
		this.textareaDrawing.style.width = this.getLayoutWidth()+'px';
		this.textareaDrawing.style.height = this.getLayoutHeight()+'px';
		return size;
	},

	arrangeCore: function(width, height) {
		this.textareaDrawing.style.width = width+'px';
		this.textareaDrawing.style.height = height+'px';
	}
},
/**@lends Ui.TextArea*/
{
/*	measureBox: undefined,

	constructor: function() {
		if(document.body === undefined) {
			var body = document.createElement('body');
			document.body = body;
		}
		Ui.TextArea.measureBox = document.createElement('textarea');
		Ui.TextArea.measureBox.style.display = 'block';
		Ui.TextArea.measureBox.style.width = '0px';
		Ui.TextArea.measureBox.style.height = '0px';
		Ui.TextArea.measureBox.style.visibility = 'hidden';
		document.body.appendChild(Ui.TextArea.measureBox);
	},

	measureArea: function(text, fontSize, fontFamily, fontWeight) {
		Ui.Label.measureBox.style.fontSize = fontSize+'px';
		Ui.Label.measureBox.style.fontFamily = fontFamily;
		Ui.Label.measureBox.style.fontWeight = fontWeight;
		Ui.Label.measureBox.style.fontWeight = fontWeight;
		Ui.Label.measureBox.textContent = text;
		return { width: Ui.Label.measureBox.offsetWidth, height: Ui.Label.measureBox.offsetHeight };
	},*/
});

<|endoftext|>


<commit_before>/**
 * Created by petergallagher on 14/12/2016.
 */
$(document).ready(function () {

  function setStatus($container, pedigreeText, status) {

      $('select[name="GeneticsPatient[pedigrees_through][' + pedigreeText + '][status_id]"]').find('option:contains(' + status + ')').prop('selected', 'selected');
  }

  $('#GeneticsPatient_pedigrees').on('MultiSelectChanged', function () {

    var $container = $(this).parents('.multi-select'),
      pedigreeText = this.options[this.selectedIndex].text.trim();

    setStatus($container, pedigreeText, 'Unknown');

  });

});<commit_msg>bugfix - javascript using text instead of value<commit_after>/**
 * Created by petergallagher on 14/12/2016.
 */
$(document).ready(function () {

  function setStatus($container, pedigreeText, status) {

      $('select[name="GeneticsPatient[pedigrees_through][' + pedigreeText + '][status_id]"]').find('option:contains(' + status + ')').prop('selected', 'selected');
  }

  $('#GeneticsPatient_pedigrees').on('MultiSelectChanged', function () {

    var $container = $(this).parents('.multi-select'),
        pedigreeText = $(this.options[this.selectedIndex]).val();

    setStatus($container, pedigreeText, 'Unknown');

  });

});<|endoftext|>


<commit_before>'use strict'

// ES2015 (previously known as ES6) feature examples

if (true) {
    var brand = 'Ford';
}

// variable brand gets hoisted and is accessible
// outside of the if block scope
console.log(brand);

if (true) {
    let model = 'Fiesta';
}

// variables declared with 'let' and 'const' do not
// get hoisted, variable model is not accessible here,
// the following commented line results in: ReferenceError (model is not defined)
// console.log(model);

const PI = 3.142;

// const can't be assigned to multiple times, the following lines
// results in: TypeError: Assignment to constant variable
//PI = 3.14159265359<commit_msg>Some more ES2015.<commit_after>'use strict'

// ES2015 (previously known as ES6) feature examples

if (true) {
    var brand = 'Ford';
}

// variable brand gets hoisted and is accessible
// outside of the if block scope
console.log(brand);

if (true) {
    let model = 'Fiesta';
}

// variables declared with 'let' and 'const' do not
// get hoisted, variable model is not accessible here,
// the following commented line results in: ReferenceError (model is not defined)
// console.log(model);

const PI = 3.142;

// const can't be assigned to multiple times, the following lines
// results in: TypeError: Assignment to constant variable
//PI = 3.14159265359

// TODO:
// functions (default params, rest params, spread operators, arrow functions)
// Objects, strings and Object.assign
// Arrays, Maps and Sets
// Classes and modules
// Promises, iterators and generators<|endoftext|>


<commit_before>class Random {
    constractor(opt_generator) {
        this.generator = opt_generator || new Xorshift();
    }

    srand(seed) {
        return this.generator.srand(seed);
    }

    rand = function() {
        return this.generator.rand();
    }
}

exports.Random = Random;

//Algorithm is coming from http://www.jstatsoft.org/v08/i14/paper Xorshift.
class Xorshift {
    static MIN_VALUE = 0;
    static MAX_VALUE = 0xFFFFFFFF;

    constractor() {
        this._reset(Date.now());
    }

    srand(seed) {
        this._reset(seed);
        return this.rand();
    }

    rand() {
        let tmp = this._x ^ (this._x << 11);
        this._x = this._y >>> 0;
        this._y = this._z >>> 0;
        this._z = this._w >>> 0;
        this._w = (this._w ^ (this._w >>> 19)) ^ (tmp ^ (tmp >>> 8));
        return this._w; /* 0 to 0xFFFFFFFF */
    }

    calcProbability(prob) {
        let dice = (this.rand() % 100);
        return (dice < prob);
    }

    _reset(seed) {
        this._x = (seed & 0x66666666) >>> 0;
        this._y = (seed ^ 0xffffffff) >>> 0;
        this._z = ((seed & 0x0000ffff << 16) | (seed >> 16) & 0x0000ffff) >>> 0;
        this._w =seed >>> 0;
        this._seed = seed >>> 0;
    }
}
<commit_msg>Update<commit_after>class Random {
    constractor(opt_generator) {
        this.generator = opt_generator || new Xorshift();
    }

    srand(seed) {
        return this.generator.srand(seed);
    }

    rand = function() {
        return this.generator.rand();
    }
}

//Algorithm is coming from http://www.jstatsoft.org/v08/i14/paper Xorshift.
class Xorshift {
    static MIN_VALUE = 0;
    static MAX_VALUE = 0xFFFFFFFF;

    constractor() {
        this._reset(Date.now());
    }

    srand(seed) {
        this._reset(seed);
        return this.rand();
    }

    rand() {
        let tmp = this._x ^ (this._x << 11);
        this._x = this._y >>> 0;
        this._y = this._z >>> 0;
        this._z = this._w >>> 0;
        this._w = (this._w ^ (this._w >>> 19)) ^ (tmp ^ (tmp >>> 8));
        return this._w; /* 0 to 0xFFFFFFFF */
    }

    calcProbability(prob) {
        let dice = (this.rand() % 100);
        return (dice < prob);
    }

    _reset(seed) {
        this._x = (seed & 0x66666666) >>> 0;
        this._y = (seed ^ 0xffffffff) >>> 0;
        this._z = ((seed & 0x0000ffff << 16) | (seed >> 16) & 0x0000ffff) >>> 0;
        this._w =seed >>> 0;
        this._seed = seed >>> 0;
    }
}
<|endoftext|>


<commit_before>$(document).ready(function() {
    $('pre code').each(function(i, block) {
        hljs.highlightBlock(block);
    });
});

$('.menu .item').tab();

/*$('.blog-list li').map(function(currentValue, index){
 console.log('ooooo')
 });*/

var DateDiff = {

    inMinutes: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
        return parseInt((t2 - t1)/(60*1000))
    },

    inHours: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
        return parseInt((t2 - t1)/(3600*1000))
    },

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000));
    },

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000*7));
    },

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },

    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    },

    getDesc: function(d1, d2) {
        var minutes = this.inMinutes(d1,d2);
        var hours = this.inHours(d1,d2);
        if (minutes < 2) {
            return "刚刚发表";
        } else if (minutes < 60) {
            return  minutes + "分钟之前";
        } else {
            if (hours < 24) {
                return hours + "小时之前";
            } else {
                var days = this.inDays(d1, d2);
                if (days < 30) {
                    return days + "天之前";
                } else {
                    return d1;
                }
            }
        }
    }
};

function doTimeAction() {
    $('.blog-list li').each(function(){
        var spanPlug = $(this).find('.list-top>span');
        var publishTime = new Date(spanPlug.attr('data-shared-at'));
        var currentTime = new Date();
        spanPlug.html(DateDiff.getDesc(publishTime, currentTime));
    });
}

function timer() {
    doTimeAction();
    setTimeout("timer()",1000);
}

timer();

$('.popup').popup();

// 正文中的图片限制最大宽度
$('body').find('img').each(function(index, value) {
    $(value).css("max-width", "700px");
});
<commit_msg>update time display<commit_after>$(document).ready(function() {
    $('pre code').each(function(i, block) {
        hljs.highlightBlock(block);
    });
});

$('.menu .item').tab();

/*$('.blog-list li').map(function(currentValue, index){
 console.log('ooooo')
 });*/

var DateDiff = {

    inMinutes: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
        return parseInt((t2 - t1)/(60*1000))
    },

    inHours: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
        return parseInt((t2 - t1)/(3600*1000))
    },

    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000));
    },

    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();

        return parseInt((t2-t1)/(24*3600*1000*7));
    },

    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },

    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    },

    getDesc: function(d1, d2) {
        var minutes = this.inMinutes(d1,d2);
        var hours = this.inHours(d1,d2);
        if (minutes < 2) {
            return "刚刚发表";
        } else if (minutes < 60) {
            return  minutes + "分钟之前";
        } else {
            if (hours < 24) {
                return hours + "小时之前";
            } else {
                var days = this.inDays(d1, d2);
                if (days < 30) {
                    return days + "天之前";
                } else {
                    if (d1 instanceof Date) {
                        return  d1.getFullYear() + "-" +
                            (d1.getMonth() + 1) + "-" +
                            (d1.getDay() +1) + " " + d1.toLocaleTimeString();
                    } else {
                        return "发表时间未知!";
                    }
                }
            }
        }
    }
};

function doTimeAction() {
    $('.blog-list li').each(function(){
        var spanPlug = $(this).find('.list-top>span');
        var publishTime = new Date(spanPlug.attr('data-shared-at'));
        var currentTime = new Date();
        spanPlug.html(DateDiff.getDesc(publishTime, currentTime));
    });
}

function timer() {
    doTimeAction();
    setTimeout("timer()",1000);
}

timer();

$('.popup').popup();

// 正文中的图片限制最大宽度
$('body').find('img').each(function(index, value) {
    $(value).css("max-width", "700px");
});
<|endoftext|>


<commit_before>angular
  .module('app')
  .controller('NewExpenseController', NewExpenseController)

  function NewExpenseController(ExpenseService, CategoryService, $location){
    var ctrl = this;

    CategoryService.getCategories().then(function(res){
      ctrl.categories = res.data;
    });

   // ctrl.expense = new Expense();

    ctrl.addExpense = function(){
      var params={
        name: ctrl.name,
        category_id: ctrl.category_id,
        amount: ctrl.amount,
        description: ctrl.description
      }

      ExpenseService.createExpense(params).then(function(response){
        console.log(response.data);
      })
    }

    //ctrl.addExpense = function(){
    // ctrl.expense.$save(function(){
     //   $location.path('expenses');
    // });
    //};
  }<commit_msg>Modified createExpense method<commit_after>angular
  .module('app')
  .controller('NewExpenseController', NewExpenseController)

  function NewExpenseController(ExpenseService, CategoryService, $location){
    var ctrl = this;

    CategoryService.getCategories().then(function(res){
      ctrl.categories = res.data;
    });

   // ctrl.expense = new Expense();

    ctrl.addExpense = function(){
        var params={
          name: ctrl.name,
          category_id: ctrl.category_id,
          amount: ctrl.amount,
          description: ctrl.description
        }

        ExpenseService.createExpense(params).then(function(response){
          $location.path('expenses');
        });
    }

    //ctrl.addExpense = function(){
    // ctrl.expense.$save(function(){
     //   $location.path('expenses');
    // });
    //};
  }<|endoftext|>


<commit_before>import React from 'react';
import { Component, PropTypes } from '../utils/';

export default class Radio extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: props.checked
    };
  }
  handleChange(e) {
    const checked = e.target.checked;
    const { children } = this.props;
    if (checked) {
      this.props.onChange(e, (this.props.value || children), checked);
    }
  }
  // fixed jest test error.
  componentWillReceiveProps(nextProps) {
    if (this.props.checked !== nextProps.checked) {
      this.setState({ checked: nextProps.checked }, () => {
        this.radio.checked = nextProps.checked;
      })
    }
  }
  render() {
    const { prefixCls, className, children, onChange, disabled, value, ...other } = this.props;
    const { checked } = this.state;
    const cls = this.classNames(`${prefixCls}`, className, {
      'disabled': disabled, // 禁用状态
      'checked': checked,   // 选中
    });
    return (

        <span className={`${prefixCls}-inner`}>
          <input ref={(node) => { this.radio = node }} checked={checked} type="radio" disabled={disabled} value={value || children} onChange={this.handleChange.bind(this)} />

        <span className={`${prefixCls}-text`}>{children || value}

    )
  }
}

Radio.propTypes = {
  prefixCls: PropTypes.string,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  onChange: PropTypes.func,
  disabled: PropTypes.bool,
  checked: PropTypes.bool
}

Radio.defaultProps = {
  prefixCls: "w-radio",
  disabled: false,
  onChange: (v) => v,
}
<commit_msg>fix(Radio): Radio checked can not be undefined.<commit_after>import React from 'react';
import { Component, PropTypes } from '../utils/';

export default class Radio extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: props.checked
    };
  }
  handleChange(e) {
    const checked = e.target.checked;
    const { children } = this.props;
    if (checked) {
      this.props.onChange(e, (this.props.value || children), checked);
    }
  }
  // fixed jest test error.
  componentWillReceiveProps(nextProps) {
    if (this.props.checked !== nextProps.checked) {
      this.setState({ checked: nextProps.checked }, () => {
        this.radio.checked = nextProps.checked;
      })
    }
  }
  render() {
    const { prefixCls, className, children, onChange, disabled, value, ...other } = this.props;
    const { checked } = this.state;
    const cls = this.classNames(`${prefixCls}`, className, {
      'disabled': disabled, // 禁用状态
      'checked': checked,   // 选中
    });
    const inputProps = {
      ref: (node) => { this.radio = node },
      type: 'radio',
      disabled: disabled,
      checked: checked || false,
      value: value || children,
      onChange: this.handleChange.bind(this),
    }
    return (

        <span className={`${prefixCls}-inner`}>
          <input {...inputProps} />

        <span className={`${prefixCls}-text`}>{children || value}

    )
  }
}

Radio.propTypes = {
  prefixCls: PropTypes.string,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  onChange: PropTypes.func,
  disabled: PropTypes.bool,
  checked: PropTypes.bool
}

Radio.defaultProps = {
  prefixCls: "w-radio",
  disabled: false,
  onChange: (v) => v,
}
<|endoftext|>


<commit_before>/*
Usage:
var simpleColorPicker = sc(picker, target);
d3.select("#foo").call(simpleColorPicker);
*/
var sc = window.sc || {};
window.sc = sc;

// sc.simplecolor =

function simplecolor(pickerSelector, targetSelector) {
    var picker = d3.select(pickerSelector),
        target = d3.select(targetSelector),
        TOLERANCE = 5, // percent or degrees
        oldColorHex = target.style('background-color'),
        newColorObj
        ;

    var newColor = d3.hsl("#00AAFF");
    newColor.opacity = 0.5; // todo - sync

    if (!d3.hsl(oldColorHex).h) oldColorHex = "#cccccc";
    newColorObj = d3.hsl(oldColorHex);
    if (!newColorObj.h) newColorObj.h = 0;

    // Make the colorpicker container, sliders, inputs, swatches, hex display
    // Append it to the pickerSelector
    var sccp = picker.append('div')
        .attr('class', 'sc-colorpicker')
        ;

    var scSliders = ["hue", "saturation", "lightness", "alpha"];
    var suffixes = {
        "hue": "°H",
        "saturation": "%S",
        "lightness": "%L",
        "alpha": "α"
    };

    var scRows = sccp.selectAll('div')
        .data(scSliders)
        .enter()
        .append('div')
            .attr('class','sc-flex-row')
        ;

    var scSliders = scRows
        .append('div')
            .attr('id', (d) => {
                return "sc-slider-container-" + d;
            })
            .append('input')
                .attr('class', 'sc-slider sc-grow')
                .attr('id', (d) => {
                    return "sc-" + d;
                })
                .attr('type', 'range')
                .attr('value', 50)
                .attr('step', TOLERANCE)
        ;
    // Override range for hue slider
    d3.select('.sc-slider#sc-hue')
        .attr('max',360)
        .attr('value',200)
        ;
    // Override background for opacity slider
    d3.select('.sc-slider#sc-alpha')
        .attr('max',1)
        .attr('value',0.5)
        .attr('step',0.1)
        .classed("checkerboard", true);
        ;

    scRows
        .append('input')
            .attr('class', 'sc-number')
            .attr('id', (d) => {
                return "sc-" + d + "-number";
            })
            .attr('type', 'text')
            .attr('value', 50)
        ;
    // Override numbers
    d3.select('#sc-hue-number')
        .attr('value',200)
        ;
    d3.select('#sc-alpha-number')
        .attr('value', 0.5)
        ;

    scRows
        .append('span')
            .attr('class', 'sc-suffix')
            .text((d) => {
                return suffixes[d];
            })
        ;

    // swatches & hex code
    var scSwatchRow = sccp.append('div')
        .attr('class','sc-flex-row')
        ;
    scSwatchRow.append('div')
        .attr('class','sc-swatch checkerboard')
        .append('div')
            .attr('id','sc-old-color')
            .attr('class','sc-swatch')
        ;
    scSwatchRow.append('div')
        .attr('class','sc-swatch checkerboard')
        .append('div')
            .attr('id','sc-new-color')
            .attr('class','sc-swatch')
        ;
    scSwatchRow.append('div')
        .append('input')
            .attr('id','sc-new-hex')
            .on('input', function(){
                // Use this value to update the sliders
                if ( d3.color(this.value) ) {
                    // updateSliders(this.value);
                    updateInputs(this.value);
                }
            })
        ;
    scSwatchRow.append('div')
        .append('input')
            .attr('id','sc-new-rgba')
        ;

    updateSliders(newColor);

    function updateInputs(colorString) {
        d3color = d3.hsl(colorString);
        d3.select('#sc-hue').attr('value', d3color.h);
        d3.select('#sc-saturation').attr('value', d3color.s);
        d3.select('#sc-lightness').attr('value', d3color.l);
        d3.select('#sc-alpha').attr('value', d3color.opacity);
        updateSliders(d3color);

        d3.select('#sc-hue-number').attr('value', d3color.h);
        d3.select('#sc-saturation-number').attr('value', d3color.s);
        d3.select('#sc-lightness-number').attr('value', d3color.l);
        d3.select('#sc-alpha-number').attr('value', d3color.opacity);
    }

    // Define the colorChange function
    function updateSliders(d3color) {
        // Update hex code && target
        d3.select('#sc-new-color').style('background', d3.hsl(d3color).toString() );
        d3.select('#sc-new-hex').attr('value', rgb2hex(d3color.toString()) );
        d3.select('#sc-new-rgba').attr('value', d3.rgb(d3color).toString().replace(/ /g,"") );
        // target.style('background', rgb2hex(d3color.toString()) ); // special case
        target.style('background', d3.hsl(d3color).toString() );

        // Ramp hue from 0 to 100
        fromColor = `hsla(0, ${100*d3color.s}%, ${100*d3color.l}%, 1)`;
        midColor = `hsla(90, ${100*d3color.s}%, ${100*d3color.l}%, 1)`;
        toColor = `hsla(180, ${100*d3color.s}%, ${100*d3color.l}%, 1)`;
        d3.select('#sc-hue').style('background', makeGradient(d3color.toString()));

        // Ramp saturation from 0 to 100
        fromColor = `hsla(${d3color.h}, 0%, ${100*d3color.l}%, 1)`;
        // midColor = `hsla(${d3color.h}, ${100*d3color.s}%, 50%, 1)`;
        toColor = `hsla(${d3color.h}, 100%, ${100*d3color.l}%, 1)`;
        gradientColor = `linear-gradient(to right, ${fromColor}, ${toColor})`;
        d3.select('#sc-saturation').style('background', gradientColor);

        // Ramp lightness from 0 to 100
        fromColor = `hsla(${d3color.h}, ${100*d3color.s}%, 0%, 1)`;
        midColor = `hsla(${d3color.h}, ${100*d3color.s}%, 50%, 1)`;
        toColor = `hsla(${d3color.h}, ${100*d3color.s}%, 100%, 1)`;
        gradientColor = `linear-gradient(to right, ${fromColor}, ${midColor}, ${toColor})`;
        d3.select('#sc-lightness').style('background', gradientColor);

        // Ramp alpha from 0 to 100
        fromColor = `hsla(${d3color.h}, ${100*d3color.s}%, ${100*d3color.l}%, 0)`;
        toColor = `hsla(${d3color.h}, ${100*d3color.s}%, ${100*d3color.l}%, 1)`;
        gradientColor = `linear-gradient(to right, ${fromColor}, ${toColor})`;
        d3.select('#sc-alpha').style('background', gradientColor);

    }

    // Set the on change handlers
    d3.select('#sc-hue').on('input',function(d){
        if ( Math.abs(newColor.h - this.value) >= TOLERANCE ) {
            newColor.h = this.value;
            d3.select('#sc-new-color').style('background', d3.hsl(newColor).toString() );
            d3.select('#sc-hue-number').attr('value',this.value);
            updateSliders(newColor);
        }
    });

    d3.select('#sc-saturation').on('input',function(d){
        if ( Math.abs(newColor.s - this.value/100) >= TOLERANCE/100 ) {
            newColor.s = this.value/100;
            d3.select('#sc-new-color').style('background', newColor);
            d3.select('#sc-saturation-number').attr('value',this.value);
            updateSliders(newColor);
        }
    });

    d3.select('#sc-lightness').on('input',function(d){
        if ( Math.abs(newColor.l - this.value/100) >= TOLERANCE/100 ) {
            newColor.l = this.value/100;
            d3.select('#sc-new-color').style('background', newColor);
            d3.select('#sc-lightness-number').attr('value',this.value);
            updateSliders(newColor);
        }
    });

    d3.select('#sc-alpha').on('input',function(d){
        if ( Math.abs(newColor.opacity - this.value) >= TOLERANCE/100 ) {
            newColor.opacity = this.value;
            d3.select('#sc-new-color').style('background', newColor);
            d3.select('#sc-alpha-number').attr('value',this.value);
            updateSliders(newColor);
        }
    });

    function makeGradient(hex) {
        var colorArr = [];
        var d3c = d3.hsl(hex);
        // Increment through the d3.hcl(?) spectrum
        // Converting each to HSL for CSS
        for (var i = 0; i <= 360; i = i + 10) {
            d3c.h = i;
            colorArr.push(d3c.toString());
        }
        var ret = `linear-gradient(to right, ${colorArr.join(",")} )`;
        return ret;
    }

}

function rgb2hex(rgb){
  // ignores alpha
  rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
  return (rgb && rgb.length === 4) ? "#" +
    ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
<commit_msg>Fix write from hex; initial defaults.<commit_after>/*
Usage:
var simpleColorPicker = sc(picker, target);
d3.select("#foo").call(simpleColorPicker);
*/
var sc = window.sc || {};
window.sc = sc;

// sc.simplecolor =

function simplecolor(pickerSelector, targetSelector) {
    var picker = d3.select(pickerSelector),
        target = d3.select(targetSelector),
        TOLERANCE = 5, // percent or degrees
        oldColorHex = target.style('background-color'),
        newColorObj
        ;

    var newColor = d3.hsl("#00AAFF");
    newColor.opacity = 1.0; // todo - sync

    if (!d3.hsl(oldColorHex).h) oldColorHex = "#cccccc";
    newColorObj = d3.hsl(oldColorHex);
    if (!newColorObj.h) newColorObj.h = 0;

    // Make the colorpicker container, sliders, inputs, swatches, hex display
    // Append it to the pickerSelector
    var sccp = picker.append('div')
        .attr('class', 'sc-colorpicker')
        ;

    var scSliders = ["hue", "saturation", "lightness", "alpha"];
    var suffixes = {
        "hue": "°H",
        "saturation": "%S",
        "lightness": "%L",
        "alpha": "α"
    };

    var scRows = sccp.selectAll('div')
        .data(scSliders)
        .enter()
        .append('div')
            .attr('class','sc-flex-row')
        ;

    var scSliders = scRows
        .append('div')
            .attr('id', (d) => {
                return "sc-slider-container-" + d;
            })
            .append('input')
                .attr('class', 'sc-slider sc-grow')
                .attr('id', (d) => {
                    return "sc-" + d;
                })
                .attr('type', 'range')
                .attr('value', 50)
                .attr('step', TOLERANCE)
        ;
    // Override range for hue slider
    d3.select('.sc-slider#sc-hue')
        .attr('max',360)
        .attr('value',200)
        ;
    // Override background for opacity slider
    d3.select('.sc-slider#sc-alpha')
        .attr('max',1)
        .attr('value',1.0)
        .attr('step',0.1)
        .classed("checkerboard", true);
        ;

    scRows
        .append('input')
            .attr('class', 'sc-number')
            .attr('id', (d) => {
                return "sc-" + d + "-number";
            })
            .attr('type', 'text')
            .attr('value', 50)
        ;
    // Override numbers
    d3.select('#sc-hue-number')
        .attr('value',200)
        ;
    d3.select('#sc-alpha-number')
        .attr('value', 1.0)
        ;

    scRows
        .append('span')
            .attr('class', 'sc-suffix')
            .text((d) => {
                return suffixes[d];
            })
        ;

    // swatches & hex code
    var scSwatchRow = sccp.append('div')
        .attr('class','sc-flex-row')
        ;
    scSwatchRow.append('div')
        .attr('class','sc-swatch checkerboard')
        .append('div')
            .attr('id','sc-old-color')
            .attr('class','sc-swatch')
        ;
    scSwatchRow.append('div')
        .attr('class','sc-swatch checkerboard')
        .append('div')
            .attr('id','sc-new-color')
            .attr('class','sc-swatch')
        ;
    scSwatchRow.append('div')
        .append('input')
            .attr('id','sc-new-hex')
            .on('input', function(){
                // Use this value to update the sliders
                if ( d3.color(this.value) ) {
                    // updateSliders(this.value);
                    updateInputs(this.value);
                }
            })
        ;
    scSwatchRow.append('div')
        .append('input')
            .attr('id','sc-new-rgba')
        ;

    updateInputs(newColor);

    function updateInputs(colorString) {
        d3color = d3.hsl(colorString);
        d3.select('#sc-hue').attr('value', d3color.h);
        d3.select('#sc-saturation').attr('value', d3color.s * 100);
        d3.select('#sc-lightness').attr('value', d3color.l * 100);
        d3.select('#sc-alpha').attr('value', d3color.opacity);
        updateSliders(d3color);

        d3.select('#sc-hue-number').attr('value', d3color.h);
        d3.select('#sc-saturation-number').attr('value', d3color.s * 100);
        d3.select('#sc-lightness-number').attr('value', d3color.l * 100);
        d3.select('#sc-alpha-number').attr('value', d3color.opacity);
    }

    // Define the colorChange function
    function updateSliders(d3color) {
        // Update hex code && target
        d3.select('#sc-new-color').style('background', d3.hsl(d3color).toString() );
        d3.select('#sc-new-hex').attr('value', rgb2hex(d3color.toString()) );
        d3.select('#sc-new-rgba').attr('value', d3.rgb(d3color).toString().replace(/ /g,"") );
        // target.style('background', rgb2hex(d3color.toString()) ); // special case
        target.style('background', d3.hsl(d3color).toString() );

        // Ramp hue from 0 to 100
        fromColor = `hsla(0, ${100*d3color.s}%, ${100*d3color.l}%, 1)`;
        midColor = `hsla(90, ${100*d3color.s}%, ${100*d3color.l}%, 1)`;
        toColor = `hsla(180, ${100*d3color.s}%, ${100*d3color.l}%, 1)`;
        d3.select('#sc-hue').style('background', makeGradient(d3color.toString()));

        // Ramp saturation from 0 to 100
        fromColor = `hsla(${d3color.h}, 0%, ${100*d3color.l}%, 1)`;
        // midColor = `hsla(${d3color.h}, ${100*d3color.s}%, 50%, 1)`;
        toColor = `hsla(${d3color.h}, 100%, ${100*d3color.l}%, 1)`;
        gradientColor = `linear-gradient(to right, ${fromColor}, ${toColor})`;
        d3.select('#sc-saturation').style('background', gradientColor);

        // Ramp lightness from 0 to 100
        fromColor = `hsla(${d3color.h}, ${100*d3color.s}%, 0%, 1)`;
        midColor = `hsla(${d3color.h}, ${100*d3color.s}%, 50%, 1)`;
        toColor = `hsla(${d3color.h}, ${100*d3color.s}%, 100%, 1)`;
        gradientColor = `linear-gradient(to right, ${fromColor}, ${midColor}, ${toColor})`;
        d3.select('#sc-lightness').style('background', gradientColor);

        // Ramp alpha from 0 to 100
        fromColor = `hsla(${d3color.h}, ${100*d3color.s}%, ${100*d3color.l}%, 0)`;
        toColor = `hsla(${d3color.h}, ${100*d3color.s}%, ${100*d3color.l}%, 1)`;
        gradientColor = `linear-gradient(to right, ${fromColor}, ${toColor})`;
        d3.select('#sc-alpha').style('background', gradientColor);

    }

    // Set the on change handlers
    d3.select('#sc-hue').on('input',function(d){
        if ( Math.abs(newColor.h - this.value) >= TOLERANCE ) {
            newColor.h = this.value;
            d3.select('#sc-new-color').style('background', d3.hsl(newColor).toString() );
            d3.select('#sc-hue-number').attr('value',this.value);
            updateSliders(newColor);
        }
    });

    d3.select('#sc-saturation').on('input',function(d){
        if ( Math.abs(newColor.s - this.value/100) >= TOLERANCE/100 ) {
            newColor.s = this.value/100;
            d3.select('#sc-new-color').style('background', newColor);
            d3.select('#sc-saturation-number').attr('value',this.value);
            updateSliders(newColor);
        }
    });

    d3.select('#sc-lightness').on('input',function(d){
        if ( Math.abs(newColor.l - this.value/100) >= TOLERANCE/100 ) {
            newColor.l = this.value/100;
            d3.select('#sc-new-color').style('background', newColor);
            d3.select('#sc-lightness-number').attr('value',this.value);
            updateSliders(newColor);
        }
    });

    d3.select('#sc-alpha').on('input',function(d){
        if ( Math.abs(newColor.opacity - this.value) >= TOLERANCE/100 ) {
            newColor.opacity = this.value;
            d3.select('#sc-new-color').style('background', newColor);
            d3.select('#sc-alpha-number').attr('value',this.value);
            updateSliders(newColor);
        }
    });

    function makeGradient(hex) {
        var colorArr = [];
        var d3c = d3.hsl(hex);
        // Increment through the d3.hcl(?) spectrum
        // Converting each to HSL for CSS
        for (var i = 0; i <= 360; i = i + 10) {
            d3c.h = i;
            colorArr.push(d3c.toString());
        }
        var ret = `linear-gradient(to right, ${colorArr.join(",")} )`;
        return ret;
    }

}

function rgb2hex(rgb){
  // ignores alpha
  rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
  return (rgb && rgb.length === 4) ? "#" +
    ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
    ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
<|endoftext|>