<commit_before>(function(fm, $, ng, undefined) {

	fm.app.factory("fmMapSearchRoute", function($rootScope, $templateCache, $compile, fmUtils, L, $timeout, $q, fmSortableOptions) {
		return function(map, searchUi) {
			var lineStyle = {
				color : '#0000ff',
				weight : 8,
				opacity : 0.7
			};

			var dragTimeout = 300;

			var scope = map.socket.$new();

			scope.routeMode = 'car';
			scope.destinations = [ ];

			scope.sortableOptions = ng.copy(fmSortableOptions);
			scope.sortableOptions.update = function() {
				scope.reroute();
			};

			scope.addDestination = function() {
				scope.destinations.push({
					query: "",
					suggestions: [ ]
				});
			};

			scope.addDestination();
			scope.addDestination();

			scope.removeDestination = function(idx) {
				scope.destinations.splice(idx, 1);
				scope.reroute();
			};

			scope.showSearchForm = function() {
				routeUi.hide();
				searchUi.show();
			};

			scope.loadSuggestions = function(destination) {
				if(destination.suggestionQuery == destination.query)
					return $q.resolve();

				if(destination.query.trim() == "") {
					destination.suggestions = [ ];
					destination.suggestionQuery = destination.query;
				} else {
					var query = destination.query;

					return map.socket.emit("find", { query: query }).then(function(results) {
						if(fmUtils.isSearchId(query) && results.length > 0 && results[0].display_name)
							destination.query = query = results[0].display_name;

						destination.suggestions = results;
						destination.suggestionQuery = query;
						destination.selectedSuggestionIdx = 0;
					}).catch(function(err) {
						map.messages.showMessage("danger", err);
					});
				}
			};

			scope.route = function(dragging, noZoom) {
				if(!dragging)
					scope.reset();

				if(scope.destinations[0].query.trim() == "" || scope.destinations[scope.destinations.length-1].query.trim() == "")
					return;

				var points;
				var mode = scope.routeMode;

				return $q.all(scope.destinations.map(scope.loadSuggestions)).then(function() {
					points = scope.destinations.filter(function(destination) {
						return destination.query.trim() != "";
					}).map(function(destination) {
						if(destination.suggestions.length == 0)
							throw "No place has been found for search term “" + destination.query + "”.";

						return destination.suggestions[destination.selectedSuggestionIdx] || destination.suggestions[0];
					});

					return map.socket.emit("getRoute", { destinations: points.map(function(point) { return { lat: point.lat, lon: point.lon }; }), mode: mode });
				}).then(function(route) {
					route.routePoints = points;
					route.routeMode = mode;

					scope.routeObj = route;
					scope.routeError = null;
					renderRoute(dragging, noZoom);

					map.mapEvents.$emit("searchchange");
				}).catch(function(err) {
					scope.routeError = err;
				});
			};

			scope.reroute = function() {
				if(scope.routeObj || scope.routeError)
					scope.route();
			};

			scope.reset = function() {
				scope.routeObj = null;
				scope.routeError = null;

				clearRoute();
			};

			scope.clear = function() {
				scope.reset();

				scope.destinations = [ ];
				scope.addDestination();
				scope.addDestination();
			};

			scope.addToMap = function(type) {
				if(type == null) {
					for(var i in map.socket.types) {
						if(map.socket.types[i].type == "line") {
							type = map.socket.types[i];
							break;
						}
					}
				}

				map.linesUi.createLine(type, scope.routeObj.routePoints.map(function(point) { return { lat: point.lat, lon: point.lon }; }), { mode: scope.routeObj.routeMode });

				scope.clear();
			};

			var el = $($templateCache.get("map/search/search-route.html")).insertAfter(map.map.getContainer());
			$compile(el)(scope);
			scope.$evalAsync(); // $compile only replaces variables on next digest

			var routeLayer = null;
			var dragMarker = null;
			var markers = [ ];
			var recalcRoute = fmUtils.minInterval(dragTimeout, false);

			function renderRoute(dragging, noZoom) {
				clearRoute(dragging);

				routeLayer = L.polyline(scope.routeObj.trackPoints.map(function(it) { return [ it.lat, it.lon ] }), lineStyle).addTo(map.map);
				map.map.almostOver.addLayer(routeLayer);

				dragMarker = fmUtils.temporaryDragMarker(map.map, routeLayer, map.dragMarkerColour, function(marker) {
					var latlng = marker.getLatLng();
					var idx = fmUtils.getIndexOnLine(map.map, scope.routeObj.trackPoints, scope.routeObj.routePoints, { lat: latlng.lat, lon: latlng.lng });

					scope.destinations.splice(idx, 0, makeCoordDestination(latlng));
					markers.splice(idx, 0, marker);

					registerMarkerHandlers(marker);

					marker.once("dragend", updateMarkerColours);

					scope.route(true);
				}.fmWrapApply(scope));

				if(!dragging) {
					if(!noZoom)
						map.map.flyToBounds(routeLayer.getBounds());

					// Render markers

					scope.routeObj.routePoints.forEach(function(point, i) {
						var marker = L.marker([ point.lat, point.lon ], {
							icon: fmUtils.createMarkerIcon(map.dragMarkerColour, 35),
							draggable: true
						}).addTo(map.map);

						registerMarkerHandlers(marker);

						markers.push(marker);
					});

					updateMarkerColours();
				}
			}

			function registerMarkerHandlers(marker) {
				marker.on("dblclick", function() {
					scope.$apply(function() {
						scope.removeDestination(markers.indexOf(marker));
					});
				})
				.on("drag", function() {
					recalcRoute(function() {
						scope.destinations[markers.indexOf(marker)] = makeCoordDestination(marker.getLatLng());

						return scope.route(true);
					}.fmWrapApply(scope));
				});
			}

			function updateMarkerColours() {
				markers.forEach(function(marker, i) {
					var colour = (i == 0 ? map.startMarkerColour : i == markers.length-1 ? map.endMarkerColour : map.dragMarkerColour);

					marker.setIcon(fmUtils.createMarkerIcon(colour, 35));
				});
			}

			function clearRoute(dragging) {
				if(routeLayer) {
					map.map.almostOver.removeLayer(routeLayer);
					routeLayer.remove();
					routeLayer = null;
				}

				if(dragMarker) {
					dragMarker();
					dragMarker = null;
				}

				if(!dragging) {
					markers.forEach(function(marker) {
						marker.remove();
					});
					markers = [ ];
				}
			}

			function makeCoordDestination(latlng) {
				var disp = fmUtils.round(latlng.lat, 5) + "," + fmUtils.round(latlng.lng, 5);
				return {
					query: disp,
					suggestionQuery: disp,
					selectedSuggestionIdx: 0,
					suggestions: [ {
						lat: latlng.lat,
						lon: latlng.lng,
						display_name: disp,
						short_name: disp,
						type: "coordinates",
						id: disp
					} ]
				};
			}

			function _setDestination(dest, query, suggestions, selectedSuggestion) {
				dest.query = query;

				if(suggestions) {
					dest.suggestions = suggestions;
					dest.suggestionQuery = query;
					dest.selectedSuggestionIdx = Math.max(suggestions.indexOf(selectedSuggestion), 0);
				}
			}

			var routeUi = {
				show: function() {
					el.show();
				},

				hide: function() {
					scope.reset();
					el.hide();
				},

				setQueries: function(queries) {
					scope.clear();

					for(var i=0; i<queries.length; i++) {
						if(scope.destinations.length <= i)
							scope.addDestination();

						$.extend(scope.destinations[i], typeof queries[i] == "object" ? queries[i] : { query: queries[i] });
					}
				},

				setFrom: function(from, suggestions, selectedSuggestion) {
					_setDestination(scope.destinations[0], from, suggestions, selectedSuggestion);
				},

				addVia: function(via, suggestions, selectedSuggestion) {
					scope.addDestination();
					var newDest = scope.destinations.pop();
					_setDestination(newDest, via, suggestions, selectedSuggestion);
					scope.destinations.splice(scope.destinations.length-1, 0, newDest);
				},

				setTo: function(to, suggestions, selectedSuggestion) {
					_setDestination(scope.destinations[scope.destinations.length-1], to, suggestions, selectedSuggestion);
				},

				setMode: function(mode) {
					scope.routeMode = mode;
				},

				getQueries: function() {
					if(scope.routeObj) {
						return scope.routeObj.routePoints.map(function(point) {
							return point.id;
						});
					}
				},

				getMode: function(mode) {
					if(scope.routeObj) {
						return scope.routeObj.routeMode;
					}
				},

				submit: function(noZoom) {
					scope.route(false, noZoom);
				}
			};
			routeUi.hide();
			return routeUi;
		};
	});

})(FacilMap, jQuery, angular);<commit_msg>Add route to location hash on submit, not on result<commit_after>(function(fm, $, ng, undefined) {

	fm.app.factory("fmMapSearchRoute", function($rootScope, $templateCache, $compile, fmUtils, L, $timeout, $q, fmSortableOptions) {
		return function(map, searchUi) {
			var lineStyle = {
				color : '#0000ff',
				weight : 8,
				opacity : 0.7
			};

			var dragTimeout = 300;

			var scope = map.socket.$new();

			scope.routeMode = 'car';
			scope.destinations = [ ];
			scope.submittedQueries = null;
			scope.submittedMode = null;

			scope.sortableOptions = ng.copy(fmSortableOptions);
			scope.sortableOptions.update = function() {
				scope.reroute();
			};

			scope.addDestination = function() {
				scope.destinations.push({
					query: "",
					loadingQuery: "",
					loadedQuery: "",
					suggestions: [ ]
				});
			};

			scope.addDestination();
			scope.addDestination();

			scope.removeDestination = function(idx) {
				scope.destinations.splice(idx, 1);
				scope.reroute();
			};

			scope.showSearchForm = function() {
				routeUi.hide();
				searchUi.show();
			};

			scope.loadSuggestions = function(destination) {
				if(destination.loadedQuery == destination.query)
					return $q.resolve();

				destination.suggestions = [ ];
				var query = destination.loadingQuery = destination.query;

				if(destination.query.trim() != "") {
					return map.socket.emit("find", { query: query }).then(function(results) {
						if(query != destination.loadingQuery)
							return; // The destination has changed in the meantime

						if(fmUtils.isSearchId(query) && results.length > 0 && results[0].display_name)
							destination.query = query = results[0].display_name;

						destination.suggestions = results;
						destination.loadedQuery = query;
						destination.selectedSuggestionIdx = 0;
					}).catch(function(err) {
						map.messages.showMessage("danger", err);
					});
				}
			};

			scope.route = function(dragging, noZoom) {
				if(!dragging)
					scope.reset();

				if(scope.destinations[0].query.trim() == "" || scope.destinations[scope.destinations.length-1].query.trim() == "")
					return;

				var points;
				var mode = scope.routeMode;

				scope.submittedQueries = scope.destinations.map(function(destination) {
					if(destination.loadedQuery == destination.query && destination.suggestions.length)
						return destination.suggestions[destination.selectedSuggestionIdx].id || destination.suggestions[0].id;
					else
						return destination.query;
				});
				scope.submittedMode = mode;

				map.mapEvents.$emit("searchchange");

				return $q.all(scope.destinations.map(scope.loadSuggestions)).then(function() {
					points = scope.destinations.filter(function(destination) {
						return destination.query.trim() != "";
					}).map(function(destination) {
						if(destination.suggestions.length == 0)
							throw "No place has been found for search term “" + destination.query + "”.";

						return destination.suggestions[destination.selectedSuggestionIdx] || destination.suggestions[0];
					});

					scope.submittedQueries = points.map(function(point) {
						return point.id;
					});

					map.mapEvents.$emit("searchchange");

					return map.socket.emit("getRoute", { destinations: points.map(function(point) { return { lat: point.lat, lon: point.lon }; }), mode: mode });
				}).then(function(route) {
					route.routePoints = points;
					route.routeMode = mode;

					scope.routeObj = route;
					scope.routeError = null;
					renderRoute(dragging, noZoom);
				}).catch(function(err) {
					scope.routeError = err;
				});
			};

			scope.reroute = function() {
				if(scope.routeObj || scope.routeError)
					scope.route();
			};

			scope.reset = function() {
				scope.routeObj = null;
				scope.routeError = null;
				scope.submittedQueries = null;
				scope.submittedMode = null;

				clearRoute();
			};

			scope.clear = function() {
				scope.reset();

				scope.destinations = [ ];
				scope.addDestination();
				scope.addDestination();
			};

			scope.addToMap = function(type) {
				if(type == null) {
					for(var i in map.socket.types) {
						if(map.socket.types[i].type == "line") {
							type = map.socket.types[i];
							break;
						}
					}
				}

				map.linesUi.createLine(type, scope.routeObj.routePoints.map(function(point) { return { lat: point.lat, lon: point.lon }; }), { mode: scope.routeObj.routeMode });

				scope.clear();
			};

			var el = $($templateCache.get("map/search/search-route.html")).insertAfter(map.map.getContainer());
			$compile(el)(scope);
			scope.$evalAsync(); // $compile only replaces variables on next digest

			var routeLayer = null;
			var dragMarker = null;
			var markers = [ ];
			var recalcRoute = fmUtils.minInterval(dragTimeout, false);

			function renderRoute(dragging, noZoom) {
				clearRoute(dragging);

				routeLayer = L.polyline(scope.routeObj.trackPoints.map(function(it) { return [ it.lat, it.lon ] }), lineStyle).addTo(map.map);
				map.map.almostOver.addLayer(routeLayer);

				dragMarker = fmUtils.temporaryDragMarker(map.map, routeLayer, map.dragMarkerColour, function(marker) {
					var latlng = marker.getLatLng();
					var idx = fmUtils.getIndexOnLine(map.map, scope.routeObj.trackPoints, scope.routeObj.routePoints, { lat: latlng.lat, lon: latlng.lng });

					scope.destinations.splice(idx, 0, makeCoordDestination(latlng));
					markers.splice(idx, 0, marker);

					registerMarkerHandlers(marker);

					marker.once("dragend", updateMarkerColours);

					scope.route(true);
				}.fmWrapApply(scope));

				if(!dragging) {
					if(!noZoom)
						map.map.flyToBounds(routeLayer.getBounds());

					// Render markers

					scope.routeObj.routePoints.forEach(function(point, i) {
						var marker = L.marker([ point.lat, point.lon ], {
							icon: fmUtils.createMarkerIcon(map.dragMarkerColour, 35),
							draggable: true
						}).addTo(map.map);

						registerMarkerHandlers(marker);

						markers.push(marker);
					});

					updateMarkerColours();
				}
			}

			function registerMarkerHandlers(marker) {
				marker.on("dblclick", function() {
					scope.$apply(function() {
						scope.removeDestination(markers.indexOf(marker));
					});
				})
				.on("drag", function() {
					recalcRoute(function() {
						scope.destinations[markers.indexOf(marker)] = makeCoordDestination(marker.getLatLng());

						return scope.route(true);
					}.fmWrapApply(scope));
				});
			}

			function updateMarkerColours() {
				markers.forEach(function(marker, i) {
					var colour = (i == 0 ? map.startMarkerColour : i == markers.length-1 ? map.endMarkerColour : map.dragMarkerColour);

					marker.setIcon(fmUtils.createMarkerIcon(colour, 35));
				});
			}

			function clearRoute(dragging) {
				if(routeLayer) {
					map.map.almostOver.removeLayer(routeLayer);
					routeLayer.remove();
					routeLayer = null;
				}

				if(dragMarker) {
					dragMarker();
					dragMarker = null;
				}

				if(!dragging) {
					markers.forEach(function(marker) {
						marker.remove();
					});
					markers = [ ];
				}
			}

			function makeCoordDestination(latlng) {
				var disp = fmUtils.round(latlng.lat, 5) + "," + fmUtils.round(latlng.lng, 5);
				return {
					query: disp,
					loadingQuery: disp,
					loadedQuery: disp,
					selectedSuggestionIdx: 0,
					suggestions: [ {
						lat: latlng.lat,
						lon: latlng.lng,
						display_name: disp,
						short_name: disp,
						type: "coordinates",
						id: disp
					} ]
				};
			}

			function _setDestination(dest, query, suggestions, selectedSuggestion) {
				dest.query = query;

				if(suggestions) {
					dest.suggestions = suggestions;
					dest.loadingQuery = dest.loadedQuery = query;
					dest.selectedSuggestionIdx = Math.max(suggestions.indexOf(selectedSuggestion), 0);
				}
			}

			var routeUi = {
				show: function() {
					el.show();
				},

				hide: function() {
					scope.reset();
					el.hide();
				},

				setQueries: function(queries) {
					scope.clear();

					for(var i=0; i<queries.length; i++) {
						if(scope.destinations.length <= i)
							scope.addDestination();

						$.extend(scope.destinations[i], typeof queries[i] == "object" ? queries[i] : { query: queries[i] });
					}
				},

				setFrom: function(from, suggestions, selectedSuggestion) {
					_setDestination(scope.destinations[0], from, suggestions, selectedSuggestion);
				},

				addVia: function(via, suggestions, selectedSuggestion) {
					scope.addDestination();
					var newDest = scope.destinations.pop();
					_setDestination(newDest, via, suggestions, selectedSuggestion);
					scope.destinations.splice(scope.destinations.length-1, 0, newDest);
				},

				setTo: function(to, suggestions, selectedSuggestion) {
					_setDestination(scope.destinations[scope.destinations.length-1], to, suggestions, selectedSuggestion);
				},

				setMode: function(mode) {
					scope.routeMode = mode;
				},

				getQueries: function() {
					return scope.submittedQueries;
				},

				getMode: function() {
					return scope.submittedMode;
				},

				submit: function(noZoom) {
					scope.route(false, noZoom);
				}
			};
			routeUi.hide();
			return routeUi;
		};
	});

})(FacilMap, jQuery, angular);<|endoftext|>


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

    var GridSidebarComponent;
    var _ = require('underscore');
    var $ = require('jquery');
    var mediator = require('oroui/js/mediator');
    var routing = require('routing');
    var widgetManager = require('oroui/js/widget-manager');
    var BaseComponent = require('oroui/js/app/components/base/component');
    var PageableCollection = require('orodatagrid/js/pageable-collection');

    GridSidebarComponent = BaseComponent.extend({
        /**
         * @property {Object}
         */
        options: {
            sidebarAlias: '',
            widgetAlias: '',
            widgetRoute: 'oro_datagrid_widget',
            widgetRouteParameters: {
                gridName: ''
            },
            gridParam: 'grid'
        },

        /**
         * @property {Object}
         */
        listen: {
            'grid_load:complete mediator': 'onGridLoadComplete'
        },

        /**
         * @property {Object}
         */
        gridCollection: {},

        /**
         * {@inheritDoc}
         */
        initialize: function(options) {
            this.options = _.defaults(options || {}, this.options);
            mediator.on('grid-sidebar:change:' + this.options.sidebarAlias, this.onSidebarChange, this);
        },

        /**
         * @param {Object} collection
         */
        onGridLoadComplete: function(collection) {
            if (collection.inputName === this.options.widgetRouteParameters.gridName) {
                this.gridCollection = collection;

                var self = this;
                widgetManager.getWidgetInstanceByAlias(
                    this.options.widgetAlias,
                    function() {
                        self._patchGridCollectionUrl(self._getQueryParamsFromUrl(location.search));
                    }
                );
            }
            mediator.trigger('grid-sidebar:load:' + this.options.sidebarAlias);
        },

        /**
         * @param {Object} data
         */
        onSidebarChange: function(data) {
            var params = _.extend(
                this._getQueryParamsFromUrl(location.search),
                this._getDatagridParams(),
                data.params
            );
            data = _.extend({reload: true, updateUrl: true}, data);
            var widgetParams = _.extend(
                _.omit(this.options.widgetRouteParameters, this.options.gridParam),
                params
            );

            if (data.updateUrl) {
                this._pushState(_.omit(params, _.isNull));
            }

            this._patchGridCollectionUrl(params);

            if (_.has(this.gridCollection, 'state')) {
                this.gridCollection.state.currentPage = 1;
            }
            if (data.reload) {
                if (data.widgetReload) {
                    var self = this;
                    widgetManager.getWidgetInstanceByAlias(
                        this.options.widgetAlias,
                        function(widget) {
                            widget.setUrl(routing.generate(self.options.widgetRoute, widgetParams));
                            widget.render();
                        }
                    );
                } else {
                    mediator.trigger('datagrid:doRefresh:' + widgetParams.gridName);
                }
            }
        },

        /**
         * @param {Object} params
         * @private
         */
        _patchGridCollectionUrl: function(params) {
            var collection = this.gridCollection;
            if (!_.isUndefined(collection)) {
                var url = collection.url;
                if (_.isUndefined(url)) {
                    return;
                }
                var newParams = _.extend(
                    this._getQueryParamsFromUrl(url),
                    _.omit(params, this.options.gridParam)
                );
                if (url.indexOf('?') !== -1) {
                    url = url.substring(0, url.indexOf('?'));
                }
                if (!_.isEmpty(newParams)) {
                    collection.url = url + '?' + this._urlParamsToString(newParams);
                }
            }
        },

        /**
         * @private
         * @param {Object} params
         */
        _pushState: function(params) {
            var paramsString = this._urlParamsToString(_.omit(params, ['saveState']));
            var current = mediator.execute('pageCache:getCurrent');
            mediator.execute('changeUrl', current.path + '?' + paramsString);
        },

        /**
         * @param {String} url
         * @return {Object}
         * @private
         */
        _getQueryParamsFromUrl: function(url) {
            if (_.isUndefined(url)) {
                return {};
            }

            if (url.indexOf('?') === -1) {
                return {};
            }

            var query = url.substring(url.indexOf('?') + 1, url.length);
            if (!query.length) {
                return {};
            }

            return PageableCollection.decodeStateData(query);
        },

        /**
         * @param {Object} params
         * @return {String}
         * @private
         */
        _urlParamsToString: function(params) {
            return $.param(params);
        },

        /**
         * @returns {Object}
         * @private
         */
        _getDatagridParams: function() {
            var params = {};
            if (!_.has(this.gridCollection, 'options')) {
                return params;
            }
            params[this.gridCollection.options.gridName] = this.gridCollection.urlParams;

            return params;
        },

        dispose: function() {
            if (this.disposed) {
                return;
            }

            mediator.off('grid-sidebar:change:' + this.options.sidebarAlias);

            delete this.gridCollection;

            GridSidebarComponent.__super__.dispose.call(this);
        }
    });

    return GridSidebarComponent;
});
<commit_msg>BB-8829: Merge, test, demo (#10074)<commit_after>define(function(require) {
    'use strict';

    var GridSidebarComponent;
    var _ = require('underscore');
    var $ = require('jquery');
    var mediator = require('oroui/js/mediator');
    var routing = require('routing');
    var widgetManager = require('oroui/js/widget-manager');
    var BaseComponent = require('oroui/js/app/components/base/component');
    var PageableCollection = require('orodatagrid/js/pageable-collection');

    GridSidebarComponent = BaseComponent.extend({
        /**
         * @property {Object}
         */
        options: {
            sidebarAlias: '',
            widgetAlias: '',
            widgetRoute: 'oro_datagrid_widget',
            widgetRouteParameters: {
                gridName: ''
            },
            gridParam: 'grid'
        },

        /**
         * @property {Object}
         */
        listen: {
            'grid_load:complete mediator': 'onGridLoadComplete'
        },

        /**
         * @property {Object}
         */
        gridCollection: {},

        /**
         * {@inheritDoc}
         */
        initialize: function(options) {
            this.options = _.defaults(options || {}, this.options);
            mediator.on('grid-sidebar:change:' + this.options.sidebarAlias, this.onSidebarChange, this);
        },

        /**
         * @param {Object} collection
         * @param {Object} gridElement
         */
        onGridLoadComplete: function(collection, gridElement) {
            if (collection.inputName === this.options.widgetRouteParameters.gridName) {
                this.gridCollection = collection;

                var self = this;
                widgetManager.getWidgetInstanceByAlias(
                    this.options.widgetAlias,
                    function() {
                        self._patchGridCollectionUrl(self._getQueryParamsFromUrl(location.search));
                    }
                );

                var foundGrid = this.options._sourceElement
                    .closest('[data-role="grid-sidebar-component-container"]')
                    .find(gridElement);
                if (foundGrid.length) {
                    mediator.trigger('grid-sidebar:load:' + this.options.sidebarAlias);
                }
            }
        },

        /**
         * @param {Object} data
         */
        onSidebarChange: function(data) {
            var params = _.extend(
                this._getQueryParamsFromUrl(location.search),
                this._getDatagridParams(),
                data.params
            );
            data = _.extend({reload: true, updateUrl: true}, data);
            var widgetParams = _.extend(
                _.omit(this.options.widgetRouteParameters, this.options.gridParam),
                params
            );

            if (data.updateUrl) {
                this._pushState(_.omit(params, _.isNull));
            }

            this._patchGridCollectionUrl(params);

            if (_.has(this.gridCollection, 'state')) {
                this.gridCollection.state.currentPage = 1;
            }
            if (data.reload) {
                if (data.widgetReload) {
                    var self = this;
                    widgetManager.getWidgetInstanceByAlias(
                        this.options.widgetAlias,
                        function(widget) {
                            widget.setUrl(routing.generate(self.options.widgetRoute, widgetParams));
                            widget.render();
                        }
                    );
                } else {
                    mediator.trigger('datagrid:doRefresh:' + widgetParams.gridName);
                }
            }
        },

        /**
         * @param {Object} params
         * @private
         */
        _patchGridCollectionUrl: function(params) {
            var collection = this.gridCollection;
            if (!_.isUndefined(collection)) {
                var url = collection.url;
                if (_.isUndefined(url)) {
                    return;
                }
                var newParams = _.extend(
                    this._getQueryParamsFromUrl(url),
                    _.omit(params, this.options.gridParam)
                );
                if (url.indexOf('?') !== -1) {
                    url = url.substring(0, url.indexOf('?'));
                }
                if (!_.isEmpty(newParams)) {
                    collection.url = url + '?' + this._urlParamsToString(newParams);
                }
            }
        },

        /**
         * @private
         * @param {Object} params
         */
        _pushState: function(params) {
            var paramsString = this._urlParamsToString(_.omit(params, ['saveState']));
            var current = mediator.execute('pageCache:getCurrent');
            mediator.execute('changeUrl', current.path + '?' + paramsString);
        },

        /**
         * @param {String} url
         * @return {Object}
         * @private
         */
        _getQueryParamsFromUrl: function(url) {
            if (_.isUndefined(url)) {
                return {};
            }

            if (url.indexOf('?') === -1) {
                return {};
            }

            var query = url.substring(url.indexOf('?') + 1, url.length);
            if (!query.length) {
                return {};
            }

            return PageableCollection.decodeStateData(query);
        },

        /**
         * @param {Object} params
         * @return {String}
         * @private
         */
        _urlParamsToString: function(params) {
            return $.param(params);
        },

        /**
         * @returns {Object}
         * @private
         */
        _getDatagridParams: function() {
            var params = {};
            if (!_.has(this.gridCollection, 'options')) {
                return params;
            }
            params[this.gridCollection.options.gridName] = this.gridCollection.urlParams;

            return params;
        },

        dispose: function() {
            if (this.disposed) {
                return;
            }

            mediator.off('grid-sidebar:change:' + this.options.sidebarAlias);

            delete this.gridCollection;

            GridSidebarComponent.__super__.dispose.call(this);
        }
    });

    return GridSidebarComponent;
});
<|endoftext|>


<commit_before>$(document).ready(function () {
	oTable = $('#reports_table').dataTable({
		"bSortCellsTop": true,
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": $('#reports_table').data('ajax-url'),
		"aoColumnDefs": [
			{ "bSearchable": false, "aTargets": [ 1, 6 ] },
			{ "sClass": "center", "aTargets": [ 0, 1, 4, 5, 6] },
			{ "fnRender": function (oObj) {
					return '' + oObj.aData[1] + '';
				},
				"aTargets": [ 1 ]
			}
		],
		"aoColumns": [
			{ "sWidth": "1%" },
			{ "sWidth": "10%" },
			{ "sWidth": "20%" },
			{ "sWidth": "40%" },
			{ "sWidth": "15%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" }
		],
		"fnServerData": function (sSource, aoData, fnCallback) {
			$.getJSON(sSource, aoData, function (json) {
				fnCallback(json);
				// setup necessary CSS for linkable rows.
				$('#reports_table tbody tr').hover(function() {
					$(this).css('cursor', 'pointer');
				}, function() {
					$(this).css('cursor', 'auto');
				});
				// Stop Redirecting upon checkbox click event
				$('#reports_table td input').click(function (e) {
					e.stopPropagation();
				});
			});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			// click on the row anywhere to go to the report.
			$(nRow).click(function () {
				// extract the href from the anchor string
				document.location.href = $($.parseHTML(aData[1])).attr('href');
			});
		}
	});

	$('#notifications_table').dataTable({
		"bSortCellsTop": true,
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": $('#notifications_table').data('ajax-url'),
		"aoColumnDefs": [
			{ "bSearchable": false, "aTargets": [ 1 ] },
			{ "sClass": "center", "aTargets": [ 0, 1, 2, 3, 4, 5 ] }
		],
		"aoColumns": [
			{ "sWidth": "5%" },
			{ "sWidth": "10%" },
			{ "sWidth": "15%" },
			{ "sWidth": "30%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" }
		],
		"fnServerData": function (sSource, aoData, fnCallback) {
			$.getJSON(sSource, aoData, function (json) {
				fnCallback(json);
				// setup necessary CSS for linkable rows.
				$('#notifications_table tbody tr').hover(function() {
					$(this).css('cursor', 'pointer');
				}, function() {
					$(this).css('cursor', 'auto');
				});
				// Stop Redirecting upon checkbox click event
				$('#notifications_table td input').click(function (e) {
					e.stopPropagation();
				});
			});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			// click on the row anywhere to go to the report.
			$(nRow).click(function () {
				// extract the href from the anchor string
				document.location.href = $($.parseHTML(aData[1])).attr('href');
			});
		}
	});

	oTable.find("input").on('keyup', function (e) {
		// only search when enter is pressed
		if (e.keyCode == 13) {
			oTable.fnFilter($(this).val(), oTable.find("tr:last-child th").index($(this).parent()));
		}
	});

	oTable.find("select").on('change', function (e) {
		oTable.fnFilter($(this).val(), oTable.find("tr:last-child th").index($(this).parent()));
	});

	$('#toggle-stacktrace').click(function (e) {
		if ($('#stacktrace').hasClass('shown')) {
			$('#toggle-stacktrace').html('Show stacktrace');

			$('#stacktrace').slideUp(function () {
				$(this).removeClass('shown');
			});
		} else {
			$('#toggle-stacktrace').html('Hide stacktrace');

			$('#stacktrace').slideDown(function () {
				$(this).addClass('shown');
			});
		}
		return false;
	});

		$('#resultsForm_checkall').click(function () {
			if($(this).attr('checked') == 'checked') {
				$('#reports_table td input').attr('checked', 'checked');
			} else {
				$('#reports_table td input').removeAttr('checked');
			}
		});

	// display notifications count
	if (notifications_count > 0)
	{
		$('#nav_notifications a').html($('#nav_notifications a').html() + '(' + notifications_count + ')');
	}

	setTimeout(
		function () {
			$(".alert.alert-success").slideUp();
		},
		2000
	);

	SyntaxHighlighter.defaults.toolbar = false;
	SyntaxHighlighter.all();
});

function showStateForm() {
	$('#state-form').slideToggle();
}
<commit_msg>Enable state maintenance on reports page on refresh/back/forth: btw it came out to be a built in functionality<commit_after>$(document).ready(function () {
	oTable = $('#reports_table').dataTable({
		"bSortCellsTop": true,
		"bProcessing": true,
		"bServerSide": true,
		"bStateSave": true,
		"sAjaxSource": $('#reports_table').data('ajax-url'),
		"aoColumnDefs": [
			{ "bSearchable": false, "aTargets": [ 1, 6 ] },
			{ "sClass": "center", "aTargets": [ 0, 1, 4, 5, 6] },
			{ "fnRender": function (oObj) {
					return '' + oObj.aData[1] + '';
				},
				"aTargets": [ 1 ]
			}
		],
		"aoColumns": [
			{ "sWidth": "1%" },
			{ "sWidth": "10%" },
			{ "sWidth": "20%" },
			{ "sWidth": "40%" },
			{ "sWidth": "15%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" }
		],
		"fnServerData": function (sSource, aoData, fnCallback) {
			$.getJSON(sSource, aoData, function (json) {
				fnCallback(json);
				// setup necessary CSS for linkable rows.
				$('#reports_table tbody tr').hover(function() {
					$(this).css('cursor', 'pointer');
				}, function() {
					$(this).css('cursor', 'auto');
				});
				// Stop Redirecting upon checkbox click event
				$('#reports_table td input').click(function (e) {
					e.stopPropagation();
				});
			});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			// click on the row anywhere to go to the report.
			$(nRow).click(function () {
				// extract the href from the anchor string
				document.location.href = $($.parseHTML(aData[1])).attr('href');
			});
		}
	});

	$('#notifications_table').dataTable({
		"bSortCellsTop": true,
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": $('#notifications_table').data('ajax-url'),
		"aoColumnDefs": [
			{ "bSearchable": false, "aTargets": [ 1 ] },
			{ "sClass": "center", "aTargets": [ 0, 1, 2, 3, 4, 5 ] }
		],
		"aoColumns": [
			{ "sWidth": "5%" },
			{ "sWidth": "10%" },
			{ "sWidth": "15%" },
			{ "sWidth": "30%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" }
		],
		"fnServerData": function (sSource, aoData, fnCallback) {
			$.getJSON(sSource, aoData, function (json) {
				fnCallback(json);
				// setup necessary CSS for linkable rows.
				$('#notifications_table tbody tr').hover(function() {
					$(this).css('cursor', 'pointer');
				}, function() {
					$(this).css('cursor', 'auto');
				});
				// Stop Redirecting upon checkbox click event
				$('#notifications_table td input').click(function (e) {
					e.stopPropagation();
				});
			});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			// click on the row anywhere to go to the report.
			$(nRow).click(function () {
				// extract the href from the anchor string
				document.location.href = $($.parseHTML(aData[1])).attr('href');
			});
		}
	});

	oTable.find("input").on('keyup', function (e) {
		// only search when enter is pressed
		if (e.keyCode == 13) {
			oTable.fnFilter($(this).val(), oTable.find("tr:last-child th").index($(this).parent()));
		}
	});

	oTable.find("select").on('change', function (e) {
		oTable.fnFilter($(this).val(), oTable.find("tr:last-child th").index($(this).parent()));
	});

	$('#toggle-stacktrace').click(function (e) {
		if ($('#stacktrace').hasClass('shown')) {
			$('#toggle-stacktrace').html('Show stacktrace');

			$('#stacktrace').slideUp(function () {
				$(this).removeClass('shown');
			});
		} else {
			$('#toggle-stacktrace').html('Hide stacktrace');

			$('#stacktrace').slideDown(function () {
				$(this).addClass('shown');
			});
		}
		return false;
	});

		$('#resultsForm_checkall').click(function () {
			if($(this).attr('checked') == 'checked') {
				$('#reports_table td input').attr('checked', 'checked');
			} else {
				$('#reports_table td input').removeAttr('checked');
			}
		});

	// display notifications count
	if (notifications_count > 0)
	{
		$('#nav_notifications a').html($('#nav_notifications a').html() + '(' + notifications_count + ')');
	}

	setTimeout(
		function () {
			$(".alert.alert-success").slideUp();
		},
		2000
	);

	SyntaxHighlighter.defaults.toolbar = false;
	SyntaxHighlighter.all();
});

function showStateForm() {
	$('#state-form').slideToggle();
}
<|endoftext|>


<commit_before>// Copyright © 2012 Martin Ueding <dev@martin-ueding.de>

var animationTime = 300;

/**
 * The time that has to elapse since the last AJAX event was sent off.
 */
var idleTime = 500;

var currentData = [];
var animationActive = false;
var ajaxActive = false;
var lastChange = 0;
var currentQuery = "";

var searchMain = function () {
	showField();
	attachListener();
};

var showField = function () {
	console.debug('showField()');
	$('#navigation').after('
<input id="search_input" type="text" />
');
};

var attachListener = function () {
	console.debug('attachListener()');
	$('#search_input').keyup(formChanged);
};

var formChanged = function () {
	console.debug('formChanged()');
	var newQuery = $(this).val();
	if (newQuery == currentQuery) {
		return;
	}
	currentQuery = newQuery;
	lastChange = new Date().getTime();
	waitToQuery();
};

var waitToQuery = function () {
	console.debug('formChanged()');

	if (ajaxActive) {
		return;
	}

	var now = new Date().getTime();
	var elapsed = now - lastChange;

	if (elapsed > idleTime) {
		hideResultPane();
		performQuery();
	}
	else {
		var toWait = idleTime - elapsed;
		console.debug('formChanged(): Still have to wait '+toWait+'.');
		setTimeout(waitToQuery, toWait);
	}
};

var performQuery = function () {
	console.debug('perfomQuery()');
	ajaxActive = true;
	$.ajax({
		dataType: 'json',
		success: querySuccess,
		type: 'GET',
		url: 'bookmarks/search/'+currentQuery,
	});
};

var querySuccess = function (data, textStatus, jqXHR) {
	console.debug('querySuccess()');
	ajaxActive = false;
	console.debug(data);
	currentData = data;
	updateResultPane();
};

var initResultPane = function () {
	console.debug('initResultPane()');
	if ($('#search_result_pane').length == 0) {
		$('#search').append('

');
		$('#search_result_pane').slideUp(0);
	}
};

var hideResultPane = function () {
	console.debug('hideResultPane()');
	if ($('#search_result_pane').length > 0) {
		animationActive = true;
		$('#search_result_pane').slideUp(animationTime, animationDone);
	}
};

var updateResultPane = function () {
	console.debug('updateResultPane()');

	if (ajaxActive || animationActive) {
		console.debug('updateResultPane(): Quitting since active.');
		return;
	}

	initResultPane();
	var searchResultPane = $('#search_result_pane');
	searchResultPane.html(formatResults(currentData));
	searchResultPane.slideDown(animationTime);
};

var animationDone = function () {
	console.debug('animationDone()');
	animationActive = false;
	updateResultPane();
};

var formatResults = function (data) {
	console.debug('formatResults()');
	var parts = [];

	// TODO Limit this in PHP, and not here to save transfer time.
	for (var rowNum = 0; rowNum < data.length && rowNum < 10; rowNum++) {
		var row = data[rowNum];
		var hitTarget = 'bookmarks/visit/'+row.Bookmark.id
		parts.push('
');
		parts.push('');
		parts.push(row.Bookmark.title);
		parts.push('');
		parts.push('');
		parts.push(row.Bookmark.url);
		parts.push('');
		parts.push('
');
	}

	var result = '
'+parts.join('')+'
';
	console.debug(result);
	return result;
};

$(searchMain);
<commit_msg>Quit search on focus loss<commit_after>// Copyright © 2012 Martin Ueding <dev@martin-ueding.de>

var animationTime = 300;

/**
 * The time that has to elapse since the last AJAX event was sent off.
 */
var idleTime = 500;

var currentData = [];
var animationActive = false;
var ajaxActive = false;
var lastChange = 0;
var currentQuery = "";

var searchMain = function () {
	showField();
	attachListener();
};

var showField = function () {
	console.debug('showField()');
	$('#navigation').after('
<input id="search_input" type="text" />
');
	$('#search_input').focus();
	$('#search_input').focusout(exitSearch);
};

var attachListener = function () {
	console.debug('attachListener()');
	$('#search_input').keyup(formChanged);
};

var formChanged = function () {
	console.debug('formChanged()');
	var newQuery = $(this).val();
	if (newQuery == currentQuery) {
		return;
	}
	currentQuery = newQuery;
	lastChange = new Date().getTime();
	waitToQuery();
};

var waitToQuery = function () {
	console.debug('formChanged()');

	if (ajaxActive) {
		return;
	}

	var now = new Date().getTime();
	var elapsed = now - lastChange;

	if (elapsed > idleTime) {
		hideResultPane();
		performQuery();
	}
	else {
		var toWait = idleTime - elapsed;
		console.debug('formChanged(): Still have to wait '+toWait+'.');
		setTimeout(waitToQuery, toWait);
	}
};

var performQuery = function () {
	console.debug('perfomQuery()');
	ajaxActive = true;
	$.ajax({
		dataType: 'json',
		success: querySuccess,
		type: 'GET',
		url: 'bookmarks/search/'+currentQuery,
	});
};

var querySuccess = function (data, textStatus, jqXHR) {
	console.debug('querySuccess()');
	ajaxActive = false;
	console.debug(data);
	currentData = data;
	updateResultPane();
};

var initResultPane = function () {
	console.debug('initResultPane()');
	if ($('#search_result_pane').length == 0) {
		$('#search').append('

');
		$('#search_result_pane').slideUp(0);
	}
};

var hideResultPane = function () {
	console.debug('hideResultPane()');
	if ($('#search_result_pane').length > 0) {
		animationActive = true;
		$('#search_result_pane').slideUp(animationTime, animationDone);
	}
};

var updateResultPane = function () {
	console.debug('updateResultPane()');

	if (ajaxActive || animationActive) {
		console.debug('updateResultPane(): Quitting since active.');
		return;
	}

	if (currentData === null) {
		return;
	}

	initResultPane();
	var searchResultPane = $('#search_result_pane');
	searchResultPane.html(formatResults(currentData));
	searchResultPane.slideDown(animationTime);
};

var animationDone = function () {
	console.debug('animationDone()');
	animationActive = false;
	updateResultPane();
};

var formatResults = function (data) {
	console.debug('formatResults()');
	var parts = [];

	// TODO Limit this in PHP, and not here to save transfer time.
	for (var rowNum = 0; rowNum < data.length && rowNum < 10; rowNum++) {
		var row = data[rowNum];
		var hitTarget = 'bookmarks/visit/'+row.Bookmark.id
		parts.push('
');
		parts.push('');
		parts.push(row.Bookmark.title);
		parts.push('');
		parts.push('');
		parts.push(row.Bookmark.url);
		parts.push('');
		parts.push('
');
	}

	var result = '
'+parts.join('')+'
';
	console.debug(result);
	return result;
};

var exitSearch = function () {
	currentData = null;
	hideResultPane();
};

$(searchMain);
<|endoftext|>


<commit_before>"use strict";

// Extend the object
var extend = function(template, fields) {
  var object = {};
  for(var name in template) {
    object[name] = template[name];
  }

  for(var name in fields) {
   object[name] = fields[name];
  }

  return object;
}

exports['Successful connection to replicaset of 1 primary, 1 secondary and 1 arbiter'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(primary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(arbiter[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    server.on('joined', function(_type) {
      if(_type == 'arbiter' && _type == 'secondary') {
        if(server.s.replState.secondaries.length == 1
          && server.s.replState.arbiters.length == 1
          && server.s.replState.primary) {
            test.equal(true, server.__connected);

            test.equal(1, server.s.replState.secondaries.length);
            test.equal('localhost:32001', server.s.replState.secondaries[0].name);

            test.equal(1, server.s.replState.arbiters.length);
            test.equal('localhost:32002', server.s.replState.arbiters[0].name);

            test.ok(server.s.replState.primary != null);
            test.equal('localhost:32000', server.s.replState.primary.name);

            primaryServer.destroy();
            firstSecondaryServer.destroy();
            arbiterServer.destroy();
            server.destroy();
            running = false;

            test.done();
          }
      }
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Successful connection to replicaset of 1 primary, 1 secondary but missing arbiter'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var secondSecondaryServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(primary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {
      test.equal(true, server.__connected);

      test.equal(1, server.s.replState.secondaries.length);
      test.equal('localhost:32001', server.s.replState.secondaries[0].name);

      test.equal(0, server.s.replState.arbiters.length);

      test.ok(server.s.replState.primary != null);
      test.equal('localhost:32000', server.s.replState.primary.name);

      primaryServer.destroy();
      firstSecondaryServer.destroy();
      server.destroy();
      running = false;

      test.done();
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Fail to connect due to missing primary'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var firstSecondaryServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Boot the mock
    co(function*() {
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    server.on('error', function(error) {
      server.destroy();
      firstSecondaryServer.destroy();
      running = false;
      test.done();
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Successful connection to replicaset of 0 primary, 1 secondary and 1 arbiter with secondaryOnlyConnectionAllowed'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(arbiter[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1,
        secondaryOnlyConnectionAllowed: true
    });

    server.on('joined', function(_type) {
      if(_type == 'arbiter') {
        test.equal(true, server.__connected);

        test.equal(1, server.s.replState.secondaries.length);
        test.equal('localhost:32001', server.s.replState.secondaries[0].name);

        test.equal(1, server.s.replState.arbiters.length);
        test.equal('localhost:32002', server.s.replState.arbiters[0].name);

        test.ok(server.s.replState.primary == null);

        firstSecondaryServer.destroy();
        arbiterServer.destroy();
        server.destroy();
        running = false;

        test.done();
      }
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}
<commit_msg>fixing brittle tests<commit_after>"use strict";

// Extend the object
var extend = function(template, fields) {
  var object = {};
  for(var name in template) {
    object[name] = template[name];
  }

  for(var name in fields) {
   object[name] = fields[name];
  }

  return object;
}

exports['Successful connection to replicaset of 1 primary, 1 secondary and 1 arbiter'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(primary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(arbiter[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    server.on('joined', function(_type) {
      if(_type == 'arbiter' || _type == 'secondary') {
        if(server.s.replState.secondaries.length == 1
          && server.s.replState.arbiters.length == 1
          && server.s.replState.primary) {
            test.equal(true, server.__connected);

            test.equal(1, server.s.replState.secondaries.length);
            test.equal('localhost:32001', server.s.replState.secondaries[0].name);

            test.equal(1, server.s.replState.arbiters.length);
            test.equal('localhost:32002', server.s.replState.arbiters[0].name);

            test.ok(server.s.replState.primary != null);
            test.equal('localhost:32000', server.s.replState.primary.name);

            primaryServer.destroy();
            firstSecondaryServer.destroy();
            arbiterServer.destroy();
            server.destroy();
            running = false;

            test.done();
          }
      }
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Successful connection to replicaset of 1 primary, 1 secondary but missing arbiter'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var secondSecondaryServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(primary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {
      test.equal(true, server.__connected);

      test.equal(1, server.s.replState.secondaries.length);
      test.equal('localhost:32001', server.s.replState.secondaries[0].name);

      test.equal(0, server.s.replState.arbiters.length);

      test.ok(server.s.replState.primary != null);
      test.equal('localhost:32000', server.s.replState.primary.name);

      primaryServer.destroy();
      firstSecondaryServer.destroy();
      server.destroy();
      running = false;

      test.done();
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Fail to connect due to missing primary'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var firstSecondaryServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Boot the mock
    co(function*() {
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    server.on('error', function(error) {
      server.destroy();
      firstSecondaryServer.destroy();
      running = false;
      test.done();
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Successful connection to replicaset of 0 primary, 1 secondary and 1 arbiter with secondaryOnlyConnectionAllowed'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(arbiter[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1,
        secondaryOnlyConnectionAllowed: true
    });

    server.on('joined', function(_type) {
      if(_type == 'arbiter') {
        test.equal(true, server.__connected);

        test.equal(1, server.s.replState.secondaries.length);
        test.equal('localhost:32001', server.s.replState.secondaries[0].name);

        test.equal(1, server.s.replState.arbiters.length);
        test.equal('localhost:32002', server.s.replState.arbiters[0].name);

        test.ok(server.s.replState.primary == null);

        firstSecondaryServer.destroy();
        arbiterServer.destroy();
        server.destroy();
        running = false;

        test.done();
      }
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc directive
 * @name grafterizerApp.directive:previewTable
 * @description
 * # previewTable
 */
angular.module('grafterizerApp')
  .directive('previewTable', function() {
    return {
      template: '

\u2205

',
      restrict: 'E',
      scope: {
        data: '=ngModel'
      },
      link: function postLink(scope, element, attrs) {
        scope.gridOptions = {
          data:  null,
          columnDefs: [],
          headerRowHeight: 82,
          rowHeight: 38,
          showHeader: !attrs.hasOwnProperty('hideHeaders'),
          exporterMenuCsv: true,
          exporterMenuPdf: false,
          enableGridMenu: true,
          enableMinHeightCheck: false
        };

        scope.$watch('data', function() {
          var data = scope.data;
          if (!data || !data.hasOwnProperty(':rows')) {
            scope.gridOptions.data = null;
            return;
          }

          var widths = {};
          var rawWidths = {};

          _.each(data[':column-names'], function(f) {
            // the header size is 3 times more important
            widths[f] = f.length * 3;
          });

          var rows = data[':rows'];
          var largest = 0;

          {
            var i;
            var key;
            var irow;
            var w;
            var maxIter = Math.min(10, rows.length);

            for (i = 0; i < maxIter; ++i) {
              for (key in rows[i]) {
                irow = rows[i][key];
                w = widths[key];

                widths[key] += ('' + irow).length;
              }
            }

            var total = 0;
            for (key in widths) {
              widths[key] /= (maxIter + 3);
              rawWidths[key] = widths[key];
              total += widths[key];
            }

            for (key in widths) {
              widths[key] = w = widths[key] / total;
              if (w > largest) {
                largest = w;
              }
            }
          }

          scope.gridOptions.columnDefs =
            _.map(data[':column-names'], function(f) {
              var w = widths[f];
              var width = w === largest || isNaN(w) ? '*' : Math.floor(w * 100) + '%';
              var minWidth = isNaN(rawWidths[f]) ? 200 : Math.min(80 + rawWidths[f] * 8, 200);

              return {
                name: f,
                displayName: f,
                width: width,
                minWidth: minWidth,
                cellTooltip: true
              };
            });

          scope.gridOptions.data = rows;
        });
      }
    };
  });
<commit_msg>Names of columns are now displayed without the leading ':' put by Graftwerk<commit_after>'use strict';

/**
 * @ngdoc directive
 * @name grafterizerApp.directive:previewTable
 * @description
 * # previewTable
 */
angular.module('grafterizerApp')
  .directive('previewTable', function() {
    return {
      template: '

\u2205

',
      restrict: 'E',
      scope: {
        data: '=ngModel'
      },
      link: function postLink(scope, element, attrs) {
        scope.gridOptions = {
          data:  null,
          columnDefs: [],
          headerRowHeight: 82,
          rowHeight: 38,
          showHeader: !attrs.hasOwnProperty('hideHeaders'),
          exporterMenuCsv: true,
          exporterMenuPdf: false,
          enableGridMenu: true,
          enableMinHeightCheck: false
        };

        scope.$watch('data', function() {
          var data = scope.data;
          if (!data || !data.hasOwnProperty(':rows')) {
            scope.gridOptions.data = null;
            return;
          }

          var widths = {};
          var rawWidths = {};

          _.each(data[':column-names'], function(f) {
            // the header size is 3 times more important
            widths[f] = f.length * 3;
          });

          var rows = data[':rows'];
          var largest = 0;

          {
            var i;
            var key;
            var irow;
            var w;
            var maxIter = Math.min(10, rows.length);

            for (i = 0; i < maxIter; ++i) {
              for (key in rows[i]) {
                irow = rows[i][key];
                w = widths[key];

                widths[key] += ('' + irow).length;
              }
            }

            var total = 0;
            for (key in widths) {
              widths[key] /= (maxIter + 3);
              rawWidths[key] = widths[key];
              total += widths[key];
            }

            for (key in widths) {
              widths[key] = w = widths[key] / total;
              if (w > largest) {
                largest = w;
              }
            }
          }

          scope.gridOptions.columnDefs =
            _.map(data[':column-names'], function(f) {
              var w = widths[f];
              var width = w === largest || isNaN(w) ? '*' : Math.floor(w * 100) + '%';
              var minWidth = isNaN(rawWidths[f]) ? 200 : Math.min(80 + rawWidths[f] * 8, 200);

              return {
                name: f,
                displayName: f.substring(1),
                width: width,
                minWidth: minWidth,
                cellTooltip: true
              };
            });

          scope.gridOptions.data = rows;
        });
      }
    };
  });
<|endoftext|>


<commit_before>/**
 * Created by alejandrobarreiro on 8/10/15.
 */
angular.module('sapoApp')
  .service('almacenService', ['$q', 'Almacen', 'Usuario', 'authService', function ($q, Almacen, Usuario, authService) {

    this.init = function () {};

    this.getAlmacen = function(id) {
      var deferred = $q.defer();
      console.log('buscando almacen con id' + id);
      Almacen.getAlmacen({ id: id }, {}, function (almacen) {
        deferred.resolve(almacen);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.getAlmacenes = function() {
      var deferred = $q.defer();
      Almacen.getAlmacenes({}, {}, function (almacenes) {
        console.log(almacenes);
        deferred.resolve(almacenes);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.getMisAlmacenes = function () {
      var user = authService.getLoggedUser();

      var deferred = $q.defer();
      Usuario.getMisAlmacenes({userid: user.id}, {}, function (almacenes) {
        console.log(almacenes);
        deferred.resolve(almacenes);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.crearNuevaAlmacen = function (almacen) {
      //Esta logica se va a ir cuando se haga lo del token
      var user = authService.getLoggedUser();
      console.log(user);

      var deferred = $q.defer();
      Usuario.agregarAlmacen({userid: user.id}, almacen, function (almacenResult) {
        console.log(almacenResult);
        deferred.resolve(almacenResult);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.cargarCategoriasAlmacen = function (almacenId, categorias) {

      var deferred = $q.defer();
      Almacen.agregarCategorias({id: almacenId}, categorias, function (almacenResult) {
        console.log(almacenResult);
        deferred.resolve(almacenResult);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.cargarProductosAlmacen = function (almacenId, productos) {

      var deferred = $q.defer();
      Almacen.agregarProductos({id: almacenId}, productos, function (almacenResult) {
        console.log(almacenResult);
        deferred.resolve(almacenResult);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.agregarColaborador = function (almacenId, userId) {

      var deferred = $q.defer();
      Almacen.agregarColaborador({id: almacenId, userid: userId}, function (result) {
        deferred.resolve(result);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.validarAlmacen = function(almacen) {

      return almacen.nombre && almacen.nombre.length && almacen.id && almacen.id.length;
    }

  }]);<commit_msg>actualizar almacen service<commit_after>/**
 * Created by alejandrobarreiro on 8/10/15.
 */
angular.module('sapoApp')
  .service('almacenService', ['$q', 'Almacen', 'Usuario', 'authService', function ($q, Almacen, Usuario, authService) {

    this.init = function () {};

    this.getAlmacen = function(id) {
      var deferred = $q.defer();
      console.log('buscando almacen con id' + id);
      Almacen.getAlmacen({ id: id }, {}, function (almacen) {
        deferred.resolve(almacen);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.getAlmacenes = function() {
      var deferred = $q.defer();
      Almacen.getAlmacenes({}, {}, function (almacenes) {
        console.log(almacenes);
        deferred.resolve(almacenes);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.getMisAlmacenes = function () {
      var user = authService.getLoggedUser();

      var deferred = $q.defer();
      Usuario.getMisAlmacenes({userid: user.id}, {}, function (almacenes) {
        console.log(almacenes);
        deferred.resolve(almacenes);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.crearNuevaAlmacen = function (almacen) {
      //Esta logica se va a ir cuando se haga lo del token
      var user = authService.getLoggedUser();
      console.log(user);

      var deferred = $q.defer();
      Usuario.agregarAlmacen({userid: user.id}, almacen, function (almacenResult) {
        console.log(almacenResult);
        deferred.resolve(almacenResult);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.cargarCategoriasAlmacen = function (almacenId, categorias) {

      var deferred = $q.defer();
      Almacen.agregarCategorias({id: almacenId}, categorias, function (almacenResult) {
        console.log(almacenResult);
        deferred.resolve(almacenResult);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.cargarProductosAlmacen = function (almacenId, productos) {

      var deferred = $q.defer();
      Almacen.agregarProductos({id: almacenId}, productos, function (almacenResult) {
        console.log(almacenResult);
        deferred.resolve(almacenResult);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.agregarColaborador = function (almacenId, userId) {

      var deferred = $q.defer();
      Almacen.agregarColaborador({id: almacenId, userid: userId}, function (result) {
        deferred.resolve(result);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.actualizarAlmacen = function (almacenId, data) {

      var deferred = $q.defer();
      Almacen.actualizarAlmacen({id: almacenId}, data, function (result) {
        deferred.resolve(result);
      }, function (error) {
        deferred.reject(error);
      });
      return deferred.promise;
    };

    this.validarAlmacen = function(almacen) {

      return almacen.nombre && almacen.nombre.length && almacen.id && almacen.id.length;
    }

  }]);<|endoftext|>


<commit_before>'use strict';

/*
 * Wraps Marvel's rest API and does things like caching results and logging
 * errors
 */
angular.module('marvelQuizApp.common')
  .provider('MarvelWrapper', function MarvelWrapper() {

    /*
     * Private provider variables
     */

    // contains the Marvel API key to attach to every request
    var apiKey;

    /*
     * Public API for configuration
     */
    this.setApiKey = function (newKey) {
      apiKey = newKey;
    };

    /*
     * Service constructor
     */
    this.$get = function ($http, Cache, $q) {
      var BASE_URL = 'http://gateway.marvel.com/v1/public';

      // returns a promise for a constant value
      function future(value) {
        var deferred = $q.defer();

        deferred.resolve(value);

        return deferred.promise;
      }

      // common function that handles error responses from marvel services
      function marvelServiceError() {
        // TODO: inspect the error response and do something like logging
        // in order to monitor the app usage of the service

        // when maximum request number is exceeded, set some global variable
        // that completely disable the application with an alert

        // every time that a user the application tha has been disabled,
        // signal it somewhere so that I can keep track of it
      }

      /*
       * Get the total number of character present in the database
       */
      function totalCharacters() {
        var CACHE_KEY = 'totalCharacters';
        var cacheValue = Cache.get(CACHE_KEY);

        if (cacheValue) {
          return future(cacheValue);
        }
        else {
          return $http.get(BASE_URL + '/characters', {
            params: {
              limit: 1,
              apikey: apiKey
            }
          }).then(
            function (res) {
              var count = res.data.data.total;

              Cache.put(CACHE_KEY, count);
              return count;
            },
            marvelServiceError
          );
        }
      }

      /*
       * Interface to the "characters" service
       */
      function characters(params) {
        var CACHE_KEY = 'characters/' + angular.toJson(params);
        var cacheValue = Cache.get(CACHE_KEY);

        if (cacheValue) {
          return future(cacheValue);
        }
        else {
          return $http.get(BASE_URL + '/characters', {
            params: angular.extend(params, {
              apikey: apiKey
            })
          }).then(
            function (res) {
              var characters = res.data.data.results;

              Cache.put(CACHE_KEY, characters);
              return characters;
            },
            marvelServiceError
          );
        }
      }

      return {
        totalCharacters: totalCharacters,
        characters: characters
      };
    };

  });
<commit_msg>feat(marvel-wraper): add some tracking using analytics<commit_after>'use strict';

/*
 * Wraps Marvel's rest API and does things like caching results and logging
 * errors
 */
angular.module('marvelQuizApp.common')
  .provider('MarvelWrapper', function MarvelWrapperProvider() {

    /*
     * Private provider variables
     */

    // contains the Marvel API key to attach to every request
    var apiKey;

    /*
     * Public API for configuration
     */
    this.setApiKey = function (newKey) {
      apiKey = newKey;
    };

    /*
     * Service constructor
     */
    this.$get = function MarvelWrapper($http, Cache, $q, GoogleAnalytics) {
      var BASE_URL = 'http://gateway.marvel.com/v1/public';

      // returns a promise for a constant value
      function future(value) {
        var deferred = $q.defer();

        deferred.resolve(value);

        return deferred.promise;
      }

      // common function that handles error responses from marvel services
      function marvelServiceError(res) {
        // TODO: when maximum request number is exceeded, set some global variable
        // that completely disable the application with an alert

        // every time that a user access the application that has been disabled,
        // signal it somewhere so that I can keep track of it

        if (res.status === 429) {
          GoogleAnalytics.marvelServiceLimitExceeded();
        }
        else {
          GoogleAnalytics.marvelServiceError('' + res.status + ' - ' + res.data);
        }
      }

      /*
       * Get the total number of character present in the database
       */
      function totalCharacters() {
        var CACHE_KEY = 'totalCharacters';
        var cacheValue = Cache.get(CACHE_KEY);

        if (cacheValue) {
          return future(cacheValue);
        }
        else {
          return $http.get(BASE_URL + '/characters', {
            params: {
              limit: 1,
              apikey: apiKey
            }
          }).then(
            function (res) {
              var count = res.data.data.total;

              Cache.put(CACHE_KEY, count);
              GoogleAnalytics.marvelServiceRequest('characters');
              return count;
            },
            marvelServiceError
          );
        }
      }

      /*
       * Interface to the "characters" service
       */
      function characters(params) {
        var CACHE_KEY = 'characters/' + angular.toJson(params);
        var cacheValue = Cache.get(CACHE_KEY);

        if (cacheValue) {
          return future(cacheValue);
        }
        else {
          return $http.get(BASE_URL + '/characters', {
            params: angular.extend(params, {
              apikey: apiKey
            })
          }).then(
            function (res) {
              var characters = res.data.data.results;

              Cache.put(CACHE_KEY, characters);
              GoogleAnalytics.marvelServiceRequest('characters');
              return characters;
            },
            marvelServiceError
          );
        }
      }

      return {
        totalCharacters: totalCharacters,
        characters: characters
      };
    };

  });
<|endoftext|>


<commit_before>/**
 * @providesModule Site
 * @jsx React.DOM
 */

var React = require('React');
var HeaderLinks = require('HeaderLinks');

var Site = React.createClass({
  render: function() {
    return (

          <meta charSet="utf-8" />
          <meta httpEquiv="X-UA-Compatible" content="IE=edge,chrome=1" />
          <title>Flux | Application Architecture for Building User Interfaces</title>
          <meta name="viewport" content="width=device-width" />
          <meta property="og:title" content="Flux | Application Architecture for Building User Interfaces" />
          <meta property="og:type" content="website" />
          <meta property="og:url" content="http://facebook.github.io/flux/index.html" />
          <meta property="og:description" content="Application Architecture for Building User Interfaces" />

          <link rel="stylesheet" href="/flux/css/flux.css" />

                  Flux

                <HeaderLinks section={this.props.section} />

            {this.props.children}

© 2014-2015 Facebook Inc.

                  Flux

                <HeaderLinks section={this.props.section} />

            {this.props.children}

© 2014-2015 Facebook Inc.