<commit_before>/**
 * Digitizing tool set
 *
 * @author Andriy Oblivantsev <eslider@gmail.com>
 * @author Stefan Winkelmann <stefan.winkelmann@wheregroup.com>
 *
 * @copyright 20.04.2015 by WhereGroup GmbH & Co. KG
 */
(function($) {

    $.widget("vis-ui-js.digitizingToolSet", {

        options:           {
            layer:    null,
            // Open layer control events
            controlEvents: []
        },
        controls:          null,
        _activeControls:   [],
        currentController: null,

        /**
         * Init controls
         *
         * @private
         */
        _create: function() {
            var widget = this;
            var mapElement = widget.getMapElement();
            var layer = widget.getLayer();

            widget.controls = {
                drawPoint:      {
                    infoText: "Draw point",
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Point),
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        }
                    }
                },
                drawLine:       {
                    infoText: "Draw line",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        }

                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Path)
                },
                drawPolygon:    {
                    infoText: "Draw polygone",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }

                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Polygon)
                },
                drawRectangle:  {
                    infoText: "Draw rectangle",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }

                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.RegularPolygon, {
                        handlerOptions: {
                            sides:     4,
                            irregular: true
                        }
                    })
                },
                drawCircle:     {
                    infoText: "Draw circle",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }

                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.RegularPolygon, {
                        handlerOptions: {
                            sides: 40
                        }
                    })
                },
                drawEllipse:    {
                    infoText: "Draw ellipse",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }

                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.RegularPolygon, {
                        handlerOptions: {
                            sides:     40,
                            irregular: true
                        }
                    })
                },
                drawDonut:          {
                    infoText: "Draw donut",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }
                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Polygon, {
                        handlerOptions: {
                            holeModifier: 'element'
                        }
                    })
                },
                modifyFeature:           {
                    infoText: "Select and edit geometry position/size",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }

                    },
                    control:  new OpenLayers.Control.ModifyFeature(layer)
                },
                moveFeature:           {
                    infoText: "Move geometry",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'default'});
                        }
                        mapElement.css({cursor: 'default'});
                    },
                    control:  new OpenLayers.Control.DragFeature(layer, {
                        onStart:    function(feature) {
                            feature.renderIntent = 'select';
                        },
                        onComplete: function(feature) {
                            feature.renderIntent = 'default';
                            feature.layer.redraw();

                        }
                    })
                },
                selectFeature:         {
                    infoText: "Select geometry",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        widget.toggleController(el.data('control'));
                        mapElement.css({cursor: 'default'});

                    },
                    control:  new OpenLayers.Control.SelectFeature(layer, {
                        clickout:    true,
                        toggle:      true,
                        multiple:    true,
                        hover:       false,
                        box:         true,
                        toggleKey:   "ctrlKey", // ctrl key removes from selection
                        multipleKey: "shiftKey" // shift key adds to selection
                    })
                },
                removeSelected: {
                    infoText: "Remove selected geometries",
                    cssClass: 'critical',
                    onClick: function() {
                        layer.removeFeatures(layer.selectedFeatures);
                    }
                },
                removeAll:      {
                    infoText: "Remove all geometries",
                    cssClass: 'critical',
                    onClick: function() {
                        layer.removeAllFeatures();
                    }
                }
            };
            widget.element.addClass('digitizing-tool-set');
            widget.refresh();
        },

        /**
         * Refresh widget
         */
        refresh: function() {
            var widget = this;
            var element = $(widget.element);
            var children = widget.options.children;
            var layer = widget.getLayer();
            var map = layer.map;

            // clean controllers
            //widget.cleanUp();

            // clean navigation
            element.empty();

            widget.buildNavigation(children);

            // Init map controllers
            for (var k in widget._activeControls) {
                map.addControl(widget._activeControls[k]);
            }

            widget._trigger('ready', null, this);
        },

        _setOptions: function(options) {
            this._super(options);
            this.refresh();
        },

        /**
         * Toggle controller and return true if controller turned on
         *
         * @param controller
         * @returns {boolean}
         */
        toggleController: function(controller) {
            var widget = this;
            var setOn = widget.currentController != controller;
            if(setOn) {
                widget.setController(controller);
            } else {
                widget.deactivateCurrentController();
            }
            return setOn;
        },

        /**
         * Switch between current and element controller.
         *
         * @param controller
         */
        setController: function(controller) {
            var widget = this;

            if(controller) {
                controller.activate();
            }

            if(widget.currentController) {
                widget.deactivateCurrentController();
            }

            widget.currentController = controller;
        },

        /**
         * Build Navigation
         *
         * @param buttons
         */
        buildNavigation: function(buttons) {
            var widget = this;
            var element = $(widget.element);
            var controls = widget.controls;
            var controlEvents = widget.options.controlEvents;

            $.each(buttons, function(i, item) {
                //var item = this;
                if(!item || !item.hasOwnProperty('type')){
                    return;
                }
                var button = $("<button class='button' type='button'/>");
                var type = item.type;

                button.addClass(item.type);
                button.data(item);

                if(controls.hasOwnProperty(type)) {
                    var controlDefinition = controls[type];

                    if(controlDefinition.hasOwnProperty('infoText')){
                        button.attr('title',controlDefinition.infoText)
                    }

                    // add icon css class
                    button.addClass("icon-" + type.replace(/([A-Z])+/g,'-$1').toLowerCase());

                    if(controlDefinition.hasOwnProperty('cssClass')){
                        button.addClass(controlDefinition.cssClass)
                    }

                    button.on('click', controlDefinition.onClick);

                    if(controlDefinition.hasOwnProperty('control')) {
                        button.data('control', controlDefinition.control);
                        widget._activeControls.push(controlDefinition.control);

                        var drawControlEvents = controlDefinition.control.events;
                        drawControlEvents.register('activate', button, function(e) {
                            widget._trigger('controlActivate', null, e);
                            button.addClass('active');
                        });
                        drawControlEvents.register('deactivate', button, function(e) {
                            widget._trigger('controlDeactivate', null, e);
                            button.removeClass('active');
                        });

                        // Map event handler to ol controls
                        $.each(controlEvents,function(eventName,eventHandler){
                            drawControlEvents.register(eventName, null, eventHandler);
                        });
                    }
                }

                element.append(button);
            });
        },

        /**
         * Get OpenLayer Layer
         *
         * @return OpenLayers.Map.OpenLayers.Class.initialize
         */
        getLayer: function() {
            return this.options.layer;
        },

        /**
         * Get map jQuery HTML element
         *
         * @return HTMLElement jquery HTML element
         */
        getMapElement: function() {
            var layer = this.getLayer();
            return layer?$(layer.map.div):null;
        },

        /**
         * Has layer?
         * @return {boolean}
         */
        hasLayer: function(){
            return !!this.getLayer();
        },

        /**
         * Deactivate current OpenLayer controller
         */
        deactivateCurrentController: function(){
            var widget = this;
            var mapElement = widget.getMapElement();
            var previousController = widget.currentController;

            if(previousController) {
                if(previousController instanceof OpenLayers.Control.SelectFeature) {
                    previousController.unselectAll();
                }

                previousController.deactivate();
                widget.currentController = null;
            }

            mapElement.css({cursor: 'default'});
        }
    });

})(jQuery);
<commit_msg>Add registration of non trigger-Events like onStart<commit_after>/**
 * Digitizing tool set
 *
 * @author Andriy Oblivantsev <eslider@gmail.com>
 * @author Stefan Winkelmann <stefan.winkelmann@wheregroup.com>
 *
 * @copyright 20.04.2015 by WhereGroup GmbH & Co. KG
 */
(function($) {

    $.widget("vis-ui-js.digitizingToolSet", {

        options:           {
            layer:    null,
            // Open layer control events
            controlEvents: []
        },
        controls:          null,
        _activeControls:   [],
        currentController: null,

        /**
         * Init controls
         *
         * @private
         */
        _create: function() {
            var widget = this;
            var mapElement = widget.getMapElement();
            var layer = widget.getLayer();

            widget.controls = {
                drawPoint:      {
                    infoText: "Draw point",
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Point),
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        }
                    }
                },
                drawLine:       {
                    infoText: "Draw line",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        }

                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Path)
                },
                drawPolygon:    {
                    infoText: "Draw polygone",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }

                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Polygon)
                },
                drawRectangle:  {
                    infoText: "Draw rectangle",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }

                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.RegularPolygon, {
                        handlerOptions: {
                            sides:     4,
                            irregular: true
                        }
                    })
                },
                drawCircle:     {
                    infoText: "Draw circle",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }

                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.RegularPolygon, {
                        handlerOptions: {
                            sides: 40
                        }
                    })
                },
                drawEllipse:    {
                    infoText: "Draw ellipse",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }

                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.RegularPolygon, {
                        handlerOptions: {
                            sides:     40,
                            irregular: true
                        }
                    })
                },
                drawDonut:          {
                    infoText: "Draw donut",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }
                    },
                    control:  new OpenLayers.Control.DrawFeature(layer, OpenLayers.Handler.Polygon, {
                        handlerOptions: {
                            holeModifier: 'element'
                        }
                    })
                },
                modifyFeature:           {
                    infoText: "Select and edit geometry position/size",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'crosshair'});
                        } else {
                            mapElement.css({cursor: 'default'});
                        }

                    },
                    control:  new OpenLayers.Control.ModifyFeature(layer)
                },
                moveFeature:           {
                    infoText: "Move geometry",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        if(widget.toggleController(el.data('control'))) {
                            mapElement.css({cursor: 'default'});
                        }
                        mapElement.css({cursor: 'default'});
                    },
                    control:  new OpenLayers.Control.DragFeature(layer, {
                        onStart:    function(feature) {
                            feature.renderIntent = 'select';
                        },
                        onComplete: function(feature) {
                            feature.renderIntent = 'default';
                            feature.layer.redraw();

                        }
                    })
                },
                selectFeature:         {
                    infoText: "Select geometry",
                    onClick: function(e) {
                        var el = $(e.currentTarget);
                        widget.toggleController(el.data('control'));
                        mapElement.css({cursor: 'default'});

                    },
                    control:  new OpenLayers.Control.SelectFeature(layer, {
                        clickout:    true,
                        toggle:      true,
                        multiple:    true,
                        hover:       false,
                        box:         true,
                        toggleKey:   "ctrlKey", // ctrl key removes from selection
                        multipleKey: "shiftKey" // shift key adds to selection
                    })
                },
                removeSelected: {
                    infoText: "Remove selected geometries",
                    cssClass: 'critical',
                    onClick: function() {
                        layer.removeFeatures(layer.selectedFeatures);
                    }
                },
                removeAll:      {
                    infoText: "Remove all geometries",
                    cssClass: 'critical',
                    onClick: function() {
                        layer.removeAllFeatures();
                    }
                }
            };
            widget.element.addClass('digitizing-tool-set');
            widget.refresh();
        },

        /**
         * Refresh widget
         */
        refresh: function() {
            var widget = this;
            var element = $(widget.element);
            var children = widget.options.children;
            var layer = widget.getLayer();
            var map = layer.map;

            // clean controllers
            //widget.cleanUp();

            // clean navigation
            element.empty();

            widget.buildNavigation(children);

            // Init map controllers
            for (var k in widget._activeControls) {
                map.addControl(widget._activeControls[k]);
            }

            widget._trigger('ready', null, this);
        },

        _setOptions: function(options) {
            this._super(options);
            this.refresh();
        },

        /**
         * Toggle controller and return true if controller turned on
         *
         * @param controller
         * @returns {boolean}
         */
        toggleController: function(controller) {
            var widget = this;
            var setOn = widget.currentController != controller;
            if(setOn) {
                widget.setController(controller);
            } else {
                widget.deactivateCurrentController();
            }
            return setOn;
        },

        /**
         * Switch between current and element controller.
         *
         * @param controller
         */
        setController: function(controller) {
            var widget = this;

            if(controller) {
                controller.activate();
            }

            if(widget.currentController) {
                widget.deactivateCurrentController();
            }

            widget.currentController = controller;
        },

        /**
         * Build Navigation
         *
         * @param buttons
         */
        buildNavigation: function(buttons) {
            var widget = this;
            var element = $(widget.element);
            var controls = widget.controls;
            var controlEvents = widget.options.controlEvents;

            $.each(buttons, function(i, item) {
                //var item = this;
                if(!item || !item.hasOwnProperty('type')){
                    return;
                }
                var button = $("<button class='button' type='button'/>");
                var type = item.type;

                button.addClass(item.type);
                button.data(item);

                if(controls.hasOwnProperty(type)) {
                    var controlDefinition = controls[type];

                    if(controlDefinition.hasOwnProperty('infoText')){
                        button.attr('title',controlDefinition.infoText)
                    }

                    // add icon css class
                    button.addClass("icon-" + type.replace(/([A-Z])+/g,'-$1').toLowerCase());

                    if(controlDefinition.hasOwnProperty('cssClass')){
                        button.addClass(controlDefinition.cssClass)
                    }

                    button.on('click', controlDefinition.onClick);

                    if(controlDefinition.hasOwnProperty('control')) {
                        button.data('control', controlDefinition.control);
                        widget._activeControls.push(controlDefinition.control);

                        var drawControlEvents = controlDefinition.control.events;
                        drawControlEvents.register('activate', button, function(e) {
                            widget._trigger('controlActivate', null, e);
                            button.addClass('active');
                        });
                        drawControlEvents.register('deactivate', button, function(e) {
                            widget._trigger('controlDeactivate', null, e);
                            button.removeClass('active');
                        });

                        // Map event handler to ol controls
                        $.each(controlEvents,function(eventName,eventHandler){
                            controlDefinition.control[eventName] = eventHandler;

                            drawControlEvents.register(eventName, null, eventHandler);
                        });
                    }
                }

                element.append(button);
            });
        },

        /**
         * Get OpenLayer Layer
         *
         * @return OpenLayers.Map.OpenLayers.Class.initialize
         */
        getLayer: function() {
            return this.options.layer;
        },

        /**
         * Get map jQuery HTML element
         *
         * @return HTMLElement jquery HTML element
         */
        getMapElement: function() {
            var layer = this.getLayer();
            return layer?$(layer.map.div):null;
        },

        /**
         * Has layer?
         * @return {boolean}
         */
        hasLayer: function(){
            return !!this.getLayer();
        },

        /**
         * Deactivate current OpenLayer controller
         */
        deactivateCurrentController: function(){
            var widget = this;
            var mapElement = widget.getMapElement();
            var previousController = widget.currentController;

            if(previousController) {
                if(previousController instanceof OpenLayers.Control.SelectFeature) {
                    previousController.unselectAll();
                }

                previousController.deactivate();
                widget.currentController = null;
            }

            mapElement.css({cursor: 'default'});
        }
    });

})(jQuery);
<|endoftext|>


<commit_before>/*======================================================
************   Searchbar   ************
======================================================*/
var Searchbar = function (container, params) {
    var defaults = {
        input: null,
        clearButton: null,
        cancelButton: null,
        searchList: null,
        searchIn: '.item-title',
        searchBy: '',
        found: null,
        notFound: null,
        overlay: null,
        ignore: '.searchbar-ignore',
        customSearch: false,
        removeDiacritics: false,
        hideDividers: true,
        hideGroups: true,
        /* Callbacks
        onSearch
        onEnable
        onDisable
        onClear
        */

    };
    params = params || {};
    for (var def in defaults) {
        if (typeof params[def] === 'undefined' || params[def] === null && defaults.hasOwnProperty(def)) {
            params[def] = defaults[def];
        }
    }

    // Instance
    var s = this;

    // Material
    s.material = app.params.material;

    // Params
    s.params = params;

    // Container
    container = $(container);
    s.container = container;

    // Active
    s.active = false;

    // Input
    s.input = s.params.input ? $(s.params.input) : s.container.find('input[type="search"]');
    s.clearButton = s.params.clearButton ? $(s.params.clearButton) : s.container.find('.searchbar-clear');
    s.cancelButton = s.params.cancelButton ? $(s.params.cancelButton) : s.container.find('.searchbar-cancel');

    // Search List
    s.searchList = $(s.params.searchList);

    // Is Virtual List
    s.isVirtualList = s.searchList.hasClass('virtual-list');

    // Is In Page
    s.pageContainer = s.container.parents('.page').eq(0);

    // Overlay
    if (!s.params.overlay) {
        s.overlay = s.pageContainer.length > 0 ? s.pageContainer.find('.searchbar-overlay') : $('.searchbar-overlay');
    }
    else {
        s.overlay = $(s.params.overlay);
    }
    // Found and not found
    if (!s.params.found) {
        s.found = s.pageContainer.length > 0 ? s.pageContainer.find('.searchbar-found') : $('.searchbar-found');
    }
    else {
        s.found = $(s.params.found);
    }
    if (!s.params.notFound) {
        s.notFound = s.pageContainer.length > 0 ? s.pageContainer.find('.searchbar-not-found') : $('.searchbar-not-found');
    }
    else {
        s.notFound = $(s.params.notFound);
    }

    // Set Cancel button
    var cancelMarginProp = app.rtl ? 'margin-left' : 'margin-right';
    var cancelButtonHasMargin = false;
    s.setCancelButtonMargin = function () {
        s.cancelButton.transition(0).show();
        s.cancelButton.css(cancelMarginProp, -s.cancelButton[0].offsetWidth + 'px');
        var clientLeft = s.cancelButton[0].clientLeft;
        s.cancelButton.transition('');
        cancelButtonHasMargin = true;
    };

    // Trigger
    s.triggerEvent = function (eventName, callbackName, eventData) {
        s.container.trigger(eventName, eventData);
        if (s.searchList.length > 0) s.searchList.trigger(eventName, eventData);
        if (callbackName && s.params[callbackName]) s.params[callbackName](s, eventData);
    };

    // Enable/disalbe
    s.enable = function (e) {
        function _enable() {
            if ((s.searchList.length || s.params.customSearch) && !s.container.hasClass('searchbar-active') && !s.query) s.overlay.addClass('searchbar-overlay-active');
            s.container.addClass('searchbar-active');
            if (s.cancelButton.length > 0 && !s.material) {
                if (!cancelButtonHasMargin) {
                    s.setCancelButtonMargin();
                }
                s.cancelButton.css(cancelMarginProp, '0px');
            }
            s.triggerEvent('enableSearch searchbar:enable', 'onEnable');
            s.active = true;
        }
        if (app.device.ios && !app.params.material && e && e.type === 'focus') {
            setTimeout(function () {
                _enable();
            }, 400);
        }
        else {
            _enable();
        }
    };

    s.disable = function () {
        s.input.val('').trigger('change');
        s.container.removeClass('searchbar-active searchbar-not-empty');
        if (s.cancelButton.length > 0 && !s.material) s.cancelButton.css(cancelMarginProp, -s.cancelButton[0].offsetWidth + 'px');

        if (s.searchList.length || s.params.customSearch) s.overlay.removeClass('searchbar-overlay-active');

        s.active = false;
        function _disable() {
            s.input.blur();
        }
        if (app.device.ios) {
            setTimeout(function () {
                _disable();
            }, 400);
        }
        else {
            _disable();
        }
        s.triggerEvent('disableSearch searchbar:disable', 'onDisable');
    };

    // Clear
    s.clear = function (e) {
        if (!s.query && e && $(e.target).hasClass('searchbar-clear')) {
            s.disable();
            return;
        }
        var previousQuery = s.value;
        s.input.val('').trigger('change').focus();
        s.triggerEvent('clearSearch searchbar:clear', 'onClear', {previousQuery: previousQuery});
    };

    // Search
    s.handleInput = function () {
        setTimeout(function () {
            var value = s.input.val().trim();
            if ((s.searchList.length > 0 || s.params.customSearch) && (s.params.searchIn || s.isVirtualList)) s.search(value, true);
        }, 0);
    };

    var previousQuery = '';
    var virtualList;
    s.search = function (query, internal) {
        if (previousQuery && query.trim() === previousQuery) return;
        previousQuery = query.trim();

        if (!internal) {
            if (!s.active) {
                s.enable();
            }
            s.input.val(query);
        }
        s.query = s.value = query;
        // Add active/inactive classes on overlay
        if (query.length === 0) {
            s.container.removeClass('searchbar-not-empty');
            if (s.searchList.length && s.container.hasClass('searchbar-active')) s.overlay.addClass('searchbar-overlay-active');
        }
        else {
            s.container.addClass('searchbar-not-empty');
            if (s.searchList.length && s.container.hasClass('searchbar-active')) s.overlay.removeClass('searchbar-overlay-active');
        }

        if (s.params.customSearch) {
            s.triggerEvent('search searchbar:search', 'onSearch', {query: query});
            return;
        }

        var foundItems = [], _vlQuery;
        if (s.isVirtualList) {
            virtualList = s.searchList[0].f7VirtualList;
            if (query.trim() === '') {
                virtualList.resetFilter();
                s.notFound.hide();
                s.found.show();
                return;
            }
            _vlQuery = s.params.removeDiacritics ? $.removeDiacritics(query) : query;
            if (virtualList.params.searchAll) {
                foundItems = virtualList.params.searchAll(_vlQuery, virtualList.items) || [];
            }
            else if (virtualList.params.searchByItem) {
                for (var i = 0; i < virtualList.items.length; i++) {
                    if(virtualList.params.searchByItem(_vlQuery, i, virtualList.params.items[i])) {
                        foundItems.push(i);
                    }
                }
            }
        }
        else {
            var values;
            if (s.params.removeDiacritics) values = $.removeDiacritics(query.trim().toLowerCase()).split(' ');
            else {
                values = query.trim().toLowerCase().split(' ');
            }
            s.searchList.find('li').removeClass('hidden-by-searchbar').each(function (index, el) {
                el = $(el);
                var compareWithText = [];
                el.find(s.params.searchIn).each(function () {
                    var itemText = $(this).text().trim().toLowerCase();
                    if (s.params.removeDiacritics) itemText = $.removeDiacritics(itemText);
                    compareWithText.push(itemText);
                });
                compareWithText = compareWithText.join(' ');
                var wordsMatch = 0;
                for (var i = 0; i < values.length; i++) {
                    if (compareWithText.indexOf(values[i]) >= 0) wordsMatch++;
                }
                if (wordsMatch !== values.length && !(s.params.ignore && el.is(s.params.ignore))) {
                    el.addClass('hidden-by-searchbar');
                }
                else {
                    foundItems.push(el[0]);
                }
            });

            if (s.params.hideDividers) {
                s.searchList.find('.item-divider, .list-group-title').each(function () {
                    var title = $(this);
                    var nextElements = title.nextAll('li');
                    var hide = true;
                    for (var i = 0; i < nextElements.length; i++) {
                        var nextEl = $(nextElements[i]);
                        if (nextEl.hasClass('list-group-title') || nextEl.hasClass('item-divider')) break;
                        if (!nextEl.hasClass('hidden-by-searchbar')) {
                            hide = false;
                        }
                    }
                    var ignore = s.params.ignore && title.is(s.params.ignore);
                    if (hide && !ignore) title.addClass('hidden-by-searchbar');
                    else title.removeClass('hidden-by-searchbar');
                });
            }
            if (s.params.hideGroups) {
                s.searchList.find('.list-group').each(function () {
                    var group = $(this);
                    var ignore = s.params.ignore && group.is(s.params.ignore);
                    var notHidden = group.find('li:not(.hidden-by-searchbar)');
                    if (notHidden.length === 0 && !ignore) {
                        group.addClass('hidden-by-searchbar');
                    }
                    else {
                        group.removeClass('hidden-by-searchbar');
                    }
                });
            }
        }
        s.triggerEvent('search searchbar:search', 'onSearch', {query: query, foundItems: foundItems});
        if (foundItems.length === 0) {
            s.notFound.show();
            s.found.hide();
        }
        else {
            s.notFound.hide();
            s.found.show();
        }
        if (s.isVirtualList) {
            virtualList.filterItems(foundItems);
        }
    };

    // Events
    function preventSubmit(e) {
        e.preventDefault();
    }

    s.attachEvents = function (destroy) {
        var method = destroy ? 'off' : 'on';
        s.container[method]('submit', preventSubmit);
        if (!s.material) s.cancelButton[method]('click', s.disable);
        s.overlay[method]('click', s.disable);
        s.input[method]('focus', s.enable);
        s.input[method]('change keydown keypress keyup compositionend', s.handleInput);
        s.clearButton[method]('click', s.clear);

    };
    s.detachEvents = function() {
        s.attachEvents(true);
    };

    // Init Destroy
    s.init = function () {
        s.attachEvents();
    };
    s.destroy = function () {
        if (!s) return;
        s.detachEvents();
        s = null;
    };

    // Init
    s.init();

    s.container[0].f7Searchbar = s;
    return s;

};
app.searchbar = function (container, params) {
    return new Searchbar(container, params);
};
app.initSearchbar = function (container) {
    container = $(container);
    var searchbar = container.hasClass('searchbar') ? container : container.find('.searchbar');
    if (searchbar.length === 0) return;
    if (!searchbar.hasClass('searchbar-init')) return;

    var sb = app.searchbar(searchbar, searchbar.dataset());

    function onBeforeRemove() {
        if (sb) sb.destroy();
    }
    if (container.hasClass('page')) {
        container.once('pageBeforeRemove', onBeforeRemove);
    }
    else if (container.hasClass('navbar-inner')) {
        container.once('navbarBeforeRemove', onBeforeRemove);
    }
};
<commit_msg>Remove accents by default<commit_after>/*======================================================
************   Searchbar   ************
======================================================*/
var Searchbar = function (container, params) {
    var defaults = {
        input: null,
        clearButton: null,
        cancelButton: null,
        searchList: null,
        searchIn: '.item-title',
        searchBy: '',
        found: null,
        notFound: null,
        overlay: null,
        ignore: '.searchbar-ignore',
        customSearch: false,
        removeDiacritics: true,
        hideDividers: true,
        hideGroups: true,
        /* Callbacks
        onSearch
        onEnable
        onDisable
        onClear
        */

    };
    params = params || {};
    for (var def in defaults) {
        if (typeof params[def] === 'undefined' || params[def] === null && defaults.hasOwnProperty(def)) {
            params[def] = defaults[def];
        }
    }

    // Instance
    var s = this;

    // Material
    s.material = app.params.material;

    // Params
    s.params = params;

    // Container
    container = $(container);
    s.container = container;

    // Active
    s.active = false;

    // Input
    s.input = s.params.input ? $(s.params.input) : s.container.find('input[type="search"]');
    s.clearButton = s.params.clearButton ? $(s.params.clearButton) : s.container.find('.searchbar-clear');
    s.cancelButton = s.params.cancelButton ? $(s.params.cancelButton) : s.container.find('.searchbar-cancel');

    // Search List
    s.searchList = $(s.params.searchList);

    // Is Virtual List
    s.isVirtualList = s.searchList.hasClass('virtual-list');

    // Is In Page
    s.pageContainer = s.container.parents('.page').eq(0);

    // Overlay
    if (!s.params.overlay) {
        s.overlay = s.pageContainer.length > 0 ? s.pageContainer.find('.searchbar-overlay') : $('.searchbar-overlay');
    }
    else {
        s.overlay = $(s.params.overlay);
    }
    // Found and not found
    if (!s.params.found) {
        s.found = s.pageContainer.length > 0 ? s.pageContainer.find('.searchbar-found') : $('.searchbar-found');
    }
    else {
        s.found = $(s.params.found);
    }
    if (!s.params.notFound) {
        s.notFound = s.pageContainer.length > 0 ? s.pageContainer.find('.searchbar-not-found') : $('.searchbar-not-found');
    }
    else {
        s.notFound = $(s.params.notFound);
    }

    // Set Cancel button
    var cancelMarginProp = app.rtl ? 'margin-left' : 'margin-right';
    var cancelButtonHasMargin = false;
    s.setCancelButtonMargin = function () {
        s.cancelButton.transition(0).show();
        s.cancelButton.css(cancelMarginProp, -s.cancelButton[0].offsetWidth + 'px');
        var clientLeft = s.cancelButton[0].clientLeft;
        s.cancelButton.transition('');
        cancelButtonHasMargin = true;
    };

    // Trigger
    s.triggerEvent = function (eventName, callbackName, eventData) {
        s.container.trigger(eventName, eventData);
        if (s.searchList.length > 0) s.searchList.trigger(eventName, eventData);
        if (callbackName && s.params[callbackName]) s.params[callbackName](s, eventData);
    };

    // Enable/disalbe
    s.enable = function (e) {
        function _enable() {
            if ((s.searchList.length || s.params.customSearch) && !s.container.hasClass('searchbar-active') && !s.query) s.overlay.addClass('searchbar-overlay-active');
            s.container.addClass('searchbar-active');
            if (s.cancelButton.length > 0 && !s.material) {
                if (!cancelButtonHasMargin) {
                    s.setCancelButtonMargin();
                }
                s.cancelButton.css(cancelMarginProp, '0px');
            }
            s.triggerEvent('enableSearch searchbar:enable', 'onEnable');
            s.active = true;
        }
        if (app.device.ios && !app.params.material && e && e.type === 'focus') {
            setTimeout(function () {
                _enable();
            }, 400);
        }
        else {
            _enable();
        }
    };

    s.disable = function () {
        s.input.val('').trigger('change');
        s.container.removeClass('searchbar-active searchbar-not-empty');
        if (s.cancelButton.length > 0 && !s.material) s.cancelButton.css(cancelMarginProp, -s.cancelButton[0].offsetWidth + 'px');

        if (s.searchList.length || s.params.customSearch) s.overlay.removeClass('searchbar-overlay-active');

        s.active = false;
        function _disable() {
            s.input.blur();
        }
        if (app.device.ios) {
            setTimeout(function () {
                _disable();
            }, 400);
        }
        else {
            _disable();
        }
        s.triggerEvent('disableSearch searchbar:disable', 'onDisable');
    };

    // Clear
    s.clear = function (e) {
        if (!s.query && e && $(e.target).hasClass('searchbar-clear')) {
            s.disable();
            return;
        }
        var previousQuery = s.value;
        s.input.val('').trigger('change').focus();
        s.triggerEvent('clearSearch searchbar:clear', 'onClear', {previousQuery: previousQuery});
    };

    // Search
    s.handleInput = function () {
        setTimeout(function () {
            var value = s.input.val().trim();
            if ((s.searchList.length > 0 || s.params.customSearch) && (s.params.searchIn || s.isVirtualList)) s.search(value, true);
        }, 0);
    };

    var previousQuery = '';
    var virtualList;
    s.search = function (query, internal) {
        if (previousQuery && query.trim() === previousQuery) return;
        previousQuery = query.trim();

        if (!internal) {
            if (!s.active) {
                s.enable();
            }
            s.input.val(query);
        }
        s.query = s.value = query;
        // Add active/inactive classes on overlay
        if (query.length === 0) {
            s.container.removeClass('searchbar-not-empty');
            if (s.searchList.length && s.container.hasClass('searchbar-active')) s.overlay.addClass('searchbar-overlay-active');
        }
        else {
            s.container.addClass('searchbar-not-empty');
            if (s.searchList.length && s.container.hasClass('searchbar-active')) s.overlay.removeClass('searchbar-overlay-active');
        }

        if (s.params.customSearch) {
            s.triggerEvent('search searchbar:search', 'onSearch', {query: query});
            return;
        }

        var foundItems = [], _vlQuery;
        if (s.isVirtualList) {
            virtualList = s.searchList[0].f7VirtualList;
            if (query.trim() === '') {
                virtualList.resetFilter();
                s.notFound.hide();
                s.found.show();
                return;
            }
            _vlQuery = s.params.removeDiacritics ? $.removeDiacritics(query) : query;
            if (virtualList.params.searchAll) {
                foundItems = virtualList.params.searchAll(_vlQuery, virtualList.items) || [];
            }
            else if (virtualList.params.searchByItem) {
                for (var i = 0; i < virtualList.items.length; i++) {
                    if(virtualList.params.searchByItem(_vlQuery, i, virtualList.params.items[i])) {
                        foundItems.push(i);
                    }
                }
            }
        }
        else {
            var values;
            if (s.params.removeDiacritics) values = $.removeDiacritics(query.trim().toLowerCase()).split(' ');
            else {
                values = query.trim().toLowerCase().split(' ');
            }
            s.searchList.find('li').removeClass('hidden-by-searchbar').each(function (index, el) {
                el = $(el);
                var compareWithText = [];
                el.find(s.params.searchIn).each(function () {
                    var itemText = $(this).text().trim().toLowerCase();
                    if (s.params.removeDiacritics) itemText = $.removeDiacritics(itemText);
                    compareWithText.push(itemText);
                });
                compareWithText = compareWithText.join(' ');
                var wordsMatch = 0;
                for (var i = 0; i < values.length; i++) {
                    if (compareWithText.indexOf(values[i]) >= 0) wordsMatch++;
                }
                if (wordsMatch !== values.length && !(s.params.ignore && el.is(s.params.ignore))) {
                    el.addClass('hidden-by-searchbar');
                }
                else {
                    foundItems.push(el[0]);
                }
            });

            if (s.params.hideDividers) {
                s.searchList.find('.item-divider, .list-group-title').each(function () {
                    var title = $(this);
                    var nextElements = title.nextAll('li');
                    var hide = true;
                    for (var i = 0; i < nextElements.length; i++) {
                        var nextEl = $(nextElements[i]);
                        if (nextEl.hasClass('list-group-title') || nextEl.hasClass('item-divider')) break;
                        if (!nextEl.hasClass('hidden-by-searchbar')) {
                            hide = false;
                        }
                    }
                    var ignore = s.params.ignore && title.is(s.params.ignore);
                    if (hide && !ignore) title.addClass('hidden-by-searchbar');
                    else title.removeClass('hidden-by-searchbar');
                });
            }
            if (s.params.hideGroups) {
                s.searchList.find('.list-group').each(function () {
                    var group = $(this);
                    var ignore = s.params.ignore && group.is(s.params.ignore);
                    var notHidden = group.find('li:not(.hidden-by-searchbar)');
                    if (notHidden.length === 0 && !ignore) {
                        group.addClass('hidden-by-searchbar');
                    }
                    else {
                        group.removeClass('hidden-by-searchbar');
                    }
                });
            }
        }
        s.triggerEvent('search searchbar:search', 'onSearch', {query: query, foundItems: foundItems});
        if (foundItems.length === 0) {
            s.notFound.show();
            s.found.hide();
        }
        else {
            s.notFound.hide();
            s.found.show();
        }
        if (s.isVirtualList) {
            virtualList.filterItems(foundItems);
        }
    };

    // Events
    function preventSubmit(e) {
        e.preventDefault();
    }

    s.attachEvents = function (destroy) {
        var method = destroy ? 'off' : 'on';
        s.container[method]('submit', preventSubmit);
        if (!s.material) s.cancelButton[method]('click', s.disable);
        s.overlay[method]('click', s.disable);
        s.input[method]('focus', s.enable);
        s.input[method]('change keydown keypress keyup compositionend', s.handleInput);
        s.clearButton[method]('click', s.clear);

    };
    s.detachEvents = function() {
        s.attachEvents(true);
    };

    // Init Destroy
    s.init = function () {
        s.attachEvents();
    };
    s.destroy = function () {
        if (!s) return;
        s.detachEvents();
        s = null;
    };

    // Init
    s.init();

    s.container[0].f7Searchbar = s;
    return s;

};
app.searchbar = function (container, params) {
    return new Searchbar(container, params);
};
app.initSearchbar = function (container) {
    container = $(container);
    var searchbar = container.hasClass('searchbar') ? container : container.find('.searchbar');
    if (searchbar.length === 0) return;
    if (!searchbar.hasClass('searchbar-init')) return;

    var sb = app.searchbar(searchbar, searchbar.dataset());

    function onBeforeRemove() {
        if (sb) sb.destroy();
    }
    if (container.hasClass('page')) {
        container.once('pageBeforeRemove', onBeforeRemove);
    }
    else if (container.hasClass('navbar-inner')) {
        container.once('navbarBeforeRemove', onBeforeRemove);
    }
};
<|endoftext|>


<commit_before>import Request from './sessionSuperagent.js';
import Q from 'q';
import AWS from 'aws-sdk';
import { dispatch } from 'redux';
import _ from 'lodash';

import StoreSingleton from '../redux/storeSingleton.js';

import { kGlobalConstants } from '../GlobalConstants.js';
import * as uploadActions from '../redux/actions/uploadActions.js';

import { fileTypes } from '../containers/addData/fileTypes.js';
import * as AdminHelper from './adminHelper.js';

const availablePairs = ['appropriations-program_activity', 'award_financial-award'];
const globalFileKeys = ['appropriations', 'program_activity', 'award_financial', 'award'];
export const globalFileData = {
	appropriations: {
		name: 'Appropriations Account',
		letter: 'A'
	},
	program_activity: {
		name: 'Program Activity and Object Class Data',
		letter: 'B'
	},
	award_financial: {
		name: 'Award Financial',
		letter: 'C'
	},
	award: {
		name: 'Financial Assistance Award',
		letter: 'D2'
	}
};

const determineExpectedPairs = () => {
	const output = [];

	availablePairs.forEach((keyName) => {

		const firstKey = keyName.split('-')[0];
		const secondKey = keyName.split('-')[1];

		const item = {
			key: keyName,
			firstType: globalFileData[firstKey].letter,
			firstName: globalFileData[firstKey].name,
			firstKey: firstKey,
			secondType: globalFileData[secondKey].letter,
			secondName: globalFileData[secondKey].name,
			secondKey: secondKey
		};

		output.push(item);

	});

	return output;
}

export const fetchStatus = (submissionId) => {
	const deferred = Q.defer();

	Request.post(kGlobalConstants.API + 'check_status/')
	        .send({'submission_id': submissionId})
	        .end((errFile, res) => {

	        	if (errFile) {
	        		let detail = '';
	        		if (res.body != null && res.body.hasOwnProperty('message')) {
	        			detail = res.body.message;
	        		}

	        		deferred.reject({
	        			reason: res.statusCode,
	        			error: errFile,
	        			detail: detail
	        		});
	        	}
	        	else {
	        		// return only jobs related to CSV validation
	        		const response = Object.assign({}, res.body);
	        		const csvJobs = [];
	        		let crossFileJob;
	        		response.jobs.forEach((job) => {
	        			if (job.job_type == 'csv_record_validation') {
	        				csvJobs.push(job);
	        			}
	        			else if (job.job_type == 'validation') {
	        				crossFileJob = job;
	        			}
	        		});

	        		response.jobs = csvJobs;
	        		response.crossFile = crossFileJob;

	        		deferred.resolve(response);
	        	}

	        });

	return deferred.promise;
}

export const fetchErrorReports = (submissionId) => {
	const deferred = Q.defer();

	Request.post(kGlobalConstants.API + 'submission_error_reports/')
			.send({'submission_id': submissionId})
			.end((errFile, res) => {

				if (errFile) {
					deferred.reject(errFile);
				}
				else {
					deferred.resolve(res.body);
				}

			});

	return deferred.promise;
}

const getFileStates = (status) => {
	const output = {};

	status.jobs.forEach((item) => {
		output[item.file_type] = item;
		output[item.file_type].report = null;
		output[item.file_type].error_count = 0;

		// force an error_data array if no field is passed back in the JSON
		if (!item.hasOwnProperty('error_data')) {
			output[item.file_type].error_data = [];
		}
		else {
			let count = 0;
			item.error_data.forEach((error) => {
				count += parseInt(error.occurrences);
			});

			output[item.file_type].error_count = count;
		}

	});

	return output;
}

const getCrossFileData = (data, validKeys) => {
	const output = {};

	// generate the file pair keys
	let i = 1;

	for (let index in data.crossFile.error_data) {
		// fetch the error object
		const item = data.crossFile.error_data[index];

		// generate possible key names for this pair of target/source files
		const keyNames = [item.target_file + '-' + item.source_file, item.source_file + '-' + item.target_file];
		// determine which is the correct name
		let key = keyNames[0];
		if (_.indexOf(validKeys, key) == -1) {
			key = keyNames[1];
		}

		// check if the key is a valid cross-file pairing we care about
		if (_.indexOf(validKeys, key) == -1) {
			// not a valid pair
			continue;
		}

		// check if we've already seen an error for this pairing
		if (output.hasOwnProperty(key)) {
			// this pair already exists, so append the error to the pair's array
			output[key].push(item);
		}
		else {
			// doesn't exist yet, so create an array with this error
			output[key] = [item];
		}
	}

	return output;
}

const getFileReports = (status, reports) => {

	for (let key in status) {
		let item = status[key];
		item.report = reports['job_' + item.job_id + '_error_url'];

		// alphabetize any missing and duplicated headers
		item.missing_headers = _.sortBy(item.missing_headers);
		item.duplicated_headers = _.sortBy(item.duplicated_headers);
	}

	return status;
}

const getCrossFileReports = (crossFile, reports) => {

	const crossFileReports = {};

	for (let key in crossFile) {
		crossFileReports[key] = reports['cross_' + key];
	}

	return crossFileReports;
}

export const validateSubmission  = (submissionId) => {

	const deferred = Q.defer();

	// set the submission ID
	const store = new StoreSingleton().store;
	store.dispatch(uploadActions.setSubmissionId(submissionId));
	// determine the expected cross file validation keys and metadata
	let possiblePairs = determineExpectedPairs();
	store.dispatch(uploadActions.setExpectedCrossPairs(possiblePairs));

	const validKeys = [];
	possiblePairs.forEach((pair) => {
		validKeys.push(pair.key);
	});

	let status;
	let crossFile;
	let crossFileState;
	let crossFileReports;

	fetchStatus(submissionId)
		.then((statusRes) => {
			status = getFileStates(statusRes);
			crossFile = getCrossFileData(statusRes, validKeys);
			crossFileState = statusRes.crossFile.job_status;
			return fetchErrorReports(submissionId);
		})
		.then((reports) => {
			getFileReports(status, reports);
			crossFileReports = getCrossFileReports(crossFile, reports);
			deferred.resolve({
				file: status,
				crossFile: {
					state: crossFileState,
					reports: crossFileReports,
					data: crossFile
				}
			});
		})
		.catch((err) => {
			deferred.reject(err);
		});

	return deferred.promise;

}

export const listUsers = () => {
	const deferred = Q.defer();

	let request = {
		status: "approved"
	};

	Request.post(kGlobalConstants.API + 'list_users/')
		.send(request)
		.end((err, res) => {
			if (err) {
				deferred.reject(err);
			}
			else {
				// break up the permissions
				const users = [];
				res.body.users.forEach((user) => {
					// sometimes python adds extra spaces to the comma separated list, so strip those out
					const permString = user.permissions.replace(/\s/g, '');
					user.permissions = permString.split(',');

					const status = AdminHelper.determineStatus(user);

					user.statusString = status.string;
					user.statusType = status.type;

					users.push(user);
				});
				deferred.resolve(users);
			}
		});

	return deferred.promise;
}

export const sendNotification = (users, id) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'email_users/')
        .send({
        	'users': users,
        	'email_template': 'review_submission',
        	'submission_id': id
        })
        .end((errFile, res) => {
            if (errFile) {
                deferred.reject(errFile);
            }
            else {
                deferred.resolve(res.body);
            }
        });
    return deferred.promise;
}<commit_msg>Updated list_user_emails route<commit_after>import Request from './sessionSuperagent.js';
import Q from 'q';
import AWS from 'aws-sdk';
import { dispatch } from 'redux';
import _ from 'lodash';

import StoreSingleton from '../redux/storeSingleton.js';

import { kGlobalConstants } from '../GlobalConstants.js';
import * as uploadActions from '../redux/actions/uploadActions.js';

import { fileTypes } from '../containers/addData/fileTypes.js';
import * as AdminHelper from './adminHelper.js';

const availablePairs = ['appropriations-program_activity', 'award_financial-award'];
const globalFileKeys = ['appropriations', 'program_activity', 'award_financial', 'award'];
export const globalFileData = {
	appropriations: {
		name: 'Appropriations Account',
		letter: 'A'
	},
	program_activity: {
		name: 'Program Activity and Object Class Data',
		letter: 'B'
	},
	award_financial: {
		name: 'Award Financial',
		letter: 'C'
	},
	award: {
		name: 'Financial Assistance Award',
		letter: 'D2'
	}
};

const determineExpectedPairs = () => {
	const output = [];

	availablePairs.forEach((keyName) => {

		const firstKey = keyName.split('-')[0];
		const secondKey = keyName.split('-')[1];

		const item = {
			key: keyName,
			firstType: globalFileData[firstKey].letter,
			firstName: globalFileData[firstKey].name,
			firstKey: firstKey,
			secondType: globalFileData[secondKey].letter,
			secondName: globalFileData[secondKey].name,
			secondKey: secondKey
		};

		output.push(item);

	});

	return output;
}

export const fetchStatus = (submissionId) => {
	const deferred = Q.defer();

	Request.post(kGlobalConstants.API + 'check_status/')
	        .send({'submission_id': submissionId})
	        .end((errFile, res) => {

	        	if (errFile) {
	        		let detail = '';
	        		if (res.body != null && res.body.hasOwnProperty('message')) {
	        			detail = res.body.message;
	        		}

	        		deferred.reject({
	        			reason: res.statusCode,
	        			error: errFile,
	        			detail: detail
	        		});
	        	}
	        	else {
	        		// return only jobs related to CSV validation
	        		const response = Object.assign({}, res.body);
	        		const csvJobs = [];
	        		let crossFileJob;
	        		response.jobs.forEach((job) => {
	        			if (job.job_type == 'csv_record_validation') {
	        				csvJobs.push(job);
	        			}
	        			else if (job.job_type == 'validation') {
	        				crossFileJob = job;
	        			}
	        		});

	        		response.jobs = csvJobs;
	        		response.crossFile = crossFileJob;

	        		deferred.resolve(response);
	        	}

	        });

	return deferred.promise;
}

export const fetchErrorReports = (submissionId) => {
	const deferred = Q.defer();

	Request.post(kGlobalConstants.API + 'submission_error_reports/')
			.send({'submission_id': submissionId})
			.end((errFile, res) => {

				if (errFile) {
					deferred.reject(errFile);
				}
				else {
					deferred.resolve(res.body);
				}

			});

	return deferred.promise;
}

const getFileStates = (status) => {
	const output = {};

	status.jobs.forEach((item) => {
		output[item.file_type] = item;
		output[item.file_type].report = null;
		output[item.file_type].error_count = 0;

		// force an error_data array if no field is passed back in the JSON
		if (!item.hasOwnProperty('error_data')) {
			output[item.file_type].error_data = [];
		}
		else {
			let count = 0;
			item.error_data.forEach((error) => {
				count += parseInt(error.occurrences);
			});

			output[item.file_type].error_count = count;
		}

	});

	return output;
}

const getCrossFileData = (data, validKeys) => {
	const output = {};

	// generate the file pair keys
	let i = 1;

	for (let index in data.crossFile.error_data) {
		// fetch the error object
		const item = data.crossFile.error_data[index];

		// generate possible key names for this pair of target/source files
		const keyNames = [item.target_file + '-' + item.source_file, item.source_file + '-' + item.target_file];
		// determine which is the correct name
		let key = keyNames[0];
		if (_.indexOf(validKeys, key) == -1) {
			key = keyNames[1];
		}

		// check if the key is a valid cross-file pairing we care about
		if (_.indexOf(validKeys, key) == -1) {
			// not a valid pair
			continue;
		}

		// check if we've already seen an error for this pairing
		if (output.hasOwnProperty(key)) {
			// this pair already exists, so append the error to the pair's array
			output[key].push(item);
		}
		else {
			// doesn't exist yet, so create an array with this error
			output[key] = [item];
		}
	}

	return output;
}

const getFileReports = (status, reports) => {

	for (let key in status) {
		let item = status[key];
		item.report = reports['job_' + item.job_id + '_error_url'];

		// alphabetize any missing and duplicated headers
		item.missing_headers = _.sortBy(item.missing_headers);
		item.duplicated_headers = _.sortBy(item.duplicated_headers);
	}

	return status;
}

const getCrossFileReports = (crossFile, reports) => {

	const crossFileReports = {};

	for (let key in crossFile) {
		crossFileReports[key] = reports['cross_' + key];
	}

	return crossFileReports;
}

export const validateSubmission  = (submissionId) => {

	const deferred = Q.defer();

	// set the submission ID
	const store = new StoreSingleton().store;
	store.dispatch(uploadActions.setSubmissionId(submissionId));
	// determine the expected cross file validation keys and metadata
	let possiblePairs = determineExpectedPairs();
	store.dispatch(uploadActions.setExpectedCrossPairs(possiblePairs));

	const validKeys = [];
	possiblePairs.forEach((pair) => {
		validKeys.push(pair.key);
	});

	let status;
	let crossFile;
	let crossFileState;
	let crossFileReports;

	fetchStatus(submissionId)
		.then((statusRes) => {
			status = getFileStates(statusRes);
			crossFile = getCrossFileData(statusRes, validKeys);
			crossFileState = statusRes.crossFile.job_status;
			return fetchErrorReports(submissionId);
		})
		.then((reports) => {
			getFileReports(status, reports);
			crossFileReports = getCrossFileReports(crossFile, reports);
			deferred.resolve({
				file: status,
				crossFile: {
					state: crossFileState,
					reports: crossFileReports,
					data: crossFile
				}
			});
		})
		.catch((err) => {
			deferred.reject(err);
		});

	return deferred.promise;

}

export const listUsers = () => {
	const deferred = Q.defer();

	let request = {
		status: "approved"
	};

	Request.get(kGlobalConstants.API + 'list_user_emails/')
		.send(request)
		.end((err, res) => {
			if (err) {
				deferred.reject(err);
			}
			else {
				deferred.resolve(res.body.users);
			}
		});

	return deferred.promise;
}

export const sendNotification = (users, id) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'email_users/')
        .send({
        	'users': users,
        	'email_template': 'review_submission',
        	'submission_id': id
        })
        .end((errFile, res) => {
            if (errFile) {
                deferred.reject(errFile);
            }
            else {
                deferred.resolve(res.body);
            }
        });
    return deferred.promise;
}<|endoftext|>


<commit_before>goog.provide('hutmap.FilteredHuts');

goog.require('goog.asserts');

goog.scope(function() {
  var assertArray = goog.asserts.assertArray;

  /**
   * Applies a set of filters to a set of huts to obtain a new set of huts.
   *
   * @param {Array.<hutmap.Hut>} huts a list of hutmap.Hut objects
   * @param {Array.<hutmap.Filter>} filters a list of hutmap.Filter objects
   * @constructor
   */
  hutmap.FilteredHuts = function(huts, filters) {
    throw "not implemented";
    this.huts = assertArray(huts);
  };

  goog.inherits(hutmap.FilteredHuts, goog.events.EventTarget);

  /**
   * Event types for hutmap.FilteredHuts
   * @enum {string}
   */
  hutmap.FilteredHuts.EventType = {
    HUTS_CHANGED: 'huts_changed',
    FILTERS_CHANGED: 'filters_changed'
  };

  /**
   * @return {Array.<hutmap.Hut>} the set of huts which match all the filters.
   */
  hutmap.FilteredHuts.prototype.get_filtered_huts = function() {
    throw "not implemented";
  };

  /** Huts */

  /**
   * @param id {number} the id of the hut to retrieve
   * @return {hutmap.Hut} the hut specified by id
   */
  hutmap.FilteredHuts.prototype.get_hut = function(id) {
    throw "not implemented";
  };

  /**
   * @param id {number} the id of the hut to retrieve
   * @return {boolean} true if this contains a hut with given id
   */
  hutmap.FilteredHuts.prototype.contains_hut = function(id) {
    throw "not implemented";
  };

  /**
   * @param hut {hutmap.Hut} add the hut to this. If a hut with the same id as
   *                         the given hut already exists, it will be replaced.
   */
  hutmap.FilteredHuts.prototype.add_hut = function(hut) {
    throw "not implemented";
  };

  /**
   * @return {Array.<hutmap.Hut> a list of the huts contained in this
   */
  hutmap.FilteredHuts.prototype.get_huts = function() {
    throw "not implemented";
  };

  /**
   * @return {number} the number of huts contained in this
   */
  hutmap.FilteredHuts.prototype.get_huts_count = function() {
    throw "not implemented";
  };

  /**
   * @param {Array.<hutmap.Hut> huts the huts to set for this. All previous huts
   *                                will be cleared.
   */
  hutmap.FilteredHuts.prototype.set_huts = function(huts) {
    throw "not implemented";
  };

  /** Filters */

  /**
   * @return {Array.<hutmap.Filter>} the filters contained in this
   */
  hutmap.FilteredHuts.prototype.get_filters = function() {
    throw "not implemented";
  };

  /**
   * @param {string} name a name for the filter. If a filter with the given
   *                      name already exists, it will be replaced.
   * @param {hutmap.Filter} filter the filter
   */
  hutmap.FilteredHuts.prototype.set_filter = function(name, filter) {
    throw "not implemented";
  };

  /**
   * Clear all filters from this.
   */
  hutmap.FilteredHuts.prototype.clear_filters = function() {
    throw "not implemented";
  };
});

<commit_msg>Updated method signatures for filters.<commit_after>goog.provide('hutmap.FilteredHuts');

goog.require('goog.asserts');

goog.scope(function() {
  var assertArray = goog.asserts.assertArray;

  /**
   * Applies a set of filters to a set of huts to obtain a new set of huts.
   *
   * @param {Array.<hutmap.Hut>} huts a list of hutmap.Hut objects
   * @param {Array.<hutmap.Filter>} filters a list of hutmap.Filter objects
   * @constructor
   */
  hutmap.FilteredHuts = function(huts, filters) {
    throw "not implemented";
    this.huts = assertArray(huts);
  };

  goog.inherits(hutmap.FilteredHuts, goog.events.EventTarget);

  /**
   * Event types for hutmap.FilteredHuts
   * @enum {string}
   */
  hutmap.FilteredHuts.EventType = {
    HUTS_CHANGED: 'huts_changed',
    FILTERS_CHANGED: 'filters_changed'
  };

  /**
   * @return {Array.<hutmap.Hut>} the set of huts which match all the filters.
   */
  hutmap.FilteredHuts.prototype.get_filtered_huts = function() {
    throw "not implemented";
  };

  /** Huts */

  /**
   * @param id {number} the id of the hut to retrieve
   * @return {hutmap.Hut} the hut specified by id
   */
  hutmap.FilteredHuts.prototype.get_hut = function(id) {
    throw "not implemented";
  };

  /**
   * @param id {number} the id of the hut to retrieve
   * @return {boolean} true if this contains a hut with given id
   */
  hutmap.FilteredHuts.prototype.contains_hut = function(id) {
    throw "not implemented";
  };

  /**
   * @param hut {hutmap.Hut} add the hut to this. If a hut with the same id as
   *                         the given hut already exists, it will be replaced.
   */
  hutmap.FilteredHuts.prototype.add_hut = function(hut) {
    throw "not implemented";
  };

  /**
   * @return {Array.<hutmap.Hut> a list of the huts contained in this
   */
  hutmap.FilteredHuts.prototype.get_huts = function() {
    throw "not implemented";
  };

  /**
   * @return {number} the number of huts contained in this
   */
  hutmap.FilteredHuts.prototype.get_huts_count = function() {
    throw "not implemented";
  };

  /**
   * @param {Array.<hutmap.Hut> huts the huts to set for this. All previous huts
   *                                will be cleared.
   */
  hutmap.FilteredHuts.prototype.set_huts = function(huts) {
    throw "not implemented";
  };

  /** Filters */

  /**
   * @return {Object.<string, hutmap.Filter>} the filters contained in this
   */
  hutmap.FilteredHuts.prototype.get_filters = function() {
    throw "not implemented";
  };

  /**
   * @param {string} field the field of a hutmap.Hut the filter should be
   *                       applied to. You may include dots in the field name
   *                       to traverse into other objects. For example,
   *                       'agency.name' will be translated into an access to
   *                       hut['agency']['name']. If a filter for the given
   *                       field already exists, it will be replaced.
   * @param {hutmap.Filter} filter the filter
   */
  hutmap.FilteredHuts.prototype.set_filter = function(field, filter) {
    throw "not implemented";
  };

  /**
   * Clear all filters from this.
   */
  hutmap.FilteredHuts.prototype.clear_filters = function() {
    throw "not implemented";
  };
});

<|endoftext|>


<commit_before>// Mark MacKay http://method.ac MIT License

$.fn.dragInput = function(cfg){
  return this.each(function(){

    this.repeating = false;
    // Apply specified options or defaults:
    // (Ought to refactor this some day to use $.extend() instead)
    this.dragCfg = {
      min: cfg && !isNaN(parseFloat(cfg.min)) ? Number(cfg.min) : null, // Fixes bug with min:0
      max: cfg && !isNaN(parseFloat(cfg.max)) ? Number(cfg.max) : null,
      step: cfg && Number(cfg.step) ? cfg.step : 1,
      stepfunc: cfg && cfg.stepfunc ? cfg.stepfunc : false,
      dragAdjust: cfg && cfg.dragAdjust ? cfg.dragAdjust : 1,
      height: 70,
      cursor: cfg && cfg.cursor ? Boolean(cfg.cursor) : false,
      start: cfg && cfg.start ? Number(cfg.start) : 0,
      _btn_width: 20,
      _direction: null,
      _delay: null,
      _repeat: null,
      callback: cfg && cfg.callback ? cfg.callback : null
    };
    // if a smallStep isn't supplied, use half the regular step
    this.dragCfg.smallStep = cfg && cfg.smallStep ? cfg.smallStep : this.dragCfg.step/2;
    var dragAdjust = this.dragCfg.dragAdjust;
    var $label = $(this).parent();
    var $input = $(this);
    var cursorHeight = this.dragCfg.height;
    var min = this.dragCfg.min;
    var max = this.dragCfg.max
    var step = this.dragCfg.step
    var area = (max - min > 0) ?  (max - min) / step : 200;
    var scale = area/cursorHeight * step;
    var lastY = 0;
    var attr = this.getAttribute("data-attr");
    var canvas = methodDraw.canvas
    var isTouch = svgedit.browser.isTouch();
    var completed = true //for mousewheel
    var $cursor = (area && this.dragCfg.cursor)
      ? $("
").appendTo($label)
      : false
    $input.attr("readonly", "readonly")
    if ($cursor && !isNaN(this.dragCfg.start)) $cursor.css("top", (this.dragCfg.start*-1)/scale+cursorHeight)

    //this is where all the magic happens
    this.adjustValue = function(i, completed){
      var v;
      i = parseFloat(i);
      if(isNaN(this.value)) {
        v = this.dragCfg.reset;
      } else if($.isFunction(this.dragCfg.stepfunc)) {
        v = this.dragCfg.stepfunc(this, i);
      } else {
        v = Number((Number(this.value) + Number(i)).toFixed(5));
      }
      if (max !== null) v = Math.min(v, max);
      if (min !== null) v = Math.max(v, min);
      if ($cursor) this.updateCursor(v);
      this.value = v;
      $label.attr("data-value", v)
      if ($.isFunction(this.dragCfg.callback)) this.dragCfg.callback(this, completed)
    };

    $label.toggleClass("draginput", $label.is("label"))

    // when the mouse is down and moving
    this.move = function(e, oy, val) {
      if (isTouch) {
        e = e.originalEvent.touches[0]
      }
      // just got started let's save for undo purposes
      if (lastY === 0) {
        lastY = oy;
      }
      var deltaY = (e.pageY - lastY) *-1
      lastY = e.pageY;
      val = (deltaY * scale) * dragAdjust
      var fixed = (step < 1) ? 1 : 0
      this.adjustValue(val.toFixed(fixed))  //no undo true
    };

    //when the mouse is released
    this.stop = function() {
      var selectedElems = canvas.getSelectedElems();
      $('body').removeClass('dragging');
      $label.removeClass("active");
      completed = true;
      $(window).unbind("mousemove.draginput touchmove.draginput mouseup.draginput touchend.draginput");
      lastY = 0;
      if (selectedElems[0]) {
        var batchCmd = canvas.undoMgr.finishUndoableChange();
        if (!batchCmd.isEmpty()) canvas.undoMgr.addCommandToHistory(batchCmd);
      }
      this.adjustValue(0, completed)
    }

    this.updateCursor = function(){
      var value = parseFloat(this.value);
      var pos = (value*-1)/scale+cursorHeight;
      $cursor.css("top", pos);
    }

    this.launch = function(e) {
      var selectedElems = canvas.getSelectedElems();
      if (isTouch) e = e.originalEvent.touches[0];
      var oy = e.pageY;
      var val = this.value;
      var el = this;
      canvas.undoMgr.beginUndoableChange(attr, selectedElems)
      $('body').addClass('dragging');
      $label.addClass('active');
      $(window).bind("mousemove.draginput touchmove.draginput", function(e){el.move(e, oy, parseFloat(val))})
      $(window).bind("mouseup.draginput touchend.draginput", function(e){el.stop()})
    }

    $(this)
      .attr("readonly", "readonly")
      .attr("data-scale", scale)
      .attr("data-domain", cursorHeight)
      .attr("data-cursor", ($cursor != false))

    .bind("mousedown touchstart", function(e){
      this.blur();
      this.launch(e);
    })

    .bind("dblclick taphold", function(e) {
      this.removeAttribute("readonly", "readonly");
      this.focus();
      this.select();
    })

    .keydown(function(e){
      // Respond to up/down arrow keys.
      switch(e.keyCode){
        case 13: this.adjustValue(0); this.blur();  break; // Enter
      }
    })

    .focus(function(e){
      if (this.getAttribute("readonly") === "readonly") this.blur()
    })

    .blur(function(e){
      this.setAttribute("readonly", "readonly")
    })

    .bind("mousewheel", function(e, delta, deltaX, deltaY){
      var selectedElems = canvas.getSelectedElems();
      if (completed) canvas.undoMgr.beginUndoableChange(attr, selectedElems)
      completed = false
      clearTimeout(window.undoTimeout)
      window.undoTimeout = setTimeout(function(){
        wheel_input.stop()
      },200)

      var wheel_input = this;
      if (deltaY > 0)
        this.adjustValue(this.dragCfg.step);
      else if (deltaY < 0)
        this.adjustValue(-this.dragCfg.step);
      e.preventDefault();

    })

  });

};

// public function
$.fn.dragInput.updateCursor = function(el){
  var value = parseFloat(el.value);
  var scale = parseFloat(el.getAttribute("data-scale"));
  var domain = parseFloat(el.getAttribute("data-domain"));
  var pos = ((value*-1)/scale+domain) + "px";
  var cursor = el.parentNode.lastChild
  if (cursor.className == "draginput_cursor") cursor.style.top = pos;
}

<commit_msg>draginput enter<commit_after>// Mark MacKay http://method.ac MIT License

$.fn.dragInput = function(cfg){
  return this.each(function(){

    this.repeating = false;
    // Apply specified options or defaults:
    // (Ought to refactor this some day to use $.extend() instead)
    this.dragCfg = {
      min: cfg && !isNaN(parseFloat(cfg.min)) ? Number(cfg.min) : null, // Fixes bug with min:0
      max: cfg && !isNaN(parseFloat(cfg.max)) ? Number(cfg.max) : null,
      step: cfg && Number(cfg.step) ? cfg.step : 1,
      stepfunc: cfg && cfg.stepfunc ? cfg.stepfunc : false,
      dragAdjust: cfg && cfg.dragAdjust ? cfg.dragAdjust : 1,
      height: 70,
      cursor: cfg && cfg.cursor ? Boolean(cfg.cursor) : false,
      start: cfg && cfg.start ? Number(cfg.start) : 0,
      _btn_width: 20,
      _direction: null,
      _delay: null,
      _repeat: null,
      callback: cfg && cfg.callback ? cfg.callback : null
    };
    // if a smallStep isn't supplied, use half the regular step
    this.dragCfg.smallStep = cfg && cfg.smallStep ? cfg.smallStep : this.dragCfg.step/2;
    var dragAdjust = this.dragCfg.dragAdjust;
    var $label = $(this).parent();
    var $input = $(this);
    var cursorHeight = this.dragCfg.height;
    var min = this.dragCfg.min;
    var max = this.dragCfg.max
    var step = this.dragCfg.step
    var area = (max - min > 0) ?  (max - min) / step : 200;
    var scale = area/cursorHeight * step;
    var lastY = 0;
    var attr = this.getAttribute("data-attr");
    var canvas = methodDraw.canvas
    var isTouch = svgedit.browser.isTouch();
    var completed = true //for mousewheel
    var $cursor = (area && this.dragCfg.cursor)
      ? $("
").appendTo($label)
      : false
    $input.attr("readonly", "readonly")
    if ($cursor && !isNaN(this.dragCfg.start)) $cursor.css("top", (this.dragCfg.start*-1)/scale+cursorHeight)

    //this is where all the magic happens
    this.adjustValue = function(i, completed){
      var v;
      i = parseFloat(i);
      if(isNaN(this.value)) {
        v = this.dragCfg.reset;
      } else if($.isFunction(this.dragCfg.stepfunc)) {
        v = this.dragCfg.stepfunc(this, i);
      } else {
        v = Number((Number(this.value) + Number(i)).toFixed(5));
      }
      if (max !== null) v = Math.min(v, max);
      if (min !== null) v = Math.max(v, min);
      if ($cursor) this.updateCursor(v);
      this.value = v;
      $label.attr("data-value", v)
      if ($.isFunction(this.dragCfg.callback)) this.dragCfg.callback(this, completed)
    };

    $label.toggleClass("draginput", $label.is("label"))

    // when the mouse is down and moving
    this.move = function(e, oy, val) {
      if (isTouch) {
        e = e.originalEvent.touches[0]
      }
      // just got started let's save for undo purposes
      if (lastY === 0) {
        lastY = oy;
      }
      var deltaY = (e.pageY - lastY) *-1
      lastY = e.pageY;
      val = (deltaY * scale) * dragAdjust
      var fixed = (step < 1) ? 1 : 0
      this.adjustValue(val.toFixed(fixed))  //no undo true
    };

    //when the mouse is released
    this.stop = function() {
      var selectedElems = canvas.getSelectedElems();
      $('body').removeClass('dragging');
      $label.removeClass("active");
      completed = true;
      $(window).unbind("mousemove.draginput touchmove.draginput mouseup.draginput touchend.draginput");
      lastY = 0;
      if (selectedElems[0]) {
        var batchCmd = canvas.undoMgr.finishUndoableChange();
        if (!batchCmd.isEmpty()) canvas.undoMgr.addCommandToHistory(batchCmd);
      }
      this.adjustValue(0, completed)
    }

    this.updateCursor = function(){
      var value = parseFloat(this.value);
      var pos = (value*-1)/scale+cursorHeight;
      $cursor.css("top", pos);
    }

    this.launch = function(e) {
      var selectedElems = canvas.getSelectedElems();
      if (isTouch) e = e.originalEvent.touches[0];
      var oy = e.pageY;
      var val = this.value;
      var el = this;
      canvas.undoMgr.beginUndoableChange(attr, selectedElems)
      $('body').addClass('dragging');
      $label.addClass('active');
      $(window).bind("mousemove.draginput touchmove.draginput", function(e){el.move(e, oy, parseFloat(val))})
      $(window).bind("mouseup.draginput touchend.draginput", function(e){el.stop()})
    }

    $(this)
      .attr("readonly", "readonly")
      .attr("data-scale", scale)
      .attr("data-domain", cursorHeight)
      .attr("data-cursor", ($cursor !== false))

    .bind("mousedown touchstart", function(e){
      this.blur();
      this.launch(e);
    })

    .bind("dblclick taphold", function(e) {
      this.removeAttribute("readonly", "readonly");
      this.focus();
      this.select();
    })

    .keydown(function(e){
      // Respond to up/down arrow keys.
      var key = e.key;
      var _self = this;
      var keys = {
        "ArrowUp": function(){ _self.adjustValue(1) },
        "ArrowDown": function(){ _self.adjustValue(-1) },
        "ArrowDown": function(){ _self.adjustValue(-1) },
        "Enter": function(){ _self.adjustValue(0); _self.blur(); },
      }
      if (keys[key]) {
        e.preventDefault();
        keys[key]();
      }
    })

    .focus(function(e){
      if (this.getAttribute("readonly") === "readonly") this.blur()
    })

    .blur(function(e){
      this.setAttribute("readonly", "readonly")
    })

    .bind("mousewheel", function(e, delta, deltaX, deltaY){
      var selectedElems = canvas.getSelectedElems();
      if (completed) canvas.undoMgr.beginUndoableChange(attr, selectedElems)
      completed = false
      clearTimeout(window.undoTimeout)
      window.undoTimeout = setTimeout(function(){
        wheel_input.stop()
      },200)

      var wheel_input = this;
      if (deltaY > 0)
        this.adjustValue(this.dragCfg.step);
      else if (deltaY < 0)
        this.adjustValue(-this.dragCfg.step);
      e.preventDefault();

    })

  });

};

// public function
$.fn.dragInput.updateCursor = function(el){
  var value = parseFloat(el.value);
  var scale = parseFloat(el.getAttribute("data-scale"));
  var domain = parseFloat(el.getAttribute("data-domain"));
  var pos = ((value*-1)/scale+domain) + "px";
  var cursor = el.parentNode.lastChild
  if (cursor.className == "draginput_cursor") cursor.style.top = pos;
}

<|endoftext|>


<commit_before>import {
  FETCH_USER_PENDING,
  FETCH_USER_REJECTED,
  FETCH_USER_FULFILLED,
} from './actionTypes';

const initialState = {
  isFetching: false,
  isFetched: false,
  error: null,
  request: null,
  users: {

  },
};

const reducer = (state = { ...initialState }, action) => {
  switch (action.type) {
    case FETCH_USER_PENDING: {
      return { ...state, isFetching: true };
    }
    case FETCH_USER_REJECTED: {
      return { ...state, isFetching: false, error: action.payload };
    }
    case FETCH_USER_FULFILLED: {
      return {
        ...state,
        isFetching: false,
        isFetched: true,
        request: action.payload,
      };
    }
  }
  return state;
};

export default reducer;
<commit_msg>set user initial state<commit_after>import {
  FETCH_USER_PENDING,
  FETCH_USER_REJECTED,
  FETCH_USER_FULFILLED,
} from './actionTypes';

const initialState = {
  isFetching: false,
  isFetched: false,
  error: null,
  request: null,
  users: {
    "jason-kao": {
      id: 0,
      firstName: "Jason",
      lastName: "Kao",
      username: "jkao1",
      email: "jkao1@stuy.edu",
      description: "Jason is a web editor for The Spectator."
    }
  },
  roles: {
    0: {
      id: 0,
      title: "Contributor",
      slug: "contributors",
      credentials: 0
    },
  },
  userRoles: [
    {
      userSlug: "jason-kao",
      roleID: 0
    }
  ],
  authorship: [
    {
      articleSlug: "apples-rain-in-new-york-city",
      userSlug: "jason-kao"
    }
  ]
};

const reducer = (state = { ...initialState }, action) => {
  switch (action.type) {
    case FETCH_USER_PENDING: {
      return { ...state, isFetching: true };
    }
    case FETCH_USER_REJECTED: {
      return { ...state, isFetching: false, error: action.payload };
    }
    case FETCH_USER_FULFILLED: {
      return {
        ...state,
        isFetching: false,
        isFetched: true,
        request: action.payload,
      };
    }
  }
  return state;
};

export default reducer;
<|endoftext|>