<commit_before>import {
	isArray,
	isStringOrNumber,
	isFunction,
	isNullOrUndef,
	isStatefulComponent,
	isString,
	isInvalid,
	isNull,
	throwError
} from './../core/utils';
import {
	setTextContent,
	documentCreateElement,
	selectValue,
	normaliseChild,
	appendChild,
	normalise
} from './utils';
import { patchStyle, patch, patchProp } from './patching';
import { componentToDOMNodeMap } from './rendering';
import {
	createVPlaceholder,
	isVText,
	isVPlaceholder,
	isVFragment,
	isVElement,
	isVComponent,
	isVTemplate,
	isVariable,
	isVNode
} from '../core/shapes';
import {
	isKeyedListChildrenType,
	isTextChildrenType,
	isNodeChildrenType,
	isNonKeyedListChildrenType,
	isUnknownChildrenType
} from '../core/ChildrenTypes';
import { recycleVTemplate, recyclingEnabled } from './templates';

export function mount(input, parentDom, lifecycle, context, isSVG) {
	if (isVTemplate(input)) {
		return mountVTemplate(input, parentDom, lifecycle, context, isSVG);
	} else if (isVPlaceholder(input)) {
		return mountVPlaceholder(input, parentDom);
	} else if (isVText(input)) {
		return mountVText(input, parentDom);
	} else if (isVFragment(input)) {
		return mountVFragment(input, parentDom, lifecycle, context, isSVG);
	} else if (isVElement(input)) {
		return mountVElement(input, parentDom, lifecycle, context, isSVG);
	} else if (isVComponent(input)) {
		return mountVComponent(input, parentDom, lifecycle, context, isSVG);
	} else {
		if (process.env.NODE_ENV !== 'production') {
			throwError('bad input argument called on mount(). Input argument may need normalising.');
		}
		throwError();
	}
}

export function mountVTemplate(vTemplate, parentDom, lifecycle, context, isSVG) {
	const templateReducers = vTemplate._tr;
	let dom = null;

	if (recyclingEnabled) {
		dom = recycleVTemplate(vTemplate, lifecycle, context, isSVG);
	}
	if (isNull(dom)) {
		dom = templateReducers.mount(vTemplate, null, lifecycle, context, isSVG);
	}
	vTemplate._dom = dom;
	if (!isNull(parentDom)) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function mountVElement(vElement, parentDom, lifecycle, context, isSVG) {
	const tag = vElement._tag;

	if (!isString(tag)) {
		if (process.env.NODE_ENV !== 'production') {
			throwError('expects VElement to have a string as the tag name');
		}
		throwError();
	}
	if (tag === 'svg') {
		isSVG = true;
	}
	const dom = documentCreateElement(tag, isSVG);
	const children = vElement._children;
	const props = vElement._props;
	const ref = vElement._ref;

	vElement._dom = dom;
	if (!isNullOrUndef(ref)) {
		lifecycle.addListener(() => {
			ref(dom);
		});
	}
	if (!isNullOrUndef(children)) {
		mountChildren(vElement._childrenType, children, dom, lifecycle, context, isSVG);
	}
	if (!isNullOrUndef(props)) {
		handleSelects(vElement);
		mountProps(vElement, props, dom);
	}
	if (!isNull(parentDom)) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function mountVFragment(vFragment, parentDom, lifecycle, context, isSVG) {
	const children = vFragment._children;
	const pointer = document.createTextNode('');
	const dom = document.createDocumentFragment();
	const childrenType = vFragment._childrenType;

	if (isKeyedListChildrenType(childrenType) || isNonKeyedListChildrenType(childrenType)) {
		mountArrayChildrenWithType(children, dom, lifecycle, context, isSVG);
	} else if (isUnknownChildrenType(childrenType)) {
		mountArrayChildrenWithoutType(children, dom, lifecycle, context, isSVG);
	}
	vFragment._pointer = pointer;
	vFragment._dom = dom;
	appendChild(dom, pointer);
	if (parentDom) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function mountVText(vText, parentDom) {
	const dom = document.createTextNode(vText._text);

	vText._dom = dom;
	if (parentDom) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function mountVPlaceholder(vPlaceholder, parentDom) {
	const dom = document.createTextNode('');

	vPlaceholder._dom = dom;
	if (parentDom) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function handleSelects(node) {
	if (node.tag === 'select') {
		selectValue(node);
	}
}

export function mountArrayChildrenWithoutType(children, dom, lifecycle, context, isSVG) {
	children.complex = false;
	for (let i = 0; i < children.length; i++) {
		const child = normaliseChild(children, i);

		if (isVText(child)) {
			mountVText(child, dom);
			children.complex = true;
		} else if (isVPlaceholder(child)) {
			mountVPlaceholder(child, dom);
			children.complex = true;
		} else if (isVFragment(child)) {
			mountVFragment(child, dom, lifecycle, context, isSVG);
			children.complex = true;
		} else {
			mount(child, dom, lifecycle, context, isSVG);
		}
	}
}

export function mountChildrenWithUnknownType(children, dom, lifecycle, context, isSVG) {
	if (isArray(children)) {
		mountArrayChildrenWithoutType(children, dom, lifecycle, context, isSVG);
	} else if (isStringOrNumber(children)) {
		setTextContent(dom, children);
	} else if (!isInvalid(children)) {
		mount(children, dom, lifecycle, context, isSVG);
	}
}

export function mountArrayChildrenWithType(children, dom, lifecycle, context, isSVG) {
	for (let i = 0; i < children.length; i++) {
		mount(children[i], dom, lifecycle, context, isSVG);
	}
}

function mountChildren(childrenType, children, dom, lifecycle, context, isSVG) {
	if (isTextChildrenType(childrenType)) {
		setTextContent(dom, children);
	} else if (isNodeChildrenType(childrenType)) {
		mount(children, dom, lifecycle, context, isSVG);
	} else if (isKeyedListChildrenType(childrenType) || isNonKeyedListChildrenType(childrenType)) {
		mountArrayChildrenWithType(children, dom, lifecycle, context, isSVG);
	} else if (isUnknownChildrenType(childrenType)) {
		mountChildrenWithUnknownType(children, dom, lifecycle, context, isSVG);
	} else {
		if (process.env.NODE_ENV !== 'production') {
			throwError('bad childrenType value specified when attempting to mountChildren.');
		}
		throwError();
	}
}

export function mountVComponent(vComponent, parentDom, lifecycle, context, isSVG) {
	const Component = vComponent._component;
	const props = vComponent._props;
	const hooks = vComponent._hooks;
	const ref = vComponent._ref;
	let dom;

	if (isStatefulComponent(vComponent)) {
		if (hooks) {
			if (process.env.NODE_ENV !== 'production') {
				throwError('"hooks" are not supported on stateful components.');
			}
			throwError();
		}
		const instance = new Component(props, context);

		instance._patch = patch;
		instance._componentToDOMNodeMap = componentToDOMNodeMap;
		const childContext = instance.getChildContext();

		if (!isNullOrUndef(childContext)) {
			context = Object.assign({}, context, childContext);
		}
		instance._unmounted = false;
		instance._pendingSetState = true;
		instance._vComponent = vComponent;
		instance.componentWillMount();
		let input = instance.render();

		if (isInvalid(input)) {
			input = createVPlaceholder();
		}
		instance._pendingSetState = false;
		dom = mount(input, null, lifecycle, context, false);
		instance._lastInput = input;
		if (parentDom !== null && !isInvalid(dom)) {
			appendChild(parentDom, dom);
		}
		if (ref) {
			if (isFunction(ref)) {
				lifecycle.addListener(() => ref(instance));
			} else {
				if (process.env.NODE_ENV !== 'production') {
					throwError('string "refs" are not supported in Inferno 0.8+. Use callback "refs" instead.');
				}
				throwError();
			}
		}
		if (!isNull(instance.componentDidMount)) {
			lifecycle.addListener(() => {
				instance.componentDidMount();
			});
		}
		componentToDOMNodeMap.set(instance, dom);
		vComponent._dom = dom;
		vComponent._instance = instance;
	} else {
		if (ref) {
			if (process.env.NODE_ENV !== 'production') {
				throwError('"refs" are not supported on stateless components.');
			}
			throwError();
		}
		if (!isNullOrUndef(hooks)) {
			if (!isNullOrUndef(hooks.onComponentWillMount)) {
				hooks.onComponentWillMount(null, props);
			}
			if (!isNullOrUndef(hooks.onComponentDidMount)) {
				lifecycle.addListener(() => hooks.onComponentDidMount(dom, props));
			}
		}

		/* eslint new-cap: 0 */
		let input = Component(props, context);

		if (isInvalid(input)) {
			input = createVPlaceholder();
		}
		dom = mount(input, null, lifecycle, context, null, false);
		vComponent._instance = input;
		if (parentDom !== null && !isInvalid(dom)) {
			appendChild(parentDom, dom);
		}
		vComponent._dom = dom;
	}
	return dom;
}

function mountProps(vElement, props, dom) {
	for (let prop in props) {
		const value = props[prop];

		patchProp(prop, null, value, dom);
	}
}

export function mountVariableAsExpression(pointer, templateIsSVG) {
	return function mountVariableAsExpression(vTemplate, dom, lifecycle, context, isSVG) {
		let input = vTemplate.read(pointer);

		if (isNullOrUndef(input) || !isVNode(input)) {
			input = normalise(input);
			vTemplate.write(pointer, input);
		}
		return mount(input, dom, lifecycle, context, isSVG || templateIsSVG);
	};
}

export function mountVariableAsChildren(pointer, templateIsSVG, childrenType) {
	return function mountVariableAsChildren(vTemplate, dom, lifecycle, context, isSVG) {
		return mountChildren(childrenType, vTemplate.read(pointer), dom, lifecycle, context, isSVG || templateIsSVG);
	};
}

export function mountVariableAsText(pointer) {
	return function mountVariableAsText(vTemplate, textNode) {
		textNode.nodeValue = vTemplate.read(pointer);
	};
}

export function mountDOMNodeFromTemplate(templateDomNode, deepClone) {
	return function mountDOMNodeFromTemplate(vTemplate, dom) {
		const domNode = templateDomNode.cloneNode(deepClone);

		if (!isNull(dom)) {
			appendChild(dom, domNode);
		}
		return domNode;
	};
}

export function mountRefFromTemplate(ref) {
	return function mountRefFromTemplate(vTemplate, dom, lifecycle) {
		let value = ref;

		if (isVariable(ref)) {
			value = vTemplate.read(ref._pointer);
		}
		if (isFunction(value)) {
			lifecycle.addListener(() => value(dom));
		} else {
			if (process.env.NODE_ENV !== 'production') {
				throwError('string "refs" are not supported in Inferno 0.8+. Use callback "refs" instead.');
			}
			throwError();
		}
	};
}

export function mountSpreadPropsFromTemplate(pointer) {
	return function mountSpreadPropsFromTemplate(vTemplate, dom) {
		const props = vTemplate.read(pointer);

		for (let prop in props) {
			const value = props[prop];

			if (prop === 'key') {
				// debugger;
			} else if (prop === 'ref') {
				// debugger;
			} else {
				patchProp(prop, null, value, dom);
			}
		}
	};
}

export function mountEmptyTextNode(vTemplate, parentDom) {
	const dom = document.createTextNode('');

	if (!isNull(parentDom)) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function mountTemplateClassName(pointer) {
	return function mountTemplateClassName(vTemplate, dom) {
		const className = vTemplate.read(pointer);

		if (!isNullOrUndef(className)) {
			dom.className = className;
		}
	};
}

export function mountTemplateStyle(pointer) {
	return function mountTemplateStyle(vTemplate, dom) {
		patchStyle(null, vTemplate.read(pointer), dom);
	};
}

export function mountTemplateProps(propsToMount) {
	return function mountTemplateProps(vTemplate, dom) {
		for (let i = 0; i < propsToMount.length; i += 2) {
			const prop = propsToMount[i];
			let value = propsToMount[i + 1];

			if (isVariable(value)) {
				value = vTemplate.read(value._pointer);
			}
			patchProp(prop, null, value, dom);
		}
	};
}
<commit_msg>fix typo<commit_after>import {
	isArray,
	isStringOrNumber,
	isFunction,
	isNullOrUndef,
	isStatefulComponent,
	isString,
	isInvalid,
	isNull,
	throwError
} from './../core/utils';
import {
	setTextContent,
	documentCreateElement,
	selectValue,
	normaliseChild,
	appendChild,
	normalise
} from './utils';
import { patchStyle, patch, patchProp } from './patching';
import { componentToDOMNodeMap } from './rendering';
import {
	createVPlaceholder,
	isVText,
	isVPlaceholder,
	isVFragment,
	isVElement,
	isVComponent,
	isVTemplate,
	isVariable,
	isVNode
} from '../core/shapes';
import {
	isKeyedListChildrenType,
	isTextChildrenType,
	isNodeChildrenType,
	isNonKeyedListChildrenType,
	isUnknownChildrenType
} from '../core/ChildrenTypes';
import { recycleVTemplate, recyclingEnabled } from './templates';

export function mount(input, parentDom, lifecycle, context, isSVG) {
	if (isVTemplate(input)) {
		return mountVTemplate(input, parentDom, lifecycle, context, isSVG);
	} else if (isVPlaceholder(input)) {
		return mountVPlaceholder(input, parentDom);
	} else if (isVText(input)) {
		return mountVText(input, parentDom);
	} else if (isVFragment(input)) {
		return mountVFragment(input, parentDom, lifecycle, context, isSVG);
	} else if (isVElement(input)) {
		return mountVElement(input, parentDom, lifecycle, context, isSVG);
	} else if (isVComponent(input)) {
		return mountVComponent(input, parentDom, lifecycle, context, isSVG);
	} else {
		if (process.env.NODE_ENV !== 'production') {
			throwError('bad input argument called on mount(). Input argument may need normalising.');
		}
		throwError();
	}
}

export function mountVTemplate(vTemplate, parentDom, lifecycle, context, isSVG) {
	const templateReducers = vTemplate._tr;
	let dom = null;

	if (recyclingEnabled) {
		dom = recycleVTemplate(vTemplate, lifecycle, context, isSVG);
	}
	if (isNull(dom)) {
		dom = templateReducers.mount(vTemplate, null, lifecycle, context, isSVG);
	}
	vTemplate._dom = dom;
	if (!isNull(parentDom)) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function mountVElement(vElement, parentDom, lifecycle, context, isSVG) {
	const tag = vElement._tag;

	if (!isString(tag)) {
		if (process.env.NODE_ENV !== 'production') {
			throwError('expects VElement to have a string as the tag name');
		}
		throwError();
	}
	if (tag === 'svg') {
		isSVG = true;
	}
	const dom = documentCreateElement(tag, isSVG);
	const children = vElement._children;
	const props = vElement._props;
	const ref = vElement._ref;

	vElement._dom = dom;
	if (!isNullOrUndef(ref)) {
		lifecycle.addListener(() => {
			ref(dom);
		});
	}
	if (!isNullOrUndef(children)) {
		mountChildren(vElement._childrenType, children, dom, lifecycle, context, isSVG);
	}
	if (!isNullOrUndef(props)) {
		handleSelects(vElement);
		mountProps(vElement, props, dom);
	}
	if (!isNull(parentDom)) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function mountVFragment(vFragment, parentDom, lifecycle, context, isSVG) {
	const children = vFragment._children;
	const pointer = document.createTextNode('');
	const dom = document.createDocumentFragment();
	const childrenType = vFragment._childrenType;

	if (isKeyedListChildrenType(childrenType) || isNonKeyedListChildrenType(childrenType)) {
		mountArrayChildrenWithType(children, dom, lifecycle, context, isSVG);
	} else if (isUnknownChildrenType(childrenType)) {
		mountArrayChildrenWithoutType(children, dom, lifecycle, context, isSVG);
	}
	vFragment._pointer = pointer;
	vFragment._dom = dom;
	appendChild(dom, pointer);
	if (parentDom) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function mountVText(vText, parentDom) {
	const dom = document.createTextNode(vText._text);

	vText._dom = dom;
	if (parentDom) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function mountVPlaceholder(vPlaceholder, parentDom) {
	const dom = document.createTextNode('');

	vPlaceholder._dom = dom;
	if (parentDom) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function handleSelects(node) {
	if (node._tag === 'select') {
		selectValue(node);
	}
}

export function mountArrayChildrenWithoutType(children, dom, lifecycle, context, isSVG) {
	children.complex = false;
	for (let i = 0; i < children.length; i++) {
		const child = normaliseChild(children, i);

		if (isVText(child)) {
			mountVText(child, dom);
			children.complex = true;
		} else if (isVPlaceholder(child)) {
			mountVPlaceholder(child, dom);
			children.complex = true;
		} else if (isVFragment(child)) {
			mountVFragment(child, dom, lifecycle, context, isSVG);
			children.complex = true;
		} else {
			mount(child, dom, lifecycle, context, isSVG);
		}
	}
}

export function mountChildrenWithUnknownType(children, dom, lifecycle, context, isSVG) {
	if (isArray(children)) {
		mountArrayChildrenWithoutType(children, dom, lifecycle, context, isSVG);
	} else if (isStringOrNumber(children)) {
		setTextContent(dom, children);
	} else if (!isInvalid(children)) {
		mount(children, dom, lifecycle, context, isSVG);
	}
}

export function mountArrayChildrenWithType(children, dom, lifecycle, context, isSVG) {
	for (let i = 0; i < children.length; i++) {
		mount(children[i], dom, lifecycle, context, isSVG);
	}
}

function mountChildren(childrenType, children, dom, lifecycle, context, isSVG) {
	if (isTextChildrenType(childrenType)) {
		setTextContent(dom, children);
	} else if (isNodeChildrenType(childrenType)) {
		mount(children, dom, lifecycle, context, isSVG);
	} else if (isKeyedListChildrenType(childrenType) || isNonKeyedListChildrenType(childrenType)) {
		mountArrayChildrenWithType(children, dom, lifecycle, context, isSVG);
	} else if (isUnknownChildrenType(childrenType)) {
		mountChildrenWithUnknownType(children, dom, lifecycle, context, isSVG);
	} else {
		if (process.env.NODE_ENV !== 'production') {
			throwError('bad childrenType value specified when attempting to mountChildren.');
		}
		throwError();
	}
}

export function mountVComponent(vComponent, parentDom, lifecycle, context, isSVG) {
	const Component = vComponent._component;
	const props = vComponent._props;
	const hooks = vComponent._hooks;
	const ref = vComponent._ref;
	let dom;

	if (isStatefulComponent(vComponent)) {
		if (hooks) {
			if (process.env.NODE_ENV !== 'production') {
				throwError('"hooks" are not supported on stateful components.');
			}
			throwError();
		}
		const instance = new Component(props, context);

		instance._patch = patch;
		instance._componentToDOMNodeMap = componentToDOMNodeMap;
		const childContext = instance.getChildContext();

		if (!isNullOrUndef(childContext)) {
			context = Object.assign({}, context, childContext);
		}
		instance._unmounted = false;
		instance._pendingSetState = true;
		instance._vComponent = vComponent;
		instance.componentWillMount();
		let input = instance.render();

		if (isInvalid(input)) {
			input = createVPlaceholder();
		}
		instance._pendingSetState = false;
		dom = mount(input, null, lifecycle, context, false);
		instance._lastInput = input;
		if (parentDom !== null && !isInvalid(dom)) {
			appendChild(parentDom, dom);
		}
		if (ref) {
			if (isFunction(ref)) {
				lifecycle.addListener(() => ref(instance));
			} else {
				if (process.env.NODE_ENV !== 'production') {
					throwError('string "refs" are not supported in Inferno 0.8+. Use callback "refs" instead.');
				}
				throwError();
			}
		}
		if (!isNull(instance.componentDidMount)) {
			lifecycle.addListener(() => {
				instance.componentDidMount();
			});
		}
		componentToDOMNodeMap.set(instance, dom);
		vComponent._dom = dom;
		vComponent._instance = instance;
	} else {
		if (ref) {
			if (process.env.NODE_ENV !== 'production') {
				throwError('"refs" are not supported on stateless components.');
			}
			throwError();
		}
		if (!isNullOrUndef(hooks)) {
			if (!isNullOrUndef(hooks.onComponentWillMount)) {
				hooks.onComponentWillMount(null, props);
			}
			if (!isNullOrUndef(hooks.onComponentDidMount)) {
				lifecycle.addListener(() => hooks.onComponentDidMount(dom, props));
			}
		}

		/* eslint new-cap: 0 */
		let input = Component(props, context);

		if (isInvalid(input)) {
			input = createVPlaceholder();
		}
		dom = mount(input, null, lifecycle, context, null, false);
		vComponent._instance = input;
		if (parentDom !== null && !isInvalid(dom)) {
			appendChild(parentDom, dom);
		}
		vComponent._dom = dom;
	}
	return dom;
}

function mountProps(vElement, props, dom) {
	for (let prop in props) {
		const value = props[prop];

		patchProp(prop, null, value, dom);
	}
}

export function mountVariableAsExpression(pointer, templateIsSVG) {
	return function mountVariableAsExpression(vTemplate, dom, lifecycle, context, isSVG) {
		let input = vTemplate.read(pointer);

		if (isNullOrUndef(input) || !isVNode(input)) {
			input = normalise(input);
			vTemplate.write(pointer, input);
		}
		return mount(input, dom, lifecycle, context, isSVG || templateIsSVG);
	};
}

export function mountVariableAsChildren(pointer, templateIsSVG, childrenType) {
	return function mountVariableAsChildren(vTemplate, dom, lifecycle, context, isSVG) {
		return mountChildren(childrenType, vTemplate.read(pointer), dom, lifecycle, context, isSVG || templateIsSVG);
	};
}

export function mountVariableAsText(pointer) {
	return function mountVariableAsText(vTemplate, textNode) {
		textNode.nodeValue = vTemplate.read(pointer);
	};
}

export function mountDOMNodeFromTemplate(templateDomNode, deepClone) {
	return function mountDOMNodeFromTemplate(vTemplate, dom) {
		const domNode = templateDomNode.cloneNode(deepClone);

		if (!isNull(dom)) {
			appendChild(dom, domNode);
		}
		return domNode;
	};
}

export function mountRefFromTemplate(ref) {
	return function mountRefFromTemplate(vTemplate, dom, lifecycle) {
		let value = ref;

		if (isVariable(ref)) {
			value = vTemplate.read(ref._pointer);
		}
		if (isFunction(value)) {
			lifecycle.addListener(() => value(dom));
		} else {
			if (process.env.NODE_ENV !== 'production') {
				throwError('string "refs" are not supported in Inferno 0.8+. Use callback "refs" instead.');
			}
			throwError();
		}
	};
}

export function mountSpreadPropsFromTemplate(pointer) {
	return function mountSpreadPropsFromTemplate(vTemplate, dom) {
		const props = vTemplate.read(pointer);

		for (let prop in props) {
			const value = props[prop];

			if (prop === 'key') {
				// debugger;
			} else if (prop === 'ref') {
				// debugger;
			} else {
				patchProp(prop, null, value, dom);
			}
		}
	};
}

export function mountEmptyTextNode(vTemplate, parentDom) {
	const dom = document.createTextNode('');

	if (!isNull(parentDom)) {
		appendChild(parentDom, dom);
	}
	return dom;
}

export function mountTemplateClassName(pointer) {
	return function mountTemplateClassName(vTemplate, dom) {
		const className = vTemplate.read(pointer);

		if (!isNullOrUndef(className)) {
			dom.className = className;
		}
	};
}

export function mountTemplateStyle(pointer) {
	return function mountTemplateStyle(vTemplate, dom) {
		patchStyle(null, vTemplate.read(pointer), dom);
	};
}

export function mountTemplateProps(propsToMount) {
	return function mountTemplateProps(vTemplate, dom) {
		for (let i = 0; i < propsToMount.length; i += 2) {
			const prop = propsToMount[i];
			let value = propsToMount[i + 1];

			if (isVariable(value)) {
				value = vTemplate.read(value._pointer);
			}
			patchProp(prop, null, value, dom);
		}
	};
}
<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

var H = require('../index').EventEmitter;
var _ = require('underscore');
var assert = require('assert');

describe('HevEmitter once', function () {

    it('should emit and recieve one level events', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['storage'], function () {
            emitted += 1;
        });
        h.emit(['storage']);
        h.emit(['storage'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should not be able to trigger twice', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['storage'], function () {
            emitted += 1;
            h.emit(['storage']);
        });
        h.emit(['storage']);
        h.emit(['storage'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should emit and recieve two level events', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['request', 'date'], function () {
            emitted += 1;
        });
        h.emit(['request', 'date']);
        h.emit(['request', 'date'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should NOT recieve the wrong event', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['prismo'], function () {
            emitted += 1;
        });
        h.emit(['wish']);
        h.emit(['wish'])
            .then(function () {
                assert.equal(0, emitted);
                done();
            });

    });

    it('should NOT receive the wrong two level event', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['ritz', 'cracker'], function () {
            emitted += 1;
        });
        h.emit(['cheese', 'cracker']);
        h.emit(['cheese', 'cracker'])
            .then(function () {
                assert.equal(0, emitted);
                done();
            });
    });

    it('should trigger listeners on one star events', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['bones', '*'], function () {
            emitted += 1;
        });
        h.emit(['bones', 'elephant']);
        h.emit(['bones', 'elephant'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should trigger listeners on one star events in the first place', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['*', 'bill'], function () {
            emitted += 1;
        });
        h.emit(['thankyou', 'bill']);
        h.emit(['thankyou', 'bill'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should trigger one star events in the first place', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['baby', 'booster'], function () {
            emitted += 1;
        });
        h.emit(['*', 'booster']);
        h.emit(['*', 'booster'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should NOT trigger one star events only in the first place', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['baby', 'booster'], function () {
            emitted += 1;
        });
        h.emit(['*']);
        h.emit(['*'])
            .then(function () {
                assert.equal(0, emitted);
                done();
            });
    });

    it('should NOT trigger one star events only in the first place', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['*'], function () {
            emitted += 1;
        });
        h.emit(['green', 'buns']);
        h.emit(['green', 'buns'])
            .then(function () {
                assert.equal(0, emitted);
                done();
            });
    });

    it('should trigger two star events in the first place with one level', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['**'], function () {
            emitted += 1;
        });
        h.emit(['giant']);
        h.emit(['giant'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should trigger two star emitted events in the first place with one level', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['sun'], function () {
            emitted += 1;
        });
        h.emit(['**']);
        h.emit(['**'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should trigger two star events in the first place with two levels', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['**'], function () {
            emitted += 1;
        });
        h.emit(['oglethorpe', 'piggy']);
        h.emit(['oglethorpe', 'piggy'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should trigger second level two star emitted events in the first place with two levels', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['emry', 'please'], function () {
            emitted += 1;
        });
        h.emit(['emry', '**']);
        h.emit(['emry', '**'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should trigger second level two star events in the first place with one level', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['**'], function () {
            emitted += 1;
        });
        h.emit(['vanted', 'vatch']);
        h.emit(['vanted', 'vatch'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should trigger second level two star emitted events in the first place with one level', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['trail'], function () {
            emitted += 1;
        });
        h.emit(['trail', '**']);
        h.emit(['trail', '**'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should trigger second level two star events in the first place with two levels', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['rrr', '**'], function () {
            emitted += 1;
        });
        h.emit(['rrr', 'mooninite']);
        h.emit(['rrr', 'mooninite'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });

    it('should trigger second level two star emitted events in the first place with two levels', function (done) {
        var h = new H();
        var emitted = 0;
        h.once(['hypersleep', 'dreams'], function () {
            emitted += 1;
        });
        h.emit(['hypersleep', '**']);
        h.emit(['hypersleep', '**'])
            .then(function () {
                assert.equal(1, emitted);
                done();
            });
    });
});
<commit_msg>Add once promise tests.<commit_after>/*jslint node: true */
"use strict";

var H = require('../index').EventEmitter;
var _ = require('underscore');
var assert = require('assert');

describe('HevEmitter once', function () {

    describe(' synchronous ', function () {

        it('should emit and recieve one level events', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['storage'], function () {
                emitted += 1;
            });
            h.emit(['storage']);
            h.emit(['storage'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should not be able to trigger twice', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['storage'], function () {
                emitted += 1;
                h.emit(['storage']);
            });
            h.emit(['storage']);
            h.emit(['storage'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should emit and recieve two level events', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['request', 'date'], function () {
                emitted += 1;
            });
            h.emit(['request', 'date']);
            h.emit(['request', 'date'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should NOT recieve the wrong event', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['prismo'], function () {
                emitted += 1;
            });
            h.emit(['wish']);
            h.emit(['wish'])
                .then(function () {
                    assert.equal(0, emitted);
                    done();
                });

        });

        it('should NOT receive the wrong two level event', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['ritz', 'cracker'], function () {
                emitted += 1;
            });
            h.emit(['cheese', 'cracker']);
            h.emit(['cheese', 'cracker'])
                .then(function () {
                    assert.equal(0, emitted);
                    done();
                });
        });

        it('should trigger listeners on one star events', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['bones', '*'], function () {
                emitted += 1;
            });
            h.emit(['bones', 'elephant']);
            h.emit(['bones', 'elephant'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger listeners on one star events in the first place', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['*', 'bill'], function () {
                emitted += 1;
            });
            h.emit(['thankyou', 'bill']);
            h.emit(['thankyou', 'bill'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger one star events in the first place', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['baby', 'booster'], function () {
                emitted += 1;
            });
            h.emit(['*', 'booster']);
            h.emit(['*', 'booster'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should NOT trigger one star events only in the first place', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['baby', 'booster'], function () {
                emitted += 1;
            });
            h.emit(['*']);
            h.emit(['*'])
                .then(function () {
                    assert.equal(0, emitted);
                    done();
                });
        });

        it('should NOT trigger one star events only in the first place', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['*'], function () {
                emitted += 1;
            });
            h.emit(['green', 'buns']);
            h.emit(['green', 'buns'])
                .then(function () {
                    assert.equal(0, emitted);
                    done();
                });
        });

        it('should trigger two star events in the first place with one level', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['**'], function () {
                emitted += 1;
            });
            h.emit(['giant']);
            h.emit(['giant'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger two star emitted events in the first place with one level', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['sun'], function () {
                emitted += 1;
            });
            h.emit(['**']);
            h.emit(['**'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger two star events in the first place with two levels', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['**'], function () {
                emitted += 1;
            });
            h.emit(['oglethorpe', 'piggy']);
            h.emit(['oglethorpe', 'piggy'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger second level two star emitted events in the first place with two levels', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['emry', 'please'], function () {
                emitted += 1;
            });
            h.emit(['emry', '**']);
            h.emit(['emry', '**'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger second level two star events in the first place with one level', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['**'], function () {
                emitted += 1;
            });
            h.emit(['vanted', 'vatch']);
            h.emit(['vanted', 'vatch'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger second level two star emitted events in the first place with one level', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['trail'], function () {
                emitted += 1;
            });
            h.emit(['trail', '**']);
            h.emit(['trail', '**'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger second level two star events in the first place with two levels', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['rrr', '**'], function () {
                emitted += 1;
            });
            h.emit(['rrr', 'mooninite']);
            h.emit(['rrr', 'mooninite'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger second level two star emitted events in the first place with two levels', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['hypersleep', 'dreams'], function () {
                emitted += 1;
            });
            h.emit(['hypersleep', '**']);
            h.emit(['hypersleep', '**'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });

        });

    });
    describe(' promise ', function () {

        it('should emit and recieve one level events', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['storage'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['storage']).catch(done);
            h.emit(['storage'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should not be able to trigger twice', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['storage'], function (msg, cb) {
                emitted += 1;
                h.emit(['storage']);
                cb();
            });
            h.emit(['storage']).catch(done);
            h.emit(['storage'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should emit and recieve two level events', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['request', 'date'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['request', 'date']).catch(done);
            h.emit(['request', 'date'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should NOT recieve the wrong event', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['prismo'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['wish']).catch(done);
            h.emit(['wish'])
                .then(function () {
                    assert.equal(0, emitted);
                    done();
                });

        });

        it('should NOT receive the wrong two level event', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['ritz', 'cracker'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['cheese', 'cracker']).catch(done);
            h.emit(['cheese', 'cracker'])
                .then(function () {
                    assert.equal(0, emitted);
                    done();
                });
        });

        it('should trigger listeners on one star events', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['bones', '*'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['bones', 'elephant']).catch(done);
            h.emit(['bones', 'elephant'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger listeners on one star events in the first place', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['*', 'bill'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['thankyou', 'bill']).catch(done);
            h.emit(['thankyou', 'bill'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger one star events in the first place', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['baby', 'booster'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['*', 'booster']).catch(done);
            h.emit(['*', 'booster'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should NOT trigger one star events only in the first place', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['baby', 'booster'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['*']).catch(done);
            h.emit(['*'])
                .then(function () {
                    assert.equal(0, emitted);
                    done();
                });
        });

        it('should NOT trigger one star events only in the first place', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['*'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['green', 'buns']).catch(done);
            h.emit(['green', 'buns'])
                .then(function () {
                    assert.equal(0, emitted);
                    done();
                });
        });

        it('should trigger two star events in the first place with one level', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['**'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['giant']).catch(done);
            h.emit(['giant'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger two star emitted events in the first place with one level', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['sun'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['**']).catch(done);
            h.emit(['**'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger two star events in the first place with two levels', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['**'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['oglethorpe', 'piggy']).catch(done);
            h.emit(['oglethorpe', 'piggy'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger second level two star emitted events in the first place with two levels', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['emry', 'please'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['emry', '**']).catch(done);
            h.emit(['emry', '**'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger second level two star events in the first place with one level', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['**'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['vanted', 'vatch']).catch(done);
            h.emit(['vanted', 'vatch'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger second level two star emitted events in the first place with one level', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['trail'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['trail', '**']).catch(done);
            h.emit(['trail', '**'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger second level two star events in the first place with two levels', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['rrr', '**'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['rrr', 'mooninite']).catch(done);
            h.emit(['rrr', 'mooninite'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });

        it('should trigger second level two star emitted events in the first place with two levels', function (done) {
            var h = new H();
            var emitted = 0;
            h.once(['hypersleep', 'dreams'], function (msg, cb) {
                emitted += 1;
                cb();
            });
            h.emit(['hypersleep', '**']).catch(done);
            h.emit(['hypersleep', '**'])
                .then(function () {
                    assert.equal(1, emitted);
                    done();
                });
        });
    });

});
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Service.extend({

  getCookie : function (cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) === 0) {
        let s = c.substring(name.length, c.length);
        return s;
      }
    }

    //cookie not found, look for token in url
    let token, matchInfo = /token=(.*)/.exec(document.location.search);
    if(matchInfo) {
        token = matchInfo[1] || null;
        if(token) this.setCookie('girderToken', token);
//        var location = this.get('router.url');
  //      window.location.href = location.split('?')[0];

        return token;
    }

    return null;
  },

  setCookie : function(cname, value, path, domain, expiry) {
    let d = new Date();
    d.setTime(d.getTime() + ((expiry||180)*24*60*60*1000));
    let expires = d.toUTCString();

    document.cookie = cname + "=" + value + ";" +
        ((path) ? ";path="+path:"")+
        ((domain)?";domain="+domain:"") +
        ";expires=" + expires;
  },

  deleteCookie : function ( name, path, domain ) {
    if( this.getCookie( name ) ) {
      document.cookie = name + "=" +
        ((path) ? ";path="+path:"")+
        ((domain)?";domain="+domain:"") +
        ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
    }
  },

  getWholeTaleAuthToken: function() {
    return this.getCookie('girderToken');
  },

  releaseWholeTaleCookie: function () {
    return this.deleteCookie('girderToken');
  }
});
<commit_msg>Fixed cookie delete method<commit_after>import Ember from 'ember';

export default Ember.Service.extend({

  getCookie : function (cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) === 0) {
        let s = c.substring(name.length, c.length);
        return s;
      }
    }

    //cookie not found, look for token in url
    let token, matchInfo = /token=(.*)/.exec(document.location.search);
    if(matchInfo) {
        token = matchInfo[1] || null;
        if(token) this.setCookie('girderToken', token);
        return token;
    }

    return null;
  },

  setCookie : function(cname, value, path, domain, expiry) {
    let d = new Date();
    d.setTime(d.getTime() + ((expiry||180)*24*60*60*1000));
    let expires = d.toUTCString();

    document.cookie = cname + "=" + value + ";" +
        ((path) ? ";path="+path:"")+
        ((domain)?";domain="+domain:"") +
        ";expires=" + expires;
  },

  deleteCookie : function ( name, path, domain ) {
    if( this.getCookie( name ) ) {
      // Modified according to http://stackoverflow.com/questions/2144386/javascript-delete-cookie
      // Read Tasos_K's comment about the old method (commented out here) and how it no longer works.
      // It isn't explained why the old method should fail, but new method seems to work okay.
      //   document.cookie = name + "=" +
      //     ((path) ? ";path="+path:"")+
      //     ((domain)?";domain="+domain:"") +
      //     ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
      this.setCookie(name, "", path, domain, -1);
    }
  },

  getWholeTaleAuthToken: function() {
    return this.getCookie('girderToken');
  },

  releaseWholeTaleCookie: function () {
    console.log("did i reach here?");
    return this.deleteCookie('girderToken');
  }
});
<|endoftext|>


<commit_before>import d3 from "d3";
import d3MeasureText from "d3-measure-text"; d3MeasureText.d3 = d3;

import _ from "lodash";

import $ from "jquery";

import { makeEdges, DOC_URL, EMAIL_URL, CALENDAR_URL,
  relationColors, NOTE_URL
} from "./misc.js";

import Hammer from "hammerjs";

//Hummer.jsのイベントのリスナー
function addHummerEventListener(that, d){

}

const D2R = Math.PI / 180;

var NODE_RAD = 20;
// var NODE_PADDING = 20;
var LABEL_OFFSET = 15;
// var INIT_RAD_LAYOUT = 150;
// var INIT_NODE_PADDING = 20;
var LAYOUT_RAD = 175;

Array.prototype.last = function() {
    if (this.length > 0)
      return this[this.length-1];
    else return null;
};

function getTangibles(length, successFunc) {
  console.log("getTangibles length", length);
  $.ajax({
    url: "http://localhost:8080/CamCapture/AjaxTypeServlett?callback=?",
    type: "get",
    data: {length: length},
    dataType: "jsonp",
    jsonp: "callback",
    // Accept: "application/sparql-results+json",
    // async: false,
    success: function(tangibles) {
       successFunc(tangibles);
    },
    error: function(err) {
      console.log("err", err);
    }
  });
}

function myDiffList(oldTypes, newTypes) {
  // TODO: clone oldTypes
  if (oldTypes.length >= newTypes) return newTypes.last();
  var newType;
  newTypes.forEach(type => {
    var index = oldTypes.indexOf(type);
    if (index >= 0) {
        oldTypes.splice(index, 1);
    } else {
      newType = type;
    }
  });
  return newType;
}

function backgroundArc(radius) {
  return d3.svg.arc()
           .innerRadius(radius)
           .outerRadius(radius - 1)
           .startAngle(0)
           .endAngle(2 * Math.PI);
}

function labelArc(innerRadius, outerRadius) {
  return d3.svg.arc()
           .innerRadius(innerRadius)
           .outerRadius(outerRadius)
           .startAngle(0)
           .endAngle(2 * Math.PI);
}

function cropLen(string) {
  if (string.length > 13) return string.substring(0, 14).concat("...");
  else return string;
}

// var groupFill = function(d, i) { return fill(i & 3); };
// var fill = d3.scale.category10();

function collide(data, alpha, padding) {
  var quadtree = d3.geom.quadtree(data);
  return function(d) {
      var r = d.radius + padding,
          nx1 = d.x - r,
          nx2 = d.x + r,
          ny1 = d.y - r,
          ny2 = d.y + r;
      quadtree.visit(function(quad, x1, y1, x2, y2) {
        if (quad.point && (quad.point !== d)) {
          var x = d.x - quad.point.x,
              y = d.y - quad.point.y,
              l = Math.sqrt(x * x + y * y),
              r = d.radius + padding + quad.point.radius;

          if (l < r) {
            l = (l - r) / l * alpha;
            d.x -= x *= l;
            d.y -= y *= l;
            quad.point.x += x;
            quad.point.y += y;
          }
        }
        return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
    });
  };
}

// function movePos(pos, alpha) {
//     return function(d) {
//         d.x = d.x + (pos.x - d.x) * (0.1 + 0.02) * alpha * 1.1;
//         d.y = d.y + (pos.y - d.y) * (0.1 + 0.02) * alpha * 1.1;
//     };
// }

function radial(d, radius, alpha, energy, center) {

  var currentAngleRadians = d.angle * D2R;

  var radialPoint = {
    x: center.x + radius * Math.cos(currentAngleRadians),
    y: center.y + radius * Math.sin(currentAngleRadians)
  };

  var affectSize = alpha * energy;

  d.x += (radialPoint.x - d.x) * affectSize;
  d.y += (radialPoint.y - d.y) * affectSize;
}

// function movePos(pos, alpha) {
//     return function(d) {
//         d.x = d.x + (pos.x - d.x) * (0.1 + 0.02) * alpha * 1.1;
//         d.y = d.y + (pos.y - d.y) * (0.1 + 0.02) * alpha * 1.1;
//     };
// }

function tick(node, link, width, height) {
  function lineData(d){ var straightLine = d3.svg.line().interpolate("bundle")
            .x(d => d.x)
            .y(d => d.y);

    var points = [
        {x: d.source.x - (NODE_RAD - LABEL_OFFSET), y: d.source.y},
        {x: d.target.x, y: d.target.y}
    ];
    return straightLine(points);
  }

  var nodeGroups = d3.nest()
                   .key(d => d.dim)
                   .entries(node.data());
  var lastGroup = nodeGroups[nodeGroups.length - 1];

  return function(e) {
    nodeGroups.forEach(group => {
      group.values.forEach((d, i) => {
        var radius = d.dim*LAYOUT_RAD;
        d.angle = d.angle || 360 / group.values.length * i;
        // d.offset = NODE_RAD + LABEL_OFFSET + 50;
        radial(d, radius + d.offset, e.alpha, 0.9, {x: width/2, y: height/2});
      });
    });

    node.each(collide(node.data(), 0.1, NODE_RAD + LABEL_OFFSET));

    node.attr("transform", d => "translate(" + d.x + "," + d.y + ")");
    link.attr("d", lineData);

    var arc = d3.select("#background-arc" + lastGroup.key);
    if (e.alpha < 0.1 && arc.empty()) {
      var radius = lastGroup.key*(LAYOUT_RAD - NODE_RAD - LABEL_OFFSET);
        d3.select("#vis-cont svg")
          .insert("path", ":first-child")
          .attr("d", backgroundArc(radius))
          .attr("id", "background-arc" + lastGroup.key)
          .attr("transform", "translate(" + width/2 + "," +  height/2  + ")") .style("stroke-width", 1)
          .attr("fill", "lightgrey");
    }
  };
}

function contextMenu(d, props, state, type, that) {
    // var selectedNode = props.path.last();
    var nbs = state.linkedByIndex.nbs(d, type);
    state.nbs = nbs;
    if (nbs.length == 0) return;

    var nbsByLinkValueDuplicates = _.flatten(nbs.map(d => {
      return d.linkedBy.value.map(v => {
        d.linkValue = v;
        return d;
      });
    }));

    var nestedNbs = d3.nest()
      .key(function(d) { return d.linkValue; })
      .entries(nbsByLinkValueDuplicates);

    var ul = d3.select("#vis-cont")
        .insert("div")
        .attr("class", "context-menu")
        .insert("ul", ":first-child")
        .attr("class", "list")
        .style("position", "absolute")
        .style("left", d.x + "px")
        .style("top", (d.y  - (nestedNbs.length * 25 )) + "px")
        .style("margin-top", -75 + "px")
        .style("display", "inline");

    ul.selectAll("li")
      .data(nestedNbs)
      .enter()
    .append("li")
      .text(d => d.key)
      .each(function(d){
        Hammer(this).on("tap", function(){
          state.dataStack.pop();
          d3.select(".context-menu").remove();
          update(props, state, that, d.values);
        });
      });

}

var create = function(el, props, state) {
  state.data.forEach(d => {
    d.radius = NODE_RAD;
  });

  state.dataStack = [ state.data ];
  state.types = [];

  d3.select(el).append("svg")
    .attr("width", props.width)
    .attr("height", props.height);

  this.force.size([props.width, props.height]);

  return this;
};

function update(props, state, that, nbs) {
  var svg = d3.select("#vis-cont svg");
  var edges = [];
  var selectedNode = props.path.last();

  // console.log("selectedNode", selectedNode);

  if (selectedNode) {
    var sumRadius = d3.sum(nbs, d => d.radius);

    nbs.forEach((d, i) => {
      edges.push({
        id: selectedNode.title + "-" + d.title,
        source: selectedNode,
        target: d,
        value: 1,
        type: d.connectedByType
      });
      // d.connectedByType = type;
      d.dim = selectedNode.dim + 1;

      d.angle = selectedNode.angle - (sumRadius / (d.dim*2))
                + ((i * (d.radius)) / d.dim );
      d.offset = selectedNode.offset;
    });

    edges = edges.concat(makeEdges(props.path.slice()));

    // attach nbs
    if (props.forward) {
      state.dataStack.push(_.uniq(props.path.concat(nbs), "title"));
    }

    // console.log("update Graph inner", this);
    that.force.links(edges);
  }

  that.force.nodes(state.dataStack.last());

  var node = svg.selectAll("g.group")
                .data(state.dataStack.last(), d => d.id);

  node
    .enter()
    .call(function() {
      var g = this.append("g")
        .attr("class", "group");

      g.append("svg:image")
        .attr("xlink:href", d => {
          switch (d.datatype) {
            case "Publication":
              return DOC_URL;
            case "Email":
              return EMAIL_URL;
            case "Note":
              return NOTE_URL;
            default:
              return CALENDAR_URL;
          }
        })
        .attr("x", d => - d.radius)
        .attr("y", d => - d.radius)
        .attr("height", d => d.radius * 2)
        .attr("width", d => d.radius * 2);

      g.append("path")
        .attr("d", labelArc(NODE_RAD, NODE_RAD))
        // .attr("fill", "lightgrey")
        .attr("id", (_, i) => "arc"+i)
        .style("font-size", 20)
        .attr("alignment-baseline", "middle")
        .attr("text-anchor", "middle");

      g.append("text")
        // .attr("x", 8)
        .attr("dy", - 2)
        .append("textPath")
        .attr("textLength", d => {
          return d3MeasureText(cropLen(d.title)).width;
        })
        .attr("xlink:href",(_, i) => "#arc"+i)
        .attr("startOffset", 3/40)
        .attr("dy","-1em")
        .text(d => cropLen(d.title));

      g.append("path")
        .attr("d", labelArc(NODE_RAD, NODE_RAD + LABEL_OFFSET))
        .attr("fill", "lightgrey")
        .attr("alignment-baseline", "middle")
        .style("font-size", 20)
        .attr("text-anchor", "middle")
        .attr("opacity", 0.5);
    });

  var maxDim = d3.max(node.data(), d => d.dim);
  node
    .attr("opacity", d => {
      if (d.dim < maxDim && !d.selected) return 0.1;
      // TODO: delete later
      // if (d.dim === maxDim && !d.selected) return 0.5;
      // return 1;
    });

  node
    .on("touchstart", function(d) {
      d3.event.stopPropagation();
      if (!d.selected) {
          d.fixed = true;
          d.selected = true;
          // TODO: change to state
          props.path.push(d);
          props.forward = true;
          console.log("state types before", "length", state.types.length);
          // console.log("retrieved Type", "length", types.length);

          // TODO: check if it works
          console.log("state.type", state.type);
          // state.types = types;

          console.log("NEW state types", "length", state.types.length);
          props.getPath(props.path);

          getTangibles(props.path.length, function(types) {
            console.log("New response server", types);
            console.log("oldTypes", state.types);
            var type = myDiffList(state.types, types);
            console.log("type", type);
            // var type = "Keyword";
            state.types = types;
            contextMenu(d, props, state, type, that);
          });

          update(props, state, that, []);
      } else {
        true;
      }
    })
    .on("touchend", function(d) {
        d3.event.stopPropagation();
        if (!d.selected) return;
        d3.select(".context-menu").remove();

        if (props.path.last().id !== d.id) return;
        d.fixed = false;
        d.selected = false;

        props.path.pop();
        props.forward = false;
        state.dataStack.pop();

        // send path to parent component
        props.getPath(props.path);
        state.dataStack.last().forEach(e => {
          if (e.dim > d.dim) e.dim = d.dim;
        });
        // reset angles
        if (d.dim === 1) state.dataStack.last().forEach(e => e.angle = null );

        var nbs1 = [];
        if (props.path.length > 0) {
          nbs1 = state.nbs;
        }
        else nbs1 = [];

        update(props, state, that, nbs1);

    });

  var link = d3.select("#vis-cont svg").selectAll(".link")
        .data(edges, d => d.source.title + "-" + d.target.title);

  link
    .style("stroke-width", d => d.target.selected ? 15 : 1)
    .style("stroke", d => d.target.selected ? relationColors[d.type] : null);

  link
    .enter()
    .insert("path", ":first-child")
    .attr("class", "link");
    // .style("stroke-width", d => d.value)
    // .style("stroke", 20);

  that.force.on("tick", tick(node, link, props.width, props.height));

  that.force.start();

  link.exit().remove();
  node.exit().remove();

}

// defaultProps{
//   widthTotal: 1350,
//   heightTotal: 500,
//   margin: {
//     left: 40,
//     right: 40,
//     top: 40,
//     bottom: 0
//   },
//   data: [],
//   view: "overview"
// };
const d3ggLayout = new function(){
  return {
    force: d3.layout.force()
              .charge(0)
              .gravity(0.2)
              .friction(0.9)
              .linkDistance(0)
              .linkStrength(0),
    update: update,
    create: create
  };
};

export default d3ggLayout;
<commit_msg>myDiffList change!<commit_after>import d3 from "d3";
import d3MeasureText from "d3-measure-text"; d3MeasureText.d3 = d3;

import _ from "lodash";

import $ from "jquery";

import { makeEdges, DOC_URL, EMAIL_URL, CALENDAR_URL,
  relationColors, NOTE_URL
} from "./misc.js";

import Hammer from "hammerjs";

//Hummer.jsのイベントのリスナー
function addHummerEventListener(that, d){

}

const D2R = Math.PI / 180;

var NODE_RAD = 20;
// var NODE_PADDING = 20;
var LABEL_OFFSET = 15;
// var INIT_RAD_LAYOUT = 150;
// var INIT_NODE_PADDING = 20;
var LAYOUT_RAD = 175;

Array.prototype.last = function() {
    if (this.length > 0)
      return this[this.length-1];
    else return null;
};

function getTangibles(length, successFunc) {
  console.log("getTangibles length", length);
  $.ajax({
    url: "http://localhost:8080/CamCapture/AjaxTypeServlett?callback=?",
    type: "get",
    data: {length: length},
    dataType: "jsonp",
    jsonp: "callback",
    // Accept: "application/sparql-results+json",
    // async: false,
    success: function(tangibles) {
       successFunc(tangibles);
    },
    error: function(err) {
      console.log("err", err);
    }
  });
}

function myDiffList(oldTypes, newTypes) {
  if (oldTypes.length >= newTypes) {
    if (newTypes.length > 0)
      return newTypes.last();
  }

  var newType;
  newTypes.forEach(type => {
    var index = oldTypes.indexOf(type);
    if (index >= 0) {
        oldTypes.splice(index, 1);
    } else {
      newType = type;
    }
  });
  return newType;
}

function backgroundArc(radius) {
  return d3.svg.arc()
           .innerRadius(radius)
           .outerRadius(radius - 1)
           .startAngle(0)
           .endAngle(2 * Math.PI);
}

function labelArc(innerRadius, outerRadius) {
  return d3.svg.arc()
           .innerRadius(innerRadius)
           .outerRadius(outerRadius)
           .startAngle(0)
           .endAngle(2 * Math.PI);
}

function cropLen(string) {
  if (string.length > 13) return string.substring(0, 14).concat("...");
  else return string;
}

// var groupFill = function(d, i) { return fill(i & 3); };
// var fill = d3.scale.category10();

function collide(data, alpha, padding) {
  var quadtree = d3.geom.quadtree(data);
  return function(d) {
      var r = d.radius + padding,
          nx1 = d.x - r,
          nx2 = d.x + r,
          ny1 = d.y - r,
          ny2 = d.y + r;
      quadtree.visit(function(quad, x1, y1, x2, y2) {
        if (quad.point && (quad.point !== d)) {
          var x = d.x - quad.point.x,
              y = d.y - quad.point.y,
              l = Math.sqrt(x * x + y * y),
              r = d.radius + padding + quad.point.radius;

          if (l < r) {
            l = (l - r) / l * alpha;
            d.x -= x *= l;
            d.y -= y *= l;
            quad.point.x += x;
            quad.point.y += y;
          }
        }
        return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
    });
  };
}

// function movePos(pos, alpha) {
//     return function(d) {
//         d.x = d.x + (pos.x - d.x) * (0.1 + 0.02) * alpha * 1.1;
//         d.y = d.y + (pos.y - d.y) * (0.1 + 0.02) * alpha * 1.1;
//     };
// }

function radial(d, radius, alpha, energy, center) {

  var currentAngleRadians = d.angle * D2R;

  var radialPoint = {
    x: center.x + radius * Math.cos(currentAngleRadians),
    y: center.y + radius * Math.sin(currentAngleRadians)
  };

  var affectSize = alpha * energy;

  d.x += (radialPoint.x - d.x) * affectSize;
  d.y += (radialPoint.y - d.y) * affectSize;
}

// function movePos(pos, alpha) {
//     return function(d) {
//         d.x = d.x + (pos.x - d.x) * (0.1 + 0.02) * alpha * 1.1;
//         d.y = d.y + (pos.y - d.y) * (0.1 + 0.02) * alpha * 1.1;
//     };
// }

function tick(node, link, width, height) {
  function lineData(d){ var straightLine = d3.svg.line().interpolate("bundle")
            .x(d => d.x)
            .y(d => d.y);

    var points = [
        {x: d.source.x - (NODE_RAD - LABEL_OFFSET), y: d.source.y},
        {x: d.target.x, y: d.target.y}
    ];
    return straightLine(points);
  }

  var nodeGroups = d3.nest()
                   .key(d => d.dim)
                   .entries(node.data());
  var lastGroup = nodeGroups[nodeGroups.length - 1];

  return function(e) {
    nodeGroups.forEach(group => {
      group.values.forEach((d, i) => {
        var radius = d.dim*LAYOUT_RAD;
        d.angle = d.angle || 360 / group.values.length * i;
        // d.offset = NODE_RAD + LABEL_OFFSET + 50;
        radial(d, radius + d.offset, e.alpha, 0.9, {x: width/2, y: height/2});
      });
    });

    node.each(collide(node.data(), 0.1, NODE_RAD + LABEL_OFFSET));

    node.attr("transform", d => "translate(" + d.x + "," + d.y + ")");
    link.attr("d", lineData);

    var arc = d3.select("#background-arc" + lastGroup.key);
    if (e.alpha < 0.1 && arc.empty()) {
      var radius = lastGroup.key*(LAYOUT_RAD - NODE_RAD - LABEL_OFFSET);
        d3.select("#vis-cont svg")
          .insert("path", ":first-child")
          .attr("d", backgroundArc(radius))
          .attr("id", "background-arc" + lastGroup.key)
          .attr("transform", "translate(" + width/2 + "," +  height/2  + ")") .style("stroke-width", 1)
          .attr("fill", "lightgrey");
    }
  };
}

function contextMenu(d, props, state, type, that) {
    // var selectedNode = props.path.last();
    var nbs = state.linkedByIndex.nbs(d, type);
    state.nbs = nbs;
    if (nbs.length == 0) return;

    var nbsByLinkValueDuplicates = _.flatten(nbs.map(d => {
      return d.linkedBy.value.map(v => {
        d.linkValue = v;
        return d;
      });
    }));

    var nestedNbs = d3.nest()
      .key(function(d) { return d.linkValue; })
      .entries(nbsByLinkValueDuplicates);

    var ul = d3.select("#vis-cont")
        .insert("div")
        .attr("class", "context-menu")
        .insert("ul", ":first-child")
        .attr("class", "list")
        .style("position", "absolute")
        .style("left", d.x + "px")
        .style("top", (d.y  - (nestedNbs.length * 25 )) + "px")
        .style("margin-top", -75 + "px")
        .style("display", "inline");

    ul.selectAll("li")
      .data(nestedNbs)
      .enter()
    .append("li")
      .text(d => d.key)
      .each(function(d){
        Hammer(this).on("tap", function(){
          state.dataStack.pop();
          d3.select(".context-menu").remove();
          update(props, state, that, d.values);
        });
      });

}

var create = function(el, props, state) {
  state.data.forEach(d => {
    d.radius = NODE_RAD;
  });

  state.dataStack = [ state.data ];
  state.types = [];

  d3.select(el).append("svg")
    .attr("width", props.width)
    .attr("height", props.height);

  this.force.size([props.width, props.height]);

  return this;
};

function update(props, state, that, nbs) {
  var svg = d3.select("#vis-cont svg");
  var edges = [];
  var selectedNode = props.path.last();

  // console.log("selectedNode", selectedNode);

  if (selectedNode) {
    var sumRadius = d3.sum(nbs, d => d.radius);

    nbs.forEach((d, i) => {
      edges.push({
        id: selectedNode.title + "-" + d.title,
        source: selectedNode,
        target: d,
        value: 1,
        type: d.connectedByType
      });
      // d.connectedByType = type;
      d.dim = selectedNode.dim + 1;

      d.angle = selectedNode.angle - (sumRadius / (d.dim*2))
                + ((i * (d.radius)) / d.dim );
      d.offset = selectedNode.offset;
    });

    edges = edges.concat(makeEdges(props.path.slice()));

    // attach nbs
    if (props.forward) {
      state.dataStack.push(_.uniq(props.path.concat(nbs), "title"));
    }

    // console.log("update Graph inner", this);
    that.force.links(edges);
  }

  that.force.nodes(state.dataStack.last());

  var node = svg.selectAll("g.group")
                .data(state.dataStack.last(), d => d.id);

  node
    .enter()
    .call(function() {
      var g = this.append("g")
        .attr("class", "group");

      g.append("svg:image")
        .attr("xlink:href", d => {
          switch (d.datatype) {
            case "Publication":
              return DOC_URL;
            case "Email":
              return EMAIL_URL;
            case "Note":
              return NOTE_URL;
            default:
              return CALENDAR_URL;
          }
        })
        .attr("x", d => - d.radius)
        .attr("y", d => - d.radius)
        .attr("height", d => d.radius * 2)
        .attr("width", d => d.radius * 2);

      g.append("path")
        .attr("d", labelArc(NODE_RAD, NODE_RAD))
        // .attr("fill", "lightgrey")
        .attr("id", (_, i) => "arc"+i)
        .style("font-size", 20)
        .attr("alignment-baseline", "middle")
        .attr("text-anchor", "middle");

      g.append("text")
        // .attr("x", 8)
        .attr("dy", - 2)
        .append("textPath")
        .attr("textLength", d => {
          return d3MeasureText(cropLen(d.title)).width;
        })
        .attr("xlink:href",(_, i) => "#arc"+i)
        .attr("startOffset", 3/40)
        .attr("dy","-1em")
        .text(d => cropLen(d.title));

      g.append("path")
        .attr("d", labelArc(NODE_RAD, NODE_RAD + LABEL_OFFSET))
        .attr("fill", "lightgrey")
        .attr("alignment-baseline", "middle")
        .style("font-size", 20)
        .attr("text-anchor", "middle")
        .attr("opacity", 0.5);
    });

  var maxDim = d3.max(node.data(), d => d.dim);
  node
    .attr("opacity", d => {
      if (d.dim < maxDim && !d.selected) return 0.1;
      // TODO: delete later
      // if (d.dim === maxDim && !d.selected) return 0.5;
      // return 1;
    });

  node
    .on("touchstart", function(d) {
      d3.event.stopPropagation();
      if (!d.selected) {
          d.fixed = true;
          d.selected = true;
          // TODO: change to state
          props.path.push(d);
          props.forward = true;
          console.log("state types before", "length", state.types.length);
          // console.log("retrieved Type", "length", types.length);

          // TODO: check if it works
          console.log("state.type", state.type);
          // state.types = types;

          console.log("NEW state types", "length", state.types.length);
          props.getPath(props.path);

          getTangibles(props.path.length, function(types) {
            console.log("New response server", types);
            console.log("oldTypes", state.types);
            var type = myDiffList(state.types, types);
            console.log("type", type);
            // var type = "Keyword";
            state.types = types;
            contextMenu(d, props, state, type, that);
          });

          update(props, state, that, []);
      } else {
        true;
      }
    })
    .on("touchend", function(d) {
        d3.event.stopPropagation();
        if (!d.selected) return;
        d3.select(".context-menu").remove();

        if (props.path.last().id !== d.id) return;
        d.fixed = false;
        d.selected = false;

        props.path.pop();
        props.forward = false;
        state.dataStack.pop();

        // send path to parent component
        props.getPath(props.path);
        state.dataStack.last().forEach(e => {
          if (e.dim > d.dim) e.dim = d.dim;
        });
        // reset angles
        if (d.dim === 1) state.dataStack.last().forEach(e => e.angle = null );

        var nbs1 = [];
        if (props.path.length > 0) {
          nbs1 = state.nbs;
        }
        else nbs1 = [];

        update(props, state, that, nbs1);

    });

  var link = d3.select("#vis-cont svg").selectAll(".link")
        .data(edges, d => d.source.title + "-" + d.target.title);

  link
    .style("stroke-width", d => d.target.selected ? 15 : 1)
    .style("stroke", d => d.target.selected ? relationColors[d.type] : null);

  link
    .enter()
    .insert("path", ":first-child")
    .attr("class", "link");
    // .style("stroke-width", d => d.value)
    // .style("stroke", 20);

  that.force.on("tick", tick(node, link, props.width, props.height));

  that.force.start();

  link.exit().remove();
  node.exit().remove();

}

// defaultProps{
//   widthTotal: 1350,
//   heightTotal: 500,
//   margin: {
//     left: 40,
//     right: 40,
//     top: 40,
//     bottom: 0
//   },
//   data: [],
//   view: "overview"
// };
const d3ggLayout = new function(){
  return {
    force: d3.layout.force()
              .charge(0)
              .gravity(0.2)
              .friction(0.9)
              .linkDistance(0)
              .linkStrength(0),
    update: update,
    create: create
  };
};

export default d3ggLayout;
<|endoftext|>


<commit_before>(function(buster, poll, when, delay) {

var assert, refute, fail, resolved, rejected;

assert = buster.assert;
refute = buster.refute;
fail = buster.assertions.fail;

resolved = when.resolve;
rejected = when.reject;

function failIfCalled(done, message) {
	return function () {
		fail(message || 'should never be called');
		done();
	};
}

buster.testCase('when/poll', {

	'should poll until canceled': function (done) {
		var i, p, progback;

		i = 0;
		p = poll(function () { i += 1; return i; }, 10);
		progback = this.spy(function (result) { assert.equals(i, result); });

		p.then(
			failIfCalled(done, 'should never be resolved'),
			function () {
				assert(progback.called);
				done();
			},
			progback
		);
		delay(100).then(p.cancel);
	},

	'should poll with interval function': function (done) {
		var countdown, interval;

		countdown = 3;
		interval = this.spy(function () {
			return delay(10);
		});

		poll(function () {}, interval, function () { countdown -= 1; return countdown == 0; }).then(
			function () {
//				assert(interval.withArgs(undef).calledOnce);
//				assert(interval.withArgs(10).calledOnce);
				assert(interval.calledTwice);
				done();
			},
			failIfCalled(done, 'should never be rejected')
		);
	},

	'should be canceled by rejected work': function (done) {
		var p = poll(rejected, 10);

		p.then(
			failIfCalled(done, 'should never be resolved'),
			function () {
				assert(true);
				done();
			},
			failIfCalled(done, 'should never receive progress')
		);
	},

	'should poll with delayed start': function (done) {
		var i, p, progback;

		i = 0;
		p = poll(function () { i += 1; return i; }, 10, function (result) { return result === 2; }, true);
		progback = this.spy(function (result) { assert.equals(result, 1); });

		p.then(
			function (result) {
				assert.equals(result, 2);
				assert(progback.called);
				done();
			},
			failIfCalled(done),
			progback
		);
	},

	'should keep polling from rejected verification, stop for resolved verification': function (done) {
		var i, p, progback;

		i = 0;
		p = poll(function () { i += 1; return i; }, 10, function () { return i < 3 ? rejected() : resolved(true); });
		progback = this.spy(function (result) { assert.equals(result, 2); });

		p.then(
			function (result) {
				assert.equals(result, 3);
				assert(progback.called);
				done();
			},
			failIfCalled(done, 'should never be rejected'),
			progback
		);
	},

	'should keep polling from falsey resolved verification, stop for truthy resolved verification': function (done) {
		var i, p, progback;

		i = 0;
		p = poll(function () { i += 1; return i; }, 10, function (result) { return result < 3 ? resolved(false) : resolved(true); });
		progback = this.spy(function (result) { assert.equals(result, 2); });

		p.then(
			function (result) {
				assert.equals(result, 3);
				assert(progback.called);
				done();
			},
			failIfCalled(done, 'should never be rejected'),
			progback
		);
	}

});
})(
	this.buster || require('buster'),
	this.when_poll || require('../poll'),
	this.when || require('../when'),
	this.when_delay || require('../delay')
);
<commit_msg>Minor cleanup<commit_after>(function(buster, poll, when, delay) {

var assert, refute, fail, resolved, rejected;

assert = buster.assert;
refute = buster.refute;
fail = buster.assertions.fail;

resolved = when.resolve;
rejected = when.reject;

function failIfCalled(done, message) {
	return function () {
		fail(message || 'should never be called');
		done();
	};
}

buster.testCase('when/poll', {

	'should poll until canceled': function (done) {
		var i, p, progback;

		i = 0;
		p = poll(function () { i += 1; return i; }, 10);
		progback = this.spy(function (result) { assert.equals(i, result); });

		p.then(
			failIfCalled(done, 'should never be resolved'),
			function () {
				assert(progback.called);
				done();
			},
			progback
		);
		delay(100).then(p.cancel);
	},

	'should poll with interval function': function (done) {
		var countdown, interval;

		countdown = 3;
		interval = this.spy(function () {
			return delay(10);
		});

		poll(function () {}, interval, function () { countdown -= 1; return countdown == 0; }).then(
			function () {
				assert(interval.calledTwice);
				done();
			},
			failIfCalled(done, 'should never be rejected')
		);
	},

	'should be canceled by rejected work': function (done) {
		var p = poll(rejected, 10);

		p.then(
			failIfCalled(done, 'should never be resolved'),
			function () {
				assert(true);
				done();
			},
			failIfCalled(done, 'should never receive progress')
		);
	},

	'should poll with delayed start': function (done) {
		var i, p, progback;

		i = 0;
		p = poll(function () { i += 1; return i; }, 10, function (result) { return result === 2; }, true);
		progback = this.spy(function (result) { assert.equals(result, 1); });

		p.then(
			function (result) {
				assert.equals(result, 2);
				assert(progback.called);
				done();
			},
			failIfCalled(done),
			progback
		);
	},

	'should keep polling from rejected verification, stop for resolved verification': function (done) {
		var i, p, progback;

		i = 0;
		p = poll(function () { i += 1; return i; }, 10, function () { return i < 3 ? rejected() : resolved(true); });
		progback = this.spy(function (result) { assert.equals(result, 2); });

		p.then(
			function (result) {
				assert.equals(result, 3);
				assert(progback.called);
				done();
			},
			failIfCalled(done, 'should never be rejected'),
			progback
		);
	},

	'should keep polling from falsey resolved verification, stop for truthy resolved verification': function (done) {
		var i, p, progback;

		i = 0;
		p = poll(function () { i += 1; return i; }, 10, function (result) { return result < 3 ? resolved(false) : resolved(true); });
		progback = this.spy(function (result) { assert.equals(result, 2); });

		p.then(
			function (result) {
				assert.equals(result, 3);
				assert(progback.called);
				done();
			},
			failIfCalled(done, 'should never be rejected'),
			progback
		);
	}

});
})(
	this.buster || require('buster'),
	this.when_poll || require('../poll'),
	this.when || require('../when'),
	this.when_delay || require('../delay')
);
<|endoftext|>


<commit_before>module.exports = {
  findSystem: createFinder('system'),
  findIssuer: createFinder('issuer'),
  findProgram: createFinder('program'),
  findBadge: createFinder('badge'),
  verifyRequest: verifyRequest,
}

const jws = require('jws')
const crypto = require('crypto')
const restify = require('restify')
const log = require('../lib/logger')
const models = {
  system: require('../models/system'),
  issuer: require('../models/issuer'),
  program: require('../models/program'),
  badge: require('../models/badge'),
  consumer: require('../models/consumer')
}

const http403 = restify.NotAuthorizedError
const http404 = restify.ResourceNotFoundError
const http500 = restify.InternalError

function createFinder(modelName) {
  return function findModel(opts) {
    opts = opts || {}
    const param = opts.param || modelName + 'Slug'
    const key = opts.key || modelName
    const where = opts.where || {}
    const relationships = typeof opts.relationships !== 'undefined'
      ? opts.relationships
      : false
    return function finder(req, res, next) {
      const slug = req.params[param]
      const query = makeQuery(req, where, {slug: slug})
      const opts = {relationships: relationships}
      models[modelName].getOne(query, opts, function (error, item) {
        if (error) {
          log.error(error)
          return next(new http500('An internal error occured'))
        }
        if (!item) {
          log.warn({code: 'ResourceNotFound', model: modelName, slug: slug})
          return next(new http404('Could not find '+modelName+' `'+slug+'`'))
        }
        req[key] = item
        return next()
      })
    }
  }
}

function makeQuery(req, where, query) {
  return Object.keys(where).reduce(function (query, key) {
    const clause = where[key]
    const value = clause.reduce(function (obj, field) {
      return obj[field]
    }, req)
    query[key] = value
    return query
  }, query)
}

function verifyRequest() {
  if (process.env.NODE_ENV == 'test') {
    log.warn('In test environment, bypassing request verification')
    return function (req, res, next) {
      return next()
    }
  }

  return function (req, res, next) {
    const token = getAuthToken(req)
    if (!token)
      return next(new http403('Missing valid Authorization header'))

    try {
      const parts = jws.decode(token) }
    catch (e) {
      log.warn({code: 'JWTDecodeError', token: token}, 'Could not decode JWT')
      return next(new http403('Could not decode JWT'))
    }

    const auth = parts.payload
    if (!auth)
      return next(new http403('Missing JWT payload'))

    if (!auth.method)
      return next(new http403('Missing JWT claim: method'))

    if (''+auth.method.toUpperCase() !== req.method.toUpperCase())
      return next(new http403('`method` does not match: using "'+auth.method+'" token for "'+req.method+'" request'))

    if (!auth.path)
      return next(new http403('Missing JWT claim: path'))

    if (auth.path !== req.url)
      return next(new http403('`path` does not match: trying to use token for "'+auth.path+'" on "'+req.url+'"'))

    const now = Date.now()/1000|0
    if (auth.exp && auth.exp <= now)
      return next(new http403('Token is expired (token expiry: '+auth.exp+', server time: '+now))

    if (!(/GET|DELETE|HEAD/i.exec(req.method))) {
      if (!auth.body)
        return next(new http403('Missing JWT claim: body'))

      if (!auth.body.alg)
        return next(new http403('Missing JWT claim: body.alg'))

      if (!auth.body.hash)
        return next(new http403('Missing JWT claim: body.hash'))

      const givenHash = auth.body.hash
      try {
        const computedHash = hash(auth.body.alg, req._body)
      } catch (e) {
        return next(new http403('Could not calculate hash, unsupported algorithm: '+auth.body.alg))
      }
      if (givenHash !== computedHash)
        return next(new http403('Computed hash does not match given hash: '+givenHash+' != '+computedHash+''))
    }

    if (auth.key === 'master') {
      const masterSecret = process.env.MASTER_SECRET
      if (!jws.verify(token, masterSecret))
        return next(new http403('Invalid token signature'))
      return success()
    }

    else {
      models.consumer.findByKey(auth.key, function (err, consumer) {
        if (!consumer)
          return next(new http403('Could not find consumer for API key'))

        const requestSystemSlug = req.params.systemSlug
        if (!requestSystemSlug || consumer.system.slug !== requestSystemSlug)
          return next(new http403('Invalid token for system'))

        if (!jws.verify(token, consumer.apiSecret))
          return next(new http403('Invalid token signature'))
        return success()
      })
    }

    function success() { next() }
  }
}

function getAuthToken(req) {
  const authHeader = req.headers.authentication
  if (!authHeader) return

  const match = authHeader.match(/^JWT token="(.+?)"$/)
  if (!match) return

  return match[1]
}

function hash(alg, body) {
  return crypto.createHash(alg).update(body).digest('hex')
}
<commit_msg>NO `HEADLESS HORSEMEN` ALLOWED (enforce verb boundaries)<commit_after>module.exports = {
  findSystem: createFinder('system'),
  findIssuer: createFinder('issuer'),
  findProgram: createFinder('program'),
  findBadge: createFinder('badge'),
  verifyRequest: verifyRequest,
}

const jws = require('jws')
const crypto = require('crypto')
const restify = require('restify')
const log = require('../lib/logger')
const models = {
  system: require('../models/system'),
  issuer: require('../models/issuer'),
  program: require('../models/program'),
  badge: require('../models/badge'),
  consumer: require('../models/consumer')
}

const http403 = restify.NotAuthorizedError
const http404 = restify.ResourceNotFoundError
const http500 = restify.InternalError

function createFinder(modelName) {
  return function findModel(opts) {
    opts = opts || {}
    const param = opts.param || modelName + 'Slug'
    const key = opts.key || modelName
    const where = opts.where || {}
    const relationships = typeof opts.relationships !== 'undefined'
      ? opts.relationships
      : false
    return function finder(req, res, next) {
      const slug = req.params[param]
      const query = makeQuery(req, where, {slug: slug})
      const opts = {relationships: relationships}
      models[modelName].getOne(query, opts, function (error, item) {
        if (error) {
          log.error(error)
          return next(new http500('An internal error occured'))
        }
        if (!item) {
          log.warn({code: 'ResourceNotFound', model: modelName, slug: slug})
          return next(new http404('Could not find '+modelName+' `'+slug+'`'))
        }
        req[key] = item
        return next()
      })
    }
  }
}

function makeQuery(req, where, query) {
  return Object.keys(where).reduce(function (query, key) {
    const clause = where[key]
    const value = clause.reduce(function (obj, field) {
      return obj[field]
    }, req)
    query[key] = value
    return query
  }, query)
}

function verifyRequest() {
  if (process.env.NODE_ENV == 'test') {
    log.warn('In test environment, bypassing request verification')
    return function (req, res, next) {
      return next()
    }
  }

  return function (req, res, next) {
    const token = getAuthToken(req)
    if (!token)
      return next(new http403('Missing valid Authorization header'))

    try {
      const parts = jws.decode(token) }
    catch (e) {
      log.warn({code: 'JWTDecodeError', token: token}, 'Could not decode JWT')
      return next(new http403('Could not decode JWT'))
    }

    const auth = parts.payload
    if (!auth)
      return next(new http403('Missing JWT payload'))

    if (!auth.method)
      return next(new http403('Missing JWT claim: method'))

    if (''+auth.method.toUpperCase() !== req.method.toUpperCase())
      return next(new http403('`method` does not match: using "'+auth.method+'" token for "'+req.method+'" request'))

    if (!auth.path)
      return next(new http403('Missing JWT claim: path'))

    if (auth.path !== req.url)
      return next(new http403('`path` does not match: trying to use token for "'+auth.path+'" on "'+req.url+'"'))

    const now = Date.now()/1000|0
    if (auth.exp && auth.exp <= now)
      return next(new http403('Token is expired (token expiry: '+auth.exp+', server time: '+now))

    if (!(/^(GET|DELETE|HEAD)$/i.exec(req.method))) {
      if (!auth.body)
        return next(new http403('Missing JWT claim: body'))

      if (!auth.body.alg)
        return next(new http403('Missing JWT claim: body.alg'))

      if (!auth.body.hash)
        return next(new http403('Missing JWT claim: body.hash'))

      const givenHash = auth.body.hash
      try {
        const computedHash = hash(auth.body.alg, req._body)
      } catch (e) {
        return next(new http403('Could not calculate hash, unsupported algorithm: '+auth.body.alg))
      }
      if (givenHash !== computedHash)
        return next(new http403('Computed hash does not match given hash: '+givenHash+' != '+computedHash+''))
    }

    if (auth.key === 'master') {
      const masterSecret = process.env.MASTER_SECRET
      if (!jws.verify(token, masterSecret))
        return next(new http403('Invalid token signature'))
      return success()
    }

    else {
      models.consumer.findByKey(auth.key, function (err, consumer) {
        if (!consumer)
          return next(new http403('Could not find consumer for API key'))

        const requestSystemSlug = req.params.systemSlug
        if (!requestSystemSlug || consumer.system.slug !== requestSystemSlug)
          return next(new http403('Invalid token for system'))

        if (!jws.verify(token, consumer.apiSecret))
          return next(new http403('Invalid token signature'))
        return success()
      })
    }

    function success() { next() }
  }
}

function getAuthToken(req) {
  const authHeader = req.headers.authentication
  if (!authHeader) return

  const match = authHeader.match(/^JWT token="(.+?)"$/)
  if (!match) return

  return match[1]
}

function hash(alg, body) {
  return crypto.createHash(alg).update(body).digest('hex')
}
<|endoftext|>


<commit_before>const express = require('express');
const rp = require('request-promise')
const Person = require('../models/Person')
const router = express.Router();

router.post('/', (req, res) => {
  const options = {
    method: 'POST',
    uri: 'http://api.kairos.com/recognize',
    headers: {
      'content-type': 'application/json',
      app_id: process.env.KAIROS_ID,
      app_key: process.env.KAIROS_KEY
    },
    body: {
      image: req.body.image,
      gallery_name: 'facedex'
    },
    json: true
  }
  rp(options)
    .then((APIresponse) => {
      console.log(APIresponse.images[0])
      if (APIresponse.Errors)  {
        res.send({
          people: [],
          error: APIresponse.Errors[0].Message
        })
        return
      }
      if(APIresponse.images[0].transaction.status === 'failure') {
        res.send({
          people: [],
          error: APIresponse.images[0].transaction.message,
        })
        return
      }
      const namesList = APIresponse.images.map(face => face.transaction.subject_id)
      const peopleList = namesList.map((name) => {
        return new Promise((resolve, reject) => {
          Person.findOne({ name })
          .lean()
          .then(person => resolve(person))
          .catch(err => console.log(err))
        })
      })
      return Promise.all(peopleList)
    })
    .then(people => res.send({ people, error: null }))
    .catch(err => res.send({
      people: [],
      error: 'API Broke :('
    }))
})

module.exports = router;
<commit_msg>recognize returns proper error for now match found<commit_after>const express = require('express');
const rp = require('request-promise')
const Person = require('../models/Person')
const router = express.Router();

router.post('/', (req, res) => {
  const options = {
    method: 'POST',
    uri: 'http://api.kairos.com/recognize',
    headers: {
      'content-type': 'application/json',
      app_id: process.env.KAIROS_ID,
      app_key: process.env.KAIROS_KEY
    },
    body: {
      image: req.body.image,
      gallery_name: 'facedex'
    },
    json: true
  }
  rp(options)
    .then((APIresponse) => {
      if (APIresponse.Errors)  {
        res.send({
          people: [],
          error: APIresponse.Errors[0].Message
        })
        return
      }
      if(APIresponse.images[0].transaction.status === 'failure') {
        res.send({
          people: [],
          error: APIresponse.images[0].transaction.message,
        })
        return
      }
      const namesList = APIresponse.images.map(face => face.transaction.subject_id)
      const peopleList = namesList.map((name) => {
        return new Promise((resolve, reject) => {
          Person.findOne({ name })
          .lean()
          .then(person => resolve(person))
          .catch(err => console.log(err))
        })
      })
      return Promise.all(peopleList)
    })
    .then(people => res.send({ people, error: null }))
    .catch(err => res.send({
      people: [],
      error: 'API Broke :('
    }))
})

module.exports = router;
<|endoftext|>