<commit_before>import { h, Component } from 'preact';
import Map from 'google-maps-react';

export class Directions extends Component {

    constructor() {
        super();
        this.directionsService = null;
        this.directionsDisplay = null;
    }

    componentDidUpdate(prevProps) {
        if ((this.props.map !== prevProps.map) ||
            (this.props.position !== prevProps.position) ||
            (this.props.points !== prevProps.points)) {
            this.renderDirections();
        }
    }

    renderDirections() {
        if (this.directionsService === null || this.directionsDisplay === null) {
            this.directionsService = new this.props.google.maps.DirectionsService();
            this.directionsDisplay = new this.props.google.maps.DirectionsRenderer();
        }

        this.directionsDisplay.setMap(this.props.map);
        const request = {
            origin: this.props.points.start,
            destination: this.props.points.stop,
            travelMode: this.props.points.mode
        };

        if (request.destination && request.origin) {
            this.directionsService.route(request, (result, status) => {
                if (status == 'OK') {
                    this.directionsDisplay.setDirections(result);
                    console.log('result', result);
                }
            });
        }
    }

    render() {
        return null;
    }

}

export default Directions;<commit_msg>ip-52 cleanup<commit_after>import { h, Component } from 'preact';

export class Directions extends Component {

    constructor() {
        super();
        this.directionsService = null;
        this.directionsDisplay = null;
    }

    componentDidUpdate(prevProps) {
        if ((this.props.map !== prevProps.map) ||
            (this.props.position !== prevProps.position) ||
            (this.props.points !== prevProps.points)) {
            this.renderDirections();
        }
    }

    renderDirections() {
        if (this.directionsService === null || this.directionsDisplay === null) {
            this.directionsService = new this.props.google.maps.DirectionsService();
            this.directionsDisplay = new this.props.google.maps.DirectionsRenderer();
        }

        this.directionsDisplay.setMap(this.props.map);
        const request = {
            origin: this.props.points.start,
            destination: this.props.points.stop,
            travelMode: this.props.points.mode
        };

        if (request.destination && request.origin) {
            this.directionsService.route(request, (result, status) => {
                if (status == 'OK') {
                    this.directionsDisplay.setDirections(result);
                    console.log('result', result);
                }
            });
        }
    }

    render() {
        return null;
    }

}

export default Directions;<|endoftext|>


<commit_before>"use strict";

var fs = require('fs'),
    etree = require('elementtree'),
    utils = require('./utils'),
    JSZip = require('jszip'),
    Sheet = require('./Sheet');

/**
 * Initializes a new Workbook.
 * @param {Buffer} data
 * @constructor
 */
var Workbook = function (data) {
    this._zip = new JSZip(data, { base64: false, checkCRC32: true });
    var workbookText = this._zip.file("xl/workbook.xml").asText();
    this._workbookXML = etree.parse(workbookText);

    this.sheets = [];
    var sheetNodes = this._workbookXML.findall("*/sheet");
    for (var i = 0; i < sheetNodes.length; i++) {
        var index = i + 1;
        var sheetText = this._zip.file("xl/worksheets/sheet" + index + ".xml").asText();
        var sheetXML = etree.parse(sheetText);

        // This is a blunt way to make sure formula values get updated.
        // It just clears all stored values in case the referenced cell values change.
        var formulaParents = sheetXML.findall("sheetData/row/c/f/..");
        formulaParents.forEach(function (formulaParent) {
            var vNode = formulaParent.find("v");
            if (vNode) formulaParent.remove(vNode);
        });

        var sheet = new Sheet(this, sheetNodes[i], sheetXML);
        this.sheets.push(sheet);
    }
};

/**
 * Gets the sheet with the provided name or index (0-based).
 * @param {string|number} sheetNameOrIndex
 * @returns {*}
 */
Workbook.prototype.getSheet = function (sheetNameOrIndex) {
    if (Number.isInteger(sheetNameOrIndex)) return this.sheets[sheetNameOrIndex];

    for (var i = 0; i < this.sheets.length; i++) {
        var sheet = this.sheets[i];
        if (sheet.getName() === sheetNameOrIndex) return sheet;
    }
};

/**
 * Get a named cell. (Assumes names with workbook scope pointing to single cells.)
 * @param {string} cellName
 * @returns {Cell}
 */
Workbook.prototype.getNamedCell = function (cellName) {
    var definedName = this._workbookXML.find("definedNames/definedName[@name='" + cellName + "']");
    if (!definedName) return;

    var address = definedName.text;
    var ref = utils.addressToRowAndColumn(address);
    if (!ref) return;

    return this.getSheet(ref.sheet).getCell(ref.row, ref.column);
};

/**
 * Gets the output.
 * @returns {Buffer}
 */
Workbook.prototype.output = function () {
    this._zip.file("xl/workbook.xml", this._workbookXML.write());

    for (var i = 0; i < this.sheets.length; i++) {
        var index = i + 1;
        var sheet = this.sheets[i];
        this._zip.file("xl/worksheets/sheet" + index + ".xml", sheet._sheetXML.write())
    }

    // Kill the calc chain since this will corrupt the file is formulas are removed.
    this._zip.remove("xl/calcChain.xml");

    return this._zip.generate({ type: "nodebuffer" });
};

/**
 * Writes to file with the given path.
 * @param {string} path
 * @param cb
 */
Workbook.prototype.toFile = function (path, cb) {
    fs.writeFile(path, this.output(), cb);
};

/**
 * Wirtes to file with the given path synchronously.
 * @param {string} path
 */
Workbook.prototype.toFileSync = function (path) {
    fs.writeFileSync(path, this.output());
};

/**
 * Creates a Workbook from the file with the given path.
 * @param {string} path
 * @param cb
 */
Workbook.fromFile = function (path, cb) {
    fs.readFile(path, function (err, data) {
        if (err) return cb(err);
        cb(null, new Workbook(data));
    });
};

/**
 * Creates a Workbook from the file with the given path synchronously.
 * @param path
 * @returns {Workbook}
 */
Workbook.fromFileSync = function (path) {
    var data = fs.readFileSync(path);
    return new Workbook(data);
};

module.exports = Workbook;
<commit_msg>Fixed JSDocs.<commit_after>"use strict";

var fs = require('fs'),
    etree = require('elementtree'),
    utils = require('./utils'),
    JSZip = require('jszip'),
    Sheet = require('./Sheet');

/**
 * Initializes a new Workbook.
 * @param {Buffer} data
 * @constructor
 */
var Workbook = function (data) {
    this._zip = new JSZip(data, { base64: false, checkCRC32: true });
    var workbookText = this._zip.file("xl/workbook.xml").asText();
    this._workbookXML = etree.parse(workbookText);

    this.sheets = [];
    var sheetNodes = this._workbookXML.findall("*/sheet");
    for (var i = 0; i < sheetNodes.length; i++) {
        var index = i + 1;
        var sheetText = this._zip.file("xl/worksheets/sheet" + index + ".xml").asText();
        var sheetXML = etree.parse(sheetText);

        // This is a blunt way to make sure formula values get updated.
        // It just clears all stored values in case the referenced cell values change.
        var formulaParents = sheetXML.findall("sheetData/row/c/f/..");
        formulaParents.forEach(function (formulaParent) {
            var vNode = formulaParent.find("v");
            if (vNode) formulaParent.remove(vNode);
        });

        var sheet = new Sheet(this, sheetNodes[i], sheetXML);
        this.sheets.push(sheet);
    }
};

/**
 * Gets the sheet with the provided name or index (0-based).
 * @param {string|number} sheetNameOrIndex
 * @returns {Sheet}
 */
Workbook.prototype.getSheet = function (sheetNameOrIndex) {
    if (Number.isInteger(sheetNameOrIndex)) return this.sheets[sheetNameOrIndex];

    for (var i = 0; i < this.sheets.length; i++) {
        var sheet = this.sheets[i];
        if (sheet.getName() === sheetNameOrIndex) return sheet;
    }
};

/**
 * Get a named cell. (Assumes names with workbook scope pointing to single cells.)
 * @param {string} cellName
 * @returns {Cell}
 */
Workbook.prototype.getNamedCell = function (cellName) {
    var definedName = this._workbookXML.find("definedNames/definedName[@name='" + cellName + "']");
    if (!definedName) return;

    var address = definedName.text;
    var ref = utils.addressToRowAndColumn(address);
    if (!ref) return;

    return this.getSheet(ref.sheet).getCell(ref.row, ref.column);
};

/**
 * Gets the output.
 * @returns {Buffer}
 */
Workbook.prototype.output = function () {
    this._zip.file("xl/workbook.xml", this._workbookXML.write());

    for (var i = 0; i < this.sheets.length; i++) {
        var index = i + 1;
        var sheet = this.sheets[i];
        this._zip.file("xl/worksheets/sheet" + index + ".xml", sheet._sheetXML.write())
    }

    // Kill the calc chain since this will corrupt the file is formulas are removed.
    this._zip.remove("xl/calcChain.xml");

    return this._zip.generate({ type: "nodebuffer" });
};

/**
 * Writes to file with the given path.
 * @param {string} path
 * @param {function} cb
 */
Workbook.prototype.toFile = function (path, cb) {
    fs.writeFile(path, this.output(), cb);
};

/**
 * Wirtes to file with the given path synchronously.
 * @param {string} path
 */
Workbook.prototype.toFileSync = function (path) {
    fs.writeFileSync(path, this.output());
};

/**
 * Creates a Workbook from the file with the given path.
 * @param {string} path
 * @param {function} cb
 */
Workbook.fromFile = function (path, cb) {
    fs.readFile(path, function (err, data) {
        if (err) return cb(err);
        cb(null, new Workbook(data));
    });
};

/**
 * Creates a Workbook from the file with the given path synchronously.
 * @param path
 * @returns {Workbook}
 */
Workbook.fromFileSync = function (path) {
    var data = fs.readFileSync(path);
    return new Workbook(data);
};

module.exports = Workbook;
<|endoftext|>


<commit_before>morpheus.CollapseDatasetTool = function() {
};
morpheus.CollapseDatasetTool.Functions = [ morpheus.Mean, morpheus.Median,
		new morpheus.MaxPercentiles([ 25, 75 ]), morpheus.Min, morpheus.Max ];
morpheus.CollapseDatasetTool.Functions.fromString = function(s) {
	for (var i = 0; i < morpheus.CollapseDatasetTool.Functions.length; i++) {
		if (morpheus.CollapseDatasetTool.Functions[i].toString() === s) {
			return morpheus.CollapseDatasetTool.Functions[i];
		}
	}
	throw new Error(s + ' not found');
};
morpheus.CollapseDatasetTool.prototype = {
	toString : function() {
		return 'Collapse';
	},
	init : function(project, form) {
		var setValue = function(val) {
			var isRows = val === 'Rows';
			var names = morpheus.MetadataUtil.getMetadataNames(isRows ? project
					.getFullDataset().getRowMetadata() : project
					.getFullDataset().getColumnMetadata());
			form.setOptions('collapse_to_fields', names);
		};
		form.$form.find('[name=collapse]').on('change', function(e) {
			setValue($(this).val());
		});
		setValue('Rows');
	},
	gui : function() {
		return [ {
			name : 'collapse_method',
			options : morpheus.CollapseDatasetTool.Functions,
			value : morpheus.CollapseDatasetTool.Functions[1].toString(),
			type : 'select'
		}, {
			name : 'collapse',
			options : [ 'Columns', 'Rows' ],
			value : 'Rows',
			type : 'radio'
		}, {
			name : 'collapse_to_fields',
			options : [],
			type : 'select',
			multiple : true
		} ];
	},
	execute : function(options) {
		var project = options.project;
		var controller = options.controller;
		var f = morpheus.CollapseDatasetTool.Functions
				.fromString(options.input.collapse_method);
		var collapseToFields = options.input.collapse_to_fields;
		if (collapseToFields.length === 0) {
			throw new Error('Please select one or more fields to collapse to');
		}
		var dataset = project.getFullDataset();
		var rows = options.input.collapse == 'Rows';
		if (!rows) {
			dataset = morpheus.DatasetUtil.transposedView(dataset);
		}
		var allFields = morpheus.MetadataUtil.getMetadataNames(dataset
				.getRowMetadata());
		dataset = morpheus.CollapseDataset(dataset, collapseToFields, f, true);
		if (!rows) {
			dataset = dataset.getDataset();
		}
		var set = new morpheus.Map();
		_.each(allFields, function(field) {
			set.set(field, true);
		});
		_.each(collapseToFields, function(field) {
			set.remove(field);
		});
		// hide fields that were not part of collapse to
		set.forEach(function(val, name) {
			controller.setTrackVisible(name, false, !rows);
		});
		project.setFullDataset(dataset, true);
	}
};<commit_msg>added sum<commit_after>morpheus.CollapseDatasetTool = function () {
};
morpheus.CollapseDatasetTool.Functions = [morpheus.Mean, morpheus.Median,
	new morpheus.MaxPercentiles([25, 75]), morpheus.Min, morpheus.Max, morpheus.Sum];
morpheus.CollapseDatasetTool.Functions.fromString = function (s) {
	for (var i = 0; i < morpheus.CollapseDatasetTool.Functions.length; i++) {
		if (morpheus.CollapseDatasetTool.Functions[i].toString() === s) {
			return morpheus.CollapseDatasetTool.Functions[i];
		}
	}
	throw new Error(s + ' not found');
};
morpheus.CollapseDatasetTool.prototype = {
	toString: function () {
		return 'Collapse';
	},
	init: function (project, form) {
		var setValue = function (val) {
			var isRows = val === 'Rows';
			var names = morpheus.MetadataUtil.getMetadataNames(isRows ? project
			.getFullDataset().getRowMetadata() : project
			.getFullDataset().getColumnMetadata());
			form.setOptions('collapse_to_fields', names);
		};
		form.$form.find('[name=collapse]').on('change', function (e) {
			setValue($(this).val());
		});
		setValue('Rows');
	},
	gui: function () {
		return [{
			name: 'collapse_method',
			options: morpheus.CollapseDatasetTool.Functions,
			value: morpheus.CollapseDatasetTool.Functions[1].toString(),
			type: 'select'
		}, {
			name: 'collapse',
			options: ['Columns', 'Rows'],
			value: 'Rows',
			type: 'radio'
		}, {
			name: 'collapse_to_fields',
			options: [],
			type: 'select',
			multiple: true
		}];
	},
	execute: function (options) {
		var project = options.project;
		var controller = options.controller;
		var f = morpheus.CollapseDatasetTool.Functions
		.fromString(options.input.collapse_method);
		var collapseToFields = options.input.collapse_to_fields;
		if (collapseToFields.length === 0) {
			throw new Error('Please select one or more fields to collapse to');
		}
		var dataset = project.getFullDataset();
		var rows = options.input.collapse == 'Rows';
		if (!rows) {
			dataset = morpheus.DatasetUtil.transposedView(dataset);
		}
		var allFields = morpheus.MetadataUtil.getMetadataNames(dataset
		.getRowMetadata());
		dataset = morpheus.CollapseDataset(dataset, collapseToFields, f, true);
		if (!rows) {
			dataset = dataset.getDataset();
		}
		var set = new morpheus.Map();
		_.each(allFields, function (field) {
			set.set(field, true);
		});
		_.each(collapseToFields, function (field) {
			set.remove(field);
		});
		// hide fields that were not part of collapse to
		set.forEach(function (val, name) {
			controller.setTrackVisible(name, false, !rows);
		});
		project.setFullDataset(dataset, true);
	}
};
<|endoftext|>


<commit_before>/*
	mokjs配置文件，详细请参考：http://mokjs.com/
*/

var http_port = 80; //服务器默认监听端口

//项目配置
var projects = {
	'blog': {
		//path是项目代码路径，相对于__config.js这个文件的路径，也可用绝对路径。
		//有多个开发分支时，将路径指到对应分支就行（解决多分支切换开发）。
		path: '../demos/blog/src-define/',
		build_path: '../demos/blog/build/',
		modular_spec: 'CMD',	//遵循的模块化规范：'CMD' - CMD规范，'Modules' - CommonJS Modules规范
		boot_js: 'abc.js',	//启动文件（种子文件）
		use_base: true,	//是否使用了base.js（base.js是拆分出来的基本库文件或所有页面都用到的文件）
		charset: 'utf8',	//gbk
		//格式化上线tag号。参数tag_num为打包时输入的版本号或某种格式的字符串。
		format_tag: function(tag_num){
			var t = new Date(), M = t.getMonth()+1, d = t.getDate();
			return {
				version: '' + t.getFullYear() + (M>9 ? M : '0'+M) +'/'+ (d>9 ? d : '0'+d) + '/js_' + tag_num + '/',
				folder_name: 'js_' + tag_num	//存放所有更新的文件的文件夹名，在updated目录下。前后都别加反斜线“/”。
			};
		},
		//惰性压缩列表
		lazy_list: {
			//'test.js': true
		}
	},
	'mycss': {
		type: 'css',	//项目类型
		path: '../demos/css/',	 //也可以使用绝对路径
		build_path: '../demos/css-build/',	//构建路径，合并压缩后的css存放的地方
		ver_js: 'version.js',	 //存放版本和MD5信息的文件，可选
		charset: 'utf8',	//gbk。css源文件编码
		//格式化上线tag号，可选
		format_tag: function(tag_num){
			var t = new Date(), M = t.getMonth()+1, d = t.getDate();
			if(!tag_num){
				var h = t.getHours(), m = t.getMinutes();
				h<10 && (h = '0'+h);
				m<10 && (m = '0'+m);
				tag_num = String(h)+String(m);
			}
			//前后都别加反斜线“/”
			return {
				version: '' + t.getFullYear() + (M>9 ? M : '0'+M) +'/'+ (d>9 ? d : '0'+d) + '/css_' + tag_num + '/',
				folder_name: 'css_' + tag_num	//存放有更新的文件的文件夹名，在updated目录下
			};
		}
	},
	'myhtml': {
		type: 'html',	//项目类型
		path: '../demos/html/',	//相对于__config.js的相对路径，推荐使用绝对路径
		build_path: '../demos/www/',	//构建路径
		data: {	//开发时的全局数据
			$root: '//s.m.com/',	//图片、CSS、JS资源
			$jquery: '//libs.baidu.com/jquery/1.11.1/jquery.min.js'
		},
		build_data: {	//构建时的全局数据
			$root: '//mokjs.sinaapp.com/',	 //图片、CSS、JS资源
			$jquery: '//libs.baidu.com/jquery/1.11.1/jquery.min.js'
		},
		charset: 'utf8'	//gbk。html源文件编码
	},
	'air': {
		path: '../demos/air', //源代码路径
		doc_path: '../demos/air-doc', //文档生成到哪里
		charset: 'utf8' //源代码的文件编码
	}
};

//路由表
var routes = {
	'blog.cn': [
		{
			regexp: /^\/js\/(\w+\.js)$/,	//匹配http://blog.cn/js/*.js这样的js请求
			project: 'blog'	//将请求映射到blog项目，regexp里(\w+\.js)部分的值为映射过去文件名
		},
		{
			regexp: /^\/css\/(.+?\.css)$/,	//匹配http://blog.cn/css/*.css这样的css请求
			//说明：/css/a.css会映射到mycss下的a.css，/css/main/test.css会映射到mycss下的main/test.css
			project: 'mycss'	//将请求映射到mycss项目
		},
		{
			regexp: /.*/,	//不满足前面格式的其他任何请求，直接定位到资源位置
			locate: function(match){
				//返回相对于__config.js这个文件的路径，也可用绝对路径
				return '../demos/blog/static' + match[0]; //return 'D:/1144/demos/blog/static' + match[0];
			}
		}
	],
	'm.com': [
		{
			regexp: /^.+?\.html$/,	 //处理所有.html结尾的请求
			project: 'myhtml'
		}, {
			regexp: /.+?\.pre$/,	//以.pre结尾的请求，映射到预览模块
			handler: function(match, request, response, reqpath){
				require('./moktext/html').viewModule(match[0].slice(0,-3)+'html', projects['myhtml'], response);
			}
		}, {
			regexp: /.*?\/$/,	//以/结尾的，请求对应的index.html，实现默认index.html
			project: 'myhtml',
			format: function(match){
				return match[0]+'index.html';
			}
		}, {
			regexp: /.*/,
			locate: function(match){
				return projects['myhtml'].path + match[0];
			}
		}
	],
	's.m.com': [	//图片、CSS和JS资源
		{
			regexp: /.*/,
			locate: function(match){
				return '../demos/www' + match[0];	 //不需要处理的资源，直接定位到资源位置
			}
		}
	],
	'count.cn': [
		{
			//用自定义的模块 处理url符合某种格式的http请求：http://count.cn/3
			//累加最后的数字
			regexp: /^\/(\d+)$/,
			handler: function(match, request, response, reqpath){
				require('./mok_modules/demo').count(match[1], response);
			}
		}
	],
	//js使用同一个域名的不同产品线
	'js.xxx.com': [
		{
			regexp: /^\/(\w+\.js)$/,
			project: 'ecom'
		}, {
			regexp: /^\/test\/(\w+\.js)$/,
			project: 'test',
			format: function(match){	//对js请求路径进行重定向
				return match[1];
			}
		}
	]
};

exports.http_port = http_port;
exports.projects = projects;
exports.routes = routes;

//Uglifyjs压缩
exports.compress_cmd = 'uglifyjs {filename} -m -c unused=true -o {filename}';
//YUI压缩
//exports.compress_cmd = 'java -jar ./mokjs/yuicompressor-2.4.2.jar {filename} -o {filename}';

//mokdoc标签别名配置：tag的别名与tag id的映射
exports.alias2tagid = {
	'method': 'fn',
	'version': 'ver'
};

/*exports.proxy_conf = {
	'8086': {
		'ecom.com': [
			{
				regexp: /b\.html/,
				head: function(header, match){
					return {
						host: 'm.com',
						path: '/start.html'
					};
				}
			}
		]
	},
};*/
<commit_msg>v1.2.3 修改uglifyjs压缩命令<commit_after>/*
	mokjs配置文件，详细请参考：http://mokjs.com/
*/

var http_port = 80; //服务器默认监听端口

//项目配置
var projects = {
	'blog': {
		//path是项目代码路径，相对于__config.js这个文件的路径，也可用绝对路径。
		//有多个开发分支时，将路径指到对应分支就行（解决多分支切换开发）。
		path: '../demos/blog/src-define/',
		build_path: '../demos/blog/build/',
		modular_spec: 'CMD',	//遵循的模块化规范：'CMD' - CMD规范，'Modules' - CommonJS Modules规范
		boot_js: 'abc.js',	//启动文件（种子文件）
		use_base: true,	//是否使用了base.js（base.js是拆分出来的基本库文件或所有页面都用到的文件）
		charset: 'utf8',	//gbk
		//格式化上线tag号。参数tag_num为打包时输入的版本号或某种格式的字符串。
		format_tag: function(tag_num){
			var t = new Date(), M = t.getMonth()+1, d = t.getDate();
			return {
				version: '' + t.getFullYear() + (M>9 ? M : '0'+M) +'/'+ (d>9 ? d : '0'+d) + '/js_' + tag_num + '/',
				folder_name: 'js_' + tag_num	//存放所有更新的文件的文件夹名，在updated目录下。前后都别加反斜线“/”。
			};
		},
		//惰性压缩列表
		lazy_list: {
			//'test.js': true
		}
	},
	'mycss': {
		type: 'css',	//项目类型
		path: '../demos/css/',	 //也可以使用绝对路径
		build_path: '../demos/css-build/',	//构建路径，合并压缩后的css存放的地方
		ver_js: 'version.js',	 //存放版本和MD5信息的文件，可选
		charset: 'utf8',	//gbk。css源文件编码
		//格式化上线tag号，可选
		format_tag: function(tag_num){
			var t = new Date(), M = t.getMonth()+1, d = t.getDate();
			if(!tag_num){
				var h = t.getHours(), m = t.getMinutes();
				h<10 && (h = '0'+h);
				m<10 && (m = '0'+m);
				tag_num = String(h)+String(m);
			}
			//前后都别加反斜线“/”
			return {
				version: '' + t.getFullYear() + (M>9 ? M : '0'+M) +'/'+ (d>9 ? d : '0'+d) + '/css_' + tag_num + '/',
				folder_name: 'css_' + tag_num	//存放有更新的文件的文件夹名，在updated目录下
			};
		}
	},
	'myhtml': {
		type: 'html',	//项目类型
		path: '../demos/html/',	//相对于__config.js的相对路径，推荐使用绝对路径
		build_path: '../demos/www/',	//构建路径
		data: {	//开发时的全局数据
			$root: '//s.m.com/',	//图片、CSS、JS资源
			$jquery: '//libs.baidu.com/jquery/1.11.1/jquery.min.js'
		},
		build_data: {	//构建时的全局数据
			$root: '//mokjs.sinaapp.com/',	 //图片、CSS、JS资源
			$jquery: '//libs.baidu.com/jquery/1.11.1/jquery.min.js'
		},
		charset: 'utf8'	//gbk。html源文件编码
	},
	'air': {
		path: '../demos/air', //源代码路径
		doc_path: '../demos/air-doc', //文档生成到哪里
		charset: 'utf8' //源代码的文件编码
	}
};

//路由表
var routes = {
	'blog.cn': [
		{
			regexp: /^\/js\/(\w+\.js)$/,	//匹配http://blog.cn/js/*.js这样的js请求
			project: 'blog'	//将请求映射到blog项目，regexp里(\w+\.js)部分的值为映射过去文件名
		},
		{
			regexp: /^\/css\/(.+?\.css)$/,	//匹配http://blog.cn/css/*.css这样的css请求
			//说明：/css/a.css会映射到mycss下的a.css，/css/main/test.css会映射到mycss下的main/test.css
			project: 'mycss'	//将请求映射到mycss项目
		},
		{
			regexp: /.*/,	//不满足前面格式的其他任何请求，直接定位到资源位置
			locate: function(match){
				//返回相对于__config.js这个文件的路径，也可用绝对路径
				return '../demos/blog/static' + match[0]; //return 'D:/1144/demos/blog/static' + match[0];
			}
		}
	],
	'm.com': [
		{
			regexp: /^.+?\.html$/,	 //处理所有.html结尾的请求
			project: 'myhtml'
		}, {
			regexp: /.+?\.pre$/,	//以.pre结尾的请求，映射到预览模块
			handler: function(match, request, response, reqpath){
				require('./moktext/html').viewModule(match[0].slice(0,-3)+'html', projects['myhtml'], response);
			}
		}, {
			regexp: /.*?\/$/,	//以/结尾的，请求对应的index.html，实现默认index.html
			project: 'myhtml',
			format: function(match){
				return match[0]+'index.html';
			}
		}, {
			regexp: /.*/,
			locate: function(match){
				return projects['myhtml'].path + match[0];
			}
		}
	],
	's.m.com': [	//图片、CSS和JS资源
		{
			regexp: /.*/,
			locate: function(match){
				return '../demos/www' + match[0];	 //不需要处理的资源，直接定位到资源位置
			}
		}
	],
	'count.cn': [
		{
			//用自定义的模块 处理url符合某种格式的http请求：http://count.cn/3
			//累加最后的数字
			regexp: /^\/(\d+)$/,
			handler: function(match, request, response, reqpath){
				require('./mok_modules/demo').count(match[1], response);
			}
		}
	],
	//js使用同一个域名的不同产品线
	'js.xxx.com': [
		{
			regexp: /^\/(\w+\.js)$/,
			project: 'ecom'
		}, {
			regexp: /^\/test\/(\w+\.js)$/,
			project: 'test',
			format: function(match){	//对js请求路径进行重定向
				return match[1];
			}
		}
	]
};

exports.http_port = http_port;
exports.projects = projects;
exports.routes = routes;

//uglifyjs压缩，如果已全局安装了uglifyjs，则压缩命令为 'uglifyjs {filename} -m -c unused=true -o {filename}'
exports.compress_cmd = 'node node_modules/uglify-js/bin/uglifyjs {filename} -m -c unused=true -o {filename}';
//YUI压缩
//exports.compress_cmd = 'java -jar ./mokjs/yuicompressor-2.4.2.jar {filename} -o {filename}';

//mokdoc标签别名配置：tag的别名与tag id的映射
exports.alias2tagid = {
	'method': 'fn',
	'version': 'ver'
};

/*exports.proxy_conf = {
	'8086': {
		'ecom.com': [
			{
				regexp: /b\.html/,
				head: function(header, match){
					return {
						host: 'm.com',
						path: '/start.html'
					};
				}
			}
		]
	},
};*/
<|endoftext|>


<commit_before>/***
Adds the app switcher to a TiddlySpace app.

Makes use of tw.Stylesheet
Triple licensed under the BSD, MIT and GPL licenses:
  http://www.opensource.org/licenses/bsd-license.php
  http://www.opensource.org/licenses/mit-license.php
  http://www.gnu.org/licenses/gpl.html
***/
(function() {

// Add or replace a style sheet
// css argument is a string of CSS rule sets
// options.id is an optional name identifying the style sheet
// options.doc is an optional document reference
// N.B.: Uses DOM methods instead of jQuery to ensure cross-browser comaptibility.
var twStylesheet = function(css, options) {
	options = options || {};
	var id = options.id || "backstageStyleSheet";
	var doc = options.doc || document;
	var el = doc.getElementById(id);
	if(doc.createStyleSheet) { // IE-specific handling
		if(el) {
			el.parentNode.removeChild(el);
		}
		doc.getElementsByTagName("head")[0].insertAdjacentHTML("beforeEnd",
			' '); // fails without
	} else { // modern browsers
		if(el) {
			el.replaceChild(doc.createTextNode(css), el.firstChild);
		} else {
			el = doc.createElement("style");
			el.type = "text/css";
			el.id = id;
			el.appendChild(doc.createTextNode(css));
			doc.getElementsByTagName("head")[0].appendChild(el);
		}
	}
};

// detect background-size support
// in <IE9 need to fallback to msfilter property
function hasBgSizing() {
	var supported,
		elem = document.createElement('div');

	document.body.appendChild(elem);
	elem.style.cssText = "background-size: cover;";
	supported = (elem.style.backgroundSize === undefined || elem.style.backgroundSize === null) ? false : true;
	// clean up
	elem.parentNode.removeChild(elem);
	return supported;
}
var backgroundSizeSupported = hasBgSizing();

// ms filters as fix for not supporting background-size property
var msfilter_in = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://tiddlyspace.com/bags/tiddlyspace/tiddlers/privateAndPublicIcon', sizingMethod='scale')",
	msfilter_out = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://tiddlyspace.com/bags/tiddlyspace/tiddlers/privateAndPublicIcon', sizingMethod='scale')";

var stylesheet = ["iframe {",
"	height: 180px;",
"	z-index: 1000;",
"	position: relative;",
"}",
"",
"#app-picker {",
"	cursor: pointer;",
"	position: absolute;",
"	right: 24px;",
"	top: 0px;",
"	width: 24px;",
"	height: 24px;",
"	background-size: 24px 24px;",
"	text-indent: -999px;",
"	overflow: hidden;",
"	z-index: 2000;",
"	border: none;",
"	opacity: 0.5;",
"}",
"",
"#app-picker:hover {",
"	background-color: none !important;",
"	opacity: 1;",
"}",
"",
".bs-popup {",
"	width: 100%;",
"	position: absolute;",
"	z-index: 1000;",
"	right: 10px;",
"	top: 52px;",
"}",
"",
".bubble .description {",
"	margin-left: 70px;",
"	margin-top: 2px;",
"}",
"",
".bubble {",
"	float: right;",
"	font-size: 0.9em;",
"	font-family: Georgia;",
"	position: relative;",
"	width: 300px;",
"	margin: 0px auto 0px auto;",
"	margin: top right bottom left;",
"	padding: 20px 20px 20px 10px;",
"	border: solid 2px rgb(255, 255, 255);",
"	border-radius: 8px 8px;",
"	-webkit-box-shadow: #F4C4E0 0px 0px 8px;",
"	-moz-box-shadow: #F4C4E0 0px 0px 8px;",
"	-o-box-shadow: #F4C4E0 0px 0px 8px;",
"	-ms-box-shadow: #F4C4E0 0px 0px 8px;",
"	box-shadow: #F4C4E0 0px 0px 8px;",
"	background-color: rgb(220, 231, 241);",
"}",
"",
".bubble .tail:before {",
"	content: \"\";",
"	position:absolute;",
"	border-style:solid;",
"	display:block; ",
"	width:0;",
"	top:-24px;",
"	right:5px;",
"	bottom:auto;",
"	left:auto;",
"	opacity: 0.5;",
"	border-width:0 20px 20px;",
"	border-color: rgba(244, 196, 224, 0.6) transparent;",
"}",
"",
".bubble .tail:after {",
"	content:\"\";",
"	position:absolute;",
"	border-style:solid;",
"	display:block; ",
"	width:0;",
"	top:-15px;",
"	right:10px;",
"	bottom:auto;",
"	left:auto;",
"	border-width:0 15px 15px;",
"	border-color: #DCE7F1 transparent;",
"}",
".ts-logout {",
"	display: none;",
"}",
".ts-loggedin .ts-logout {",
"	display: block;",
"}"
].join("\n");

function addEventListener(node, event, handler, bubble) {
	if (node.addEventListener){
		node.addEventListener(event, handler, bubble);
	} else if (node.attachEvent){
		event = event == "click" ? "onclick" : event;
		event = event == "load" ? "onload" : event;
		node.attachEvent(event, handler);
	}
}

var loadEvent = function() {
	var link = document.createElement("a");
	link.setAttribute("id", "app-picker");
	link.setAttribute("class", "app-picker");
	link.appendChild(document.createTextNode("tiddlyspace"));

        // Quite a hack. GUEST does not have a csrf token.
        if (/csrf_token=\d+:\w+:\w+/.test(document.cookie)) {
			if( backgroundSizeSupported ) {
				link.style.backgroundImage = 'url(/bags/tiddlyspace/tiddlers/privateAndPublicIcon)';
			} else {
				link.style.filter = msfilter_in;
			}
        } else {
			if( backgroundSizeSupported ) {
				link.style.backgroundImage = 'url(/bags/tiddlyspace/tiddlers/publicIcon)';
			} else {
				link.style.filter = msfilter_out;
			}
			stylesheet = stylesheet.replace('height: 180px;', 'height: 156px;');
        }

	var body = document.getElementsByTagName("BODY")[0];
	body.insertBefore(link, body.firstChild);
	var html = [
	'
',
		'',
		'

',
	'
'].join("");
	var bubble = document.createElement("div");
	bubble.setAttribute("id", "bs-popup");
	bubble.style.cssText = "visibility:hidden;";
	bubble.className = "bs-popup";
	bubble.innerHTML = html;
	body.insertBefore(bubble, link);

	twStylesheet(stylesheet);

	var bubbleFadeInterval;
	function fade(el, fadeIn) {
		var opacity = fadeIn ? 0 : 1;
		if(bubbleFadeInterval) {
			clearInterval(bubbleFadeInterval);
		}
		bubbleFadeInterval = setInterval(function() {
			// TODO: IE does not support opacity
			el.style.cssText = "opacity:" + opacity;
			opacity = fadeIn ? opacity + 0.1 : opacity - 0.1;
			if(opacity < 0 || opacity > 1) {
				clearInterval(bubbleFadeInterval);
				el.style.cssText = fadeIn ? "" : "visibility:hidden;";
			}
		}, 50);
	}

	addEventListener(link, "mousedown", function(ev) {
		ev.preventDefault();
	}, false);

	var bubbleOpen = false;
	var toggleBubble = function(ev) {
		if(ev.stopPropagation) {
			ev.stopPropagation();
		} else {
			ev.cancelBubble = false;
		}
		if(bubbleOpen) {
			fade(bubble, false);
		} else {
			fade(bubble, true);
		}
		bubbleOpen = !bubbleOpen;
	};

	addEventListener(link, "click", toggleBubble);

	addEventListener(window, "click",
		function(ev) {
			if(bubbleOpen) {
				toggleBubble(ev);
			}
		}, true);

	addEventListener(bubble, "click", function(ev) {
		if(ev.stopPropagation) {
			ev.stopPropagation();
		} else {
			ev.cancelBubble = false;
		}
	});
};

if(window.top == window) { // only add the backstage when NOT in an iframe (top window)
	addEventListener(window, "load", loadEvent);
}

})();
<commit_msg>No need to have fully qualified URIs for roundel icon paths<commit_after>/***
Adds the app switcher to a TiddlySpace app.

Makes use of tw.Stylesheet
Triple licensed under the BSD, MIT and GPL licenses:
  http://www.opensource.org/licenses/bsd-license.php
  http://www.opensource.org/licenses/mit-license.php
  http://www.gnu.org/licenses/gpl.html
***/
(function() {

// Add or replace a style sheet
// css argument is a string of CSS rule sets
// options.id is an optional name identifying the style sheet
// options.doc is an optional document reference
// N.B.: Uses DOM methods instead of jQuery to ensure cross-browser comaptibility.
var twStylesheet = function(css, options) {
	options = options || {};
	var id = options.id || "backstageStyleSheet";
	var doc = options.doc || document;
	var el = doc.getElementById(id);
	if(doc.createStyleSheet) { // IE-specific handling
		if(el) {
			el.parentNode.removeChild(el);
		}
		doc.getElementsByTagName("head")[0].insertAdjacentHTML("beforeEnd",
			' '); // fails without
	} else { // modern browsers
		if(el) {
			el.replaceChild(doc.createTextNode(css), el.firstChild);
		} else {
			el = doc.createElement("style");
			el.type = "text/css";
			el.id = id;
			el.appendChild(doc.createTextNode(css));
			doc.getElementsByTagName("head")[0].appendChild(el);
		}
	}
};

// detect background-size support
// in <IE9 need to fallback to msfilter property
function hasBgSizing() {
	var supported,
		elem = document.createElement('div');

	document.body.appendChild(elem);
	elem.style.cssText = "background-size: cover;";
	supported = (elem.style.backgroundSize === undefined || elem.style.backgroundSize === null) ? false : true;
	// clean up
	elem.parentNode.removeChild(elem);
	return supported;
}
var backgroundSizeSupported = hasBgSizing();

// ms filters as fix for not supporting background-size property
var msfilter_in = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/bags/tiddlyspace/tiddlers/privateAndPublicIcon', sizingMethod='scale')",
	msfilter_out = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/bags/tiddlyspace/tiddlers/privateAndPublicIcon', sizingMethod='scale')";

var stylesheet = ["iframe {",
"	height: 180px;",
"	z-index: 1000;",
"	position: relative;",
"}",
"",
"#app-picker {",
"	cursor: pointer;",
"	position: absolute;",
"	right: 24px;",
"	top: 0px;",
"	width: 24px;",
"	height: 24px;",
"	background-size: 24px 24px;",
"	text-indent: -999px;",
"	overflow: hidden;",
"	z-index: 2000;",
"	border: none;",
"	opacity: 0.5;",
"}",
"",
"#app-picker:hover {",
"	background-color: none !important;",
"	opacity: 1;",
"}",
"",
".bs-popup {",
"	width: 100%;",
"	position: absolute;",
"	z-index: 1000;",
"	right: 10px;",
"	top: 52px;",
"}",
"",
".bubble .description {",
"	margin-left: 70px;",
"	margin-top: 2px;",
"}",
"",
".bubble {",
"	float: right;",
"	font-size: 0.9em;",
"	font-family: Georgia;",
"	position: relative;",
"	width: 300px;",
"	margin: 0px auto 0px auto;",
"	margin: top right bottom left;",
"	padding: 20px 20px 20px 10px;",
"	border: solid 2px rgb(255, 255, 255);",
"	border-radius: 8px 8px;",
"	-webkit-box-shadow: #F4C4E0 0px 0px 8px;",
"	-moz-box-shadow: #F4C4E0 0px 0px 8px;",
"	-o-box-shadow: #F4C4E0 0px 0px 8px;",
"	-ms-box-shadow: #F4C4E0 0px 0px 8px;",
"	box-shadow: #F4C4E0 0px 0px 8px;",
"	background-color: rgb(220, 231, 241);",
"}",
"",
".bubble .tail:before {",
"	content: \"\";",
"	position:absolute;",
"	border-style:solid;",
"	display:block; ",
"	width:0;",
"	top:-24px;",
"	right:5px;",
"	bottom:auto;",
"	left:auto;",
"	opacity: 0.5;",
"	border-width:0 20px 20px;",
"	border-color: rgba(244, 196, 224, 0.6) transparent;",
"}",
"",
".bubble .tail:after {",
"	content:\"\";",
"	position:absolute;",
"	border-style:solid;",
"	display:block; ",
"	width:0;",
"	top:-15px;",
"	right:10px;",
"	bottom:auto;",
"	left:auto;",
"	border-width:0 15px 15px;",
"	border-color: #DCE7F1 transparent;",
"}",
".ts-logout {",
"	display: none;",
"}",
".ts-loggedin .ts-logout {",
"	display: block;",
"}"
].join("\n");

function addEventListener(node, event, handler, bubble) {
	if (node.addEventListener){
		node.addEventListener(event, handler, bubble);
	} else if (node.attachEvent){
		event = event == "click" ? "onclick" : event;
		event = event == "load" ? "onload" : event;
		node.attachEvent(event, handler);
	}
}

var loadEvent = function() {
	var link = document.createElement("a");
	link.setAttribute("id", "app-picker");
	link.setAttribute("class", "app-picker");
	link.appendChild(document.createTextNode("tiddlyspace"));

        // Quite a hack. GUEST does not have a csrf token.
        if (/csrf_token=\d+:\w+:\w+/.test(document.cookie)) {
			if( backgroundSizeSupported ) {
				link.style.backgroundImage = 'url(/bags/tiddlyspace/tiddlers/privateAndPublicIcon)';
			} else {
				link.style.filter = msfilter_in;
			}
        } else {
			if( backgroundSizeSupported ) {
				link.style.backgroundImage = 'url(/bags/tiddlyspace/tiddlers/publicIcon)';
			} else {
				link.style.filter = msfilter_out;
			}
			stylesheet = stylesheet.replace('height: 180px;', 'height: 156px;');
        }

	var body = document.getElementsByTagName("BODY")[0];
	body.insertBefore(link, body.firstChild);
	var html = [
	'
',
		'',
		'

',
	'
'].join("");
	var bubble = document.createElement("div");
	bubble.setAttribute("id", "bs-popup");
	bubble.style.cssText = "visibility:hidden;";
	bubble.className = "bs-popup";
	bubble.innerHTML = html;
	body.insertBefore(bubble, link);

	twStylesheet(stylesheet);

	var bubbleFadeInterval;
	function fade(el, fadeIn) {
		var opacity = fadeIn ? 0 : 1;
		if(bubbleFadeInterval) {
			clearInterval(bubbleFadeInterval);
		}
		bubbleFadeInterval = setInterval(function() {
			// TODO: IE does not support opacity
			el.style.cssText = "opacity:" + opacity;
			opacity = fadeIn ? opacity + 0.1 : opacity - 0.1;
			if(opacity < 0 || opacity > 1) {
				clearInterval(bubbleFadeInterval);
				el.style.cssText = fadeIn ? "" : "visibility:hidden;";
			}
		}, 50);
	}

	addEventListener(link, "mousedown", function(ev) {
		ev.preventDefault();
	}, false);

	var bubbleOpen = false;
	var toggleBubble = function(ev) {
		if(ev.stopPropagation) {
			ev.stopPropagation();
		} else {
			ev.cancelBubble = false;
		}
		if(bubbleOpen) {
			fade(bubble, false);
		} else {
			fade(bubble, true);
		}
		bubbleOpen = !bubbleOpen;
	};

	addEventListener(link, "click", toggleBubble);

	addEventListener(window, "click",
		function(ev) {
			if(bubbleOpen) {
				toggleBubble(ev);
			}
		}, true);

	addEventListener(bubble, "click", function(ev) {
		if(ev.stopPropagation) {
			ev.stopPropagation();
		} else {
			ev.cancelBubble = false;
		}
	});
};

if(window.top == window) { // only add the backstage when NOT in an iframe (top window)
	addEventListener(window, "load", loadEvent);
}

})();
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
// import { CSSTransitionGroup } from 'react-transition-group'

class FadeInAnimation extends React.Component {
  render () {
    return (
      <span>
        {this.props.children}
      </span>
    )
    // return (
    //   <CSSTransitionGroup
    //     transitionName='fade'
    //     transitionAppear
    //     transitionAppearTimeout={300}
    //     transitionEnterTimeout={300}
    //     transitionLeaveTimeout={300}>
    //     {this.props.children}
    //   </CSSTransitionGroup>
    // )
  }
}

FadeInAnimation.propTypes = {
  children: PropTypes.object.isRequired
}

FadeInAnimation.defaultProps = {
}

export default FadeInAnimation
<commit_msg>Restore fade in animation.<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import { CSSTransitionGroup } from 'react-transition-group'

class FadeInAnimation extends React.Component {
  render () {
    return (
      <CSSTransitionGroup
        transitionName='fade'
        transitionAppear
        transitionAppearTimeout={300}
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300}>
        {this.props.children}
      </CSSTransitionGroup>
    )
  }
}

FadeInAnimation.propTypes = {
  children: PropTypes.object.isRequired
}

export default FadeInAnimation
<|endoftext|>


<commit_before>/*global document,$,sessionStorage,location*/

/*
 * A javascript wrapper around the github API that facilitates
 * a simple commit-comment based commenting system for static
 * content sites (e.g. github pages).
 */

/*
 * Configuration
 */
var REPOSITORY_NAME = 'm2w.github.com',
    GITHUB_USERNAME = 'm2w',
    COMMENTABLE_CONTENT_PATH_PREFIX = '_posts/',
    CONTENT_SUFFIX = '.md',
    CACHE_TIMEOUT = 10 * 60 * 1000, // cache github data for 10 minutes
    PAGINATION_SCHEME = /\/page\d+\//,
    LOCAL_STORAGE_SUPPORTED = false,
    COMMIT_API_ENDPOINT = 'https://api.github.com/repos/' + GITHUB_USERNAME + '/' + REPOSITORY_NAME + '/commits',
    REPO_COMMIT_URL_ROOT = 'https://github.com/' + GITHUB_USERNAME + '/' + REPOSITORY_NAME + '/commit/',
    PERMALINK_IDENTIFIER = 'a.permalink';

/*
 * Utilities
 */
function extrapolatePathFromPermalink(permalink_url) {
    'use strict';
    return permalink_url.replace(/[\.\w\-_:\/]+\/(\d+)\/(\d+)\/(\d+)\/([\w\-_]+)$/,
        COMMENTABLE_CONTENT_PATH_PREFIX + '$1-$2-$3-$4' + CONTENT_SUFFIX);
}
function shortenCommitId(commit_id) {
    'use strict';
    return commit_id.substr(0, 7);
}
function localStorageSupported() {
    'use strict';
    try {
        sessionStorage.setItem("dummy", "dummy");
        sessionStorage.removeItem("dummy");
        return true;
    } catch (e) {
        return false;
    }
}
function byAscendingDate(commentA, commentB) {
    'use strict';
    return new Date(commentA.updated_at) > new Date(commentB.updated_at);
}
/*
 * timeDifference is taken from:
 * http://stackoverflow.com/questions/6108819/javascript-timestamp-to-relative-time-eg-2-seconds-ago-one-week-ago-etc-best
 * tweaks by me
 */
function timeDifference(current, previous) {
    'use strict';
    function maybePluralize(elapsed) {
        return elapsed === 1 ? '' : 's';
    }
    var msPerMinute = 60 * 1000,
        msPerHour = msPerMinute * 60,
        msPerDay = msPerHour * 24,
        msPerMonth = msPerDay * 30,
        msPerYear = msPerDay * 365,
        justNowLim = 15 * 1000,
        elapsed = current - previous,
        t = 0;
    if (elapsed < msPerMinute) {
        return elapsed < justNowLim ? ' just now' : Math.round(elapsed / 1000) + ' seconds ago';
    }
    if (elapsed < msPerHour) {
        t = Math.round(elapsed / msPerMinute);
        return t + ' minute' + maybePluralize(t) + ' ago';
    }
    if (elapsed < msPerDay) {
        t = Math.round(elapsed / msPerHour);
        return t + ' hour' + maybePluralize(t) + ' ago';
    }
    if (elapsed < msPerMonth) {
        t = Math.round(elapsed / msPerDay);
        return t + ' day' + maybePluralize(t) + ' ago';
    }
    if (elapsed < msPerYear) {
        t = Math.round(elapsed / msPerMonth);
        return 'about ' + t + ' month' + maybePluralize(t) + ' ago';
    }
    t = Math.round(elapsed / msPerYear);
    return 'about ' + t + ' year' + maybePluralize(t) + ' ago';
}
var isStale = function (cached_comment_data) {
    'use strict';
    return (new Date().getTime() - cached_comment_data.timestamp) > CACHE_TIMEOUT;
};
var maybeGetCachedVersion = function (url) {
    'use strict';
    var cache = sessionStorage.getItem(url);
    if (cache) {
        cache = JSON.parse(cache);
        if (!isStale(cache)) {
            return cache.comment_data;
        }
    }
    return undefined;
};

/*
 * github API interaction
 */
var retrieveCommentsForCommit = function (commit) {
    'use strict';
    var dfd = new $.Deferred();
    $.getJSON(COMMIT_API_ENDPOINT + '/' + commit.sha + '/comments').done(function (comments) {
        dfd.resolveWith({ commits: commit, comments: comments });
    });
    return dfd;
};
var combineDataForFile = function (path, commits) {
    'use strict';
    var dfd = new $.Deferred(),
        deferred_comments = commits.map(function (commit) {
            return retrieveCommentsForCommit(commit).done(function () {
                this.path = path;
                return this;
            });
        });
    $.when.apply(null, deferred_comments).done(function () {
        var data = this,
            root;
        if (data && data.length) {
            root = { path: path, commits: [], comments: [] };
            data = data.reduce(function (acc, elem) {
                acc.commits = acc.commits.concat(elem.commits);
                acc.comments = acc.comments.concat(elem.comments);
                return acc;
            }, root);
        }
        dfd.resolveWith(data);
    });
    return dfd;
};
var getDataForPathWithDeferred = function (path, dfd) {
    'use strict';
    $.getJSON(COMMIT_API_ENDPOINT, { path: path }).then(function (commits) {
        return combineDataForFile(path, commits);
    }).done(function () {
        dfd.resolveWith(this);
    });
};
// returns a deferred object which holds all necessary commit and comment information for a specific permalink
var retrieveDataForPermalink = function (url) {
    'use strict';
    var wrapper_dfd = new $.Deferred(),
        path = extrapolatePathFromPermalink(url),
        cache;
    if (LOCAL_STORAGE_SUPPORTED) {
        cache = maybeGetCachedVersion(url);
        if (cache) {
            wrapper_dfd.resolveWith(cache);
        } else {
            getDataForPathWithDeferred(path, wrapper_dfd);
        }
    } else {
        getDataForPathWithDeferred(path, wrapper_dfd);
    }
    return wrapper_dfd;
};

/*
 * HTML generators
 */
var generateHtmlForComments = function (comment) {
    'use strict';
    var now = new Date().getTime(),
        template_clone = $('#talaria-comment-placeholder').clone(),
        header = template_clone.find('div.talaria-comment-header');
    template_clone.find('img').attr('src', comment.user.avatar_url);
    header.find('b').text(comment.user.login);
    header.find('a.talaria-author-nick').attr('href', comment.user.html_url);
    header.find('a.talaria-commit-sha').attr('href', comment.html_url).html('' + shortenCommitId(comment.commit_id) + '');
    header.find('span.talaria-header-right').text(timeDifference(now, new Date(comment.updated_at)));
    template_clone.find('div.talaria-comment-body').html(comment.body_html);
    template_clone.attr('id', comment.id).show();
    return template_clone;
};
/*
 * HTML manipulators
 */
var updateCommentMeta = function (permalink_element, comment_data) {
    'use strict';
    var wrapper = permalink_element.parents('article').find('div.talaria-wrapper'),
        latest_commit,
        latest_commit_url,
        c,
        text;
    if (comment_data.commits.length) {
        latest_commit = comment_data.commits.sort(function (a, b) {
            return new Date(a.commit.author.date) < new Date(b.commit.author.date);
        })[0];
    } else {
        latest_commit = comment_data.commits;
    }
    latest_commit_url = REPO_COMMIT_URL_ROOT + latest_commit.sha + '#all_commit_comments';
    wrapper.find('a.talaria-last-commit-href').attr('href', latest_commit_url);
    if (comment_data.comments.length > 0) {
        // check if currently displaying paginated content
        if (location.pathname === "/" || PAGINATION_SCHEME.test(location.pathname)) {
            c = comment_data.comments.length;
            text = c + ' comment' + (c !== 1 ? 's' : '');
            wrapper.find('a.talaria-expand-comments').attr('href', latest_commit_url).click(function (e) {
                e.preventDefault();
                wrapper.find('div.talaria-comment-list-wrapper').fadeIn();
                $(this).hide();
            }).text(text);
        } else {
            wrapper.find('div.talaria-comment-count').hide();
            wrapper.find('div.talaria-comment-list-wrapper').fadeIn();
        }
    } else {
        wrapper.find('a.talaria-expand-comments').attr('href', latest_commit_url).text('Be the first to comment');
    }
    wrapper.find('a.talaria-add-comment-button').attr('href', latest_commit_url).click(function () {
        if (LOCAL_STORAGE_SUPPORTED) {
            sessionStorage.removeItem(permalink_element.get(0).href);
        }
    });
};

$(document).ready(function () {
    'use strict';

    // check for local storage support
    if (localStorageSupported) {
        LOCAL_STORAGE_SUPPORTED = true;
    }

    // ensure that github returns fully rendered markup
    $.ajaxSetup({
        accepts: { json: 'application/vnd.github.v3.html+json' }
    });

    // iterate over permalinks and retrieve relevant commit and comment data
    $(PERMALINK_IDENTIFIER).map(function () {
        var permalink = this;
        $.when(retrieveDataForPermalink(permalink.href)).then(function () {
            var commentHtml = this.comments.sort(byAscendingDate).map(generateHtmlForComments);
            updateCommentMeta($(permalink), this);
            $(permalink).parents('article').find('div.talaria-comment-list').prepend(commentHtml);
            if (LOCAL_STORAGE_SUPPORTED) {
                sessionStorage.setItem(permalink.href, JSON.stringify({timestamp: new Date().getTime(), comment_data: this}));
            }
        });
    });
});<commit_msg>Transitions from the old resolveWith to plain resolve and adds initial error handling.<commit_after>/*global document,$,sessionStorage,location*/

/*
 * A javascript wrapper around the github API that facilitates
 * a simple commit-comment based commenting system for static
 * content sites (e.g. github pages).
 */

/*
 * Configuration
 */
var REPOSITORY_NAME = 'm2w.github.com',
    GITHUB_USERNAME = 'm2w',
    COMMENTABLE_CONTENT_PATH_PREFIX = '_posts/',
    CONTENT_SUFFIX = '.md',
    CACHE_TIMEOUT = 10 * 60 * 1000, // cache github data for 10 minutes
    PAGINATION_SCHEME = /\/page\d+\//,
    LOCAL_STORAGE_SUPPORTED = false,
    COMMIT_API_ENDPOINT = 'https://api.github.com/repos/' + GITHUB_USERNAME + '/' + REPOSITORY_NAME + '/commits',
    REPO_COMMIT_URL_ROOT = 'https://github.com/' + GITHUB_USERNAME + '/' + REPOSITORY_NAME + '/commit/',
    PERMALINK_IDENTIFIER = 'a.permalink';

/*
 * Utilities
 */
function extrapolatePathFromPermalink(permalink_url) {
    'use strict';
    return permalink_url.replace(/[\.\w\-_:\/]+\/(\d+)\/(\d+)\/(\d+)\/([\w\-_]+)$/,
        COMMENTABLE_CONTENT_PATH_PREFIX + '$1-$2-$3-$4' + CONTENT_SUFFIX);
}
function shortenCommitId(commit_id) {
    'use strict';
    return commit_id.substr(0, 7);
}
function localStorageSupported() {
    'use strict';
    try {
        sessionStorage.setItem("dummy", "dummy");
        sessionStorage.removeItem("dummy");
        return true;
    } catch (e) {
        return false;
    }
}
function byAscendingDate(commentA, commentB) {
    'use strict';
    return new Date(commentA.updated_at) > new Date(commentB.updated_at);
}
/*
 * timeDifference is taken from:
 * http://stackoverflow.com/questions/6108819/javascript-timestamp-to-relative-time-eg-2-seconds-ago-one-week-ago-etc-best
 * tweaks by me
 */
function timeDifference(current, previous) {
    'use strict';
    function maybePluralize(elapsed) {
        return elapsed === 1 ? '' : 's';
    }
    var msPerMinute = 60 * 1000,
        msPerHour = msPerMinute * 60,
        msPerDay = msPerHour * 24,
        msPerMonth = msPerDay * 30,
        msPerYear = msPerDay * 365,
        justNowLim = 15 * 1000,
        elapsed = current - previous,
        t = 0;
    if (elapsed < msPerMinute) {
        return elapsed < justNowLim ? ' just now' : Math.round(elapsed / 1000) + ' seconds ago';
    }
    if (elapsed < msPerHour) {
        t = Math.round(elapsed / msPerMinute);
        return t + ' minute' + maybePluralize(t) + ' ago';
    }
    if (elapsed < msPerDay) {
        t = Math.round(elapsed / msPerHour);
        return t + ' hour' + maybePluralize(t) + ' ago';
    }
    if (elapsed < msPerMonth) {
        t = Math.round(elapsed / msPerDay);
        return t + ' day' + maybePluralize(t) + ' ago';
    }
    if (elapsed < msPerYear) {
        t = Math.round(elapsed / msPerMonth);
        return 'about ' + t + ' month' + maybePluralize(t) + ' ago';
    }
    t = Math.round(elapsed / msPerYear);
    return 'about ' + t + ' year' + maybePluralize(t) + ' ago';
}
var isStale = function (cached_comment_data) {
    'use strict';
    return (new Date().getTime() - cached_comment_data.timestamp) > CACHE_TIMEOUT;
};
var maybeGetCachedVersion = function (url) {
    'use strict';
    var cache = sessionStorage.getItem(url);
    if (cache) {
        cache = JSON.parse(cache);
        if (!isStale(cache)) {
            return cache.comment_data;
        }
    }
    return undefined;
};

/*
 * github API interaction
 */
var retrieveCommentsForCommit = function (commit, path) {
    'use strict';
    var dfd = new $.Deferred();
    $.getJSON(COMMIT_API_ENDPOINT + '/' + commit.sha + '/comments').then(function (comments) {
        dfd.resolve({ commits: commit, comments: comments, path: path });
    }, function (error) {
        dfd.reject(error.status);
    });
    return dfd;
};
var combineDataForFile = function (path, commits) {
    'use strict';
    var dfd = new $.Deferred(),
        deferred_comments = commits.map(function (commit) {
            return retrieveCommentsForCommit(commit, path);
        });

    $.when.apply($, deferred_comments).done(function () {
        var data = Array.prototype.slice.call(arguments, 0),
            root;
        if (data && data.length) {
            root = { path: path, commits: [], comments: [] };
            data = data.reduce(function (acc, elem) {
                acc.commits = acc.commits.concat(elem.commits);
                acc.comments = acc.comments.concat(elem.comments);
                return acc;
            }, root);
        }
        dfd.resolve(data);
    });
    return dfd;
};
var getDataForPathWithDeferred = function (path) {
    'use strict';
    var dfd = new $.Deferred();
    $.getJSON(COMMIT_API_ENDPOINT, { path: path }).then(function (commits) {
        combineDataForFile(path, commits).done(function (dataForPath) {
            dfd.resolve(dataForPath);
        });
    }, function (error) {
        dfd.reject(error.status);
    });
    return dfd;
};
// returns a deferred object which holds all necessary commit and comment information for a specific permalink
var retrieveDataForPermalink = function (url) {
    'use strict';
    var path = extrapolatePathFromPermalink(url),
        cache;
    // if (LOCAL_STORAGE_SUPPORTED) {
    //     cache = maybeGetCachedVersion(url);
    //     if (cache) {
    //         wrapper_dfd.resolveWith(cache);
    //     } else {
    //         getDataForPathWithDeferred(path, wrapper_dfd);
    //     }
    // } else {
        return getDataForPathWithDeferred(path);
    // }

};

/*
 * HTML generators
 */
var generateHtmlForComments = function (comment) {
    'use strict';
    var now = new Date().getTime(),
        template_clone = $('#talaria-comment-placeholder').clone(),
        header = template_clone.find('div.talaria-comment-header');
    template_clone.find('span.talaria-img-placeholder').replaceWith(
        '');
    header.find('b').text(comment.user.login);
    header.find('a.talaria-author-nick').attr('href', comment.user.html_url);
    header.find('a.talaria-commit-sha').attr('href', comment.html_url).html(
        '' + shortenCommitId(comment.commit_id) + '');
    header.find('span.talaria-header-right').text(timeDifference(now, new Date(comment.updated_at)));
    template_clone.find('div.talaria-comment-body').html(comment.body_html);
    template_clone.attr('id', comment.id).show();
    return template_clone;
};
/*
 * HTML manipulators
 */
var updateCommentMeta = function (permalink_element, comment_data) {
    'use strict';
    var wrapper = permalink_element.parents('article').find('div.talaria-wrapper'),
        latest_commit,
        latest_commit_url,
        c,
        text;
    if (comment_data.commits.length) {
        latest_commit = comment_data.commits.sort(function (a, b) {
            return new Date(a.commit.author.date) < new Date(b.commit.author.date);
        })[0];
    } else {
        latest_commit = comment_data.commits;
    }
    latest_commit_url = REPO_COMMIT_URL_ROOT + latest_commit.sha + '#all_commit_comments';
    wrapper.find('a.talaria-last-commit-href').attr('href', latest_commit_url);
    if (comment_data.comments.length > 0) {
        // check if currently displaying paginated content
        if (location.pathname === "/" || PAGINATION_SCHEME.test(location.pathname)) {
            c = comment_data.comments.length;
            text = c + ' comment' + (c !== 1 ? 's' : '');
            wrapper.find('a.talaria-expand-comments').attr('href', latest_commit_url).click(function (e) {
                e.preventDefault();
                wrapper.find('div.talaria-comment-list-wrapper').fadeIn();
                $(this).hide();
            }).text(text);
        } else {
            wrapper.find('div.talaria-comment-count').hide();
            wrapper.find('div.talaria-comment-list-wrapper').fadeIn();
        }
    } else {
        wrapper.find('a.talaria-expand-comments').attr('href', latest_commit_url).text('Be the first to comment');
    }
    wrapper.find('a.talaria-add-comment-button').attr('href', latest_commit_url).click(function () {
        if (LOCAL_STORAGE_SUPPORTED) {
            sessionStorage.removeItem(permalink_element.get(0).href);
        }
    });
};
$(document).ready(function () {
    'use strict';
    // check for local storage support
    if (localStorageSupported) {
        LOCAL_STORAGE_SUPPORTED = true;
    }
    // ensure that github returns fully rendered markup
    $.ajaxSetup({
        accepts: { json: 'application/vnd.github.v3.html+json' }
    });
    // iterate over permalinks and retrieve relevant commit and comment data
    $(PERMALINK_IDENTIFIER).map(function () {
        var permalink = this;
        $.when(retrieveDataForPermalink(permalink.href)).then(function (data) {
            if ($.isEmptyObject(data)) {
                var parent = $(permalink).parents('article');
                parent.find('div.talaria-load-error').show();
                parent.find('div.talaria-comment-count').hide();
            } else {
                var commentHtml = data.comments.sort(byAscendingDate).map(generateHtmlForComments);
                updateCommentMeta($(permalink), data);
                $(permalink).parents('article').find('div.talaria-comment-list').prepend(commentHtml);
                if (LOCAL_STORAGE_SUPPORTED) {
                    sessionStorage.setItem(permalink.href, JSON.stringify({timestamp: new Date().getTime(), comment_data: this}));
                }
            }
        }, function (status) {
            var parent = $(permalink).parents('article');
            parent.find('div.talaria-load-error').text(
                'You have exceeded the github API request limit. Could not retrieve the comments.').show();
            parent.find('div.talaria-comment-count').hide();
        });
    });
});<|endoftext|>


<commit_before>$(document).ready(function () {

    //pathetic trying to restrict the form being sent on Enter
    $('#GeneticsPatient_id').closest('form').keydown(function(event){
        if(event.keyCode == 13) {
            event.preventDefault();
            return false;
        }
    });
});<commit_msg>hotfix/change-request - enter can submit genetics forms<commit_after>$(document).ready(function () {

    // this is not required at the moment
    // $('#GeneticsPatient_id').closest('form').keydown(function(event){
    //     if(event.keyCode == 13) {
    //         event.preventDefault();
    //         return false;
    //     }
    // });
});<|endoftext|>


<commit_before>var twitter = require('twitter');
var NodeGeocoder = require('node-geocoder');

const gpsOptions = {
    provider: process.env.GeoCoderProvider,
    httpAdapter: 'https', // Default
    apiKey: process.env.GeoCoderApiKey, // for Mapquest, OpenCage, Google Premier
    formatter: null         // 'gpx', 'string', ...
};

const twit = new twitter({
    consumer_key: process.env.TwitterConsumerKey,
    consumer_secret: process.env.TwitterConsumerSecret,
    access_token_key: process.env.TwitterAccessTokenKey,
    access_token_secret: process.env.TwitterAccessTokenSecret
});

module.exports = function (context, message) {
    //context.log(JSON.stringify(message, null, 4));

    return twit.get(`statuses/show/${message.mediaid}`, { include_entities: true })
        .then(getLocation)
        .then(getImages)
        .then(getHistory)
        .then(logTweetHistory)
        .then(setOutputBinding)

    function getLocation(message) {
        if (message.place != null) {
            var tweetLocation = message.place.full_name + ' ' + message.place.country_code;

            if (message.place.country_code == 'US') {//THIS SHOULD BE CONFIGURABLE
                // Get GPS from Tweet
                if (message.coordinates != null && 2 <= message.coordinates.coordinates.length) {
                    message.latitude = message.coordinates.coordinates[0];
                    message.longitude = message.coordinates.coordinates[1];
                    context.log('Lon: ' + message.longitude, 'Lat: ' + message.latitude);
                }
                else if (message.place.full_name != null) { // Get GPS via 3rd party GeoLocation module
                    var geocoder = NodeGeocoder(gpsOptions);

                    return new Promise((resolve, reject) => {
                        geocoder.geocode(tweetLocation, function (err, res) {
                            if (err)
                                return reject(err);
                            message.latitude = res[0].latitude;
                            message.longitude = res[0].longitude;
                            context.log('Lon: ' + message.longitude, 'Lat: ' + message.latitude);
                            resolve(message);
                        });
                    });
                }
            }
        }
        return message;
    }

    function getImages(message) {
        // Add photo urls
        message.photourls = [];
        if (message.entities != null && message.entities.media != null) {
            if (message.entities.media.length > 0) {
                message.entities.media.forEach(function (item) {
                    message.photourls.push(item.media_url);
                });
            }

            // Print photo urls
            // message.photourls.forEach(function (photourl) {
            //     context.log(photourl);
            // });
        }

        return message;
    }

    // Get all past tweets that contains user's handle
    function getHistory(message) {
        message.tweethistory_ids = [];
        var params = {
            q: options.screen_name,  // REQUIRED
            result_type: 'mixed',
            lang: 'en',
            max_id: message.tweetid
        };

        if (message.latitude && message.longitude) {
            params.geocode = `${message.latitude},${message.longitude},${process.env.TweetSearchRadius}km`;
        }

        return twit.get('search/tweets', params)
            .then(historyData => {
                message.tweethistory_ids = historyData.statuses
                    .map(statusItem => statusItem.id_str);

                return message;
            });
    }

    function logTweetHistory(message) {

        var loggingPromises = message.tweethistory_ids.map(historyId => {
            twit.get(`statuses/show/${historyId}`, { include_entities: true })
                .then(msg => {
                    context.log('tweethistory_id:' + historyId);
                    context.log(msg.text);
                });
        });

        return Promise.all(loggingPromises)
            .then(() => message);
    }

    function setOutputBinding(message) {
        context.bindings.out = message;
        return message;
    }
};<commit_msg>spelling<commit_after>var twitter = require('twitter');
var NodeGeocoder = require('node-geocoder');

const gpsOptions = {
    provider: process.env.GeoCoderProvider,
    httpAdapter: 'https', // Default
    apiKey: process.env.GeoCoderApiKey, // for Mapquest, OpenCage, Google Premier
    formatter: null         // 'gpx', 'string', ...
};

const twit = new twitter({
    consumer_key: process.env.TwitterConsumerKey,
    consumer_secret: process.env.TwitterConsumerSecret,
    access_token_key: process.env.TwitterAccessTokenKey,
    access_token_secret: process.env.TwitterAccessTokenSecret
});

module.exports = function (context, message) {
    //context.log(JSON.stringify(message, null, 4));

    return twit.get(`statuses/show/${message.mediaid}`, { include_entities: true })
        .then(getLocation)
        .then(getImages)
        .then(getHistory)
        .then(logTweetHistory)
        .then(setOutputBinding)

    function getLocation(message) {
        if (message.place != null) {
            var tweetLocation = message.place.full_name + ' ' + message.place.country_code;

            if (message.place.country_code == 'US') {//THIS SHOULD BE CONFIGURABLE
                // Get GPS from Tweet
                if (message.coordinates != null && 2 <= message.coordinates.coordinates.length) {
                    message.latitude = message.coordinates.coordinates[0];
                    message.longitude = message.coordinates.coordinates[1];
                    context.log('Lon: ' + message.longitude, 'Lat: ' + message.latitude);
                }
                else if (message.place.full_name != null) { // Get GPS via 3rd party GeoLocation module
                    var geocoder = NodeGeocoder(gpsOptions);

                    return new Promise((resolve, reject) => {
                        geocoder.geocode(tweetLocation, function (err, res) {
                            if (err)
                                return reject(err);
                            message.latitude = res[0].latitude;
                            message.longitude = res[0].longitude;
                            context.log('Lon: ' + message.longitude, 'Lat: ' + message.latitude);
                            resolve(message);
                        });
                    });
                }
            }
        }
        return message;
    }

    function getImages(message) {
        // Add photo urls
        message.photourls = [];
        if (message.entities != null && message.entities.media != null) {
            if (message.entities.media.length > 0) {
                message.entities.media.forEach(function (item) {
                    message.photourls.push(item.media_url);
                });
            }

            // Print photo urls
            // message.photourls.forEach(function (photourl) {
            //     context.log(photourl);
            // });
        }

        return message;
    }

    // Get all past tweets that contains user's handle
    function getHistory(message) {
        message.tweethistory_ids = [];
        var params = {
            q: message.user.screen_name,  // REQUIRED
            result_type: 'mixed',
            lang: 'en',
            max_id: message.tweetid
        };

        if (message.latitude && message.longitude) {
            params.geocode = `${message.latitude},${message.longitude},${process.env.TweetSearchRadius}km`;
        }

        return twit.get('search/tweets', params)
            .then(historyData => {
                message.tweethistory_ids = historyData.statuses
                    .map(statusItem => statusItem.id_str);

                return message;
            });
    }

    function logTweetHistory(message) {

        var loggingPromises = message.tweethistory_ids.map(historyId => {
            twit.get(`statuses/show/${historyId}`, { include_entities: true })
                .then(msg => {
                    context.log('tweethistory_id:' + historyId);
                    context.log(msg.text);
                });
        });

        return Promise.all(loggingPromises)
            .then(() => message);
    }

    function setOutputBinding(message) {
        context.bindings.out = message;
        return message;
    }
};<|endoftext|>


<commit_before>/**
 * Detailed explanation https://github.com/graphql/graphql-js/issues/312#issuecomment-196169994
 */

import { nodeInterface } from '../../schema/schema';
import {
  GraphQLScalarType,
  GraphQLInputObjectType,
  GraphQLEnumType,
  GraphQLID,
} from 'graphql';

function createInputObject(type) {
  return new GraphQLInputObjectType({
    name: `${type.name}Input`,
    fields: filterFields(type.getFields(), (field) => (!field.noInputObject)), // eslint-disable-line
  });
}

function filterFields(obj, filter) {
  const result = {};
  Object.keys(obj).forEach((key) => {
    if (filter(obj[key])) {
      result[key] = convertInputObjectField(obj[key]); // eslint-disable-line no-use-before-define
    }
  });
  return result;
}

function convertInputObjectField(field) {
  let fieldType = field.type;
  const wrappers = [];

  while (fieldType.ofType) {
    wrappers.unshift(fieldType.constructor);
    fieldType = fieldType.ofType;
  }

  if (
    !(fieldType instanceof GraphQLInputObjectType ||
      fieldType instanceof GraphQLScalarType ||
      fieldType instanceof GraphQLEnumType
    )
  ) {
    fieldType = fieldType.getInterfaces().includes(nodeInterface)
      ? GraphQLID
      : createInputObject(fieldType);
  }

  fieldType = wrappers.reduce((type, Wrapper) => new Wrapper(type), fieldType);

  return { type: fieldType };
}

export default createInputObject;
<commit_msg>fix(type): add to input-object ability for self-nesting<commit_after>/**
 * Detailed explanation https://github.com/graphql/graphql-js/issues/312#issuecomment-196169994
 */

import { nodeInterface } from '../../schema/schema';
import {
  GraphQLScalarType,
  GraphQLInputObjectType,
  GraphQLEnumType,
  GraphQLID
} from 'graphql';

const cachedTypes = {};

function createInputObject(type) {
  const typeName = `${type.name}Input`;

  if (!cachedTypes.hasOwnProperty(typeName)) {
    cachedTypes[typeName] = new GraphQLInputObjectType({
      name: typeName,
      fields: {}
    });
    cachedTypes[typeName]._typeConfig.fields =
      () => filterFields(type.getFields(), (field) => (!field.noInputObject)); // eslint-disable-line
  }

  return cachedTypes[typeName];
}

function filterFields(obj, filter) {
  const result = {};
  Object.keys(obj).forEach((key) => {
    if (filter(obj[key])) {
      result[key] = convertInputObjectField(obj[key]); // eslint-disable-line no-use-before-define
    }
  });
  return result;
}

function convertInputObjectField(field) {
  let fieldType = field.type;
  const wrappers = [];

  while (fieldType.ofType) {
    wrappers.unshift(fieldType.constructor);
    fieldType = fieldType.ofType;
  }

  if (
    !(fieldType instanceof GraphQLInputObjectType ||
      fieldType instanceof GraphQLScalarType ||
      fieldType instanceof GraphQLEnumType
    )
  ) {
    fieldType = fieldType.getInterfaces().includes(nodeInterface)
      ? GraphQLID
      : createInputObject(fieldType);
  }

  fieldType = wrappers.reduce((type, Wrapper) => new Wrapper(type), fieldType);

  return { type: fieldType };
}

export default createInputObject;
<|endoftext|>


<commit_before>window.hipanel = (function () {
    var notify = {
        create: function (options) {
            options = $.extend({
                buttons: {
                    sticker: false
                },
                icon: false,
                styling: 'bootstrap3'
            }, options, true);

            return new PNotify(options);
        },
        error: function (text) {
            return notify.create({type: 'error', text: text});
        },
        success: function (text) {
            return notify.create({type: 'success', text: text});
        }
    };

    var publicMethods = {
        updateCart: function (callback) {
            $('.dropdown.notifications-cart a.dropdown-toggle').html('');
            $.get("/cart/cart/topcart", function(data) {
                $("li.dropdown.notifications-menu.notifications-cart").html( data );
            }).done(callback());
        },
        loadingBar: function (options) {
            options = $.extend({}, options, true);

            return '
' +
                '
' +
                    '' + options.text + '' +
                '
' +
            '
';
        },
        notify: notify
    };

    return publicMethods;
})();
<commit_msg>Added extra method to hipanel.js - form.preventSubmitWithEnter()<commit_after>window.hipanel = (function () {
    var notify = {
        create: function (options) {
            options = $.extend({
                buttons: {
                    sticker: false
                },
                icon: false,
                styling: 'bootstrap3'
            }, options, true);

            return new PNotify(options);
        },
        error: function (text) {
            return notify.create({type: 'error', text: text});
        },
        success: function (text) {
            return notify.create({type: 'success', text: text});
        }
    };

    var publicMethods = {
        updateCart: function (callback) {
            $('.dropdown.notifications-cart a.dropdown-toggle').html('');
            $.get("/cart/cart/topcart", function(data) {
                $("li.dropdown.notifications-menu.notifications-cart").html( data );
            }).done(callback());
        },
        loadingBar: function (options) {
            options = $.extend({}, options, true);

            return '
' +
                '
' +
                    '' + options.text + '' +
                '
' +
            '
';
        },
        notify: notify,
        form: {
            preventSubmitWithEnter: function (formId) {
                $(formId).on('keyup keypress', function (e) {
                    var keyCode = e.keyCode || e.which;
                    if (keyCode === 13) {
                        e.preventDefault();
                        e.stopPropagation();
                        $(e.target).blur();
                    }
                });
            }
        }
    };

    return publicMethods;
})();
<|endoftext|>