<commit_before>/*global $, jQuery, alert, console, error, success, endless, ajax, templateHelper, Routing, appLocale*/
/*jslint nomen: true */ /* Tolerate dangling _ in identifiers */
/*jslint vars: true */ /* Tolerate many var statements per function */
/*jslint white: true */
/*jslint browser: true */
/*jslint devel: true */ /* Assume console, alert, ... */
/*jslint windows: true */ /* Assume Windows */
/*jslint maxerr: 100 */ /* Maximum number of errors */

/*
 * library dependencies:
 *      jquery 1.8.3
 *		isotope
 *		jsrender
 *		jsviews
 * external dependencies:
 *      template helper
 */

// fansWorld isotope wrapper plugin 1.4 /* resolution breaks at getMaxSections */

$(document).ready(function () {
	"use strict";
	var pluginName = "fwGalerizer";
	var defaults = {
		propertyName: "fansworld",
		selector: null,
		endless: true,
		cellWidth: 200,
		feedSource: '',
		feedfilter: {},
		normalize: true,
		jsonData: null,
		defaultMediaType: null,
		itemSelector: '.item',
		prevWidth: null,
		// custom callback events
		onError: function(error) {},
		onIsotopeLoad: function(data) {},
		onEndless: function(data) {},
		/////////////////////////////////////////////////////////
		// onDataReady()                                       //
		// Permite interceptar los datos recibidos por ajax    //
		// La funcion debe devolver los datos procesados       //
		/////////////////////////////////////////////////////////
		onDataReady: function(data) {return data;},
		onBeforeRender: function(data) {},
		onFilter: function(data) {},
		onGallery: function(data) {}
	};
	function Plugin(element, options) {
		this.element = element;
		this.options = $.extend({}, defaults, options);
		this._defaults = defaults;
		this._name = pluginName;
		this.init();
	}
	Plugin.prototype = {
		init: function () {
			console.log("fwGalerizer.init()");
			var that = this;
			var $container = $(that.element);
			that.options.feedSource = $container.attr('data-feed-source');
			$container.addClass(that._name);
			$container.isotope({
				itemSelector : that.options.itemSelector,
				resizable: false, // disable normal resizing
				masonry: {
					columnWidth: ($container.width() / that.getMaxSections($container))
				}
			});

			// Attach to window resize event
			$(window).smartresize(function(){
				var cells = that.getMaxSections($container);
				$container.find('.item').each(function(i, item){
					var $this = $(this);
					$this.css('width', ((100 / cells) - 1) + "%"); // 2% margen entre los elementos
				});
				$container.isotope({
					// update columnWidth to a percentage of container width
					masonry: { columnWidth: $container.width() / cells }
				});
				$container.isotope('reLayout');
		    });
			// Get feed
			$.when(that.loadData(that.options.feedSource, that.options.feedfilter))
			.then(function(jsonData) {
				that.options.jsonData = that.options.onDataReady(that.options.jsonData);
				that.loadGallery(that, that.options.jsonData);
				return;
			})
			.done(that.options.onGallery);
		},
		loadGallery: function(plugin, jsonData) {
			console.log("loadGallery()");
			var that = plugin;
			var $container = $(that.element);
			var i, element;
			endless.stop();
			function appendElement (htmlTemplate) {
				var $post = $(htmlTemplate);
				$container.append($post).isotope('appended', $post);
				$(htmlTemplate).find('.image').load(function() {
					var $this = $(this);
					$container.isotope('reloadItems');
					that.resize();
				});
			}
			if(that.options.jsonData.length > 0) {
				for(i in that.options.jsonData) {
					if (that.options.jsonData.hasOwnProperty(i)) {
						if(that.options.normalize === true) {
							element = that.normalizeData(that.options.jsonData[i]);
						} else {
							element = that.options.jsonData[i];
						}
						$.when(templateHelper.htmlTemplate('general-column_element', element))
						.then(appendElement);
					}
				}
				$container.isotope('reLayout');
				$container.isotope('reloadItems');
				if(that.options.endless) {
					that.makeEndless();
				}
			} else {
				endless.stop();
			}
			return that.options.onGallery();
		},
		loadData: function(source, query) {
			if(typeof(query) === 'undefined'){
				query = {};
			}
			var that = this;
			var $container = $(that.element);
			var deferred = new jQuery.Deferred();
			$.ajax({
				url: 'http://' + location.host + Routing.generate(appLocale + '_' + that.options.feedSource),
				data: query,
				type: 'post'
			})
			.then(function (responseJSON) {
				that.options.jsonData = responseJSON;
				return that.options.jsonData;
			})
			.done(function (data){
				deferred.resolve(data);
			})
			.fail(function (jqXHR, status, error) {
				deferred.reject(new Error(error));
			});
			return deferred.promise();
		},
		normalizeData: function(data) {
			var href = Routing.generate(appLocale + '_' + data.type + '_show', {
				'id': data.id,
				'slug': data.slug
			});

			var hrefModal = Routing.generate(appLocale + '_modal_media', {
				'id': data.id,
				'type': data.type
			});

			var authorUrl = Routing.generate(appLocale + '_user_land', {
				'username': data.author.username
			});
			return {
					'type': data.type,
					'date': data.created,
					'href': href,
					'hrefModal': hrefModal,
					'image': data.image,
					'slug': data.slug,
					'title': data.title,
					'author': data.author.username,
					'authorHref': authorUrl,
					'authorImage': data.author.image
			};
		},
		getMaxSections: function(container) {
			var that = this;
			var $container = $(that.element);
			var cells = 0;
			var width = parseInt($container.width());

			if(width <= 600) {
				cells = 1;
			} else if (width <= 800) {
				cells = 1;
			} else if (width <= 1000) {
				cells = 2;
			} else if (width <= 1200) {
				cells = 3;
			} else if (width <= 1200) {
				cells = 4;
			} else if (width <= 1600) {
				cells = 4;
			} else if (width > 1600) {
				cells = 5;
			}
			//console.log("will use [%s] cols at [%s]px", cells, width);
			return cells;
		},
		resize: function(event) {
			var that = this;
			var $container = $(that.element);
			var cells = that.getMaxSections($container);
			$container.find('.item').each(function(i, item){
				var $this = $(this);
				$this.css('width', ((100 / cells) - 1) + "%"); // 2% margen entre los elementos
			});
			$container.isotope({
				// update columnWidth to a percentage of container width
				masonry: {
					columnWidth: $container.width() / that.getMaxSections($container)
				}
			});
			$container.isotope('reLayout');
		},
		makeEndless: function(event) {
			var that = this;
			var $container = $(that.element);
			endless.init(1, function() {
				endless.stop();
				that.options.onEndless(that);
				$.when(that.loadData(that.options.feedSource, that.options.feedfilter))
				.then(function(jsonData) {
					jsonData = that.options.onDataReady(jsonData);
					that.options.jsonData = that.options.onDataReady(that.options.jsonData);
					that.loadGallery(that, that.options.jsonData);
				});
			});
		},
		removeAll: function() {
			var that = this;
			var $container = $(that.element);
			var $removable = $container.find(that.options.itemSelector);
			$container.isotope( 'remove', $removable );
			$container.empty();
			endless.stop();
		},
		destroy: function () {
			var that = this;
			$(that.element).unbind("destroyed", that.teardown);
			that.teardown();
		},
		teardown: function () {
			var that = this;
			var $container = $(that.element);
			endless.stop();
			that.removeAll();
			$container.isotope('destroy');
			$.removeData($(that.element)[0], that._name);
			$(that.element).removeClass(that._name);
			that.unbind();
			that.element = null;
		},
		bind: function () { },
		unbind: function () { }
	};
	$.fn[pluginName] = function (options) {
		return this.each(function () {
			if (!$.data(this, pluginName)) {
				$.data(this, pluginName, new Plugin(this, options));
			}
		});
	};
});
<commit_msg>con preload<commit_after>/*global $, jQuery, alert, console, error, success, endless, ajax, templateHelper, Routing, appLocale*/
/*jslint nomen: true */ /* Tolerate dangling _ in identifiers */
/*jslint vars: true */ /* Tolerate many var statements per function */
/*jslint white: true */
/*jslint browser: true */
/*jslint devel: true */ /* Assume console, alert, ... */
/*jslint windows: true */ /* Assume Windows */
/*jslint maxerr: 100 */ /* Maximum number of errors */

/*
 * library dependencies:
 *      jquery 1.8.3
 *		isotope
 *		jsrender
 *		jsviews
 * external dependencies:
 *      template helper
 */

// fansWorld isotope wrapper plugin 1.5 /* preloadData */
// 1.4 /* resolution breaks at getMaxSections */

$(document).ready(function () {
	"use strict";
	var pluginName = "fwGalerizer";
	var defaults = {
		propertyName: "fansworld",
		selector: null,
		endless: true,
		cellWidth: 200,
		feedSource: '',
		feedfilter: {},
		preoloadData: [],
		normalize: true,
		jsonData: null,
		defaultMediaType: null,
		itemSelector: '.item',
		prevWidth: null,
		// custom callback events
		onError: function(error) {},
		onIsotopeLoad: function(data) {},
		onEndless: function(data) {},
		/////////////////////////////////////////////////////////
		// onDataReady()                                       //
		// Permite interceptar los datos recibidos por ajax    //
		// La funcion debe devolver los datos procesados       //
		/////////////////////////////////////////////////////////
		onDataReady: function(data) {return data;},
		onBeforeRender: function(data) {},
		onFilter: function(data) {},
		onGallery: function(data) {}
	};
	function Plugin(element, options) {
		this.element = element;
		this.options = $.extend({}, defaults, options);
		this._defaults = defaults;
		this._name = pluginName;
		this.init();
	}
	Plugin.prototype = {
		init: function () {
			console.log("fwGalerizer.init()");
			var that = this;
			console.log("preload: ");
			console.log(that.options.preoloadData);
			var $container = $(that.element);
			that.options.feedSource = $container.attr('data-feed-source');
			$container.addClass(that._name);
			$container.isotope({
				itemSelector : that.options.itemSelector,
				resizable: false, // disable normal resizing
				masonry: {
					columnWidth: ($container.width() / that.getMaxSections($container))
				}
			});

			// Attach to window resize event
			$(window).smartresize(function(){
				var cells = that.getMaxSections($container);
				$container.find('.item').each(function(i, item){
					var $this = $(this);
					$this.css('width', ((100 / cells) - 1) + "%"); // 2% margen entre los elementos
				});
				$container.isotope({
					// update columnWidth to a percentage of container width
					masonry: { columnWidth: $container.width() / cells }
				});
				$container.isotope('reLayout');
		    });
			// Get feed
			var galleryData = null;
			if($.isEmptyObject(that.options.preoloadData)) {
				galleryData = $.when(that.loadData(that.options.feedSource, that.options.feedfilter));
			} else {
				galleryData = $.when((function() {
					var deferred = new jQuery.Deferred();
					that.options.jsonData = that.options.preoloadData;
					console.log("that.options.jsonData: ");
					console.log(that.options.jsonData)
					deferred.resolve(that.options.jsonData);
					return deferred.promise();
				})());
			}

			galleryData.then(function(jsonData) {
				that.options.jsonData = that.options.onDataReady(that.options.jsonData);
				that.loadGallery(that, that.options.jsonData);
				return;
			})
			.done(that.options.onGallery);
		},
		loadGallery: function(plugin, jsonData) {
			console.log("loadGallery()");
			var that = plugin;
			var $container = $(that.element);
			var i, element;
			endless.stop();
			function appendElement (htmlTemplate) {
				var $post = $(htmlTemplate);
				$container.append($post).isotope('appended', $post);
				$(htmlTemplate).find('.image').load(function() {
					var $this = $(this);
					$container.isotope('reloadItems');
					that.resize();
				});
			}
			if(that.options.jsonData.length > 0) {
				for(i in that.options.jsonData) {
					if (that.options.jsonData.hasOwnProperty(i)) {
						if(that.options.normalize === true) {
							element = that.normalizeData(that.options.jsonData[i]);
						} else {
							element = that.options.jsonData[i];
						}
						$.when(templateHelper.htmlTemplate('general-column_element', element))
						.then(appendElement);
					}
				}
				$container.isotope('reLayout');
				$container.isotope('reloadItems');
				if(that.options.endless) {
					that.makeEndless();
				}
			} else {
				endless.stop();
			}
			return that.options.onGallery();
		},
		loadData: function(source, query) {
			if(typeof(query) === 'undefined'){
				query = {};
			}
			var that = this;
			var $container = $(that.element);
			var deferred = new jQuery.Deferred();
			$.ajax({
				url: 'http://' + location.host + Routing.generate(appLocale + '_' + that.options.feedSource),
				data: query,
				type: 'post'
			})
			.then(function (responseJSON) {
				that.options.jsonData = responseJSON;
				return that.options.jsonData;
			})
			.done(function (data){
				deferred.resolve(data);
			})
			.fail(function (jqXHR, status, error) {
				deferred.reject(new Error(error));
			});
			return deferred.promise();
		},
		normalizeData: function(data) {
			var href = Routing.generate(appLocale + '_' + data.type + '_show', {
				'id': data.id,
				'slug': data.slug
			});

			var hrefModal = Routing.generate(appLocale + '_modal_media', {
				'id': data.id,
				'type': data.type
			});

			var authorUrl = Routing.generate(appLocale + '_user_land', {
				'username': data.author.username
			});
			return {
					'type': data.type,
					'date': data.created,
					'href': href,
					'hrefModal': hrefModal,
					'image': data.image,
					'slug': data.slug,
					'title': data.title,
					'author': data.author.username,
					'authorHref': authorUrl,
					'authorImage': data.author.image
			};
		},
		getMaxSections: function(container) {
			var that = this;
			var $container = $(that.element);
			var cells = 0;
			var width = parseInt($container.width());

			if(width <= 600) {
				cells = 1;
			} else if (width <= 800) {
				cells = 1;
			} else if (width <= 1000) {
				cells = 2;
			} else if (width <= 1200) {
				cells = 3;
			} else if (width <= 1200) {
				cells = 4;
			} else if (width <= 1600) {
				cells = 4;
			} else if (width > 1600) {
				cells = 5;
			}
			//console.log("will use [%s] cols at [%s]px", cells, width);
			return cells;
		},
		resize: function(event) {
			var that = this;
			var $container = $(that.element);
			var cells = that.getMaxSections($container);
			$container.find('.item').each(function(i, item){
				var $this = $(this);
				$this.css('width', ((100 / cells) - 1) + "%"); // 2% margen entre los elementos
			});
			$container.isotope({
				// update columnWidth to a percentage of container width
				masonry: {
					columnWidth: $container.width() / that.getMaxSections($container)
				}
			});
			$container.isotope('reLayout');
		},
		makeEndless: function(event) {
			var that = this;
			var $container = $(that.element);
			endless.init(1, function() {
				endless.stop();
				that.options.onEndless(that);
				$.when(that.loadData(that.options.feedSource, that.options.feedfilter))
				.then(function(jsonData) {
					jsonData = that.options.onDataReady(jsonData);
					that.options.jsonData = that.options.onDataReady(that.options.jsonData);
					that.loadGallery(that, that.options.jsonData);
				});
			});
		},
		removeAll: function() {
			var that = this;
			var $container = $(that.element);
			var $removable = $container.find(that.options.itemSelector);
			$container.isotope( 'remove', $removable );
			$container.empty();
			endless.stop();
		},
		destroy: function () {
			var that = this;
			$(that.element).unbind("destroyed", that.teardown);
			that.teardown();
		},
		teardown: function () {
			var that = this;
			var $container = $(that.element);
			endless.stop();
			that.removeAll();
			$container.isotope('destroy');
			$.removeData($(that.element)[0], that._name);
			$(that.element).removeClass(that._name);
			that.unbind();
			that.element = null;
		},
		bind: function () { },
		unbind: function () { }
	};
	$.fn[pluginName] = function (options) {
		return this.each(function () {
			if (!$.data(this, pluginName)) {
				$.data(this, pluginName, new Plugin(this, options));
			}
		});
	};
});
<|endoftext|>


<commit_before>window.onload = setupFunc;
var webSocketPingHandler;
var sessionTOHandler;

function setupFunc() {
	hideBusySign();

	Wicket.Event.subscribe('/ajax/call/beforeSend', function (attributes, jqXHR, settings) {
		showBusySign();
	});
	Wicket.Event.subscribe('/ajax/call/complete', function (attributes, jqXHR, textStatus) {
		hideBusySign();
	});
	Wicket.Event.subscribe('/ajax/call/failure', function (attributes, jqXHR, errorThrown, textStatus) {
		hideBusySign();
		alert(errorThrown);
	});

	if(pingServerInterval) {
		Wicket.Event.subscribe("/websocket/open", function (jqEvent, message) {
			webSocketPingHandler = setInterval(pingServerByWS, pingServerInterval);
		});

		Wicket.Event.subscribe("/websocket/closed", function (jqEvent, message) {
			window.clearInterval(webSocketPingHandler);
		});

		Wicket.Event.subscribe("/websocket/error", function (jqEvent, message) {
			window.clearInterval(webSocketPingHandler);
		});
	}

	if(sessionTO && sessionTO > 0) {
		sessionTOHandler = setInterval(onBeforeSessionTimeout, sessionTO);
	} else if(sessionTOHandler) {
		window.clearInterval(webSocketPingHandler);
	}
}
function hideBusySign() {
	$("#ajaxVeil").css("display", "none");
}
function showBusySign() {
	$("#ajaxVeil").css("display", "inline");
}
function pingServerByWS() {
	Wicket.WebSocket.send('{msg:"p"}');
}
function onBeforeSessionTimeout() {
	if(confirm('Session is to expire.Reconnect?')) {
		Wicket.Ajax.get({u:ajaxUrl});
	}
}<commit_msg>some bugs removed<commit_after>window.onload = setupFunc;
var webSocketPingHandler;

function setupFunc() {
	console.log('Demeter SetupFunc');

	hideBusySign();

	Wicket.Event.subscribe('/ajax/call/beforeSend', function (attributes, jqXHR, settings) {
		showBusySign();
	});
	Wicket.Event.subscribe('/ajax/call/complete', function (attributes, jqXHR, textStatus) {
		hideBusySign();
	});
	Wicket.Event.subscribe('/ajax/call/failure', function (attributes, jqXHR, errorThrown, textStatus) {
		hideBusySign();
		alert(errorThrown);
	});

	if(pingServerInterval) {
		Wicket.Event.subscribe("/websocket/open", function (jqEvent, message) {
			console.log('Demeter Wicket.Event: websocket/open!, ' + message);
			webSocketPingHandler = setInterval(pingServerByWS, pingServerInterval);
		});

		Wicket.Event.subscribe("/websocket/closed", function (jqEvent, message) {
			console.log('Demeter Wicket.Event: websocket/closed!, ' + message);
			window.clearInterval(webSocketPingHandler);
		});

		Wicket.Event.subscribe("/websocket/error", function (jqEvent, message) {
			console.log('Demeter Wicket.Event: websocket/error!, ' + message);
			window.clearInterval(webSocketPingHandler);
		});
	}

	if (sessionTO && sessionTO > 3000) {
		// alert user 3 sec before session timeout
		setInterval(onBeforeSessionTimeout, sessionTO - 3000);
	}
}

function hideBusySign() {
	$("#ajaxVeil").css("display", "none");
}

function showBusySign() {
	$("#ajaxVeil").css("display", "inline");
}

function pingServerByWS() {
	Wicket.WebSocket.send('{msg:"p"}');
}

function onBeforeSessionTimeout() {
	if(confirm('Session is to expire.Reconnect?')) {
		Wicket.Ajax.get({u:ajaxUrl});
	}
}<|endoftext|>


<commit_before>import React from 'react'
import { expect } from 'chai'
import { shallow } from 'enzyme'
import Dropdown from '../../dropdown/Dropdown'
import sinon from 'sinon'

describe ('Dropdown', () => {
  it ('exists', () => {
    expect (Dropdown).to.exist
  })
})<commit_msg>more tests for dropdown<commit_after>import React from 'react'
import { expect } from 'chai'
import { shallow } from 'enzyme'
import Dropdown from '../../dropdown/Dropdown'
import sinon from 'sinon'

describe ('Dropdown', () => {
  it ('exists', () => {
    expect (Dropdown).to.exist
  })
  it ('extends Component class of React', () => {
    const mockDropdown = new Dropdown()
    expect (mockDropdown instanceof React.Component).is.eq(true)
  })
  describe ('.defaultProps', () => {
    it ('exists', () => {
      expect (Dropdown.defaultProps).to.exist
    })
    it ('has correct properties', () => {
      expect (Dropdown.defaultProps).to.have.all.keys('style', 'searchable', 'onSearch')
    })
  })
  describe ('#filterMenu()', () => {
    const mockDropdown = new Dropdown()
    const mockHash = [{value: 'apple'}, {value: 'pear'}, {value: 'plum'}]
    it ('exists with correct number of parameters required', () => {
      expect (mockDropdown.filterMenu).to.exist.to.have.lengthOf(2)
    })
    context ('when given arguments', () => {
      it ('returns correct object for string 4 or greater', () => {
        expect (mockDropdown.filterMenu(mockHash, 'appl')).to.deep.equal([{ value: 'apple', filtered: true}])
      })
      it ('returns original object if less than 4 characters', () => {
        expect (mockDropdown.filterMenu(mockHash, '')).to.eq(mockHash)
      })
    })
  })
  describe ('#handleEvent()', () => {
    const mockDropdown = new Dropdown()
    const event = { type: 'keyup', keyCode: 27 }
    it ('exists with correct number of parameters required', () => {
      expect (mockDropdown.handleEvent).to.exist.and.have.lengthOf(1)
    })
    context ('when given an event keyCode is 27 and type keyup as an argument', () => {
      it.skip ('triggers close method', () => {
        //not recognizing method
        const spy = sinon.spy(Dropdown.prototype.__reactAutoBindMap, 'close')
        const spyMockDropdown = new Dropdown()
        spyMockDropdown.handleEvent(event)
        expect (spy.calledOnce).to.eq(true)
        spy.restore()
      })
    })
  })
})<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import AppRoutes from '../components/AppRoutes';
import 'jquery';

// var injectTapEventPlugin = require('react-tap-event-plugin');

import './less/style.less';

// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
// injectTapEventPlugin();

  //Needed for React Developer Tools
  window.React = React;

window.onload = () => {
  ReactDOM.render(<AppRoutes/>, document.getElementById('main'));
};
<commit_msg>Fix react-tap-event-plugin issue<commit_after>'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import AppRoutes from '../components/AppRoutes';
import 'jquery';

import injectTapEventPlugin from 'react-tap-event-plugin';

import './less/style.less';

// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();

  //Needed for React Developer Tools
  window.React = React;

window.onload = () => {
  ReactDOM.render(<AppRoutes/>, document.getElementById('main'));
};
<|endoftext|>


<commit_before>/* global define */
/* jshint indent:2 */

define([
  'app',
], function(app) {
  'use strict';

  app.provider('mbApiFoundation', function() {
    var server,
        repositoriesPrefix,
        workspacesPrefix,
        nodesPrefix;

    this.setServer = function(value) {
      server = value;
    };

    this.setRepositoriesPrefix = function(value) {
      repositoriesPrefix = value;
    };

    this.setWorkspacesPrefix = function(value) {
      workspacesPrefix = value;
    };

    this.setNodesPrefix = function(value) {
      nodesPrefix = value;
    };

    this.$get = ['$q', 'Restangular', function($q, Restangular) {
      Restangular.setBaseUrl(server);

      var repositories = Restangular.all(repositoriesPrefix);
      var repositoryCache = {};
      var workspaceCache = {};
      var nodeCache = {};

      var repository = function(repository) {
        if (!repositoryCache[repository]) {
          repositoryCache[repository] = Restangular.one(repositoriesPrefix, repository);
        }
        return repositoryCache[repository];
      };
      var workspaces = function(repositoryName) {
        return repository(repositoryName).all(workspacesPrefix);
      };
      var workspace = function(repositoryName, name) {
        if (!workspaceCache[repositoryName+'/'+name]) {
          workspaceCache[repositoryName+'/'+name] = repository(repositoryName).one(workspacesPrefix, name);
        }
        return workspaceCache[repositoryName+'/'+name];
      };

      var node = function(repositoryName, workspaceName, path) {
        if (!nodeCache[repositoryName+'/'+workspaceName+path]) {
          if (path.slice(0,1) === '/') {
            path = path.slice(1);
          }
          nodeCache[repositoryName+'/'+workspaceName+path] = workspace(repositoryName, workspaceName).one(nodesPrefix, path);
        }
        return nodeCache[repositoryName+'/'+workspaceName+path];
      };
      var nodeCollection = function(repositoryName, workspaceName, path) {
        if (path.slice(0,1) === '/') {
          path = path.slice(1);
        }
        return workspace(repositoryName, workspaceName).all(nodesPrefix).all(path);
      };
      var nodeProperties = function(repositoryName, workspaceName, path) {
        if (path.slice(0,1) === '/') {
          path = path.slice(1);
        }
        return workspace(repositoryName, workspaceName).all(nodesPrefix).all(path + '@properties');
      };
      var nodeProperty = function(repositoryName, workspaceName, path, propertyName) {
        if (path.slice(0,1) === '/') {
          path = path.slice(1);
        }
        return workspace(repositoryName, workspaceName).all(nodesPrefix).one(path + '@properties', propertyName);
      };

      return {
        getServer: function() {
          return server;
        },
        getRepositoriesPrefix: function() {
          return repositoriesPrefix;
        },
        getWorkspacesPrefix: function() {
          return workspacesPrefix;
        },
        getNodesPrefix: function() {
          return nodesPrefix;
        },
        getRepositories: function(config) {
          config = config || {};
          return repositories.withHttpConfig(config).getList();
        },
        getRepository: function(name, config) {
          config = config || {};
          return repository(name).withHttpConfig(config).get();
        },
        getWorkspaces: function(repositoryName, config) {
          config = config || {};
          return workspaces(repositoryName).withHttpConfig(config).getList();
        },
        getWorkspace: function(repositoryName, name, config) {
          config = config || {};
          return workspace(repositoryName, name).withHttpConfig(config).get();
        },
        createWorkspace: function(repositoryName, name, config) {
          config = config || {};
          return workspaces(repositoryName).withHttpConfig(config).post({ name: name });
        },
        deleteWorkspace: function(repositoryName, name, config) {
          config = config || {};
          return workspace(repositoryName, name).withHttpConfig(config).remove();
        },
        getNode: function(repositoryName, workspaceName, path, config) {
          config = config || {};
          var params;
          if (config.reducedTree) {
            params = { reducedTree: true };
            delete config.reducedTree;
          } else{
            params = {};
          }
          return node(repositoryName, workspaceName, path).withHttpConfig(config).get(params);
        },
        createNode: function(repositoryName, workspaceName, parentPath, relPath, config) {
          config = config || {};
          return nodeCollection(repositoryName, workspaceName, parentPath).withHttpConfig(config).post({ relPath: relPath});
        },
        deleteNode: function(repositoryName, workspaceName, path, config) {
          config = config || {};
          return node(repositoryName, workspaceName, path).withHttpConfig(config).remove();
        },
        moveNode: function(repositoryName, workspaceName, path, newPath, config) {
          config = config || {};
          return node(repositoryName, workspaceName, path).withHttpConfig(config).put({
            method: 'move',
            destAbsPath: newPath
          });
        },
        renameNode: function(repositoryName, workspaceName, path, newName, config) {
          config = config || {};
          return node(repositoryName, workspaceName, path).withHttpConfig(config).put({
            method: 'rename',
            newName: newName
          });
        },
        createNodeProperty: function(repositoryName, workspaceName, path, propertyName, propertyValue, propertyType, config) {
          config = config || {};
          if (propertyType) {
            return nodeProperties(repositoryName, workspaceName, path).withHttpConfig(config).post({ name: propertyName, value: propertyValue, type: propertyType });
          }
          return nodeProperties(repositoryName, workspaceName, path).withHttpConfig(config).post({ name: propertyName, value: propertyValue });
        },
        deleteNodeProperty: function(repositoryName, workspaceName, path, propertyName, config) {
          config = config || {};
          return nodeProperty(repositoryName, workspaceName, path, propertyName).withHttpConfig(config).remove();
        },
        updateNodeProperty: function(repositoryName, workspaceName, path, propertyName, propertyValue, propertyType, config) {
          config = config || {};
          return nodeProperties(repositoryName, workspaceName, path).withHttpConfig(config).post({ name: propertyName, value: propertyValue, type: propertyType });
        },
      };
    }];
  });
});
<commit_msg>Add comments for ApiFoundation<commit_after>/* global define */
/* jshint indent:2 */

define([
  'app',
], function(app) {
  'use strict';
  /**
   * ApiFoundation is the lower layer of the phpcr-browser.
   * It transforms the basic actions in REST requests on the API
   */
  app.provider('mbApiFoundation', function() {
    var server,
        repositoriesPrefix,
        workspacesPrefix,
        nodesPrefix;

    /**
     * Configure server url
     * @param {string} value
     */
    this.setServer = function(value) {
      server = value;
    };

    /**
     * Configure repositories collection prefix in url
     * @param {string} value
     */
    this.setRepositoriesPrefix = function(value) {
      repositoriesPrefix = value;
    };

    /**
     * Configure workspaces collection prefix in url
     * @param {string} value
     */
    this.setWorkspacesPrefix = function(value) {
      workspacesPrefix = value;
    };

    /**
     * Configure nodes collection prefixe in url
     * @param {string} value
     */
    this.setNodesPrefix = function(value) {
      nodesPrefix = value;
    };

    this.$get = ['$q', 'Restangular', function($q, Restangular) {
      Restangular.setBaseUrl(server);

      var repositories    = Restangular.all(repositoriesPrefix);
      var repositoryCache = {};
      var workspaceCache  = {};
      var nodeCache       = {};

      /**
       * Build repository Restangular object and cache it
       * @param  {string} repository
       * @return {Restangular object}
       */
      var repository = function(repository) {
        if (!repositoryCache[repository]) {
          repositoryCache[repository] = Restangular.one(repositoriesPrefix, repository);
        }
        return repositoryCache[repository];
      };

      /**
       * Build workspaces Restangular object
       * @param  {string} repositoryName
       * @return {Restangular object}
       */
      var workspaces = function(repositoryName) {
        return repository(repositoryName).all(workspacesPrefix);
      };

      /**
       * Build workspace Restangular object and cache it
       * @param  {string} repositoryName
       * @param  {string} name
       * @return {Restangular object}
       */
      var workspace = function(repositoryName, name) {
        if (!workspaceCache[repositoryName+'/'+name]) {
          workspaceCache[repositoryName+'/'+name] = repository(repositoryName).one(workspacesPrefix, name);
        }
        return workspaceCache[repositoryName+'/'+name];
      };

      /**
       * Build node Restangular object and cache it
       * @param  {string} repositoryName
       * @param  {string} workspaceName
       * @param  {string} path
       * @return {Restangular object}
       */
      var node = function(repositoryName, workspaceName, path) {
        if (!nodeCache[repositoryName+'/'+workspaceName+path]) {
          if (path.slice(0,1) === '/') {
            path = path.slice(1);
          }
          nodeCache[repositoryName+'/'+workspaceName+path] = workspace(repositoryName, workspaceName).one(nodesPrefix, path);
        }
        return nodeCache[repositoryName+'/'+workspaceName+path];
      };

      /**
       * Build nodes Restangular object
       * @param  {string} repositoryName
       * @param  {string} workspaceName
       * @param  {string} path
       * @return {Restangular object}
       */
      var nodeCollection = function(repositoryName, workspaceName, path) {
        if (path.slice(0,1) === '/') {
          path = path.slice(1);
        }
        return workspace(repositoryName, workspaceName).all(nodesPrefix).all(path);
      };

      /**
       * Build node properties Restangular object
       * @param  {string} repositoryName
       * @param  {string} workspaceName
       * @param  {string} path
       * @return {Restangular object}
       */
      var nodeProperties = function(repositoryName, workspaceName, path) {
        if (path.slice(0,1) === '/') {
          path = path.slice(1);
        }
        return workspace(repositoryName, workspaceName).all(nodesPrefix).all(path + '@properties');
      };

      /**
       * Build node property Restangular object
       * @param  {string} repositoryName
       * @param  {string} workspaceName
       * @param  {string} path
       * @param  {string} propertyName
       * @return {Restangular object}
       */
      var nodeProperty = function(repositoryName, workspaceName, path, propertyName) {
        if (path.slice(0,1) === '/') {
          path = path.slice(1);
        }
        return workspace(repositoryName, workspaceName).all(nodesPrefix).one(path + '@properties', propertyName);
      };

      return {
        /**
         * Get server url
         * @return {string}
         */
        getServer: function() {
          return server;
        },

        /**
         * Get repositories collection prefix
         * @return {string}
         */
        getRepositoriesPrefix: function() {
          return repositoriesPrefix;
        },

        /**
         * Get workspaces collection prefix
         * @return {string}
         */
        getWorkspacesPrefix: function() {
          return workspacesPrefix;
        },

        /**
         * Get nodes collection prefix
         * @return {string}
         */
        getNodesPrefix: function() {
          return nodesPrefix;
        },

        /**
         * Get all repositories
         * @param  {object} config
         * @return {promise}
         */
        getRepositories: function(config) {
          config = config || {};
          return repositories.withHttpConfig(config).getList();
        },

        /**
         * Get a repository
         * @param  {string} name
         * @param  {object} config
         * @return {promise}
         */
        getRepository: function(name, config) {
          config = config || {};
          return repository(name).withHttpConfig(config).get();
        },

        /**
         * Get all workspaces in a repository
         * @param  {string} repositoryName
         * @param  {object} config
         * @return {promise}
         */
        getWorkspaces: function(repositoryName, config) {
          config = config || {};
          return workspaces(repositoryName).withHttpConfig(config).getList();
        },

        /**
         * Get a workspace in a repository
         * @param  {string} repositoryName
         * @param  {string} name
         * @param  {object} config
         * @return {promise}
         */
        getWorkspace: function(repositoryName, name, config) {
          config = config || {};
          return workspace(repositoryName, name).withHttpConfig(config).get();
        },

        /**
         * Create a workspace in a repository
         * @param  {string} repositoryName
         * @param  {string} name
         * @param  {object} config
         * @return {promise}
         */
        createWorkspace: function(repositoryName, name, config) {
          config = config || {};
          return workspaces(repositoryName).withHttpConfig(config).post({ name: name });
        },

        /**
         * Delete a workspace in a repository
         * @param  {string} repositoryName
         * @param  {string} name
         * @param  {object} config
         * @return {promise}
         */
        deleteWorkspace: function(repositoryName, name, config) {
          config = config || {};
          return workspace(repositoryName, name).withHttpConfig(config).remove();
        },

        /**
         * Get a node in a workspace
         * @param  {string} repositoryName
         * @param  {string} workspaceName
         * @param  {string} path
         * @param  {object} config
         * @return {promise}
         */
        getNode: function(repositoryName, workspaceName, path, config) {
          config = config || {};
          var params;
          if (config.reducedTree) {
            params = { reducedTree: true };
            delete config.reducedTree;
          } else{
            params = {};
          }
          return node(repositoryName, workspaceName, path).withHttpConfig(config).get(params);
        },

        /**
         * Create a node in a workspace
         * @param  {string} repositoryName
         * @param  {string} workspaceName
         * @param  {string} parentPath
         * @param  {string} relPath
         * @param  {object} config
         * @return {promise}
         */
        createNode: function(repositoryName, workspaceName, parentPath, relPath, config) {
          config = config || {};
          return nodeCollection(repositoryName, workspaceName, parentPath).withHttpConfig(config).post({ relPath: relPath});
        },

        /**
         * Delete a node in a workspace
         * @param  {string} repositoryName
         * @param  {string} workspaceName
         * @param  {string} path
         * @param  {object} config
         * @return {promise}
         */
        deleteNode: function(repositoryName, workspaceName, path, config) {
          config = config || {};
          return node(repositoryName, workspaceName, path).withHttpConfig(config).remove();
        },

        /**
         * Move a node in a workspace
         * @param  {string} repositoryName
         * @param  {string} workspaceName
         * @param  {string} path
         * @param  {string} newPath
         * @param  {object} config
         * @return {promise}
         */
        moveNode: function(repositoryName, workspaceName, path, newPath, config) {
          config = config || {};
          return node(repositoryName, workspaceName, path).withHttpConfig(config).put({
            method:      'move',
            destAbsPath: newPath
          });
        },

        /**
         * Rename a node in a workspace
         * @param  {string} repositoryName
         * @param  {string} workspaceName
         * @param  {string} path
         * @param  {string} newName
         * @param  {object} config
         * @return {promise}
         */
        renameNode: function(repositoryName, workspaceName, path, newName, config) {
          config = config || {};
          return node(repositoryName, workspaceName, path).withHttpConfig(config).put({
            method: 'rename',
            newName: newName
          });
        },

        /**
         * Create a property in a node
         * @param  {string} repositoryName
         * @param  {string} workspaceName
         * @param  {string} path
         * @param  {string} propertyName
         * @param  {mixed} propertyValue
         * @param  {string} propertyType
         * @param  {object} config
         * @return {promise}
         */
        createNodeProperty: function(repositoryName, workspaceName, path, propertyName, propertyValue, propertyType, config) {
          config = config || {};
          if (propertyType) {
            return nodeProperties(repositoryName, workspaceName, path).withHttpConfig(config).post({ name: propertyName, value: propertyValue, type: propertyType });
          }
          return nodeProperties(repositoryName, workspaceName, path).withHttpConfig(config).post({ name: propertyName, value: propertyValue });
        },

        /**
         * Delete a property in a node
         * @param  {string} repositoryName
         * @param  {string} workspaceName
         * @param  {string} path
         * @param  {string} propertyName
         * @param  {object} config
         * @return {promise}
         */
        deleteNodeProperty: function(repositoryName, workspaceName, path, propertyName, config) {
          config = config || {};
          return nodeProperty(repositoryName, workspaceName, path, propertyName).withHttpConfig(config).remove();
        },

        /**
         * Update a property in a node
         * @param  {string} repositoryName
         * @param  {string} workspaceName
         * @param  {string} path
         * @param  {string} propertyName
         * @param  {mixed} propertyValue
         * @param  {string} propertyType
         * @param  {object} config
         * @return {promise}
         */
        updateNodeProperty: function(repositoryName, workspaceName, path, propertyName, propertyValue, propertyType, config) {
          config = config || {};
          return nodeProperties(repositoryName, workspaceName, path).withHttpConfig(config).post({ name: propertyName, value: propertyValue, type: propertyType });
        },
      };
    }];
  });
});
<|endoftext|>


<commit_before>/**********************************************************************
 *
 * purpose: build a simple hilite system for serach end query systems
 *
 * author:  Andrea Cappugi & Lorenzo Becchi
 *
 * TODO:
 *   - all
 *
 **********************************************************************
 *
 * Copyright (c)  2006, ominiverdi.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 **********************************************************************/

/******************************************************************************
 * wpsManager
 *
 * recive map name,layer name and extent and hilite requested shape
 *
 *****************************************************************************/
function wpsManager( oKaMap ) {

 	this.kaMap=oKaMap;
 	this.qId=0;
 	this.qLayer=null;
 	this.sessionId=null;
 	this.wpsCache='';
};
wpsManager.prototype.setWpsCache=function(dir){
 	this.wpsCache= dir;
}
wpsManager.prototype.query=function(map,extents,identifier,datainputs){
  // old string
  //map,extents,searchString,shapeIndex,tileIndex

   if (this.kaMap.sessionId)  szSessionIdP="&sessionId="+this.kaMap.sessionId;
    else szSessionIdP="";

   var params="map="+map+szSessionIdP+"&id="+this.qId;
   params += "&extents="+extents+"&identifier="+identifier;
   params += "&datainputs="+datainputs;
   params += "&wpsCache="+this.wpsCache;
 	//alert(params);
 	//showContent('tools/query/wpsManager.php?'+params);

  if (this.qLayer==null){
      this.createLayer();
    } else {
    for (i=0;i<this.qLayer.scales.length;i++)this.qLayer.scales[i]=1;
     this.qLayer.setVisibility( true );
     this.kaMap.triggerEvent( KAMAP_SCALE_CHANGED, this.kaMap.getCurrentScale());
     this.qLayer.setLayer(layers,this.qId);
    }
   call('../../ka-map/htdocs/tools/wps/wpsManager.php?'+params, this, this.queryResult);

};
wpsManager.prototype.queryResult=function(szResult ){
	if (szResult.substr(0, 1) != "/") {
        alert(szResult);
        return false;
    }
	//alert(szResult);
 	eval(szResult);

	if(queryResult==0){

       this.kaMap.sessionId  = this.sessionId;
	   var cMap = this.kaMap.getCurrentMap().name;
	   this.kaMap.paintLayer(this.qLayer);

     	this.qId++;

     }else{
//     	if(this.kaMap.getCurrentMap().getLayer("queryLayer")) this.kaMap.removeMapLayer("queryLayer");
		alert("No results for this query!");
	 }
 };
wpsManager.prototype.createLayer=function(){

     this.qLayer= new _wpsLayer("queryLayer",true,100,'PNG',false,layers,this.qId);
     this.kaMap.addMapLayer(this.qLayer);

     var legend=this.kaMap.getRawObject("group_wpsLayer");
    /* if(legend){

     var button= document.createElement('img');
     button.src=this.kaMap.server+"/images/legend_x.png";
     button.title="Remove Layer";
     button.alt="Remove Layer";
     button.qM=this;
     button.onclick = _queryManager_queryOnClick;
     legend.getElementsByTagName('tr')[0].appendChild(button);
     }*/

};
wpsManager_queryOnClick=function(){

     for (i=0;i<this.qM.qLayer.scales.length;i++)this.qM.qLayer.scales[i]=0;
     this.qM.qLayer.setVisibility( false );
     this.qM.kaMap.triggerEvent( KAMAP_SCALE_CHANGED, this.qM.kaMap.getCurrentScale() );
       if(this.qM.resultDiv )  this.qM.injectResult('');
 };
 <commit_msg>process output drawing over ka-map. version 008<commit_after>/**********************************************************************
 *
 * purpose: build a simple hilite system for serach end query systems
 *
 * author:  Andrea Cappugi & Lorenzo Becchi
 *
 * TODO:
 *   - all
 *
 **********************************************************************
 *
 * Copyright (c)  2006, ominiverdi.org
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 **********************************************************************/

/******************************************************************************
 * wpsManager
 *
 * recive map name,layer name and extent and hilite requested shape
 *
 *****************************************************************************/
function wpsManager( oKaMap ) {

 	this.kaMap=oKaMap;
 	this.qId=0;
 	this.qLayer=null;
 	this.sessionId=null;
 	this.wpsCache='';
};
wpsManager.prototype.setWpsCache=function(dir){
 	this.wpsCache= dir;
}
wpsManager.prototype.query=function(map,extents,identifier,datainputs){
  // old string
  //map,extents,searchString,shapeIndex,tileIndex

   if (this.kaMap.sessionId)  szSessionIdP="&sessionId="+this.kaMap.sessionId;
    else szSessionIdP="";

   var params="map="+map+szSessionIdP+"&id="+this.qId;
   params += "&extents="+extents+"&identifier="+identifier;
   params += "&datainputs="+datainputs;
   params += "&wpsCache="+this.wpsCache;
 	//alert(params);
 	//showContent('tools/query/wpsManager.php?'+params);

  if (this.qLayer==null){
      this.createLayer();
    } else {
    for (i=0;i<this.qLayer.scales.length;i++)this.qLayer.scales[i]=1;
     this.qLayer.setVisibility( true );
     this.kaMap.triggerEvent( KAMAP_SCALE_CHANGED, this.kaMap.getCurrentScale());
     this.qLayer.setLayer(layers,this.qId);
    }
   call('../../ka-map/htdocs/tools/wps/wpsManager.php?'+params, this, this.queryResult);

};
wpsManager.prototype.queryResult=function(szResult ){
	if (szResult.substr(0, 1) != "/") {
        alert(szResult);
        return false;
    }
	//alert(szResult);
 	eval(szResult);

	if(queryResult==0){

       this.kaMap.sessionId  = this.sessionId;
	   var cMap = this.kaMap.getCurrentMap().name;

	   this.kaMap.paintLayer(this.qLayer);
	   alert(cMap);
     	this.qId++;

     }else{
//     	if(this.kaMap.getCurrentMap().getLayer("queryLayer")) this.kaMap.removeMapLayer("queryLayer");
		alert("No results for this query!");
	 }
 };
wpsManager.prototype.createLayer=function(){

     this.qLayer= new _wpsLayer(this.identifier,true,100,'PNG',false,this.identifier,this.qId);
     this.kaMap.addMapLayer(this.qLayer);
	 alert('layer to add:' +this.identifier);
 	 /*
     var legend=this.kaMap.getRawObject("group_wpsLayer");
     if(legend){

     var button= document.createElement('img');
     button.src=this.kaMap.server+"/images/legend_x.png";
     button.title="Remove Layer";
     button.alt="Remove Layer";
     button.qM=this;
     button.onclick = _queryManager_queryOnClick;
     legend.getElementsByTagName('tr')[0].appendChild(button);
     }*/

};
wpsManager_queryOnClick=function(){

     for (i=0;i<this.qM.qLayer.scales.length;i++)this.qM.qLayer.scales[i]=0;
     this.qM.qLayer.setVisibility( false );
     this.qM.kaMap.triggerEvent( KAMAP_SCALE_CHANGED, this.qM.kaMap.getCurrentScale() );
       if(this.qM.resultDiv )  this.qM.injectResult('');
 };
 <|endoftext|>


<commit_before>/*
 * Graph general cash flow (balance over time)
 */

import { List as list } from 'immutable';

import { rgba } from '../../../../misc/color';
import {
    GRAPH_FUND_ITEM_WIDTH, GRAPH_FUND_ITEM_WIDTH_LARGE,
    GRAPH_FUND_ITEM_HEIGHT, GRAPH_FUND_ITEM_HEIGHT_LARGE
} from '../../../../misc/const';
import {
    COLOR_LOSS, COLOR_PROFIT, COLOR_DARK, FONT_AXIS_LABEL
} from '../../../../misc/config';
import { aFundItemGraphToggled } from '../../../../actions/graph.actions';
import { separateLine } from './helpers';

import { connect } from 'react-redux';
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import LineGraph from '../../../../components/graph/line';

function onDraw({ minX, minY, maxY, data, popout }, { ctx, height }, { pixX, pixY, drawCubicLine }) {
    // draw axes
    ctx.lineWidth = 1;
    if (popout) {
        ctx.fillStyle = rgba(COLOR_DARK);
        ctx.textBaseline = 'middle';
        ctx.textAlign = 'left';
        ctx.font = FONT_AXIS_LABEL;

        const range = maxY - minY;
        const increment = Math.round(Math.max(20, height / range) / (height / range) / 2) * 2;
        const start = Math.ceil(minY / increment) * increment;
        const numTicks = Math.ceil(range / increment);

        if (numTicks > 0) {
            new Array(numTicks)
                .fill(0)
                .forEach((tick, key) => {
                    const tickValue = start + key * increment;
                    const tickPos = Math.floor(pixY(tickValue)) + 0.5;
                    const tickName = `${tickValue.toFixed(1)}p`;
                    ctx.fillText(tickName, pixX(minX), tickPos);
                });
        }
    }

    // plot data
    ctx.lineWidth = 1.5;

    const { values: initialValues } = data
        .map(item => item.get(1))
        .reduce(({ values, last }, value, index) => {
            if (last === 0 && value > 0) {
                return {
                    values: [...values, value],
                    last: value
                };
            }

            return { values, last: value };

        }, {
            values: [data.getIn([0, 1])],
            last: data.getIn([0, 1])
        });

    const colorLoss = rgba(COLOR_LOSS);
    const colorProfit = rgba(COLOR_PROFIT);
    const colorValue = lineKey => {
        const initialValue = initialValues[lineKey];

        return value => {
            if (value < initialValue) {
                return colorLoss;
            }

            return colorProfit;
        };
    };

    const lines = separateLine(data);

    lines.forEach((line, key) => drawCubicLine(line, colorValue(key)));
}

function getDimensions({ popout }) {
    if (popout) {
        return { width: GRAPH_FUND_ITEM_WIDTH_LARGE, height: GRAPH_FUND_ITEM_HEIGHT_LARGE };
    }

    return { width: GRAPH_FUND_ITEM_WIDTH, height: GRAPH_FUND_ITEM_HEIGHT };
}

function processData({ data, ...props }) {
    const validData = data.filter(item => item.last() !== 0);

    const dataY = validData.map(item => item.last());
    const dataX = validData.map(item => item.first());

    const minY = dataY.min();
    const maxY = dataY.max();
    const minX = dataX.min();
    const maxX = dataX.max();

    return { minX, maxX, minY, maxY, ...getDimensions(props) };
}

function GraphFundItem({ id, onToggle, ...props }) {
    const canvasProperties = {
        onClick: () => () => onToggle(id)
    };

    const canvasClasses = classNames({ popout: props.popout });

    return <LineGraph
        name={id}
        canvasProperties={canvasProperties}
        canvasClasses={canvasClasses}
        onDraw={onDraw}
        colorTransition={[null]}
        {...processData(props)}
        {...props}
    />;
}

GraphFundItem.propTypes = {
    id: PropTypes.number.isRequired,
    data: PropTypes.instanceOf(list).isRequired,
    popout: PropTypes.bool.isRequired,
    onToggle: PropTypes.func.isRequired
};

const mapStateToProps = (state, ownProps) => ({
    data: state.getIn(['pages', 'funds', 'rows', ownProps.id, 'prices']) || list.of(),
    popout: Boolean(state.getIn(['pages', 'funds', 'rows', ownProps.id, 'historyPopout']))
});

const mapDispatchToProps = dispatch => ({
    onToggle: id => dispatch(aFundItemGraphToggled(id))
});

export default connect(mapStateToProps, mapDispatchToProps)(GraphFundItem);

<commit_msg>Removed unnecessary index in loop<commit_after>/*
 * Graph general cash flow (balance over time)
 */

import { List as list } from 'immutable';

import { rgba } from '../../../../misc/color';
import {
    GRAPH_FUND_ITEM_WIDTH, GRAPH_FUND_ITEM_WIDTH_LARGE,
    GRAPH_FUND_ITEM_HEIGHT, GRAPH_FUND_ITEM_HEIGHT_LARGE
} from '../../../../misc/const';
import {
    COLOR_LOSS, COLOR_PROFIT, COLOR_DARK, FONT_AXIS_LABEL
} from '../../../../misc/config';
import { aFundItemGraphToggled } from '../../../../actions/graph.actions';
import { separateLine } from './helpers';

import { connect } from 'react-redux';
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import LineGraph from '../../../../components/graph/line';

function onDraw({ minX, minY, maxY, data, popout }, { ctx, height }, { pixX, pixY, drawCubicLine }) {
    // draw axes
    ctx.lineWidth = 1;
    if (popout) {
        ctx.fillStyle = rgba(COLOR_DARK);
        ctx.textBaseline = 'middle';
        ctx.textAlign = 'left';
        ctx.font = FONT_AXIS_LABEL;

        const range = maxY - minY;
        const increment = Math.round(Math.max(20, height / range) / (height / range) / 2) * 2;
        const start = Math.ceil(minY / increment) * increment;
        const numTicks = Math.ceil(range / increment);

        if (numTicks > 0) {
            new Array(numTicks)
                .fill(0)
                .forEach((tick, key) => {
                    const tickValue = start + key * increment;
                    const tickPos = Math.floor(pixY(tickValue)) + 0.5;
                    const tickName = `${tickValue.toFixed(1)}p`;
                    ctx.fillText(tickName, pixX(minX), tickPos);
                });
        }
    }

    // plot data
    ctx.lineWidth = 1.5;

    const { values: initialValues } = data
        .map(item => item.get(1))
        .reduce(({ values, last }, value) => {
            if (last === 0 && value > 0) {
                return {
                    values: [...values, value],
                    last: value
                };
            }

            return { values, last: value };

        }, {
            values: [data.getIn([0, 1])],
            last: data.getIn([0, 1])
        });

    const colorLoss = rgba(COLOR_LOSS);
    const colorProfit = rgba(COLOR_PROFIT);
    const colorValue = lineKey => {
        const initialValue = initialValues[lineKey];

        return value => {
            if (value < initialValue) {
                return colorLoss;
            }

            return colorProfit;
        };
    };

    const lines = separateLine(data);

    lines.forEach((line, key) => drawCubicLine(line, colorValue(key)));
}

function getDimensions({ popout }) {
    if (popout) {
        return { width: GRAPH_FUND_ITEM_WIDTH_LARGE, height: GRAPH_FUND_ITEM_HEIGHT_LARGE };
    }

    return { width: GRAPH_FUND_ITEM_WIDTH, height: GRAPH_FUND_ITEM_HEIGHT };
}

function processData({ data, ...props }) {
    const validData = data.filter(item => item.last() !== 0);

    const dataY = validData.map(item => item.last());
    const dataX = validData.map(item => item.first());

    const minY = dataY.min();
    const maxY = dataY.max();
    const minX = dataX.min();
    const maxX = dataX.max();

    return { minX, maxX, minY, maxY, ...getDimensions(props) };
}

function GraphFundItem({ id, onToggle, ...props }) {
    const canvasProperties = {
        onClick: () => () => onToggle(id)
    };

    const canvasClasses = classNames({ popout: props.popout });

    return <LineGraph
        name={id}
        canvasProperties={canvasProperties}
        canvasClasses={canvasClasses}
        onDraw={onDraw}
        colorTransition={[null]}
        {...processData(props)}
        {...props}
    />;
}

GraphFundItem.propTypes = {
    id: PropTypes.number.isRequired,
    data: PropTypes.instanceOf(list).isRequired,
    popout: PropTypes.bool.isRequired,
    onToggle: PropTypes.func.isRequired
};

const mapStateToProps = (state, ownProps) => ({
    data: state.getIn(['pages', 'funds', 'rows', ownProps.id, 'prices']) || list.of(),
    popout: Boolean(state.getIn(['pages', 'funds', 'rows', ownProps.id, 'historyPopout']))
});

const mapDispatchToProps = dispatch => ({
    onToggle: id => dispatch(aFundItemGraphToggled(id))
});

export default connect(mapStateToProps, mapDispatchToProps)(GraphFundItem);

<|endoftext|>


<commit_before>export const GET_COMMENTS = 'GET_COMMENTS';
export const GET_COMMENTS_START = 'GET_COMMENTS_START';
export const GET_COMMENTS_SUCCESS = 'GET_COMMENTS_SUCCESS';
export const GET_COMMENTS_ERROR = 'GET_COMMENTS_ERROR';

export const GET_MORE_COMMENTS = 'GET_MORE_COMMENTS';
export const GET_MORE_COMMENTS_START = 'GET_MORE_COMMENTS_START';
export const GET_MORE_COMMENTS_SUCCESS = 'GET_MORE_COMMENTS_SUCCESS';
export const GET_MORE_COMMENTS_ERROR = 'GET_MORE_COMMENTS_ERROR';

export const SHOW_MORE_COMMENTS = 'SHOW_MORE_COMMENTS';

export const SEND_COMMENT = 'SEND_COMMENT';
export const SEND_COMMENT_START = 'SEND_COMMENT_START';
export const SEND_COMMENT_SUCCESS = 'SEND_COMMENT_SUCCESS';
export const SEND_COMMENT_ERROR = 'SEND_COMMENT_ERROR';

export const OPEN_COMMENTING_DRAFT = 'OPEN_COMMENTING_DRAFT';
export const UPDATE_COMMENTING_DRAFT = 'UPDATE_COMMENTING_DRAFT';
export const CLOSE_COMMENTING_DRAFT = 'CLOSE_COMMENTING_DRAFT';
<commit_msg>remove more actionTypes for comment<commit_after>export const GET_COMMENTS = 'GET_COMMENTS';
export const GET_COMMENTS_START = 'GET_COMMENTS_START';
export const GET_COMMENTS_SUCCESS = 'GET_COMMENTS_SUCCESS';
export const GET_COMMENTS_ERROR = 'GET_COMMENTS_ERROR';

export const SHOW_MORE_COMMENTS = 'SHOW_MORE_COMMENTS';

export const SEND_COMMENT = 'SEND_COMMENT';
export const SEND_COMMENT_START = 'SEND_COMMENT_START';
export const SEND_COMMENT_SUCCESS = 'SEND_COMMENT_SUCCESS';
export const SEND_COMMENT_ERROR = 'SEND_COMMENT_ERROR';

export const OPEN_COMMENTING_DRAFT = 'OPEN_COMMENTING_DRAFT';
export const UPDATE_COMMENTING_DRAFT = 'UPDATE_COMMENTING_DRAFT';
export const CLOSE_COMMENTING_DRAFT = 'CLOSE_COMMENTING_DRAFT';
<|endoftext|>


<commit_before>import React from 'react';
import Relay from 'react-relay';
import ActionLockOpen from 'material-ui/svg-icons/action/lock-open';
import Avatar from 'material-ui/Avatar';
import { Menu, MenuItem } from 'material-ui/Menu';
import IconButton from 'material-ui/IconButton';
import Popover from 'material-ui/Popover';
import NavigationMenu from 'material-ui/svg-icons/navigation/menu';
import RaisedButton from 'material-ui/RaisedButton';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import { fullWhite, lightBlue900 } from 'material-ui/styles/colors';
import { Link } from 'react-router';

import theme from '../theme';

class Navigation extends React.Component {
    static propTypes = {
        viewer: React.PropTypes.object,
        organization: React.PropTypes.object,
        //socket: React.PropTypes.object,
    }

    static childContextTypes = {
        muiTheme: React.PropTypes.object.isRequired,
    };

    state = {
        open: false,
    }

    getChildContext() {
        return { muiTheme: getMuiTheme(theme) };
    }

    handleOpen = (event) => {
        // This prevents ghost click.
        event.preventDefault();

        this.setState({
            open: true,
            anchorEl: event.currentTarget,
        });
    }

    handleClose = () => {
        this.setState({
            open: false,
        });
    }

    render() {
        const viewer = this.props.viewer;
        const org = this.props.organization;
        const isMember = org.isMember;
        const logo = (
            <Link
                to="/"
                onClick={this.handleClose}
                style={{
                    padding: '19px 10px 20px 9px',
                }}
            >

            </Link>
        );

        return (

                            {logo}

                            <Link to="/om" style={{ color: 'white' }}>
                                Om oss
                            </Link>
                            <Link to="/projects" style={{ color: 'white' }}>
                                Konserter
                            </Link>
                            <Link to="/members" style={{ color: 'white' }}>
                                Medlemmer
                            </Link>
                            <Link to="/stott-oss" style={{ color: 'white' }}>
                                Støtt oss
                            </Link>

                            {isMember
                                ? <Link to="/files">Filer</Link>
                                : null
                            }
                            {isMember
                                ? <Link to="/pages">Sider</Link>
                                : null
                            }
                            {isMember
                                ? <Link to="/events">Aktiviteter</Link>
                                : null
                            }
                            {isMember
                                ? <Link to="/music">Notearkiv</Link>
                                : null
                            }
                            {viewer
                                ? <Link
                                    to={`/users/${viewer.id}`}
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        margin: '-5px 0',
                                        color: 'white',
                                    }}
                                >
                                    <Avatar
                                        src={viewer.profilePicturePath}
                                        style={{ margin: '0 5px' }}
                                    />
                                    {viewer.name}
                                </Link>
                                : <Link
                                    to="/login"
                                    style={{
                                        padding: 0,
                                        margin: '12px 15px 12px 10px',
                                    }}
                                >
                                    <RaisedButton
                                        label="Logg inn"
                                        icon={<ActionLockOpen />}
                                    />
                                </Link>
                            }

                        {logo}

                        {this.props.viewer ? <Link to={`/users/${viewer.id}`}>
                            <Avatar
                                src={viewer.profilePicturePath}
                            />
                        </Link>
                        : <Link to="/login">
                            <RaisedButton
                                style={{ minWidth: 44, marginLeft: 10 }}
                                icon={<ActionLockOpen />}
                            />
                        </Link>
                        }

                        <IconButton
                            className="flex-menu-handler"
                            onClick={this.handleOpen}
                            touch
                        >
                            <NavigationMenu color={fullWhite} />
                        </IconButton>
                        <Popover
                            open={this.state.open}
                            anchorEl={this.state.anchorEl}
                            anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
                            targetOrigin={{ horizontal: 'right', vertical: 'top' }}
                            onRequestClose={this.handleClose}
                        >

                                <Menu>
                                    <MenuItem>
                                        <Link
                                            to="about"
                                            onClick={this.handleClose}
                                        >
                                            Om oss
                                        </Link>
                                    </MenuItem>
                                    <MenuItem>
                                        <Link
                                            to="/projects"
                                            onClick={this.handleClose}
                                        >
                                            Konserter
                                        </Link>
                                    </MenuItem>
                                    <MenuItem>
                                        <Link
                                            to="/members"
                                            onClick={this.handleClose}
                                        >
                                            Medlemmer
                                        </Link>
                                    </MenuItem>
                                    <MenuItem>
                                        <Link
                                            to="/stott-oss"
                                            onClick={this.handleClose}
                                        >
                                            Støtt oss
                                        </Link>
                                    </MenuItem>
                                </Menu>
                                {isMember
                                    ? <Menu>
                                        {isMember
                                            ? <MenuItem>
                                                <Link to="/files" onClick={this.handleClose}>
                                                    Filer
                                                </Link>
                                            </MenuItem>
                                            : null
                                        }
                                        {isMember
                                            ? <MenuItem>
                                                <Link to="/pages" onClick={this.handleClose}>
                                                    Sider
                                                </Link>
                                            </MenuItem>
                                            : null
                                        }
                                        {isMember
                                            ? <MenuItem>
                                                <Link to="/events" onClick={this.handleClose}>
                                                    Aktiviteter
                                                </Link>
                                            </MenuItem>
                                            : null
                                        }
                                        {isMember
                                            ? <MenuItem>
                                                <Link to="/music" onClick={this.handleClose}>
                                                    Notearkiv
                                                </Link>
                                            </MenuItem>
                                            : null
                                        }
                                    </Menu>
                                    : null
                                }

                        </Popover>

        );
    }
}

export default Relay.createContainer(Navigation, {
    fragments: {
        organization: () => Relay.QL`
        fragment on Organization {
            id
            isMember,
        }`,
        viewer: () => Relay.QL`
        fragment on User {
            id,
            name,
            profilePicturePath,
        }`,
    },
});
<commit_msg>Fix missing slash in Navigation, breaking the page when clicked.<commit_after>import React from 'react';
import Relay from 'react-relay';
import ActionLockOpen from 'material-ui/svg-icons/action/lock-open';
import Avatar from 'material-ui/Avatar';
import { Menu, MenuItem } from 'material-ui/Menu';
import IconButton from 'material-ui/IconButton';
import Popover from 'material-ui/Popover';
import NavigationMenu from 'material-ui/svg-icons/navigation/menu';
import RaisedButton from 'material-ui/RaisedButton';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import { fullWhite, lightBlue900 } from 'material-ui/styles/colors';
import { Link } from 'react-router';

import theme from '../theme';

class Navigation extends React.Component {
    static propTypes = {
        viewer: React.PropTypes.object,
        organization: React.PropTypes.object,
        //socket: React.PropTypes.object,
    }

    static childContextTypes = {
        muiTheme: React.PropTypes.object.isRequired,
    };

    state = {
        open: false,
    }

    getChildContext() {
        return { muiTheme: getMuiTheme(theme) };
    }

    handleOpen = (event) => {
        // This prevents ghost click.
        event.preventDefault();

        this.setState({
            open: true,
            anchorEl: event.currentTarget,
        });
    }

    handleClose = () => {
        this.setState({
            open: false,
        });
    }

    render() {
        const viewer = this.props.viewer;
        const org = this.props.organization;
        const isMember = org.isMember;
        const logo = (
            <Link
                to="/"
                onClick={this.handleClose}
                style={{
                    padding: '19px 10px 20px 9px',
                }}
            >

            </Link>
        );

        return (

                            {logo}

                            <Link to="/om" style={{ color: 'white' }}>
                                Om oss
                            </Link>
                            <Link to="/projects" style={{ color: 'white' }}>
                                Konserter
                            </Link>
                            <Link to="/members" style={{ color: 'white' }}>
                                Medlemmer
                            </Link>
                            <Link to="/stott-oss" style={{ color: 'white' }}>
                                Støtt oss
                            </Link>

                            {isMember
                                ? <Link to="/files">Filer</Link>
                                : null
                            }
                            {isMember
                                ? <Link to="/pages">Sider</Link>
                                : null
                            }
                            {isMember
                                ? <Link to="/events">Aktiviteter</Link>
                                : null
                            }
                            {isMember
                                ? <Link to="/music">Notearkiv</Link>
                                : null
                            }
                            {viewer
                                ? <Link
                                    to={`/users/${viewer.id}`}
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        margin: '-5px 0',
                                        color: 'white',
                                    }}
                                >
                                    <Avatar
                                        src={viewer.profilePicturePath}
                                        style={{ margin: '0 5px' }}
                                    />
                                    {viewer.name}
                                </Link>
                                : <Link
                                    to="/login"
                                    style={{
                                        padding: 0,
                                        margin: '12px 15px 12px 10px',
                                    }}
                                >
                                    <RaisedButton
                                        label="Logg inn"
                                        icon={<ActionLockOpen />}
                                    />
                                </Link>
                            }

                        {logo}

                        {this.props.viewer ? <Link to={`/users/${viewer.id}`}>
                            <Avatar
                                src={viewer.profilePicturePath}
                            />
                        </Link>
                        : <Link to="/login">
                            <RaisedButton
                                style={{ minWidth: 44, marginLeft: 10 }}
                                icon={<ActionLockOpen />}
                            />
                        </Link>
                        }

                        <IconButton
                            className="flex-menu-handler"
                            onClick={this.handleOpen}
                            touch
                        >
                            <NavigationMenu color={fullWhite} />
                        </IconButton>
                        <Popover
                            open={this.state.open}
                            anchorEl={this.state.anchorEl}
                            anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
                            targetOrigin={{ horizontal: 'right', vertical: 'top' }}
                            onRequestClose={this.handleClose}
                        >

                                <Menu>
                                    <MenuItem>
                                        <Link
                                            to="/about"
                                            onClick={this.handleClose}
                                        >
                                            Om oss
                                        </Link>
                                    </MenuItem>
                                    <MenuItem>
                                        <Link
                                            to="/projects"
                                            onClick={this.handleClose}
                                        >
                                            Konserter
                                        </Link>
                                    </MenuItem>
                                    <MenuItem>
                                        <Link
                                            to="/members"
                                            onClick={this.handleClose}
                                        >
                                            Medlemmer
                                        </Link>
                                    </MenuItem>
                                    <MenuItem>
                                        <Link
                                            to="/stott-oss"
                                            onClick={this.handleClose}
                                        >
                                            Støtt oss
                                        </Link>
                                    </MenuItem>
                                </Menu>
                                {isMember
                                    ? <Menu>
                                        {isMember
                                            ? <MenuItem>
                                                <Link to="/files" onClick={this.handleClose}>
                                                    Filer
                                                </Link>
                                            </MenuItem>
                                            : null
                                        }
                                        {isMember
                                            ? <MenuItem>
                                                <Link to="/pages" onClick={this.handleClose}>
                                                    Sider
                                                </Link>
                                            </MenuItem>
                                            : null
                                        }
                                        {isMember
                                            ? <MenuItem>
                                                <Link to="/events" onClick={this.handleClose}>
                                                    Aktiviteter
                                                </Link>
                                            </MenuItem>
                                            : null
                                        }
                                        {isMember
                                            ? <MenuItem>
                                                <Link to="/music" onClick={this.handleClose}>
                                                    Notearkiv
                                                </Link>
                                            </MenuItem>
                                            : null
                                        }
                                    </Menu>
                                    : null
                                }

                        </Popover>

        );
    }
}

export default Relay.createContainer(Navigation, {
    fragments: {
        organization: () => Relay.QL`
        fragment on Organization {
            id
            isMember,
        }`,
        viewer: () => Relay.QL`
        fragment on User {
            id,
            name,
            profilePicturePath,
        }`,
    },
});
<|endoftext|>