<commit_before>// Stacked Graph Type Javascript
//
//
var dataChart = []
var i;
	function getMetrics(metrics) {
		dataChart = new Array(metrics.length)
		$.each(metrics, function (i, d) {

			feed = metricURL(gon.metrics[i].feed, gon.start, gon.stop, gon.step)
			$.getJSON(feed, function (data) {
				if (data.error) {
					renderError("chart", "endpoint returned an error", data.error);

					stopUpdates();
					return false
				}
				if (data.length == 0) {
					renderError("chart", "no data returned from endpoint",feed);
					stopUpdates();
					return false
				}
				i = $.map(gon.metrics,function(d){ return d.metric}).indexOf(d)

				dataChart[i] = {data: data, name: d}
				flagComplete()
			})
		})
	}

complete = 0

function flagComplete() {
	complete++;
	if (complete == metrics.length) {
		renderStacked(dataChart)
		unrenderWaiting()
	}
}
var slider;
function isRight(d) {
	return right_id.indexOf(gon.metrics[d].metric) >= 0
}

function noRight() {
	return clean(right_id, "").length == 0
}
function renderStacked(data) {

	var palette = new Rickshaw.Color.Palette({
		scheme: "munin"
	})

	colours = []

	min = Number.MAX_VALUE; max = Number.MIN_VALUE;

	left_range = [min,max]
	right_range = [min,max]
	for (n = 0; n < data.length; n++) {
		min = Number.MAX_VALUE; max = Number.MIN_VALUE;
		for (i = 0; i < data[n].data.length; i++) {
			min = Math.min(min, data[n].data[i].y)
			max = Math.max(max, data[n].data[i].y)
		}
		if (isRight(n)) {
			right_range = [ Math.min(min, right_range[0]) , Math.max(max, right_range[1]) ]
		} else {
			left_range = [ Math.min(min, left_range[0]) , Math.max(max, left_range[1]) ]
		}
	}

	if (!noRight()) { right_scale = d3.scale.linear().domain(right_range) };//.range(right_range); )
	left_scale = d3.scale.linear().domain(left_range);//.range(left_range);

	// Push scales and their metrics into a rickshaw-eatable array
	series = []
	for (n = 0; n < data.length; n++) {
		colours[n] = palette.color()
		scale = left_scale
		if (isRight(n)) { scale = right_scale}
		if (data[n].name.indexOf("uom:c") != -1 ) { inter = "step"} else { inter = "cardinal" }
		series.push({
			color: colours[n],
			data: data[n].data,
			name: data[n].name,
			interpolation: inter,
			scale: scale
		})
	}

	// Finally, make the chart
	graph = new Rickshaw.Graph({
		element: document.querySelector("#chart"),
		width: 700,
		height: 300,
		renderer: 'line',
		series: series
	});

	// Left Y-Axis will always be around
	left_axis = new Rickshaw.Graph.Axis.Y.Scaled({
		element: document.getElementById('y_axis'),
		graph: graph,
		orientation: 'left',
		tickFormat: Rickshaw.Fixtures.Number.formatBase1024KMGTP_round,
		scale: left_scale
	});

	// Right Y-Axis will sometimes be here
	if (!noRight()) {
	right_axis = new Rickshaw.Graph.Axis.Y.Scaled({
		element: document.getElementById('y_axis_right'),
		graph: graph,
		grid: false,
		orientation: 'right',
		tickFormat: Rickshaw.Fixtures.Number.formatBase1024KMGTP_round,
		scale: right_scale
	})
	};

	// One X-axis for time
	new Rickshaw.Graph.Axis.Time({
		graph: graph,
		timeFixture: new Rickshaw.Fixtures.Time.Precise.Local()
	});

	/////
	dynamicWidth(graph);
	graph.render();

	// X-axis slider for zooming
	slider = new Rickshaw.Graph.RangeSlider.Preview({
		graph: graph,
	        height: 30,
		element: $('#slider')[0]
	});

	// Custom Legend
	var legend = document.querySelector("#legend-dual")

	function divme(className, inner) {
		var x = document.createElement("div")
		x.className = className
		x.innerHTML = inner
		return x
	}

	function generate_legend(date, v) {
		legend.innerHTML = ""

		date = divme("legend-date", date)

		left = [];
		right = [];

		for (var i = 0; i < v.length; i++) {
			d = v[i]

			label = divme("legend_label", "")
			swatch = divme("legend-swatch","")
			swatch.style.backgroundColor = d[2]
			metric = divme("legend-metric",d[0])
			data = divme("legend-data",d[1])

			label.appendChild(swatch)
			label.appendChild(metric)
			label.appendChild(data)

			if (isRight(i)) {
				icon = "icon-arrow-left"
				el = right
				tip = "Jump metric to the left axis"
				ref = left_links[i]
			} else {
				icon = "icon-arrow-right"
				el = left
				tip = "Step metric to the right axis"
				ref = right_links[i]
			}

			//link = " "+ "" +""
			link = "  "
			shuffle = divme("legend-shuffle",link)
			label.appendChild(shuffle)
			el.push(label)

		}

		legend.appendChild(date)

		a = divme("legend-indent","")
		for (var i = 0; i < left.length; i++) {
			a.appendChild(left[i])
		}
		legend.appendChild(a)

		b = divme("legend-indent","")
		for (var i = 0; i < right.length; i++) {
			b.appendChild(right[i])
		}
		legend.appendChild(b)

	}

	// Initial Labels with no values
	fake_label = []
	for (i = 0; i < metrics.length; i++) {
		fake_label.push([metrics[i], "", colours[i]])
	}
	generate_legend(" ", fake_label)

	// Overload HoverDetail so it populates our legend dynamically
	var Hover = Rickshaw.Class.create(Rickshaw.Graph.HoverDetail, {
		render: function (args) {

			date = d3.time.format("%a, %d %b %Y %H:%M:%S")(new Date(args.domainX * 1000)) //args.formattedXValue;
			v = []
		/*sort(function (a, b) {return a.order - b.order})*/
			args.detail.forEach(function (d) {
				v.push([d.name, d.formattedYValue, d.series.color])

				// Highlight selected datapoints
				var dot = document.createElement('div');
				dot.className = 'dot';
				dot.style.top = graph.y(d.value.y0 + d.value.y) + 'px';
				dot.style.borderColor = d.series.color;

				this.element.appendChild(dot);
				dot.className = 'dot active';
				this.show();
			}, this);
			generate_legend(date, v)
		}
	});

	// Call the cover function
	var hover = new Hover({
		graph: graph
	});

}

function updateStacked() {
	intervalID = setInterval(function (d) {

		now = parseInt(Date.now() / 1000)
		span = (gon.stop - gon.start)

		$.each(gon.metrics, function (i, metric) {
			if (metric.live) {
	                        update = metricURL(metric.feed,now-span,now,gon.step)

				$.getJSON(update, function (d) {
					if (d.error) {
						renderError("flash", "update returned an error on update", d.error);
						stopUpdates();
						return false
					}
					if (d.length == 0) {
						renderError("flash", "no data returned from endpoint on update", update);
						stopUpdates();
						return false
					}
					graph.series[i].data = d
					graph.render()
				})
			}
		})

	}, gon.step * 1000)
	return intervalID
}
<commit_msg>Run tooltip create after tooltips exist - otherwise, they never fire<commit_after>// Stacked Graph Type Javascript
//
//
var dataChart = []
var i;
	function getMetrics(metrics) {
		dataChart = new Array(metrics.length)
		$.each(metrics, function (i, d) {

			feed = metricURL(gon.metrics[i].feed, gon.start, gon.stop, gon.step)
			$.getJSON(feed, function (data) {
				if (data.error) {
					renderError("chart", "endpoint returned an error", data.error);

					stopUpdates();
					return false
				}
				if (data.length == 0) {
					renderError("chart", "no data returned from endpoint",feed);
					stopUpdates();
					return false
				}
				i = $.map(gon.metrics,function(d){ return d.metric}).indexOf(d)

				dataChart[i] = {data: data, name: d}
				flagComplete()
			})
		})
	}

complete = 0

function flagComplete() {
	complete++;
	if (complete == metrics.length) {
		renderStacked(dataChart)
		unrenderWaiting()
	}
}
var slider;
function isRight(d) {
	return right_id.indexOf(gon.metrics[d].metric) >= 0
}

function noRight() {
	return clean(right_id, "").length == 0
}
function renderStacked(data) {

	var palette = new Rickshaw.Color.Palette({
		scheme: "munin"
	})

	colours = []

	min = Number.MAX_VALUE; max = Number.MIN_VALUE;

	left_range = [min,max]
	right_range = [min,max]
	for (n = 0; n < data.length; n++) {
		min = Number.MAX_VALUE; max = Number.MIN_VALUE;
		for (i = 0; i < data[n].data.length; i++) {
			min = Math.min(min, data[n].data[i].y)
			max = Math.max(max, data[n].data[i].y)
		}
		if (isRight(n)) {
			right_range = [ Math.min(min, right_range[0]) , Math.max(max, right_range[1]) ]
		} else {
			left_range = [ Math.min(min, left_range[0]) , Math.max(max, left_range[1]) ]
		}
	}

	if (!noRight()) { right_scale = d3.scale.linear().domain(right_range) };//.range(right_range); )
	left_scale = d3.scale.linear().domain(left_range);//.range(left_range);

	// Push scales and their metrics into a rickshaw-eatable array
	series = []
	for (n = 0; n < data.length; n++) {
		colours[n] = palette.color()
		scale = left_scale
		if (isRight(n)) { scale = right_scale}
		if (data[n].name.indexOf("uom:c") != -1 ) { inter = "step"} else { inter = "cardinal" }
		series.push({
			color: colours[n],
			data: data[n].data,
			name: data[n].name,
			interpolation: inter,
			scale: scale
		})
	}

	// Finally, make the chart
	graph = new Rickshaw.Graph({
		element: document.querySelector("#chart"),
		width: 700,
		height: 300,
		renderer: 'line',
		series: series
	});

	// Left Y-Axis will always be around
	left_axis = new Rickshaw.Graph.Axis.Y.Scaled({
		element: document.getElementById('y_axis'),
		graph: graph,
		orientation: 'left',
		tickFormat: Rickshaw.Fixtures.Number.formatBase1024KMGTP_round,
		scale: left_scale
	});

	// Right Y-Axis will sometimes be here
	if (!noRight()) {
	right_axis = new Rickshaw.Graph.Axis.Y.Scaled({
		element: document.getElementById('y_axis_right'),
		graph: graph,
		grid: false,
		orientation: 'right',
		tickFormat: Rickshaw.Fixtures.Number.formatBase1024KMGTP_round,
		scale: right_scale
	})
	};

	// One X-axis for time
	new Rickshaw.Graph.Axis.Time({
		graph: graph,
		timeFixture: new Rickshaw.Fixtures.Time.Precise.Local()
	});

	/////
	dynamicWidth(graph);
	graph.render();

	// X-axis slider for zooming
	slider = new Rickshaw.Graph.RangeSlider.Preview({
		graph: graph,
	        height: 30,
		element: $('#slider')[0]
	});

	// Custom Legend
	var legend = document.querySelector("#legend-dual")

	function divme(className, inner) {
		var x = document.createElement("div")
		x.className = className
		x.innerHTML = inner
		return x
	}

	function generate_legend(date, v) {
		legend.innerHTML = ""

		date = divme("legend-date", date)

		left = [];
		right = [];

		for (var i = 0; i < v.length; i++) {
			d = v[i]

			label = divme("legend_label", "")
			swatch = divme("legend-swatch","")
			swatch.style.backgroundColor = d[2]
			metric = divme("legend-metric",d[0])
			data = divme("legend-data",d[1])

			label.appendChild(swatch)
			label.appendChild(metric)
			label.appendChild(data)

			if (isRight(i)) {
				icon = "icon-arrow-left"
				el = right
				tip = "Jump metric to the left axis"
				ref = left_links[i]
			} else {
				icon = "icon-arrow-right"
				el = left
				tip = "Step metric to the right axis"
				ref = right_links[i]
			}

			//link = " "+ "" +""
			link = "  "
			shuffle = divme("legend-shuffle",link)
			label.appendChild(shuffle)
			el.push(label)

		}

		legend.appendChild(date)

		a = divme("legend-indent","")
		for (var i = 0; i < left.length; i++) {
			a.appendChild(left[i])
		}
		legend.appendChild(a)

		b = divme("legend-indent","")
		for (var i = 0; i < right.length; i++) {
			b.appendChild(right[i])
		}
		legend.appendChild(b)

		$("[data-toggle='tooltip-shuffle']").tooltip({ placement: "bottom", container: "body", delay: { show: 500}})
	}

	// Initial Labels with no values
	fake_label = []
	for (i = 0; i < metrics.length; i++) {
		fake_label.push([metrics[i], "", colours[i]])
	}
	generate_legend(" ", fake_label)

	// Overload HoverDetail so it populates our legend dynamically
	var Hover = Rickshaw.Class.create(Rickshaw.Graph.HoverDetail, {
		render: function (args) {

			date = d3.time.format("%a, %d %b %Y %H:%M:%S")(new Date(args.domainX * 1000)) //args.formattedXValue;
			v = []
		/*sort(function (a, b) {return a.order - b.order})*/
			args.detail.forEach(function (d) {
				v.push([d.name, d.formattedYValue, d.series.color])

				// Highlight selected datapoints
				var dot = document.createElement('div');
				dot.className = 'dot';
				dot.style.top = graph.y(d.value.y0 + d.value.y) + 'px';
				dot.style.borderColor = d.series.color;

				this.element.appendChild(dot);
				dot.className = 'dot active';
				this.show();
			}, this);
			generate_legend(date, v)
		}
	});

	// Call the cover function
	var hover = new Hover({
		graph: graph
	});

}

function updateStacked() {
	intervalID = setInterval(function (d) {

		now = parseInt(Date.now() / 1000)
		span = (gon.stop - gon.start)

		$.each(gon.metrics, function (i, metric) {
			if (metric.live) {
	                        update = metricURL(metric.feed,now-span,now,gon.step)

				$.getJSON(update, function (d) {
					if (d.error) {
						renderError("flash", "update returned an error on update", d.error);
						stopUpdates();
						return false
					}
					if (d.length == 0) {
						renderError("flash", "no data returned from endpoint on update", update);
						stopUpdates();
						return false
					}
					graph.series[i].data = d
					graph.render()
				})
			}
		})

	}, gon.step * 1000)
	return intervalID
}
<|endoftext|>


<commit_before>var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function drawBall(){
  ctx.beginPath();
  ctx.arc( x, y, ballRadius, 0, Math.PI*2);

  ctx.fill();
  ctx.closePath();
}

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBall();
  drawPaddle();

  if (x + dx < ballRadius || x + dx > canvas.width-ballRadius){
    dx = -dx;
    ctx.fillStyle = getRandomColor();
  }
  if (y + dy > canvas.height-ballRadius || y + dy < ballRadius){
    dy = -dy;
    ctx.fillStyle = getRandomColor();

  }

  if(rightPressed && paddleX < canvas.width-paddleWidth) {
    paddleX += 7;
  }
  else if(leftPressed && paddleX > 0) {
    paddleX -= 7;
  }

  x += dx;
  y += dy;
}

function drawPaddle() {
    ctx.beginPath();
    ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
    // ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}
function keyDownHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = true;
    }
    else if(e.keyCode == 37) {
        leftPressed = true;
    }
}

function keyUpHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = false;
    }
    else if(e.keyCode == 37) {
        leftPressed = false;
    }
}
setInterval(draw, 15);
<commit_msg>Add game over logic<commit_after>var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function drawBall(){
  ctx.beginPath();
  ctx.arc( x, y, ballRadius, 0, Math.PI*2);

  ctx.fill();
  ctx.closePath();
}

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBall();
  drawPaddle();

  if(x + dx < ballRadius || x + dx > canvas.width-ballRadius){
    dx = -dx;
    ctx.fillStyle = getRandomColor();
  }
  if(y + dy < ballRadius){
    dy = -dy;
    ctx.fillStyle = getRandomColor();
  } else if(y + dy > canvas.height-ballRadius) {
    alert("GAME OVER");
    document.location.reload();

  }

  if(rightPressed && paddleX < canvas.width-paddleWidth) {
    paddleX += 7;
  }
  else if(leftPressed && paddleX > 0) {
    paddleX -= 7;
  }

  x += dx;
  y += dy;
}

function drawPaddle() {
    ctx.beginPath();
    ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
    // ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}
function keyDownHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = true;
    }
    else if(e.keyCode == 37) {
        leftPressed = true;
    }
}

function keyUpHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = false;
    }
    else if(e.keyCode == 37) {
        leftPressed = false;
    }
}
setInterval(draw, 15);
<|endoftext|>


<commit_before>//= require jquery.autocomplete

(function ($) {

    $.fn.ministerSelect = function (options) {
        var settings = $.extend({
            inputClass: 'minister-select-input'
        }, options);

        return this.each(function () {
            var dropdown = $(this);
            var input = $('<input type="text" value="" class="' + settings['inputClass'] + '" />');
            var lookup = [];

            dropdown.find('option').each(function () {
                var option = $(this);

                lookup.push(option.text());
                if (option.is(':selected')) {
                    input.val(option.text());
                }
            });

            input.autocomplete({
                lookup: lookup,
                onSelect: function () {
                    $(this).trigger('change');
                }
            }).on('change', function () {
                var text = $(this).val();
                var options = dropdown.find('option').filter(function () {
                    return $(this).text().toLowerCase().indexOf(text.toLowerCase()) !== -1;
                });
                if (options.length == 1) {
                    var option = $(options[0]);

                    dropdown.val(option.val());
                    $(this).val(option.text());
                } else {
                    dropdown.val('');
                    $(this).val('');
                }
            });

            dropdown.hide();
            dropdown.before(input);
        });
    }
}(jQuery));<commit_msg>Improve the ministerSelect to comply to jQuery naming convention<commit_after>//= require jquery.autocomplete

(function ($) {

    $.fn.ministerSelect = function (options) {
        var settings = $.extend({
            inputClass: 'minister-select-input'
        }, options);

        return this.each(function () {
            var $select = $(this),
                $input = $('<input type="text" value="" class="' + settings['inputClass'] + '" />'),
                lookup = [];

            // compile the list of auto suggestions from the select and pre-fill the input field
            $select.find('option').each(function () {
                var $option = $(this);

                lookup.push($option.text());
                if ($option.is(':selected')) {
                    $input.val($option.text());
                }
            });

            // construct the auto complete and only trigger change method on the input when user selects an option
            $input.autocomplete({
                lookup: lookup,
                onSelect: function () {
                    $(this).trigger('change');
                }
            });

            // when the input changes, the relevant select option has to be chosen
            $input.on('change', function () {
                var text = $(this).val(),
                    options = $select.find('option').filter(function () {
                        return $(this).text().toLowerCase().indexOf(text.toLowerCase()) !== -1;
                    });

                if (options.length == 1) {
                    var $option = $(options[0]);

                    $select.val($option.val());
                    $input.val($option.text());
                } else {
                    $select.val('');
                    $input.val('');
                }
            });

            $select.hide();
            $select.before($input);
        });
    }
}(jQuery));<|endoftext|>


<commit_before>
var laeh = require('laeh2').leanStacks(true);
var _e = laeh._e;
var _x = laeh._x;

var express = require('express');
var stylus = require('stylus');
var nib = require('nib');
var app = express();
var http = require('http');
var server = http.createServer(app);
var marked = require('marked');
var highlight = require('highlight.js');
var _ = require('underscore');
var fs = require('fs');
var ews = require('ws');
var ws = require('ws-rpc').extend(ews);
var wss = new ws.Server({ server: server });
var request = require('request');
var async = require('async-mini');
var utilz = require('utilz');
var optimist = require('optimist');

var watched = {};
var styles = {};
var cssUpdateInterval = 1000 * 60 * 60 * 24;
var cssCheckInterval = 1000 * 60 * 5;
var lastCssUpdate = 0;
var updatingCss;

var pkgJson = require('./package.json');

function cb(err, msg) {
    console.log(err ? (err.stack || err) : msg || 'done');
}

var argv = optimist
    .usage('\nGithub Flavored Markdown Server.\nRun in your project\'s root directory.\nUsage: $0')
    .demand('p')
    .alias('p', 'port')
    .describe('p', 'Port number to listen at.')
    .alias('h', 'host')
    .describe('h', 'Host address to bind to.')
    .default('h', 'localhost')
    .describe('proxy', 'if behind a proxy, proxy url.')
    .boolean('a')
    .describe('a', 'Render using Github API.')
    .alias('a', 'api')
    .boolean('n')
    .describe('n', 'Disable usage of Github API when the doc is manually reloaded.')
    .alias('n', 'no-api-on-reload')
    .argv;

app.configure(function() {

    var pub = __dirname + '/public';
    var views = __dirname + '/views';
    app.set('views', views);
    app.set('view engine', 'jade');
    app.set('view options', { layout: false });

    if(process.env.NODE_ENV === 'development') {
        // only use Stylus in development, because when gfms is installed
        // globally with sudo, and then run by an user, it cannot create
        // the generate .css files (and I'm too tired to look for a solution now).
        app.use(stylus.middleware({
            src: views,
            dest: pub,
            compile: function(str, path) {
                return stylus(str)
                    .set('filename', path)
                    .set('compress', true)
                    .use(nib())
                    .import('nib');
            }
        }));
    }

    app.use(wss.middleware(express));
    app.use(express.favicon());
    app.use(app.router);
    app.use(express.static(pub));
    app.use(express.errorHandler({ dump: true, stack: true }));
});

app.configure('development', function() {
    utilz.watchFile(__filename);
});

function basename(fn) {
    var m = fn.match(/.*?([^\/]+)\/?$/);
    return m ? m[1] : fn;
}

function is_markdown(v) {
    return v.match(/.*?(?:\.md|\.markdown)$/) ? true : false;
}

function is_image(v) {
    return v.match(/.*?(?:\.png|\.jpg|\.gif|\.svg)$/) ? true : false;
}

function is_sourcecode(v) {
    var matched = v.match(/.*?(?:(\.js|\.php|\.php5|\.py|\.sql))$/, 'i');

    if (matched) {
        return matched[1].substring(1).toLowerCase();
    }

    return false;
}

app.get('*', function(req, res, next) {

    if(req.path.indexOf('/styles/') === 0) {
        var style = styles[req.path];
        if(!style) {
            res.send(404);
        }
        else {
            res.set('Content-Type', 'text/css');
            // res.set('ETag', utilz.randomString());
            return res.send(200, style);
        }
    }

    var base = req.path.replace('..', 'DENIED').replace(/\/$/, '');
    var query = req.query || {};
    var dir = decodeURI(process.cwd() + base);
    var lang = "";

    var stat;
    try {
        stat = fs.statSync(dir);
    }
    catch(e) {
        return next();
    }

    if(stat.isDirectory()) {

        var files = _.chain(fs.readdirSync(dir)).filter(function(v) {
            var stat = fs.statSync(dir + '/' + v);
            return stat.isDirectory() || (stat.isFile() && (is_markdown(v) || is_image(v)));
        }).map(function(v) {
            return {
                url: base + '/' + v,
                name: v
            };
        }).value();

        res.render('directory', {
            files: files,
            dir: dir,
            styles: Object.keys(styles),
            title: basename(dir)
        });
    } else if(query.raw === "true") {
        var content = fs.readFileSync(dir);
        res.writeHead('200');
        res.end(content,'binary');
    } else if(is_markdown(dir)) {

        if(!watched[dir]) {
            fs.watchFile(dir, { interval: 500 }, function(curr, prev) {
                if(curr.mtime.getTime() !== prev.mtime.getTime()) {

                    console.log('file ' + dir + ' has changed');

                    renderFile(dir, argv.a, _x(console.log, false, function(err, rendered) {
                        wss.message('update', { update: dir, content: err || rendered });
                    }));
                }
            });
            watched[dir] = true;
        }

        renderFile(dir, argv.a || argv.b, _x(next, true, function(err, rendered) {
            res.render('file', {
                file: rendered,
                title: basename(dir),
                styles: Object.keys(styles),
                fullname: dir
            });
        }));

    }
    else if(is_image(dir)) {

        if(!watched[dir]) {
            fs.watchFile(dir, { interval: 500 }, function(curr, prev) {
                if(curr.mtime.getTime() !== prev.mtime.getTime()) {

                    console.log('file ' + dir + ' has changed');

                    renderImageFile(base, argv.a, _x(console.log, false, function(err, rendered) {
                        wss.message('update', { update: dir, content: err || rendered });
                    }));
                }
            });
            watched[dir] = true;
        }

        renderImageFile(base, argv.a || argv.b, _x(next, true, function(err, rendered) {
            res.render('file', {
                file: rendered,
                title: basename(dir),
                styles: Object.keys(styles),
                fullname: dir
            });
        }));

    }
    else if(lang = is_sourcecode(dir)) {
        if(!watched[dir]) {
            fs.watchFile(dir, { interval: 500 }, function(curr, prev) {
                if(curr.mtime.getTime() !== prev.mtime.getTime()) {

                    console.log('file ' + dir + ' has changed');

                    renderSourceCode(dir, argv.a, lang, _x(console.log, false, function(err, rendered) {
                        wss.message('update', { update: dir, content: err || rendered });
                    }));
                }
            });
            watched[dir] = true;
        }

        renderSourceCode(dir, argv.a || argv.b, lang, _x(next, true, function(err, rendered) {
            res.render('file', {
                file: rendered,
                title: basename(dir),
                styles: Object.keys(styles),
                fullname: dir
            });
        }));
    }
    else
        return next();
});

function renderFile(file, api, cb) { // cb(err, res)
    var contents = fs.readFileSync(file, 'utf8');
    var func = api ? renderWithGithub : renderWithMarked;
    func(contents, _x(cb, true, cb));
}

function renderImageFile(file, api, cb) { // cb(err, res)
    var html = '

';
    cb(null, html);
}

function renderSourceCode(file, api, lang, cb) { // cb(err, res)
    var contents = "```" + lang + "\n" + fs.readFileSync(file, 'utf8') + "\n```";
    var func = api ? renderWithGithub : renderWithMarked;
    func(contents, _x(cb, true, cb));
}

function renderWithMarked(contents, cb) { // cb(err, res)
    marked.setOptions({
      gfm: true,
      tables: true,
      smartLists: true,
      breaks: true,
      highlight: function (code, lang) {
        if (lang) {
            return highlight.highlight(lang, code, true).value;
        } else {
            return highlight.highlightAuto(code).value;
        }
      }
    });

    var html = marked(contents);
    cb(null, html);
}

function renderWithGithub(contents, cb) { // cb(err, res)
    var opts = {
        method: 'post',
        url: 'https://api.github.com/markdown',
        json: {
            text: contents,
            mode: 'markdown'
        },
        headers: {
          'User-Agent': 'gfms/' + pkgJson.version + ' https://github.com/ypocat/gfms'
        },
        encoding: 'utf8'
    };

    if(argv.proxy && argv.proxy.length > 0) {
        opts.proxy = argv.proxy;
    }

    request(opts, _x(cb, true, function(err, res, body) {
        console.log('remaining API requests: %d', res.headers['x-ratelimit-remaining']);
        cb(null, body);
    }));
}

process.on('SIGINT', function() {
    console.log('\nGFMS exit.');
    return process.exit();
});

function loadStyle(style, cb) {

    request(style, _x(cb, true, function(err, res, body) {

        if(res.statusCode != 200)
            throw 'Cannot load stylesheet: ' + style;

        cb(null, body);
    }));
}

function getStylesheetBaseName(url) {

    var m = /\/([^\/]+)$/.exec(url);

    if(!m)
        _e('unexpected stylesheet url: ' + url);

    return m[1];
}

function loadStyles(_cb) {

    if(updatingCss)
        return;
    updatingCss = true;

    function cb(err) {
        updatingCss = false;
        _cb(err);
    }

    _x(cb, false, function() {

        console.log('Loading Github CSS...');

        var opts = {url:'http://www.github.com'};
        if(argv.proxy && argv.proxy.length > 0) {
            opts.proxy = argv.proxy;
        }
        request(opts, _x(cb, true, function(err, res, body) {

            if(res.statusCode != 200)
                throw 'Cannot load .css links from Github';

            var ff = {};
            var m;
            var re = /href="([^"]+?\/assets\/[^"]+?\.css)"/g;

            while(m = re.exec(body)) {

                (function(url) {

                    var base = '/styles/' + getStylesheetBaseName(url);

                    ff[base] = _x(null, false, function(cb) {
                        var opts = {url:url};
                        if(argv.proxy && argv.proxy.length > 0) {
                            opts.proxy = argv.proxy;
                        }
                        loadStyle(opts, cb);
                    });

                })(m[1]);
            }

            async.parallel(ff, _x(cb, true, function(err, res) {
                styles = res;
                cb();
            }));

        }));

    })();
}

function startCssUpdater(interval) {

    console.log('Auto-updating CSS every ' + utilz.timeSpan(interval) + '.');

    setInterval(_x(cb, false, function() {

        if(Date.now() - lastCssUpdate > interval) {

            loadStyles(_x(cb, true, function() {

                lastCssUpdate = Date.now();

                cb(null, 'Auto-updated CSS.');
            }));
        }

    }), cssCheckInterval);
}

if(!argv.a && !argv.n)
    argv.b = true;

_x(cb, false, function() {
    loadStyles(_x(cb, true, function() {

        if(!Object.keys(styles).length)
            _e('Cannot parse .css links from Github');

        if(argv.a)
            console.log('Using Github API to render markdown for all updates.');
        else if(argv.b)
            console.log('Using Github API to render markdown for manual reload updates.');

        server.listen(argv.p, argv.h);
        console.log('GFMS ' + pkgJson.version + ' serving ' + process.cwd() + ' at http://' + argv.h + ':' + argv.p + '/ - press CTRL+C to exit.');

        lastCssUpdate = Date.now();
        startCssUpdater(cssUpdateInterval);
    }));
})();
<commit_msg>Updated gfms.js to support current express.js<commit_after>
var laeh = require('laeh2').leanStacks(true);
var _e = laeh._e;
var _x = laeh._x;

var express = require('express');
var stylus = require('stylus');
var nib = require('nib');
var app = express();
var http = require('http');
var server = http.createServer(app);
var marked = require('marked');
var highlight = require('highlight.js');
var _ = require('underscore');
var fs = require('fs');
var ews = require('ws');
var ws = require('ws-rpc').extend(ews);
var wss = new ws.Server({ server: server });
var request = require('request');
var async = require('async-mini');
var utilz = require('utilz');
var optimist = require('optimist');

var watched = {};
var styles = {};
var cssUpdateInterval = 1000 * 60 * 60 * 24;
var cssCheckInterval = 1000 * 60 * 5;
var lastCssUpdate = 0;
var updatingCss;

var pkgJson = require('./package.json');

function cb(err, msg) {
    console.log(err ? (err.stack || err) : msg || 'done');
}

var argv = optimist
    .usage('\nGithub Flavored Markdown Server.\nRun in your project\'s root directory.\nUsage: $0')
    .demand('p')
    .alias('p', 'port')
    .describe('p', 'Port number to listen at.')
    .alias('h', 'host')
    .describe('h', 'Host address to bind to.')
    .default('h', 'localhost')
    .describe('proxy', 'if behind a proxy, proxy url.')
    .boolean('a')
    .describe('a', 'Render using Github API.')
    .alias('a', 'api')
    .boolean('n')
    .describe('n', 'Disable usage of Github API when the doc is manually reloaded.')
    .alias('n', 'no-api-on-reload')
    .argv;

var pub = __dirname + '/public';
var views = __dirname + '/views';
app.set('views', views);
app.set('view engine', 'jade');
app.set('view options', { layout: false });

if(process.env.NODE_ENV === 'development') {
    // only use Stylus in development, because when gfms is installed
    // globally with sudo, and then run by an user, it cannot create
    // the generate .css files (and I'm too tired to look for a solution now).
    app.use(stylus.middleware({
        src: views,
        dest: pub,
        compile: function(str, path) {
            return stylus(str)
                .set('filename', path)
                .set('compress', true)
                .use(nib())
                .import('nib');
        }
    }));
}

app.use(wss.middleware(express));
app.use(express.static(pub));

function basename(fn) {
    var m = fn.match(/.*?([^\/]+)\/?$/);
    return m ? m[1] : fn;
}

function is_markdown(v) {
    return v.match(/.*?(?:\.md|\.markdown)$/) ? true : false;
}

function is_image(v) {
    return v.match(/.*?(?:\.png|\.jpg|\.gif|\.svg)$/) ? true : false;
}

function is_sourcecode(v) {
    var matched = v.match(/.*?(?:(\.js|\.php|\.php5|\.py|\.sql))$/, 'i');

    if (matched) {
        return matched[1].substring(1).toLowerCase();
    }

    return false;
}

app.get('*', function(req, res, next) {

    if(req.path.indexOf('/styles/') === 0) {
        var style = styles[req.path];
        if(!style) {
            res.send(404);
        }
        else {
            res.set('Content-Type', 'text/css');
            // res.set('ETag', utilz.randomString());
            return res.send(200, style);
        }
    }

    var base = req.path.replace('..', 'DENIED').replace(/\/$/, '');
    var query = req.query || {};
    var dir = decodeURI(process.cwd() + base);
    var lang = "";

    var stat;
    try {
        stat = fs.statSync(dir);
    }
    catch(e) {
        return next();
    }

    if(stat.isDirectory()) {

        var files = _.chain(fs.readdirSync(dir)).filter(function(v) {
            var stat = fs.statSync(dir + '/' + v);
            return stat.isDirectory() || (stat.isFile() && (is_markdown(v) || is_image(v)));
        }).map(function(v) {
            return {
                url: base + '/' + v,
                name: v
            };
        }).value();

        res.render('directory', {
            files: files,
            dir: dir,
            styles: Object.keys(styles),
            title: basename(dir)
        });
    } else if(query.raw === "true") {
        var content = fs.readFileSync(dir);
        res.writeHead('200');
        res.end(content,'binary');
    } else if(is_markdown(dir)) {

        if(!watched[dir]) {
            fs.watchFile(dir, { interval: 500 }, function(curr, prev) {
                if(curr.mtime.getTime() !== prev.mtime.getTime()) {

                    console.log('file ' + dir + ' has changed');

                    renderFile(dir, argv.a, _x(console.log, false, function(err, rendered) {
                        wss.message('update', { update: dir, content: err || rendered });
                    }));
                }
            });
            watched[dir] = true;
        }

        renderFile(dir, argv.a || argv.b, _x(next, true, function(err, rendered) {
            res.render('file', {
                file: rendered,
                title: basename(dir),
                styles: Object.keys(styles),
                fullname: dir
            });
        }));

    }
    else if(is_image(dir)) {

        if(!watched[dir]) {
            fs.watchFile(dir, { interval: 500 }, function(curr, prev) {
                if(curr.mtime.getTime() !== prev.mtime.getTime()) {

                    console.log('file ' + dir + ' has changed');

                    renderImageFile(base, argv.a, _x(console.log, false, function(err, rendered) {
                        wss.message('update', { update: dir, content: err || rendered });
                    }));
                }
            });
            watched[dir] = true;
        }

        renderImageFile(base, argv.a || argv.b, _x(next, true, function(err, rendered) {
            res.render('file', {
                file: rendered,
                title: basename(dir),
                styles: Object.keys(styles),
                fullname: dir
            });
        }));

    }
    else if(lang = is_sourcecode(dir)) {
        if(!watched[dir]) {
            fs.watchFile(dir, { interval: 500 }, function(curr, prev) {
                if(curr.mtime.getTime() !== prev.mtime.getTime()) {

                    console.log('file ' + dir + ' has changed');

                    renderSourceCode(dir, argv.a, lang, _x(console.log, false, function(err, rendered) {
                        wss.message('update', { update: dir, content: err || rendered });
                    }));
                }
            });
            watched[dir] = true;
        }

        renderSourceCode(dir, argv.a || argv.b, lang, _x(next, true, function(err, rendered) {
            res.render('file', {
                file: rendered,
                title: basename(dir),
                styles: Object.keys(styles),
                fullname: dir
            });
        }));
    }
    else
        return next();
});

function renderFile(file, api, cb) { // cb(err, res)
    var contents = fs.readFileSync(file, 'utf8');
    var func = api ? renderWithGithub : renderWithMarked;
    func(contents, _x(cb, true, cb));
}

function renderImageFile(file, api, cb) { // cb(err, res)
    var html = '

';
    cb(null, html);
}

function renderSourceCode(file, api, lang, cb) { // cb(err, res)
    var contents = "```" + lang + "\n" + fs.readFileSync(file, 'utf8') + "\n```";
    var func = api ? renderWithGithub : renderWithMarked;
    func(contents, _x(cb, true, cb));
}

function renderWithMarked(contents, cb) { // cb(err, res)
    marked.setOptions({
      gfm: true,
      tables: true,
      smartLists: true,
      breaks: true,
      highlight: function (code, lang) {
        if (lang) {
            return highlight.highlight(lang, code, true).value;
        } else {
            return highlight.highlightAuto(code).value;
        }
      }
    });

    var html = marked(contents);
    cb(null, html);
}

function renderWithGithub(contents, cb) { // cb(err, res)
    var opts = {
        method: 'post',
        url: 'https://api.github.com/markdown',
        json: {
            text: contents,
            mode: 'markdown'
        },
        headers: {
          'User-Agent': 'gfms/' + pkgJson.version + ' https://github.com/ypocat/gfms'
        },
        encoding: 'utf8'
    };

    if(argv.proxy && argv.proxy.length > 0) {
        opts.proxy = argv.proxy;
    }

    request(opts, _x(cb, true, function(err, res, body) {
        console.log('remaining API requests: %d', res.headers['x-ratelimit-remaining']);
        cb(null, body);
    }));
}

process.on('SIGINT', function() {
    console.log('\nGFMS exit.');
    return process.exit();
});

function loadStyle(style, cb) {

    request(style, _x(cb, true, function(err, res, body) {

        if(res.statusCode != 200)
            throw 'Cannot load stylesheet: ' + style;

        cb(null, body);
    }));
}

function getStylesheetBaseName(url) {

    var m = /\/([^\/]+)$/.exec(url);

    if(!m)
        _e('unexpected stylesheet url: ' + url);

    return m[1];
}

function loadStyles(_cb) {

    if(updatingCss)
        return;
    updatingCss = true;

    function cb(err) {
        updatingCss = false;
        _cb(err);
    }

    _x(cb, false, function() {

        console.log('Loading Github CSS...');

        var opts = {url:'http://www.github.com'};
        if(argv.proxy && argv.proxy.length > 0) {
            opts.proxy = argv.proxy;
        }
        request(opts, _x(cb, true, function(err, res, body) {

            if(res.statusCode != 200)
                throw 'Cannot load .css links from Github';

            var ff = {};
            var m;
            var re = /href="([^"]+?\/assets\/[^"]+?\.css)"/g;

            while(m = re.exec(body)) {

                (function(url) {

                    var base = '/styles/' + getStylesheetBaseName(url);

                    ff[base] = _x(null, false, function(cb) {
                        var opts = {url:url};
                        if(argv.proxy && argv.proxy.length > 0) {
                            opts.proxy = argv.proxy;
                        }
                        loadStyle(opts, cb);
                    });

                })(m[1]);
            }

            async.parallel(ff, _x(cb, true, function(err, res) {
                styles = res;
                cb();
            }));

        }));

    })();
}

function startCssUpdater(interval) {

    console.log('Auto-updating CSS every ' + utilz.timeSpan(interval) + '.');

    setInterval(_x(cb, false, function() {

        if(Date.now() - lastCssUpdate > interval) {

            loadStyles(_x(cb, true, function() {

                lastCssUpdate = Date.now();

                cb(null, 'Auto-updated CSS.');
            }));
        }

    }), cssCheckInterval);
}

if(!argv.a && !argv.n)
    argv.b = true;

_x(cb, false, function() {
    loadStyles(_x(cb, true, function() {

        if(!Object.keys(styles).length)
            _e('Cannot parse .css links from Github');

        if(argv.a)
            console.log('Using Github API to render markdown for all updates.');
        else if(argv.b)
            console.log('Using Github API to render markdown for manual reload updates.');

        server.listen(argv.p, argv.h);
        console.log('GFMS ' + pkgJson.version + ' serving ' + process.cwd() + ' at http://' + argv.h + ':' + argv.p + '/ - press CTRL+C to exit.');

        lastCssUpdate = Date.now();
        startCssUpdater(cssUpdateInterval);
    }));
})();
<|endoftext|>


<commit_before>import React, { Component } from "react";
import { Link } from "react-router";

export default class App extends Component {
  render() {
    const {
      content,
    } = this.props;
    return (

          {content ||
Default.
}

            <Link to={`/`}>Create poll</Link>

            © 2016 Powered by Kinto

    );
  }
}
<commit_msg>Bigger create button<commit_after>import React, { Component } from "react";
import { Link } from "react-router";

export default class App extends Component {
  render() {
    const {
      content,
    } = this.props;
    return (

          {content ||
Default.
}

<Link to={`/`}>Create your poll</Link>

            © 2016 Powered by Kinto

    );
  }
}
<|endoftext|>


<commit_before>//LeadBundle
Mautic.leadOnLoad = function (container) {
    if (mQuery(container + ' form[name="lead"]').length) {
        Mautic.activateLeadOwnerTypeahead('lead_owner_lookup');

        mQuery("*[data-toggle='field-lookup']").each(function (index) {
            var target = mQuery(this).attr('data-target');
            var field  = mQuery(this).attr('id');
            var options = mQuery(this).attr('data-options');
            Mautic.activateLeadFieldTypeahead(field, target, options);
        });

        Mautic.updateLeadFieldProperties(mQuery('#leadfield_type').val());
    }

    Mautic.loadRemoteContentToModal('note-modal');

    if (mQuery(container + ' #list-search').length) {
        Mautic.activateSearchAutocomplete('list-search', 'lead.lead');
    }
};

Mautic.activateLeadFieldTypeahead = function(field, target, options) {
    if (options) {
        //set to zero so the list shows from the start
        var taMinLength = 0;
        var keys = values = [];
        //check to see if there is a key/value split
        options = options.split('||');
        if (options.length == 2) {
            keys   = options[0].split('|');
            values = options[1].split('|');
        } else {
            values = options[0].split('|');
        }

        var substringMatcher = function(strs, strKeys) {
            return function findMatches(q, cb) {
                var matches, substringRegex;

                // an array that will be populated with substring matches
                matches = [];

                // regex used to determine if a string contains the substring `q`
                substrRegex = new RegExp(q, 'i');

                // iterate through the pool of strings and for any string that
                // contains the substring `q`, add it to the `matches` array
                mQuery.each(strs, function(i, str) {
                    if (substrRegex.test(str)) {
                        // the typeahead jQuery plugin expects suggestions to a
                        // JavaScript object, refer to typeahead docs for more info
                        if (strKeys.length && typeof strKeys[i] != 'undefined') {
                            matches.push({
                                value: str,
                                id:    strKeys[i]
                            });
                        } else {
                            matches.push({value: str});
                        }
                    }
                });

                cb(matches);
            };
        };

        var source = substringMatcher(values, keys);
    } else {
        //set the length to 2 so it requires at least 2 characters to search
        var taMinLength = 2;

        this[field] = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            prefetch: {
                url: mauticAjaxUrl + "?action=lead:fieldList&field=" + target,
                ajax: {
                    beforeSend: function () {
                        MauticVars.showLoadingBar = false;
                    }
                }
            },
            remote: {
                url: mauticAjaxUrl + "?action=lead:fieldList&field=" + target + "&filter=%QUERY",
                ajax: {
                    beforeSend: function () {
                        MauticVars.showLoadingBar = false;
                    }
                }
            },
            dupDetector: function (remoteMatch, localMatch) {
                return (remoteMatch.value == localMatch.value);
            },
            ttl: 1800000,
            limit: 5
        });
        this[field].initialize();
        var source = this[field].ttAdapter();
    }

    mQuery('#' + field).typeahead(
        {
            hint: true,
            highlight: true,
            minLength: taMinLength
        },
        {
            name: field,
            displayKey: 'value',
            source: source
        }
    ).on('typeahead:selected', function (event, datum) {
        if (mQuery("#" + field + "_id").length && datum["id"]) {
            mQuery("#" + field + "_id").val(datum["id"]);
        }
    }).on('typeahead:autocompleted', function (event, datum) {
        if (mQuery("#" + field + "_id").length && datum["id"]) {
            mQuery("#" + field + "_id").val(datum["id"]);
        }
    }).on('keypress', function (event) {
        if ((event.keyCode || event.which) == 13) {
            mQuery('#' + field).typeahead('close');
        }
    });
};

Mautic.activateLeadOwnerTypeahead = function(el) {
    var owners = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('label'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: mauticAjaxUrl + "?action=lead:userList",
            ajax: {
                beforeSend: function () {
                    MauticVars.showLoadingBar = false;
                }
            }
        },
        remote: {
            url: mauticAjaxUrl + "?action=lead:userList&filter=%QUERY",
            ajax: {
                beforeSend: function () {
                    MauticVars.showLoadingBar = false;
                }
            }
        },
        dupDetector: function (remoteMatch, localMatch) {
            return (remoteMatch.label == localMatch.label);
        },
        ttl: 1800000,
        limit: 5
    });
    owners.initialize();
    mQuery("#"  + el).typeahead(
        {
            hint: true,
            highlight: true,
            minLength: 2
        },
        {
            name: 'lead_owners',
            displayKey: 'label',
            source: owners.ttAdapter()
        }).on('typeahead:selected', function (event, datum) {
            if (mQuery("#lead_owner").length) {
                mQuery("#lead_owner").val(datum["value"]);
            }
        }).on('typeahead:autocompleted', function (event, datum) {
            if (mQuery("#lead_owner").length) {
                mQuery("#lead_owner").val(datum["value"]);
            }
        }
    ).on( 'focus', function() {
        mQuery(this).typeahead( 'open');
    });
};

Mautic.leadlistOnLoad = function(container) {
    if (mQuery(container + ' #list-search').length) {
        Mautic.activateSearchAutocomplete('list-search', 'lead.list');
    }

    mQuery('#leadlist_filters_left li').draggable({
        appendTo: "body",
        helper: "clone"
    });

    mQuery('#leadlist_filters_right').sortable({
        items: "li",
        handle: '.sortable-handle'
    });

    if (mQuery('#leadlist_filters_right').length) {
        mQuery('#leadlist_filters_right .remove-selected').each( function (index, el) {
            mQuery(el).on('click', function () {
                mQuery(this).parent().remove();
                if (!mQuery('#leadlist_filters_right li:not(.placeholder)').length) {
                    mQuery('#leadlist_filters_right li.placeholder').removeClass('hide');
                } else {
                    mQuery('#leadlist_filters_right li.placeholder').addClass('hide');
                }
            });
        });
    }

    mQuery("*[data-toggle='field-lookup']").each(function (index) {
        var target = mQuery(this).attr('data-target');
        var options = mQuery(this).attr('data-options');
        var field  = mQuery(this).attr('id');
        Mautic.activateLeadFieldTypeahead(field, target, options);
    });
};

Mautic.addLeadListFilter = function (elId) {
    var filterId = '#available_' + elId;
    var label  = mQuery(filterId + ' span.leadlist-filter-name').text();

    //create a new filter
    var li = mQuery("<li />").addClass("padding-sm").text(label).appendTo(mQuery('#leadlist_filters_right'));

    //add a delete button
    mQuery("<i />").addClass("fa fa-fw fa-trash-o remove-selected").prependTo(li).on('click', function() {
        mQuery(this).parent().remove();
    });

    //add a sortable handle
    mQuery("<i />").addClass("fa fa-fw fa-ellipsis-v sortable-handle").prependTo(li);

    var fieldType = mQuery(filterId).find("input.field_type").val();
    var alias     = mQuery(filterId).find("input.field_alias").val();

    //add wrapping div and add the template html

    var container = mQuery('<div />')
        .addClass('filter-container')
        .appendTo(li);

    if (fieldType == 'country' || fieldType == 'timezone') {
        container.html(mQuery('#filter-' + fieldType + '-template').html());
    } else {
        container.html(mQuery('#filter-template').html());
    }
    mQuery(container).find("input[name='leadlist[filters][field][]']").val(alias);
    mQuery(container).find("input[name='leadlist[filters][type][]']").val(fieldType);

    //give the value element a unique id
    var uniqid = "id_" + Date.now();
    var filter = mQuery(container).find("input[name='leadlist[filters][filter][]']");
    filter.attr('id', uniqid);

    //activate fields
    if (fieldType == 'lookup' || fieldType == 'select') {
        var fieldCallback = mQuery(filterId).find("input.field_callback").val();
        if (fieldCallback) {
            var fieldOptions = mQuery(filterId).find("input.field_list").val();
            Mautic[fieldCallback](uniqid, alias, fieldOptions);
        }
    } else if (fieldType == 'datetime') {
        filter.datetimepicker({
            format: 'Y-m-d H:i',
            lazyInit: true,
            validateOnBlur: false,
            allowBlank: true,
            scrollInput: false
        });
    } else if (fieldType == 'date') {
        filter.datetimepicker({
            timepicker: false,
            format: 'Y-m-d',
            lazyInit: true,
            validateOnBlur: false,
            allowBlank: true,
            scrollInput: false,
            closeOnDateSelect: true
        });
    } else if (fieldType == 'time') {
        filter.datetimepicker({
            datepicker: false,
            format: 'H:i',
            lazyInit: true,
            validateOnBlur: false,
            allowBlank: true,
            scrollInput: false
        });
    } else if (fieldType == 'lookup_id' || fieldType == 'boolean') {
        //switch the filter and display elements
        var oldFilter = mQuery(container).find("input[name='leadlist[filters][filter][]']");
        var newDisplay = oldFilter.clone();
        newDisplay.attr('id', uniqid);
        newDisplay.attr('name', 'leadlist[filters][display][]');

        var oldDisplay = mQuery(container).find("input[name='leadlist[filters][display][]']");
        var newFilter = oldDisplay.clone();
        newFilter.attr('id', uniqid + "_id");
        newFilter.attr('name', 'leadlist[filters][filter][]');

        oldFilter.replaceWith(newFilter);
        oldDisplay.replaceWith(newDisplay);

        var fieldCallback = mQuery(filterId).find("input.field_callback").val();
        if (fieldCallback) {
            var fieldOptions = mQuery(filterId).find("input.field_list").val();
            Mautic[fieldCallback](uniqid, alias, fieldOptions);
        }
    } else {
        filter.attr('type', fieldType);
    }
};

Mautic.leadfieldOnLoad = function (container) {

    var fixHelper = function(e, ui) {
        ui.children().each(function() {
            mQuery(this).width(mQuery(this).width());
        });
        return ui;
    };

    if (mQuery(container + ' .leadfield-list').length) {
        mQuery(container + ' .leadfield-list tbody').sortable({
            handle: '.fa-ellipsis-v',
            helper: fixHelper,
            stop: function(i) {
                mQuery.ajax({
                    type: "POST",
                    url: mauticAjaxUrl + "?action=lead:reorder",
                    data: mQuery(container + ' .leadfield-list tbody').sortable("serialize")});
            }
        });
    }

};

/**
 * Update the properties for field data types
 */
Mautic.updateLeadFieldProperties = function(selectedVal) {
    if (mQuery('#field-templates .'+selectedVal).length) {
        mQuery('#leadfield_properties').html(mQuery('#field-templates .'+selectedVal).html());

        mQuery("#leadfield_properties *[data-toggle='tooltip']").tooltip({html: true});
    } else {
        mQuery('#leadfield_properties').html('');
    }

    if (selectedVal == 'time') {
        mQuery('#leadfield_isListable').closest('.row').addClass('hide');
    } else {
        mQuery('#leadfield_isListable').closest('.row').removeClass('hide');
    }
};

Mautic.leadlistOnLoad = function(container) {
    // Shuffle
    // ================================
    var grid   = mQuery("#shuffle-grid"),
        filter = mQuery("#shuffle-filter"),
        sizer  = grid.find("shuffle-sizer");

    // instatiate shuffle
    grid.shuffle({
        itemSelector: ".shuffle",
        sizer: sizer
    });

    // Filter options
    (function () {
        filter.on("keyup change", function () {
            var val = this.value.toLowerCase();
            grid.shuffle("shuffle", function (el, shuffle) {

                // Only search elements in the current group
                if (shuffle.group !== "all" && mQuery.inArray(shuffle.group, el.data("groups")) === -1) {
                    return false;
                }

                var text = mQuery.trim(el.find(".panel-body > h5").text()).toLowerCase();
                return text.indexOf(val) !== -1;
            });
        });
    })();

    // Update shuffle on sidebar minimize/maximize
    mQuery("html")
        .on("fa.sidebar.minimize", function () { grid.shuffle("update"); })
        .on("fa.sidebar.maximize", function () { grid.shuffle("update"); });
};

Mautic.refreshLeadSocialProfile = function(network, leadId, event) {
    Mautic.startIconSpinOnEvent(event);
    var query = "action=lead:updateSocialProfile&network=" + network + "&lead=" + leadId;
    mQuery.ajax({
        url: mauticAjaxUrl,
        type: "POST",
        data: query,
        dataType: "json",
        success: function (response) {
            if (response.success) {
                //loop through each network
                mQuery.each(response.profiles, function( index, value ){
                    if (mQuery('#' + index + 'CompleteProfile').length) {
                        mQuery('#' + index + 'CompleteProfile').html(value.newContent);
                    }
                });
            }
            Mautic.stopIconSpinPostEvent(event);
        },
        error: function (request, textStatus, errorThrown) {
            if (mauticEnv == 'dev') {
                alert(errorThrown);
            }
            Mautic.stopIconSpinPostEvent(event);
        }
    });
}

Mautic.loadRemoteContentToModal = function(elementId) {
    mQuery('#'+elementId).on('loaded.bs.modal', function (e) {
        var remoteContent = mQuery.parseJSON(e.target.textContent).newContent;
        mQuery(this).find('.modal-content').html(remoteContent);
    });
}<commit_msg>MAU-14 Cancel button behaviour<commit_after>//LeadBundle
Mautic.leadOnLoad = function (container) {
    if (mQuery(container + ' form[name="lead"]').length) {
        Mautic.activateLeadOwnerTypeahead('lead_owner_lookup');

        mQuery("*[data-toggle='field-lookup']").each(function (index) {
            var target = mQuery(this).attr('data-target');
            var field  = mQuery(this).attr('id');
            var options = mQuery(this).attr('data-options');
            Mautic.activateLeadFieldTypeahead(field, target, options);
        });

        Mautic.updateLeadFieldProperties(mQuery('#leadfield_type').val());
    }

    Mautic.loadRemoteContentToModal('note-modal');

    if (mQuery(container + ' #list-search').length) {
        Mautic.activateSearchAutocomplete('list-search', 'lead.lead');
    }
};

Mautic.activateLeadFieldTypeahead = function(field, target, options) {
    if (options) {
        //set to zero so the list shows from the start
        var taMinLength = 0;
        var keys = values = [];
        //check to see if there is a key/value split
        options = options.split('||');
        if (options.length == 2) {
            keys   = options[0].split('|');
            values = options[1].split('|');
        } else {
            values = options[0].split('|');
        }

        var substringMatcher = function(strs, strKeys) {
            return function findMatches(q, cb) {
                var matches, substringRegex;

                // an array that will be populated with substring matches
                matches = [];

                // regex used to determine if a string contains the substring `q`
                substrRegex = new RegExp(q, 'i');

                // iterate through the pool of strings and for any string that
                // contains the substring `q`, add it to the `matches` array
                mQuery.each(strs, function(i, str) {
                    if (substrRegex.test(str)) {
                        // the typeahead jQuery plugin expects suggestions to a
                        // JavaScript object, refer to typeahead docs for more info
                        if (strKeys.length && typeof strKeys[i] != 'undefined') {
                            matches.push({
                                value: str,
                                id:    strKeys[i]
                            });
                        } else {
                            matches.push({value: str});
                        }
                    }
                });

                cb(matches);
            };
        };

        var source = substringMatcher(values, keys);
    } else {
        //set the length to 2 so it requires at least 2 characters to search
        var taMinLength = 2;

        this[field] = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            prefetch: {
                url: mauticAjaxUrl + "?action=lead:fieldList&field=" + target,
                ajax: {
                    beforeSend: function () {
                        MauticVars.showLoadingBar = false;
                    }
                }
            },
            remote: {
                url: mauticAjaxUrl + "?action=lead:fieldList&field=" + target + "&filter=%QUERY",
                ajax: {
                    beforeSend: function () {
                        MauticVars.showLoadingBar = false;
                    }
                }
            },
            dupDetector: function (remoteMatch, localMatch) {
                return (remoteMatch.value == localMatch.value);
            },
            ttl: 1800000,
            limit: 5
        });
        this[field].initialize();
        var source = this[field].ttAdapter();
    }

    mQuery('#' + field).typeahead(
        {
            hint: true,
            highlight: true,
            minLength: taMinLength
        },
        {
            name: field,
            displayKey: 'value',
            source: source
        }
    ).on('typeahead:selected', function (event, datum) {
        if (mQuery("#" + field + "_id").length && datum["id"]) {
            mQuery("#" + field + "_id").val(datum["id"]);
        }
    }).on('typeahead:autocompleted', function (event, datum) {
        if (mQuery("#" + field + "_id").length && datum["id"]) {
            mQuery("#" + field + "_id").val(datum["id"]);
        }
    }).on('keypress', function (event) {
        if ((event.keyCode || event.which) == 13) {
            mQuery('#' + field).typeahead('close');
        }
    });
};

Mautic.activateLeadOwnerTypeahead = function(el) {
    var owners = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('label'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
            url: mauticAjaxUrl + "?action=lead:userList",
            ajax: {
                beforeSend: function () {
                    MauticVars.showLoadingBar = false;
                }
            }
        },
        remote: {
            url: mauticAjaxUrl + "?action=lead:userList&filter=%QUERY",
            ajax: {
                beforeSend: function () {
                    MauticVars.showLoadingBar = false;
                }
            }
        },
        dupDetector: function (remoteMatch, localMatch) {
            return (remoteMatch.label == localMatch.label);
        },
        ttl: 1800000,
        limit: 5
    });
    owners.initialize();
    mQuery("#"  + el).typeahead(
        {
            hint: true,
            highlight: true,
            minLength: 2
        },
        {
            name: 'lead_owners',
            displayKey: 'label',
            source: owners.ttAdapter()
        }).on('typeahead:selected', function (event, datum) {
            if (mQuery("#lead_owner").length) {
                mQuery("#lead_owner").val(datum["value"]);
            }
        }).on('typeahead:autocompleted', function (event, datum) {
            if (mQuery("#lead_owner").length) {
                mQuery("#lead_owner").val(datum["value"]);
            }
        }
    ).on( 'focus', function() {
        mQuery(this).typeahead( 'open');
    });
};

Mautic.leadlistOnLoad = function(container) {
    if (mQuery(container + ' #list-search').length) {
        Mautic.activateSearchAutocomplete('list-search', 'lead.list');
    }

    mQuery('#leadlist_filters_left li').draggable({
        appendTo: "body",
        helper: "clone"
    });

    mQuery('#leadlist_filters_right').sortable({
        items: "li",
        handle: '.sortable-handle'
    });

    if (mQuery('#leadlist_filters_right').length) {
        mQuery('#leadlist_filters_right .remove-selected').each( function (index, el) {
            mQuery(el).on('click', function () {
                mQuery(this).parent().remove();
                if (!mQuery('#leadlist_filters_right li:not(.placeholder)').length) {
                    mQuery('#leadlist_filters_right li.placeholder').removeClass('hide');
                } else {
                    mQuery('#leadlist_filters_right li.placeholder').addClass('hide');
                }
            });
        });
    }

    mQuery("*[data-toggle='field-lookup']").each(function (index) {
        var target = mQuery(this).attr('data-target');
        var options = mQuery(this).attr('data-options');
        var field  = mQuery(this).attr('id');
        Mautic.activateLeadFieldTypeahead(field, target, options);
    });
};

Mautic.addLeadListFilter = function (elId) {
    var filterId = '#available_' + elId;
    var label  = mQuery(filterId + ' span.leadlist-filter-name').text();

    //create a new filter
    var li = mQuery("<li />").addClass("padding-sm").text(label).appendTo(mQuery('#leadlist_filters_right'));

    //add a delete button
    mQuery("<i />").addClass("fa fa-fw fa-trash-o remove-selected").prependTo(li).on('click', function() {
        mQuery(this).parent().remove();
    });

    //add a sortable handle
    mQuery("<i />").addClass("fa fa-fw fa-ellipsis-v sortable-handle").prependTo(li);

    var fieldType = mQuery(filterId).find("input.field_type").val();
    var alias     = mQuery(filterId).find("input.field_alias").val();

    //add wrapping div and add the template html

    var container = mQuery('<div />')
        .addClass('filter-container')
        .appendTo(li);

    if (fieldType == 'country' || fieldType == 'timezone') {
        container.html(mQuery('#filter-' + fieldType + '-template').html());
    } else {
        container.html(mQuery('#filter-template').html());
    }
    mQuery(container).find("input[name='leadlist[filters][field][]']").val(alias);
    mQuery(container).find("input[name='leadlist[filters][type][]']").val(fieldType);

    //give the value element a unique id
    var uniqid = "id_" + Date.now();
    var filter = mQuery(container).find("input[name='leadlist[filters][filter][]']");
    filter.attr('id', uniqid);

    //activate fields
    if (fieldType == 'lookup' || fieldType == 'select') {
        var fieldCallback = mQuery(filterId).find("input.field_callback").val();
        if (fieldCallback) {
            var fieldOptions = mQuery(filterId).find("input.field_list").val();
            Mautic[fieldCallback](uniqid, alias, fieldOptions);
        }
    } else if (fieldType == 'datetime') {
        filter.datetimepicker({
            format: 'Y-m-d H:i',
            lazyInit: true,
            validateOnBlur: false,
            allowBlank: true,
            scrollInput: false
        });
    } else if (fieldType == 'date') {
        filter.datetimepicker({
            timepicker: false,
            format: 'Y-m-d',
            lazyInit: true,
            validateOnBlur: false,
            allowBlank: true,
            scrollInput: false,
            closeOnDateSelect: true
        });
    } else if (fieldType == 'time') {
        filter.datetimepicker({
            datepicker: false,
            format: 'H:i',
            lazyInit: true,
            validateOnBlur: false,
            allowBlank: true,
            scrollInput: false
        });
    } else if (fieldType == 'lookup_id' || fieldType == 'boolean') {
        //switch the filter and display elements
        var oldFilter = mQuery(container).find("input[name='leadlist[filters][filter][]']");
        var newDisplay = oldFilter.clone();
        newDisplay.attr('id', uniqid);
        newDisplay.attr('name', 'leadlist[filters][display][]');

        var oldDisplay = mQuery(container).find("input[name='leadlist[filters][display][]']");
        var newFilter = oldDisplay.clone();
        newFilter.attr('id', uniqid + "_id");
        newFilter.attr('name', 'leadlist[filters][filter][]');

        oldFilter.replaceWith(newFilter);
        oldDisplay.replaceWith(newDisplay);

        var fieldCallback = mQuery(filterId).find("input.field_callback").val();
        if (fieldCallback) {
            var fieldOptions = mQuery(filterId).find("input.field_list").val();
            Mautic[fieldCallback](uniqid, alias, fieldOptions);
        }
    } else {
        filter.attr('type', fieldType);
    }
};

Mautic.leadfieldOnLoad = function (container) {

    var fixHelper = function(e, ui) {
        ui.children().each(function() {
            mQuery(this).width(mQuery(this).width());
        });
        return ui;
    };

    if (mQuery(container + ' .leadfield-list').length) {
        mQuery(container + ' .leadfield-list tbody').sortable({
            handle: '.fa-ellipsis-v',
            helper: fixHelper,
            stop: function(i) {
                mQuery.ajax({
                    type: "POST",
                    url: mauticAjaxUrl + "?action=lead:reorder",
                    data: mQuery(container + ' .leadfield-list tbody').sortable("serialize")});
            }
        });
    }

};

/**
 * Update the properties for field data types
 */
Mautic.updateLeadFieldProperties = function(selectedVal) {
    if (mQuery('#field-templates .'+selectedVal).length) {
        mQuery('#leadfield_properties').html(mQuery('#field-templates .'+selectedVal).html());

        mQuery("#leadfield_properties *[data-toggle='tooltip']").tooltip({html: true});
    } else {
        mQuery('#leadfield_properties').html('');
    }

    if (selectedVal == 'time') {
        mQuery('#leadfield_isListable').closest('.row').addClass('hide');
    } else {
        mQuery('#leadfield_isListable').closest('.row').removeClass('hide');
    }
};

Mautic.leadlistOnLoad = function(container) {
    // Shuffle
    // ================================
    var grid   = mQuery("#shuffle-grid"),
        filter = mQuery("#shuffle-filter"),
        sizer  = grid.find("shuffle-sizer");

    // instatiate shuffle
    grid.shuffle({
        itemSelector: ".shuffle",
        sizer: sizer
    });

    // Filter options
    (function () {
        filter.on("keyup change", function () {
            var val = this.value.toLowerCase();
            grid.shuffle("shuffle", function (el, shuffle) {

                // Only search elements in the current group
                if (shuffle.group !== "all" && mQuery.inArray(shuffle.group, el.data("groups")) === -1) {
                    return false;
                }

                var text = mQuery.trim(el.find(".panel-body > h5").text()).toLowerCase();
                return text.indexOf(val) !== -1;
            });
        });
    })();

    // Update shuffle on sidebar minimize/maximize
    mQuery("html")
        .on("fa.sidebar.minimize", function () { grid.shuffle("update"); })
        .on("fa.sidebar.maximize", function () { grid.shuffle("update"); });
};

Mautic.refreshLeadSocialProfile = function(network, leadId, event) {
    Mautic.startIconSpinOnEvent(event);
    var query = "action=lead:updateSocialProfile&network=" + network + "&lead=" + leadId;
    mQuery.ajax({
        url: mauticAjaxUrl,
        type: "POST",
        data: query,
        dataType: "json",
        success: function (response) {
            if (response.success) {
                //loop through each network
                mQuery.each(response.profiles, function( index, value ){
                    if (mQuery('#' + index + 'CompleteProfile').length) {
                        mQuery('#' + index + 'CompleteProfile').html(value.newContent);
                    }
                });
            }
            Mautic.stopIconSpinPostEvent(event);
        },
        error: function (request, textStatus, errorThrown) {
            if (mauticEnv == 'dev') {
                alert(errorThrown);
            }
            Mautic.stopIconSpinPostEvent(event);
        }
    });
}

Mautic.loadRemoteContentToModal = function(elementId) {
    mQuery('#'+elementId).on('loaded.bs.modal', function (e) {
        // take HTML content from JSON and place it back
        var remoteContent = mQuery.parseJSON(e.target.textContent).newContent;
        mQuery(this).find('.modal-content').html(remoteContent);

        // form submit
        mQuery(this).find('form').ajaxForm({
            beforeSubmit: function(formData) {
                // cancel form if cancel button was hit
                var submitForm = true;
                mQuery.each(formData, function( index, value ) {
                    if (value.type === 'submit' && value.name.indexOf('[buttons][cancel]') >= 0) {
                        submitForm = false;
                    }
                });

                if (submitForm) {
                    return true;
                } else {
                    mQuery('#'+elementId).modal('hide');
                }
            }
        });
    });
}<|endoftext|>


<commit_before>function State(params) {
    var state;

    if (this instanceof State) {
        state = this;
    } else {
        state = createObject(State.prototype);
    }

    state._init(params);

    return state;
}

State.prototype = {
    constructor: State,

    _init: function(params) {
        this._params = this._path2object(this._getHash()) || {};

        this.set(params);
    },

    /**
     * Converts slash-slpitted key-value path to object
     *
     * @param {String} path The path (Like: key1/value1/key2/value2)
     *
     * @returns {Object} Object
     */
    _path2object: function(path) {
        var object = {},
            pathParts = path.split('/');

        if (pathParts.length > 1) {
            var key,
                value;

            for (var i = 1; i < pathParts.length; i+=2) {
                key = pathParts[i];
                value = pathParts[i + 1];

                if (key.length) {
                    object[key] = decodeURIComponent(value);
                }
            }
        }

        return object;
    },

    /**
     * Converts object to key-value path
     *
     * @param {String} path The path (Like: key1/value1/key2/value2)
     *
     * @returns {Object} Object
     */
    _object2path: function(object) {
        var path = '!';

        for (var key in object) {
            path = path + '/' + encodeURIComponent(key) + '/' + encodeURIComponent(object[key]);
        }

        return path;
    },

    /**
     * Sets page location hash
     *
     * @param {String} hash
     */
    _setHash: function(hash) {
        window.location.hash = hash;
    },

    /**
     * Returns page location hash
     *
     * @returns {String} The hash string
     */
    _getHash: function() {
        var hash = window.location.hash;

        if (hash.length) {
            return hash.split('!')[1];
        }

        return '';
    },

    /**
     * Sets state
     *
     * @param {Object} params
     *
     * @returns {Object} State object
     *
     */
    set: function(params) {
        _.assign(this._params, params);

        this._setHash(this._object2path(this._params));

        return this._params;
    },

    /**
     * Returns state value by a key
     *
     * @param {[String]} key The key
     *
     * @returns {String|Object} The value
     */
    get: function(key) {
        if (typeof key == 'undefined') {
            return this._params;
        }

        return (key in this._params) ? this._params[key] : null;
    }
};
<commit_msg>State now listen location changes<commit_after>function State(params) {
    var state;

    if (this instanceof State) {
        state = this;
    } else {
        state = createObject(State.prototype);
    }

    state._init(params);

    return state;
}

State.prototype = {
    constructor: State,

    _init: function(params) {
        this._params = this._path2object(this._getHash()) || {};

        this._bindListeners();

        this.set(params);
    },

    _bindListeners: function() {
        var state = this,

            onhashchangeHandler = window.onhashchange;

        window.onhashchange = function() {
            if (onhashchangeHandler instanceof Function) {
                onhashchangeHandler.call(window);
            }

            state.set(state._path2object(state._getHash()));
        };
    },

    /**
     * Converts slash-slpitted key-value path to object
     *
     * @param {String} path The path (Like: key1/value1/key2/value2)
     *
     * @returns {Object} Object
     */
    _path2object: function(path) {
        var object = {},
            pathParts = path.split('/');

        if (pathParts.length > 1) {
            var key,
                value;

            for (var i = 1; i < pathParts.length; i+=2) {
                key = pathParts[i];
                value = pathParts[i + 1];

                if (key.length) {
                    object[key] = decodeURIComponent(value);
                }
            }
        }

        return object;
    },

    /**
     * Converts object to key-value path
     *
     * @param {String} path The path (Like: key1/value1/key2/value2)
     *
     * @returns {Object} Object
     */
    _object2path: function(object) {
        var path = '!';

        for (var key in object) {
            path = path + '/' + encodeURIComponent(key) + '/' + encodeURIComponent(object[key]);
        }

        return path;
    },

    /**
     * Sets page location hash
     *
     * @param {String} hash
     */
    _setHash: function(hash) {
        window.location.hash = hash;
    },

    /**
     * Returns page location hash
     *
     * @returns {String} The hash string
     */
    _getHash: function() {
        var hash = window.location.hash;

        if (hash.length) {
            return hash.split('!')[1];
        }

        return '';
    },

    /**
     * Sets state according to `params`
     *
     * @param {Object} params Key-value object
     *
     * @returns {Object} State object
     *
     */
    set: function(params) {
        _.assign(this._params, params);

        this._setHash(this._object2path(this._params));

        return this._params;
    },

    /**
     * Returns state value by a key
     *
     * @param {[String]} key The key
     *
     * @returns {String|Object} The value
     */
    get: function(key) {
        if (typeof key == 'undefined') {
            return this._params;
        }

        return (key in this._params) ? this._params[key] : null;
    }
};
<|endoftext|>


<commit_before>Template['components_setup'].rendered = function(){
	var template = this;

	//if(LocalStore.get('setup'))
	//	TemplateVar.set(template, 'setup', true);
};

Template['components_setup'].helpers({
	'rpcProvider': function(){
		return LocalStore.get('rpcProvider');
	},
	'ipfsProvider': function(){
		return LocalStore.get('ipfsProvider').host + ':' + LocalStore.get('ipfsProvider').port;
	},
	'defaultAccount': function(){
		if(_.isEmpty(web3.eth.defaultAccount))
			web3.eth.defaultAccount = web3.address(0);

		return web3.eth.defaultAccount;
	},
});

Template['components_setup'].events({
    /**
    Deploy the price feed, used for setup of contract.

    @event (click #setupClient)
    **/

    'click .blur': function(event, template){
		TemplateVar.set(template, 'setup', true);

		// Reroute if on setup
		if(!_.isUndefined(Router.current().route)
		   && Router.current().route._path == '/setup')
			Router.go('/');
	},

    /**
    Deploy the price feed, used for setup of contract.

    @event (click #setupClient)
    **/

    'click #setupClient': function(event, template){
		try {
			var ethereumProvider = Helpers.cleanAscii($('#ethereumProvider').val()),
				ipfsProvider = Helpers.cleanAscii($('#ipfsProvider').val()),
				selectedAccount = Helpers.cleanAscii($('#ethereumAccount').val());
			var ipfsProviderData = ipfsProvider.split(":");
			var ipfsProviderHost = ipfsProviderData[0].replace("http://", "").replace("https://", ""),
				ipfsProviderPort = ipfsProviderData[1],
				testIPFSHash = 'QmekvvCfcQg3LXXtUGeGy3kU4jGwg82txuZtVNRE8BvY9W';

			// Set state
			TemplateVar.set(template, 'state', {isTesting: true, testing: 'Ethereum Provider'});

			// Metamask Support
			if(ethereumProvider != 'metamask')
				web3.setProvider(new web3.providers.HttpProvider(ethereumProvider));

			if(ethereumProvider == 'metamask') {
				LocalStore.set('rpcProvider', 'metamask');
				Router.go('/setup');
			}

			// IPFS Provider
			ipfs.setProvider({host: ipfsProviderHost, port: ipfsProviderPort});

			// Get Ethereum Accounts
			web3.eth.getAccounts(function(err, accounts){
				if(err)
					return TemplateVar.set(template, 'state', {isError: true, error: 'Ethereum Provider: ' + err});

				// Check if there are accounts
				if(accounts.length < 0)
					return TemplateVar.set(template, 'state', {isError: true, error: 'Your Ethereum provider must have accounts'});

				if(selectedAccount == "")
					selectedAccount = accounts[0];

				// set state
				TemplateVar.set(template, 'state', {isTesting: true});

				// try IPFS cat
				try  {
					TemplateVar.set(template, 'state', {isTesting: true, testing: 'IPFS Provider'});

					ipfs.cat(testIPFSHash, function(err, result){
						if(err)
							return TemplateVar.set(template, 'state', {isError: true, error: 'IPFS Provider: ' + err.Message});

						// Testing is Success
						TemplateVar.set(template, 'state', {isSuccess: true});
						LocalStore.set('setup', true);

						// Set Provider LocalStorage
						LocalStore.set('ipfsProvider', {host: ipfsProviderHost, port: ipfsProviderPort});
						LocalStore.set('rpcProvider', ethereumProvider);

						// Set Default Account
						LocalStore.set('defaultAccount', selectedAccount);

						// Shutdown Setup WIndow
						TemplateVar.set(template, 'setup', true);

						// Reroute if on setup
						if(!_.isUndefined(Router.current().route)
		   					&& Router.current().route._path == '/setup')
							Router.go('/');
					});
				}catch(err){
					return TemplateVar.set(template, 'state', {isError: true, error: err});
				}
			});
		}catch(err){
			return TemplateVar.set(template, 'state', {isError: true, error: err});
		}
	}
});<commit_msg>Setup Fix<commit_after>Template['components_setup'].rendered = function(){
	var template = this;

	//if(LocalStore.get('setup'))
	//	TemplateVar.set(template, 'setup', true);
};

Template['components_setup'].helpers({
	'rpcProvider': function(){
		return LocalStore.get('rpcProvider');
	},
	'ipfsProvider': function(){
		return LocalStore.get('ipfsProvider').host + ':' + LocalStore.get('ipfsProvider').port;
	},
	'defaultAccount': function(){
		if(_.isEmpty(web3.eth.defaultAccount))
			web3.eth.defaultAccount = web3.address(0);

		return web3.eth.defaultAccount;
	},
});

Template['components_setup'].events({
    /**
    Deploy the price feed, used for setup of contract.

    @event (click #setupClient)
    **/

    'click .blur': function(event, template){
		TemplateVar.set(template, 'setup', true);

		// Reroute if on setup
		if(!_.isUndefined(Router.current().route)
		   && Router.current().route._path == '/setup')
			Router.go('/');
	},

    /**
    Deploy the price feed, used for setup of contract.

    @event (click #setupClient)
    **/

    'click #setupClient': function(event, template){
		try {
			var ethereumProvider = Helpers.cleanAscii($('#ethereumProvider').val()),
				ipfsProvider = Helpers.cleanAscii($('#ipfsProvider').val()),
				selectedAccount = Helpers.cleanAscii($('#ethereumAccount').val());
			var ipfsProviderData = ipfsProvider.split(":");
			var ipfsProviderHost = ipfsProviderData[0].replace("http://", "").replace("https://", ""),
				ipfsProviderPort = ipfsProviderData[1],
				testIPFSHash = 'QmekvvCfcQg3LXXtUGeGy3kU4jGwg82txuZtVNRE8BvY9W';

			// Set state
			TemplateVar.set(template, 'state', {isTesting: true, testing: 'Ethereum Provider'});

			// Metamask Support
			if(ethereumProvider != 'metamask')
				web3.setProvider(new web3.providers.HttpProvider(ethereumProvider));

			if(ethereumProvider == 'metamask')
				LocalStore.set('rpcProvider', 'metamask');

			// IPFS Provider
			ipfs.setProvider({host: ipfsProviderHost, port: ipfsProviderPort});

			// Get Ethereum Accounts
			web3.eth.getAccounts(function(err, accounts){
				if(err)
					return TemplateVar.set(template, 'state', {isError: true, error: 'Ethereum Provider: ' + err});

				// Check if there are accounts
				if(accounts.length < 0)
					return TemplateVar.set(template, 'state', {isError: true, error: 'Your Ethereum provider must have accounts'});

				if(selectedAccount == "")
					selectedAccount = accounts[0];

				// set state
				TemplateVar.set(template, 'state', {isTesting: true});

				// try IPFS cat
				try  {
					TemplateVar.set(template, 'state', {isTesting: true, testing: 'IPFS Provider'});

					ipfs.cat(testIPFSHash, function(err, result){
						if(err)
							return TemplateVar.set(template, 'state', {isError: true, error: 'IPFS Provider: ' + err.Message});

						// Testing is Success
						TemplateVar.set(template, 'state', {isSuccess: true});
						LocalStore.set('setup', true);

						// Set Provider LocalStorage
						LocalStore.set('ipfsProvider', {host: ipfsProviderHost, port: ipfsProviderPort});
						LocalStore.set('rpcProvider', ethereumProvider);

						// Set Default Account
						LocalStore.set('defaultAccount', selectedAccount);

						// Shutdown Setup WIndow
						TemplateVar.set(template, 'setup', true);

						// Reroute if on setup
						if(!_.isUndefined(Router.current().route)
		   					&& Router.current().route._path == '/setup')
							Router.go('/');
					});
				}catch(err){
					return TemplateVar.set(template, 'state', {isError: true, error: err});
				}
			});
		}catch(err){
			return TemplateVar.set(template, 'state', {isError: true, error: err});
		}
	}
});<|endoftext|>


<commit_before>

import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import ReactCardFlip from 'react-card-flip'
import muiThemeable from 'material-ui/styles/muiThemeable'
import { PICTOGRAMS_URL } from 'services/config'
import IconButton from 'material-ui/IconButton'
import ActionSetFavorite from 'material-ui/svg-icons/action/favorite-border'
import FileDownload from 'material-ui/svg-icons/file/file-download'
import StyledPaper from './StyledPaper'
import Image from './Image'
import Item from './Item'

class PictogramSnippet extends PureComponent {

  state = {
    isFlipped: false
  }

  styles = {
    icon: {
      width: 48,
      height: 48
    },
    leftIconButton: {
      width: 96,
      height: 96,
      padding: 24,
      position: 'absolute',
      top: '0',
      left: '0'
    },
    rightIconButton: {
      width: 96,
      height: 96,
      padding: 24,
      position: 'absolute',
      top: '0',
      right: '0'
    },
    cardTitle: {
      textAlign: 'center',
      fontSize: '1.4rem',
      textTransform: 'uppercase',
      color: this.props.muiTheme.appBar.textColor,
      fontWeight: '900'
    },
    cardContainer: {
      position: 'absolute',
      top: '0',
      button: '0',
      opacity: '0.93',
      width: '250px',
      height: '250px',
      backgroundColor: this.props.muiTheme.palette.primary1Color,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center'
    }
  }

  handleMouseEnter = () => {
    this.setState({
      isFlipped: true,
      zDepth: 3
    })
  }

  handleMouseLeave = () => {
    this.setState({
      isFlipped: false,
      zDepth: 1
    })
  }

  render() {
    const { pictogram, searchText, muiTheme } = this.props
    const searchTextArray = searchText.split(' ')
    let keywordSelector = pictogram.keywords.find(
      (keywordsItem) => {

        const keywordArray = keywordsItem.keyword.split(' ')
        const found = searchTextArray.some(
          (word) => keywordArray.includes(word)
        )
        return found
      }
    )
    if (!keywordSelector) keywordSelector = pictogram.keywords[0]
    return (

        <ReactCardFlip isFlipped={this.state.isFlipped}>

        </ReactCardFlip>

    )
  }
}

PictogramSnippet.propTypes = {
  pictogram: PropTypes.object.isRequired,
  searchText: PropTypes.string,
  muiTheme: PropTypes.object
}

export default muiThemeable()(PictogramSnippet)
<commit_msg>remove touch event<commit_after>

import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import ReactCardFlip from 'react-card-flip'
import muiThemeable from 'material-ui/styles/muiThemeable'
import { PICTOGRAMS_URL } from 'services/config'
import IconButton from 'material-ui/IconButton'
import ActionSetFavorite from 'material-ui/svg-icons/action/favorite-border'
import FileDownload from 'material-ui/svg-icons/file/file-download'
import withWidth, { SMALL } from 'material-ui/utils/withWidth'
import StyledPaper from './StyledPaper'
import Image from './Image'
import Item from './Item'

class PictogramSnippet extends PureComponent {

  state = {
    isFlipped: false
  }

  styles = {
    icon: {
      width: 48,
      height: 48
    },
    leftIconButton: {
      width: 96,
      height: 96,
      padding: 24,
      position: 'absolute',
      top: '0',
      left: '0'
    },
    rightIconButton: {
      width: 96,
      height: 96,
      padding: 24,
      position: 'absolute',
      top: '0',
      right: '0'
    },
    cardTitle: {
      textAlign: 'center',
      fontSize: '1.4rem',
      textTransform: 'uppercase',
      color: this.props.muiTheme.appBar.textColor,
      fontWeight: '900'
    },
    cardContainer: {
      position: 'absolute',
      top: '0',
      button: '0',
      opacity: '0.93',
      width: '250px',
      height: '250px',
      backgroundColor: this.props.muiTheme.palette.primary1Color,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center'
    }
  }

  handleMouseEnter = () => {
    this.setState({
      isFlipped: true,
      zDepth: 3
    })
  }

  handleMouseLeave = () => {
    this.setState({
      isFlipped: false,
      zDepth: 1
    })
  }

  handleTouchStart = () => {
    this.setState({
      isFlipped: !this.state.isFlipped
    })
  }

  render() {
    const { pictogram, searchText, muiTheme, width } = this.props
    const isSmall = SMALL === width
    const searchTextArray = searchText.split(' ')
    let keywordSelector = pictogram.keywords.find(
      (keywordsItem) => {

        const keywordArray = keywordsItem.keyword.split(' ')
        const found = searchTextArray.some(
          (word) => keywordArray.includes(word)
        )
        return found
      }
    )
    if (!keywordSelector) keywordSelector = pictogram.keywords[0]
    return (

        <ReactCardFlip isFlipped={this.state.isFlipped}>

        </ReactCardFlip>

    )
  }
}

PictogramSnippet.propTypes = {
  pictogram: PropTypes.object.isRequired,
  searchText: PropTypes.string,
  muiTheme: PropTypes.object,
  width: PropTypes.number.isRequired
}

export default withWidth()(muiThemeable()(PictogramSnippet))
<|endoftext|>