<commit_before>import { EMPTY_OBJ, EMPTY_ARR } from '../constants';
import { Component, enqueueRender } from '../component';
import { coerceToVNode, Fragment } from '../create-element';
import { diffChildren } from './children';
import { diffProps } from './props';
import { assign } from '../util';
import options from '../options';

/**
 * Diff two virtual nodes and apply proper changes to the DOM
 * @param {import('../internal').PreactElement | Text} dom The DOM element representing
 * the virtual nodes under diff
 * @param {import('../internal').PreactElement} parentDom The parent of the DOM element
 * @param {import('../internal').VNode | null} newVNode The new virtual node
 * @param {import('../internal').VNode | null} oldVNode The old virtual node
 * @param {object} context The current context object
 * @param {boolean} isSvg Whether or not this element is an SVG node
 * @param {Array<import('../internal').PreactElement>} excessDomChildren
 * @param {Array<import('../internal').Component>} mounts A list of newly
 * mounted components
 * @param {import('../internal').Component | null} ancestorComponent The direct
 * parent component
 */
export function diff(dom, parentDom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent) {

	// If the previous type doesn't match the new type we drop the whole subtree
	if (oldVNode==null || newVNode==null || oldVNode.type!==newVNode.type) {
		if (oldVNode!=null) unmount(oldVNode, ancestorComponent);
		if (newVNode==null) return null;
		dom = null;
		oldVNode = EMPTY_OBJ;
	}

	if (options.beforeDiff) options.beforeDiff(newVNode);

	let c, p, isNew = false, oldProps, oldState, oldContext,
		newType = newVNode.type;

	/** @type {import('../internal').Component | null} */
	let clearProcessingException;

	try {
		outer: if (oldVNode.type===Fragment || newType===Fragment) {
			diffChildren(parentDom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, c);

			if (newVNode._children.length) {
				dom = newVNode._children[0]._dom;
				newVNode._lastDomChild = newVNode._children[newVNode._children.length - 1]._dom;
			}
		}
		else if (typeof newType==='function') {

			// Necessary for createContext api. Setting this property will pass
			// the context value as `this.context` just for this component.
			let cxType = newType.contextType;
			let provider = cxType && context[cxType._id];
			let cctx = cxType != null ? (provider ? provider.props.value : cxType._defaultValue) : context;

			// Get component and set it to `c`
			if (oldVNode._component) {
				c = newVNode._component = oldVNode._component;
				clearProcessingException = c._processingException;
			}
			else {
				isNew = true;

				// Instantiate the new component
				if (newType.prototype && newType.prototype.render) {
					newVNode._component = c = new newType(newVNode.props, cctx); // eslint-disable-line new-cap
				}
				else {
					newVNode._component = c = new Component(newVNode.props, cctx);
					c._constructor = newType;
					c.render = doRender;
				}
				c._ancestorComponent = ancestorComponent;
				if (provider) provider.sub(c);

				c.props = newVNode.props;
				if (!c.state) c.state = {};
				c.context = cctx;
				c._context = context;
				c._dirty = true;
				c._renderCallbacks = [];
			}

			c._vnode = newVNode;

			// Invoke getDerivedStateFromProps
			let s = c._nextState || c.state;
			if (newType.getDerivedStateFromProps!=null) {
				oldState = assign({}, c.state);
				if (s===c.state) s = assign({}, s);
				assign(s, newType.getDerivedStateFromProps(newVNode.props, s));
			}

			// Invoke pre-render lifecycle methods
			if (isNew) {
				if (newType.getDerivedStateFromProps==null && c.componentWillMount!=null) c.componentWillMount();
				if (c.componentDidMount!=null) mounts.push(c);
			}
			else {
				if (!c._force && c.shouldComponentUpdate!=null && c.shouldComponentUpdate(newVNode.props, s, cctx)===false) {
					c._dirty = false;
					break outer;
				}
				if (newType.getDerivedStateFromProps==null && c._force==null && c.componentWillReceiveProps!=null) {
					c.componentWillReceiveProps(newVNode.props, cctx);
				}

				if (c.componentWillUpdate!=null) {
					c.componentWillUpdate(newVNode.props, s, cctx);
				}
			}

			oldProps = c.props;
			if (!oldState) oldState = c.state;

			oldContext = c.context = cctx;
			c.props = newVNode.props;
			c.state = s;

			if (options.beforeRender) options.beforeRender(newVNode);

			let prev = c._prevVNode;
			let vnode = c._prevVNode = coerceToVNode(c.render(c.props, c.state, c.context));
			c._dirty = false;

			if (c.getChildContext!=null) {
				context = assign(assign({}, context), c.getChildContext());
			}

			if (!isNew && c.getSnapshotBeforeUpdate!=null) {
				oldContext = c.getSnapshotBeforeUpdate(oldProps, oldState);
			}

			c.base = dom = diff(dom, parentDom, vnode, prev, context, isSvg, excessDomChildren, mounts, c);

			if (vnode!=null) {
				// If this component returns a Fragment (or another component that
				// returns a Fragment), then _lastDomChild will be non-null,
				// informing `diffChildren` to diff this component's VNode like a Fragemnt
				newVNode._lastDomChild = vnode._lastDomChild;
			}

			c._parentDom = parentDom;

			if (newVNode.ref) applyRef(newVNode.ref, c, ancestorComponent);
		}
		else {
			dom = diffElementNodes(dom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent);

			if (newVNode.ref && (oldVNode.ref !== newVNode.ref)) {
				applyRef(newVNode.ref, dom, ancestorComponent);
			}
		}

		newVNode._dom = dom;

		if (c!=null) {
			while (p=c._renderCallbacks.pop()) p();

			// Don't call componentDidUpdate on mount or when we bailed out via
			// `shouldComponentUpdate`
			if (!isNew && oldProps!=null && c.componentDidUpdate!=null) {
				c.componentDidUpdate(oldProps, oldState, oldContext);
			}
		}

		if (clearProcessingException) {
			c._processingException = null;
		}

		if (options.afterDiff) options.afterDiff(newVNode);
	}
	catch (e) {
		catchErrorInComponent(e, ancestorComponent);
	}

	return dom;
}

export function commitRoot(mounts, root) {
	let c;
	while ((c = mounts.pop())) {
		try {
			c.componentDidMount();
		}
		catch (e) {
			catchErrorInComponent(e, c._ancestorComponent);
		}
	}

	if (options.commitRoot) options.commitRoot(root);
}

/**
 * Diff two virtual nodes representing DOM element
 * @param {import('../internal').PreactElement} dom The DOM element representing
 * the virtual nodes being diffed
 * @param {import('../internal').VNode} newVNode The new virtual node
 * @param {import('../internal').VNode} oldVNode The old virtual node
 * @param {object} context The current context object
 * @param {boolean} isSvg Whether or not this DOM node is an SVG node
 * @param {*} excessDomChildren
 * @param {Array<import('../internal').Component>} mounts An array of newly
 * mounted components
 * @param {import('../internal').Component} ancestorComponent The parent
 * component to the ones being diffed
 * @returns {import('../internal').PreactElement}
 */
function diffElementNodes(dom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent) {
	let d = dom;

	// Tracks entering and exiting SVG namespace when descending through the tree.
	isSvg = isSvg ? newVNode.type !== 'foreignObject' : newVNode.type === 'svg';

	if (dom==null && excessDomChildren!=null) {
		for (let i=0; i<excessDomChildren.length; i++) {
			const child = excessDomChildren[i];
			if (child!=null && (newVNode.type===null ? child.nodeType===3 : child.localName===newVNode.type)) {
				dom = child;
				excessDomChildren[i] = null;
				break;
			}
		}
	}

	if (dom==null) {
		dom = newVNode.type===null ? document.createTextNode(newVNode.text) : isSvg ? document.createElementNS('http://www.w3.org/2000/svg', newVNode.type) : document.createElement(newVNode.type);

		// we created a new parent, so none of the previously attached children can be reused:
		excessDomChildren = null;
	}
	newVNode._dom = dom;

	if (newVNode.type===null) {
		if ((d===null || dom===d) && newVNode.text!==oldVNode.text) {
			dom.data = newVNode.text;
		}
	}
	else {
		if (excessDomChildren!=null && dom.childNodes!=null) {
			excessDomChildren = EMPTY_ARR.slice.call(dom.childNodes);
		}
		if (newVNode!==oldVNode) {
			let oldProps = oldVNode.props;
			// if we're hydrating, use the element's attributes as its current props:
			if (oldProps==null) {
				oldProps = {};
				if (excessDomChildren!=null) {
					for (let i=0; i<dom.attributes.length; i++) {
						oldProps[dom.attributes[i].name] = dom.attributes[i].value;
					}
				}
			}
			diffProps(dom, newVNode.props, oldProps, isSvg);
		}

		diffChildren(dom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent);
	}

	return dom;
}

/**
 * Invoke or update a ref, depending on whether it is a function or object ref.
 * @param {object|function} [ref=null]
 * @param {any} [value]
 */
export function applyRef(ref, value, ancestorComponent) {
	try {
		if (typeof ref=='function') ref(value);
		else ref.current = value;
	}
	catch (e) {
		catchErrorInComponent(e, ancestorComponent);
	}
}

/**
 * Unmount a virtual node from the tree and apply DOM changes
 * @param {import('../internal').VNode} vnode The virtual node to unmount
 * @param {import('../internal').Component} ancestorComponent The parent
 * component to this virtual node
 */
export function unmount(vnode, ancestorComponent) {
	let r;
	if (options.beforeUnmount) options.beforeUnmount(vnode);

	if (r = vnode.ref) {
		applyRef(r, null, ancestorComponent);
	}

	if ((r = vnode._dom)!=null) r.remove();

	vnode._dom = vnode._lastDomChild = null;

	if ((r = vnode._component)!=null) {
		if (r.componentWillUnmount) {
			try {
				r.componentWillUnmount();
			}
			catch (e) {
				catchErrorInComponent(e, ancestorComponent);
			}
		}

		r.base = r._parentDom = null;
		if (r = r._prevVNode) unmount(r, ancestorComponent);
	}
	else if (r = vnode._children) {
		for (let i = 0; i < r.length; i++) {
			unmount(r[i], ancestorComponent);
		}
	}
}

/** The `.render()` method for a PFC backing instance. */
function doRender(props, state, context) {
	return this._constructor(props, context);
}

/**
 * Find the closest error boundary to a thrown error and call it
 * @param {object} error The thrown value
 * @param {import('../internal').Component} component The first ancestor
 * component check for error boundary behaviors
 */
function catchErrorInComponent(error, component) {
	for (; component; component = component._ancestorComponent) {
		if (!component._processingException) {
			try {
				if (component.constructor.getDerivedStateFromError!=null) {
					component.setState(component.constructor.getDerivedStateFromError(error));
				}
				else if (component.componentDidCatch!=null) {
					component.componentDidCatch(error);
				}
				else {
					continue;
				}
				return enqueueRender(component._processingException = component);
			}
			catch (e) {
				error = e;
			}
		}
	}
	throw error;
}
<commit_msg>Assign .constructor for pure functional components (#1313)<commit_after>import { EMPTY_OBJ, EMPTY_ARR } from '../constants';
import { Component, enqueueRender } from '../component';
import { coerceToVNode, Fragment } from '../create-element';
import { diffChildren } from './children';
import { diffProps } from './props';
import { assign } from '../util';
import options from '../options';

/**
 * Diff two virtual nodes and apply proper changes to the DOM
 * @param {import('../internal').PreactElement | Text} dom The DOM element representing
 * the virtual nodes under diff
 * @param {import('../internal').PreactElement} parentDom The parent of the DOM element
 * @param {import('../internal').VNode | null} newVNode The new virtual node
 * @param {import('../internal').VNode | null} oldVNode The old virtual node
 * @param {object} context The current context object
 * @param {boolean} isSvg Whether or not this element is an SVG node
 * @param {Array<import('../internal').PreactElement>} excessDomChildren
 * @param {Array<import('../internal').Component>} mounts A list of newly
 * mounted components
 * @param {import('../internal').Component | null} ancestorComponent The direct
 * parent component
 */
export function diff(dom, parentDom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent) {

	// If the previous type doesn't match the new type we drop the whole subtree
	if (oldVNode==null || newVNode==null || oldVNode.type!==newVNode.type) {
		if (oldVNode!=null) unmount(oldVNode, ancestorComponent);
		if (newVNode==null) return null;
		dom = null;
		oldVNode = EMPTY_OBJ;
	}

	if (options.beforeDiff) options.beforeDiff(newVNode);

	let c, p, isNew = false, oldProps, oldState, oldContext,
		newType = newVNode.type;

	/** @type {import('../internal').Component | null} */
	let clearProcessingException;

	try {
		outer: if (oldVNode.type===Fragment || newType===Fragment) {
			diffChildren(parentDom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, c);

			if (newVNode._children.length) {
				dom = newVNode._children[0]._dom;
				newVNode._lastDomChild = newVNode._children[newVNode._children.length - 1]._dom;
			}
		}
		else if (typeof newType==='function') {

			// Necessary for createContext api. Setting this property will pass
			// the context value as `this.context` just for this component.
			let cxType = newType.contextType;
			let provider = cxType && context[cxType._id];
			let cctx = cxType != null ? (provider ? provider.props.value : cxType._defaultValue) : context;

			// Get component and set it to `c`
			if (oldVNode._component) {
				c = newVNode._component = oldVNode._component;
				clearProcessingException = c._processingException;
			}
			else {
				isNew = true;

				// Instantiate the new component
				if (newType.prototype && newType.prototype.render) {
					newVNode._component = c = new newType(newVNode.props, cctx); // eslint-disable-line new-cap
				}
				else {
					newVNode._component = c = new Component(newVNode.props, cctx);
					c.constructor = newType;
					c.render = doRender;
				}
				c._ancestorComponent = ancestorComponent;
				if (provider) provider.sub(c);

				c.props = newVNode.props;
				if (!c.state) c.state = {};
				c.context = cctx;
				c._context = context;
				c._dirty = true;
				c._renderCallbacks = [];
			}

			c._vnode = newVNode;

			// Invoke getDerivedStateFromProps
			let s = c._nextState || c.state;
			if (newType.getDerivedStateFromProps!=null) {
				oldState = assign({}, c.state);
				if (s===c.state) s = assign({}, s);
				assign(s, newType.getDerivedStateFromProps(newVNode.props, s));
			}

			// Invoke pre-render lifecycle methods
			if (isNew) {
				if (newType.getDerivedStateFromProps==null && c.componentWillMount!=null) c.componentWillMount();
				if (c.componentDidMount!=null) mounts.push(c);
			}
			else {
				if (!c._force && c.shouldComponentUpdate!=null && c.shouldComponentUpdate(newVNode.props, s, cctx)===false) {
					c._dirty = false;
					break outer;
				}
				if (newType.getDerivedStateFromProps==null && c._force==null && c.componentWillReceiveProps!=null) {
					c.componentWillReceiveProps(newVNode.props, cctx);
				}

				if (c.componentWillUpdate!=null) {
					c.componentWillUpdate(newVNode.props, s, cctx);
				}
			}

			oldProps = c.props;
			if (!oldState) oldState = c.state;

			oldContext = c.context = cctx;
			c.props = newVNode.props;
			c.state = s;

			if (options.beforeRender) options.beforeRender(newVNode);

			let prev = c._prevVNode;
			let vnode = c._prevVNode = coerceToVNode(c.render(c.props, c.state, c.context));
			c._dirty = false;

			if (c.getChildContext!=null) {
				context = assign(assign({}, context), c.getChildContext());
			}

			if (!isNew && c.getSnapshotBeforeUpdate!=null) {
				oldContext = c.getSnapshotBeforeUpdate(oldProps, oldState);
			}

			c.base = dom = diff(dom, parentDom, vnode, prev, context, isSvg, excessDomChildren, mounts, c);

			if (vnode!=null) {
				// If this component returns a Fragment (or another component that
				// returns a Fragment), then _lastDomChild will be non-null,
				// informing `diffChildren` to diff this component's VNode like a Fragemnt
				newVNode._lastDomChild = vnode._lastDomChild;
			}

			c._parentDom = parentDom;

			if (newVNode.ref) applyRef(newVNode.ref, c, ancestorComponent);
		}
		else {
			dom = diffElementNodes(dom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent);

			if (newVNode.ref && (oldVNode.ref !== newVNode.ref)) {
				applyRef(newVNode.ref, dom, ancestorComponent);
			}
		}

		newVNode._dom = dom;

		if (c!=null) {
			while (p=c._renderCallbacks.pop()) p();

			// Don't call componentDidUpdate on mount or when we bailed out via
			// `shouldComponentUpdate`
			if (!isNew && oldProps!=null && c.componentDidUpdate!=null) {
				c.componentDidUpdate(oldProps, oldState, oldContext);
			}
		}

		if (clearProcessingException) {
			c._processingException = null;
		}

		if (options.afterDiff) options.afterDiff(newVNode);
	}
	catch (e) {
		catchErrorInComponent(e, ancestorComponent);
	}

	return dom;
}

export function commitRoot(mounts, root) {
	let c;
	while ((c = mounts.pop())) {
		try {
			c.componentDidMount();
		}
		catch (e) {
			catchErrorInComponent(e, c._ancestorComponent);
		}
	}

	if (options.commitRoot) options.commitRoot(root);
}

/**
 * Diff two virtual nodes representing DOM element
 * @param {import('../internal').PreactElement} dom The DOM element representing
 * the virtual nodes being diffed
 * @param {import('../internal').VNode} newVNode The new virtual node
 * @param {import('../internal').VNode} oldVNode The old virtual node
 * @param {object} context The current context object
 * @param {boolean} isSvg Whether or not this DOM node is an SVG node
 * @param {*} excessDomChildren
 * @param {Array<import('../internal').Component>} mounts An array of newly
 * mounted components
 * @param {import('../internal').Component} ancestorComponent The parent
 * component to the ones being diffed
 * @returns {import('../internal').PreactElement}
 */
function diffElementNodes(dom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent) {
	let d = dom;

	// Tracks entering and exiting SVG namespace when descending through the tree.
	isSvg = isSvg ? newVNode.type !== 'foreignObject' : newVNode.type === 'svg';

	if (dom==null && excessDomChildren!=null) {
		for (let i=0; i<excessDomChildren.length; i++) {
			const child = excessDomChildren[i];
			if (child!=null && (newVNode.type===null ? child.nodeType===3 : child.localName===newVNode.type)) {
				dom = child;
				excessDomChildren[i] = null;
				break;
			}
		}
	}

	if (dom==null) {
		dom = newVNode.type===null ? document.createTextNode(newVNode.text) : isSvg ? document.createElementNS('http://www.w3.org/2000/svg', newVNode.type) : document.createElement(newVNode.type);

		// we created a new parent, so none of the previously attached children can be reused:
		excessDomChildren = null;
	}
	newVNode._dom = dom;

	if (newVNode.type===null) {
		if ((d===null || dom===d) && newVNode.text!==oldVNode.text) {
			dom.data = newVNode.text;
		}
	}
	else {
		if (excessDomChildren!=null && dom.childNodes!=null) {
			excessDomChildren = EMPTY_ARR.slice.call(dom.childNodes);
		}
		if (newVNode!==oldVNode) {
			let oldProps = oldVNode.props;
			// if we're hydrating, use the element's attributes as its current props:
			if (oldProps==null) {
				oldProps = {};
				if (excessDomChildren!=null) {
					for (let i=0; i<dom.attributes.length; i++) {
						oldProps[dom.attributes[i].name] = dom.attributes[i].value;
					}
				}
			}
			diffProps(dom, newVNode.props, oldProps, isSvg);
		}

		diffChildren(dom, newVNode, oldVNode, context, isSvg, excessDomChildren, mounts, ancestorComponent);
	}

	return dom;
}

/**
 * Invoke or update a ref, depending on whether it is a function or object ref.
 * @param {object|function} [ref=null]
 * @param {any} [value]
 */
export function applyRef(ref, value, ancestorComponent) {
	try {
		if (typeof ref=='function') ref(value);
		else ref.current = value;
	}
	catch (e) {
		catchErrorInComponent(e, ancestorComponent);
	}
}

/**
 * Unmount a virtual node from the tree and apply DOM changes
 * @param {import('../internal').VNode} vnode The virtual node to unmount
 * @param {import('../internal').Component} ancestorComponent The parent
 * component to this virtual node
 */
export function unmount(vnode, ancestorComponent) {
	let r;
	if (options.beforeUnmount) options.beforeUnmount(vnode);

	if (r = vnode.ref) {
		applyRef(r, null, ancestorComponent);
	}

	if ((r = vnode._dom)!=null) r.remove();

	vnode._dom = vnode._lastDomChild = null;

	if ((r = vnode._component)!=null) {
		if (r.componentWillUnmount) {
			try {
				r.componentWillUnmount();
			}
			catch (e) {
				catchErrorInComponent(e, ancestorComponent);
			}
		}

		r.base = r._parentDom = null;
		if (r = r._prevVNode) unmount(r, ancestorComponent);
	}
	else if (r = vnode._children) {
		for (let i = 0; i < r.length; i++) {
			unmount(r[i], ancestorComponent);
		}
	}
}

/** The `.render()` method for a PFC backing instance. */
function doRender(props, state, context) {
	return this.constructor(props, context);
}

/**
 * Find the closest error boundary to a thrown error and call it
 * @param {object} error The thrown value
 * @param {import('../internal').Component} component The first ancestor
 * component check for error boundary behaviors
 */
function catchErrorInComponent(error, component) {
	for (; component; component = component._ancestorComponent) {
		if (!component._processingException) {
			try {
				if (component.constructor.getDerivedStateFromError!=null) {
					component.setState(component.constructor.getDerivedStateFromError(error));
				}
				else if (component.componentDidCatch!=null) {
					component.componentDidCatch(error);
				}
				else {
					continue;
				}
				return enqueueRender(component._processingException = component);
			}
			catch (e) {
				error = e;
			}
		}
	}
	throw error;
}
<|endoftext|>


<commit_before>App = Ember.Application.create();

App.ApplicationView = Ember.View.extend({
  templateName: 'application'
});
App.ApplicationController = Ember.Controller.extend();

// Index view to display all posts on the page
App.AllPostsView = Ember.View.extend({
  tagName: "ul",
  templateName: 'post-list-view'
});

// Create new post text field. Separate view to be able to bind events
App.CreatePostView = Ember.TextField.extend(Ember.TargetActionSupport, {
  valueBinding: 'App.PostsController.postBody',

  insertNewline: function() {
    this.triggerAction();
  }
})

// View to display single post. Post has following subviews (defined below):
//  - link to show a comment form
//  - form to add a new comment
App.PostContainerView = Ember.View.extend({
  tagName: "li",
  templateName: 'post-view',
  isFormVisible: true,

  toggleVisibility: function(){
    this.toggleProperty('isFormVisible');
  }
});

// TODO: create view for CommentContainer and AllCommentsView
// App.CommentContainer = Ember.View.extend({
//   tagName: "li",
//   templateName: 'comment-view'
// });

// Create new post text field. Separate view to be able to bind events
App.CommentPostView = Ember.View.extend(Ember.TargetActionSupport, {
  tagName: "a",

  click: function() {
    this.triggerAction();
  }
})

// Text field to post a comment. Separate view to make it hideable
App.CommentForm = Ember.View.extend({
  // I'd no success to use isVisibleBinding property...
  classNameBindings: 'isVisible visible:invisible',
  bound: {
    body: '',
  },

  isVisible: function() {
    return this.get('parentView.isFormVisible') == true;
  }.property('parentView.isFormVisible'),

  submitComment: function() {
    if (this.bound.body) {
      var post = this.bindingContext;
      App.CommentsController.createComment(post, this.bound.body)
      this.bound.body.clear = ''
    }
  }
});

// Create new post text field. Separate view to be able to bind events
App.CreateCommentView = Ember.TextField.extend(Ember.TargetActionSupport, {
  insertNewline: function() {
    this.triggerAction();
  }
})

// Separate page for a single post
App.OnePostController = Ember.ObjectController.extend();
App.OnePostView = Ember.View.extend({
  templateName: 'a-post'
});

App.Comment = Ember.Object.extend({
  body: null,
  created_at: null,
  user: null
});

App.CommentsController = Ember.ArrayController.create({
  createComment: function(post, body) {
    var comment = App.Comment.create({
      body: body,
      post_id: post.id
    });

    $.ajax({
      url: '/v1/comments',
      type: 'post',
      data: { body: body, post_id: post.id }, // XXX: we've already defined a model above
      context: comment,
      success: function(response) {
        this.setProperties(response);
        post.comments.pushObject(comment)
        // App.PostsController.insertAt(0, comments)
      }
    })
    return comment;
  }
})

App.Post = Ember.Object.extend({
  body: null,
  created_at: null,
  comment: [],
  user: null
});

App.PostsController = Ember.ArrayController.create({
  content: [],
  postBody: '',

  // XXX: a bit strange having this method here.
  submitPost: function() {
    if (this.postBody) {
      App.PostsController.createPost(this.postBody);
      this.postBody = ''
    }
  },

  createPost: function(body) {
    var post = App.Post.create({
      body: body
    });

    $.ajax({
      url: '/v1/posts',
      type: 'post',
      data: { body: body }, // XXX: we've already defined a model above
      context: post,
      success: function(response) {
        this.setProperties(response);
        App.PostsController.insertAt(0, post)
      }
    })
    return post;
  },

  find: function() {
    // clear posts in content or whatever variable
    $.ajax({
      url: '/v1/timeline/anonymous',
      dataType: 'jsonp',
      context: this,
      success: function(response){
        response.forEach(function(attrs) {
          var post = App.Post.create(attrs)
          this.pushObject(post)
        }, this)
      }
    })
    return this
  },

  findOne: function(postId) {
    var post = App.Post.create({
      id: postId
    });

    $.ajax({
      url: '/v1/posts/' + postId,
      dataType: 'jsonp',
      context: post,
      success: function(response){
        this.setProperties(response)
      }
    })
    return post;
  }
})

App.Router = Ember.Router.extend({
  enableLogging: true,

  root: Ember.Route.extend({
    posts: Ember.Route.extend({
      route: '/',

      showPost: Ember.Route.transitionTo('aPost'),

      connectOutlets: function(router){
        router.get('applicationController').connectOutlet('allPosts', App.PostsController.find());
      }
    }),

    aPost: Ember.Route.extend({
      route: '/:postId',

      showAllPosts: Ember.Route.transitionTo('posts'),

      connectOutlets: function(router, context) {
        router.get('applicationController').connectOutlet('onePost', context);
      },

      serialize: function(router, context){
        return {postId: context.get('id')}
      },

      deserialize: function(router, urlParams) {
        return App.PostsController.findOne(urlParams.postId);
      }
    })
  })
});

App.initialize();

<commit_msg>Clears posts collection before pushing new entring into it.<commit_after>App = Ember.Application.create();

App.ApplicationView = Ember.View.extend({
  templateName: 'application'
});
App.ApplicationController = Ember.Controller.extend();

// Index view to display all posts on the page
App.AllPostsView = Ember.View.extend({
  tagName: "ul",
  templateName: 'post-list-view'
});

// Create new post text field. Separate view to be able to bind events
App.CreatePostView = Ember.TextField.extend(Ember.TargetActionSupport, {
  // TODO: Extract value from controller
  valueBinding: 'App.PostsController.postBody',

  insertNewline: function() {
    this.triggerAction();
  }
})

// View to display single post. Post has following subviews (defined below):
//  - link to show a comment form
//  - form to add a new comment
App.PostContainerView = Ember.View.extend({
  tagName: "li",
  templateName: 'post-view',
  isFormVisible: false,

  toggleVisibility: function(){
    this.toggleProperty('isFormVisible');
  }
});

// TODO: create view for CommentContainer and AllCommentsView
// App.CommentContainer = Ember.View.extend({
//   tagName: "li",
//   templateName: 'comment-view'
// });

// Create new post text field. Separate view to be able to bind events
App.CommentPostView = Ember.View.extend(Ember.TargetActionSupport, {
  tagName: "a",

  click: function() {
    this.triggerAction();
  }
})

// Text field to post a comment. Separate view to make it hideable
App.CommentForm = Ember.View.extend({
  // I'd no success to use isVisibleBinding property...
  classNameBindings: 'isVisible visible:invisible',
  bound: {
    body: '',
  },

  isVisible: function() {
    return this.get('parentView.isFormVisible') == true;
  }.property('parentView.isFormVisible'),

  submitComment: function() {
    if (this.bound.body) {
      var post = this.bindingContext;
      App.CommentsController.createComment(post, this.bound.body)
      this.bound.body.clear = ''
    }
  }
});

// Create new post text field. Separate view to be able to bind events
App.CreateCommentView = Ember.TextField.extend(Ember.TargetActionSupport, {
  insertNewline: function() {
    this.triggerAction();
  }
})

// Separate page for a single post
App.OnePostController = Ember.ObjectController.extend();
App.OnePostView = Ember.View.extend({
  templateName: 'a-post'
});

App.Comment = Ember.Object.extend({
  body: null,
  created_at: null,
  user: null
});

App.CommentsController = Ember.ArrayController.create({
  createComment: function(post, body) {
    var comment = App.Comment.create({
      body: body,
      post_id: post.id
    });

    $.ajax({
      url: '/v1/comments',
      type: 'post',
      data: { body: body, post_id: post.id }, // XXX: we've already defined a model above
      context: comment,
      success: function(response) {
        this.setProperties(response);
        post.comments.pushObject(comment)
        // App.PostsController.insertAt(0, comments)
      }
    })
    return comment;
  }
})

App.Post = Ember.Object.extend({
  body: null,
  created_at: null,
  comments: [],
  user: null
});

App.PostsController = Ember.ArrayController.create({
  content: [],
  postBody: '',

  // XXX: a bit strange having this method here.
  submitPost: function() {
    if (this.postBody) {
      App.PostsController.createPost(this.postBody);
      this.postBody = ''
    }
  },

  createPost: function(body) {
    var post = App.Post.create({
      body: body
    });

    $.ajax({
      url: '/v1/posts',
      type: 'post',
      data: { body: body }, // XXX: we've already defined a model above
      context: post,
      success: function(response) {
        this.setProperties(response);
        App.PostsController.insertAt(0, post)
      }
    })
    return post;
  },

  find: function() {
    this.set('content', [])

    $.ajax({
      url: '/v1/timeline/anonymous',
      dataType: 'jsonp',
      context: this,
      success: function(response){
        App.PostsController.content = []
        response.forEach(function(attrs) {
          var post = App.Post.create(attrs)
          this.pushObject(post)
        }, this)
      }
    })
    return this
  },

  findOne: function(postId) {
    var post = App.Post.create({
      id: postId
    });

    $.ajax({
      url: '/v1/posts/' + postId,
      dataType: 'jsonp',
      context: post,
      success: function(response){
        this.setProperties(response)
      }
    })
    return post;
  }
})

App.Router = Ember.Router.extend({
  enableLogging: true,

  root: Ember.Route.extend({
    posts: Ember.Route.extend({
      route: '/',

      showPost: Ember.Route.transitionTo('aPost'),

      connectOutlets: function(router){
        router.get('applicationController').connectOutlet('allPosts', App.PostsController.find());
      }
    }),

    aPost: Ember.Route.extend({
      route: '/:postId',

      showAllPosts: Ember.Route.transitionTo('posts'),

      connectOutlets: function(router, context) {
        router.get('applicationController').connectOutlet('onePost', context);
      },

      serialize: function(router, context){
        return {postId: context.get('id')}
      },

      deserialize: function(router, urlParams) {
        return App.PostsController.findOne(urlParams.postId);
      }
    })
  })
});

App.initialize();

<|endoftext|>


<commit_before>var socket = io.connect(window.location.hostname);
var markers = [];
var pause = true;
var photo = false;
var total = 0;
var map = null;

function initialize() {
	var mapOptions = {
		center: new google.maps.LatLng(25, 0),
		zoom: 3,
		panControl: false,
		streetViewControl: false,
		mapTypeControl: false
	};
	map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);

function display_tweet(tweet) {
	if (pause === false)
	{
		total = total + 1;
		$('#total').text(total);

		var marker = new google.maps.Marker({
			position: new google.maps.LatLng(tweet.geo[0],tweet.geo[1]),
			animation: google.maps.Animation.DROP,
			map: map
		});
		markers.push(marker);

		if (photo)
		{
			var infowindow = new google.maps.InfoWindow({
				content: '
@' + tweet.twittos + '',
				maxWidth: 140
			});
			infowindow.open(map,marker);
		}
		else
		{
			var infowindow = new google.maps.InfoWindow({
				content: '@' + tweet.twittos + '
' + tweet.tweet,
				maxWidth: 140
			});
		}

		google.maps.event.addListener(marker, 'click', function() {
			infowindow.open(map,marker);
		});
	}
};

function reset()
{
	for (var i = 0; i < markers.length; i++ ) {
		markers[i].setMap(null);
	}
	markers.length = 0;
	total = 0;
	$('#total').text(0);
}

socket.on('tweet', function(tweet) {
	if ((photo && tweet.media) || !photo)
		display_tweet(tweet);
});

$('#pause').click(function() {
	if (pause)
		$('#pause').text('STOP');
	else
		$('#pause').text('START');
	pause = !pause;
	return false;
});

$('#reset').click(function() {
	reset();
	return false;
});

$('#type-all').click(function() {
	reset();
	photo = false;
});

$('#type-photos').click(function() {
	reset();
	photo = true;
});
<commit_msg>Remove temp file<commit_after><|endoftext|>


<commit_before>/**
 * React Static Boilerplate
 * https://github.com/kriasoft/react-static-boilerplate
 *
 * Copyright © 2015-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { PropTypes } from 'react';
import Layout from '../../components/Layout';
import Footer from '../../components/Footer';
import s from './styles.css';
import { title, html } from './index.md';

class HomePage extends React.Component {

  static propTypes = {
    articles: PropTypes.arrayOf(PropTypes.shape({
      url: PropTypes.string.isRequired,
      title: PropTypes.string.isRequired,
      author: PropTypes.string.isRequired,
    }).isRequired).isRequired,
  };

  componentDidMount() {
    document.title = title;
  }

  render() {
    let styleSkillSymfony = {
      width: '90%'
    };
    let styleSkillAngular = {
      width: '70%'
    };
    let styleSkillReact = {
      width: '25%'
    };

    let styleSkillMySQL = {
      width: '90%'
    };
    let styleSkillElasticSearch = {
      width: '60%'
    };
    let styleSkillRedis = {
      width: '70%'
    };
    let styleSkillMongoDB = {
      width: '50%'
    };

    let styleSkillOOP = {
      width: '80%'
    };
    let styleSkillSolid = {
      width: '80%'
    };
    let styleSkillDesignPattern = {
      width: '70%'
    };
    let styleSkillDDD = {
      width: '80%'
    };
    let styleSkillSOA = {
      width: '70%'
    };

    return (
      <Layout className={s.content}>

                                Humility

Always something to learn

                                Team Management

Growing TeamPlay

                                Coaching

Knowledge sharing

                                Quality Assurance

Unit/Functional Testing

                                REST API

Aiming for Interoperability

                                Software Architecture

Reducing technical debt

                                DevOps

AdminSys / Docker / Linux

                                Min Viable Product

So business can experiment

                                Disruptive

Using technology to thrive

Web Framework

Symfony 4 PHP7

Angular 4 (AoT/Redux)Javascript

ReactJavascript

Database

MySQL MariaDB

ElasticSearch NoSQL

Redis NoSQL

Mongo DB NoSQL

Architecture

Object-Oriented Programming

S.O.L.I.D.

Design Pattern

Domain Driven Design DDD

Service Oriented Architecture SOA

Location : Marseille (France)

Currently Learning : Event Storming

      </Layout>
    );
  }

}

export default HomePage;
<commit_msg>Rephrase SOA<commit_after>/**
 * React Static Boilerplate
 * https://github.com/kriasoft/react-static-boilerplate
 *
 * Copyright © 2015-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { PropTypes } from 'react';
import Layout from '../../components/Layout';
import Footer from '../../components/Footer';
import s from './styles.css';
import { title, html } from './index.md';

class HomePage extends React.Component {

  static propTypes = {
    articles: PropTypes.arrayOf(PropTypes.shape({
      url: PropTypes.string.isRequired,
      title: PropTypes.string.isRequired,
      author: PropTypes.string.isRequired,
    }).isRequired).isRequired,
  };

  componentDidMount() {
    document.title = title;
  }

  render() {
    let styleSkillSymfony = {
      width: '90%'
    };
    let styleSkillAngular = {
      width: '70%'
    };
    let styleSkillReact = {
      width: '25%'
    };

    let styleSkillMySQL = {
      width: '90%'
    };
    let styleSkillElasticSearch = {
      width: '60%'
    };
    let styleSkillRedis = {
      width: '70%'
    };
    let styleSkillMongoDB = {
      width: '50%'
    };

    let styleSkillOOP = {
      width: '80%'
    };
    let styleSkillSolid = {
      width: '80%'
    };
    let styleSkillDesignPattern = {
      width: '70%'
    };
    let styleSkillDDD = {
      width: '80%'
    };
    let styleSkillMicroService = {
      width: '70%'
    };

    return (
      <Layout className={s.content}>

                                Humility

Always something to learn

                                Team Management

Growing TeamPlay

                                Coaching

Knowledge sharing

                                Quality Assurance

Unit/Functional Testing

                                REST API

Aiming for Interoperability

                                Software Architecture

Reducing technical debt

                                DevOps

AdminSys / Docker / Linux

                                Min Viable Product

So business can experiment

                                Disruptive

Using technology to thrive

Web Framework

Symfony 4 PHP7

Angular 4 (AoT/Redux)Javascript

ReactJavascript

Database

MySQL MariaDB

ElasticSearch NoSQL

Redis NoSQL

Mongo DB NoSQL

Architecture

Object-Oriented Programming

S.O.L.I.D.

Design Pattern

Domain Driven Design DDD

Micro Service and controlled Monolith too

Location : Marseille (France)

Currently Learning : Event Storming

      </Layout>
    );
  }

}

export default HomePage;
<|endoftext|>


<commit_before>angular.module('bens-penhorados-filters', []).filter('vehicleCondition', function() {
    return function(goodCondition) {
        if (goodCondition === true) {
            return 'Bom/Razoável';
        }
        if (goodCondition === false) {
            return 'Mau';
        }
    }
}).filter('generateLink', function() {
    var base_url = 'http://www.e-financas.gov.pt/vendas/detalheVenda.action';
    return function(code) {
        if (code) {
            var values = code.split('.');
            return base_url + '?sf=' + values[0] + '&ano=' + values[1] + '&idVenda=' + values[2];
        }
    }
}).filter('range', function() {
    return function([], min, max) {
        var range = [];
        min = parseInt(min);
        max = parseInt(max);
        for (var i = max; i >= min; i--) {
            range.push(i);
        }
        return range;
    };
}).filter('phonenumber', function() {
    return function(number, prefix) {
        if (number) {
            number = number.toString().split(/(\d{3})/).join(' ').trim();
            return '(+' + prefix + ') ' + number;
        }
    };
}).filter('resultTitle', function() {
    return function(title) {
        if (title) {
            return title.replace(/(\d+\.\d+\.\d+\s-\s)/, '');
        }
    };
});<commit_msg>Update filters.js<commit_after>angular.module('bens-penhorados-filters', []).filter('vehicleCondition', function() {
    return function(goodCondition) {
        if (goodCondition === true) {
            return 'Bom/Razoável';
        }
        if (goodCondition === false) {
            return 'Mau';
        }
    }
}).filter('generateLink', function() {
    var base_url = 'http://www.e-financas.gov.pt/vendas/detalheVenda.action';
    return function(code) {
        if (code) {
            var values = code.split('.');
            return base_url + '?sf=' + values[0] + '&ano=' + values[1] + '&idVenda=' + values[2];
        }
    }
}).filter('range', function() {
    return function(min, max) {
        var range = [];
        min = parseInt(min);
        max = parseInt(max);
        for (var i = max; i >= min; i--) {
            range.push(i);
        }
        return range;
    };
}).filter('phonenumber', function() {
    return function(number, prefix) {
        if (number) {
            number = number.toString().split(/(\d{3})/).join(' ').trim();
            return '(+' + prefix + ') ' + number;
        }
    };
}).filter('resultTitle', function() {
    return function(title) {
        if (title) {
            return title.replace(/(\d+\.\d+\.\d+\s-\s)/, '');
        }
    };
});
<|endoftext|>


<commit_before>define(['jquery', 'toastr', 'jquery.blockui'], function ($, toastr) {
  var globals = {
    constants: {
      failureTitle: 'Server Error',
      failureMessage: 'There has been a catastrophic error with:',
      validationTitle: 'Invalid',
      informationTitle: 'Information',
      validationMessage: 'Please correct the invalid fields before submitting',
      successTitle: 'Hurrah!',
      successMessage: 'Completed successfully :)',
      urls: {
        packTree: 'PackReportTree',
        packs: 'Pack',
        elmah: 'ElmahSearch',
        environments: 'Environment',
        attributes: 'Attribute',
        reports: 'Report',
        desktops: 'Desktop',
        apiRoutes: 'ApiRoute',
        userDetails: 'UserDetail',
        catalogueItemPackEnvironments: 'CatalogueItemPackEnvironment',
        entities: 'Entity',
        entityAttributesFlatList: 'EntityAttributesFlatList',
        entityAttributes: 'EntityAttribute',
        entityAssociations: 'EntityAssociation',
        attributeDataTypeLookup: 'AttributeDataTypeLookup',
        lookupVariableParameter: 'LookupVariableParameter',
        lookup: "lookup",
        actionPlanTaskTypes: "ActionPlanTaskType",
        catalogueItemPacks: 'CatalogueItemPack',
        packEnvironments: 'PackEnvironment',
        roles: 'Role',
        roleEntityAssociations: 'RoleEntityAssociation',
        roleEntities: 'RoleEntity',
        roleRouteApiAssociations: 'ApiRouteRoleAssociation',
        syncLocations: 'offlinesynclocation',
        syncAudits: 'offlinesyncaudit',
        offlineLocation: 'offlinelocation',
        tags: 'Tag',
        tagTree: 'TagTree',
        locations: 'Location',
        locationTree: 'LocationTree',
        locationTreeMoveChildren: 'LocationTreeMoveChildren',
        lookupGroups: 'LookupVariableParameter',
        lookupGroupTree: 'LookupGroupTree',
        dataType: "attributedatatypelookup",
        syncState: "SyncState"
      }
    },
    errorMessage: function (title, message) {
      var t = title || globals.constants.failureTitle;
      var m = message || globals.constants.failureMessage;
      toastr['error'](m, t);
    },
    validationMessage: function (title, message) {
      var t = title || globals.constants.validationTitle;
      var m = message || globals.constants.validationMessage;
      toastr['warning'](m, t);
    },
    infoMessage: function (title, message) {
      var t = title; // || globals.constants.informationTitle;
      var m = message;
      toastr.info(m, t);
    },
    successMessage: function (title, message) {
      var t = title || globals.constants.successTitle;
      var m = message || globals.constants.successMessage;
      toastr['success'](m, t);
    },

    blockUI: function(element) {
      if (element) {
        $(element).block({
            message: ''
        });
      } else {
        $.blockUI({
            message: ''
        });
      }
    },
    unblockUI: function(element) {
      if (element) {
          $(element).unblock();
      } else {
          $.unblockUI();
      }
    }
  };

  // toastr global options
  toastr.options = {
    "closeButton": true,
    "debug": false,
    "positionClass": "toast-top-right",
    "onclick": null,
    "showDuration": "50",
    "hideDuration": "50",
    "timeOut": "5000",
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
  };

  return globals;
});
<commit_msg>Delete global.js<commit_after><|endoftext|>


<commit_before>var firstImages = 0;
$(document).ready(function() {
    document.addEventListener('touchmove', function(e) {
        e.preventDefault();
    }, false);

    var gallery,
    el,
    span,
    i,
    page,
    slides = []
    ;

    gallery = new SwipeView('#wrapper', {numberOfPages: slides.length,loop: false});

    // Load initial data
    for (i = 0; i < 3; i++) {
        page = i == 0 ? slides.length - 1 : i - 1;

        el = $(_.template($('#gallery-page').html())());
        $(gallery.masterPages[i]).append(el);

        el.find("#gallery-img").load(function() {this.className='';});
    }

    var detailsTemplate = $('#details-template').html();
    function setDetails(details, item) {
        details.html(_.template(detailsTemplate, item, {variable:"item"}));
    }

    function putSlideAt(upcoming, i) {
        var slide = slides[upcoming] ? slides[upcoming] : {width: 250,height: 250,item:{url: ""}};

        var page = $(gallery.masterPages[i]);
        var htmlSpan = page.find("#htmlSpan");
        var img = page.find("#gallery-img");

        if (slide.html) {
            img.hide();
            htmlSpan.show();
            htmlSpan.html(slide.html);
        } else {
            htmlSpan.hide();
            img.show();
            img.attr('src', slide.url)
            .attr('className', 'loading')
            .width(slide.width)
            .height(slide.height)
            .data('orig-width', slide.width)
            .data('orig-height', slide.height)
            .data('orig-top', null) // Need to set a null so that it can be persisted.  Can't data set undefined although it's the beginning state
            ;
        }

        setDetails(page.find("#details"), slide.item);
    }

    gallery.onFlip(function() {
        var el,
        upcoming,
        i;

        for (i = 0; i < 3; i++) {
            upcoming = gallery.masterPages[i].dataset.upcomingPageIndex;

            if (upcoming != gallery.masterPages[i].dataset.pageIndex) {
                putSlideAt(upcoming, i);
            }
        }
    });

    gallery.onMoveOut(function() {
        gallery.masterPages[gallery.currentMasterPage].className = gallery.masterPages[gallery.currentMasterPage].className.replace(/(^|\s)swipeview-active(\s|$)/, '');
    });

    gallery.onMoveIn(function() {
        var className = gallery.masterPages[gallery.currentMasterPage].className;
        /(^|\s)swipeview-active(\s|$)/.test(className) || (gallery.masterPages[gallery.currentMasterPage].className = !className ? 'swipeview-active' : className + ' swipeview-active');
    });
    var respondToKeys = true;
    $(document).keydown(function(event) {
        if (!respondToKeys)
            return;

        function resetImageSize() {
            img.width(img.data('orig-width'));
            img.height(img.data('orig-height'));
            var origTop = img.data('orig-top');
            if (null != origTop) {
                img.offset({top: origTop});
                img.data('orig-top', null);
            }
        }

        var img = $(gallery.masterPages[gallery.currentMasterPage]).find("#gallery-img");
        function advanceImg() {
            resetImageSize();
            picFetcher.getMorePosts(); // TODO: rely on throttling for now.  Find a better way!
            if (!gallery.next()) {
            // TODO: Show some kind of loading screen... maybe let it advance 1 and then replace it as the image comes in
            }
        }
        var jCode = 74, kCode = 75, lCode = 76, aCode = 65, sCode = 83, dCode = 68, spaceCode = 32;
        switch (event.which) {
            case jCode:
            case aCode:
                advanceImg();
                break;

            case kCode:
            case sCode:
                resetImageSize();
                gallery.prev();
                break;

            case spaceCode:
                if (null == img.data('orig-top')) {
                    img.data('orig-top', img.offset().top);
                }

                var imgBottom = img.offset().top + img.height(),
                bottomOffScreen = $(window).height() < imgBottom;
                if (bottomOffScreen) {
                    img.offset({top: img.offset().top - $(window).height()});
                } else {
                    advanceImg();
                }
                //TODO: make these more easily pageable by an integer number of times
                // TODO: advance down the image if it's super tall, advance to next if we're at the bottom / it was already visible
                break;

            case dCode:
            case lCode:
                var zoomed = img.width() != img.data('orig-width');
                if (zoomed) {
                    img.width(img.data('orig-width'));
                    img.height(img.data('orig-height'));
                } else {
                    if (null != img.data('orig-top')) {
                        img.offset({top: img.data('orig-top')})
                    }

                    var maxHeight = $(window).height() - 30;
                    if (maxHeight < img.height()) {
                        img.width(img.width() * maxHeight / img.height());
                        img.height(maxHeight);
                    }
                }
                break;

                break;
        }
    });

    function addSlide(slide) {
        var newPageI = gallery.options.numberOfPages;

        gallery.updatePageCount(newPageI + 1);
        slides.push(slide);
        if (1 == firstImages) {
            putSlideAt(1, 2);
            firstImages++;
        } else if (0 == firstImages) {
            putSlideAt(0, 1);
            firstImages++;
        }
    }

    var onlineMode = window.location.toString().split("#")[1] != "test";
    picFetcher = new reddit.PicFetcher({onlineMode: onlineMode,
                                        imgFn: function(img, w, h, advanceToNext) {
                                                    addSlide({url: img.url, width: w, height: h, item: img});
                                                },
                                        htmlFn: function (item, html) {
                                                    addSlide({html: html, item: item});
                                        },
                                        });
    picFetcher.setSubreddits(getSubreddits());

    function start() {
        picFetcher.getMorePosts()
    }
    var startDelay = onlineMode ? 0 : 100;
    setTimeout(start, startDelay);

    function getSubreddits() {
        var reddits = window.location.toString().split("?")[1];
        if (undefined == reddits)
            return (["all"])
        return (reddits.split("+"))
    }

    // TODO: Tie into actual settings
    var configHtml = _.template($('#settings-modal').html())();
    $('#wrapper').avgrund({
        height: 400,
        holderClass: 'custom',
        showClose: true,
        showCloseText: 'OK',
        enableStackAnimation: true,
        onBlurContainer: '.container',
        template: configHtml,
        onActivate: function() {
            respondToKeys = false
        },
        onDeactivate: function() {
            respondToKeys = true
        },
    });
// end document ready
});<commit_msg>Remove extra params<commit_after>var firstImages = 0;
$(document).ready(function() {
    document.addEventListener('touchmove', function(e) {
        e.preventDefault();
    }, false);

    var gallery,
    el,
    span,
    i,
    page,
    slides = []
    ;

    gallery = new SwipeView('#wrapper', {numberOfPages: slides.length,loop: false});

    // Load initial data
    for (i = 0; i < 3; i++) {
        page = i == 0 ? slides.length - 1 : i - 1;

        el = $($('#gallery-page').html());
        $(gallery.masterPages[i]).append(el);

        el.find("#gallery-img").load(function() {this.className='';});
    }

    var detailsTemplate = $('#details-template').html();
    function setDetails(details, item) {
        details.html(_.template(detailsTemplate, item, {variable:"item"}));
    }

    function putSlideAt(upcoming, i) {
        var slide = slides[upcoming] ? slides[upcoming] : {width: 250,height: 250,item:{url: ""}};

        var page = $(gallery.masterPages[i]);
        var htmlSpan = page.find("#htmlSpan");
        var img = page.find("#gallery-img");

        if (slide.html) {
            img.hide();
            htmlSpan.show();
            htmlSpan.html(slide.html);
        } else {
            htmlSpan.hide();
            img.show();
            img.attr('src', slide.url)
            .attr('className', 'loading')
            .width(slide.width)
            .height(slide.height)
            .data('orig-width', slide.width)
            .data('orig-height', slide.height)
            .data('orig-top', null) // Need to set a null so that it can be persisted.  Can't data set undefined although it's the beginning state
            ;
        }

        setDetails(page.find("#details"), slide.item);
    }

    gallery.onFlip(function() {
        var el,
        upcoming,
        i;

        for (i = 0; i < 3; i++) {
            upcoming = gallery.masterPages[i].dataset.upcomingPageIndex;

            if (upcoming != gallery.masterPages[i].dataset.pageIndex) {
                putSlideAt(upcoming, i);
            }
        }
    });

    gallery.onMoveOut(function() {
        gallery.masterPages[gallery.currentMasterPage].className = gallery.masterPages[gallery.currentMasterPage].className.replace(/(^|\s)swipeview-active(\s|$)/, '');
    });

    gallery.onMoveIn(function() {
        var className = gallery.masterPages[gallery.currentMasterPage].className;
        /(^|\s)swipeview-active(\s|$)/.test(className) || (gallery.masterPages[gallery.currentMasterPage].className = !className ? 'swipeview-active' : className + ' swipeview-active');
    });
    var respondToKeys = true;
    $(document).keydown(function(event) {
        if (!respondToKeys)
            return;

        function resetImageSize() {
            img.width(img.data('orig-width'));
            img.height(img.data('orig-height'));
            var origTop = img.data('orig-top');
            if (null != origTop) {
                img.offset({top: origTop});
                img.data('orig-top', null);
            }
        }

        var img = $(gallery.masterPages[gallery.currentMasterPage]).find("#gallery-img");
        function advanceImg() {
            resetImageSize();
            picFetcher.getMorePosts(); // TODO: rely on throttling for now.  Find a better way!
            if (!gallery.next()) {
            // TODO: Show some kind of loading screen... maybe let it advance 1 and then replace it as the image comes in
            }
        }
        var jCode = 74, kCode = 75, lCode = 76, aCode = 65, sCode = 83, dCode = 68, spaceCode = 32;
        switch (event.which) {
            case jCode:
            case aCode:
                advanceImg();
                break;

            case kCode:
            case sCode:
                resetImageSize();
                gallery.prev();
                break;

            case spaceCode:
                if (null == img.data('orig-top')) {
                    img.data('orig-top', img.offset().top);
                }

                var imgBottom = img.offset().top + img.height(),
                bottomOffScreen = $(window).height() < imgBottom;
                if (bottomOffScreen) {
                    img.offset({top: img.offset().top - $(window).height()});
                } else {
                    advanceImg();
                }
                //TODO: make these more easily pageable by an integer number of times
                // TODO: advance down the image if it's super tall, advance to next if we're at the bottom / it was already visible
                break;

            case dCode:
            case lCode:
                var zoomed = img.width() != img.data('orig-width');
                if (zoomed) {
                    img.width(img.data('orig-width'));
                    img.height(img.data('orig-height'));
                } else {
                    if (null != img.data('orig-top')) {
                        img.offset({top: img.data('orig-top')})
                    }

                    var maxHeight = $(window).height() - 30;
                    if (maxHeight < img.height()) {
                        img.width(img.width() * maxHeight / img.height());
                        img.height(maxHeight);
                    }
                }
                break;

                break;
        }
    });

    function addSlide(slide) {
        var newPageI = gallery.options.numberOfPages;

        gallery.updatePageCount(newPageI + 1);
        slides.push(slide);
        if (1 == firstImages) {
            putSlideAt(1, 2);
            firstImages++;
        } else if (0 == firstImages) {
            putSlideAt(0, 1);
            firstImages++;
        }
    }

    var onlineMode = window.location.toString().split("#")[1] != "test";
    picFetcher = new reddit.PicFetcher({onlineMode: onlineMode,
                                        imgFn: function(img, w, h, advanceToNext) {
                                                    addSlide({url: img.url, width: w, height: h, item: img});
                                                },
                                        htmlFn: function (item, html) {
                                                    addSlide({html: html, item: item});
                                        },
                                        });
    picFetcher.setSubreddits(getSubreddits());

    function start() {
        picFetcher.getMorePosts()
    }
    var startDelay = onlineMode ? 0 : 100;
    setTimeout(start, startDelay);

    function getSubreddits() {
        var reddits = window.location.toString().split("?")[1];
        if (undefined == reddits)
            return (["all"])
        return (reddits.split("+"))
    }

    // TODO: Tie into actual settings
    var configHtml = _.template($('#settings-modal').html())();
    $('#wrapper').avgrund({
        height: 400,
        holderClass: 'custom',
        showClose: true,
        showCloseText: 'OK',
        enableStackAnimation: true,
        onBlurContainer: '.container',
        template: configHtml,
        onActivate: function() {
            respondToKeys = false
        },
        onDeactivate: function() {
            respondToKeys = true
        },
    });
// end document ready
});<|endoftext|>


<commit_before>window.urlParams = window.location.search.split(/[?&]/).slice(1).map(function(paramPair) {
    return paramPair.split(/=(.+)?/).slice(0, 2);
}).reduce(function (obj, pairArray) {
    obj[pairArray[0]] = pairArray[1];
    return obj;
}, {});
<commit_msg>inject css into any screensavers. WIP<commit_after>window.urlParams = window.location.search.split(/[?&]/).slice(1).map(function(paramPair) {
    return paramPair.split(/=(.+)?/).slice(0, 2);
}).reduce(function (obj, pairArray) {
    obj[pairArray[0]] = pairArray[1];
    return obj;
}, {});

var sheet = (function() {
	// Create the <style> tag
	var style = document.createElement("style");

	// WebKit hack :(
	style.appendChild(document.createTextNode(""));

	// Add the <style> element to the page
	document.head.appendChild(style);

	return style.sheet;
})();

sheet.insertRule("body {margin:0; padding:0; cursor:none;}"); /* remove top and left whitespace */
sheet.insertRule("canvas {display:block;}");    /* remove scrollbars */
sheet.insertRule("canvas:focus {outline:0;}"); /* remove blue outline around canvas */
<|endoftext|>


<commit_before>function weightP(n){
  var rating = parseFloat($('#pRating' + n).val());
  var weight = parseFloat($('#pWheight' + n).val());

  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#pValue'+n).html(codigo);
    return 0
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#pValue'+n).html(codigo);
    return weight/5*rating
  }

}

function tWeightP(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {
    total1 = total1 + parseFloat($('#pWheight' + i).val());
    total = total + weightP(i);
  }
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1.toFixed(2)+'
';
  }
  var codigo = '
'+total.toFixed(2)+'
';

  $("#tpWheight1").html(codigo1);
  $("#tpValue1").html(codigo);
  return total.toFixed(2)
}

function weightS(n){
  var rating = parseFloat($('#sRating' + n).val());
  var weight = parseFloat($('#sWheight' + n).val());
  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#sValue'+n).html(codigo);
    return 0
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#sValue'+n).html(codigo);
    return weight/5*rating
    //
  }
  //var codigo = '
'+weight/5*rating+'
';

}

function tWeightS(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {

    total1 = total1 + parseFloat($('#sWheight' + i).val());
    total = total + weightS(i);

  }
  var codigo = '
'+total.toFixed(2)+'
';
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1.toFixed(2)+'
';
  }

  $("#Tswheight").html(codigo1);
  $("#tsValue2").html(codigo);
return total.toFixed(2)
}

function weightT(n){
  var rating = parseFloat($('#tRating' + n).val());
  var weight = parseFloat($('#tWheight' + n).val());
  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#tValue'+n).html(codigo);
    return 0
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#tValue'+n).html(codigo);
    return weight/5*rating
  }
  //var codigo = '
'+weight/5*rating+'
';

}

function tWeightT(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {

    total1 = total1 + parseFloat($('#tWheight' + i).val());
    total = total + weightT(i);

  }
  var codigo = '
'+total.toFixed(2)+'
';
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1.toFixed(2)+'
';
  }

  $("#Ttwheight").html(codigo);
  $("#ttValue3").html(codigo1);
  return total.toFixed(2)
}

function finalWeightp(){
  var total=0;
  var totalInit = 0;
  if(isNaN((tWeightP(4)/100*parseFloat($('#pWeighti').val())).toFixed(2))){
    var codigo = 0;
  }else {
    total+=(tWeightP(4)/100*parseFloat($('#pWeighti').val())).toFixed(2)
    totalInit+=parseFloat($('#pWeighti').val());
    var codigo = '
'+(tWeightP(4)/100*parseFloat($('#pWeighti').val())).toFixed(2)+'
';
    var codigoInit = '
'+parseFloat($('#pWeighti').val())+'
'
  }
  $("#fValue1").html(codigo);
  $("#af").html(codigo);
  $("#ai").html(codigoInit);
  if(isNaN((tWeightS(10)/100*parseFloat($('#sWeighti').val()).toFixed(2)))){
    var codigo = 0;
  }else {
    total+=(tWeightS(4)/100*parseFloat($('#sWeighti').val())).toFixed(2)
    totalInit+=parseFloat($('#sWeighti').val());
    var codigo = '
'+(tWeightS(10)/100*parseFloat($('#sWeighti').val()).toFixed(2))+'
';
    var codigoInit = '
'+parseFloat($('#sWeighti').val())+'
'
  }
    $("#fValue2").html(codigo);
    $("#bf").html(codigo);
    $("#bi").html(codigoInit);
  if(isNaN((tWeightT(8)/100*parseFloat($('#tWeighti').val())).toFixed(2))){
    var codigo = 0;
  }else {
    total+=(tWeightT(4)/100*parseFloat($('#tWeighti').val())).toFixed(2)
    totalInit+=parseFloat($('#tWeighti').val());
    var codigo = '
'+(tWeightT(8)/100*parseFloat($('#tWeighti').val())).toFixed(2)+'
';
    var codigoInit = '
'+parseFloat($('#tWeighti').val())+'
'
  }
  $("#fValue3").html(codigo);
  $("#cf").html(codigo);
  $("#bi").html(codigoInit);
  $("#gi").html('
'+totalInit+'
');
  $("#gf").html('
'+total+'
');
}

function showWeight(){

  finalWeightp()

}
<commit_msg>show final values<commit_after>function weightP(n){
  var rating = parseFloat($('#pRating' + n).val());
  var weight = parseFloat($('#pWheight' + n).val());

  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#pValue'+n).html(codigo);
    return 0
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#pValue'+n).html(codigo);
    return weight/5*rating
  }

}

function tWeightP(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {
    total1 = total1 + parseFloat($('#pWheight' + i).val());
    total = total + weightP(i);
  }
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1.toFixed(2)+'
';
  }
  var codigo = '
'+total.toFixed(2)+'
';

  $("#tpWheight1").html(codigo1);
  $("#tpValue1").html(codigo);
  return total.toFixed(2)
}

function weightS(n){
  var rating = parseFloat($('#sRating' + n).val());
  var weight = parseFloat($('#sWheight' + n).val());
  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#sValue'+n).html(codigo);
    return 0
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#sValue'+n).html(codigo);
    return weight/5*rating
    //
  }
  //var codigo = '
'+weight/5*rating+'
';

}

function tWeightS(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {

    total1 = total1 + parseFloat($('#sWheight' + i).val());
    total = total + weightS(i);

  }
  var codigo = '
'+total.toFixed(2)+'
';
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1.toFixed(2)+'
';
  }

  $("#Tswheight").html(codigo1);
  $("#tsValue2").html(codigo);
return total.toFixed(2)
}

function weightT(n){
  var rating = parseFloat($('#tRating' + n).val());
  var weight = parseFloat($('#tWheight' + n).val());
  if(isNaN(weight/5*rating)){ // check if the number in the textbox is zero
    var codigo = '
'+0+'
';
    $('#tValue'+n).html(codigo);
    return 0
  }else{
    var codigo = '
'+weight/5*rating+'
';
    $('#tValue'+n).html(codigo);
    return weight/5*rating
  }
  //var codigo = '
'+weight/5*rating+'
';

}

function tWeightT(n){
  var total = 0;
  var total1 = 0;
  for (var i = 1; i < n + 1; i++) {

    total1 = total1 + parseFloat($('#tWheight' + i).val());
    total = total + weightT(i);

  }
  var codigo = '
'+total.toFixed(2)+'
';
  if(isNaN(total1)){
    var codigo1 = '
'+0+'
';
  }else{
    var codigo1 = '
'+total1.toFixed(2)+'
';
  }

  $("#Ttwheight").html(codigo);
  $("#ttValue3").html(codigo1);
  return total.toFixed(2)
}

function finalWeightp(){
  var total=0;
  var totalInit = 0;
  if(isNaN((tWeightP(4)/100*parseFloat($('#pWeighti').val())).toFixed(2))){
    var codigo = 0;
  }else {
    total+=(tWeightP(4)/100*parseFloat($('#pWeighti').val())).toFixed(2)
    totalInit+=parseFloat($('#pWeighti').val());
    var codigo = '
'+(tWeightP(4)/100*parseFloat($('#pWeighti').val())).toFixed(2)+'
';
    var codigoInit = '
'+parseFloat($('#pWeighti').val())+'
'
  }
  $("#fValue1").html(codigo);
  $("#aF").html(codigo);
  $("#aI").html(codigoInit);
  if(isNaN((tWeightS(10)/100*parseFloat($('#sWeighti').val()).toFixed(2)))){
    var codigo = 0;
  }else {
    total+=(tWeightS(4)/100*parseFloat($('#sWeighti').val())).toFixed(2)
    totalInit+=parseFloat($('#sWeighti').val());
    var codigo = '
'+(tWeightS(10)/100*parseFloat($('#sWeighti').val()).toFixed(2))+'
';
    var codigoInit = '
'+parseFloat($('#sWeighti').val())+'
'
  }
    $("#fValue2").html(codigo);
    $("#bF").html(codigo);
    $("#bI").html(codigoInit);
  if(isNaN((tWeightT(8)/100*parseFloat($('#tWeighti').val())).toFixed(2))){
    var codigo = 0;
  }else {
    total+=(tWeightT(4)/100*parseFloat($('#tWeighti').val())).toFixed(2)
    totalInit+=parseFloat($('#tWeighti').val());
    var codigo = '
'+(tWeightT(8)/100*parseFloat($('#tWeighti').val())).toFixed(2)+'
';
    var codigoInit = '
'+parseFloat($('#tWeighti').val())+'
'
  }
  $("#fValue3").html(codigo);
  $("#cF").html(codigo);
  $("#bI").html(codigoInit);
  $("#gI").html('
'+totalInit+'
');
  $("#gF").html('
'+total+'
');
}

function showWeight(){

  finalWeightp()

}
<|endoftext|>


<commit_before>'use strict'

import R from 'ramda';
import React, {PropTypes} from 'react';
import Registry from './registry';
import NotifyObservers from './components/core/NotifyObservers.react';

export default function render(component, path=[]) {
    if (R.contains(R.type(component), ['String', 'Number', 'Null'])) {
        return component;
    }

    // Create list of child elements
    let children;

    // TODO - Rename component.content to component.children
    const props = R.propOr({}, 'props', component);
    const content = props.content;
    if (!R.has('props', component) || !R.has('content', component.props)) {

        // No children
        children = [];

    } else if (R.contains(R.type(component.props.content), ['String', 'Number', 'Null'])) {

        children = [component.props.content];

    } else {
        // One or multiple objects

        // Recursively render the tree
        const renderChild = (child, i) =>
            render(child, R.append(i, path))

        children = (Array.isArray(content) ? content : [content])
                   .map(renderChild);

    }

    const element = Registry.resolve(component.type, component.namespace);

    const parent = React.createElement(
        element,
        R.omit(['content'], component.props),
        ...children
    );

    return (
        <NotifyObservers id={props.id}>
            {parent}
        </NotifyObservers>
    );
}

render.propTypes = {
    content: PropTypes.object,
    id: PropTypes.string
}
<commit_msg>handle undefined case<commit_after>'use strict'

import R from 'ramda';
import React, {PropTypes} from 'react';
import Registry from './registry';
import NotifyObservers from './components/core/NotifyObservers.react';

export default function render(component, path=[]) {
    if (R.contains(R.type(component), ['String', 'Number', 'Null'])) {
        return component;
    }

    // Create list of child elements
    let children;

    const props = R.propOr({}, 'props', component);

    // TODO - Rename component.content to component.children
    if (!R.has('props', component) ||
        !R.has('content', component.props) ||
        typeof component.props.content === 'undefined') {

        // No children
        children = [];

    } else if (R.contains(R.type(component.props.content), ['String', 'Number', 'Null'])) {

        children = [component.props.content];

    } else {
        // One or multiple objects

        // Recursively render the tree
        const renderChild = (child, i) =>
            render(child, R.append(i, path))

        children = (Array.isArray(content) ? content : [content])
                   .map(renderChild);

    }

    const element = Registry.resolve(component.type, component.namespace);

    const parent = React.createElement(
        element,
        R.omit(['content'], component.props),
        ...children
    );

    return (
        <NotifyObservers id={props.id}>
            {parent}
        </NotifyObservers>
    );
}

render.propTypes = {
    content: PropTypes.object,
    id: PropTypes.string
}
<|endoftext|>


<commit_before>const allStates = {
    NOT_SUBMITTED: ['primary', 'info-circle', 'Report not submitted', 'The report has not been submitted yet.'],
    SUBMITTED: ['primary', 'check2-circle', 'Report submitted', 'Your report has been submitted, and will be processed soon, then your manager will review your submission.'],
    PROCESSING: ['primary', 'info-circle', 'Report is being processed', 'Your report has been submitted, and is currently being processed.'],
    AWAITING: ['primary', 'info-circle', 'Report is awaiting validation', 'Your manager has received your report, will review it, and then validate or reject it.'],
    APPROVED: ['success', 'check2-circle', 'Report validated', 'Your manager has validated your report.'],
    REJECTED: ['danger', 'exclamation-octagon', 'Report rejected', 'Your manager has rejected your report.'],
    ERROR: ['danger', 'exclamation-octagon', 'Error occured', 'An error occurred while processing your report. Please contact your IT department.']
}

const reportId = window.location.pathname.substring(9);

var app = new Vue({
    el: '#request',
    data: {
        reportId: reportId,
        images: [],
        status: "NOT_SUBMITTED",
        alert: allStates["NOT_SUBMITTED"][0],
        icon: allStates["NOT_SUBMITTED"][1],
        title: allStates["NOT_SUBMITTED"][2],
        description: allStates["NOT_SUBMITTED"][3]
    },
    watch: {
        status: function(newVal, oldVal) {
            this.alert = allStates[this.status][0];
            this.icon = allStates[this.status][1];
            this.title = allStates[this.status][2];
            this.description = allStates[this.status][3];
        }
    },
    methods: {
        onFileChange: function(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length) return;

            this.images = [];
            var vm = this;
            Array.from(files).forEach(f => {
                var reader = new FileReader();
                reader.onload = (e) => {
                    vm.images.push({
                        src: e.target.result,
                        title: f.name
                    });
                };
                reader.readAsDataURL(f);
            });
        },
        clickFileChooser: function(e) {
            document.querySelector("#filesInput").click(e);
        }
    }
})

const db = firebase.firestore();
db.collection("requests").doc(reportId).onSnapshot((doc) => {
    if (doc.data()) {
        app.status = doc.data().status;
        console.log("New status from Firestore: ", app.status);
    }
});

document.querySelector("#formFiles").addEventListener('sl-submit', async (event) => {
    const reportId = app.reportId;
    const fileList = Array.from(document.querySelector("#filesInput").files);

    app.status = "SUBMITTED";

    // store in GCS via Firestore Storage
    const storageRef = firebase.storage().ref();
    for await (const f of fileList) {
        const receiptRef = storageRef.child(`${reportId}/${f.name}`);
        await receiptRef.put(f);
        await receiptRef.getDownloadURL();
        console.log("Uploaded", f.name);
    }
    // TODO: ensure all files are uploaded before actually starting the call to the function workflow invoker

    // call function to start workflow execution

    // TODO: avoid hard-coded function URL
    const fnUrl = "https://europe-west1-easy-ai-serverless.cloudfunctions.net/invoke-workflow";
    try {
        const fnWorkflowResp = await fetch(fnUrl, {
            method: "POST",
            headers: { "Content-Type" : "application/json" },
            body: JSON.stringify({ reportId })
        });
        const outcome = await fnWorkflowResp.json();
        console.log("Workflow execution", outcome);
    } catch (e) {
        // TODO: notify web UI in case of error
        console.error(e);
    }
});<commit_msg>One more try at awaiting for firebase storage upload<commit_after>const allStates = {
    NOT_SUBMITTED: ['primary', 'info-circle', 'Report not submitted', 'The report has not been submitted yet.'],
    SUBMITTED: ['primary', 'check2-circle', 'Report submitted', 'Your report has been submitted, and will be processed soon, then your manager will review your submission.'],
    PROCESSING: ['primary', 'info-circle', 'Report is being processed', 'Your report has been submitted, and is currently being processed.'],
    AWAITING: ['primary', 'info-circle', 'Report is awaiting validation', 'Your manager has received your report, will review it, and then validate or reject it.'],
    APPROVED: ['success', 'check2-circle', 'Report validated', 'Your manager has validated your report.'],
    REJECTED: ['danger', 'exclamation-octagon', 'Report rejected', 'Your manager has rejected your report.'],
    ERROR: ['danger', 'exclamation-octagon', 'Error occured', 'An error occurred while processing your report. Please contact your IT department.']
}

const reportId = window.location.pathname.substring(9);

var app = new Vue({
    el: '#request',
    data: {
        reportId: reportId,
        images: [],
        status: "NOT_SUBMITTED",
        alert: allStates["NOT_SUBMITTED"][0],
        icon: allStates["NOT_SUBMITTED"][1],
        title: allStates["NOT_SUBMITTED"][2],
        description: allStates["NOT_SUBMITTED"][3]
    },
    watch: {
        status: function(newVal, oldVal) {
            this.alert = allStates[this.status][0];
            this.icon = allStates[this.status][1];
            this.title = allStates[this.status][2];
            this.description = allStates[this.status][3];
        }
    },
    methods: {
        onFileChange: function(e) {
            var files = e.target.files || e.dataTransfer.files;
            if (!files.length) return;

            this.images = [];
            var vm = this;
            Array.from(files).forEach(f => {
                var reader = new FileReader();
                reader.onload = (e) => {
                    vm.images.push({
                        src: e.target.result,
                        title: f.name
                    });
                };
                reader.readAsDataURL(f);
            });
        },
        clickFileChooser: function(e) {
            document.querySelector("#filesInput").click(e);
        }
    }
})

const db = firebase.firestore();
db.collection("requests").doc(reportId).onSnapshot((doc) => {
    if (doc.data()) {
        app.status = doc.data().status;
        console.log("New status from Firestore: ", app.status);
    }
});

document.querySelector("#formFiles").addEventListener('sl-submit', async (event) => {
    const reportId = app.reportId;
    const fileList = Array.from(document.querySelector("#filesInput").files);

    app.status = "SUBMITTED";

    // store in GCS via Firestore Storage
    const storageRef = firebase.storage().ref();
    for await (const f of fileList) {
        const receiptRef = storageRef.child(`${reportId}/${f.name}`);
        const uploadSnapshot = await receiptRef.put(f);
        const downloadUrl = await uploadSnapshot.ref.getDownloadURL();
        console.log("Uploaded", f.name);
        console.log("Downlaod URL", downloadUrl);
    }
    // TODO: ensure all files are uploaded before actually starting the call to the function workflow invoker

    // call function to start workflow execution

    // TODO: avoid hard-coded function URL
    const fnUrl = "https://europe-west1-easy-ai-serverless.cloudfunctions.net/invoke-workflow";
    try {
        const fnWorkflowResp = await fetch(fnUrl, {
            method: "POST",
            headers: { "Content-Type" : "application/json" },
            body: JSON.stringify({ reportId })
        });
        const outcome = await fnWorkflowResp.json();
        console.log("Workflow execution", outcome);
    } catch (e) {
        // TODO: notify web UI in case of error
        console.error(e);
    }
});<|endoftext|>


<commit_before>var exec = require('child_process').exec
var mkdirp = require('mkdirp');

module.exports = function(path) {
  var path = path

  this.init = function(callback) {
    mkdirp(path, function(err) {
      gitExecute('init', callback)
    });
  }

  this.pull = function(callback) {
    gitExecute('pull', callback)
  }

  this.push = function(callback) {
    gitExecute('push', callback)
  }

  this.addAll = function(callback) {
    gitExecute('add -A', callback)
  }

  this.jsonLog = function(callback) {

    gitExecute('log --pretty=format:"{ *commit*: *%H*, *author*: *%an <%ae>*, *date*: *%ad*, *message*: *%f*},"', function(data) {

      // replace *'s with "'s
      var quoted = data.split('*').join('"')

      // remove trailing ,
      var commaRemoved = quoted.slice(0, -1)

      // add array [ & ]
      var jsonString = '[' + commaRemoved + ']'

      callback(JSON.parse(jsonString))
    })
  }

  this.commit = function(message, callback) {
    gitExecute('commit -m "' + message + '"', callback)
  }

  var gitExecute = function(command, callback) {
    var command = 'git ' + command;

    exec(command, {cwd: path}, function(error, result) {
      console.log(command)

      if (error != null) {
        console.log(error)
      }

      if (result != null) {
        console.log(result)
      }

      callback(result)
    })
  }
}

module.exportsa = function(path) {
  var path = path

  var gitExecute = function(command, callback) {

  }

  return {
    commit: function(message, callback) {
      gitExecute('commit -m "' + message + '"', callback)
    }
  }
}
<commit_msg>Refactored repository to use better object pattern<commit_after>var exec = require('child_process').exec
var mkdirp = require('mkdirp');

module.exports = function(path) {
  var path = path

  var gitExecute = function(command, callback) {
    var command = 'git ' + command

    exec(command, {cwd: path}, function(error, result) {
      console.log(command)

      if (error != null) {
        console.log(error)
        return;
      }

      callback(result)
    })
  }

  var commit = function(message, callback) {
    gitExecute('commit -m "' + message + '"', callback)
  }

  var jsonLog = function(callback) {

    gitExecute('log --pretty=format:"{ *commit*: *%H*, *author*: *%an <%ae>*, *date*: *%ad*, *message*: *%f*},"', function(data) {

      // replace *'s with "'s
      var quoted = data.split('*').join('"')

      // remove trailing ,
      var commaRemoved = quoted.slice(0, -1)

      // add array [ & ]
      var jsonString = '[' + commaRemoved + ']'

      callback(JSON.parse(jsonString))
    })
  }

  var init = function(callback) {
    mkdirp(path, function(err) {
      gitExecute('init', callback)
    })
  }

  var pull = function(callback) {
    gitExecute('pull', callback)
  }

  var push = function(callback) {
    gitExecute('push', callback)
  }

  var addAll = function(callback) {
    gitExecute('add -A', callback)
  }

  return {
      commit: commit,
      jsonLog: jsonLog,
      init:init,
      pull: pull,
      push: push,
      addAll: addAll
    }
  }
<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('testRky', ['$scope', function($scope){
      $scope.title = "testRky";
      $scope.d3Data = [
        {capteur: "Rky_L", score:10},
        {capteur: "Rky_L", score: 87}
      ];
    }]);

}());

// --------
// recuperation des valeur depuis MongoDB
(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('httpRky', ['$scope', '$http', function($scope, $http){
      $scope.title = "httpRky ... in progress";
      var url1 = "/api/v1/list/scale";
      var url ="/api/v1/search?name=Rky_P&source=*&after=2016/11/05";
      var data = [];
      $http.get(url)
        .then(function(response){
        angular.forEach(response.data,function(value){
          data.push({ capteur: value.heure, score: value.value });
        });
      });
      $scope.d3Data = data;
    }]);
}());<commit_msg>octobre<commit_after>(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('testRky', ['$scope', function($scope){
      $scope.title = "testRky";
      $scope.d3Data = [
        {capteur: "Rky_L", score:10},
        {capteur: "Rky_L", score: 87}
      ];
    }]);

}());

// --------
// recuperation des valeur depuis MongoDB
(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('httpRky', ['$scope', '$http', function($scope, $http){
      $scope.title = "httpRky ... in progress";
      var url1 = "/api/v1/list/scale";
      var url ="/api/v1/search?name=Rky_P&source=*&after=2016/10/01";
      var data = [];
      $http.get(url)
        .then(function(response){
        angular.forEach(response.data,function(value){
          data.push({ capteur: value.heure, score: value.value });
        });
      });
      $scope.d3Data = data;
    }]);
}());<|endoftext|>