<commit_before>function tizen_alarm() {
	var dictionary = [],
		win = Titanium.UI.createWindow(),
		button_bar = Ti.UI.createView({
			backgroundColor: '#555555',
			height: 65,
			bottom: 0,
			layout: 'horizontal',
			horizontalWrap: false
		}),
		newAbsolute = Ti.UI.createButton({
			top : 10,
			height: 45,
			left: 10,
			title: 'Absolute',
			color: '#555555',
		}),
		newRelative = Ti.UI.createButton({
			top : 10,
			height: 45,
			left: 10,
			title: 'Relative',
			color: '#555555',
		}),
		deleteAll = Ti.UI.createButton({
			top : 10,
			height: 45,
			left: 10,
			right: 10,
			title: 'Delete all ',
			color: '#555555',
		}),
		headView = Ti.UI.createView({
			backgroundColor:'#555555',
			height: 25,
			bottom: 0,
		}),
		headLabel = Ti.UI.createLabel({
			color: '#ffffff',
			text: 'Alarm'
		});

	headView.add(headLabel);

	var	tableViewOptions = {
			headerView: headView,
			backgroundColor: '#ffffff',
			rowBackgroundColor: '#555555',
			bottom: 85,
			data : dictionary
		},
		tabView = Ti.UI.createTableView(tableViewOptions);

	newAbsolute.addEventListener('click', function() {
		createAbsoluteAlarm();
	});

	newRelative.addEventListener('click', function() {
		createRelativeAlarm();
	});

	deleteAll.addEventListener('click', function() {
		Ti.Tizen.Alarm.removeAll();
		dictionary = [];
		tabView.setData(dictionary);
	});

	button_bar.add(newAbsolute);
	button_bar.add(newRelative);
	button_bar.add(deleteAll);

	win.add(tabView);
	win.add(button_bar);
	return win;

	function createAbsoluteAlarm(){
		var win = Ti.UI.createWindow({
			backgroundColor: '#555555'
		}),
		dateView = Ti.UI.createView({
			backgroundColor: '#ffffff',
			borderColor: '#333333',
			borderwidth: 1,
			height: 150,
			top: 60,
		}),
		dateLabel = Titanium.UI.createLabel({
			color: '#555555',
			text: 'Time',
			top: 10,
			left: 20
		}),
		dateTimePicker = createPicker({
			value: new Date()
		}),
		periodView = Ti.UI.createView({
			backgroundColor: '#ffffff',
			borderColor: '#333333',
			borderwidth: 1,
			height: 100,
			top: 260,
		}),
		slider = Titanium.UI.createSlider({
			top: 50,
			left: 10,
			right: 10,
			min: 0,
			max: 120,
			value: 0
		}),
		periodLabel = Titanium.UI.createLabel({
			color: '#555555',
			text: 'Repeat interval (sec): ' + slider.value,
			top: 10,
			left: 20
		}),
		winTitle = Ti.UI.createLabel({
			color: '#555555',
			text: 'Absolute Alarm Add',
			top: 20,
			left: 20
		}),
		notification_label = Ti.UI.createLabel({
			color: '#555555',
			text: 'When the time is up, the browser will be shown.',
			bottom : 85
		}),
		saveButton = Ti.UI.createButton({
			color: '#555555',
			bottom: 20,
			left: 20,
			height: 45,
			width : 100,
			title: 'Save'
		}),
		cancelButton = Ti.UI.createButton({
			color: '#555555',
			bottom: 20,
			right : 20,
			height: 45,
			width : 55,
			title: 'Back'
		});

		slider.addEventListener('change', function(e) {
			periodLabel.text = String.format('Repeat interval (sec): %3d', e.value);
		});

		saveButton.addEventListener('click', function(){
			addAbsoluteAlarm(dateTimePicker.value, slider.value);
			win.close();
		});

		cancelButton.addEventListener('click', function(){
			win.close();
		});

		dateView.add(dateTimePicker);
		dateView.add(dateLabel);

		periodView.add(slider);
		periodView.add(periodLabel);

		win.add(dateView);
		win.add(notification_label);
		win.add(winTitle);
		win.add(periodView);
		win.add(saveButton);
		win.add(cancelButton);

		win.open();
	}

	function createPicker() {
		var picker = Ti.UI.createPicker({
			type: Ti.UI.PICKER_TYPE_DATE_AND_TIME,
			selectionIndicator: true, // turn on the selection indicator (off by default)
			value: new Date()
		});

		return picker;
	}

	function addAbsoluteAlarm(time, period) {
		var period = Math.floor(period),
			alarm = Ti.Tizen.Alarm.createAlarmAbsolute({
				date: time,
				period: period
			});

			dialog = Ti.UI.createAlertDialog({
				cancel: 1,
				buttonNames: ['Ok'],
				title: 'Alarm'
			});

		Ti.Tizen.Alarm.add(alarm, 'org.tizen.browser');
		dialog.message = 'Alarm has been successfuly added with id ' + alarm.id;
		dialog.show();
		addRow(alarm);
	}

	function createRelativeAlarm(){
		var win = Ti.UI.createWindow({
				backgroundColor: '#555555'
			}),
			delayView = Ti.UI.createView({
				backgroundColor: '#ffffff',
				borderColor: '#555555',
				borderwidth: 1,
				height: 100,
				top: 60,
			}),
			sliderDelay = Titanium.UI.createSlider({
				top: 50,
				left: 10,
				right: 10,
				min: 0,
				max: 120,
				value: 10
			}),
			delayLabel = Titanium.UI.createLabel({
				color: '#555555',
				text: 'Delay (sec)' + sliderDelay.value,
				top: 10,
				left: 20
			}),
			periodView = Ti.UI.createView({
				backgroundColor: '#ffffff',
				borderColor: '#555555',
				borderwidth: 1,
				height: 100,
				top: 210,
			}),
			slider = Titanium.UI.createSlider({
				top: 50,
				left: 10,
				right: 10,
				min: 0,
				max: 120,
				value: 0
			}),
			periodLabel = Titanium.UI.createLabel({
				color: '#555555',
				text: 'Repeat interval (sec): ' + slider.value,
				top: 10,
				left: 20
			}),
			winTitle = Ti.UI.createLabel({
				color: '#ffffff',
				text: 'Relative Alarm Add',
				top: 20,
				left: 20
			}),
			notificationLabel = Ti.UI.createLabel({
				color: '#ffffff',
				text: 'When the time is up, the clock app will be shown.',
				bottom : 85
			}),
			saveButton = Ti.UI.createButton({
				color: '#555555',
				bottom: 20,
				left: 20,
				height: 45,
				width : 100,
				title: 'Save'
			}),
			cancelButton = Ti.UI.createButton({
				color: '#555555',
				bottom: 20,
				right : 20,
				height: 45,
				width : 55,
				title: 'Back'
			});

		sliderDelay.addEventListener('change', function(e) {
			delayLabel.text = String.format('Delay (sec): %3d', e.value);
		});

		delayView.add(sliderDelay);
		delayView.add(delayLabel);

		slider.addEventListener('change', function(e) {
		    periodLabel.text = String.format('Repeat interval (sec): %3d', e.value);
		});

		periodView.add(slider);
		periodView.add(periodLabel);

		win.add(notificationLabel);
		win.add(winTitle);

		saveButton.addEventListener('click', function() {
			addRelativeAlarm(sliderDelay.value, slider.value);
			win.close();
		});

		cancelButton.addEventListener('click', function() {
			win.close();
		});

		win.add(delayView);
		win.add(periodView);
		win.add(saveButton);
		win.add(cancelButton);

		win.open();

	}

	function addRelativeAlarm(delay, period) {
		period = Math.floor(period);
		delay = Math.floor(delay);

		var alarm = Ti.Tizen.Alarm.createAlarmRelative({
				delay: delay,
				period: period
			}),
			dialog = Ti.UI.createAlertDialog({
				cancel: 1,
				buttonNames: ['Ok'],
				message: 'Alarm has been successfuly added with id ' + alarm.id,
				title: 'Alarm'
			});

		Ti.Tizen.Alarm.add(alarm, 'org.tizen.clock');

		dialog.show();
		addRow(alarm);
	}

	function addRow(alarm) {
		var row = createRow(alarm);

		dictionary.push(row);
		tabView.setData(dictionary);
	}

	function createRow(alarm) {
		var text1,
			text2,
			remaining,
			view = Ti.UI.createView({
				layout: 'horizontal'
			}),
			childView = Ti.UI.createView({
				width: 220,
				layout: 'vertical'
			}),
			label1 = Ti.UI.createLabel({
				font: { fontSize:18 },
				color: '#555555'
			}),
			label2 = Ti.UI.createLabel({
				color: '#555555'
			}),
			button = Ti.UI.createButton({
				color: '#555555',
				title: 'Delete',
				right: 20
			}),
			row = Ti.UI.createTableViewRow({
				alarmId: alarm.id,
				touchEnabled: true,
				height: 50
			});

		if (alarm instanceof Ti.Tizen.Alarm.AlarmAbsolute) {
			remaining = alarm.getNextScheduledDate();
			text1 = remaining.toDateString();
			text2 = 'Absolute alarm (Period ' + alarm.period + ')';
		} else if (alarm instanceof Ti.Tizen.Alarm.AlarmRelative) {
			text1 = alarm.delay + ' sec';
			text2 = 'Relative alarm (Period ' + alarm.period + ')';
		}

		label2.text = text2;
		label1.text = text1;

		childView.add(label1);
		childView.add(label2);

		button.addEventListener('click', function() {
			var id = alarm.id,
				i = 0,
				len = dictionary.length;

			try {
				Ti.Tizen.Alarm.remove(alarm.id);
			} catch(e) {}

			for(; i < len; i++) {
				if (dictionary[i].alarmId === id) {
					dictionary.splice(i, 1);
					tabView.setData(dictionary);
					break;
				}
			}
		});

		view.add(childView);
		view.add(button);

		row.add(view);
		return row;
	}
}

module.exports = tizen_alarm;<commit_msg>Change program id in Alarm module in KitchenSink.<commit_after>function tizen_alarm() {
	var dictionary = [],
		win = Titanium.UI.createWindow(),
		button_bar = Ti.UI.createView({
			backgroundColor: '#555555',
			height: 65,
			bottom: 0,
			layout: 'horizontal',
			horizontalWrap: false
		}),
		newAbsolute = Ti.UI.createButton({
			top : 10,
			height: 45,
			left: 10,
			title: 'Absolute',
			color: '#555555',
		}),
		newRelative = Ti.UI.createButton({
			top : 10,
			height: 45,
			left: 10,
			title: 'Relative',
			color: '#555555',
		}),
		deleteAll = Ti.UI.createButton({
			top : 10,
			height: 45,
			left: 10,
			right: 10,
			title: 'Delete all ',
			color: '#555555',
		}),
		headView = Ti.UI.createView({
			backgroundColor:'#555555',
			height: 25,
			bottom: 0,
		}),
		headLabel = Ti.UI.createLabel({
			color: '#ffffff',
			text: 'Alarm'
		});

	headView.add(headLabel);

	var	tableViewOptions = {
			headerView: headView,
			backgroundColor: '#ffffff',
			rowBackgroundColor: '#555555',
			bottom: 85,
			data : dictionary
		},
		tabView = Ti.UI.createTableView(tableViewOptions);

	newAbsolute.addEventListener('click', function() {
		createAbsoluteAlarm();
	});

	newRelative.addEventListener('click', function() {
		createRelativeAlarm();
	});

	deleteAll.addEventListener('click', function() {
		Ti.Tizen.Alarm.removeAll();
		dictionary = [];
		tabView.setData(dictionary);
	});

	button_bar.add(newAbsolute);
	button_bar.add(newRelative);
	button_bar.add(deleteAll);

	win.add(tabView);
	win.add(button_bar);
	return win;

	function createAbsoluteAlarm(){
		var win = Ti.UI.createWindow({
			backgroundColor: '#555555'
		}),
		dateView = Ti.UI.createView({
			backgroundColor: '#ffffff',
			borderColor: '#333333',
			borderwidth: 1,
			height: 150,
			top: 60,
		}),
		dateLabel = Titanium.UI.createLabel({
			color: '#555555',
			text: 'Time',
			top: 10,
			left: 20
		}),
		dateTimePicker = createPicker({
			value: new Date()
		}),
		periodView = Ti.UI.createView({
			backgroundColor: '#ffffff',
			borderColor: '#333333',
			borderwidth: 1,
			height: 100,
			top: 260,
		}),
		slider = Titanium.UI.createSlider({
			top: 50,
			left: 10,
			right: 10,
			min: 0,
			max: 120,
			value: 0
		}),
		periodLabel = Titanium.UI.createLabel({
			color: '#555555',
			text: 'Repeat interval (sec): ' + slider.value,
			top: 10,
			left: 20
		}),
		winTitle = Ti.UI.createLabel({
			color: '#555555',
			text: 'Absolute Alarm Add',
			top: 20,
			left: 20
		}),
		notification_label = Ti.UI.createLabel({
			color: '#555555',
			text: 'When the time is up, the browser will be shown.',
			bottom : 85
		}),
		saveButton = Ti.UI.createButton({
			color: '#555555',
			bottom: 20,
			left: 20,
			height: 45,
			width : 100,
			title: 'Save'
		}),
		cancelButton = Ti.UI.createButton({
			color: '#555555',
			bottom: 20,
			right : 20,
			height: 45,
			width : 55,
			title: 'Back'
		});

		slider.addEventListener('change', function(e) {
			periodLabel.text = String.format('Repeat interval (sec): %3d', e.value);
		});

		saveButton.addEventListener('click', function(){
			addAbsoluteAlarm(dateTimePicker.value, slider.value);
			win.close();
		});

		cancelButton.addEventListener('click', function(){
			win.close();
		});

		dateView.add(dateTimePicker);
		dateView.add(dateLabel);

		periodView.add(slider);
		periodView.add(periodLabel);

		win.add(dateView);
		win.add(notification_label);
		win.add(winTitle);
		win.add(periodView);
		win.add(saveButton);
		win.add(cancelButton);

		win.open();
	}

	function createPicker() {
		var picker = Ti.UI.createPicker({
			type: Ti.UI.PICKER_TYPE_DATE_AND_TIME,
			selectionIndicator: true, // turn on the selection indicator (off by default)
			value: new Date()
		});

		return picker;
	}

	function addAbsoluteAlarm(time, period) {
		var period = Math.floor(period),
			alarm = Ti.Tizen.Alarm.createAlarmAbsolute({
				date: time,
				period: period
			});

			dialog = Ti.UI.createAlertDialog({
				cancel: 1,
				buttonNames: ['Ok'],
				title: 'Alarm'
			});

		Ti.Tizen.Alarm.add(alarm, 'tlp6xwqzos.Calculator');
		dialog.message = 'Alarm has been successfuly added with id ' + alarm.id;
		dialog.show();
		addRow(alarm);
	}

	function createRelativeAlarm(){
		var win = Ti.UI.createWindow({
				backgroundColor: '#555555'
			}),
			delayView = Ti.UI.createView({
				backgroundColor: '#ffffff',
				borderColor: '#555555',
				borderwidth: 1,
				height: 100,
				top: 60,
			}),
			sliderDelay = Titanium.UI.createSlider({
				top: 50,
				left: 10,
				right: 10,
				min: 0,
				max: 120,
				value: 10
			}),
			delayLabel = Titanium.UI.createLabel({
				color: '#555555',
				text: 'Delay (sec)' + sliderDelay.value,
				top: 10,
				left: 20
			}),
			periodView = Ti.UI.createView({
				backgroundColor: '#ffffff',
				borderColor: '#555555',
				borderwidth: 1,
				height: 100,
				top: 210,
			}),
			slider = Titanium.UI.createSlider({
				top: 50,
				left: 10,
				right: 10,
				min: 0,
				max: 120,
				value: 0
			}),
			periodLabel = Titanium.UI.createLabel({
				color: '#555555',
				text: 'Repeat interval (sec): ' + slider.value,
				top: 10,
				left: 20
			}),
			winTitle = Ti.UI.createLabel({
				color: '#ffffff',
				text: 'Relative Alarm Add',
				top: 20,
				left: 20
			}),
			notificationLabel = Ti.UI.createLabel({
				color: '#ffffff',
				text: 'When the time is up, the clock app will be shown.',
				bottom : 85
			}),
			saveButton = Ti.UI.createButton({
				color: '#555555',
				bottom: 20,
				left: 20,
				height: 45,
				width : 100,
				title: 'Save'
			}),
			cancelButton = Ti.UI.createButton({
				color: '#555555',
				bottom: 20,
				right : 20,
				height: 45,
				width : 55,
				title: 'Back'
			});

		sliderDelay.addEventListener('change', function(e) {
			delayLabel.text = String.format('Delay (sec): %3d', e.value);
		});

		delayView.add(sliderDelay);
		delayView.add(delayLabel);

		slider.addEventListener('change', function(e) {
		    periodLabel.text = String.format('Repeat interval (sec): %3d', e.value);
		});

		periodView.add(slider);
		periodView.add(periodLabel);

		win.add(notificationLabel);
		win.add(winTitle);

		saveButton.addEventListener('click', function() {
			addRelativeAlarm(sliderDelay.value, slider.value);
			win.close();
		});

		cancelButton.addEventListener('click', function() {
			win.close();
		});

		win.add(delayView);
		win.add(periodView);
		win.add(saveButton);
		win.add(cancelButton);

		win.open();

	}

	function addRelativeAlarm(delay, period) {
		period = Math.floor(period);
		delay = Math.floor(delay);

		var alarm = Ti.Tizen.Alarm.createAlarmRelative({
				delay: delay,
				period: period
			}),
			dialog = Ti.UI.createAlertDialog({
				cancel: 1,
				buttonNames: ['Ok'],
				title: 'Alarm'
			});

		Ti.Tizen.Alarm.add(alarm, 'org.tizen.clock');

		dialog.message = 'Alarm has been successfuly added with id ' + alarm.id;
		dialog.show();

		addRow(alarm);
	}

	function addRow(alarm) {
		var row = createRow(alarm);

		dictionary.push(row);
		tabView.setData(dictionary);
	}

	function createRow(alarm) {
		var text1,
			text2,
			remaining,
			view = Ti.UI.createView({
				layout: 'horizontal'
			}),
			childView = Ti.UI.createView({
				width: 220,
				layout: 'vertical'
			}),
			label1 = Ti.UI.createLabel({
				font: { fontSize:18 },
				color: '#555555'
			}),
			label2 = Ti.UI.createLabel({
				color: '#555555'
			}),
			button = Ti.UI.createButton({
				color: '#555555',
				title: 'Delete',
				right: 20
			}),
			row = Ti.UI.createTableViewRow({
				alarmId: alarm.id,
				touchEnabled: true,
				height: 50
			});

		if (alarm instanceof Ti.Tizen.Alarm.AlarmAbsolute) {
			remaining = alarm.getNextScheduledDate();
			text1 = remaining.toDateString();
			text2 = 'Absolute alarm (Period ' + alarm.period + ')';
		} else if (alarm instanceof Ti.Tizen.Alarm.AlarmRelative) {
			text1 = alarm.delay + ' sec';
			text2 = 'Relative alarm (Period ' + alarm.period + ')';
		}

		label2.text = text2;
		label1.text = text1;

		childView.add(label1);
		childView.add(label2);

		button.addEventListener('click', function() {
			var id = alarm.id,
				i = 0,
				len = dictionary.length;

			try {
				Ti.Tizen.Alarm.remove(alarm.id);
			} catch(e) {}

			for(; i < len; i++) {
				if (dictionary[i].alarmId === id) {
					dictionary.splice(i, 1);
					tabView.setData(dictionary);
					break;
				}
			}
		});

		view.add(childView);
		view.add(button);

		row.add(view);
		return row;
	}
}

module.exports = tizen_alarm;<|endoftext|>


<commit_before>var Structr = require('structr'),
Parser = require('./parser');

var Request = Structr({

	/**
	 */

	'__construct': function(listener, batch)
	{
		// this.batch  = batch;
		this.data     = batch.data;
		this.callback = batch.callback;

		this._used = {};
		this._queue = [];

		this._add(listener, this.data);

		if(batch._next)
		{
			this.add(batch._next);
		}

	},

	/**
	 */

	'init': function()
	{
		return this;
	},

	/**
	 */

	'hasNext': function()
	{
		return !!this._queue.length;
	},

	/**
	 */

	'next': function()
	{
		if(this._queue.length)
		{
			var thru = this._queue.pop(),
			target = thru.target;

			this.current = target;

			if(target.paths)
			{
				var route = this.origin.getRoute({ channel: target });

				this._addListeners(route.listeners, route.data);
				return this.next();
			}

			if(this._used[target.id]) return this.next();

			//keep tabs of what's used so there's no overlap. this will happen when we get back to the router
			//for middleware specified in path -> to -> route
			this._used[target.id] = thru;

			this._prepare(target, thru.data);

			return true;
		}

		return false;
	},

	/**
	 */

	'_addListeners': function(listeners, data)
	{
		if(listeners instanceof Array)
		{
			for(var i = listeners.length; i--;)
			{
				this._add(listeners[i], data);
			}
			return;
		}
	},

	/**
	 * adds middleware to the END of the call stack
	 */

	'add': function(callback)
	{
		this._queue.unshift(this._func(callback));
	},

	/**
	 * adds  middleware to the beginning of the call stack
	 */

	'unshift': function(callback)
	{
		this._queue.push(this._func(callback));
	},

	/**
	 */

	'_func': function(callback)
	{
		return { target: { callback: callback }, data: {} };
	},

	/**
	 */

	'_add': function(route, data)
	{
		var current = route, _queue = this._queue;

		while(current)
		{
			//make sure not to use the same route twice. this will happen especially with middleware specified as /middleware/*
			_queue.push({ target: current, data: data });

			current = current.thru;
		}
	},

	/**
	 */

	'_prepare': function(target, data)
	{
		for(var index in data._params)
		{
			//breaks on middleware
            var v = target.path[index];
            if(!v) break;

			var iname = target.path[index].name;

			//should it really be set to global?
			this.data[iname] = data[iname] = data._params[index];
		}

		/*for(var i = target.path.length; i--;)
		{
			var path = target.path[i];

			if(path.param && !data[path.name])
			{
				console.log(data._params[i])
			}
		}*/

		this._callback(target, data);
	},

	/**
	 */

	'_callback': function(target, data)
	{
		return target.callback.call(this, this);
	}
});

module.exports = Request;<commit_msg>better route traversing<commit_after>var Structr = require('structr'),
Parser = require('./parser');

var Request = Structr({

	/**
	 */

	'__construct': function(listener, batch)
	{
		// this.batch  = batch;
		this.data     = batch.data;
		this.callback = batch.callback;

		this._used = {};
		this._queue = [];

		this._add(listener, this.data, batch.paths);

		if(batch._next)
		{
			this.add(batch._next);
		}

	},

	/**
	 */

	'init': function()
	{
		return this;
	},

	/**
	 */

	'hasNext': function()
	{
		return !!this._queue.length;
	},

	/**
	 */

	'next': function()
	{
		if(this._queue.length)
		{
			var thru = this._queue.pop(),
			target = thru.target;

			this.current = target;

			if(target.paths)
			{
				var route = this.origin.getRoute({ channel: target });

				this._addListeners(route.listeners, route.data, target.paths);
				return this.next();
			}

			if(this._used[target.id]) return this.next();

			//keep tabs of what's used so there's no overlap. this will happen when we get back to the router
			//for middleware specified in path -> to -> route
			this._used[target.id] = thru;

			this._prepare(target, thru.data, thru.paths);

			return true;
		}

		return false;
	},

	/**
	 */

	'_addListeners': function(listeners, data, paths)
	{
		if(listeners instanceof Array)
		{
			for(var i = listeners.length; i--;)
			{
				this._add(listeners[i], data, paths);
			}
			return;
		}
	},

	/**
	 * adds middleware to the END of the call stack
	 */

	'add': function(callback)
	{
		this._queue.unshift(this._func(callback));
	},

	/**
	 * adds  middleware to the beginning of the call stack
	 */

	'unshift': function(callback)
	{
		this._queue.push(this._func(callback));
	},

	/**
	 */

	'_func': function(callback)
	{
		return { target: { callback: callback }, data: {} };
	},

	/**
	 */

	'_add': function(route, data, paths)
	{
		var current = route, _queue = this._queue;

		if(!data) data = {};

		while(current)
		{
			for(var i = paths.length; i--;)
			{
				var opath = paths[i],
				cpath = route.path[i],
				param,
				value;

				if(cpath.param && !opath.param)
				{
					param = cpath.name;
					value = opath.name;
				}
				else
				if(cpath.param && opath.param)
				{
					param = cpath.name;
					value = this.data[opath.name];
				}

				this.data[param] = data[param] = value;

				// if(path.param)
			}

			//make sure not to use the same route twice. this will happen especially with middleware specified as /middleware/*
			_queue.push({ target: current, data: data || {}, paths: paths });

			current = current.thru;
		}
	},

	/**
	 */

	'_prepare': function(target, data, paths)
	{
		this._callback(target, data);
	},

	/**
	 */

	'_callback': function(target, data)
	{
		return target.callback.call(this, this);
	}
});

module.exports = Request;<|endoftext|>


<commit_before>#!/usr/bin/env node

const glob = require('fast-glob');
const { satisfies } = require('semver');
const { spawn } = require('@malept/cross-spawn-promise');

const DO_NOT_UPGRADE = [
  '@types/node-fetch', // No longer needed when node-fetch is upgraded to >= 3.0.0
  '@typescript-eslint/eslint-plugin', // special case
  'chalk', // Requires ESM
  'commander', // TODO: convert to yargs
  'find-up', // Requires ESM
  'log-symbols', // Requires ESM
  'node-fetch', // Requires ESM
  'ora', // Requires ESM
  'username', // Requires ESM
];

/**
 * Spawn, but pass through stdio by default.
 */
async function spawnPassthrough(cmd, args, options) {
  await spawn(cmd, args, { stdio: 'inherit', ...options });
}

async function bolt(...args) {
  await spawnPassthrough('bolt', args);
}

async function git(...args) {
  await spawnPassthrough('git', args);
}

async function yarn(...args) {
  await spawnPassthrough('yarn', args);
}

const packageJSON = require(__dirname + '/../package.json');

class Package {
  constructor(name, currentVersion, wantedVersion, latestVersion, type) {
    this.name = name;
    this.currentVersion = currentVersion;
    this.wantedVersion = wantedVersion;
    this.latestVersion = latestVersion;
    this.type = type;
  }

  get commitType() {
    switch (this.type) {
      case 'dependencies':
      case 'optionalDependencies':
        return 'deps';
      case 'devDependencies':
        return 'deps-dev';
      default:
        return 'deps-unknown';
    }
  }

  get commitVersion() {
    if (this.isMajorVersionBump()) {
      return `^${this.latestVersion}`;
    } else if (this.isMinorVersionBump()) {
      return `~${this.latestVersion}`;
    } else {
      return this.latestVersion;
    }
  }

  get minorVersionLocked() {
    return packageJSON[this.type][this.name].startsWith('~');
  }

  isMajorVersionBump() {
    return !satisfies(this.latestVersion, `^${this.wantedVersion}`);
  }

  isMinorVersionBump() {
    return this.minorVersionLocked && !satisfies(this.latestVersion, `~${this.wantedVersion}`);
  }

  async smoketestAndCommit(packageName = null) {
    const packageJSONs = await glob('packages/*/*/package.json');
    await yarn('lint');
    await bolt('build');
    await git('add', 'package.json', 'yarn.lock', ...packageJSONs);
    await git('commit', '-m', `build(${this.commitType}): upgrade ${packageName || this.name} to ${this.commitVersion}`);
  }

  async upgrade() {
    if (this.isMajorVersionBump() || this.isMinorVersionBump()) {
      await this.bolt_upgrade();
    } else {
      await this.yarn_upgrade();
    }
  }

  async bolt_upgrade() {
    console.log(`Upgrading ${this.name} from ${this.wantedVersion} to ^${this.latestVersion} (and updating package.json)...`);
    await bolt('upgrade', `${this.name}@^${this.latestVersion}`);
  }

  async yarn_upgrade() {
    console.log(`Upgrading ${this.name} from ${this.currentVersion} to ${this.latestVersion} in yarn.lock...`);
    await yarn('upgrade', this.name);
  }
}

async function main() {
  const onlyModules = [];
  if (process.argv.length > 2) {
    onlyModules.push(...process.argv.slice(2));
  }
  try {
    await spawn('yarn', ['outdated', '--json']);
    console.log('No packages to update.');
  } catch (error) {
    const table = JSON.parse(error.stdout.split('\n')[1]);
    for (const [packageName, currentVersion, wantedVersion, latestVersion, packageType /*, _url */] of table.data.body) {
      if (DO_NOT_UPGRADE.includes(packageName)) {
        console.log(`Skipping "${packageName} from update as it is in the denylist`);
        continue;
      }
      if (onlyModules.length > 0 && !onlyModules.includes(packageName)) {
        console.log(`Skipping "${packageName}" from update as it was not specified on the command line`);
        continue;
      }
      let commitPackageName = null;
      const nodePackage = new Package(packageName, currentVersion, wantedVersion, latestVersion, packageType);
      await nodePackage.upgrade();

      if (packageName === '@typescript-eslint/parser') {
        const eslintPlugin = new Package('@typescript-eslint/eslint-plugin', currentVersion, wantedVersion, latestVersion, packageType);
        await eslintPlugin.upgrade();
        commitPackageName = '@typescript-eslint/{parser,eslint-plugin}';
      }

      await nodePackage.smoketestAndCommit(commitPackageName);
    }
  }

  if (onlyModules.length == 0) {
    console.log(`Upgrading transitive dependencies in yarn.lock...`);
    await yarn('upgrade');
    await git('add', 'yarn.lock');
    await git('commit', '-m', `build(deps): upgrade transitive dependencies`);
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
<commit_msg>chore(update-deps): add more modules to the denylist<commit_after>#!/usr/bin/env node

const glob = require('fast-glob');
const { satisfies } = require('semver');
const { spawn } = require('@malept/cross-spawn-promise');

const DO_NOT_UPGRADE = [
  '@types/node-fetch', // No longer needed when node-fetch is upgraded to >= 3.0.0
  '@typescript-eslint/eslint-plugin', // special case
  'chalk', // Requires ESM
  'commander', // TODO: convert to yargs
  'electron-osx-sign', // Requires Electron Packager's dependency to also be upgraded
  'eslint-plugin-mocha', // Requires Node 14
  'find-up', // Requires ESM
  'log-symbols', // Requires ESM
  'node-fetch', // Requires ESM
  'ora', // Requires ESM
  'username', // Requires ESM
];

/**
 * Spawn, but pass through stdio by default.
 */
async function spawnPassthrough(cmd, args, options) {
  await spawn(cmd, args, { stdio: 'inherit', ...options });
}

async function bolt(...args) {
  await spawnPassthrough('bolt', args);
}

async function git(...args) {
  await spawnPassthrough('git', args);
}

async function yarn(...args) {
  await spawnPassthrough('yarn', args);
}

const packageJSON = require(__dirname + '/../package.json');

class Package {
  constructor(name, currentVersion, wantedVersion, latestVersion, type) {
    this.name = name;
    this.currentVersion = currentVersion;
    this.wantedVersion = wantedVersion;
    this.latestVersion = latestVersion;
    this.type = type;
  }

  get commitType() {
    switch (this.type) {
      case 'dependencies':
      case 'optionalDependencies':
        return 'deps';
      case 'devDependencies':
        return 'deps-dev';
      default:
        return 'deps-unknown';
    }
  }

  get commitVersion() {
    if (this.isMajorVersionBump()) {
      return `^${this.latestVersion}`;
    } else if (this.isMinorVersionBump()) {
      return `~${this.latestVersion}`;
    } else {
      return this.latestVersion;
    }
  }

  get minorVersionLocked() {
    return packageJSON[this.type][this.name].startsWith('~');
  }

  isMajorVersionBump() {
    return !satisfies(this.latestVersion, `^${this.wantedVersion}`);
  }

  isMinorVersionBump() {
    return this.minorVersionLocked && !satisfies(this.latestVersion, `~${this.wantedVersion}`);
  }

  async smoketestAndCommit(packageName = null) {
    const packageJSONs = await glob('packages/*/*/package.json');
    await yarn('lint');
    await bolt('build');
    await git('add', 'package.json', 'yarn.lock', ...packageJSONs);
    await git('commit', '-m', `build(${this.commitType}): upgrade ${packageName || this.name} to ${this.commitVersion}`);
  }

  async upgrade() {
    if (this.isMajorVersionBump() || this.isMinorVersionBump()) {
      await this.bolt_upgrade();
    } else {
      await this.yarn_upgrade();
    }
  }

  async bolt_upgrade() {
    console.log(`Upgrading ${this.name} from ${this.wantedVersion} to ^${this.latestVersion} (and updating package.json)...`);
    await bolt('upgrade', `${this.name}@^${this.latestVersion}`);
  }

  async yarn_upgrade() {
    console.log(`Upgrading ${this.name} from ${this.currentVersion} to ${this.latestVersion} in yarn.lock...`);
    await yarn('upgrade', this.name);
  }
}

async function main() {
  const onlyModules = [];
  if (process.argv.length > 2) {
    onlyModules.push(...process.argv.slice(2));
  }
  try {
    await spawn('yarn', ['outdated', '--json']);
    console.log('No packages to update.');
  } catch (error) {
    const table = JSON.parse(error.stdout.split('\n')[1]);
    for (const [packageName, currentVersion, wantedVersion, latestVersion, packageType /*, _url */] of table.data.body) {
      if (DO_NOT_UPGRADE.includes(packageName)) {
        console.log(`Skipping "${packageName} from update as it is in the denylist`);
        continue;
      }
      if (onlyModules.length > 0 && !onlyModules.includes(packageName)) {
        console.log(`Skipping "${packageName}" from update as it was not specified on the command line`);
        continue;
      }
      let commitPackageName = null;
      const nodePackage = new Package(packageName, currentVersion, wantedVersion, latestVersion, packageType);
      await nodePackage.upgrade();

      if (packageName === '@typescript-eslint/parser') {
        const eslintPlugin = new Package('@typescript-eslint/eslint-plugin', currentVersion, wantedVersion, latestVersion, packageType);
        await eslintPlugin.upgrade();
        commitPackageName = '@typescript-eslint/{parser,eslint-plugin}';
      }

      await nodePackage.smoketestAndCommit(commitPackageName);
    }
  }

  if (onlyModules.length == 0) {
    console.log(`Upgrading transitive dependencies in yarn.lock...`);
    await yarn('upgrade');
    await git('add', 'yarn.lock');
    await git('commit', '-m', `build(deps): upgrade transitive dependencies`);
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import themeable from 'react-themeable';
import { autokey } from './autokey';
import clamp from 'clamp';

const isMobile = typeof document != 'undefined' && 'ontouchstart' in document;

class XYControl extends React.Component {
  _isMounted = false;

  static propTypes = {
    children: PropTypes.node.isRequired,
    theme: PropTypes.object.isRequired,
    x: PropTypes.number.isRequired,
    y: PropTypes.number.isRequired,
    xmax: PropTypes.number.isRequired,
    ymax: PropTypes.number.isRequired,
    isDark: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired
  };

  componentDidMount() {
    this._isMounted = true;
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  change(pos) {
    if (!this._isMounted) return;
    const rect = this.getOwnBoundingRect();
    this.props.onChange({
      x: clamp(pos.left, 0, rect.width) / rect.width * this.props.xmax,
      y: clamp(pos.top, 0, rect.height) / rect.height * this.props.ymax
    });
  }

  getOwnBoundingRect() {
    return ReactDOM.findDOMNode(this).getBoundingClientRect();
  }

  _dragStart = e => {
    e.preventDefault();
    if (!this._isMounted) return;
    const rect = this.getOwnBoundingRect();
    const x = isMobile ? e.changedTouches[0].clientX : e.clientX;
    const y = isMobile ? e.changedTouches[0].clientY : e.clientY;

    const offset = {
      left: x - rect.left,
      top: y - rect.top
    };

    this.change(offset);

    // Handle interaction
    this.setState({
      start: { x: offset.left, y: offset.top },
      offset: { x, y }
    });

    window.addEventListener(isMobile ? 'touchmove' : 'mousemove', this._drag);
    window.addEventListener(isMobile ? 'touchend' : 'mouseup', this._dragEnd);
  };

  _drag = e => {
    e.preventDefault();
    const { start, offset } = this.state;
    const top =
      (isMobile ? e.changedTouches[0].clientY : e.clientY) +
      start.y - offset.y;
    const left =
      (isMobile ? e.changedTouches[0].clientX : e.clientX) +
      start.x - offset.x;

    this.change({ top, left });
  };

  _dragEnd = () => {
    window.removeEventListener(isMobile ? 'touchmove' : 'mousemove', this._drag);
    window.removeEventListener(isMobile ? 'touchend' : 'mouseup', this._dragEnd);
  };

  render() {
    const theme = autokey(themeable(this.props.theme));
    const {
      children,
      x,
      y,
      xmax,
      ymax,
      isDark
    } = this.props;

    const top = Math.round(clamp(y / ymax * 100, 0, 100));
    const left = Math.round(clamp(x / xmax * 100, 0, 100));

    return (
      <div
        {...theme('xyControlContainer')}
        onTouchStart={this._dragStart}
        onMouseDown={this._dragStart}
      >
        <div
          {...theme('xyControl', `${isDark ? 'xyControlDark' : ''}`)}
          style={{
            top: `${top}%`,
            left: `${left}%`
          }}
        />
        {children}
      </div>
    );
  }
}

export default XYControl;
<commit_msg>always listen for both mouse and touch events<commit_after>'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import themeable from 'react-themeable';
import { autokey } from './autokey';
import clamp from 'clamp';

class XYControl extends React.Component {
  _isMounted = false;

  static propTypes = {
    children: PropTypes.node.isRequired,
    theme: PropTypes.object.isRequired,
    x: PropTypes.number.isRequired,
    y: PropTypes.number.isRequired,
    xmax: PropTypes.number.isRequired,
    ymax: PropTypes.number.isRequired,
    isDark: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired
  };

  componentDidMount() {
    this._isMounted = true;
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  change(pos) {
    if (!this._isMounted) return;
    const rect = this.getOwnBoundingRect();
    this.props.onChange({
      x: clamp(pos.left, 0, rect.width) / rect.width * this.props.xmax,
      y: clamp(pos.top, 0, rect.height) / rect.height * this.props.ymax
    });
  }

  getOwnBoundingRect() {
    return ReactDOM.findDOMNode(this).getBoundingClientRect();
  }

  _dragStart = e => {
    e.preventDefault();
    if (!this._isMounted) return;
    const rect = this.getOwnBoundingRect();
    const x = isMobile ? e.changedTouches[0].clientX : e.clientX;
    const y = isMobile ? e.changedTouches[0].clientY : e.clientY;

    const offset = {
      left: x - rect.left,
      top: y - rect.top
    };

    this.change(offset);

    // Handle interaction
    this.setState({
      start: { x: offset.left, y: offset.top },
      offset: { x, y }
    });

    window.addEventListener('mousemove', this._drag);
    window.addEventListener('mouseup', this._dragEnd);

    window.addEventListener('touchmove', this._drag);
    window.addEventListener('touchend', this._dragEnd);
  };

  _drag = e => {
    e.preventDefault();
    const { start, offset } = this.state;
    const top =
      (isMobile ? e.changedTouches[0].clientY : e.clientY) +
      start.y - offset.y;
    const left =
      (isMobile ? e.changedTouches[0].clientX : e.clientX) +
      start.x - offset.x;

    this.change({ top, left });
  };

  _dragEnd = () => {
    window.removeEventListener('mousemove', this._drag);
    window.removeEventListener('mouseup', this._dragEnd);

    window.removeEventListener('touchmove', this._drag);
    window.removeEventListener('touchend', this._dragEnd);
  };

  render() {
    const theme = autokey(themeable(this.props.theme));
    const {
      children,
      x,
      y,
      xmax,
      ymax,
      isDark
    } = this.props;

    const top = Math.round(clamp(y / ymax * 100, 0, 100));
    const left = Math.round(clamp(x / xmax * 100, 0, 100));

    return (
      <div
        {...theme('xyControlContainer')}
        onTouchStart={this._dragStart}
        onMouseDown={this._dragStart}
      >
        <div
          {...theme('xyControl', `${isDark ? 'xyControlDark' : ''}`)}
          style={{
            top: `${top}%`,
            left: `${left}%`
          }}
        />
        {children}
      </div>
    );
  }
}

export default XYControl;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import {
  matchContext as matchContextType
} from './PropTypes'

class MatchProvider extends React.Component {
  static propTypes = {
    match: PropTypes.any,
    children: PropTypes.node
  }

  static childContextTypes = {
    match: matchContextType.isRequired
  }

  constructor(props) {
    super(props)
    this.parent = props.match
    // React doesn't support a parent calling `setState` from an descendant's
    // componentWillMount, so we use an instance property to track matches
    this.matches = []
  }

  addMatch = match => {
    this.matches = this.matches.concat([match])
  }

  removeMatch = match => {
    this.matches = this.matches.splice(this.matches.indexOf(match), 1)
  }

  getChildContext() {
    return {
      match: {
        addMatch: this.addMatch,
        removeMatch: this.removeMatch,

        parent: this.parent,
        matches: this.matches,

        matchFound: () => this.matches.length > 0
      }
    }
  }

  render() {
    return this.props.children
  }
}

export default MatchProvider
<commit_msg>remove matches assignment (opposite of what we want!)<commit_after>import React, { PropTypes } from 'react'
import {
  matchContext as matchContextType
} from './PropTypes'

class MatchProvider extends React.Component {
  static propTypes = {
    match: PropTypes.any,
    children: PropTypes.node
  }

  static childContextTypes = {
    match: matchContextType.isRequired
  }

  constructor(props) {
    super(props)
    this.parent = props.match
    // React doesn't support a parent calling `setState` from an descendant's
    // componentWillMount, so we use an instance property to track matches
    this.matches = []
  }

  addMatch = match => {
    this.matches = this.matches.concat([match])
  }

  removeMatch = match => {
    this.matches.splice(this.matches.indexOf(match), 1)
  }

  getChildContext() {
    return {
      match: {
        addMatch: this.addMatch,
        removeMatch: this.removeMatch,

        parent: this.parent,
        matches: this.matches,

        matchFound: () => this.matches.length > 0
      }
    }
  }

  render() {
    return this.props.children
  }
}

export default MatchProvider
<|endoftext|>


<commit_before>import invariant from 'invariant'
import React from 'react'

import deprecateObjectProperties from './deprecateObjectProperties'
import getRouteParams from './getRouteParams'
import { isReactChildren } from './RouteUtils'
import warning from './warning'

const { array, func, object } = React.PropTypes

/**
 * A <RouterContext> renders the component tree for a given router state
 * and sets the history object and the current location in context.
 */
const RouterContext = React.createClass({

  propTypes: {
    history: object.isRequired,
    router: object.isRequired,
    location: object.isRequired,
    routes: array.isRequired,
    params: object.isRequired,
    components: array.isRequired,
    createElement: func.isRequired
  },

  getDefaultProps() {
    return {
      createElement: React.createElement
    }
  },

  childContextTypes: {
    history: object.isRequired,
    location: object.isRequired,
    router: object.isRequired
  },

  getChildContext() {
    let { router, history, location } = this.props
    if (!router) {
      warning(
        false,
        '`<RouterContext>` expects a `router` rather than a `history`'
      )

      router = {
        ...history,
        addRouteLeaveHook: history.listenBeforeLeavingRoute
      }
      delete router.listenBeforeLeavingRoute
    }

    if (__DEV__) {
      location = deprecateObjectProperties(location, '`context.location` is deprecated, please use a route component\'s `props.location` instead. If this is a deeply nested component, please refer to the strategies described in https://github.com/rackt/react-router/blob/v1.1.0/CHANGES.md#v110')
    }

    return { history, location, router }
  },

  createElement(component, props) {
    return component == null ? null : this.props.createElement(component, props)
  },

  render() {
    const { history, location, routes, params, components } = this.props
    let element = null

    if (components) {
      element = components.reduceRight((element, components, index) => {
        if (components == null)
          return element // Don't create new children; use the grandchildren.

        const route = routes[index]
        const routeParams = getRouteParams(route, params)
        const props = {
          history: deprecateObjectProperties(history, 'Accessing `props.history` is deprecated, please use a singleton `history` or `context.router`.'),
          location,
          params,
          route,
          routeParams,
          routes
        }

        if (isReactChildren(element)) {
          props.children = element
        } else if (element) {
          for (let prop in element)
            if (element.hasOwnProperty(prop))
              props[prop] = element[prop]
        }

        if (typeof components === 'object') {
          const elements = {}

          for (const key in components) {
            if (components.hasOwnProperty(key)) {
              // Pass through the key as a prop to createElement to allow
              // custom createElement functions to know which named component
              // they're rendering, for e.g. matching up to fetched data.
              elements[key] = this.createElement(components[key], {
                key, ...props
              })
            }
          }

          return elements
        }

        return this.createElement(components, props)
      }, element)
    }

    invariant(
      element === null || element === false || React.isValidElement(element),
      'The root route must render a single element'
    )

    return element
  }

})

export default RouterContext
<commit_msg>Don't require history in RouterContext<commit_after>import invariant from 'invariant'
import React from 'react'

import deprecateObjectProperties from './deprecateObjectProperties'
import getRouteParams from './getRouteParams'
import { isReactChildren } from './RouteUtils'
import warning from './warning'

const { array, func, object } = React.PropTypes

/**
 * A <RouterContext> renders the component tree for a given router state
 * and sets the history object and the current location in context.
 */
const RouterContext = React.createClass({

  propTypes: {
    history: object,
    router: object.isRequired,
    location: object.isRequired,
    routes: array.isRequired,
    params: object.isRequired,
    components: array.isRequired,
    createElement: func.isRequired
  },

  getDefaultProps() {
    return {
      createElement: React.createElement
    }
  },

  childContextTypes: {
    history: object,
    location: object.isRequired,
    router: object.isRequired
  },

  getChildContext() {
    let { router, history, location } = this.props
    if (!router) {
      warning(
        false,
        '`<RouterContext>` expects a `router` rather than a `history`'
      )

      router = {
        ...history,
        addRouteLeaveHook: history.listenBeforeLeavingRoute
      }
      delete router.listenBeforeLeavingRoute
    }

    if (__DEV__) {
      location = deprecateObjectProperties(location, '`context.location` is deprecated, please use a route component\'s `props.location` instead. If this is a deeply nested component, please refer to the strategies described in https://github.com/rackt/react-router/blob/v1.1.0/CHANGES.md#v110')
    }

    return { history, location, router }
  },

  createElement(component, props) {
    return component == null ? null : this.props.createElement(component, props)
  },

  render() {
    const { history, location, routes, params, components } = this.props
    let element = null

    if (components) {
      element = components.reduceRight((element, components, index) => {
        if (components == null)
          return element // Don't create new children; use the grandchildren.

        const route = routes[index]
        const routeParams = getRouteParams(route, params)
        const props = {
          history: history && deprecateObjectProperties(history, 'Accessing `props.history` is deprecated, please use a singleton `history` or `context.router`.'),
          location,
          params,
          route,
          routeParams,
          routes
        }

        if (isReactChildren(element)) {
          props.children = element
        } else if (element) {
          for (let prop in element)
            if (element.hasOwnProperty(prop))
              props[prop] = element[prop]
        }

        if (typeof components === 'object') {
          const elements = {}

          for (const key in components) {
            if (components.hasOwnProperty(key)) {
              // Pass through the key as a prop to createElement to allow
              // custom createElement functions to know which named component
              // they're rendering, for e.g. matching up to fetched data.
              elements[key] = this.createElement(components[key], {
                key, ...props
              })
            }
          }

          return elements
        }

        return this.createElement(components, props)
      }, element)
    }

    invariant(
      element === null || element === false || React.isValidElement(element),
      'The root route must render a single element'
    )

    return element
  }

})

export default RouterContext
<|endoftext|>


<commit_before>// RequireJS Mustache template plugin
// http://github.com/jfparadis/requirejs-mustache
//
// An alternative to https://github.com/millermedeiros/requirejs-hogan-plugin
//
// Using Mustache Logic-less templates at http://mustache.github.com
// Using and RequireJS text.js at http://requirejs.org/docs/api.html#text
// @author JF Paradis
// @version 0.0.3
//
// Released under the MIT license
//
// Usage:
//   require(['backbone', 'stache!mytemplate'], function (Backbone, mytemplate) {
//     return Backbone.View.extend({
//       initialize: function(){
//         this.render();
//       },
//       render: function(){
//         this.$el.html(mytemplate({message: 'hello'}));
//     });
//   });
//
// Configuration: (optional)
//   require.config({
//     stache: {
//       extension: '.stache' // default = '.html'
//     }
//   });

/*jslint nomen: true */
/*global define: false */

define(['text', 'mustache'], function (text, Mustache) {
    'use strict';

    var sourceMap = {},
        buildMap = {},
        buildTemplateSource = "define('{pluginName}!{moduleName}', ['mustache'], function (Mustache) { var template = '{content}'; Mustache.parse( template ); return function( view ) { return Mustache.render( template, view ); } });\n";

    return {
        version: '0.0.3',

        load: function (moduleName, parentRequire, onload, config) {
            if (buildMap[moduleName]) {
                onload(buildMap[moduleName]);

            } else {
                var ext = (config.stache && config.stache.extension) || '.html';
                var path = (config.stache && config.stache.path) || '';
                text.load(path + moduleName + ext, parentRequire, function (source) {
                    if (config.isBuild) {
                        sourceMap[moduleName] = source;
                        onload();
                    } else {
                        Mustache.parse(source);
                        buildMap[moduleName] = function( view ) {
                            return Mustache.render( source, view );
                        };
                        onload(buildMap[moduleName]);
                    }
                }, config);
            }
        },

        write: function (pluginName, moduleName, write, config) {
            var source = sourceMap[moduleName],
                content = source && text.jsEscape(source);
            if (content) {
                write.asModule(pluginName + '!' + moduleName,
                    buildTemplateSource
                    .replace('{pluginName}', pluginName)
                    .replace('{moduleName}', moduleName)
                    .replace('{content}', content));
            }
        }
    };
});<commit_msg>allow partials when built with r.js<commit_after>// RequireJS Mustache template plugin
// http://github.com/jfparadis/requirejs-mustache
//
// An alternative to https://github.com/millermedeiros/requirejs-hogan-plugin
//
// Using Mustache Logic-less templates at http://mustache.github.com
// Using and RequireJS text.js at http://requirejs.org/docs/api.html#text
// @author JF Paradis
// @version 0.0.3
//
// Released under the MIT license
//
// Usage:
//   require(['backbone', 'stache!mytemplate'], function (Backbone, mytemplate) {
//     return Backbone.View.extend({
//       initialize: function(){
//         this.render();
//       },
//       render: function(){
//         this.$el.html(mytemplate({message: 'hello'}));
//     });
//   });
//
// Configuration: (optional)
//   require.config({
//     stache: {
//       extension: '.stache' // default = '.html'
//     }
//   });

/*jslint nomen: true */
/*global define: false */

define(['text', 'mustache'], function (text, Mustache) {
    'use strict';

    var sourceMap = {},
        buildMap = {},
        buildTemplateSource = "define('{pluginName}!{moduleName}', ['mustache'], function (Mustache) { var template = '{content}'; Mustache.parse( template ); return function( view, partials ) { return Mustache.render( template, view, partials ); } });\n";

    return {
        version: '0.0.3',

        load: function (moduleName, parentRequire, onload, config) {
            if (buildMap[moduleName]) {
                onload(buildMap[moduleName]);

            } else {
                var ext = (config.stache && config.stache.extension) || '.html';
                var path = (config.stache && config.stache.path) || '';
                text.load(path + moduleName + ext, parentRequire, function (source) {
                    if (config.isBuild) {
                        sourceMap[moduleName] = source;
                        onload();
                    } else {
                        Mustache.parse(source);
                        buildMap[moduleName] = function( view ) {
                            return Mustache.render( source, view );
                        };
                        onload(buildMap[moduleName]);
                    }
                }, config);
            }
        },

        write: function (pluginName, moduleName, write, config) {
            var source = sourceMap[moduleName],
                content = source && text.jsEscape(source);
            if (content) {
                write.asModule(pluginName + '!' + moduleName,
                    buildTemplateSource
                    .replace('{pluginName}', pluginName)
                    .replace('{moduleName}', moduleName)
                    .replace('{content}', content));
            }
        }
    };
});
<|endoftext|>


<commit_before>// /* global describe, it, expect */
import React from 'react';
import sinon from 'sinon';
import { ReactWrapper, shallow, mount } from 'enzyme';
import PowerSelect from '../index';

const frameworks = ['React', 'Ember', 'Angular', 'Vue', 'Inferno'];
const countries = [
  {
    name: 'Argentina',
    code: 'ARG',
    flag: 'https://restcountries.eu/data/arg.svg',
    continent: 'South America',
  },
  {
    name: 'Brazil',
    code: 'BRA',
    flag: 'https://restcountries.eu/data/bra.svg',
    continent: 'South America',
  },
  {
    name: 'Canada',
    code: 'CAN',
    flag: 'https://restcountries.eu/data/can.svg',
    continent: 'North America',
  },
  {
    name: 'China',
    code: 'CHN',
    flag: 'https://restcountries.eu/data/chn.svg',
    continent: 'Asia',
  },
  {
    name: 'India',
    code: 'IND',
    flag: 'https://restcountries.eu/data/ind.svg',
    continent: 'Asia',
  },
];

const renderPowerSelect = props => {
  let selected;
  let handleChange = () => {};
  return mount(
    <PowerSelect
      options={countries}
      selected={selected}
      optionLabelPath="name"
      onChange={handleChange}
      {...props}
    />
  );
};

const renderPowerSelectWithStringOptions = props => {
  let selected;
  let handleChange = () => {};
  return mount(
    <PowerSelect options={frameworks} selected={selected} onChange={handleChange} {...props} />
  );
};

describe('<PowerSelect />', () => {
  it('should render the container tag', () => {
    const wrapper = renderPowerSelectWithStringOptions();
    expect(wrapper.find('.PowerSelect').length).toBe(1);
    expect(wrapper.find('.PowerSelect__Trigger').length).toBe(1);
    expect(wrapper.find('.PowerSelect__TriggerLabel').length).toBe(1);
    expect(wrapper.find('.PowerSelect__Clear').length).toBe(1);
    expect(wrapper.find('.PowerSelect__TriggerStatus').length).toBe(1);
  });

  it('should preselect, when `selected` is passed', () => {
    const wrapper = renderPowerSelectWithStringOptions({
      selected: frameworks[2],
    });
    expect(wrapper.find('.PowerSelect__TriggerLabel').text()).toBe(frameworks[2]);
  });

  it('should preselect, when `selected` is passed even with object option', () => {
    const wrapper = renderPowerSelect({
      selected: countries[2],
    });
    expect(wrapper.find('.PowerSelect__TriggerLabel').text()).toBe(countries[2].name);
  });

  it('should not render close button, when `showClear` is false', () => {
    const wrapper = renderPowerSelect({
      showClear: false,
    });
    expect(wrapper.find('.PowerSelect__Clear').length).toBe(0);
  });

  it('should clear the selected option, when the clear button is clicked', () => {
    const handleChange = sinon.spy();
    const wrapper = renderPowerSelect({
      selected: countries[2],
      onChange: handleChange,
    });

    expect(wrapper.find('.PowerSelect__TriggerLabel').text()).toBe('Canada');
    wrapper.find('.PowerSelect__Clear').simulate('click');
    expect(handleChange.calledOnce).toBeTruthy();

    let args = handleChange.getCall(0).args[0];
    expect(args.option).toBe(undefined);
    expect(args.select).toBeTruthy();
    expect(args.select.searchTerm).toBe(null);

    wrapper.setProps({
      selected: args.option,
    });
    expect(wrapper.find('.PowerSelect__TriggerLabel').text()).toBeFalsy();
  });

  it.only('should delegate `className` to the container, tether & menu', () => {
    const wrapper = renderPowerSelect({
      className: 'TestPowerSelect',
    });
    expect(wrapper.find('.PowerSelect').hasClass('TestPowerSelect')).toBeTruthy();

    wrapper.find('.PowerSelect').simulate('click');
    var portal = new ReactWrapper(wrapper.instance().select.dropdownRef, true);

    expect(portal.find('.PowerSelect__Menu').hasClass('TestPowerSelect__Menu')).toBeTruthy();
    expect(document.querySelectorAll('.PowerSelect__Tether.TestPowerSelect__Tether').length).toBe(
      1
    );
  });

  it('should delegate `tabIndex` when passed');

  it('should display placeholder when passed');

  it('should render `triggerLHSComponent` when passed');

  it('should render `triggerRHSComponent` when passed');

  it('should be disabled, when `disabled` prop is set');

  it('should disable search when `searchEnabled` is false');

  it('should toggle the dropdown on click', () => {
    const wrapper = renderPowerSelect({
      selected: countries[2],
    });

    var portal = new ReactWrapper(wrapper.instance().select.dropdownRef, true);
    expect(portal.exists()).toBeFalsy();
    expect(wrapper.find('.PowerSelect').hasClass('PowerSelect--open')).toBeFalsy();

    wrapper.find('.PowerSelect').simulate('click');

    expect(wrapper.find('.PowerSelect').hasClass('PowerSelect--open')).toBeTruthy();
    portal = new ReactWrapper(wrapper.instance().select.dropdownRef, true);
    expect(portal.exists()).toBeTruthy();
    expect(document.querySelectorAll('.PowerSelect__Tether').length).toBe(1);
  });

  it('should close the dropdown on document click');

  it('should highlight the below option on down arrow press');

  it('should highlight the above option on up arrow press');

  it('should highlight the first option on down arrow press with last option highlighted');

  it('should highlight the last option on up arrow press with first option highlighted');

  it('should highlight the selected option when opened');

  it('should make the highlighted option within viewport');

  it('should select the option when click');

  it('should select the option on tab & focusout');

  it('should select the option on enter & focusin');

  it('should close dropdown on escape press');

  it('should filter the options based on the searchTerm');

  it('should use custom `matcher` func when provided');

  it('should reset the filter when the dropdown is closed');

  it('should trigger `onChange` when an option is selected or cleared');

  it('should trigger `onFocus` when the powerselect is focused');

  it('should trigger `onBlur` when the powerselect is blurred');

  it('should trigger `onOpen` when the powerselect is opened');

  it('should trigger `onClose` when the powerselect is closed');

  it('should trigger `onKeyDown` when any key is pressed');

  it('should trigger `onSearchInputChange` when searchInput changes');

  it('should render the `optionComponent`, when provided');

  it('should render the `selectedOptionComponent`, when provided');

  it('should render the `beforeOptionsComponent`, when provided');

  it('should render the `afterOptionsComponent`, when provided');

  it('should disable & prevent clicks & highlights when the option is disabled');

  it('should prevent max call limit recursion, when all options are disabled');
});
<commit_msg>More tests with powerselect pageobject<commit_after>// /* global describe, it, expect */
import React from 'react';
import TestUtils from 'react-dom/test-utils';
import sinon from 'sinon';
import { ReactWrapper, shallow, mount } from 'enzyme';
import PowerSelect from '../index';

const frameworks = ['React', 'Ember', 'Angular', 'Vue', 'Inferno'];
const countries = [
  {
    name: 'Argentina',
    code: 'ARG',
    flag: 'https://restcountries.eu/data/arg.svg',
    continent: 'South America',
  },
  {
    name: 'Brazil',
    code: 'BRA',
    flag: 'https://restcountries.eu/data/bra.svg',
    continent: 'South America',
  },
  {
    name: 'Canada',
    code: 'CAN',
    flag: 'https://restcountries.eu/data/can.svg',
    continent: 'North America',
  },
  {
    name: 'China',
    code: 'CHN',
    flag: 'https://restcountries.eu/data/chn.svg',
    continent: 'Asia',
  },
  {
    name: 'India',
    code: 'IND',
    flag: 'https://restcountries.eu/data/ind.svg',
    continent: 'Asia',
  },
];

class PowerSelectPageObject {
  handleChange = sinon.spy();

  renderWithProps(props) {
    let selected;
    let container;
    if (!this.container) {
      container = this.container = document.createElement('div');
      document.body.appendChild(container);
    }

    let mountedComponent = (this.mountedComponent = mount(
      <PowerSelect
        options={countries}
        selected={selected}
        optionLabelPath="name"
        onChange={this.handleChange}
        {...props}
      />,
      {
        attachTo: container,
      }
    ));
    return mountedComponent;
  }

  unmount() {
    if (this.mountedComponent) {
      this.mountedComponent.detach();
    }
  }

  get portal() {
    return new ReactWrapper(this.mountedComponent.instance().select.dropdownRef, true);
  }

  get isOpened() {
    let wrapper = this.mountedComponent;
    let hasOpenClass = wrapper.find('.PowerSelect').hasClass('PowerSelect--open');
    let isDropdownVisible = this.portal.exists();

    return isDropdownVisible && hasOpenClass;
  }

  triggerContainerClick() {
    this.mountedComponent.find('.PowerSelect').simulate('click');
  }
}

describe('<PowerSelect />', () => {
  let powerselect;
  beforeEach(() => {
    powerselect = new PowerSelectPageObject();
  });

  afterEach(() => {
    powerselect.unmount();
  });

  it('should render the container tag', () => {
    const wrapper = powerselect.renderWithProps({
      options: frameworks,
    });
    expect(wrapper.find('.PowerSelect').length).toBe(1);
    expect(wrapper.find('.PowerSelect__Trigger').length).toBe(1);
    expect(wrapper.find('.PowerSelect__TriggerLabel').length).toBe(1);
    expect(wrapper.find('.PowerSelect__Clear').length).toBe(1);
    expect(wrapper.find('.PowerSelect__TriggerStatus').length).toBe(1);
  });

  it('should preselect, when `selected` is passed', () => {
    let selectedOption = frameworks[2];
    const wrapper = powerselect.renderWithProps({
      options: frameworks,
      selected: selectedOption,
    });
    expect(wrapper.find('.PowerSelect__TriggerLabel').text()).toBe(selectedOption);
  });

  it('should preselect, when `selected` is passed even with object option', () => {
    let selectedOption = countries[2];
    const wrapper = powerselect.renderWithProps({
      selected: selectedOption,
    });
    expect(wrapper.find('.PowerSelect__TriggerLabel').text()).toBe(selectedOption.name);
  });

  it('should not render close button, when `showClear` is false', () => {
    const wrapper = powerselect.renderWithProps({
      showClear: false,
    });
    expect(wrapper.find('.PowerSelect__Clear').length).toBe(0);
  });

  it('should clear the selected option, when the clear button is clicked', () => {
    const wrapper = powerselect.renderWithProps({
      selected: countries[2],
    });

    expect(wrapper.find('.PowerSelect__TriggerLabel').text()).toBe('Canada');
    wrapper.find('.PowerSelect__Clear').simulate('click');
    expect(powerselect.handleChange.calledOnce).toBeTruthy();

    let args = powerselect.handleChange.getCall(0).args[0];
    expect(args.option).toBe(undefined);
    expect(args.select).toBeTruthy();
    expect(args.select.searchTerm).toBe(null);

    wrapper.setProps({
      selected: args.option,
    });
    expect(wrapper.find('.PowerSelect__TriggerLabel').text()).toBeFalsy();
  });

  it('should delegate `className` to the container, tether & menu', () => {
    const wrapper = powerselect.renderWithProps({
      className: 'TestPowerSelect',
    });
    expect(wrapper.find('.PowerSelect').hasClass('TestPowerSelect')).toBeTruthy();

    powerselect.triggerContainerClick();
    expect(
      powerselect.portal.find('.PowerSelect__Menu').hasClass('TestPowerSelect__Menu')
    ).toBeTruthy();
    expect(document.querySelectorAll('.PowerSelect__Tether.TestPowerSelect__Tether').length).toBe(
      1
    );
  });

  it('should delegate `tabIndex` when passed', () => {
    const tabIndex = 2;
    const wrapper = powerselect.renderWithProps({ tabIndex });
    expect(wrapper.find('.PowerSelect').prop('tabIndex')).toBe(tabIndex);
  });

  it('should display placeholder when passed', () => {
    const placeholder = 'Please select a country';
    const wrapper = powerselect.renderWithProps({ placeholder });
    expect(wrapper.find('.PowerSelect__Placeholder').exists()).toBeTruthy();
    expect(wrapper.find('.PowerSelect__Placeholder').text()).toBe(placeholder);

    wrapper.setProps({ selected: countries[2] });
    expect(wrapper.find('.PowerSelect__Placeholder').exists()).toBeFalsy();
  });

  it('should render `triggerLHSComponent` when passed', () => {
    const SearchIcon = <i className="icon-search" />;
    const TriggerLHSComponent = () => SearchIcon;
    const wrapper = powerselect.renderWithProps({
      triggerLHSComponent: TriggerLHSComponent,
    });

    expect(wrapper.contains(SearchIcon)).toBeTruthy();
    expect(wrapper.find('.PowerSelect__Trigger__LHS').exists()).toBeTruthy();
  });

  it('should render `triggerRHSComponent` when passed', () => {
    const SearchIcon = <i className="icon-search" />;
    const TriggerRHSComponent = () => SearchIcon;
    const wrapper = powerselect.renderWithProps({
      triggerRHSComponent: TriggerRHSComponent,
    });

    expect(wrapper.contains(SearchIcon)).toBeTruthy();
    expect(wrapper.find('.PowerSelect__Trigger__RHS').exists()).toBeTruthy();
  });

  it('should be disabled, when `disabled` prop is set', () => {
    const wrapper = powerselect.renderWithProps({
      disabled: true,
    });

    expect(wrapper.find('.PowerSelect').hasClass('PowerSelect--disabled')).toBeTruthy();
    powerselect.triggerContainerClick();
    expect(powerselect.isOpened).toBeFalsy();
  });

  it('should disable search when `searchEnabled` is false', () => {
    const wrapper = powerselect.renderWithProps();
    powerselect.triggerContainerClick();
    expect(powerselect.portal.find('.PowerSelect__SearchInput').exists()).toBeTruthy();

    wrapper.setProps({
      searchEnabled: false,
    });

    expect(powerselect.portal.find('.PowerSelect__SearchInput').exists()).toBeFalsy();
  });

  it('should toggle the dropdown on click', () => {
    const wrapper = powerselect.renderWithProps({
      selected: countries[2],
    });

    expect(powerselect.isOpened).toBeFalsy();
    powerselect.triggerContainerClick();
    expect(powerselect.isOpened).toBeTruthy();
    powerselect.triggerContainerClick();
    expect(powerselect.isOpened).toBeFalsy();
  });

  it('should close the dropdown on document click', () => {
    const map = {};
    document.addEventListener = jest.fn((event, cb) => {
      map[event] = cb;
    });

    const wrapper = powerselect.renderWithProps();

    powerselect.triggerContainerClick();
    expect(powerselect.isOpened).toBeTruthy();

    // Should re-check this
    map.click({
      target: {
        closest: function(selector) {
          return false;
        },
      },
    });
    expect(powerselect.isOpened).toBeFalsy();
  });

  it('should highlight the below option on down arrow press');

  it('should highlight the above option on up arrow press');

  it('should highlight the first option on down arrow press with last option highlighted');

  it('should highlight the last option on up arrow press with first option highlighted');

  it('should highlight the selected option when opened');

  it('should make the highlighted option within viewport');

  it('should select the option when click');

  it('should select the option on tab & focusout');

  it('should select the option on enter & focusin');

  it('should close dropdown on escape press');

  it('should filter the options based on the searchTerm');

  it('should use custom `matcher` func when provided');

  it('should reset the filter when the dropdown is closed');

  it('should trigger `onChange` when an option is selected or cleared');

  it('should trigger `onFocus` when the powerselect is focused');

  it('should trigger `onBlur` when the powerselect is blurred');

  it('should trigger `onOpen` when the powerselect is opened');

  it('should trigger `onClose` when the powerselect is closed');

  it('should trigger `onKeyDown` when any key is pressed');

  it('should trigger `onSearchInputChange` when searchInput changes');

  it('should render the `optionComponent`, when provided');

  it('should render the `selectedOptionComponent`, when provided');

  it('should render the `beforeOptionsComponent`, when provided');

  it('should render the `afterOptionsComponent`, when provided');

  it('should disable & prevent clicks & highlights when the option is disabled');

  it('should prevent max call limit recursion, when all options are disabled');
});
<|endoftext|>


<commit_before>import React from 'react';
import Dropzone from 'react-dropzone';
import { connect } from 'react-redux'
import { Field, reduxForm, reset } from 'redux-form'
import TextField from 'material-ui/TextField'
import { Card, CardActions, CardHeader, CardText } from 'material-ui/Card'
import FlatButton from 'material-ui/FlatButton'
import FontIcon from 'material-ui/FontIcon'

import { cardSpace } from 'lib/styles'
import { Row, Col } from 'react-flexbox-grid/lib/index'

import Immutable from 'immutable'
import { gotoScreen } from 'store/screenActions'
import { loadAccountsList, createAccount } from 'store/accountActions'
import { required, minLength, passwordMatch } from 'lib/validators'
import log from 'loglevel'
import AccountShow from '../show'

const renderFileField = ({ input, name, meta: { touched, error } }) => (

    <Dropzone rejectStyle name={name} onDrop={( filesToUpload, e ) => input.onChange(filesToUpload)}>
        <FlatButton label="Select Wallet File..."
                            icon={<FontIcon className="fa fa-briefcase" />}/>
    </Dropzone>
    {touched && error &&
        {error}}

)

const Render = ({account, submitSucceeded, handleSubmit, onDrop, pristine, reset, submitting, cancel}) => {

    return (
        <Card style={cardSpace}>
            <CardHeader
                title='Import Wallet'
                actAsExpander={false}
                showExpandableButton={false}
            />

            <CardText expandable={submitSucceeded}>
                <form onSubmit={handleSubmit}>
                    <Field  name="wallet"
                            component={renderFileField} />
                    <FlatButton label="Submit" type="submit"
                                disabled={pristine || submitting } />
                </form>
            </CardText>
            <CardText expandable={!submitSucceeded}>
                 <AccountShow key={(account===undefined) ? undefined : account.get('id')} account={account}/>
                 <FlatButton label="Done"
                            onClick={cancel}
                            icon={<FontIcon className="fa fa-home" />}/>
            </CardText>
            <CardActions>
                <FlatButton label="Cancel"
                            onClick={cancel}
                            icon={<FontIcon className="fa fa-ban" />}/>
            </CardActions>
        </Card>
        );
}

const ImportAccountForm = reduxForm({
    form: 'importjson',
    fields: ['wallet']
})(Render);

const ImportAccount = connect(
    (state, ownProps) => {
        console.log(state)
        return {
            account: state.accounts.get('accounts', Immutable.List()).last()
        }
    },
    (dispatch, ownProps) => {
        return {
            onDrop: data => {
                console.log(data)
            },
            onSubmit: data => {
                return new Promise((resolve, reject) => {
                    dispatch(createAccount(data.name, data.password))
                        .then((response) => {
                            resolve(response);
                        });
                    });
            },
            cancel: () => {
                dispatch(gotoScreen('home'))
            }
        }
    }
)(ImportAccountForm);

export default ImportAccount;<commit_msg>accounts/add/importjson.js: file upload without decryption<commit_after>import React from 'react';
import Dropzone from 'react-dropzone';
import { connect } from 'react-redux'
import { Field, reduxForm, reset } from 'redux-form'
import TextField from 'material-ui/TextField'
import { Card, CardActions, CardHeader, CardText } from 'material-ui/Card'
import FlatButton from 'material-ui/FlatButton'
import FontIcon from 'material-ui/FontIcon'

import { cardSpace } from 'lib/styles'
import { Row, Col } from 'react-flexbox-grid/lib/index'

import Immutable from 'immutable'
import { gotoScreen } from 'store/screenActions'
import { loadAccountsList, createAccount } from 'store/accountActions'
import { required, minLength, passwordMatch } from 'lib/validators'
import log from 'loglevel'
import AccountShow from '../show'

const renderFileField = ({ input, name, meta: { touched, error } }) => (

    <Dropzone rejectStyle multiple="false" accept="application/json" name={name} onDrop={( filesToUpload, e ) => input.onChange(filesToUpload)}>
        <FlatButton label="Select Wallet File..."
                            icon={<FontIcon className="fa fa-briefcase" />}/>
    </Dropzone>
    {touched && error && {error}}

)

const Render = ({account, submitSucceeded, handleSubmit, onDrop, pristine, reset, submitting, cancel}) => {

    return (
        <Card style={cardSpace}>
            <CardHeader
                title='Import Wallet'
                actAsExpander={false}
                showExpandableButton={false}
            />

            <CardText expandable={submitSucceeded}>
                <form onSubmit={handleSubmit}>
                    <Field  name="wallet"
                            component={renderFileField} />
                    <FlatButton label="Submit" type="submit"
                                disabled={pristine || submitting } />
                </form>
            </CardText>
            <CardText expandable={!submitSucceeded}>
                 <AccountShow key={(account===undefined) ? undefined : account.get('id')} account={account}/>
                 <FlatButton label="Done"
                            onClick={cancel}
                            icon={<FontIcon className="fa fa-home" />}/>
            </CardText>
            <CardActions>
                <FlatButton label="Cancel"
                            onClick={cancel}
                            icon={<FontIcon className="fa fa-ban" />}/>
            </CardActions>
        </Card>
        );
}

const ImportAccountForm = reduxForm({
    form: 'importjson',
    fields: ['wallet']
})(Render);

const ImportAccount = connect(
    (state, ownProps) => {
        console.log(state)
        return {
            account: state.accounts.get('accounts', Immutable.List()).last()
        }
    },
    (dispatch, ownProps) => {
        return {
            onSubmit: data => {
                console.log(data)
            },
            cancel: () => {
                dispatch(gotoScreen('home'))
            }
        }
    }
)(ImportAccountForm);

export default ImportAccount;<|endoftext|>


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

module.exports = {

	source_dir : "project", // `source_dir` is the directory where all your source files are.
	output_dir: "deploy", // `output_dir` is the directory you want to compile your static site to.

	template_engine : "swig", // the npm package name of the template engine, only engines supported by consolidate.js will work
	template_dir : "project/templates", // Only relevant if using swig : The directory where all your templates are.

	/*
		Literal regexes here. Statix won't include anything, unless it matches an `include_pattern` and also does
		not match an `exclude_pattern`. Checks against the full path, i.e. /Users/your.name/some/dir/site/blah.html
	*/

	include_patterns : [
		/^(.*)$/
	],

	exclude_patterns : [
		/^(.*)(base\.html{1})$/,
		/^(.*)(\/templates{1})(.*)$/
	],

	/*
		An array of the pages to be rendered with the template engine.

		`output` is where your page will eventually live, in the static version of the site. I.e. "{output_dir}/{page.output}"

		`source` is where your template lives. I.e. "{source_dir}{page.source}"

		`data` is an object of variables you want to pass through to the template when it gets rendered.
	*/

	pages : [
		{
			output : "index.html",
			source : "templates/home.html",
			data : {}
		},

		{
			output : "404.html",
			source : "templates/404.html",
			data : {}
		},

		{
			output : "500.html",
			source : "templates/500.html",
			data : {}
		}

	],

	/*
		`global_data` is an object that gets passed to all pages. Note, if you set `global_data.someProp` to something
		and also have `page.data.someProp`, the latter will take precedence.
	*/

	global_data: {

		settings : {
			TEMPLATE_DEBUG : true
		},

		STATIC_URL : "static/"
	},

	/*
		Like `global_data`, but `build_data` only gets passed to the renderer when you build, not when viewing locally through the webserver.
		`build_data` properties take precedence over `global_data` properties.
	*/

	build_data : {

		settings : {
			TEMPLATE_DEBUG: false
		}

	},

	// Misc. things to pass to express for the local web server, currently the only value used is port.
	express : {
		port: "8000"
	},

	/*
		If you need to process some things before you're ready to generate the pages (either through the web server or compilation),
		you can use this `ready` method. Common use case, you need to grab a bunch of data from a database, and are using asynch i/o
		Statix, does nothing until the `callback` passed to this method is called, so once you are done with everything you need to do,
		simply call `callback();`
	*/

	ready : function (callback) {
		callback();
	},

	/*
		Statix gives you a hook to do whatever you want before the build actually happens. You can use this method to minify js/css,
		compile scss stylesheets, etc. Just be sure to invoke the `done()` function when you are ready for Statix to do it's thing.
	*/

	preBuild : function (done) {
		done();
	},

	/*
		Just like `preBuild()` but this method gets called after Statix has generated the static site. You can use this to
		cleanup some files, git commit/push, or whatever you feel like. Just be sure to invoke the `done()` function afterwards.
	*/
	postBuild : function (done) {

		function moveFiles(from, to) {

			from = (from[0] == "/") ? from : process.cwd() + "/" + from;
			to = (to[0] == "/") ? to : process.cwd() + "/" + to;

			var fromStats = fs.statSync(from);
			var fromName = from.substr(from.lastIndexOf("/"));

			if(fromStats.isDirectory()){

				if(!path.existsSync(to)){
					console.log(to);
					fs.mkdirSync(to);
				}

				var files = fs.readdirSync(from);
				for(var i = 0; i < files.length; i ++){
					moveFiles(from + "/" + files[i], to + "/" + files[i]);
				}

				fs.rmdirSync(from);
			}

			else{
				fs.writeFileSync(to, fs.readFileSync(from, 'utf-8'));
				fs.unlinkSync(from);
			}
		}

		moveFiles.bind(this);
		moveFiles(this.output_dir + "/static-local", this.output_dir);

		done();
	}

}<commit_msg>Statix now takes a port as `statix server -p 3000` vs specifying it in the statix.js file.<commit_after>var fs = require("fs");
var path = require("path");

module.exports = {

	source_dir : "project", // `source_dir` is the directory where all your source files are.
	output_dir: "deploy", // `output_dir` is the directory you want to compile your static site to.

	template_engine : "swig", // the npm package name of the template engine, only engines supported by consolidate.js will work
	template_dir : "project/templates", // Only relevant if using swig : The directory where all your templates are.

	/*
		Literal regexes here. Statix won't include anything, unless it matches an `include_pattern` and also does
		not match an `exclude_pattern`. Checks against the full path, i.e. /Users/your.name/some/dir/site/blah.html
	*/

	include_patterns : [
		/^(.*)$/
	],

	exclude_patterns : [
		/^(.*)(base\.html{1})$/,
		/^(.*)(\/templates{1})(.*)$/
	],

	/*
		An array of the pages to be rendered with the template engine.

		`output` is where your page will eventually live, in the static version of the site. I.e. "{output_dir}/{page.output}"

		`source` is where your template lives. I.e. "{source_dir}{page.source}"

		`data` is an object of variables you want to pass through to the template when it gets rendered.
	*/

	pages : [
		{
			output : "index.html",
			source : "templates/home.html",
			data : {}
		},

		{
			output : "404.html",
			source : "templates/404.html",
			data : {}
		},

		{
			output : "500.html",
			source : "templates/500.html",
			data : {}
		}

	],

	/*
		`global_data` is an object that gets passed to all pages. Note, if you set `global_data.someProp` to something
		and also have `page.data.someProp`, the latter will take precedence.
	*/

	global_data: {

		settings : {
			TEMPLATE_DEBUG : true
		},

		STATIC_URL : "static/"
	},

	/*
		Like `global_data`, but `build_data` only gets passed to the renderer when you build, not when viewing locally through the webserver.
		`build_data` properties take precedence over `global_data` properties.
	*/

	build_data : {

		settings : {
			TEMPLATE_DEBUG: false
		}

	},

	/*
		If you need to process some things before you're ready to generate the pages (either through the web server or compilation),
		you can use this `ready` method. Common use case, you need to grab a bunch of data from a database, and are using asynch i/o
		Statix, does nothing until the `callback` passed to this method is called, so once you are done with everything you need to do,
		simply call `callback();`
	*/

	ready : function (callback) {
		callback();
	},

	/*
		Statix gives you a hook to do whatever you want before the build actually happens. You can use this method to minify js/css,
		compile scss stylesheets, etc. Just be sure to invoke the `done()` function when you are ready for Statix to do it's thing.
	*/

	preBuild : function (done) {
		done();
	},

	/*
		Just like `preBuild()` but this method gets called after Statix has generated the static site. You can use this to
		cleanup some files, git commit/push, or whatever you feel like. Just be sure to invoke the `done()` function afterwards.
	*/
	postBuild : function (done) {

		function moveFiles(from, to) {

			from = (from[0] == "/") ? from : process.cwd() + "/" + from;
			to = (to[0] == "/") ? to : process.cwd() + "/" + to;

			var fromStats = fs.statSync(from);
			var fromName = from.substr(from.lastIndexOf("/"));

			if(fromStats.isDirectory()){

				if(!path.existsSync(to)){
					console.log(to);
					fs.mkdirSync(to);
				}

				var files = fs.readdirSync(from);
				for(var i = 0; i < files.length; i ++){
					moveFiles(from + "/" + files[i], to + "/" + files[i]);
				}

				fs.rmdirSync(from);
			}

			else{
				fs.writeFileSync(to, fs.readFileSync(from, 'utf-8'));
				fs.unlinkSync(from);
			}
		}

		moveFiles.bind(this);
		moveFiles(this.output_dir + "/static-local", this.output_dir);

		done();
	}

}<|endoftext|>


<commit_before>import {Component, linkEvent} from 'inferno';

const setCurrent = ({ instance, index }, e) => {
  e.stopPropagation();
  instance.setState({ current: index });
  ga('send', 'event', 'Differences', instance.state.list[instance.state.current].name);
};

export default class ContentAccordion extends Component {
  constructor() {
    super();
    this.state = {
      current: 0,
      list: [
        {
          name: 'Differences from React',
          description: [
            "Inferno is much smaller in size, ~8kb vs 45kb gzip.",
            "Inferno is considerably faster than React. This doesn't apply to only benchmarks, but real-world applications that companies have converted to Inferno from React.",
            "Inferno doesn't have a fully synthetic event system like React does, instead opting to only delegate certain events (such as onClick).",
            "Inferno doesn't support React Native. Inferno was only designed for the browser/server with the DOM in mind.",
            "Inferno doesn't support string refs – although this can be enabled using inferno-compat. We don't recommend using them, they are the source of many memory leaks and performance issues in real-world apps.",
            "Inferno provides lifecycle events on stateless components. This is a major win for people who prefer lightweight components rather than ES2015 classes.",
            "Inferno is able to use the React Dev Tools extensions for Chrome/Firefox/etc to provide the same level of debugging experience to users of Inferno via `inferno-devtools`"
          ]
        },
        {
          name: 'Differences from Preact',
          description: [
            "Inferno is larger in size, ~8kb vs 3kb gzip.",
            "Inferno has a partial synthetic event system, resulting in better performance via delegation of certain events.",
            "Inferno is much faster than Preact in rendering, updating and removing elements from the DOM.",
            "Inferno fully supports controlled components for input/select/textarea elements. This prevents lots of edgecases where the virtual DOM is not the source of truth (it should always be). Preact pushes the source of truth to the DOM itself.",
            "Inferno provides lifecycle events on stateless components. This is a major win for people who prefer lightweight components rather than ES2015 classes.",
          ]
        }
      ]
    };
  }

  render() {
    return (

          {this.state.list.map((item, index) => {
            return

                {item.name}

;
          })}

          {this.state.list[this.state.current].description.map((item) => {
            return
{item}
;
          })}

    );
  }
}
<commit_msg>Update ContentAccordion.js<commit_after>import {Component, linkEvent} from 'inferno';

const setCurrent = ({ instance, index }, e) => {
  e.stopPropagation();
  instance.setState({ current: index });
  ga('send', 'event', 'Differences', instance.state.list[instance.state.current].name);
};

export default class ContentAccordion extends Component {
  constructor() {
    super();
    this.state = {
      current: 0,
      list: [
        {
          name: 'Differences from React',
          description: [
            "Inferno is much smaller in size, ~8kb vs ~30kb gzip.",
            "Inferno is considerably faster than React. This doesn't apply to only benchmarks, but real-world applications that companies have converted to Inferno from React.",
            "Inferno doesn't have a fully synthetic event system like React does, instead opting to only delegate certain events (such as onClick).",
            "Inferno doesn't support React Native. Inferno was only designed for the browser/server with the DOM in mind.",
            "Inferno doesn't support string refs – although this can be enabled using inferno-compat. We don't recommend using them, they are the source of many memory leaks and performance issues in real-world apps.",
            "Inferno provides lifecycle events on stateless components. This is a major win for people who prefer lightweight components rather than ES2015 classes.",
            "Inferno is able to use the React Dev Tools extensions for Chrome/Firefox/etc to provide the same level of debugging experience to users of Inferno via `inferno-devtools`"
          ]
        },
        {
          name: 'Differences from Preact',
          description: [
            "Inferno is larger in size, ~8kb vs 3kb gzip.",
            "Inferno has a partial synthetic event system, resulting in better performance via delegation of certain events.",
            "Inferno is much faster than Preact in rendering, updating and removing elements from the DOM.",
            "Inferno fully supports controlled components for input/select/textarea elements. This prevents lots of edgecases where the virtual DOM is not the source of truth (it should always be). Preact pushes the source of truth to the DOM itself.",
            "Inferno provides lifecycle events on stateless components. This is a major win for people who prefer lightweight components rather than ES2015 classes.",
          ]
        }
      ]
    };
  }

  render() {
    return (

          {this.state.list.map((item, index) => {
            return

                {item.name}

;
          })}

          {this.state.list[this.state.current].description.map((item) => {
            return
{item}
;
          })}

    );
  }
}
<|endoftext|>