<commit_before>const { darken } = require('postcss-js-mixins/lib/colorHelpers');

let variables = {};

variables.unit = {
	default: 'rem',
	fontSize: 'rem',
	lineHeight: 'em'
};

variables.root = {
	fontSize: '62.5%'
};

variables.default = {
	radius: '3px',
	opacity: 0.2,
	duration: '0.2s',
	timing: 'ease-in-out',
	delay: '0s'
};

variables.width = {
	min: 0,
	max: '1280px'
};

variables.bumper = {
	enabled: true,
	padding: '6%'
};

variables.block = {
	margin: {
		bottom: '4rem'
	}
};

variables.grid = {
	margin: '5%',
	columns: 8,
	spaceless: false
};

variables.colors = {
	primary: '#349bb9',
	secondary: '#70c1b3',
	tertiary: '#f18f01',
	info: '#00f',
	success: '#008000',
	warning: '#f00',
	white: '#fff',
	lightestGray: darken('#fff', 4),
	lighterGray: darken('#fff', 10),
	lightGray: darken('#fff', 25),
	gray: darken('#fff', 35),
	darkGray: darken('#fff', 55),
	darkerGray: darken('#fff', 65),
	darkestGray: darken('#fff', 75),
	black: '#000'
};

variables.colors.body = {
	background: variables.colors.white
};

variables.font = {
	color: variables.colors.darkestGray,
	family: 'Arial, Helvetica, sans-serif',
	size: '1.6rem',
	weight: {
		normal: 'normal',
		bold: 'bold'
	},
	lineHeight: '1em'
};

variables.heading = {
	color: variables.font.color,
	family: 'Tahoma, Geneva, sans-serif',
	weight: variables.font.weight.bold,
	lineHeight: '1.4em',
	margin: {
		bottom: '2rem'
	}
};

variables.h1 = '3.6rem';
variables.h2 = '3.2rem';
variables.h3 = '2.8rem';
variables.h4 = '2.4rem';
variables.h5 = '2rem';
variables.h6 = '1.6rem';

variables.mark = {
	color: variables.font.color,
	background: 'yellow'
};

variables.abbr = {
	underline: 'dotted'
};

variables.border = {
	color: variables.colors.lightGray,
	style: 'solid',
	width: '1px'
};

variables.paragraph = {
	color: variables.font.color,
	weight: variables.font.weight.normal,
	lineHeight: '1.7em',
	margin: {
		bottom: '2rem'
	}
};

variables.figure = {
	border: {
		color: false,
		radius: false
	},
	padding: variables.block.margin.bottom
};

variables.figCaption = {
	color: variables.colors.darkGray,
	style: 'italic',
	lineHeight: variables.paragraph.lineHeight
};

variables.link = {
	color: variables.colors.primary,
	decoration: 'none'
};

variables.link.hover = {
	color: darken(variables.link.color, 10),
	decoration: 'none'
};

variables.link.active = {
	color: darken(variables.link.color, 20)
};

variables.selection = {
	color: variables.colors.white,
	background: variables.link.color
};

variables.small = {
	size: '0.8em'
};

variables.quote = {
	color: variables.colors.darkestGray,
	family: 'Georgia, Times, serif',
	size: '2rem',
	style: 'italic',
	weight: 'normal',
	lineHeight: '1.4em',
	padding: {
		horizontal: '2em',
		vertical: '1em'
	}
};

variables.cite = {
	color: variables.colors.gray,
	family: variables.font.family,
	size: '1.8rem',
	style: 'normal',
	weight: 'normal',
	lineHeight: '1.2em',
	margin: {
		top: '1.4rem'
	},
	indicator: "'\\2014\\00a0'"
};

variables.rule = {
	color: variables.colors.lightGray,
	height: '1px',
	style: 'solid',
	margin: {
		vertical: variables.block.margin.bottom
	}
};

variables.address = {
	color: variables.colors.darkestGray,
	family: variables.font.family,
	size: variables.font.size,
	weight: 'normal',
	style: 'normal',
	lineHeight: variables.paragraph.lineHeight
};

variables.list = {
	color: variables.paragraph.color,
	lineHeight: variables.paragraph.lineHeight,
	margin: {
		bottom: variables.paragraph.margin.bottom,
		left: false
	},
	bullet: {
		style: 'disc',
		position: 'inside'
	}
};

variables.nestedList = {
	margin: {
		left: '2rem'
	}
};

variables.li = {
	margin: {
		bottom: '0.2rem'
	}
};

variables.dl = {
	margin: {
		bottom: variables.block.margin.bottom
	}
};

variables.dt = {
	color: variables.colors.darkerGray,
	family: variables.heading.family,
	size: '2rem',
	margin: {
		bottom: '0.2rem'
	}
};

variables.dd = {
	color: variables.colors.gray,
	family: variables.font.family,
	size: variables.font.size,
	margin: {
		bottom: '1rem'
	}
};

variables.print = {
	page: {
		margin: '2cm .5cm'
	}
};

variables.button = {
	color: variables.colors.white,
	family: variables.font.family,
	size: variables.font.size,
	weight: 'normal',
	padding: {
		horizontal: '3rem',
		vertical: '1.3rem'
	},
	margin: {
		bottom: 0
	},
	transition: {
		property: 'background-color',
		duration: '0.2s'
	},
	background: variables.colors.darkGray,
	border: {
		color: false,
		radius: variables.default.radius,
		width: 0
	}
};

variables.button.hover = {
	background: darken(variables.button.background, 5)
};

variables.button.active = {
	background: darken(variables.button.background, 10),
	transition: {
		property: 'none'
	}
};

variables.coloredButton = {
	class: '.colored-button',
	color: variables.colors.white,
	background: variables.link.color,
	border: {
		color: false,
		radius: variables.button.border.radius,
		width: variables.button.border.width
	}
};

variables.coloredButton.hover = {
	background: darken(variables.coloredButton.background, 5)
};

variables.coloredButton.active = {
	background: darken(variables.coloredButton.background, 10)
};

variables.button.disabled = {
	modifier: '.-is-disabled',
	color: variables.colors.darkGray,
	background: variables.colors.lightGray,
	border: {
		color: false
	},
	cursor: 'not-allowed'
};

variables.code = {
	color: variables.colors.darkestGray,
	family: 'monospace',
	size: variables.font.size,
	lineHeight: '1.4em',
	background: variables.colors.lighterGray,
	border: {
		color: false,
		radius: false
	},
	padding: {
		horizontal: '0.5em',
		vertical: '0.2em'
	},
	rounded: false
};

variables.code.block = {
	color: variables.colors.lightestGray,
	family: variables.code.family,
	size: '1.3rem',
	lineHeight: variables.paragraph.lineHeight,
	tabSize: 4,
	wrap: false,
	margin: {
		bottom: variables.block.margin.bottom
	},
	background: variables.colors.darkestGray,
	border: {
		color: variables.code.border.color,
		radius: false
	},
	padding: {
		horizontal: '2rem',
		vertical: '1.4rem'
	},
	rounded: false
};

variables.input = {
	cursorDisabled: 'not-allowed',
	background: {
		disabled: variables.colors.lightestGray
	},
	color: {
		disabled: variables.colors.darkerGray
	},
	font: {
		family: variables.font.family,
		size: variables.font.size,
		weight: variables.font.weight
	},
	padding: {
		horizontal: '1.6rem',
		vertical: '1rem'
	}
};

variables.legend = {
	color: variables.colors.darkerGray,
	family: variables.font.family,
	size: '1.8rem',
	spacing: '1.4rem'
};

variables.label = {
	weight: 'normal',
	lineHeight: '1.3em',
	margin: {
		bottom: '.4rem',
		right: '1rem'
	}
};

variables.checkbox = {
	margin: {
		bottom: '1rem',
		right: '.5rem'
	}
};

variables.multiSelect = {
	minHeight: '8rem'
};

variables.textarea = {
	lineHeight: '1.3em',
	minHeight: '8rem',
	resize: 'vertical',
	padding: {
		horizontal: '1.6rem',
		vertical: '1rem'
	}
};

variables.table = {
	size: variables.font.size,
	cell: {
		borderColor: variables.colors.lighterGray,
		lineHeight: variables.paragraph.lineHeight,
		padding: {
			horizontal: '1.6rem',
			vertical: '.6rem'
		}
	},
	striped: {
		background: variables.colors.lightestGray,
		position: 'odd'
	}
};

variables.table.caption = {
	background: variables.colors.lightestGray,
	style: 'italic',
	padding: {
		horizontal: variables.table.cell.padding.horizontal,
		vertical: '1.2rem'
	}
};

module.exports = variables;<commit_msg>Add input variables<commit_after>const { darken } = require('postcss-js-mixins/lib/colorHelpers');

let variables = {};

variables.unit = {
	default: 'rem',
	fontSize: 'rem',
	lineHeight: 'em'
};

variables.root = {
	fontSize: '62.5%'
};

variables.default = {
	radius: '3px',
	opacity: 0.2,
	duration: '0.2s',
	timing: 'ease-in-out',
	delay: '0s'
};

variables.width = {
	min: 0,
	max: '1280px'
};

variables.bumper = {
	enabled: true,
	padding: '6%'
};

variables.block = {
	margin: {
		bottom: '4rem'
	}
};

variables.grid = {
	margin: '5%',
	columns: 8,
	spaceless: false
};

variables.colors = {
	primary: '#349bb9',
	secondary: '#70c1b3',
	tertiary: '#f18f01',
	info: '#00f',
	success: '#008000',
	warning: '#f00',
	white: '#fff',
	lightestGray: darken('#fff', 4),
	lighterGray: darken('#fff', 10),
	lightGray: darken('#fff', 25),
	gray: darken('#fff', 35),
	darkGray: darken('#fff', 55),
	darkerGray: darken('#fff', 65),
	darkestGray: darken('#fff', 75),
	black: '#000'
};

variables.colors.body = {
	background: variables.colors.white
};

variables.font = {
	color: variables.colors.darkestGray,
	family: 'Arial, Helvetica, sans-serif',
	size: '1.6rem',
	weight: {
		normal: 'normal',
		bold: 'bold'
	},
	lineHeight: '1em'
};

variables.heading = {
	color: variables.font.color,
	family: 'Tahoma, Geneva, sans-serif',
	weight: variables.font.weight.bold,
	lineHeight: '1.4em',
	margin: {
		bottom: '2rem'
	}
};

variables.h1 = '3.6rem';
variables.h2 = '3.2rem';
variables.h3 = '2.8rem';
variables.h4 = '2.4rem';
variables.h5 = '2rem';
variables.h6 = '1.6rem';

variables.mark = {
	color: variables.font.color,
	background: 'yellow'
};

variables.abbr = {
	underline: 'dotted'
};

variables.border = {
	color: variables.colors.lightGray,
	style: 'solid',
	width: '1px'
};

variables.paragraph = {
	color: variables.font.color,
	weight: variables.font.weight.normal,
	lineHeight: '1.7em',
	margin: {
		bottom: '2rem'
	}
};

variables.figure = {
	border: {
		color: false,
		radius: false
	},
	padding: variables.block.margin.bottom
};

variables.figCaption = {
	color: variables.colors.darkGray,
	style: 'italic',
	lineHeight: variables.paragraph.lineHeight
};

variables.link = {
	color: variables.colors.primary,
	decoration: 'none'
};

variables.link.hover = {
	color: darken(variables.link.color, 10),
	decoration: 'none'
};

variables.link.active = {
	color: darken(variables.link.color, 20)
};

variables.selection = {
	color: variables.colors.white,
	background: variables.link.color
};

variables.small = {
	size: '0.8em'
};

variables.quote = {
	color: variables.colors.darkestGray,
	family: 'Georgia, Times, serif',
	size: '2rem',
	style: 'italic',
	weight: 'normal',
	lineHeight: '1.4em',
	padding: {
		horizontal: '2em',
		vertical: '1em'
	}
};

variables.cite = {
	color: variables.colors.gray,
	family: variables.font.family,
	size: '1.8rem',
	style: 'normal',
	weight: 'normal',
	lineHeight: '1.2em',
	margin: {
		top: '1.4rem'
	},
	indicator: "'\\2014\\00a0'"
};

variables.rule = {
	color: variables.colors.lightGray,
	height: '1px',
	style: 'solid',
	margin: {
		vertical: variables.block.margin.bottom
	}
};

variables.address = {
	color: variables.colors.darkestGray,
	family: variables.font.family,
	size: variables.font.size,
	weight: 'normal',
	style: 'normal',
	lineHeight: variables.paragraph.lineHeight
};

variables.list = {
	color: variables.paragraph.color,
	lineHeight: variables.paragraph.lineHeight,
	margin: {
		bottom: variables.paragraph.margin.bottom,
		left: false
	},
	bullet: {
		style: 'disc',
		position: 'inside'
	}
};

variables.nestedList = {
	margin: {
		left: '2rem'
	}
};

variables.li = {
	margin: {
		bottom: '0.2rem'
	}
};

variables.dl = {
	margin: {
		bottom: variables.block.margin.bottom
	}
};

variables.dt = {
	color: variables.colors.darkerGray,
	family: variables.heading.family,
	size: '2rem',
	margin: {
		bottom: '0.2rem'
	}
};

variables.dd = {
	color: variables.colors.gray,
	family: variables.font.family,
	size: variables.font.size,
	margin: {
		bottom: '1rem'
	}
};

variables.print = {
	page: {
		margin: '2cm .5cm'
	}
};

variables.button = {
	color: variables.colors.white,
	family: variables.font.family,
	size: variables.font.size,
	weight: 'normal',
	padding: {
		horizontal: '3rem',
		vertical: '1.3rem'
	},
	margin: {
		bottom: 0
	},
	transition: {
		property: 'background-color',
		duration: '0.2s'
	},
	background: variables.colors.darkGray,
	border: {
		color: false,
		radius: variables.default.radius,
		width: 0
	}
};

variables.button.hover = {
	background: darken(variables.button.background, 5)
};

variables.button.active = {
	background: darken(variables.button.background, 10),
	transition: {
		property: 'none'
	}
};

variables.coloredButton = {
	class: '.colored-button',
	color: variables.colors.white,
	background: variables.link.color,
	border: {
		color: false,
		radius: variables.button.border.radius,
		width: variables.button.border.width
	}
};

variables.coloredButton.hover = {
	background: darken(variables.coloredButton.background, 5)
};

variables.coloredButton.active = {
	background: darken(variables.coloredButton.background, 10)
};

variables.button.disabled = {
	modifier: '.-is-disabled',
	color: variables.colors.darkGray,
	background: variables.colors.lightGray,
	border: {
		color: false
	},
	cursor: 'not-allowed'
};

variables.code = {
	color: variables.colors.darkestGray,
	family: 'monospace',
	size: variables.font.size,
	lineHeight: '1.4em',
	background: variables.colors.lighterGray,
	border: {
		color: false,
		radius: false
	},
	padding: {
		horizontal: '0.5em',
		vertical: '0.2em'
	},
	rounded: false
};

variables.code.block = {
	color: variables.colors.lightestGray,
	family: variables.code.family,
	size: '1.3rem',
	lineHeight: variables.paragraph.lineHeight,
	tabSize: 4,
	wrap: false,
	margin: {
		bottom: variables.block.margin.bottom
	},
	background: variables.colors.darkestGray,
	border: {
		color: variables.code.border.color,
		radius: false
	},
	padding: {
		horizontal: '2rem',
		vertical: '1.4rem'
	},
	rounded: false
};

variables.input = {
	background: variables.colors.white,
	cursorDisabled: 'not-allowed',
	color: variables.colors.darkerGray,
	spacing: '2rem',
	font: {
		family: variables.font.family,
		size: variables.font.size,
		weight: variables.font.weight
	},
	padding: {
		horizontal: '1.6rem',
		vertical: '1rem'
	}
};

variables.disabledInput = {
	background: variables.colors.lightestGray,
	color: variables.colors.darkerGray
};

variables.invalidInput = {
	background: variables.colors.white,
	border: {
		color: '#a41818',
		width: '1px' // false to disable
	}
};

variables.invalidInput.color = darken($invalidInput.border.color, 10%);

variables.invalidInput.focus = {
	border: {
		color: darken($invalidInput.border.color, 10%)
	}
};

variables.invalidInput.hover = {
	border: {
		color: darken($invalidInput.border.color, 20%)
	}
};

variables.requiredInput = {
	border: {
		color: variables.colors.darkerGray,
		width: '1px' // false to disable
	}
};

variables.requiredInput.color = darken($requiredInput.border.color, 10%);

variables.legend = {
	color: variables.colors.darkerGray,
	family: variables.font.family,
	size: '1.8rem',
	spacing: '1.4rem'
};

variables.label = {
	weight: 'normal',
	lineHeight: '1.3em',
	margin: {
		bottom: '.4rem',
		right: '1rem'
	}
};

variables.checkbox = {
	margin: {
		bottom: '1rem',
		right: '.5rem'
	}
};

variables.multiSelect = {
	minHeight: '8rem'
};

variables.textarea = {
	lineHeight: '1.3em',
	minHeight: '8rem',
	resize: 'vertical',
	padding: {
		horizontal: '1.6rem',
		vertical: '1rem'
	}
};

variables.table = {
	size: variables.font.size,
	cell: {
		borderColor: variables.colors.lighterGray,
		lineHeight: variables.paragraph.lineHeight,
		padding: {
			horizontal: '1.6rem',
			vertical: '.6rem'
		}
	},
	striped: {
		background: variables.colors.lightestGray,
		position: 'odd'
	}
};

variables.table.caption = {
	background: variables.colors.lightestGray,
	style: 'italic',
	padding: {
		horizontal: variables.table.cell.padding.horizontal,
		vertical: '1.2rem'
	}
};

module.exports = variables;<|endoftext|>


<commit_before>
/*

  Compile.js

*/

var _           = require("lodash"),
    Bundler     = require("./bundler"),
    express     = require("express"),
    Metadata    = require("./metadata"),
    Motors      = global.engines,
    Promise     = require("bluebird"),
    Utils       = require("./utils");

function createDataQuery(queries) {
  return function(context) {
    data = (queries) ? global.db.queries(queries, context) : {};
    return Promise.resolve(_.assign({}, global.vars, context, data));
  }
}

function sequence(tasks, initial) {
  return Promise.reduce(tasks || [], function(val, task) {
    return task(val);
  }, initial);
}

function addFile(router, route, file, type, basePath) {

    var tasks = [],
        metadata = {};

    // Add to list of extensions if not present
    if (!Motors.hasEngine(file.ext)) Motors.addEngine(file.ext);

    // Extract metadata
    if ("html" === type) {
      metadata = Metadata.extract(Utils.readFileHead(file.path, 500));
      tasks.push(createDataQuery(metadata.data));
    }

    // File compilation function
    if (file.bundle)
      tasks.push(Bundler.fromFile(file, type).get);
    else
      tasks.push(Promise.promisify(Motors.compileFile.bind(Motors, file.path)));

    // Route handling function
    function handler(req, res) {

      // Set cookies
      for (var key in metadata.cookies || {})
        res.cookie(key, metadata.cookies[key]);

      // Set session
      for (var key in metadata.session || {})
        req.session[key] = metadata.session[key];

      sequence(tasks, req.params)
      .then(res.type(type).send.bind(res))
      .catch(function(err) { console.log(err); res.sendStatus(500); });

    }

    // Add routes to router
    Utils.makeRoutes(route, file, { type : type, query : metadata.query }).forEach(function(r) {
      router.get(r, handler);
    });

}

module.exports = function(options) {

  var router = express(),
      files  = Utils.mapFiles(options.path, options),
      exts   = {};

  files.forEach(function(file) {
    addFile(router, options.route, file, options.ext);
    if (!exts[file.ext]) exts[file.ext] = Utils.watch(options.path, file.ext, options.ext);
  });

  return router;

};

<commit_msg>compiler: removes lodash dependency<commit_after>
/*

  Compile.js

*/

var Bundler     = require("./bundler"),
    express     = require("express"),
    Metadata    = require("./metadata"),
    Motors      = global.engines,
    Promise     = require("bluebird"),
    Utils       = require("./utils");

function createDataQuery(queries) {
  return function(context) {
    data = (queries) ? global.db.queries(queries, context) : {};
    return Promise.resolve(Object.assign({}, global.vars, context, data));
  }
}

function sequence(tasks, initial) {
  return Promise.reduce(tasks || [], function(val, task) {
    return task(val);
  }, initial);
}

function addFile(router, route, file, type, basePath) {

    var tasks = [],
        metadata = {};

    // Add to list of extensions if not present
    if (!Motors.hasEngine(file.ext)) Motors.addEngine(file.ext);

    // Extract metadata
    if ("html" === type) {
      metadata = Metadata.extract(Utils.readFileHead(file.path, 500));
      tasks.push(createDataQuery(metadata.data));
    }

    // File compilation function
    if (file.bundle)
      tasks.push(Bundler.fromFile(file, type).get);
    else
      tasks.push(Promise.promisify(Motors.compileFile.bind(Motors, file.path)));

    // Route handling function
    function handler(req, res) {

      // Set cookies
      for (var key in metadata.cookies || {})
        res.cookie(key, metadata.cookies[key]);

      // Set session
      for (var key in metadata.session || {})
        req.session[key] = metadata.session[key];

      sequence(tasks, req.params)
      .then(res.type(type).send.bind(res))
      .catch(function(err) { console.log(err); res.sendStatus(500); });

    }

    // Add routes to router
    Utils.makeRoutes(route, file, { type : type, query : metadata.query }).forEach(function(r) {
      router.get(r, handler);
    });

}

module.exports = function(options) {

  var router = express(),
      files  = Utils.mapFiles(options.path, options),
      exts   = {};

  files.forEach(function(file) {
    addFile(router, options.route, file, options.ext);
    if (!exts[file.ext]) exts[file.ext] = Utils.watch(options.path, file.ext, options.ext);
  });

  return router;

};

<|endoftext|>


<commit_before>var Vault=(function(){var _parse=function(_value){if(_value===null||_value===undefined){return undefined;}if(_value==="true"){return true;}if(_value==="false"){return false;}if(!isNaN(_value)){return parseFloat(_value);}if(_value.indexOf&&(_value.indexOf("{")===0||_value.indexOf("[")===0)){if(window.JSON!==undefined){return JSON.parse(_value);}else{return eval("("+_value+")");}}return _value;};var _prepare=function(_value){if(typeof _value==="object"&&window.JSON!==undefined){return JSON.stringify(_value);}return _value;};var _notSupported=function(){return undefined;};var _setup=function(_type){var _storage=window[_type];if(_storage===undefined){return{get:_notSupported,set:_notSupported,remove:_notSupported,clear:_notSupported,list:_notSupported,isSupported:function(){return false;}}}return{get:function(_key){var _value=_storage[_key];return _parse(_value);},set:function(_key,_value){return _storage.setItem(_key,_prepare(_value));},remove:function(_key){return _storage.removeItem(_key);},clear:function(){return _storage.clear();},list:function(){var i,il=_storage.length;if(il===0){console.log("0 items in "+_type);return undefined;}for(i in _storage){console.log(i,"=",_parse(_storage[i]));}},isSupported:function(){return true;}}};var _cookie={get:function(_cookie){var _cookies=document.cookie.split(";");var c,cl=_cookies.length;for(c=0;c<cl;c++){var _pair=_cookies[c].split("=");_pair[0]=_pair[0].replace(/^[ ]/,"");if(_pair[0]===_cookie){return _parse(_pair[1]);}}return undefined;},set:function(_key,_value,_days,_path){var _expires="";if(_days!==undefined){var _date=new Date();_date.setDate(_date.getDate()+_days);_expires="; expires="+_date.toUTCString();}var _value=_prepare(_value)+_expires+(_path===undefined?"":"; path="+_path);document.cookie=_key+"="+_value;},remove:function(_key){this.set(_key,"",-1);},clear:function(){var _cookies=document.cookie.split(";");var c,cl=_cookies.length;for(c=0;c<cl;c++){var _pair=_cookies[c].split("=");_pair[0]=_pair[0].replace(/^[ ]/,"");this.set(_pair[0],"",-1);}},list:function(){var _cookies=document.cookie.split(";");var c,cl=_cookies.length;if(cl===0){console.log("No cookies set");return undefined;}for(c=0;c<cl;c++){var _pair=_cookies[c].split("=");_pair[0]=_pair[0].replace(/^[ ]/,"");console.log(_pair[0],"=",_parse(_pair[1]));}}};return{Local:_setup("localStorage"),Session:_setup("sessionStorage"),Cookie:_cookie};}());
<commit_msg>creating minified version<commit_after>
var Vault=(function(){var _parse=function(_value){if(_value===null||_value===undefined){return undefined;}
if(_value==="true"){return true;}
if(_value==="false"){return false;}
if(!isNaN(_value)){return parseFloat(_value);}
if(_value.indexOf&&(_value.indexOf("{")===0||_value.indexOf("[")===0)&&window.JSON!==undefined){return JSON.parse(_value);}
return _value;};var _prepare=function(_value){if(typeof _value==="object"&&window.JSON!==undefined){return JSON.stringify(_value);}
return _value;};var _notSupported=function(){return undefined;};var _prepareSqlValue=function(_value){if(isNaN(_value)&&_value.indexOf('"')<0){_value='"'+_value+'"';}
return _value;};var _parseKeyValueList=function(_pair){var _key,_fields=[],_values=[];for(_key in _pair){if(!_key.match(/^\_/)){_fields.push(_key);_values.push(_prepareSqlValue(_pair[_key]));}}
return{fields:_fields,values:_values};};var _setup=function(_type){var _storage=window[_type];if(_storage===undefined){return{get:_notSupported,set:_notSupported,remove:_notSupported,clear:_notSupported,list:_notSupported,isSupported:function(){return false;}}}
return{get:function(_key){var _value=_storage[_key];return _parse(_value);},set:function(_key,_value){return _storage.setItem(_key,_prepare(_value));},remove:function(_key){return _storage.removeItem(_key);},clear:function(){return _storage.clear();},list:function(){var i,il=_storage.length;if(il===0){console.log("0 items in "+_type);return undefined;}
for(i in _storage){console.log(i,"=",_parse(_storage[i]));}},isSupported:function(){return true;}}};var __db__=undefined;var _db={open:function(_name,_version,_display_name,_size){__db__=openDatabase(_name,_version,_display_name,_size);return __db__;},createTable:function(_name,_fields){var _sql='CREATE TABLE IF NOT EXISTS '+_name+' ('+_fields+')';this.sql(_sql);},dropTable:function(_name){var _sql='DROP TABLE '+_name;this.sql(_sql);},set:function(_args){var _table;for(_table in _args){var _values=_args[_table];var i,il=_values.length;for(i=0;i<il;i++){var _set=_values[i];var _pairs=_parseKeyValueList(_set);if(_set._where!==undefined){var _where=_parseKeyValueList(_set._where);var j,jl=_pairs.fields.length,_updates=[];for(j=0;j<jl;j++){_updates.push(_pairs.fields[j]+'='+_pairs.values[j]);}
var _sql='UPDATE '+_table+' SET '+_updates.join(",")+' WHERE '+_where.fields+'='+_where.values;}else if(_set._delete!==undefined){var _delete=_parseKeyValueList(_set._delete);var _sql='DELETE FROM '+_table+' WHERE '+_delete.fields+'='+_delete.values;}else{var _sql='INSERT INTO '+_table+' ('+_pairs.fields+') VALUES ('+_pairs.values+')';}
this.sql(_sql);}}},get:function(_args,_success){var _sql=[];var _table;for(_table in _args){var _fields=_args[_table];_sql.push('SELECT '+_fields+' FROM '+_table);}
_sql=_sql.join(",");this.sql(_sql,_success);},clear:function(_table){var _sql='DELETE * FROM '+_table;this.sql(_sql);},sql:function(_query,_success){if(__db__===undefined){console.warn("No DB open. Open with:\nVault.DB.open(_name, _version, _display_name, _size);");return false;}
_success=_success||function(){};console.warn(_query);__db__.transaction(function(_tx){return _tx.executeSql(_query,[],function(_tx,_results){_success(_results.rows);});});}};var _cookie={get:function(_cookie){var _cookies=document.cookie.split(";");var c,cl=_cookies.length;for(c=0;c<cl;c++){var _pair=_cookies[c].split("=");_pair[0]=_pair[0].replace(/^[ ]/,"");if(_pair[0]===_cookie){return _parse(_pair[1]);}}
return undefined;},set:function(_key,_value,_days,_path){var _expires="";if(_days!==undefined){var _date=new Date();_date.setDate(_date.getDate()+_days);_expires="; expires="+_date.toUTCString();}
var _value=_prepare(_value)+_expires+(_path===undefined?"":"; path="+_path);document.cookie=_key+"="+_value;},remove:function(_key){this.set(_key,"",-1);},clear:function(){var _cookies=document.cookie.split(";");var c,cl=_cookies.length;for(c=0;c<cl;c++){var _pair=_cookies[c].split("=");_pair[0]=_pair[0].replace(/^[ ]/,"");this.set(_pair[0],"",-1);}},list:function(){var _cookies=document.cookie.split(";");var c,cl=_cookies.length;if(cl===0){console.log("No cookies set");return undefined;}
for(c=0;c<cl;c++){var _pair=_cookies[c].split("=");_pair[0]=_pair[0].replace(/^[ ]/,"");console.log(_pair[0],"=",_parse(_pair[1]));}}};return{Local:_setup("localStorage"),Session:_setup("sessionStorage"),DB:_db,Cookie:_cookie};}());var local_storage=Vault.Local;<|endoftext|>


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

var exec = require("child_process").exec;
var spawn = require("child_process").spawn;
var path = require("path");
var fs = require("fs");
var util = require("util");

var Promise = require("./lib/promise");

var DEBUG = true;

// Some standard helpers

function debug() {
    var args;
    if(DEBUG) {
        args = Array.prototype.slice.call(arguments, 0);
        args.unshift("DEBUG:");

        console.log.apply(this, args);
    }
}

function die(message, exception) {
    if(exception) {
        message += ": " + exception.message;
    }

    console.log(message);

    if(DEBUG) {
        throw exception;
    }

    process.exit(1);
}

function help() {
    console.log("usage: git aux <command> [<args>]");
    console.log();
    console.log("Commands:");
    console.log("init <basedir>   Initialise git aux to use the chosen directory");
    console.log("add <file(s)>    Add the chosen file (from basedir) to the repository");
    console.log("sync             Import changes to tracked files in basedir into the repository");
    console.log("apply            Apply changes from the repository into the basedir");
    console.log();
}

function get_git_root() {
    var promise = new Promise();

    exec("git rev-parse --show-toplevel", function(err, stdout, stderr) {
        if(err) {
            console.log("Not a git repository");
            process.exit(1);
        }

        home = stdout.trim();

        promise.fulfill(home);
    });

    return promise;
}

function get_config(git_root) {
    var promise = new Promise();

    fs.readFile(path.join(git_root, ".git", "aux", "config.json"), "utf8", function(err, data) {
        if(err) {
            promise.fulfill(null);
            debug("No config");
        } else {
            try {
                data = JSON.parse(data);
                promise.fulfill(data);
            } catch(e) {
                die("Unable to parse git aux config", e);
            }
        }
    });

    return promise;
}

function save_config(git_root, config) {
    var promise = new Promise();

    fs.writeFile(path.join(git_root, ".git", "aux", "config.json"), JSON.stringify(config, null, 2), function(err) {
        if(err) {
            die("Unable to save config", err);
        }

        promise.fulfill();
    });

    return promise;
}

function mkdir(dir) {
    var promise = new Promise();

    debug("Making dir:", dir);

    fs.mkdir(dir, function(err) {
        if(err) {
            if(err.code === "ENOENT") {
                mkdir(path.dirname(dir)).then(function() {
                    mkdir(dir).then(promise.fulfill);
                });
            } else if(err.code === "EEXIST") {
                promise.fulfill();
            } else {
                die("Error creating directory", err);
            }
        } else {
            promise.fulfill();
        }
    });

    return promise;
}

// Git aux commands

function init(git_root, basedir) {
    // Make git aux directory
    fs.mkdir(path.join(git_root, ".git", "aux"), function(err) {
        if(err) {
            die("Couldn't create git aux directory", err);
        }

        save_config(git_root, {
            basedir: path.resolve(process.cwd(), basedir)
        }).then(function() {
            console.log("Initialised git aux repository");
        });
    });
}

function rm(file) {
    var promise = new Promise();

    fs.stat(file, function(err, stats) {
        if(err) {
            if(err.code === "ENOENT") {
                return promise.fulfill();
            } else {
                die("Unable to stat file", err);
            }
        }

        if(stats.isDirectory()) {
            fs.readdir(file, function(err, files) {
                var count = files.length;

                function finish() {
                    fs.rmdir(file, function(err) {
                        if(err) {
                            die("Unable to remove dir", err);
                        }

                        promise.fulfill();
                    });
                }

                if(count === 0) {
                    finish();
                } else {
                    files.forEach(function(f) {
                        rm(path.join(file, f)).then(function() {
                            count--;

                            if(count === 0) {
                                finish();
                            }
                        });
                    });
                }
            });
        } else {
            fs.unlink(file, function(err) {
                if(err) {
                    die("Unable to delete file", err);
                }

                promise.fulfill();
            });
        }
    });

    return promise;
}

function copy(src, dest) {
    var promise = new Promise();

    rm(dest).then(function() {
        fs.stat(src, function(err, stats) {
            var is, os;

            if(err) {
                if(err.code === "ENOENT") {
                    promise.fulfill();
                } else {
                    die("Unable to stat file", err);
                }
            }

            if(stats.isDirectory()) {
                fs.mkdir(dest, function(err) {
                    if(err) {
                        die("Unable to create directory", err);
                    }

                    fs.readdir(src, function(err, files) {
                        var count = files.length;

                        if(count === 0) {
                            promise.fulfill();
                        }

                        files.forEach(function(file) {
                            copy(path.join(src, file), path.join(dest, file)).then(function() {
                                count--;

                                if(count === 0) {
                                    promise.fulfill();
                                }
                            });
                        });
                    });
                });
            } else {
                is = fs.createReadStream(src);
                os = fs.createWriteStream(dest);

                util.pump(is, os, function(err) {
                    if(err) {
                        die("Failed copying file", err);
                    }

                    promise.fulfill();
                });
            }
        });
    });

    return promise;
}

function add(git_root, config, files) {
    files.forEach(function(file) {
        var relative_path = path.resolve(process.cwd(), file);

        // FIXME: Make this a recursive copy

        if(new RegExp("^" + config.basedir + path.sep).test(relative_path)) {
            relative_path = path.relative(config.basedir, relative_path);

            debug("Adding:", relative_path);

            copy(path.join(config.basedir, relative_path), path.join(git_root, relative_path)).then(function() {
                exec("git add " + path.join(git_root, relative_path), function(err) {
                    if(err) {
                        die("Failed adding file to git", err);
                    }
                });
            });
        } else {
            die(file + " is not within this git aux repo's basedir (" + config.basedir + ")");
        }
    });
}

function get_files(dir) {
    var promise = new Promise();

    var count = 0;

    var output = [];

    fs.readdir(dir, function(err, files) {
        if(err) {
            die("Error reading dir", err);
        }

        count = files.length;

        if(count === 0) {
            promise.fulfill(output);
        }

        files.forEach(function(file) {
            fs.stat(path.join(dir, file), function(err, stats) {
                if(err) {
                    die("Failed getting file info", err);
                }

                if(stats.isFile()) {
                    count--;

                    output.push(path.join(dir, file));

                    if(count === 0) {
                        promise.fulfill(output);
                    }
                } else if(stats.isDirectory()) {
                    get_files(path.join(dir, file)).then(function(sub_dir) {
                        count--;

                        output = output.concat(sub_dir);

                        if(count === 0) {
                            promise.fulfill(output);
                        }
                    });
                } else {
                    count--;

                    if(count === 0) {
                        promise.fulfill(output);
                    }
                }
            });
        });
    });

    return promise;
}

get_files("/home/steve/code/git-aux/test/repo").then(function(files) {
    console.log(files);
});

function sync(git_root, config) {
    fs.readdir(git_root, function(err, files) {
        var count = files.length - 1;

        function finish() {
            spawn("git", ["add", "-p"], {stdio: "inherit"});
        }

        if(count === 0) {
            finish();
        }

        files.forEach(function(file) {
            if(file !== ".git") {
                debug("Syncing: " + file);

                file = path.relative(git_root, path.join(git_root, file));

                copy(path.join(config.basedir, file), path.join(git_root, file)).then(function() {
                    count--;

                    if(count === 0) {
                        finish();
                    }
                });
            }
        });
    });
}

// Check the parameters

if(process.argv.length < 3) {
    help();
    process.exit();
}

// Get the config
get_git_root().then(function(git_root) {
    get_config(git_root).then(function(config) {
        var command = process.argv[2];
        var args = process.argv.slice(3);

        debug("Config:", config);

        debug("Command:", command);
        debug("Args:", args);

        if(!config && command !== "init") {
            die("Not a git aux repository");
        }

        if(command === "init") {
            if(config) {
                die("Already a git aux repository");
            }

            if(args.length !== 1) {
                help();
                process.exit(1);
            }

            init(git_root, args[0]);
        } else if(command === "add") {
            if(args.length === 0) {
                help();
                process.exit(1);
            }

            add(git_root, config, args);
        } else if(command === "sync") {
            if(args.length !== 0) {
                help();
                process.exit(1);
            }

            sync(git_root, config);
        } else if(command === "apply") {
        } else {
            console.log("unknown command:", command);
            help();
            process.exit(1);
        }
    });
});
<commit_msg>Fix sync<commit_after>#!/usr/bin/env node

var exec = require("child_process").exec;
var spawn = require("child_process").spawn;
var path = require("path");
var fs = require("fs");
var util = require("util");

var Promise = require("./lib/promise");

var DEBUG = true;

// Some standard helpers

function debug() {
    var args;
    if(DEBUG) {
        args = Array.prototype.slice.call(arguments, 0);
        args.unshift("DEBUG:");

        console.log.apply(this, args);
    }
}

function die(message, exception) {
    if(exception) {
        message += ": " + exception.message;
    }

    console.log(message);

    if(DEBUG) {
        throw exception;
    }

    process.exit(1);
}

function help() {
    console.log("usage: git aux <command> [<args>]");
    console.log();
    console.log("Commands:");
    console.log("init <basedir>   Initialise git aux to use the chosen directory");
    console.log("add <file(s)>    Add the chosen file (from basedir) to the repository");
    console.log("sync             Import changes to tracked files in basedir into the repository");
    console.log("apply            Apply changes from the repository into the basedir");
    console.log();
}

function get_git_root() {
    var promise = new Promise();

    exec("git rev-parse --show-toplevel", function(err, stdout, stderr) {
        if(err) {
            console.log("Not a git repository");
            process.exit(1);
        }

        home = stdout.trim();

        promise.fulfill(home);
    });

    return promise;
}

function get_config(git_root) {
    var promise = new Promise();

    fs.readFile(path.join(git_root, ".git", "aux", "config.json"), "utf8", function(err, data) {
        if(err) {
            promise.fulfill(null);
            debug("No config");
        } else {
            try {
                data = JSON.parse(data);
                promise.fulfill(data);
            } catch(e) {
                die("Unable to parse git aux config", e);
            }
        }
    });

    return promise;
}

function save_config(git_root, config) {
    var promise = new Promise();

    fs.writeFile(path.join(git_root, ".git", "aux", "config.json"), JSON.stringify(config, null, 2), function(err) {
        if(err) {
            die("Unable to save config", err);
        }

        promise.fulfill();
    });

    return promise;
}

function mkdir(dir) {
    var promise = new Promise();

    debug("Making dir:", dir);

    fs.mkdir(dir, function(err) {
        if(err) {
            if(err.code === "ENOENT") {
                mkdir(path.dirname(dir)).then(function() {
                    mkdir(dir).then(promise.fulfill);
                });
            } else if(err.code === "EEXIST") {
                promise.fulfill();
            } else {
                die("Error creating directory", err);
            }
        } else {
            promise.fulfill();
        }
    });

    return promise;
}

// Git aux commands

function init(git_root, basedir) {
    // Make git aux directory
    fs.mkdir(path.join(git_root, ".git", "aux"), function(err) {
        if(err) {
            die("Couldn't create git aux directory", err);
        }

        save_config(git_root, {
            basedir: path.resolve(process.cwd(), basedir)
        }).then(function() {
            console.log("Initialised git aux repository");
        });
    });
}

function rm(file) {
    var promise = new Promise();

    fs.stat(file, function(err, stats) {
        if(err) {
            if(err.code === "ENOENT") {
                return promise.fulfill();
            } else {
                die("Unable to stat file", err);
            }
        }

        if(stats.isDirectory()) {
            fs.readdir(file, function(err, files) {
                var count = files.length;

                function finish() {
                    fs.rmdir(file, function(err) {
                        if(err) {
                            die("Unable to remove dir", err);
                        }

                        promise.fulfill();
                    });
                }

                if(count === 0) {
                    finish();
                } else {
                    files.forEach(function(f) {
                        rm(path.join(file, f)).then(function() {
                            count--;

                            if(count === 0) {
                                finish();
                            }
                        });
                    });
                }
            });
        } else {
            fs.unlink(file, function(err) {
                if(err) {
                    die("Unable to delete file", err);
                }

                promise.fulfill();
            });
        }
    });

    return promise;
}

function copy(src, dest) {
    var promise = new Promise();

    rm(dest).then(function() {
        fs.stat(src, function(err, stats) {
            var is, os;

            if(err) {
                if(err.code === "ENOENT") {
                    promise.fulfill();
                } else {
                    die("Unable to stat file", err);
                }
            }

            if(stats.isDirectory()) {
                fs.mkdir(dest, function(err) {
                    if(err) {
                        die("Unable to create directory", err);
                    }

                    fs.readdir(src, function(err, files) {
                        var count = files.length;

                        if(count === 0) {
                            promise.fulfill();
                        }

                        files.forEach(function(file) {
                            copy(path.join(src, file), path.join(dest, file)).then(function() {
                                count--;

                                if(count === 0) {
                                    promise.fulfill();
                                }
                            });
                        });
                    });
                });
            } else {
                is = fs.createReadStream(src);
                os = fs.createWriteStream(dest);

                util.pump(is, os, function(err) {
                    if(err) {
                        die("Failed copying file", err);
                    }

                    promise.fulfill();
                });
            }
        });
    });

    return promise;
}

function add(git_root, config, files) {
    files.forEach(function(file) {
        var relative_path = path.resolve(process.cwd(), file);

        // FIXME: Make this a recursive copy

        if(new RegExp("^" + config.basedir + path.sep).test(relative_path)) {
            relative_path = path.relative(config.basedir, relative_path);

            debug("Adding:", relative_path);

            copy(path.join(config.basedir, relative_path), path.join(git_root, relative_path)).then(function() {
                exec("git add " + path.join(git_root, relative_path), function(err) {
                    if(err) {
                        die("Failed adding file to git", err);
                    }
                });
            });
        } else {
            die(file + " is not within this git aux repo's basedir (" + config.basedir + ")");
        }
    });
}

function get_files(dir) {
    var promise = new Promise();

    var count = 0;

    var output = [];

    fs.readdir(dir, function(err, files) {
        if(err) {
            die("Error reading dir", err);
        }

        count = files.length;

        if(count === 0) {
            promise.fulfill(output);
        }

        files.forEach(function(file) {
            fs.stat(path.join(dir, file), function(err, stats) {
                if(err) {
                    die("Failed getting file info", err);
                }

                if(stats.isFile()) {
                    count--;

                    output.push(path.join(dir, file));

                    if(count === 0) {
                        promise.fulfill(output);
                    }
                } else if(stats.isDirectory()) {
                    get_files(path.join(dir, file)).then(function(sub_dir) {
                        count--;

                        output = output.concat(sub_dir);

                        if(count === 0) {
                            promise.fulfill(output);
                        }
                    });
                } else {
                    count--;

                    if(count === 0) {
                        promise.fulfill(output);
                    }
                }
            });
        });
    });

    return promise;
}

get_files("/home/steve/code/git-aux/test/repo").then(function(files) {
    console.log(files);
});

function sync(git_root, config) {
    get_files(git_root).then(function(files) {
        var count;

        files = files.filter(function(f) {
            return !new RegExp("^" + path.join(git_root, ".git")).test(f);
        });

        count = files.length;

        function finish() {
            spawn("git", ["add", "-p"], {stdio: "inherit"});
        }

        if(count === 0) {
            finish();
        }

        files.forEach(function(file) {
            debug("Syncing: " + file);

            file = path.relative(git_root, file);

            fs.exists(path.join(config.basedir, file), function(exists) {
                if(exists) {
                    copy(path.join(config.basedir, file), path.join(git_root, file)).then(function() {
                        count--;

                        if(count === 0) {
                            finish();
                        }
                    });
                } else {
                    rm(path.join(git_root, file)).then(function() {
                        count--;

                        if(count === 0) {
                            finish();
                        }
                    });
                }
            });

        });
    });
}

function apply(git_root, config) {
    exec("git stash", function(err) {
        if(err) {
            die("Unable to stash", err);
        }

        fs.readdir(git_root, function(err, files) {
            var count = files.length - 1;

            function finish() {
                exec("git stash pop");
            }

            if(count === 0) {
                finish();
            }

            files.forEach(function(file) {
                if(file !== ".git") {
                    debug("Syncing: " + file);

                    file = path.relative(git_root, path.join(git_root, file));

                    copy(path.join(config.basedir, file), path.join(git_root, file)).then(function() {
                        count--;

                        if(count === 0) {
                            finish();
                        }
                    });
                }
            });
        });
    });
}

// Check the parameters

if(process.argv.length < 3) {
    help();
    process.exit();
}

// Get the config
get_git_root().then(function(git_root) {
    get_config(git_root).then(function(config) {
        var command = process.argv[2];
        var args = process.argv.slice(3);

        debug("Config:", config);

        debug("Command:", command);
        debug("Args:", args);

        if(!config && command !== "init") {
            die("Not a git aux repository");
        }

        if(command === "init") {
            if(config) {
                die("Already a git aux repository");
            }

            if(args.length !== 1) {
                help();
                process.exit(1);
            }

            init(git_root, args[0]);
        } else if(command === "add") {
            if(args.length === 0) {
                help();
                process.exit(1);
            }

            add(git_root, config, args);
        } else if(command === "sync") {
            if(args.length !== 0) {
                help();
                process.exit(1);
            }

            sync(git_root, config);
        } else if(command === "apply") {
            if(args.length !== 0) {
                help();
                process.exit(1);
            }

            apply(git_root, config);
        } else {
            console.log("unknown command:", command);
            help();
            process.exit(1);
        }
    });
});
<|endoftext|>


<commit_before>var adminApp = angular
        .module('app', ['ng-admin'])
        .run(run);

//const sendash = 'https://sendash.com/';
const sendash = 'http://localhost:8191/sendash/api/admin/';

adminApp.config(['NgAdminConfigurationProvider', 'RestangularProvider', function (nga, RestangularProvider) {
    // create an admin application
    var admin = nga.application('Sendash Admin')
        .baseApiUrl(sendash);

    var user = nga.entity('user');
    // set the fields of the user entity list view
    user.listView().fields([
        nga.field('email'),
        nga.field('firstName')
            .label('First Name'),
        nga.field('lastName')
            .label('Last Name'),
        nga.field('roles', 'embedded_list')
            .label('Roles')
            .targetFields([
                nga.field('name')
                    .label('')
            ]),
        nga.field('client', 'embedded_list')
            .targetFields([
                nga.field('name')
                    .label('')
             ])

    ]);
    user.listView().listActions(['edit', 'delete']);

    user.creationView().fields([
        nga.field('email', 'email'),
        nga.field('firstName')
            .label('First Name'),
        nga.field('lastName')
            .label('Last Name')
    ]);
    // use the same fields for the editionView as for the creationView
    user.editionView().fields(user.creationView().fields());

    admin.addEntity(user);

    var client = nga.entity('client');
    // set the fields of the user entity list view
    client.listView().fields([
        nga.field('id'),
        nga.field('name')
    ]);
    client.listView().listActions(['edit', 'delete']);

    client.creationView().fields([
        nga.field('name')

    ]);
    // use the same fields for the editionView as for the creationView
    client.editionView().fields(client.creationView().fields());
    admin.addEntity(client);

    var endpoint = nga.entity('endpoint');
    // set the fields of the user entity list view
    endpoint.listView().fields([
        nga.field('id'),
        nga.field('client.name')
            .label('Client Name'),
        nga.field('hostName')
            .label('Host Name'),
        nga.field('apiKey')
            .label('API Key'),
        nga.field('updateScriptRequest', 'datetime')
            .label('Last Request')
    ]);
    endpoint.listView()
        .listActions(['edit', 'delete']);

    endpoint.creationView().fields([
        nga.field('client.id', 'reference')
            .label('Client Name')
            .targetEntity(client)
            .targetField(nga.field('name'))
            .attributes({ placeholder: 'Select one' }),
        nga.field('hostName')
            .label('Host Name'),
        nga.field('apiKey')
            .label('API Key')
    ]);
    // use the same fields for the editionView as for the creationView
    endpoint.editionView().fields(endpoint.creationView().fields());
    admin.addEntity(endpoint);

    var pendingEndpoint = nga.entity('pending-endpoint');
    // set the fields of the user entity list view
    pendingEndpoint.listView().fields([
        nga.field('client.clientName')
            .label('Client Name'),
        nga.field('hostName')
            .label('Host Name'),
        nga.field('apiKey')
            .label('API Key')
    ]);
    pendingEndpoint.listView()
        .listActions(['edit', 'delete'])
        .batchActions(['<batch-approve type="accept" selection="selection"></batch-approve>',
            '<batch-approve type="reject" selection="selection"></batch-approve>',
            'delete']);

    pendingEndpoint.creationView().fields([
        nga.field('client.id', 'reference')
            .label('Client Name')
            .targetEntity(client)
            .targetField(nga.field('name'))
            .attributes({ placeholder: 'Select one' }),
        nga.field('hostName')
            .label('Host Name'),
        nga.field('apiKey')
            .label('API Key')
    ]);
    // use the same fields for the editionView as for the creationView
    pendingEndpoint.editionView().fields(pendingEndpoint.creationView().fields());
    admin.addEntity(pendingEndpoint);

    var githubPayload = nga.entity('github').label('Github Payload');
    githubPayload.listView().fields([
        nga.field('receivedTimestamp', 'datetime')
            .label('Received'),
        nga.field('commits')
    ]);
    githubPayload.listView().title('Github Payloads List');
    githubPayload.readOnly();
    admin.addEntity(githubPayload);

    admin.header(require('./header.html'));
    admin.menu(nga.menu()
            .addChild(nga.menu(user).icon(''))
            .addChild(nga.menu(client).icon(''))
            .addChild(nga.menu(endpoint).icon(''))
            .addChild(nga.menu(pendingEndpoint).icon(''))
            .addChild(nga.menu(githubPayload).icon(''))
    );

    nga.configure(admin);
}]);

adminApp.config(['$stateProvider', function($stateProvider) {
    $stateProvider.state('login', {
        parent: 'main',
        url: '/login',
        controller: 'LoginController',
        controllerAs: 'vm',
        templateUrl: 'login/login.view.html'
    });
}]);

adminApp.config(['RestangularProvider', function (RestangularProvider) {
    RestangularProvider.addFullRequestInterceptor(function(element, operation, what, url, headers, params) {
        if (operation == "getList") {
            // custom pagination params
            if (params._page) {
                params._page = (params._page - 1);
            }
        }
        return { params: params };
    });

}]);

adminApp.controller('username', ['$scope', '$window', '$location', function($scope, $window, $location) { // used in header.html
    if($window.sessionStorage.getItem('userInfo')) {
        $scope.username = JSON.parse($window.sessionStorage.getItem('userInfo')).username;
    }
    else {
        $location.path("/login");
    }
}]);

run.$inject = ['$rootScope', '$location',  '$http', 'AuthenticationService', 'Restangular'];
function run($rootScope, $location,  $http, AuthenticationService, Restangular) {

    $rootScope.$on('$locationChangeStart', function (event, next, current) {
        // redirect to login page if not logged in and trying to access a restricted page
        var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
        var loggedIn = AuthenticationService.IsAuthenticated();
        if (restrictedPage && !loggedIn) {
            $location.path('/login');
            Restangular.setDefaultHeaders({});
        }
        else {
            //Restangular.setDefaultHeaders({'Authorization': 'Bearer ' + AuthenticationService.GetToken()});
        }
    });
}
<commit_msg>added 's' to client.<commit_after>var adminApp = angular
        .module('app', ['ng-admin'])
        .run(run);

//const sendash = 'https://sendash.com/';
const sendash = 'http://localhost:8191/sendash/api/admin/';

adminApp.config(['NgAdminConfigurationProvider', 'RestangularProvider', function (nga, RestangularProvider) {
    // create an admin application
    var admin = nga.application('Sendash Admin')
        .baseApiUrl(sendash);

    var user = nga.entity('user');
    // set the fields of the user entity list view
    user.listView().fields([
        nga.field('email'),
        nga.field('firstName')
            .label('First Name'),
        nga.field('lastName')
            .label('Last Name'),
        nga.field('roles', 'embedded_list')
            .label('Roles')
            .targetFields([
                nga.field('name')
                    .label('')
            ]),
        nga.field('clients', 'embedded_list')
            .targetFields([
                nga.field('name')
                    .label('')
             ])

    ]);
    user.listView().listActions(['edit', 'delete']);

    user.creationView().fields([
        nga.field('email', 'email'),
        nga.field('firstName')
            .label('First Name'),
        nga.field('lastName')
            .label('Last Name')
    ]);
    // use the same fields for the editionView as for the creationView
    user.editionView().fields(user.creationView().fields());

    admin.addEntity(user);

    var client = nga.entity('client');
    // set the fields of the user entity list view
    client.listView().fields([
        nga.field('id'),
        nga.field('name')
    ]);
    client.listView().listActions(['edit', 'delete']);

    client.creationView().fields([
        nga.field('name')

    ]);
    // use the same fields for the editionView as for the creationView
    client.editionView().fields(client.creationView().fields());
    admin.addEntity(client);

    var endpoint = nga.entity('endpoint');
    // set the fields of the user entity list view
    endpoint.listView().fields([
        nga.field('id'),
        nga.field('client.name')
            .label('Client Name'),
        nga.field('hostName')
            .label('Host Name'),
        nga.field('apiKey')
            .label('API Key'),
        nga.field('updateScriptRequest', 'datetime')
            .label('Last Request')
    ]);
    endpoint.listView()
        .listActions(['edit', 'delete']);

    endpoint.creationView().fields([
        nga.field('client.id', 'reference')
            .label('Client Name')
            .targetEntity(client)
            .targetField(nga.field('name'))
            .attributes({ placeholder: 'Select one' }),
        nga.field('hostName')
            .label('Host Name'),
        nga.field('apiKey')
            .label('API Key')
    ]);
    // use the same fields for the editionView as for the creationView
    endpoint.editionView().fields(endpoint.creationView().fields());
    admin.addEntity(endpoint);

    var pendingEndpoint = nga.entity('pending-endpoint');
    // set the fields of the user entity list view
    pendingEndpoint.listView().fields([
        nga.field('client.clientName')
            .label('Client Name'),
        nga.field('hostName')
            .label('Host Name'),
        nga.field('apiKey')
            .label('API Key')
    ]);
    pendingEndpoint.listView()
        .listActions(['edit', 'delete'])
        .batchActions(['<batch-approve type="accept" selection="selection"></batch-approve>',
            '<batch-approve type="reject" selection="selection"></batch-approve>',
            'delete']);

    pendingEndpoint.creationView().fields([
        nga.field('client.id', 'reference')
            .label('Client Name')
            .targetEntity(client)
            .targetField(nga.field('name'))
            .attributes({ placeholder: 'Select one' }),
        nga.field('hostName')
            .label('Host Name'),
        nga.field('apiKey')
            .label('API Key')
    ]);
    // use the same fields for the editionView as for the creationView
    pendingEndpoint.editionView().fields(pendingEndpoint.creationView().fields());
    admin.addEntity(pendingEndpoint);

    var githubPayload = nga.entity('github').label('Github Payload');
    githubPayload.listView().fields([
        nga.field('receivedTimestamp', 'datetime')
            .label('Received'),
        nga.field('commits')
    ]);
    githubPayload.listView().title('Github Payloads List');
    githubPayload.readOnly();
    admin.addEntity(githubPayload);

    admin.header(require('./header.html'));
    admin.menu(nga.menu()
            .addChild(nga.menu(user).icon(''))
            .addChild(nga.menu(client).icon(''))
            .addChild(nga.menu(endpoint).icon(''))
            .addChild(nga.menu(pendingEndpoint).icon(''))
            .addChild(nga.menu(githubPayload).icon(''))
    );

    nga.configure(admin);
}]);

adminApp.config(['$stateProvider', function($stateProvider) {
    $stateProvider.state('login', {
        parent: 'main',
        url: '/login',
        controller: 'LoginController',
        controllerAs: 'vm',
        templateUrl: 'login/login.view.html'
    });
}]);

adminApp.config(['RestangularProvider', function (RestangularProvider) {
    RestangularProvider.addFullRequestInterceptor(function(element, operation, what, url, headers, params) {
        if (operation == "getList") {
            // custom pagination params
            if (params._page) {
                params._page = (params._page - 1);
            }
        }
        return { params: params };
    });

}]);

adminApp.controller('username', ['$scope', '$window', '$location', function($scope, $window, $location) { // used in header.html
    if($window.sessionStorage.getItem('userInfo')) {
        $scope.username = JSON.parse($window.sessionStorage.getItem('userInfo')).username;
    }
    else {
        $location.path("/login");
    }
}]);

run.$inject = ['$rootScope', '$location',  '$http', 'AuthenticationService', 'Restangular'];
function run($rootScope, $location,  $http, AuthenticationService, Restangular) {

    $rootScope.$on('$locationChangeStart', function (event, next, current) {
        // redirect to login page if not logged in and trying to access a restricted page
        var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
        var loggedIn = AuthenticationService.IsAuthenticated();
        if (restrictedPage && !loggedIn) {
            $location.path('/login');
            Restangular.setDefaultHeaders({});
        }
        else {
            //Restangular.setDefaultHeaders({'Authorization': 'Bearer ' + AuthenticationService.GetToken()});
        }
    });
}
<|endoftext|>


<commit_before> $(function(){
  $('.entry-content a').attr('target','_blank');
  var headers = $('#post .entry-content :header').map(function (idx, h){
    var a = $('');
    a.attr('data-id',h.id);
    a.attr('href', '#' + h.id);
    a.attr('class', h.nodeName.toLowerCase());
    a.html( '' + h.textContent)
    return $('
').append(a)[0].outerHTML;
  }).toArray().join("");
  var menu = $('
<button class="dl-btn btn btn-success">Contents</button>
');
  if(headers.trim())
    $('body').append(menu.append($('
').append(headers)));
  if($('#dl-headers .dl-btn').is(':visible')) {
    $('#dl-headers .dl-btn').on('click',function(){
      $('ul#headers').slideToggle();
    })
  }
  $('#headers a').click(function (e){
    e.preventDefault();
    console.info("scrollTo #" + $(this).attr('data-id'));
    var selector = '#'+$(this).attr('data-id');
    var top = $(selector).offset().top;
    $('body, html').animate({ scrollTop: top - 25 }, 500, 'swing');
  });

  /*Thanks to http://beiyuu.com/js/post.js*/
  var waitForFinalEvent = (function () {
            var timers = {};
            return function (callback, ms, uniqueId) {
                if (!uniqueId) {
                    uniqueId = "Don't call this twice without a uniqueId";
                }
                if (timers[uniqueId]) {
                    clearTimeout (timers[uniqueId]);
                }
                timers[uniqueId] = setTimeout(callback, ms);
            };
    })();
  var scrollTop = [];
  $.each($('#headers li a'),function(index,item){
      var selector = $(item).attr('data-id') ? '#'+$(item).attr('data-id') : 'h1'
      var top = $(selector).offset().top;
      scrollTop.push(top);
  });

  var footerTop = 0;
  var footer = $('.entry-meta').offset()
  if( footer )
    footerTop = footer.top;

  $(window).scroll(function(){
      waitForFinalEvent(function(){
          var nowTop = $(window).scrollTop();
          var length = scrollTop.length;
          var index;

          if(nowTop+60 > scrollTop[length-1]){
              index = length;
          }else{
              for(var i=0;i<length;i++){
                  if(nowTop+60 <= scrollTop[i]){
                      index = i;
                      break;
                  }
              }
          }
          $('#headers li').removeClass('on');
          if( 0 == index ) index = 1;
          $('#headers li').eq(index-1).addClass('on');
          if(nowTop >= footerTop) {
              $('#dl-headers').hide();
          } else {
              $('#dl-headers').show();
          }
      });
  });

});

<commit_msg>make all the anchor opened in another tab<commit_after> $(function(){
  $('.entry-content a,entry a,read-more a').attr('target','_blank');
  var headers = $('#post .entry-content :header').map(function (idx, h){
    var a = $('');
    a.attr('data-id',h.id);
    a.attr('href', '#' + h.id);
    a.attr('class', h.nodeName.toLowerCase());
    a.html( '' + h.textContent)
    return $('
').append(a)[0].outerHTML;
  }).toArray().join("");
  var menu = $('
<button class="dl-btn btn btn-success">Contents</button>
');
  if(headers.trim())
    $('body').append(menu.append($('
').append(headers)));
  if($('#dl-headers .dl-btn').is(':visible')) {
    $('#dl-headers .dl-btn').on('click',function(){
      $('ul#headers').slideToggle();
    })
  }
  $('#headers a').click(function (e){
    e.preventDefault();
    console.info("scrollTo #" + $(this).attr('data-id'));
    var selector = '#'+$(this).attr('data-id');
    var top = $(selector).offset().top;
    $('body, html').animate({ scrollTop: top - 25 }, 500, 'swing');
  });

  /*Thanks to http://beiyuu.com/js/post.js*/
  var waitForFinalEvent = (function () {
            var timers = {};
            return function (callback, ms, uniqueId) {
                if (!uniqueId) {
                    uniqueId = "Don't call this twice without a uniqueId";
                }
                if (timers[uniqueId]) {
                    clearTimeout (timers[uniqueId]);
                }
                timers[uniqueId] = setTimeout(callback, ms);
            };
    })();
  var scrollTop = [];
  $.each($('#headers li a'),function(index,item){
      var selector = $(item).attr('data-id') ? '#'+$(item).attr('data-id') : 'h1'
      var top = $(selector).offset().top;
      scrollTop.push(top);
  });

  var footerTop = 0;
  var footer = $('.entry-meta').offset()
  if( footer )
    footerTop = footer.top;

  $(window).scroll(function(){
      waitForFinalEvent(function(){
          var nowTop = $(window).scrollTop();
          var length = scrollTop.length;
          var index;

          if(nowTop+60 > scrollTop[length-1]){
              index = length;
          }else{
              for(var i=0;i<length;i++){
                  if(nowTop+60 <= scrollTop[i]){
                      index = i;
                      break;
                  }
              }
          }
          $('#headers li').removeClass('on');
          if( 0 == index ) index = 1;
          $('#headers li').eq(index-1).addClass('on');
          if(nowTop >= footerTop) {
              $('#dl-headers').hide();
          } else {
              $('#dl-headers').show();
          }
      });
  });

});

<|endoftext|>


<commit_before>(function($)
{
    // HTML5 placeholder polyfill
    function initPlaceHolders()
    {
        if ( ! ('placeholder' in document.createElement('input')))
        {
            $('[type=password][placeholder]').attr('placeholder', $('[type=password][placeholder]').eq(0).attr('placeholder'));
            var items = '[placeholder]';
            $(items).each(function()
            {
                var $this = $(this);
                if (($this.val() == '') && ($this.attr('placeholder')))
                    $this.val($this.attr('placeholder')).addClass('placeholder');
                else if ($this.val() == $this.attr('placeholder'))
                    $this.addClass('placeholder');
            });
            $(document).on('focus', items, function()
            {
                var $this = $(this);
                if ($this.val() == $this.attr('placeholder'))
                    $this.val('').removeClass('placeholder');
            });
            $(document).on('blur', items, function()
            {
                var $this = $(this);
                if (($this.val() == '') && ($this.attr('placeholder')))
                    $this.val($this.attr('placeholder')).addClass('placeholder');
            });
            $('form').on('submit', function()
            {
                var $this = $(this);
                $this.find('[placeholder]').each(function()
                {
                    if ($this.val() == $this.attr('placeholder'))
                        $this.val('').removeClass('placeholder');
                });
            });
        }
    }

    // DOM ready
    $(function()
    {
        $('form').attr('autocomplete', 'off');
        $('select').mouseleave(function(event) { event.stopPropagation(); });
        if (typeof console === 'undefined') console = { log: function(){} };
        $('html').removeClass('nojs');
        initPlaceHolders();
    });

    // Loading complete
    $(window).load(function()
    {

    });
})(jQuery);
<commit_msg>js cleanup<commit_after>(function($)
{
    // HTML5 placeholder polyfill

    function initPlaceHolders()
    {
        if ( ! ('placeholder' in document.createElement('input')))
        {
            $('[type=password][placeholder]').attr('placeholder', $('[type=password][placeholder]').eq(0).attr('placeholder'));
            var items = '[placeholder]';
            $(items).each(function()
            {
                var $this = $(this);
                if (($this.val() == '') && ($this.attr('placeholder')))
                    $this.val($this.attr('placeholder')).addClass('placeholder');
                else if ($this.val() == $this.attr('placeholder'))
                    $this.addClass('placeholder');
            });
            $(document).on('focus', items, function()
            {
                var $this = $(this);
                if ($this.val() == $this.attr('placeholder'))
                    $this.val('').removeClass('placeholder');
            });
            $(document).on('blur', items, function()
            {
                var $this = $(this);
                if (($this.val() == '') && ($this.attr('placeholder')))
                    $this.val($this.attr('placeholder')).addClass('placeholder');
            });
            $('form').on('submit', function()
            {
                var $this = $(this);
                $this.find('[placeholder]').each(function()
                {
                    if ($this.val() == $this.attr('placeholder'))
                        $this.val('').removeClass('placeholder');
                });
            });
        }
    }

    // DOM ready

    $(function()
    {
        $('form').attr('autocomplete', 'off');
        $('select').mouseleave(function(event) { event.stopPropagation(); });
        if (typeof console === 'undefined') console = { log: function(){} };
        $('html').removeClass('nojs');
        initPlaceHolders();
    });

    // Loading complete

    $(window).load(function()
    {

    });

})(jQuery);
<|endoftext|>


<commit_before>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 10/01/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/whizkydee/webtwic

*/

jQuery(document).ready(function() {

	// Define Variables
	var is_DisabledFeatures = $("div").hasClass("dfvisible"),
	img = $("img"),
	is_noAlt = img.attr("alt", null),
	scripts = $("script"),
	is_noType = scripts.attr("type", null),
	is_noCharset = scripts.attr("charset", null);

	var $to_top = $("a.to-top"),
	is_toggle_active = $(".hamburger").hasClass("is_active"),
	height = 200;

	// Performance Fixes

	// Create function to add browser name and version to body class

	function showBrowser(b) {
		$("body").addClass(b + " " + b + parseInt(browser.version));
	}

	// Start browser detection

	browser = bowser;
	browser.ie = browser.msie;

	if (browser.webkit) {
		$("body").addClass("webkit");
	}
	if(browser.chrome) {
		showBrowser("chrome");
	}
	if(browser.msedge) {
		showBrowser("msedge");
	}
	if(browser.firefox) {
		showBrowser("firefox");
	}
	if(browser.msie) {
		showBrowser("ie");
	}
	if(browser.safari) {
		showBrowser("safari");
	}
	if(browser.opera) {
		showBrowser("opera");
	}

	// Start function to set attributes and values to elements

	function setAttr(elem, name, val) {
		$(elem, this).attr(name, val);
	}

	if(is_noAlt) {
		setAttr(img, "alt", "...");
	} else {
		return img.attr("alt");
	}

	if(is_noCharset) {
		setAttr(scripts, "charset", "utf-8");
	} else {
		return scripts.attr("charset");
	}

	if(is_noType) {
		setAttr(scripts, "type", "text/javascript");
	} else {
		return scripts.attr("type");
	}

	// Notification for disabled features
	function showDisabledFeatures() {
		$(".top-stripe").before(
			"
Certain features which affect the functionality of webtwic are disabled in your browser. Please try refreshing the page or get a better browser.
"
		);
		$(".close-button").on("click",
			function() {
				hideDisabledFeatures();
				undoSiteAdjust();
			});
	}

	function hideDisabledFeatures() {
		$("#disabledFeatures").removeClass("dfvisible");
	}
	function adjustSiteContent() {
		$(".top-stripe").addClass("adjustedMargin");
		$("#header .logo").addClass("adjustedTop");
		$(".main-menu").addClass("adjustedMargin");
		$("#header").addClass("adjustSiteContent");
	}
	function undoSiteAdjust() {
		$(".top-stripe").removeClass("adjustedMargin");
		$("#header .logo").removeClass("adjustedTop");
		$(".main-menu").removeClass("adjustedMargin");
		$("#header").removeClass("adjustSiteContent");
	}

	// Modernizr funnctions

	function resetSite() {
		showDisabledFeatures();
		adjustSiteContent();
	}

	function undoReset() {
		hideDisabledFeatures();
		undoSiteAdjust();
	}

	if (!Modernizr.flexbox || !Modernizr.inlinesvg || !Modernizr.svg || !Modernizr.svgclippaths || !Modernizr.fontface || !Modernizr.boxshadow || !Modernizr.borderradius || !Modernizr.csstransforms) {
		resetSite();
	} else {
		undoReset();
	}

	// Start Main Page

	$("nav li ul.drop-nav").hide().removeClass("dropNavFallback");

	if ( $(window).width() > 860 ) {
		$("nav li.dropdown").hover(function() {
			$("ul.drop-nav", this).stop().slideDown("fast");
		}, function() {
			$("ul.drop-nav", this).stop().slideUp("fast");
		});
	}

	$(".active-item").append(
		"<svg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><path d='M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z'></path></svg>"
	);

	$("a.hamburger").click(function(e) {
		$(this).toggleClass("is_active");

		e.preventDefault();
	});
	$(".mobile-header .mobile-nav").hide();

	$(window).scroll(function() {
		($(this).scrollTop() > height) ? $to_top.addClass("topVisible"): $to_top.removeClass("topVisible");
	});

	// Styles for homepage article-social

	$(".article .article-social a").hover(function() {
		$("span", this).eq(1).fadeIn(400);
	}, function() {
		$("span", this).eq(1).fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$(".header-follow-search .search-wrap").on("click", function() {
		openUiOverlay();
	});

	$(".header-follow-search .close-icon").on("click", function() {
		closeUiOverlay();
	});

	$(".header-follow-search .close-icon").hover(
		function() {
			$(this).addClass("spin");
		},
		function() {
			$(this).removeClass("spin");
		});

	function openUiOverlay() {
		$(".ui-overlay-search").fadeIn(400).addClass("is_open");
	}

	function closeUiOverlay() {
		$(".ui-overlay-search").fadeOut(400).removeClass("is_open");
	}

	$(".ui-overlay-search .search-input input").focus(function() {
		$(".search-input").attr("data-focused", true);
		$(".search-input input").addClass("_is-focused");
		$("#__expand").addClass("visible");
	});

	$(".ui-overlay-search .search-input input").blur(function() {
		$(".search-input").attr("data-focused", false);
		$(".search-input input").removeClass("_is-focused");
		$("#__expand").removeClass("visible");
	});

	$(".post-meta .post-meta-inner .cta-btns a.is_inactive").on("click", function(e) {
		e.preventDefault();
	});

	$(document).keydown(function(e) {
    if (e.keyCode == 27) {
        closeUiOverlay();
    } else {
		 return;
	 }});

	 $(".mobile-nav").hide();

	// Functions for more-posts button click

	function addLoader() {
		$(".secondary-category-section .category-posts-column [data-clicked='false']").attr("data-clicked", "true").append("");
	}
	$(".secondary-category-section .category-posts-column [data-clicked='false']").on("click", function(e) {
		$(this).css({
			"background": "#50ABF1",
			"color": "#fff"
		});
		addLoader();
		e.preventDefault();
	});

	$to_top.on("click", function(e) {
		$("body,html").animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<commit_msg>Update script.js<commit_after>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 10/01/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/whizkydee/webtwic

*/

jQuery(document).ready(function() {

	// Define Variables
	var is_DisabledFeatures = $("div").hasClass("dfvisible"),
	img = $("img"),
	is_noAlt = img.attr("alt", null),
	scripts = $("script"),
	is_noType = scripts.attr("type", null),
	is_noCharset = scripts.attr("charset", null);

	var $to_top = $("a.to-top"),
	is_toggle_active = $(".hamburger").hasClass("is_active"),
	height = 200;

	// Performance Fixes

	// Create function to add browser name and version to body class

	function showBrowser(b) {
		$("body").addClass(b + " " + b + parseInt(browser.version));
	}

	// Start browser detection

	browser = bowser;
	browser.ie = browser.msie;

	if (browser.webkit) {
		$("body").addClass("webkit");
	}
	if(browser.chrome) {
		showBrowser("chrome");
	}
	if(browser.msedge) {
		showBrowser("msedge");
	}
	if(browser.firefox) {
		showBrowser("firefox");
	}
	if(browser.msie) {
		showBrowser("ie");
	}
	if(browser.safari) {
		showBrowser("safari");
	}
	if(browser.opera) {
		showBrowser("opera");
	}

	// Start function to set attributes and values to elements

	function setAttr(elem, name, val) {
		$(elem, this).attr(name, val);
	}

	if(is_noAlt) {
		setAttr(img, "alt", "...");
	} else {
		return img.attr("alt");
	}

	if(is_noCharset) {
		setAttr(scripts, "charset", "utf-8");
	} else {
		return scripts.attr("charset");
	}

	if(is_noType) {
		setAttr(scripts, "type", "text/javascript");
	} else {
		return scripts.attr("type");
	}

	// Notification for disabled features
	function showDisabledFeatures() {
		$(".top-stripe").before(
			"
Certain features which affect the functionality of webtwic are disabled in your browser. Please try refreshing the page or get a better browser.
"
		);
		$(".close-button").on("click",
			function() {
				hideDisabledFeatures();
				undoSiteAdjust();
			});
	}

	function hideDisabledFeatures() {
		$("#disabledFeatures").removeClass("dfvisible");
	}
	function adjustSiteContent() {
		$(".top-stripe").addClass("adjustedMargin");
		$("#header .logo").addClass("adjustedTop");
		$(".main-menu").addClass("adjustedMargin");
		$("#header").addClass("adjustSiteContent");
	}
	function undoSiteAdjust() {
		$(".top-stripe").removeClass("adjustedMargin");
		$("#header .logo").removeClass("adjustedTop");
		$(".main-menu").removeClass("adjustedMargin");
		$("#header").removeClass("adjustSiteContent");
	}

	// Modernizr funnctions

	function resetSite() {
		showDisabledFeatures();
		adjustSiteContent();
	}

	function undoReset() {
		hideDisabledFeatures();
		undoSiteAdjust();
	}

	if (!Modernizr.flexbox || !Modernizr.inlinesvg || !Modernizr.svg || !Modernizr.svgclippaths || !Modernizr.fontface || !Modernizr.boxshadow || !Modernizr.borderradius || !Modernizr.csstransforms) {
		resetSite();
	} else {
		undoReset();
	}

	// Start Main Page

	$("nav li ul.drop-nav").hide().removeClass("dropNavFallback");

	if ( $(window).width() > 860 ) {
		$("nav li.dropdown").hover(function() {
			$("ul.drop-nav", this).stop().slideDown("fast");
		}, function() {
			$("ul.drop-nav", this).stop().slideUp("fast");
		});
	}

	$(".active-item").append(
		"<svg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><path d='M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z'></path></svg>"
	);

	$("a.hamburger").click(function(e) {
		$(this).toggleClass("is_active");

		e.preventDefault();
	});
	$(".mobile-header .mobile-nav").hide();

	$(window).scroll(function() {
		($(this).scrollTop() > height) ? $to_top.addClass("topVisible"): $to_top.removeClass("topVisible");
	});

	// Styles for homepage article-social

	$(".article .article-social a").hover(function() {
		$("span", this).eq(1).fadeIn(400);
	}, function() {
		$("span", this).eq(1).fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$(".header-follow-search .search-wrap").on("click", function() {
		openUiOverlay();
	});

	$(".header-follow-search .close-icon").on("click", function() {
		closeUiOverlay();
	});

	$(".header-follow-search .close-icon").hover(
		function() {
			$(this).addClass("spin");
		},
		function() {
			$(this).removeClass("spin");
		});

	function openUiOverlay() {
		$(".ui-overlay-search").fadeIn(400).addClass("is_open");
	}

	function closeUiOverlay() {
		$(".ui-overlay-search").fadeOut(400).removeClass("is_open");
	}

	$(".ui-overlay-search .search-input input").focus(function() {
		$(".search-input").attr("data-focused", true);
		$(".search-input input").addClass("_is-focused");
		$("#__expand").addClass("visible");
	});

	$(".ui-overlay-search .search-input input").blur(function() {
		$(".search-input").attr("data-focused", false);
		$(".search-input input").removeClass("_is-focused");
		$("#__expand").removeClass("visible");
	});

	$(".post-meta .post-meta-inner .cta-btns a.is_inactive").on("click", function(e) {
		e.preventDefault();
	});

	$(document).keydown(function(e) {
    if (e.keyCode == 27) {
        closeUiOverlay();
    } else {
		 return;
	 }});

	 $(".mobile-nav").hide();

	// Functions for more-posts button click

	function addLoader() {
		$(".secondary-category-section .category-posts-column [data-clicked='false']").attr("data-clicked", "true").append("");
	}
	$(".secondary-category-section .category-posts-column [data-clicked='false']").on("click", function(e) {
		$(this).css({
			"background": "#50ABF1",
			"color": "#fff"
		});
		addLoader();
		e.preventDefault();
	});

	$to_top.on("click", function(e) {
		$("body,html").animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<|endoftext|>


<commit_before>$(document).ready(function() {
  fetch((window.baseUrl || '') + '/assets/html/custombar.html').then(function(response) {
    return response.text()
  }).then(function(html) {
    html = html.replace(/assets\/img\//g, (window.baseUrl || '') + 'assets/img/')
    $('#custombar').before(html).remove()
    render()
  })
})

var state = {
  letters:      '',
  materials:    ['white', 'white'],
  activeLetter: 0,
}

$(document).on('input', '.js-input', function(evt) {
  setState({
    letters: $(this).val()
  })
})
$(document).on('click', '.js-swatch-link', function(evt) {
  var materials = state.materials.concat([]);
  materials[state.activeLetter] = $(this).data('color')

  setState({
    materials: materials
  })
})
$(document).on('click', '.js-tab', function(evt) {
  setState({
    activeLetter: $(this).data('index')
  })
})

function setState(newState) {
  state = Object.assign({}, state, newState)
  render()
}

function updateCustomInfo() {
  var productDescription = 'Danny-Black'
  if( state.letters.length > 0 ) {
    productDescription += ` / ${state.letters[0].toUpperCase()}-${state.materials[0]}`
  }
  if( state.letters.length > 1 ) {
    productDescription += ` / ${state.letters[1].toUpperCase()}-${state.materials[1]}`
  }

  $("#custombar-custom-info").val(productDescription);
}

function render() {
  // reset
  $('.js-letters').html('')
  $('.js-tab').html('')
  $('.js-tab').removeClass('active')
  $('.js-swatch').removeClass('active')

  // render letters
  if( state.letters.length > 0 ) {
    var letter1 = letter({ letter: state.letters[0], material: state.materials[0]})
    $('.js-letters').append(letter1)
    $('.js-tab:eq(0)').append(letter1.clone())
  }
  if( state.letters.length > 1 ) {
    var letter2 = letter({ letter: state.letters[1], material: state.materials[1]})
    $('.js-letters').append(letter2)
    $('.js-tab:eq(1)').append(letter2.clone())
  }

  // render active tab
  $(`.js-tab[data-index=${state.activeLetter}]`).addClass('active')

  // render active swatch
  $(`.js-swatch[data-color=${state.materials[state.activeLetter]}]`).addClass('active')
  updateCustomInfo()
}

function letter(props) {
  var alt = `${props.letter} in ${props.material}`
  var src = `${window.baseUrl || ''}assets/img/letters/${props.letter.toUpperCase()}-${props.material}.png`;
  return $(`<img src="${src}" alt="${alt}"/>`)
}
<commit_msg>Allow editing by tapping letter on the bag<commit_after>$(document).ready(function() {
  fetch((window.baseUrl || '') + '/assets/html/custombar.html').then(function(response) {
    return response.text()
  }).then(function(html) {
    html = html.replace(/assets\/img\//g, (window.baseUrl || '') + 'assets/img/')
    $('#custombar').before(html).remove()
    render()
  })
})

var state = {
  letters:      '',
  materials:    ['white', 'white'],
  activeLetter: 0,
  editing:      false,
}

$(document).on('input', '.js-input', function(evt) {
  setState({
    letters: $(this).val()
  })
})
$(document).on('click', '.js-swatch-link', function(evt) {
  var materials = state.materials.concat([]);
  materials[state.activeLetter] = $(this).data('color')

  setState({
    materials: materials
  })
})
$(document).on('click', '.js-tab', function(evt) {
  setState({
    activeLetter: $(this).data('index'),
  })
})
$(document).on('click', '.js-letter', function(evt) {
  setState({
    editing: true,
    activeLetter: $(this).data('index'),
  })
})

function setState(newState) {
  state = Object.assign({}, state, newState)
  render()
}

function updateCustomInfo() {
  var productDescription = 'Danny-Black'
  if( state.letters.length > 0 ) {
    productDescription += ` / ${state.letters[0].toUpperCase()}-${state.materials[0]}`
  }
  if( state.letters.length > 1 ) {
    productDescription += ` / ${state.letters[1].toUpperCase()}-${state.materials[1]}`
  }

  $("#custombar-custom-info").val(productDescription);
}

function render() {
  // reset
  $('.js-letters').html('')
  $('.js-tab').html('')
  $('.js-tab').removeClass('active')
  $('.js-swatch').removeClass('active')

  // render letters
  if( state.letters.length > 0 ) {
    var letter1 = letter({ letter: state.letters[0], material: state.materials[0], index: 0})
    $('.js-letters').append(letter1)
    $('.js-tab:eq(0)').append(letter1.clone())
  }
  if( state.letters.length > 1 ) {
    var letter2 = letter({ letter: state.letters[1], material: state.materials[1], index: 1})
    $('.js-letters').append(letter2)
    $('.js-tab:eq(1)').append(letter2.clone())
  }

  // render active tab
  $(`.js-tab[data-index=${state.activeLetter}]`).addClass('active')

  // render active swatch
  $(`.js-swatch[data-color=${state.materials[state.activeLetter]}]`).addClass('active')
  updateCustomInfo()
}

function letter(props) {
  var alt = `${props.letter} in ${props.material}`
  var src = `${window.baseUrl || ''}assets/img/letters/${props.letter.toUpperCase()}-${props.material}.png`;
  return $(`
    <img src="${src}" alt="${alt}" class="js-letter" data-index="${props.index}"/>
  `)
}
<|endoftext|>