<commit_before>/**
 * Module : neoui-dialog
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-08-02 15:29:55
 */

import {BaseComponent} from 'neoui-sparrow/js/BaseComponent';
import {addClass,removeClass,hasClass,getStyle,makeDOM,makeModal} from 'neoui-sparrow/js/dom';
import {on,stopEvent,trigger} from 'neoui-sparrow/js/event';
import {extend} from 'neoui-sparrow/js/extend';
import {Button} from './neoui-button';
import {compMgr} from 'neoui-sparrow/js/compMgr';

/**
 * messageDialog.js
 */

'use strict';

/**
 * 消息提示框
 * @param options
 */

var messageDialogTemplate = '
' +
	'
' +
	'
{title}
' +
	'
' +
	'
' +
	'
{msg}
' +
	'
' +
	'
<button class="u-msg-button u-button primary raised">{btnText}</button>
' +
	'
';

var messageDialog = function(options) {
	var title, msg, btnText, template;
	if(typeof options === 'string') {
		options = {
			msg: options
		};
	}
	msg = options['msg'] || "";
	title = options['title'] || "提示";
	btnText = options['btnText'] || "确定";
	template = options['template'] || messageDialogTemplate;

	template = template.replace('{msg}', msg);
	template = template.replace('{title}', title);
	template = template.replace('{btnText}', btnText);

	var msgDom = makeDOM(template);

	var closeBtn = msgDom.querySelector('.u-msg-button');
	new Button({
		el: closeBtn
	});
	on(closeBtn, 'click', function() {
		document.body.removeChild(msgDom);
		document.body.removeChild(overlayDiv);
	})
	var overlayDiv = makeModal(msgDom);
	document.body.appendChild(msgDom);

	this.resizeFun = function() {
		var cDom = msgDom.querySelector('.u-msg-content');
		if(!cDom) return;
		cDom.style.height = '';
		var wholeHeight = msgDom.offsetHeight;
		var contentHeight = msgDom.scrollHeight;
		if(contentHeight > wholeHeight && cDom)
			cDom.style.height = wholeHeight - (56 + 46) + 'px';

	}.bind(this);

	this.resizeFun();
	on(window, 'resize', this.resizeFun);
};

/**
 * Module : confirmDialog
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-07-29 10:21:33
 */
var confirmDialogTemplate = '
' +
	'
' +
	'
{title}
' +
	'
' +
	'
' +
	'
{msg}
' +
	'
' +
	'
<button class="u-msg-ok u-button primary raised">{okText}</button><button class="u-msg-cancel u-button">{cancelText}</button>
' +
	'
';

var confirmDialog = function(options) {
	var title, msg, okText, cancelText, template, onOk, onCancel;
	msg = options['msg'] || "";
	title = options['title'] || "确认";
	okText = options['okText'] || "确定";
	cancelText = options['cancelText'] || "取消";
	onOk = options['onOk'] || function() {};
	onCancel = options['onCancel'] || function() {};
	template = options['template'] || confirmDialogTemplate;

	template = template.replace('{msg}', msg);
	template = template.replace('{title}', title);
	template = template.replace('{okText}', okText);
	template = template.replace('{cancelText}', cancelText);

	var msgDom = makeDOM(template);
	var okBtn = msgDom.querySelector('.u-msg-ok');
	var cancelBtn = msgDom.querySelector('.u-msg-cancel');
	new Button({
		el: okBtn
	});
	new Button({
		el: cancelBtn
	});
	on(okBtn, 'click', function() {
		if(onOk() !== false) {
			document.body.removeChild(msgDom);
			document.body.removeChild(overlayDiv);
		}
	})
	on(cancelBtn, 'click', function() {
		if(onCancel() !== false) {
			document.body.removeChild(msgDom);
			document.body.removeChild(overlayDiv);
		}
	})
	var overlayDiv = makeModal(msgDom);
	document.body.appendChild(msgDom);

	this.resizeFun = function() {
		var cDom = msgDom.querySelector('.u-msg-content');
		if(!cDom) return;
		cDom.style.height = '';
		var wholeHeight = msgDom.offsetHeight;
		var contentHeight = msgDom.scrollHeight;
		if(contentHeight > wholeHeight && cDom)
			cDom.style.height = wholeHeight - (56 + 46) + 'px';

	}.bind(this);

	this.resizeFun();
	on(window, 'resize', this.resizeFun);

};

/**
 * Created by dingrf on 2015-11-19.
 */

/**
 * 三按钮确认框（是 否  取消）
 */
var threeBtnDialog = function() {

}
/**
 * 禁用鼠标滚轮事件
 * @return {[type]} [description]
 */
var disable_mouseWheel = function () {
	if (document.addEventListener) {
	  document.addEventListener('DOMMouseScroll', scrollFunc, false);
	}
	window.onmousewheel = document.onmousewheel = scrollFunc;
};
/**
 * 事件禁用
 * @param  {[type]} evt [description]
 * @return {[type]}     [description]
 */
var scrollFunc = function (evt) {
  evt = evt || window.event;
    if(evt.preventDefault) {
    // Firefox
      evt.preventDefault();
      evt.stopPropagation();
    } else {
      // IE
      evt.cancelBubble=true;
      evt.returnValue = false;
  }
  return false;
};

/**
 * 开启鼠标滚轮事件
 * @return {[type]} [description]
 */
var enable_mouseWheel = function () {
	if (document.removeEventListener) {
	  document.removeEventListener('DOMMouseScroll', scrollFunc, false);
	}
	window.onmousewheel = document.onmousewheel = null;
};

/**
 * dialog.js
 */

var dialogTemplate = '
' +
	'{close}' +
	'
';

var dialogMode = function(options) {
	if(typeof options === 'string') {
		options = {
			content: options
		};
	}
	var defaultOptions = {
		id: '',
		content: '',
		hasCloseMenu: true,
		template: dialogTemplate,
		width: '',
		height: ''
	}

	options = extend(defaultOptions, options);
	this.id = options['id'];
	this.hasCloseMenu = options['hasCloseMenu'];
	this.content = options['content'];
	this.template = options['template'];
	this.width = options['width'];
	this.height = options['height'];
	this.lazyShow = options['lazyShow'];
	this.closeFun = options['closeFun'];
	this.create();

	this.resizeFun = function() {
		var cDom = this.contentDom.querySelector('.u-msg-content');
		cDom.style.height = '';
		var wholeHeight = this.templateDom.offsetHeight;
		var contentHeight = this.contentDom.offsetHeight;
		if(contentHeight > wholeHeight && cDom)
			cDom.style.height = wholeHeight - (56 + 46) + 'px';

	}.bind(this);

	this.resizeFun();
	on(window, 'resize', this.resizeFun);
}

dialogMode.prototype.create = function() {
	var closeStr = '';
	var oThis = this;
	if(this.hasCloseMenu) {
		var closeStr = '
 ×
';
	}
	var templateStr = this.template.replace('{id}', this.id);
	templateStr = templateStr.replace('{close}', closeStr);
	templateStr = templateStr.replace('{width}', this.width ? 'width:' + this.width + ';' : '');
	templateStr = templateStr.replace('{height}', this.height ? 'height:' + this.height + ';' : '');

	var htmlReg = /^(\s*)?<[a-zA-Z]+/ig;
	var selectReg = /^(\.|#)/;
	if(htmlReg.test(this.content)){
		this.contentDom= makeDOM(this.content);
		this.contentDomParent = this.contentDom.parentNode;
		this.contentDom.style.display = 'block';
	}else if(selectReg.test(this.content)){
		this.contentDom = document.querySelector(this.content);
		this.contentDomParent = this.contentDom.parentNode;
		this.contentDom.style.display = 'block';
	}else{
		this.contentDom = makeDOM('

' + this.content + '

');
	}
	this.templateDom = makeDOM(templateStr);

	/*this.contentDom = document.querySelector(this.content); //
	this.templateDom = makeDOM(templateStr);
	if(this.contentDom) { // msg第一种方式传入选择器，如果可以查找到对应dom节点，则创建整体dialog之后在msg位置添加dom元素
		this.contentDomParent = this.contentDom.parentNode;
		this.contentDom.style.display = 'block';
	} else { // 如果查找不到对应dom节点，则按照字符串处理，直接将msg拼到template之后创建dialog
		this.contentDom = makeDOM('

' + this.content + '

');
	}*/
	this.templateDom.appendChild(this.contentDom);
	this.overlayDiv = makeModal(this.templateDom);
	if(this.hasCloseMenu) {
		this.closeDiv = this.templateDom.querySelector('.u-msg-close');
		on(this.closeDiv, 'click', function() {
			oThis.close();
		});
	}
	if(this.lazyShow) {
		this.templateDom.style.display = 'none';
		this.overlayDiv.style.display = 'none';
	}
	document.body.appendChild(this.templateDom);
	this.isClosed = false;
};

dialogMode.prototype.show = function() {
	if(this.isClosed) {
		this.create();
	}
	this.templateDom.style.display = 'block';
	this.overlayDiv.style.display = 'block';
	disable_mouseWheel();
}

dialogMode.prototype.hide = function() {
	this.templateDom.style.display = 'none';
	this.overlayDiv.style.display = 'none';
	enable_mouseWheel();
}

dialogMode.prototype.close = function() {
	this.closeFun && this.closeFun.call(this);
	if(this.contentDom) {
		this.contentDom.style.display = 'none';
		this.contentDomParent && this.contentDomParent.appendChild(this.contentDom);
	}
	document.body.removeChild(this.templateDom);
	document.body.removeChild(this.overlayDiv);
	this.isClosed = true;
		enable_mouseWheel();
}

u.dialogMode = dialogMode;

var dialog = function(options) {
	return new dialogMode(options);
}

/**
 * 对话框向导
 * @param options:  {dialogs: [{content:".J-goods-pro-add-1-dialog",hasCloseMenu:false},
                               {content:".J-goods-pro-add-2-dialog",hasCloseMenu:false},
                            ]
                    }
 */
var dialogWizard = function(options) {
	var dialogs = [],
		curIndex = 0;
	options.dialogs = options.dialogs || [],
		len = options.dialogs.length;
	if(len == 0) {
		throw new Error('未加入对话框');
	}
	for(var i = 0; i < len; i++) {
		dialogs.push(dialog(extend(options.dialogs[i], {
			lazyShow: true
		})));
	}
	var wizard = function() {}
	wizard.prototype.show = function() {
		dialogs[curIndex].show();
	}
	wizard.prototype.next = function() {
		dialogs[curIndex].hide();
		dialogs[++curIndex].show();
	}
	wizard.prototype.prev = function() {
		dialogs[curIndex].hide();
		dialogs[--curIndex].show();
	}
	wizard.prototype.close = function() {
		for(var i = 0; i < len; i++) {
			dialogs[i].close();
		}
	}
	return new wizard();
}

export {messageDialog,
		confirmDialog,
		dialogMode,
		dialog,
		dialogWizard};
<commit_msg>feat: dialog mousewheel forbiddenwheel<commit_after>/**
 * Module : neoui-dialog
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-08-02 15:29:55
 */

import {BaseComponent} from 'neoui-sparrow/js/BaseComponent';
import {addClass,removeClass,hasClass,getStyle,makeDOM,makeModal} from 'neoui-sparrow/js/dom';
import {on,stopEvent,trigger} from 'neoui-sparrow/js/event';
import {extend} from 'neoui-sparrow/js/extend';
import {Button} from './neoui-button';
import {compMgr} from 'neoui-sparrow/js/compMgr';

/**
 * messageDialog.js
 */

'use strict';

/**
 * 消息提示框
 * @param options
 */

var messageDialogTemplate = '
' +
	'
' +
	'
{title}
' +
	'
' +
	'
' +
	'
{msg}
' +
	'
' +
	'
<button class="u-msg-button u-button primary raised">{btnText}</button>
' +
	'
';

var messageDialog = function(options) {
	var title, msg, btnText, template;
	if(typeof options === 'string') {
		options = {
			msg: options
		};
	}
	msg = options['msg'] || "";
	title = options['title'] || "提示";
	btnText = options['btnText'] || "确定";
	template = options['template'] || messageDialogTemplate;

	template = template.replace('{msg}', msg);
	template = template.replace('{title}', title);
	template = template.replace('{btnText}', btnText);

	var msgDom = makeDOM(template);

	var closeBtn = msgDom.querySelector('.u-msg-button');
	new Button({
		el: closeBtn
	});
	on(closeBtn, 'click', function() {
		document.body.removeChild(msgDom);
		document.body.removeChild(overlayDiv);
		enable_mouseWheel();
	})
	var overlayDiv = makeModal(msgDom);
	document.body.appendChild(msgDom);
    disable_mouseWheel();
	this.resizeFun = function() {
		var cDom = msgDom.querySelector('.u-msg-content');
		if(!cDom) return;
		cDom.style.height = '';
		var wholeHeight = msgDom.offsetHeight;
		var contentHeight = msgDom.scrollHeight;
		if(contentHeight > wholeHeight && cDom)
			cDom.style.height = wholeHeight - (56 + 46) + 'px';

	}.bind(this);

	this.resizeFun();
	on(window, 'resize', this.resizeFun);
};

/**
 * Module : confirmDialog
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-07-29 10:21:33
 */
var confirmDialogTemplate = '
' +
	'
' +
	'
{title}
' +
	'
' +
	'
' +
	'
{msg}
' +
	'
' +
	'
<button class="u-msg-ok u-button primary raised">{okText}</button><button class="u-msg-cancel u-button">{cancelText}</button>
' +
	'
';

var confirmDialog = function(options) {
	var title, msg, okText, cancelText, template, onOk, onCancel;
	msg = options['msg'] || "";
	title = options['title'] || "确认";
	okText = options['okText'] || "确定";
	cancelText = options['cancelText'] || "取消";
	onOk = options['onOk'] || function() {};
	onCancel = options['onCancel'] || function() {};
	template = options['template'] || confirmDialogTemplate;

	template = template.replace('{msg}', msg);
	template = template.replace('{title}', title);
	template = template.replace('{okText}', okText);
	template = template.replace('{cancelText}', cancelText);

	var msgDom = makeDOM(template);
	var okBtn = msgDom.querySelector('.u-msg-ok');
	var cancelBtn = msgDom.querySelector('.u-msg-cancel');
	new Button({
		el: okBtn
	});
	new Button({
		el: cancelBtn
	});
	on(okBtn, 'click', function() {
		if(onOk() !== false) {
			document.body.removeChild(msgDom);
			document.body.removeChild(overlayDiv);
			enable_mouseWheel();
		}
	})
	on(cancelBtn, 'click', function() {
		if(onCancel() !== false) {
			document.body.removeChild(msgDom);
			document.body.removeChild(overlayDiv);
			enable_mouseWheel();
		}
	})
	var overlayDiv = makeModal(msgDom);
	document.body.appendChild(msgDom);
	disable_mouseWheel();

	this.resizeFun = function() {
		var cDom = msgDom.querySelector('.u-msg-content');
		if(!cDom) return;
		cDom.style.height = '';
		var wholeHeight = msgDom.offsetHeight;
		var contentHeight = msgDom.scrollHeight;
		if(contentHeight > wholeHeight && cDom)
			cDom.style.height = wholeHeight - (56 + 46) + 'px';

	}.bind(this);

	this.resizeFun();
	on(window, 'resize', this.resizeFun);

};

/**
 * Created by dingrf on 2015-11-19.
 */

/**
 * 三按钮确认框（是 否  取消）
 */
var threeBtnDialog = function() {

}
/**
 * 禁用鼠标滚轮事件
 * @return {[type]} [description]
 */
var disable_mouseWheel = function () {
	if (document.addEventListener) {
	  document.addEventListener('DOMMouseScroll', scrollFunc, false);
	}
	window.onmousewheel = document.onmousewheel = scrollFunc;
};
/**
 * 事件禁用
 * @param  {[type]} evt [description]
 * @return {[type]}     [description]
 */
var scrollFunc = function (evt) {
  evt = evt || window.event;
    if(evt.preventDefault) {
    // Firefox
      evt.preventDefault();
      evt.stopPropagation();
    } else {
      // IE
      evt.cancelBubble=true;
      evt.returnValue = false;
  }
  return false;
};

/**
 * 开启鼠标滚轮事件
 * @return {[type]} [description]
 */
var enable_mouseWheel = function () {
	if (document.removeEventListener) {
	  document.removeEventListener('DOMMouseScroll', scrollFunc, false);
	}
	window.onmousewheel = document.onmousewheel = null;
};

/**
 * dialog.js
 */

var dialogTemplate = '
' +
	'{close}' +
	'
';

var dialogMode = function(options) {
	if(typeof options === 'string') {
		options = {
			content: options
		};
	}
	var defaultOptions = {
		id: '',
		content: '',
		hasCloseMenu: true,
		template: dialogTemplate,
		width: '',
		height: ''
	}

	options = extend(defaultOptions, options);
	this.id = options['id'];
	this.hasCloseMenu = options['hasCloseMenu'];
	this.content = options['content'];
	this.template = options['template'];
	this.width = options['width'];
	this.height = options['height'];
	this.lazyShow = options['lazyShow'];
	this.closeFun = options['closeFun'];
	this.create();

	this.resizeFun = function() {
		var cDom = this.contentDom.querySelector('.u-msg-content');
		cDom.style.height = '';
		var wholeHeight = this.templateDom.offsetHeight;
		var contentHeight = this.contentDom.offsetHeight;
		if(contentHeight > wholeHeight && cDom)
			cDom.style.height = wholeHeight - (56 + 46) + 'px';

	}.bind(this);

	this.resizeFun();
	on(window, 'resize', this.resizeFun);
}

dialogMode.prototype.create = function() {
	var closeStr = '';
	var oThis = this;
	if(this.hasCloseMenu) {
		var closeStr = '
 ×
';
	}
	var templateStr = this.template.replace('{id}', this.id);
	templateStr = templateStr.replace('{close}', closeStr);
	templateStr = templateStr.replace('{width}', this.width ? 'width:' + this.width + ';' : '');
	templateStr = templateStr.replace('{height}', this.height ? 'height:' + this.height + ';' : '');

	var htmlReg = /^(\s*)?<[a-zA-Z]+/ig;
	var selectReg = /^(\.|#)/;
	if(htmlReg.test(this.content)){
		this.contentDom= makeDOM(this.content);
		this.contentDomParent = this.contentDom.parentNode;
		this.contentDom.style.display = 'block';
	}else if(selectReg.test(this.content)){
		this.contentDom = document.querySelector(this.content);
		this.contentDomParent = this.contentDom.parentNode;
		this.contentDom.style.display = 'block';
	}else{
		this.contentDom = makeDOM('

' + this.content + '

');
	}
	this.templateDom = makeDOM(templateStr);

	/*this.contentDom = document.querySelector(this.content); //
	this.templateDom = makeDOM(templateStr);
	if(this.contentDom) { // msg第一种方式传入选择器，如果可以查找到对应dom节点，则创建整体dialog之后在msg位置添加dom元素
		this.contentDomParent = this.contentDom.parentNode;
		this.contentDom.style.display = 'block';
	} else { // 如果查找不到对应dom节点，则按照字符串处理，直接将msg拼到template之后创建dialog
		this.contentDom = makeDOM('

' + this.content + '

');
	}*/
	this.templateDom.appendChild(this.contentDom);
	this.overlayDiv = makeModal(this.templateDom);
	if(this.hasCloseMenu) {
		this.closeDiv = this.templateDom.querySelector('.u-msg-close');
		on(this.closeDiv, 'click', function() {
			oThis.close();
		});
	}
	if(this.lazyShow) {
		this.templateDom.style.display = 'none';
		this.overlayDiv.style.display = 'none';
	}
	document.body.appendChild(this.templateDom);
	disable_mouseWheel();
	this.isClosed = false;
};

dialogMode.prototype.show = function() {
	if(this.isClosed) {
		this.create();
	}
	this.templateDom.style.display = 'block';
	this.overlayDiv.style.display = 'block';
	disable_mouseWheel();
}

dialogMode.prototype.hide = function() {
	this.templateDom.style.display = 'none';
	this.overlayDiv.style.display = 'none';
	enable_mouseWheel();
}

dialogMode.prototype.close = function() {
	this.closeFun && this.closeFun.call(this);
	if(this.contentDom) {
		this.contentDom.style.display = 'none';
		this.contentDomParent && this.contentDomParent.appendChild(this.contentDom);
	}
	document.body.removeChild(this.templateDom);
	document.body.removeChild(this.overlayDiv);
	this.isClosed = true;
		enable_mouseWheel();
}

u.dialogMode = dialogMode;

var dialog = function(options) {
	return new dialogMode(options);
}

/**
 * 对话框向导
 * @param options:  {dialogs: [{content:".J-goods-pro-add-1-dialog",hasCloseMenu:false},
                               {content:".J-goods-pro-add-2-dialog",hasCloseMenu:false},
                            ]
                    }
 */
var dialogWizard = function(options) {
	var dialogs = [],
		curIndex = 0;
	options.dialogs = options.dialogs || [],
		len = options.dialogs.length;
	if(len == 0) {
		throw new Error('未加入对话框');
	}
	for(var i = 0; i < len; i++) {
		dialogs.push(dialog(extend(options.dialogs[i], {
			lazyShow: true
		})));
	}
	var wizard = function() {}
	wizard.prototype.show = function() {
		dialogs[curIndex].show();
	}
	wizard.prototype.next = function() {
		dialogs[curIndex].hide();
		dialogs[++curIndex].show();
	}
	wizard.prototype.prev = function() {
		dialogs[curIndex].hide();
		dialogs[--curIndex].show();
	}
	wizard.prototype.close = function() {
		for(var i = 0; i < len; i++) {
			dialogs[i].close();
		}
	}
	return new wizard();
}

export {messageDialog,
		confirmDialog,
		dialogMode,
		dialog,
		dialogWizard};
<|endoftext|>


<commit_before>// Copyright 2013-2020, University of Colorado Boulder

/**
 * CO Molecule
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

import Element from '../Element.js';
import nitroglycerin from '../nitroglycerin.js';
import HorizontalMoleculeNode from './HorizontalMoleculeNode.js';

class CONode extends HorizontalMoleculeNode {

  /**
   * @param {Object} [options]
   */
  constructor( options ) {
    super( [ Element.C, Element.O ], options );
  }
}

nitroglycerin.register( 'CONode', CONode );
export default CONode;<commit_msg>// @ts-nocheck<commit_after>// Copyright 2013-2020, University of Colorado Boulder

// @ts-nocheck
/**
 * CO Molecule
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

import Element from '../Element.js';
import nitroglycerin from '../nitroglycerin.js';
import HorizontalMoleculeNode from './HorizontalMoleculeNode.js';

class CONode extends HorizontalMoleculeNode {

  /**
   * @param {Object} [options]
   */
  constructor( options ) {
    super( [ Element.C, Element.O ], options );
  }
}

nitroglycerin.register( 'CONode', CONode );
export default CONode;<|endoftext|>


<commit_before>// @flow
/**
 * Part of GDL gdl-frontend.
 * Copyright (C) 2017 GDL
 *
 * See LICENSE
 */

import React from 'react';
import { cx, css } from 'react-emotion';
import { lighten } from 'polished';
import rotate360 from '../style/rotate360';
import media from '../style/media';
import theme from '../style/theme';

type Props = {
  color?: 'link' | 'green',
  customColor?: string,
  href?: string,
  className?: string,
  isLoading?: boolean,
  disabled?: boolean,
  type?: 'submit' | 'reset' | 'button',
  onClick?: (
    event: SyntheticEvent<HTMLButtonElement> | SyntheticEvent<HTMLAnchorElement>
  ) => any
};

const buttonStyle = (color: string) => css`
  color: ${theme.colors.white};
  background: ${color};
  border-style: none;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2);
  font-weight: 500;
  border-radius: 50px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  min-width: 210px;
  line-height: 22px;
  text-transform: uppercase;
  min-height: 38px;
  padding-left: 30px;
  padding-right: 30px;
  font-size: 16px;
  &[disabled] {
    opacity: 0.3;
    cursor: not-allowed;
  }
  ${media.tablet`
    min-height: 48px;
    font-size: 18px;
  `};
  transition: transform 0.15s ease-out, background 0.15s ease-out;
  &:hover:not([disabled]) {
    transform: translateY(-1px);
    background: ${lighten(0.04, color)};
  }
`;

const loadingStyle = css`
  color: transparent;
  text-shadow: none;
  position: relative;
  pointer-events: none;
  &:after {
    animation: ${rotate360} 500ms infinite linear;
    border: 2px solid ${theme.colors.white};
    border-radius: 100px;
    border-right-color: transparent;
    border-top-color: transparent;
    content: '';
    display: block;
    width: 1em;
    height: 1em;
    position: absolute;
    left: calc(50% - (1em / 2));
    top: calc(50% - (1em / 2));
  }
`;

export default function({
  color,
  customColor,
  href,
  isLoading,
  className,
  ...props
}: Props) {
  // customColor takes precedence of the color prop
  const bgColor =
    customColor ||
    (color === 'green' ? theme.colors.greens.green : theme.colors.link);

  const style = cx(
    buttonStyle(bgColor),
    { [loadingStyle]: isLoading },
    className
  );

  return props.href == null ? (
    <button className={style} type="button" {...props} />
  ) : (
    // eslint-disable-next-line jsx-a11y/anchor-has-content

  );
}
<commit_msg>Button component now displays anchors correctly<commit_after>// @flow
/**
 * Part of GDL gdl-frontend.
 * Copyright (C) 2017 GDL
 *
 * See LICENSE
 */

import React from 'react';
import { cx, css } from 'react-emotion';
import { lighten } from 'polished';
import rotate360 from '../style/rotate360';
import media from '../style/media';
import theme from '../style/theme';

type Props = {
  color?: 'link' | 'green',
  customColor?: string,
  href?: string,
  className?: string,
  isLoading?: boolean,
  disabled?: boolean,
  type?: 'submit' | 'reset' | 'button',
  onClick?: (
    event: SyntheticEvent<HTMLButtonElement> | SyntheticEvent<HTMLAnchorElement>
  ) => any
};

const buttonStyle = (color: string) => css`
  color: ${theme.colors.white};
  background: ${color};
  border-style: none;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2);
  font-weight: 500;
  border-radius: 50px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  min-width: 210px;
  line-height: 22px;
  text-transform: uppercase;
  min-height: 38px;
  padding-left: 30px;
  padding-right: 30px;
  font-size: 16px;
  &[disabled] {
    opacity: 0.3;
    cursor: not-allowed;
  }
  ${media.tablet`
    min-height: 48px;
    font-size: 18px;
  `};
  transition: transform 0.15s ease-out, background 0.15s ease-out;
  &:hover:not([disabled]) {
    transform: translateY(-1px);
    background: ${lighten(0.04, color)};
  }
`;

const loadingStyle = css`
  color: transparent;
  text-shadow: none;
  position: relative;
  pointer-events: none;
  &:after {
    animation: ${rotate360} 500ms infinite linear;
    border: 2px solid ${theme.colors.white};
    border-radius: 100px;
    border-right-color: transparent;
    border-top-color: transparent;
    content: '';
    display: block;
    width: 1em;
    height: 1em;
    position: absolute;
    left: calc(50% - (1em / 2));
    top: calc(50% - (1em / 2));
  }
`;

export default function({
  color,
  customColor,
  href,
  isLoading,
  className,
  ...props
}: Props) {
  // customColor takes precedence of the color prop
  const bgColor =
    customColor ||
    (color === 'green' ? theme.colors.greens.green : theme.colors.link);

  const style = cx(
    buttonStyle(bgColor),
    { [loadingStyle]: isLoading },
    className
  );

  return href == null ? (
    <button className={style} type="button" {...props} />
  ) : (
    // eslint-disable-next-line jsx-a11y/anchor-has-content

  );
}
<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado

/**
 * A circular node that inherits Path, and allows for optimized drawing,
 * and improved parameter handling.
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var scenery = require( 'SCENERY/scenery' );

  var Path = require( 'SCENERY/nodes/Path' );
  var Shape = require( 'KITE/Shape' );

  scenery.Circle = function Circle( radius, options ) {
    if ( typeof radius === 'object' ) {
      // allow new Circle( { radius: ... } )
      // the mutators will call invalidateCircle() and properly set the shape
      options = radius;
    } else {
      this._radius = radius;

      // ensure we have a parameter object
      options = options || {};

      // fallback for non-canvas or non-svg rendering, and for proper bounds computation
      options.shape = Shape.circle( 0, 0, radius );
    }

    Path.call( this, options );
  };
  var Circle = scenery.Circle;

  inherit( Path, Circle, {
    invalidateCircle: function() {
      // setShape should invalidate the path and ensure a redraw
      this.setShape( Shape.circle( 0, 0, this._radius ) );
    },

    // create a circle instead of a path, hopefully it is faster in implementations
    createSVGFragment: function( svg, defs, group ) {
      return document.createElementNS( 'http://www.w3.org/2000/svg', 'circle' );
    },

    // optimized for the circle element instead of path
    updateSVGFragment: function( circle ) {
      circle.setAttribute( 'r', this._radius );

      circle.setAttribute( 'style', this.getSVGFillStyle() + this.getSVGStrokeStyle() );
    },

    getBasicConstructor: function( propLines ) {
      return 'new scenery.Circle( ' + this._radius + ', {' + propLines + '} )';
    },

    getRadius: function() {
      return this._radius;
    },

    setRadius: function( radius ) {
      if ( this._radius !== radius ) {
        this._radius = radius;
        this.invalidateCircle();
      }
      return this;
    },

    get radius() { return this.getRadius(); },
    set radius( value ) { return this.setRadius( value ); }
  } );

  // not adding mutators for now
  Circle.prototype._mutatorKeys = [ 'radius' ].concat( Path.prototype._mutatorKeys );

  return Circle;
} );
<commit_msg>Accelerated circle hit testing<commit_after>// Copyright 2002-2013, University of Colorado

/**
 * A circular node that inherits Path, and allows for optimized drawing,
 * and improved parameter handling.
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var scenery = require( 'SCENERY/scenery' );

  var Path = require( 'SCENERY/nodes/Path' );
  var Shape = require( 'KITE/Shape' );

  scenery.Circle = function Circle( radius, options ) {
    if ( typeof radius === 'object' ) {
      // allow new Circle( { radius: ... } )
      // the mutators will call invalidateCircle() and properly set the shape
      options = radius;
    } else {
      this._radius = radius;

      // ensure we have a parameter object
      options = options || {};

      // fallback for non-canvas or non-svg rendering, and for proper bounds computation
      options.shape = Shape.circle( 0, 0, radius );
    }

    Path.call( this, options );
  };
  var Circle = scenery.Circle;

  inherit( Path, Circle, {
    invalidateCircle: function() {
      // setShape should invalidate the path and ensure a redraw
      this.setShape( Shape.circle( 0, 0, this._radius ) );
    },

    // create a circle instead of a path, hopefully it is faster in implementations
    createSVGFragment: function( svg, defs, group ) {
      return document.createElementNS( 'http://www.w3.org/2000/svg', 'circle' );
    },

    // optimized for the circle element instead of path
    updateSVGFragment: function( circle ) {
      circle.setAttribute( 'r', this._radius );

      circle.setAttribute( 'style', this.getSVGFillStyle() + this.getSVGStrokeStyle() );
    },

    getBasicConstructor: function( propLines ) {
      return 'new scenery.Circle( ' + this._radius + ', {' + propLines + '} )';
    },

    getRadius: function() {
      return this._radius;
    },

    setRadius: function( radius ) {
      if ( this._radius !== radius ) {
        this._radius = radius;
        this.invalidateCircle();
      }
      return this;
    },

    // accelerated hit detection
    containsPointSelf: function( point ) {
      return point.x * point.x + point.y * point.y < this._radius * this._radius;
    },

    get radius() { return this.getRadius(); },
    set radius( value ) { return this.setRadius( value ); }
  } );

  // not adding mutators for now
  Circle.prototype._mutatorKeys = [ 'radius' ].concat( Path.prototype._mutatorKeys );

  return Circle;
} );
<|endoftext|>


<commit_before>import React from 'react'
import * as hljs from 'highlight.js'
import ResizeObserver from 'resize-observer-polyfill'
import debounce from 'lodash.debounce'
import ms from 'ms'
import { Controlled as CodeMirror } from 'react-codemirror2'

import WindowControls from '../components/WindowControls'
import Watermark from '../components/svg/Watermark'
import { COLORS, LANGUAGE_MODE_HASH, LANGUAGE_NAME_HASH, DEFAULT_SETTINGS } from '../lib/constants'

class Carbon extends React.PureComponent {
  static defaultProps = {
    onAspectRatioChange: () => {},
    updateCode: () => {},
    innerRef: () => {}
  }

  componentDidMount() {
    const ro = new ResizeObserver(entries => {
      const cr = entries[0].contentRect
      this.props.onAspectRatioChange(cr.width / cr.height)
    })
    ro.observe(this.exportContainerNode)
  }

  handleLanguageChange = debounce(
    (newCode, language) => {
      if (language === 'auto') {
        // try to set the language
        const detectedLanguage = hljs.highlightAuto(newCode).language
        const languageMode =
          LANGUAGE_MODE_HASH[detectedLanguage] || LANGUAGE_NAME_HASH[detectedLanguage]

        if (languageMode) {
          return languageMode.mime || languageMode.mode
        }
      }

      return language
    },
    ms('300ms'),
    {
      leading: true,
      trailing: true
    }
  )

  onBeforeChange = (editor, meta, code) => {
    if (!this.props.readOnly) {
      this.props.updateCode(code)
    }
  }

  getRef = ele => {
    this.exportContainerNode = ele
    this.props.innerRef(ele)
  }

  render() {
    const config = { ...DEFAULT_SETTINGS, ...this.props.config }

    const languageMode = this.handleLanguageChange(this.props.children, config.language)

    const options = {
      lineNumbers: config.lineNumbers,
      mode: languageMode || 'plaintext',
      theme: config.theme,
      scrollBarStyle: null,
      viewportMargin: Infinity,
      lineWrapping: true,
      extraKeys: {
        'Shift-Tab': 'indentLess'
      },
      // negative values removes the cursor, undefined means default (530)
      cursorBlinkRate: this.props.readOnly ? -1 : undefined
    }
    const backgroundImage =
      (this.props.config.backgroundImage && this.props.config.backgroundImageSelection) ||
      this.props.config.backgroundImage

    const content = (

        {config.windowControls ? (
          <WindowControls
            titleBar={this.props.titleBar}
            theme={config.windowTheme}
            handleTitleBarChange={this.props.updateTitleBar}
            code={this.props.children}
            copyable={this.props.copyable}
          />
        ) : null}
        <CodeMirror
          className={`CodeMirror__container window-theme__${config.windowTheme}`}
          onBeforeChange={this.onBeforeChange}
          value={this.props.children}
          options={options}
        />
        {config.watermark && <Watermark />}

    )

    return (

          {content}

    )
  }
}

export default Carbon
<commit_msg>add TODO for theme specific styles<commit_after>import React from 'react'
import * as hljs from 'highlight.js'
import ResizeObserver from 'resize-observer-polyfill'
import debounce from 'lodash.debounce'
import ms from 'ms'
import { Controlled as CodeMirror } from 'react-codemirror2'

import WindowControls from '../components/WindowControls'
import Watermark from '../components/svg/Watermark'
import { COLORS, LANGUAGE_MODE_HASH, LANGUAGE_NAME_HASH, DEFAULT_SETTINGS } from '../lib/constants'

class Carbon extends React.PureComponent {
  static defaultProps = {
    onAspectRatioChange: () => {},
    updateCode: () => {},
    innerRef: () => {}
  }

  componentDidMount() {
    const ro = new ResizeObserver(entries => {
      const cr = entries[0].contentRect
      this.props.onAspectRatioChange(cr.width / cr.height)
    })
    ro.observe(this.exportContainerNode)
  }

  handleLanguageChange = debounce(
    (newCode, language) => {
      if (language === 'auto') {
        // try to set the language
        const detectedLanguage = hljs.highlightAuto(newCode).language
        const languageMode =
          LANGUAGE_MODE_HASH[detectedLanguage] || LANGUAGE_NAME_HASH[detectedLanguage]

        if (languageMode) {
          return languageMode.mime || languageMode.mode
        }
      }

      return language
    },
    ms('300ms'),
    {
      leading: true,
      trailing: true
    }
  )

  onBeforeChange = (editor, meta, code) => {
    if (!this.props.readOnly) {
      this.props.updateCode(code)
    }
  }

  getRef = ele => {
    this.exportContainerNode = ele
    this.props.innerRef(ele)
  }

  render() {
    const config = { ...DEFAULT_SETTINGS, ...this.props.config }

    const languageMode = this.handleLanguageChange(this.props.children, config.language)

    const options = {
      lineNumbers: config.lineNumbers,
      mode: languageMode || 'plaintext',
      theme: config.theme,
      scrollBarStyle: null,
      viewportMargin: Infinity,
      lineWrapping: true,
      extraKeys: {
        'Shift-Tab': 'indentLess'
      },
      // negative values removes the cursor, undefined means default (530)
      cursorBlinkRate: this.props.readOnly ? -1 : undefined
    }
    const backgroundImage =
      (this.props.config.backgroundImage && this.props.config.backgroundImageSelection) ||
      this.props.config.backgroundImage

    const content = (

        {config.windowControls ? (
          <WindowControls
            titleBar={this.props.titleBar}
            theme={config.windowTheme}
            handleTitleBarChange={this.props.updateTitleBar}
            code={this.props.children}
            copyable={this.props.copyable}
          />
        ) : null}
        <CodeMirror
          className={`CodeMirror__container window-theme__${config.windowTheme}`}
          onBeforeChange={this.onBeforeChange}
          value={this.props.children}
          options={options}
        />
        {config.watermark && <Watermark />}

    )

    return (

          {content}

    )
  }
}

export default Carbon
<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 * IO type for Node
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var scenery = require( 'SCENERY/scenery' );

  // phet-io modules
  var assertInstanceOf = require( 'ifphetio!PHET_IO/assertInstanceOf' );
  var BooleanIO = require( 'ifphetio!PHET_IO/types/BooleanIO' );
  var FunctionIO = require( 'ifphetio!PHET_IO/types/FunctionIO' );
  var NullableIO = require( 'ifphetio!PHET_IO/types/NullableIO' );
  var NumberIO = require( 'ifphetio!PHET_IO/types/NumberIO' );
  var ObjectIO = require( 'ifphetio!PHET_IO/types/ObjectIO' );
  var phetioInherit = require( 'ifphetio!PHET_IO/phetioInherit' );
  var VoidIO = require( 'ifphetio!PHET_IO/types/VoidIO' );

  /**
   * IO type for phet/scenery's Node
   * @param {Node} node
   * @param {string} phetioID
   * @constructor
   */
  function NodeIO( node, phetioID ) {
    assert && assertInstanceOf( node, phet.scenery.Node );
    ObjectIO.call( this, node, phetioID );
  }

  phetioInherit( ObjectIO, 'NodeIO', NodeIO, {
    isVisible: {
      returnType: BooleanIO,
      parameterTypes: [],
      implementation: function() {
        return this.instance.visible;
      },
      documentation: 'Gets a Boolean value indicating whether the node can be seen and interacted with'
    },

    setVisible: {
      returnType: VoidIO,
      parameterTypes: [ BooleanIO ],
      implementation: function( visible ) {
        this.instance.visible = visible;
      },
      documentation: 'Set whether the node will be visible (and interactive)'
    },

    setPickable: {
      returnType: VoidIO,
      parameterTypes: [ NullableIO( BooleanIO ) ],
      implementation: function( pickable ) {
        this.instance.pickable = pickable;
      },
      documentation: 'Set whether the node will be pickable (and hence interactive). Pickable can take one of three values:

' +
                     '
null: pass-through behavior. Nodes with input listeners are pickable, but nodes without input listeners won\'t block events for nodes behind it.
' +
                     '
false: The node cannot be interacted with, and it blocks events for nodes behind it.
' +
                     '
true: The node can be interacted with (if it has an input listener).

' +
                     'For more about Scenery node pickability, please see http://phetsims.github.io/scenery/doc/implementation-notes#pickability.'
    },

    isPickable: {
      returnType: BooleanIO,
      parameterTypes: [],
      implementation: function() {
        return this.instance.pickable;
      },
      documentation: 'Gets whether the node is pickable (and hence interactive)'
    },

    addPickableListener: {
      returnType: VoidIO,
      parameterTypes: [ FunctionIO( VoidIO, [ BooleanIO ] ) ],
      implementation: function( callback ) {
        var inst = this.instance;
        this.instance.on( 'pickability', function() {
          callback( inst.isPickable() );
        } );
      },
      documentation: 'Adds a listener for when pickability of the node changes'
    },

    addVisibleListener: {
      returnType: VoidIO,
      parameterTypes: [ FunctionIO( VoidIO, [ BooleanIO ] ) ],
      implementation: function( callback ) {
        var inst = this.instance;
        this.instance.on( 'visibility', function() {
          callback( inst.isVisible() );
        } );
      },
      documentation: 'Adds a listener for when visibility of the node changes'
    },

    setOpacity: {
      returnType: VoidIO,
      parameterTypes: [ NumberIO ],
      implementation: function( opacity ) {
        this.instance.opacity = opacity;
      },
      documentation: 'Set opacity between 0-1 (inclusive)'
    },

    setRotation: {
      returnType: VoidIO,
      parameterTypes: [ NumberIO ],
      implementation: function( rotation ) {
        this.instance.rotation = rotation;
      },
      documentation: 'Set the rotation of the node, in radians'
    }
  }, {
    toStateObject: function( node ) {
      assert && assertInstanceOf( node, phet.scenery.Node );
      return {
        visible: node.isVisible(),
        pickable: node.isPickable(),
        opacity: node.opacity
      };
    },
    fromStateObject: function( stateObject ) {
      return stateObject;
    },
    setValue: function( node, fromStateObject ) {
      assert && assertInstanceOf( node, phet.scenery.Node );
      node.visible = fromStateObject.visible;
      node.pickable = fromStateObject.pickable;
      node.opacity = fromStateObject.opacity;
    },
    documentation: 'The base type for graphical and potentially interactive objects.'
  } );

  scenery.register( 'NodeIO', NodeIO );

  return NodeIO;
} );

<commit_msg>convert Node's visible PhET-iO interface to use Property, https://github.com/phetsims/phet-io/issues/1326<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * IO type for Node
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var BooleanProperty = require( 'AXON/BooleanProperty' );
  var scenery = require( 'SCENERY/scenery' );

  // phet-io modules
  var assertInstanceOf = require( 'ifphetio!PHET_IO/assertInstanceOf' );
  var BooleanIO = require( 'ifphetio!PHET_IO/types/BooleanIO' );
  var FunctionIO = require( 'ifphetio!PHET_IO/types/FunctionIO' );
  var NullableIO = require( 'ifphetio!PHET_IO/types/NullableIO' );
  var NumberIO = require( 'ifphetio!PHET_IO/types/NumberIO' );
  var ObjectIO = require( 'ifphetio!PHET_IO/types/ObjectIO' );
  var phetioInherit = require( 'ifphetio!PHET_IO/phetioInherit' );
  var VoidIO = require( 'ifphetio!PHET_IO/types/VoidIO' );

  /**
   * IO type for phet/scenery's Node
   * @param {Node} node
   * @param {string} phetioID
   * @constructor
   */
  function NodeIO( node, phetioID ) {
    assert && assertInstanceOf( node, phet.scenery.Node );
    ObjectIO.call( this, node, phetioID );

    var visibleProperty = new BooleanProperty( node.visible, {
      tandem: node.tandem.createTandem( 'visibleProperty' ),
      instanceDocumentation: 'Property that controls whether the Node will be visible (and interactive).'
    } );

    visibleProperty.link( function( visible ) {
      node.visible = visible;
    } );
    node.on( 'visibility', function() {
      visibleProperty.value = node.visible;
    } );

  }

  phetioInherit( ObjectIO, 'NodeIO', NodeIO, {
    setPickable: {
      returnType: VoidIO,
      parameterTypes: [ NullableIO( BooleanIO ) ],
      implementation: function( pickable ) {
        this.instance.pickable = pickable;
      },
      documentation: 'Set whether the node will be pickable (and hence interactive). Pickable can take one of three values:

' +
                     '
null: pass-through behavior. Nodes with input listeners are pickable, but nodes without input listeners won\'t block events for nodes behind it.
' +
                     '
false: The node cannot be interacted with, and it blocks events for nodes behind it.
' +
                     '
true: The node can be interacted with (if it has an input listener).

' +
                     'For more about Scenery node pickability, please see http://phetsims.github.io/scenery/doc/implementation-notes#pickability.'
    },

    isPickable: {
      returnType: BooleanIO,
      parameterTypes: [],
      implementation: function() {
        return this.instance.pickable;
      },
      documentation: 'Gets whether the node is pickable (and hence interactive)'
    },

    addPickableListener: {
      returnType: VoidIO,
      parameterTypes: [ FunctionIO( VoidIO, [ BooleanIO ] ) ],
      implementation: function( callback ) {
        var inst = this.instance;
        this.instance.on( 'pickability', function() {
          callback( inst.isPickable() );
        } );
      },
      documentation: 'Adds a listener for when pickability of the node changes'
    },
    setOpacity: {
      returnType: VoidIO,
      parameterTypes: [ NumberIO ],
      implementation: function( opacity ) {
        this.instance.opacity = opacity;
      },
      documentation: 'Set opacity between 0-1 (inclusive)'
    },

    setRotation: {
      returnType: VoidIO,
      parameterTypes: [ NumberIO ],
      implementation: function( rotation ) {
        this.instance.rotation = rotation;
      },
      documentation: 'Set the rotation of the node, in radians'
    }
  }, {
    toStateObject: function( node ) {
      assert && assertInstanceOf( node, phet.scenery.Node );
      return {
        pickable: node.isPickable(),
        opacity: node.opacity
      };
    },
    fromStateObject: function( stateObject ) {
      return stateObject;
    },
    setValue: function( node, fromStateObject ) {
      assert && assertInstanceOf( node, phet.scenery.Node );
      node.pickable = fromStateObject.pickable;
      node.opacity = fromStateObject.opacity;
    },
    documentation: 'The base type for graphical and potentially interactive objects.'
  } );

  scenery.register( 'NodeIO', NodeIO );

  return NodeIO;
} );

<|endoftext|>


<commit_before>/**
 *
 * @param {Object} stats
 * @param {String} [name]
 * @param {String} [nickname]
 * @constructor
 */
function Human(stats, name, nickname) {
	if(stats) {
		this._stats = {};

		for(var stat in stats) {
			if(stats.hasOwnProperty(stat)) {
				this[stat] = stats[stat];
			}
		}
	}

	if(name) this._name = name;
	if(nickname) this._nickname = nickname;
}

Human.prototype = {
	_name: '',
	_nickname: '',

	_stats: {
		hea: 0,
		agi: 0,
		dex: 0,
		str: 0,
		ldr: 0,
		wis: 0,
		lvl: 0,
		mec: 0,
		exp: 0,
		med: 0,
		mrk: 0
	},

	_wear: {
		head: new Wear(),
		body: new Wear(),
		legs: new Wear()
	},

	_ap: 0,
	_moral: 0
};

Human.HEAD = 'head';
Human.BODY = 'body';
Human.LEGS = 'legs';

/**
 *
 * @param {Wear} wear
 */
Human.prototype.putOn = function(wear) {
	var item = this._wear[wear.type];
	this._wear[wear.type] = wear;
	return item;
};

/**
 *
 * @param {Wear} wear
 */
Human.prototype.takeOff = function(wear) {
	var item = this._wear[wear.type];
	this._wear[wear.type] = '';
	return item;
};

Human.prototype.getWeight = function() {

}

// GETTER / SETTER

Object.defineProperty(Human.prototype, "weight", {
	get: function () {
		return this._wear.head.weight + this._wear.body.weight + this._wear.legs.weight;
	}
});

Object.defineProperty(Human.prototype, "weightPerc", {
	get: function () {
		return Math.round(this.weight / this.strength * 100) / 100;
	}
});

Object.defineProperty(Human.prototype, "name", {
	get: function () {
		return this._name;
	},

	set: function(val) {
		this._name = val;
	}
});

Object.defineProperty(Human.prototype, "nickname", {
	get: function () {
		return this._nickname;
	},

	set: function(val) {
		this._nickname = val;
	}
});

Object.defineProperty(Human.prototype, "health", {
	get: function () {
		return this._stats.hea;
	},

	set: function(val) {
		this._stats.hea = val;
	}
});

Object.defineProperty(Human.prototype, "agility", {
	get: function () {
		return this._stats.agi;
	},

	set: function(val) {
		this._stats.agi = val;
	}
});

Object.defineProperty(Human.prototype, "dexterity", {
	get: function () {
		return this._stats.dex;
	},

	set: function(val) {
		this._stats.dex = val;
	}
});

Object.defineProperty(Human.prototype, "strength", {
	get: function () {
		return this._stats.str;
	},

	set: function(val) {
		this._stats.str = val;
	}
});

Object.defineProperty(Human.prototype, "leadership", {
	get: function () {
		return this._stats.ldr;
	},

	set: function(val) {
		this._stats.ldr = val;
	}
});

Object.defineProperty(Human.prototype, "wisdom", {
	get: function () {
		return this._stats.wis;
	},

	set: function(val) {
		this._stats.wis = val;
	}
});

Object.defineProperty(Human.prototype, "level", {
	get: function () {
		return this._stats.lvl;
	},

	set: function(val) {
		this._stats.lvl = val;
	}
});

Object.defineProperty(Human.prototype, "mecanical", {
	get: function () {
		return this._stats.mec;
	},

	set: function(val) {
		this._stats.mec = val;
	}
});

Object.defineProperty(Human.prototype, "explosives", {
	get: function () {
		return this._stats.exp;
	},

	set: function(val) {
		this._stats.exp = val;
	}
});

Object.defineProperty(Human.prototype, "medical", {
	get: function () {
		return this._stats.med;
	},

	set: function(val) {
		this._stats.med = val;
	}
});

Object.defineProperty(Human.prototype, "marksmanship", {
	get: function () {
		return this._stats.mrk;
	},

	set: function(val) {
		this._stats.mrk = val;
	}
});

Object.defineProperty(Human.prototype, "AP", {
	get: function () {
		return this._ap;
	},

	set: function(val) {
		this._ap = val;
	}
});

Object.defineProperty(Human.prototype, "moral", {
	get: function () {
		return this._moral;
	},

	set: function(val) {
		this._moral = val;
	}
});

Object.defineProperty(Human.prototype, "wear", {
	get: function () {
		return this._wear;
	}
});
<commit_msg>added weight in perc<commit_after>/**
 *
 * @param {Object} stats
 * @param {String} [name]
 * @param {String} [nickname]
 * @constructor
 */
function Human(stats, name, nickname) {
	if(stats) {
		this._stats = {};

		for(var stat in stats) {
			if(stats.hasOwnProperty(stat)) {
				this[stat] = stats[stat];
			}
		}
	}

	if(name) this._name = name;
	if(nickname) this._nickname = nickname;
}

Human.prototype = {
	_name: '',
	_nickname: '',

	_stats: {
		hea: 0,
		agi: 0,
		dex: 0,
		str: 0,
		ldr: 0,
		wis: 0,
		lvl: 0,
		mec: 0,
		exp: 0,
		med: 0,
		mrk: 0
	},

	_wear: {
		head: new Wear(),
		body: new Wear(),
		legs: new Wear()
	},

	_ap: 0,
	_moral: 0
};

Human.HEAD = 'head';
Human.BODY = 'body';
Human.LEGS = 'legs';

/**
 *
 * @param {Wear} wear
 */
Human.prototype.putOn = function(wear) {
	var item = this._wear[wear.type];
	this._wear[wear.type] = wear;
	return item;
};

/**
 *
 * @param {Wear} wear
 */
Human.prototype.takeOff = function(wear) {
	var item = this._wear[wear.type];
	this._wear[wear.type] = '';
	return item;
};

Human.prototype.getWeight = function() {

}

// GETTER / SETTER

Object.defineProperty(Human.prototype, "weight", {
	get: function () {
		return this._wear.head.weight + this._wear.body.weight + this._wear.legs.weight;
	}
});

Object.defineProperty(Human.prototype, "weightPerc", {
	get: function () {
		return Math.round(this.weight / this.strength * 100);
	}
});

Object.defineProperty(Human.prototype, "name", {
	get: function () {
		return this._name;
	},

	set: function(val) {
		this._name = val;
	}
});

Object.defineProperty(Human.prototype, "nickname", {
	get: function () {
		return this._nickname;
	},

	set: function(val) {
		this._nickname = val;
	}
});

Object.defineProperty(Human.prototype, "health", {
	get: function () {
		return this._stats.hea;
	},

	set: function(val) {
		this._stats.hea = val;
	}
});

Object.defineProperty(Human.prototype, "agility", {
	get: function () {
		return this._stats.agi;
	},

	set: function(val) {
		this._stats.agi = val;
	}
});

Object.defineProperty(Human.prototype, "dexterity", {
	get: function () {
		return this._stats.dex;
	},

	set: function(val) {
		this._stats.dex = val;
	}
});

Object.defineProperty(Human.prototype, "strength", {
	get: function () {
		return this._stats.str;
	},

	set: function(val) {
		this._stats.str = val;
	}
});

Object.defineProperty(Human.prototype, "leadership", {
	get: function () {
		return this._stats.ldr;
	},

	set: function(val) {
		this._stats.ldr = val;
	}
});

Object.defineProperty(Human.prototype, "wisdom", {
	get: function () {
		return this._stats.wis;
	},

	set: function(val) {
		this._stats.wis = val;
	}
});

Object.defineProperty(Human.prototype, "level", {
	get: function () {
		return this._stats.lvl;
	},

	set: function(val) {
		this._stats.lvl = val;
	}
});

Object.defineProperty(Human.prototype, "mecanical", {
	get: function () {
		return this._stats.mec;
	},

	set: function(val) {
		this._stats.mec = val;
	}
});

Object.defineProperty(Human.prototype, "explosives", {
	get: function () {
		return this._stats.exp;
	},

	set: function(val) {
		this._stats.exp = val;
	}
});

Object.defineProperty(Human.prototype, "medical", {
	get: function () {
		return this._stats.med;
	},

	set: function(val) {
		this._stats.med = val;
	}
});

Object.defineProperty(Human.prototype, "marksmanship", {
	get: function () {
		return this._stats.mrk;
	},

	set: function(val) {
		this._stats.mrk = val;
	}
});

Object.defineProperty(Human.prototype, "AP", {
	get: function () {
		return this._ap;
	},

	set: function(val) {
		this._ap = val;
	}
});

Object.defineProperty(Human.prototype, "moral", {
	get: function () {
		return this._moral;
	},

	set: function(val) {
		this._moral = val;
	}
});

Object.defineProperty(Human.prototype, "wear", {
	get: function () {
		return this._wear;
	}
});
<|endoftext|>


<commit_before>var presentation;

var term = Webterm('http://192.168.1.4:9090/terminal', '#vim_terminal', {
    scale: false,
    rows: 40,
    columns: 120,
});
$(window).load(function() {
    // Create the HTML for the indicator
    $("#presentation > div").each(function(index,elm) {
        $(elm).append("
" + (index) + "
Follow along at http://brittg.com/catbarcamp
");
    });

    presentation = new Presenteer(
        "#presentation",
        $("#presentation > div"),
        { onAfterEnter : function(elm) {  } }
    );

    var locked = false;
    var last = 1;

    $(document).keydown(function(e) {
        var current = presentation.getCurrentIndex();
        if (current == 0) {
            if (!(e.altKey && e.ctrlKey)) {
                return;
            }
        }
        switch (e.keyCode) {
        case 32:
        case 39:
        case 40:
            if (current == 0) {
                return;
            }
            if (!locked) {
                presentation.next();
            }
            break;
        case 38:
        case 37:
            if (current == 0) {
                return;
            }
            if (!locked) {
                presentation.prev();
            }
            break;
        case 84:
            if (!locked) {
                if (current == 0) {
                    presentation.show(last);
                } else {
                    last = current;
                    presentation.show(0)
                }
            }
            break;
        case 76:
            if (e.ctrlKey && e.altKey) {
                locked = !locked;
            }
            break;
        default:
            console.log(e);
            break;
        }
    });
    //$("#presentationcontainer").on("click", function() { presentation.next(); });
    $('.initial').focus();
    presentation.start();
    presentation.show(1);
});
<commit_msg>Update short url<commit_after>var presentation;

var term = Webterm('http://192.168.1.4:9090/terminal', '#vim_terminal', {
    scale: false,
    rows: 40,
    columns: 120,
});
$(window).load(function() {
    // Create the HTML for the indicator
    $("#presentation > div").each(function(index,elm) {
        $(elm).append("
" + (index) + "
Follow along at http://brittg.com/vim
");
    });

    presentation = new Presenteer(
        "#presentation",
        $("#presentation > div"),
        { onAfterEnter : function(elm) {  } }
    );

    var locked = false;
    var last = 1;

    $(document).keydown(function(e) {
        var current = presentation.getCurrentIndex();
        if (current == 0) {
            if (!(e.altKey && e.ctrlKey)) {
                return;
            }
        }
        switch (e.keyCode) {
        case 32:
        case 39:
        case 40:
            if (current == 0) {
                return;
            }
            if (!locked) {
                presentation.next();
            }
            break;
        case 38:
        case 37:
            if (current == 0) {
                return;
            }
            if (!locked) {
                presentation.prev();
            }
            break;
        case 84:
            if (!locked) {
                if (current == 0) {
                    presentation.show(last);
                } else {
                    last = current;
                    presentation.show(0)
                }
            }
            break;
        case 76:
            if (e.ctrlKey && e.altKey) {
                locked = !locked;
            }
            break;
        default:
            console.log(e);
            break;
        }
    });
    //$("#presentationcontainer").on("click", function() { presentation.next(); });
    $('.initial').focus();
    presentation.start();
    presentation.show(1);
});
<|endoftext|>


<commit_before>/******************************************************************************
This file is part of PIRATES.

PIRATES is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

PIRATES is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with PIRATES.  If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/

game.PlayScreen = me.ScreenObject.extend({
  /**
  *  action to perform on state change
  */
  onResetEvent: function(players, idPlayer) {
    //Map init
    me.levelDirector.loadLevel("map_base");

    // reset the score
    game.data.score = 0;

    var t = this;
    this.players = players;
    this.playerId = idPlayer;

    //Add the players
    for(var id in players){
      me.game.world.addChild(players[id]);
    }

    //Emit first player data
    var data =
    {
      x:t.players[t.playerId].pos._x,
      y:t.players[t.playerId].pos._y,
      velX:t.players[t.playerId].body.vel.x,
      velY:t.players[t.playerId].body.vel.y
    };
    socket.emit('updatePlayer', {id: t.playerId, player: data});

    //On each update event, update all the other players
    socket.on('update', function(param){
      var now = Date.now();

      for(var i in param) {
        var p = param[i];

        if(p.id !== t.playerId){
          var dt = now - p.lastMaj;

          t.players[p.id].body.vel.set(p.vel.x, p.vel.y);
          t.players[p.id].pos.x = p.pos.x;
          t.players[p.id].pos.y = p.pos.y;

          if(!isNaN(dt)){
            t.players[p.id].update(dt);
          }
          //TODO update other params
        }
      }
      //To force the drawing of each object by the engine
      me.game.repaint();

      var data =
      {
        x:t.players[t.playerId].pos._x,
        y:t.players[t.playerId].pos._y,
        velX:t.players[t.playerId].body.vel.x,
        velY:t.players[t.playerId].body.vel.y,
        lastMaj: Date.now(),
        currentAnimation:t.players[t.playerId].characterRenderable.current.name
      };
      socket.emit('updatePlayer', {id: t.playerId, player: data});
    });

    // add our HUD to the game world
    this.HUD = new game.HUD.Container();
    me.game.world.addChild(this.HUD);

    // set the display to follow our position on both axis
    me.game.viewport.follow(this.players[this.playerId], me.game.viewport.AXIS.BOTH);
  },

  /**
  *  action to perform when leaving this screen (state change)
  */
  onDestroyEvent: function() {
    // remove the HUD from the game world
    me.game.world.removeChild(this.HUD);
  }
});
<commit_msg>Fix z-position of players to draw objects above them The map must now have a "entities" object layer, containing at least one element. The layer's reference is saves and players are now added to it at the beginning, so we can order the layer as we want in Tiled.<commit_after>/******************************************************************************
This file is part of PIRATES.

PIRATES is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

PIRATES is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with PIRATES.  If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/

game.PlayScreen = me.ScreenObject.extend({
  /**
   *  action to perform on state change
   */
  onResetEvent: function(players, idPlayer) {
    //Map init
    me.levelDirector.loadLevel("map_base", {
      flatten: false,
      container: me.game.world
    });

    /**
     * The container of all characters in the game, creatd in Tiled
     * @type {me.Container}
     */
    this.playerLayer = me.game.world.getChildByName("entities")[0];

    if (me.game.HASH.debug === true) {
      console.assert(this.playerLayer !== undefined, 'No children named '
        + '"entities" found. The Tiled map must include such a layer to add '
        + 'the players to the game and the layer must not be empty.', this);
      console.assert(this.playerLayer instanceof me.Container, 'The "entities" '
        + 'Tiled layer must be an object layer to allow adding players inside it.', this);
    }

    var t = this;
    this.players = players;
    this.playerId = idPlayer;

    //Add the players
    for(var id in players){
      this.playerLayer.addChild(players[id]);
    }

    //Emit first player data
    var data =
    {
      x:t.players[t.playerId].pos._x,
      y:t.players[t.playerId].pos._y,
      velX:t.players[t.playerId].body.vel.x,
      velY:t.players[t.playerId].body.vel.y
    };
    socket.emit('updatePlayer', {id: t.playerId, player: data});

    //On each update event, update all the other players
    socket.on('update', function(param){
      var now = Date.now();

      for(var i in param) {
        var p = param[i];

        if(p.id !== t.playerId){
          var dt = now - p.lastMaj;

          t.players[p.id].body.vel.set(p.vel.x, p.vel.y);
          t.players[p.id].pos.x = p.pos.x;
          t.players[p.id].pos.y = p.pos.y;

          if(!isNaN(dt)){
            t.players[p.id].update(dt);
          }
          //TODO update other params
        }
      }
      //To force the drawing of each object by the engine
      me.game.repaint();

      var data =
      {
        x:t.players[t.playerId].pos._x,
        y:t.players[t.playerId].pos._y,
        velX:t.players[t.playerId].body.vel.x,
        velY:t.players[t.playerId].body.vel.y,
        lastMaj: Date.now(),
        currentAnimation:t.players[t.playerId].characterRenderable.current.name
      };
      socket.emit('updatePlayer', {id: t.playerId, player: data});
    });

    // add our HUD to the game world
    this.HUD = new game.HUD.Container();
    me.game.world.addChild(this.HUD);

    // set the display to follow our position on both axis
    me.game.viewport.follow(this.players[this.playerId], me.game.viewport.AXIS.BOTH);
  },

  /**
  *  action to perform when leaving this screen (state change)
  */
  onDestroyEvent: function() {
    // remove the HUD from the game world
    me.game.world.removeChild(this.HUD);
  }
});
<|endoftext|>


<commit_before>//
// Please update "commments" to "submit point"
//

'use strict';

var assertionUrl = 'https://3pp.io:4343/persona';
var postPointUrl = 'https://3pp.io:4343/post/point';
var serviceListUrl = 'https://tosdr.org/index/services.json';

$(document).ready(function(){
  var loggedInUser = null;
  var loadTimer = setTimeout(function() {
    showPersona();
  }, 3000);
  function logout(){
    loggedInUser = null;
    var response = $.post(assertionUrl + '/logout');
    response.always(showPersona);
  }

  function verify(assertion){
    if (loadTimer) {
      clearTimeout(loadTimer);
      loadTimer = null;
    }
    showSigningIn();
    var response = $.ajax(assertionUrl + '/verify', {data: {assertion: assertion}, type: 'POST', xhrFields: {withCredentials: true}});
    response.done(login);
    response.fail(function(){
      navigator.id.logout();
    });
  }

  function login(data){
    showSubmitForm(data.email);
  }

  navigator.id.watch({
    loggedInUser: loggedInUser,
    onlogin: verify,
    onlogout: logout
  });

  var numServices = 1;
  function showServiceFields() {
    var str = '          <input type="text" placeholder="service">';
    $('.serviceFields').html(str);
  }

  function showPersona(){
    $('#submit-point-form').html('

To submit a point, please sign in — you can use an existing email address.

');
    $('.signinButton').click(function(){ navigator.id.request(); }).css('cursor', 'pointer');
  }

  function showSigningIn(){
    $('#submit-point-form').html('

(signing you in...)

');
  }

  function showLoading(){
    $('#submit-point-form').html('

(loading...)

');
  }

  // This is ugly, too much html here
  //
  //

  function showSubmitForm(email){
    $('#submit-point-form').html('<form class="submitForm">' +
        '' +
        '<fieldset>' +
        '<legend>Submit a point about a clause</legend>' +

        'Title<input type="text" id="titleField" name="title" required />' +

        '<input type="radio" name="point" id="pointGood" value="good" />Good<input type="radio" name="point" id="pointNeutral" value="neutral" />Neutral<input type="radio" required name="point" id="pointBad" value="bad" />Bad<input type="radio" name="point" id="pointBlocker" value="blocker" />Blocker' +

        'Please summarise this clause Parsed as Markdown<textarea name="summary" id="summaryField" required class="input-xxlarge" placeholder="What the clause in the terms does. Try not to make more than 5 sentences, but sometimes more is needed. Be creative. Feel free to include some quotes from the terms directly. It is very important that it is easy to understand and written in plain English."></textarea>' +

        'Service(s)<input id="servicesField" name="services" required class="input-large" />' +

'          Service(s) to which the point applies' +
'                                       ' +
'          <button class="btn btn-inline" type="button" onclick="addServiceField();">Add one</button>' +
'' +

        'Source<input type="url" id="sourceField" name="source" placeholder="http://www.example.com/tos" />' +

        'Topic<input id="topicsField" name="topics" required class="input-large" />' +

'          <select id="topics">' +
'            <option>Select a topic</option>' +
'            <option>Scope of the copyright license</option>' +
'            <option>Changes</option>' +
'          </select>' +

        '</fieldset>' +
        '
' +
        '<button class="btn btn-primary btn-large" id="postPoint">Send</button>' +
        'Submitting as ' + email + ' (Not your email address? Log out!)' +

        '
' +
        '</form>');
    showServiceFields();
    var response = $.get(serviceListUrl, 'json');
    response.done(function(services){
      services = $.map(services, function(value, key){
        return key;
      });
      // Note: the width should be 'element', but for some reason it receives a different width than other input elements
      $('#servicesField').select2({tags: services, width: '220px', containerCss: {'border-radius': '4px'}});
    });

    $('.submitForm').submit(function(e){
      var response = $.ajax(postPointUrl, {data: {title: $('#titleField').val(), point: $('input[name=point]:checked', '.submitForm').val(), services: $('#servicesField').val(), summary: $('#summaryField').val()}, type: 'POST', xhrFields: {withCredentials: true}});
      response.done(showConfirmation);
      response.fail(showError);
      e.preventDefault();
    });
    $('.signoutButton').click(function(){ navigator.id.logout(); });
  }

  function showConfirmation(){
    $('#submit-point-form').html('Your point has been submitted. Thank you! '
        +'submit another one or '
        +'see the list.');
  }

  function showError(){
    $('#submit-point-form').prepend('
<button type="button" class="close" data-dismiss="alert">×</button>Something went wrong saving your point, did you fill in all the fields?
');
  }
  showLoading();
});
<commit_msg>hide markdown info<commit_after>//
// Please update "commments" to "submit point"
//

'use strict';

var assertionUrl = 'https://3pp.io:4343/persona';
var postPointUrl = 'https://3pp.io:4343/post/point';
var serviceListUrl = 'https://tosdr.org/index/services.json';

$(document).ready(function(){
  var loggedInUser = null;
  var loadTimer = setTimeout(function() {
    showPersona();
  }, 3000);
  function logout(){
    loggedInUser = null;
    var response = $.post(assertionUrl + '/logout');
    response.always(showPersona);
  }

  function verify(assertion){
    if (loadTimer) {
      clearTimeout(loadTimer);
      loadTimer = null;
    }
    showSigningIn();
    var response = $.ajax(assertionUrl + '/verify', {data: {assertion: assertion}, type: 'POST', xhrFields: {withCredentials: true}});
    response.done(login);
    response.fail(function(){
      navigator.id.logout();
    });
  }

  function login(data){
    showSubmitForm(data.email);
  }

  navigator.id.watch({
    loggedInUser: loggedInUser,
    onlogin: verify,
    onlogout: logout
  });

  var numServices = 1;
  function showServiceFields() {
    var str = '          <input type="text" placeholder="service">';
    $('.serviceFields').html(str);
  }

  function showPersona(){
    $('#submit-point-form').html('

To submit a point, please sign in — you can use an existing email address.

');
    $('.signinButton').click(function(){ navigator.id.request(); }).css('cursor', 'pointer');
  }

  function showSigningIn(){
    $('#submit-point-form').html('

(signing you in...)

');
  }

  function showLoading(){
    $('#submit-point-form').html('

(loading...)

');
  }

  // This is ugly, too much html here
  //
  //

  function showSubmitForm(email){
    $('#submit-point-form').html('<form class="submitForm">' +
        '' +
        '<fieldset>' +
        '<legend>Submit a point about a clause</legend>' +

        'Title<input type="text" id="titleField" name="title" required />' +

        '<input type="radio" name="point" id="pointGood" value="good" />Good<input type="radio" name="point" id="pointNeutral" value="neutral" />Neutral<input type="radio" required name="point" id="pointBad" value="bad" />Bad<input type="radio" name="point" id="pointBlocker" value="blocker" />Blocker' +

        'Please summarise this clause Parsed as Markdown<textarea name="summary" id="summaryField" required class="input-xxlarge" placeholder="What the clause in the terms does. Try not to make more than 5 sentences, but sometimes more is needed. Be creative. Feel free to include some quotes from the terms directly. It is very important that it is easy to understand and written in plain English."></textarea>' +

        'Service(s)<input id="servicesField" name="services" required class="input-large" />' +

'          Service(s) to which the point applies' +
'                                       ' +
'          <button class="btn btn-inline" type="button" onclick="addServiceField();">Add one</button>' +
'' +

        'Source<input type="url" id="sourceField" name="source" placeholder="http://www.example.com/tos" />' +

        'Topic<input id="topicsField" name="topics" required class="input-large" />' +

'          <select id="topics">' +
'            <option>Select a topic</option>' +
'            <option>Scope of the copyright license</option>' +
'            <option>Changes</option>' +
'          </select>' +

        '</fieldset>' +
        '
' +
        '<button class="btn btn-primary btn-large" id="postPoint">Send</button>' +
        'Submitting as ' + email + ' (Not your email address? Log out!)' +

        '
' +
        '</form>');
    showServiceFields();
    var response = $.get(serviceListUrl, 'json');
    response.done(function(services){
      services = $.map(services, function(value, key){
        return key;
      });
      // Note: the width should be 'element', but for some reason it receives a different width than other input elements
      $('#servicesField').select2({tags: services, width: '220px', containerCss: {'border-radius': '4px'}});
    });

    $('.submitForm').submit(function(e){
      var response = $.ajax(postPointUrl, {data: {title: $('#titleField').val(), point: $('input[name=point]:checked', '.submitForm').val(), services: $('#servicesField').val(), summary: $('#summaryField').val()}, type: 'POST', xhrFields: {withCredentials: true}});
      response.done(showConfirmation);
      response.fail(showError);
      e.preventDefault();
    });
    $('.signoutButton').click(function(){ navigator.id.logout(); });
  }

  function showConfirmation(){
    $('#submit-point-form').html('Your point has been submitted. Thank you! '
        +'submit another one or '
        +'see the list.');
  }

  function showError(){
    $('#submit-point-form').prepend('
<button type="button" class="close" data-dismiss="alert">×</button>Something went wrong saving your point, did you fill in all the fields?
');
  }
  showLoading();
});
<|endoftext|>


<commit_before>requirejs(["rAppid"], function (rAppid) {

    rAppid.defineClass("js.ui.ItemsView",
        ["js.ui.View", "js.core.Template", "js.core.List"], function (View, Template, List) {
            return View.inherit({
                defaults: {
                    tagName: "div",
                    items: null
                },
                hasItems: function(){
                    if(this.$.items){
                        return this.$.items.length;
                    }
                    return 0;
                }.on('items'),
                render: function(){
                    this.$renderedItems = [];
                    return this.callBase();
                },
                clear: function(){

                },
                _renderItems: function(items,oldItems){
                    if (oldItems && oldItems instanceof List) {
                        oldItems.unbind('sort', this._onSort);
                        oldItems.unbind('reset', this._onReset);
                        oldItems.unbind('add', this._onItemAdd);
                        oldItems.unbind('remove', this._onItemRemove);
                    }

                    if(items instanceof List){

                        items.bind('sort', this._onSort, this);
                        items.bind('reset', this._onReset, this);
                        items.bind('add', this._onItemAdd, this);
                        items.bind('remove', this._onItemRemove, this);
                        this._innerRenderItems(items.$items);
                    } else if(rAppid._.isArray(items)){
                        this._innerRenderItems(items);
                    }
                },
                _onSort: function(e){
                    if(this.isRendered()){
                        var item, c;
                        for (var i = 0; i < e.$.items.length; i++) {
                            item = e.$.items[i];
                            c = this.getComponentForItem(item);
                            this.$el.removeChild(c.$el);
                            this.$el.appendChild(c.$el);
                        }
                    }
                },
                _onReset: function(e){
                    this._innerRenderItems(e.$.items);
                },
                _onItemAdd: function(e){
                    this._innerRenderItem(e.$.item,e.$.index);
                },
                _onItemRemove: function(e){
                    this._removeRenderedItem(e.$.item);
                },
                _innerRenderItems: function (items) {
                    if (this.$renderedItems) {
                        var c;
                        for (var j = this.$renderedItems.length - 1; j >= 0; j--) {
                            c = this.$renderedItems[j];
                            this.$el.removeChild(c.component.$el);
                        }
                    }
                    this.$renderedItems = [];
                    for (var i = 0; i < items.length; i++) {
                        this._innerRenderItem(items[i],i);
                    }

                },
                _innerRenderItem: function (item,i) {
                    var comp = this.$templates['item'].createComponents({$item: item, $index: i})[0];
                    // add to rendered item map
                    this.$renderedItems.push({
                        item: item,
                        component: comp
                    });
                    this.addChild(comp);
                },
                _removeRenderedItem: function(item){
                    var ri;
                    for (var i = 0; i < this.$renderedItems.length; i++) {
                        ri = this.$renderedItems[i];
                        if (ri.item === item) {
                            this.$el.removeChild(ri.component.$el);
                            this.$renderedItems.slice(i,1);
                            return;
                        }
                    }
                },
                getComponentForItem: function (item) {
                    var ri;
                    for (var i = 0; i < this.$renderedItems.length; i++) {
                        ri = this.$renderedItems[i];
                        if (ri.item === item) {
                            return ri.component;
                        }
                    }
                    return null;
                }
            });
        }
    );
});<commit_msg>Fixed ItemsView<commit_after>requirejs(["rAppid"], function (rAppid) {

    rAppid.defineClass("js.ui.ItemsView",
        ["js.ui.View", "js.core.Template", "js.core.List"], function (View, Template, List) {
            return View.inherit({
                defaults: {
                    tagName: "div",
                    items: null
                },
                hasItems: function(){
                    if(this.$.items){
                        return this.$.items.length;
                    }
                    return 0;
                }.on('items'),
                render: function(){
                    this.$renderedItems = [];
                    return this.callBase();
                },
                clear: function(){

                },
                _renderItems: function(items,oldItems){
                    if (oldItems && oldItems instanceof List) {
                        oldItems.unbind('sort', this._onSort);
                        oldItems.unbind('reset', this._onReset);
                        oldItems.unbind('add', this._onItemAdd);
                        oldItems.unbind('remove', this._onItemRemove);
                    }

                    if(items instanceof List){

                        items.bind('sort', this._onSort, this);
                        items.bind('reset', this._onReset, this);
                        items.bind('add', this._onItemAdd, this);
                        items.bind('remove', this._onItemRemove, this);
                        this._innerRenderItems(items.$items);
                    } else if(rAppid._.isArray(items)){
                        this._innerRenderItems(items);
                    }
                },
                _onSort: function(e){
                    if(this.isRendered()){
                        var item, c;
                        for (var i = 0; i < e.$.items.length; i++) {
                            item = e.$.items[i];
                            c = this.getComponentForItem(item);
                            this.$el.removeChild(c.$el);
                            this.$el.appendChild(c.$el);
                        }
                    }
                },
                _onReset: function(e){
                    this._innerRenderItems(e.$.items);
                },
                _onItemAdd: function(e){
                    this._innerRenderItem(e.$.item,e.$.index);
                },
                _onItemRemove: function(e){
                    this._removeRenderedItem(e.$.item);
                },
                _innerRenderItems: function (items) {
                    if (this.$renderedItems) {
                        var c;
                        for (var j = this.$renderedItems.length - 1; j >= 0; j--) {
                            c = this.$renderedItems[j];
                            this.$el.removeChild(c.component.$el);
                        }
                    }
                    this.$renderedItems = [];
                    for (var i = 0; i < items.length; i++) {
                        this._innerRenderItem(items[i],i);
                    }

                },
                _innerRenderItem: function (item,i) {
                    var comp = this.$templates['item'].createComponents({$item: item, $index: i})[0];
                    // add to rendered item map
                    this.$renderedItems.push({
                        item: item,
                        component: comp
                    });
                    this.addChild(comp);
                },
                _removeRenderedItem: function(item){
                    var ri;
                    for (var i = 0; i < this.$renderedItems.length; i++) {
                        ri = this.$renderedItems[i];
                        if (ri.item === item) {
                            this.$el.removeChild(ri.component.$el);
                            this.$renderedItems.splice(i,1);
                            return;
                        }
                    }
                },
                getComponentForItem: function (item) {
                    var ri;
                    for (var i = 0; i < this.$renderedItems.length; i++) {
                        ri = this.$renderedItems[i];
                        if (ri.item === item) {
                            return ri.component;
                        }
                    }
                    return null;
                }
            });
        }
    );
});<|endoftext|>


<commit_before>define(['jquery', 'jquery-color', 'jss', './util', './storage'],
function (jquery, jqueryColor, jss, util, storage) {
  var fonts = ['"Segoe UI", Helvetica, Arial, sans-serif', 'Raleway, "Segoe UI", Helvetica, Arial, sans-serif'];

  var script = {
    init: function () { },

    /**
    Changes the style to whatever is in the scope.
    theme: The new theme to change to.
    transition: A bool indicating whether to slowly transition or immediately change.
    */
    updateStyle: function (theme, transition) {
      this.updateFont();

      var options_color = theme.colors['options-color'];
      var background_color = theme.colors['background-color'];
      var main_color = theme.colors['main-color'];
      var title_color = theme.colors['title-color'];

      jss.set('*', {
        'border-color': options_color
      });

      jss.set('::-webkit-scrollbar', {
        'background': background_color
      });

      jss.set('::-webkit-scrollbar-thumb', {
        'background': options_color
      });

      jss.set('::-webkit-input-placeholder', {
        'background': main_color
      });

      // Animate the color transition.
      if (transition) {
        jquery('.background-color').animate({ 'backgroundColor': background_color }, { duration: 800, queue: false });
        jquery('.titles-color').animate({ 'color': title_color }, { duration: 800, queue: false });
        jquery('body').animate({ 'color': main_color }, { duration: 1200, queue: false });
        jquery('input').animate({ 'color': main_color }, { duration: 1600, queue: false });
        jquery('.options-color').animate({ 'color': options_color }, { duration: 1200, queue: false });
      }

      // ...but then we still need to add it to the DOM.
      jss.set('.background-color', {
        'background-color': background_color
      });
      jss.set('.titles-color', {
        'color': title_color
      });
      jss.set('body', {
        'color': main_color
      });
      jss.set('input', {
        'color': main_color
      });
      jss.set('.options-color', {
        'color': options_color
      });
      jss.set('.bookmark-active', {
        'background-color': options_color
      });
      jss.set('.overlay', {
        'background-color': options_color
      });
      jss.set('.pagebase-grouped > .group > .page', {
        'border-top-style': 'solid',
        'border-top-width': '1px',
        'border-top-color': options_color
      });
      jss.set('.pagebase-grouped > .group > .page', {
        'border-top-style': 'solid',
        'border-top-width': '1px',
        'border-top-color': options_color
      });
      jss.set('#picker', {
        'border': '1px solid ' + options_color
      });
    },

    updateFont: function () {
      jss.set('body', {
        'font-family': fonts[storage.get('currentFont', 0)],
      });
    }
  };

  return script;
});
<commit_msg>Cleanup animations<commit_after>define(['jquery', 'jquery-color', 'jss', './util', './storage'],
  function (jquery, jqueryColor, jss, util, storage) {
    var fonts = ['"Segoe UI", Helvetica, Arial, sans-serif', 'Raleway, "Segoe UI", Helvetica, Arial, sans-serif'];

    var script = {
      init: function () { },

      /**
      Updates the page style with colors provided.
      theme: The new theme to use.
      transition: If true, animate the color transition.
      */
      updateStyle: function (theme, transition) {
        this.updateFont();

        var options_color = theme.colors['options-color'];
        var background_color = theme.colors['background-color'];
        var main_color = theme.colors['main-color'];
        var title_color = theme.colors['title-color'];

        // Animate the color transition.
        var duration = 1200;
        if (transition === false) {
          duration = 0;
        }

        jquery('*').animate({ 'borderColor': options_color }, { duration: duration, queue: false, easing: 'linear' });
        jquery('*').animate({ 'color': main_color }, { duration: duration, queue: false, easing: 'linear' });
        jquery('.background-color').animate({ 'backgroundColor': background_color }, { duration: duration, queue: false, easing: 'linear' });
        jquery('.titles-color').animate({ 'color': title_color }, { duration: duration, queue: false, easing: 'linear' });
        jquery('body').animate({ 'color': main_color }, { duration: duration, queue: false, easing: 'linear' });
        jquery('input').animate({ 'color': main_color }, { duration: duration, queue: false, easing: 'linear' });
        jquery('.options-color').animate({ 'color': options_color }, { duration: duration, queue: false, easing: 'linear' });
        jquery('#picker').animate({ 'borderColor': options_color }, { duration: duration, queue: false, easing: 'linear' });
        jquery('.overlay').animate({ 'backgroundColor': options_color }, { duration: duration, queue: false, easing: 'linear' });
        jquery('.bookmark-active').animate({ 'backgroundColor': options_color }, { duration: duration, queue: false, easing: 'linear' });

        // ...poor sods that can't be animated. SAD!
        jss.set('::-webkit-scrollbar', {
          'background': background_color
        });
        jss.set('::-webkit-scrollbar-thumb', {
          'background': options_color
        });
        jss.set('::-webkit-input-placeholder', {
          'background': main_color
        });
        jss.set('.pagebase-grouped > .group > .page', {
          'border-top-style': 'solid',
          'border-top-width': '1px'
        });
        jss.set('#picker', {
          'border': '1px solid'
        });
      },

      updateFont: function () {
        jss.set('body', {
          'font-family': fonts[storage.get('currentFont', 0)],
        });
      }
    };

    return script;
  });
<|endoftext|>


<commit_before>// Copyright 2014-2015, University of Colorado Boulder

// RequireJS configuration file for scenery-phet
require.config( {
  deps: [ 'vegas-main' ],

  paths: {

    // third party libs
    text: '../../sherpa/lib/text-2.0.12',

    // plugins
    image: '../../chipper/js/requirejs-plugins/image',
    mipmap: '../../chipper/js/requirejs-plugins/mipmap',
    string: '../../chipper/js/requirejs-plugins/string',
    ifphetio: '../../chipper/js/requirejs-plugins/ifphetio',

    // PhET libs, uppercase names to identify them in require.js imports
    AXON: '../../axon/js',
    BRAND: '../../brand/' + phet.chipper.brand + '/js',
    DOT: '../../dot/js',
    JOIST: '../../joist/js',
    KITE: '../../kite/js',
    PHETCOMMON: '../../phetcommon/js',
    REPOSITORY: '..',
    PHET_CORE: '../../phet-core/js',
    PHET_IO: '../../phet-io/js',
    SCENERY: '../../scenery/js',
    SCENERY_PHET: '../../scenery-phet/js',
    SHERPA: '../../sherpa',
    SUN: '../../sun/js',
    TANDEM: '../../tandem/js',
    VEGAS: '../../vegas/js'
  },

  // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false
  urlArgs: phet.chipper.getCacheBusterArgs()

} );
<commit_msg>Removed unnecessary SHERPA entries in config.js files, see https://github.com/phetsims/chipper/issues/553<commit_after>// Copyright 2014-2015, University of Colorado Boulder

// RequireJS configuration file for scenery-phet
require.config( {
  deps: [ 'vegas-main' ],

  paths: {

    // third party libs
    text: '../../sherpa/lib/text-2.0.12',

    // plugins
    image: '../../chipper/js/requirejs-plugins/image',
    mipmap: '../../chipper/js/requirejs-plugins/mipmap',
    string: '../../chipper/js/requirejs-plugins/string',
    ifphetio: '../../chipper/js/requirejs-plugins/ifphetio',

    // PhET libs, uppercase names to identify them in require.js imports
    AXON: '../../axon/js',
    BRAND: '../../brand/' + phet.chipper.brand + '/js',
    DOT: '../../dot/js',
    JOIST: '../../joist/js',
    KITE: '../../kite/js',
    PHETCOMMON: '../../phetcommon/js',
    REPOSITORY: '..',
    PHET_CORE: '../../phet-core/js',
    PHET_IO: '../../phet-io/js',
    SCENERY: '../../scenery/js',
    SCENERY_PHET: '../../scenery-phet/js',
    SUN: '../../sun/js',
    TANDEM: '../../tandem/js',
    VEGAS: '../../vegas/js'
  },

  // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false
  urlArgs: phet.chipper.getCacheBusterArgs()

} );
<|endoftext|>


<commit_before>/* global Backbone, Mail, models */

var views = views || {};

views.Folder = Backbone.Marionette.ItemView.extend({

	template: "#mail-folder-template",

	events: {
		"click .collapse" : "collapseFolder",
		"click li a" : "loadMessages"
	},

	initialize: function(options) {
		this.model = options.model;
	},

	collapseFolder: function(e) {
		e.preventDefault();
		this.model.toggleOpen();
	},

	loadMessages: function(e) {
		e.preventDefault();
		var accountId = this.model.get('accountId');
		var folderId = $(e.currentTarget).parent().data('folder_id');
		var noSelect = $(e.currentTarget).parent().data('no_select');
		Mail.UI.loadMessages(accountId, folderId, noSelect);
	},

	onRender: function() {
		// Get rid of that pesky wrapping-div.
		// Assumes 1 child element present in template.
		this.$el = this.$el.children();
		// Unwrap the element to prevent infinitely
		// nesting elements during re-render.
		this.$el.unwrap();
		this.setElement(this.$el);
	}
});

views.Account = Backbone.Marionette.CompositeView.extend({

	collection: null,
	model: null,

	template: "#mail-account-template",

	childView: views.Folder,

	childViewContainer: '#mail_folders',

	initialize: function(options) {
		this.model = options.model;
		this.collection = new models.FolderList(this.model.get('folders'));
	}

});

views.Folders = Backbone.Marionette.CollectionView.extend({

	// The collection will be kept here
	collection: null,

	childView: views.Account,

	initialize: function() {
		this.collection = new models.AccountList();
	}

});
<commit_msg>Revert "Remove wrapping div from backbone view for folders list"<commit_after>/* global Backbone, Mail, models */

var views = views || {};

views.Folder = Backbone.Marionette.ItemView.extend({

	template: "#mail-folder-template",

	events: {
		"click .collapse" : "collapseFolder",
		"click li a" : "loadMessages"
	},

	initialize: function(options) {
		this.model = options.model;
	},

	collapseFolder: function(e) {
		e.preventDefault();
		this.model.toggleOpen();
	},

	loadMessages: function(e) {
		e.preventDefault();
		var accountId = this.model.get('accountId');
		var folderId = $(e.currentTarget).parent().data('folder_id');
		var noSelect = $(e.currentTarget).parent().data('no_select');
		Mail.UI.loadMessages(accountId, folderId, noSelect);
	}
});

views.Account = Backbone.Marionette.CompositeView.extend({

	collection: null,
	model: null,

	template: "#mail-account-template",

	childView: views.Folder,

	childViewContainer: '#mail_folders',

	initialize: function(options) {
		this.model = options.model;
		this.collection = new models.FolderList(this.model.get('folders'));
	}

});

views.Folders = Backbone.Marionette.CollectionView.extend({

	// The collection will be kept here
	collection: null,

	childView: views.Account,

	initialize: function() {
		this.collection = new models.AccountList();
	}

});
<|endoftext|>


<commit_before>var DeveloperPlayground = DeveloperPlayground || {};

DeveloperPlayground.RegionView = Backbone.View.extend({
	tagName: 'option',
	template: _.template( $('#region-template').html() ),

	render: function() {
		this.$el.get('metro');
		renderedHtml = this.template(this.model.toJSON());
		this.$el.html(renderedHtml);
		console.log(this.model.get('country') + ", " + this.model.get('state') + ", " + this.model.get('metro'));
		this.$el.val(this.model.get('metro'));
		this.$el.text(this.model.get('country') + ", " + this.model.get('state') + ", " + this.model.get('metro'));
		return this;
	},

 });<commit_msg>remove console.log<commit_after>var DeveloperPlayground = DeveloperPlayground || {};

DeveloperPlayground.RegionView = Backbone.View.extend({
	tagName: 'option',
	template: _.template( $('#region-template').html() ),

	render: function() {
		this.$el.get('metro');
		renderedHtml = this.template(this.model.toJSON());
		this.$el.html(renderedHtml);
		this.$el.val(this.model.get('metro'));
		this.$el.text(this.model.get('country') + ", " + this.model.get('state') + ", " + this.model.get('metro'));
		return this;
	},

 });<|endoftext|>


<commit_before>const greet = require ('../index.js')
const assert = require('assert');

describe('greet', function() {
  describe('when given the name "Brodan"', function() {
    it('should return "Hello, Brodan!"', function() {
      assert.equal("Hello, Brodan!", greet.greet("Brodan"));
    });
  });

  describe('when given no name', function() {
    it('should return "Hello, World!"', function() {
      assert.equal("Hello, World!", greet.greet());
    });
  });

  describe('when designed to fail', function() {
    it('should should fail', function() {
      assert.equal("This test should fail.", greet.greet());
    });
  });
});
<commit_msg>make failing test more obvious<commit_after>const greet = require ('../index.js')
const assert = require('assert');

describe('greet', function() {
  describe('when given the name "Brodan"', function() {
    it('should return "Hello, Brodan!"', function() {
      assert.equal("Hello, Brodan!", greet.greet("Brodan"));
    });
  });

  describe('when given no name', function() {
    it('should return "Hello, World!"', function() {
      assert.equal("Hello, World!", greet.greet());
    });
  });

  describe('when designed to fail', function() {
    it('should fail', function() {
      assert.fail(null, null, 'this should fail');
    });
  });
});
<|endoftext|>


<commit_before>
function cless(commFactory, innerCss, className) {
    var stylesheet = document.createElement("style");
    stylesheet.type = "text/css";
    stylesheet.savedText = innerCss;
    innerCss = color.transform(innerCss);
    if (stylesheet.styleSheet) {
        stylesheet.styleSheet.cssText = innerCss;
    } else {
        stylesheet.innerHTML = innerCss;
    }
    appendChild(document.getElementsByTagName("head")[0], stylesheet);
    if (commFactory instanceof Promise) {
        return commFactory.then(function (result) {
            return cless(result, innerCss, className);
        });
    }
    if (isFunction(commFactory)) {
        var result = function () {
            var commRelease = commFactory.apply(result, arguments);
            if (commRelease) {
                commRelease = cless(commRelease, innerCss, className);
            }
            return commRelease;
        };
        result.prototype = commFactory.prototype;
        keys(commFactory).map(k => result[k] = commFactory[k]);
        return result;
    }
    if (isNode(commFactory)) {
        try {
            addClass(commFactory, className);
        } catch (e) {
            console.error(e, "bindClassNameError");
        }
    } else if (isString(commFactory)) {
        var template = document.createElement("div");
        template.innerHTML = commFactory;
        [].forEach.call(template.children, function (child) {
            addClass(child, className);
        });
        commFactory = template.innerHTML;
    }
    return commFactory;
}
<commit_msg>解决样式可能重复加载的问题<commit_after>
function create(commFactory, className) {
    if (commFactory instanceof Promise) {
        return commFactory.then(function (result) {
            return create(result, className);
        });
    }
    if (isFunction(commFactory)) {
        var result = function () {
            var commRelease = commFactory.apply(result, arguments);
            if (commRelease) {
                commRelease = create(commRelease, className);
            }
            return commRelease;
        };
        result.prototype = commFactory.prototype;
        keys(commFactory).map(k => result[k] = commFactory[k]);
        return result;
    }
    if (isNode(commFactory)) {
        try {
            addClass(commFactory, className);
        } catch (e) {
            console.error(e, "bindClassNameError");
        }
    } else if (isString(commFactory)) {
        var template = document.createElement("div");
        template.innerHTML = commFactory;
        [].forEach.call(template.children, function (child) {
            addClass(child, className);
        });
        commFactory = template.innerHTML;
    }
    return commFactory;
}
function cless(commFactory, innerCss, className) {
    var stylesheet = document.createElement("style");
    stylesheet.type = "text/css";
    stylesheet.savedText = innerCss;
    innerCss = color.transform(innerCss);
    if (stylesheet.styleSheet) {
        stylesheet.styleSheet.cssText = innerCss;
    } else {
        stylesheet.innerHTML = innerCss;
    }
    appendChild(document.getElementsByTagName("head")[0], stylesheet);
    return create(commFactory, className);
}
<|endoftext|>