<commit_before>/*! angular-breadcrumb - v0.4.0-dev-2015-08-07
* http://ncuillery.github.io/angular-breadcrumb
* Copyright (c) 2015 Nicolas Cuillery; Licensed MIT */

(function (window, angular, undefined) {
'use strict';

function isAOlderThanB(scopeA, scopeB) {
    if(angular.equals(scopeA.length, scopeB.length)) {
        return scopeA > scopeB;
    } else {
        return scopeA.length > scopeB.length;
    }
}

function parseStateRef(ref) {
    var parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
    if (!parsed || parsed.length !== 4) { throw new Error("Invalid state ref '" + ref + "'"); }
    return { state: parsed[1], paramExpr: parsed[3] || null };
}

function $Breadcrumb() {

    var $$options = {
        prefixStateName: null,
        template: 'bootstrap3',
        templateUrl: null,
        includeAbstract : false
    };

    this.setOptions = function(options) {
        angular.extend($$options, options);
    };

    this.$get = ['$state', '$stateParams', '$rootScope', function($state, $stateParams, $rootScope) {

        var $lastViewScope = $rootScope;

        // Early catch of $viewContentLoaded event
        $rootScope.$on('$viewContentLoaded', function (event) {
            // With nested views, the event occur several times, in "wrong" order
            if(!event.targetScope.ncyBreadcrumbIgnore &&
                isAOlderThanB(event.targetScope.$id, $lastViewScope.$id)) {
                $lastViewScope = event.targetScope;
            }
        });

        // Get the parent state
        var $$parentState = function(state) {
            // Check if state has explicit parent OR we try guess parent from its name
            var parent = state.parent || (/^(.+)\.[^.]+$/.exec(state.name) || [])[1];
            var isObjectParent = typeof parent === "object";
            // if parent is a object reference, then extract the name
            return isObjectParent ? parent.name : parent;
        };

        // Add the state in the chain if not already in and if not abstract
        var $$addStateInChain = function(chain, stateRef) {
            var conf,
                parentParams,
                ref = parseStateRef(stateRef),
                force = false,
                skip = false;

            for(var i=0, l=chain.length; i<l; i+=1) {
                if (chain[i].name === ref.state) {
                    return;
                }
            }

            conf = $state.get(ref.state);
            // Get breadcrumb options
            if(conf.ncyBreadcrumb) {
                if(conf.ncyBreadcrumb.force){ force = true; }
                if(conf.ncyBreadcrumb.skip){ skip = true; }
            }
            if((!conf.abstract || $$options.includeAbstract || force) && !skip) {
                if(ref.paramExpr) {
                    parentParams = $lastViewScope.$eval(ref.paramExpr);
                }

                conf.ncyBreadcrumbLink = $state.href(ref.state, parentParams || $stateParams || {});
                chain.unshift(conf);
            }
        };

        // Get the state for the parent step in the breadcrumb
        var $$breadcrumbParentState = function(stateRef) {
            var ref = parseStateRef(stateRef),
                conf = $state.get(ref.state);

            if(conf.ncyBreadcrumb && conf.ncyBreadcrumb.parent) {
                // Handle the "parent" property of the breadcrumb, override the parent/child relation of the state
                var isFunction = typeof conf.ncyBreadcrumb.parent === 'function';
                var parentStateRef = isFunction ? conf.ncyBreadcrumb.parent($lastViewScope) : conf.ncyBreadcrumb.parent;
                if(parentStateRef) {
                    return parentStateRef;
                }
            }

            return $$parentState(conf);
        };

        return {

            getTemplate: function(templates) {
                if($$options.templateUrl) {
                    // templateUrl takes precedence over template
                    return null;
                } else if(templates[$$options.template]) {
                    // Predefined templates (bootstrap, ...)
                    return templates[$$options.template];
                } else {
                    return $$options.template;
                }
            },

            getTemplateUrl: function() {
                return $$options.templateUrl;
            },

            getStatesChain: function(exitOnFirst) { // Deliberately undocumented param, see getLastStep
                var chain = [];

                // From current state to the root
                for(var stateRef = $state.$current.self.name; stateRef; stateRef=$$breadcrumbParentState(stateRef)) {
                    $$addStateInChain(chain, stateRef);
                    if(exitOnFirst && chain.length) {
                        return chain;
                    }
                }

                // Prefix state treatment
                if($$options.prefixStateName) {
                    $$addStateInChain(chain, $$options.prefixStateName);
                }

                return chain;
            },

            getLastStep: function() {
                var chain = this.getStatesChain(true);
                return chain.length ? chain[0] : undefined;
            },

            $getLastViewScope: function() {
                return $lastViewScope;
            }
        };
    }];
}

var getExpression = function(interpolationFunction) {
    if(interpolationFunction.expressions) {
        return interpolationFunction.expressions;
    } else {
        var expressions = [];
        angular.forEach(interpolationFunction.parts, function(part) {
            if(angular.isFunction(part)) {
                expressions.push(part.exp);
            }
        });
        return expressions;
    }
};

var registerWatchers = function(labelWatcherArray, interpolationFunction, viewScope, step) {
    angular.forEach(getExpression(interpolationFunction), function(expression) {
        var watcher = viewScope.$watch(expression, function() {
            step.ncyBreadcrumbLabel = interpolationFunction(viewScope);
        });
        labelWatcherArray.push(watcher);
    });

};

var deregisterWatchers = function(labelWatcherArray) {
    angular.forEach(labelWatcherArray, function(deregisterWatch) {
        deregisterWatch();
    });
};

function BreadcrumbDirective($interpolate, $breadcrumb, $rootScope) {
    var $$templates = {
        bootstrap2: '
' +
            '
' +
            '{{step.ncyBreadcrumbLabel}}' +
            '{{step.ncyBreadcrumbLabel}}' +
            '/' +
            '
' +
            '
',
        bootstrap3: '
' +
            '
' +
            '{{step.ncyBreadcrumbLabel}}' +
            '{{step.ncyBreadcrumbLabel}}' +
            '
' +
            '
'
    };

    return {
        restrict: 'AE',
        replace: true,
        scope: {},
       // template: $breadcrumb.getTemplate($$templates),
       // templateUrl: $breadcrumb.getTemplateUrl(),
        templateUrl: 'breadcrumb.tpl.html',
        controller: function ($scope,$state,$location, $rootScope) {
            $scope.testevent = function(statename, label){
           console.log($location.url());
           console.log($location.absUrl());
           console.log( $rootScope.cattree);
           var tree = $rootScope.cattree;

                if (statename == 'home') {
                    $state.go('home');
                }

                if (statename == 'category') {
                     var result = _.where(tree, {Name: label});
                     console.log(result);
                    $state.go('category' , {ID:result[0].ID});
                }
                if(statename == 'secound'){
                    var result = _.where(tree, {Name: label});
                    var subId = result[0].ID;
                    var parentCat =  _.where(tree, {ID: result.ParentID});
                    $state.go('secound', {ID:parentCat[0].ID,subID:result[0].ID});
                }

            }
        },
        link: {
            post: function postLink(scope) {
                var labelWatchers = [];

                var renderBreadcrumb = function() {
                    deregisterWatchers(labelWatchers);
                    labelWatchers = [];

                    var viewScope = $breadcrumb.$getLastViewScope();
                    scope.steps = $breadcrumb.getStatesChain();

                    angular.forEach(scope.steps, function (step) {
                        if (step.ncyBreadcrumb && step.ncyBreadcrumb.label) {
                            var parseLabel = $interpolate(step.ncyBreadcrumb.label);
                          //  var parseId = $interpolate(step.ncyBreadcrumb.id);
                            step.ncyBreadcrumbLabel = parseLabel(viewScope);
                            //step.ncyBreadcrumbId = parseId(viewScope);
                            // Watcher for further viewScope updates
                            registerWatchers(labelWatchers, parseLabel, viewScope, step);
                        } else {
                            step.ncyBreadcrumbLabel = step.name;
                        }
                    });
                };

                $rootScope.$on('$viewContentLoaded', function (event) {
                    if(!event.targetScope.ncyBreadcrumbIgnore) {
                        renderBreadcrumb();
                    }
                });

                // View(s) may be already loaded while the directive's linking
                renderBreadcrumb();
            }
        }
    };
}
BreadcrumbDirective.$inject = ['$interpolate', '$breadcrumb', '$rootScope'];

function BreadcrumbLastDirective($interpolate, $breadcrumb, $rootScope) {

    return {
        restrict: 'A',
        scope: {},
        template: '{{ncyBreadcrumbLabel}}',
        compile: function(cElement, cAttrs) {
            alert();
            // Override the default template if ncyBreadcrumbLast has a value
            var template = cElement.attr(cAttrs.$attr.ncyBreadcrumbLast);
            if(template) {
                cElement.html(template);
            }

            return {
                post: function postLink(scope) {
                    var labelWatchers = [];

                    var renderLabel = function() {
                        deregisterWatchers(labelWatchers);
                        labelWatchers = [];

                        var viewScope = $breadcrumb.$getLastViewScope();
                        var lastStep = $breadcrumb.getLastStep();
                        if(lastStep) {
                            scope.ncyBreadcrumbLink = lastStep.ncyBreadcrumbLink;
                            if (lastStep.ncyBreadcrumb && lastStep.ncyBreadcrumb.label) {
                                var parseLabel = $interpolate(lastStep.ncyBreadcrumb.label);
                                scope.ncyBreadcrumbLabel = parseLabel(viewScope);
                                // Watcher for further viewScope updates
                                // Tricky last arg: the last step is the entire scope of the directive !
                                registerWatchers(labelWatchers, parseLabel, viewScope, scope);
                            } else {
                                scope.ncyBreadcrumbLabel = lastStep.name;
                            }
                        }
                    };

                    $rootScope.$on('$viewContentLoaded', function (event) {
                        if(!event.targetScope.ncyBreadcrumbIgnore) {
                            renderLabel();
                        }
                    });

                    // View(s) may be already loaded while the directive's linking
                    renderLabel();
                }
            };

        }
    };
}
BreadcrumbLastDirective.$inject = ['$interpolate', '$breadcrumb', '$rootScope'];

function BreadcrumbTextDirective($interpolate, $breadcrumb, $rootScope) {

    return {
        restrict: 'A',
        scope: {},
        template: '{{ncyBreadcrumbChain}}',

        compile: function(cElement, cAttrs) {
            // Override the default template if ncyBreadcrumbText has a value
            var template = cElement.attr(cAttrs.$attr.ncyBreadcrumbText);
            if(template) {
                cElement.html(template);
            }

            var separator = cElement.attr(cAttrs.$attr.ncyBreadcrumbTextSeparator) || ' / ';

            return {
                post: function postLink(scope) {
                    var labelWatchers = [];

                    var registerWatchersText = function(labelWatcherArray, interpolationFunction, viewScope) {
                        angular.forEach(getExpression(interpolationFunction), function(expression) {
                            var watcher = viewScope.$watch(expression, function(newValue, oldValue) {
                                if (newValue !== oldValue) {
                                    renderLabel();
                                }
                            });
                            labelWatcherArray.push(watcher);
                        });
                    };

                    var renderLabel = function() {
                        deregisterWatchers(labelWatchers);
                        labelWatchers = [];

                        var viewScope = $breadcrumb.$getLastViewScope();
                        var steps = $breadcrumb.getStatesChain();
                        var combinedLabels = [];
                        angular.forEach(steps, function (step) {
                            if (step.ncyBreadcrumb && step.ncyBreadcrumb.label) {
                                var parseLabel = $interpolate(step.ncyBreadcrumb.label);
                                combinedLabels.push(parseLabel(viewScope));
                                // Watcher for further viewScope updates
                                registerWatchersText(labelWatchers, parseLabel, viewScope);
                            } else {
                                combinedLabels.push(step.name);
                            }
                        });

                        scope.ncyBreadcrumbChain = combinedLabels.join(separator);
                    };

                    $rootScope.$on('$viewContentLoaded', function (event) {
                        if(!event.targetScope.ncyBreadcrumbIgnore) {
                            renderLabel();
                        }
                    });

                    // View(s) may be already loaded while the directive's linking
                    renderLabel();
                }
            };

        }
    };
}
BreadcrumbTextDirective.$inject = ['$interpolate', '$breadcrumb', '$rootScope'];

angular.module('ncy-angular-breadcrumb', ['ui.router.state'])
    .provider('$breadcrumb', $Breadcrumb)
    .directive('ncyBreadcrumb', BreadcrumbDirective)
    .directive('ncyBreadcrumbLast', BreadcrumbLastDirective)
    .directive('ncyBreadcrumbText', BreadcrumbTextDirective);
})(window, window.angular);
<commit_msg>breabcrumb<commit_after>/*! angular-breadcrumb - v0.4.0-dev-2015-08-07
* http://ncuillery.github.io/angular-breadcrumb
* Copyright (c) 2015 Nicolas Cuillery; Licensed MIT */

(function (window, angular, undefined) {
'use strict';

function isAOlderThanB(scopeA, scopeB) {
    if(angular.equals(scopeA.length, scopeB.length)) {
        return scopeA > scopeB;
    } else {
        return scopeA.length > scopeB.length;
    }
}

function parseStateRef(ref) {
    var parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
    if (!parsed || parsed.length !== 4) { throw new Error("Invalid state ref '" + ref + "'"); }
    return { state: parsed[1], paramExpr: parsed[3] || null };
}

function $Breadcrumb() {

    var $$options = {
        prefixStateName: null,
        template: 'bootstrap3',
        templateUrl: null,
        includeAbstract : false
    };

    this.setOptions = function(options) {
        angular.extend($$options, options);
    };

    this.$get = ['$state', '$stateParams', '$rootScope', function($state, $stateParams, $rootScope) {

        var $lastViewScope = $rootScope;

        // Early catch of $viewContentLoaded event
        $rootScope.$on('$viewContentLoaded', function (event) {
            // With nested views, the event occur several times, in "wrong" order
            if(!event.targetScope.ncyBreadcrumbIgnore &&
                isAOlderThanB(event.targetScope.$id, $lastViewScope.$id)) {
                $lastViewScope = event.targetScope;
            }
        });

        // Get the parent state
        var $$parentState = function(state) {
            // Check if state has explicit parent OR we try guess parent from its name
            var parent = state.parent || (/^(.+)\.[^.]+$/.exec(state.name) || [])[1];
            var isObjectParent = typeof parent === "object";
            // if parent is a object reference, then extract the name
            return isObjectParent ? parent.name : parent;
        };

        // Add the state in the chain if not already in and if not abstract
        var $$addStateInChain = function(chain, stateRef) {
            var conf,
                parentParams,
                ref = parseStateRef(stateRef),
                force = false,
                skip = false;

            for(var i=0, l=chain.length; i<l; i+=1) {
                if (chain[i].name === ref.state) {
                    return;
                }
            }

            conf = $state.get(ref.state);
            // Get breadcrumb options
            if(conf.ncyBreadcrumb) {
                if(conf.ncyBreadcrumb.force){ force = true; }
                if(conf.ncyBreadcrumb.skip){ skip = true; }
            }
            if((!conf.abstract || $$options.includeAbstract || force) && !skip) {
                if(ref.paramExpr) {
                    parentParams = $lastViewScope.$eval(ref.paramExpr);
                }

                conf.ncyBreadcrumbLink = $state.href(ref.state, parentParams || $stateParams || {});
                chain.unshift(conf);
            }
        };

        // Get the state for the parent step in the breadcrumb
        var $$breadcrumbParentState = function(stateRef) {
            var ref = parseStateRef(stateRef),
                conf = $state.get(ref.state);

            if(conf.ncyBreadcrumb && conf.ncyBreadcrumb.parent) {
                // Handle the "parent" property of the breadcrumb, override the parent/child relation of the state
                var isFunction = typeof conf.ncyBreadcrumb.parent === 'function';
                var parentStateRef = isFunction ? conf.ncyBreadcrumb.parent($lastViewScope) : conf.ncyBreadcrumb.parent;
                if(parentStateRef) {
                    return parentStateRef;
                }
            }

            return $$parentState(conf);
        };

        return {

            getTemplate: function(templates) {
                if($$options.templateUrl) {
                    // templateUrl takes precedence over template
                    return null;
                } else if(templates[$$options.template]) {
                    // Predefined templates (bootstrap, ...)
                    return templates[$$options.template];
                } else {
                    return $$options.template;
                }
            },

            getTemplateUrl: function() {
                return $$options.templateUrl;
            },

            getStatesChain: function(exitOnFirst) { // Deliberately undocumented param, see getLastStep
                var chain = [];

                // From current state to the root
                for(var stateRef = $state.$current.self.name; stateRef; stateRef=$$breadcrumbParentState(stateRef)) {
                    $$addStateInChain(chain, stateRef);
                    if(exitOnFirst && chain.length) {
                        return chain;
                    }
                }

                // Prefix state treatment
                if($$options.prefixStateName) {
                    $$addStateInChain(chain, $$options.prefixStateName);
                }

                return chain;
            },

            getLastStep: function() {
                var chain = this.getStatesChain(true);
                return chain.length ? chain[0] : undefined;
            },

            $getLastViewScope: function() {
                return $lastViewScope;
            }
        };
    }];
}

var getExpression = function(interpolationFunction) {
    if(interpolationFunction.expressions) {
        return interpolationFunction.expressions;
    } else {
        var expressions = [];
        angular.forEach(interpolationFunction.parts, function(part) {
            if(angular.isFunction(part)) {
                expressions.push(part.exp);
            }
        });
        return expressions;
    }
};

var registerWatchers = function(labelWatcherArray, interpolationFunction, viewScope, step) {
    angular.forEach(getExpression(interpolationFunction), function(expression) {
        var watcher = viewScope.$watch(expression, function() {
            step.ncyBreadcrumbLabel = interpolationFunction(viewScope);
        });
        labelWatcherArray.push(watcher);
    });

};

var deregisterWatchers = function(labelWatcherArray) {
    angular.forEach(labelWatcherArray, function(deregisterWatch) {
        deregisterWatch();
    });
};

function BreadcrumbDirective($interpolate, $breadcrumb, $rootScope) {
    var $$templates = {
        bootstrap2: '
' +
            '
' +
            '{{step.ncyBreadcrumbLabel}}' +
            '{{step.ncyBreadcrumbLabel}}' +
            '/' +
            '
' +
            '
',
        bootstrap3: '
' +
            '

' +
            '
' +
            '
' +
            '
'
    };

    return {
        restrict: 'AE',
        replace: true,
        scope: {},
       // template: $breadcrumb.getTemplate($$templates),
       // templateUrl: $breadcrumb.getTemplateUrl(),
        template: $$templates.bootstrap3,
        controller: function ($scope,$state,$location, $rootScope) {
            $scope.testevent = function(statename, label){
           console.log($location.url());
           console.log($location.absUrl());
           console.log( $rootScope.cattree);
           var tree = $rootScope.cattree;

                if (statename == 'home') {
                    $state.go('home');
                }

                if (statename == 'category') {
                     var result = _.where(tree, {Name: label});
                     console.log(result);
                    $state.go('category' , {ID:result[0].ID});
                }
                if(statename == 'secound'){
                    var result = _.where(tree, {Name: label});
                    var subId = result[0].ID;
                    var parentCat =  _.where(tree, {ID: result.ParentID});
                    $state.go('secound', {ID:parentCat[0].ID,subID:result[0].ID});
                }

            }
        },
        link: {
            post: function postLink(scope) {
                var labelWatchers = [];

                var renderBreadcrumb = function() {
                    deregisterWatchers(labelWatchers);
                    labelWatchers = [];

                    var viewScope = $breadcrumb.$getLastViewScope();
                    scope.steps = $breadcrumb.getStatesChain();

                    angular.forEach(scope.steps, function (step) {
                        if (step.ncyBreadcrumb && step.ncyBreadcrumb.label) {
                            var parseLabel = $interpolate(step.ncyBreadcrumb.label);
                          //  var parseId = $interpolate(step.ncyBreadcrumb.id);
                            step.ncyBreadcrumbLabel = parseLabel(viewScope);
                            //step.ncyBreadcrumbId = parseId(viewScope);
                            // Watcher for further viewScope updates
                            registerWatchers(labelWatchers, parseLabel, viewScope, step);
                        } else {
                            step.ncyBreadcrumbLabel = step.name;
                        }
                    });
                };

                $rootScope.$on('$viewContentLoaded', function (event) {
                    if(!event.targetScope.ncyBreadcrumbIgnore) {
                        renderBreadcrumb();
                    }
                });

                // View(s) may be already loaded while the directive's linking
                renderBreadcrumb();
            }
        }
    };
}
BreadcrumbDirective.$inject = ['$interpolate', '$breadcrumb', '$rootScope'];

function BreadcrumbLastDirective($interpolate, $breadcrumb, $rootScope) {

    return {
        restrict: 'A',
        scope: {},
        template: '{{ncyBreadcrumbLabel}}',
        compile: function(cElement, cAttrs) {
            alert();
            // Override the default template if ncyBreadcrumbLast has a value
            var template = cElement.attr(cAttrs.$attr.ncyBreadcrumbLast);
            if(template) {
                cElement.html(template);
            }

            return {
                post: function postLink(scope) {
                    var labelWatchers = [];

                    var renderLabel = function() {
                        deregisterWatchers(labelWatchers);
                        labelWatchers = [];

                        var viewScope = $breadcrumb.$getLastViewScope();
                        var lastStep = $breadcrumb.getLastStep();
                        if(lastStep) {
                            scope.ncyBreadcrumbLink = lastStep.ncyBreadcrumbLink;
                            if (lastStep.ncyBreadcrumb && lastStep.ncyBreadcrumb.label) {
                                var parseLabel = $interpolate(lastStep.ncyBreadcrumb.label);
                                scope.ncyBreadcrumbLabel = parseLabel(viewScope);
                                // Watcher for further viewScope updates
                                // Tricky last arg: the last step is the entire scope of the directive !
                                registerWatchers(labelWatchers, parseLabel, viewScope, scope);
                            } else {
                                scope.ncyBreadcrumbLabel = lastStep.name;
                            }
                        }
                    };

                    $rootScope.$on('$viewContentLoaded', function (event) {
                        if(!event.targetScope.ncyBreadcrumbIgnore) {
                            renderLabel();
                        }
                    });

                    // View(s) may be already loaded while the directive's linking
                    renderLabel();
                }
            };

        }
    };
}
BreadcrumbLastDirective.$inject = ['$interpolate', '$breadcrumb', '$rootScope'];

function BreadcrumbTextDirective($interpolate, $breadcrumb, $rootScope) {

    return {
        restrict: 'A',
        scope: {},
        template: '{{ncyBreadcrumbChain}}',

        compile: function(cElement, cAttrs) {
            // Override the default template if ncyBreadcrumbText has a value
            var template = cElement.attr(cAttrs.$attr.ncyBreadcrumbText);
            if(template) {
                cElement.html(template);
            }

            var separator = cElement.attr(cAttrs.$attr.ncyBreadcrumbTextSeparator) || ' / ';

            return {
                post: function postLink(scope) {
                    var labelWatchers = [];

                    var registerWatchersText = function(labelWatcherArray, interpolationFunction, viewScope) {
                        angular.forEach(getExpression(interpolationFunction), function(expression) {
                            var watcher = viewScope.$watch(expression, function(newValue, oldValue) {
                                if (newValue !== oldValue) {
                                    renderLabel();
                                }
                            });
                            labelWatcherArray.push(watcher);
                        });
                    };

                    var renderLabel = function() {
                        deregisterWatchers(labelWatchers);
                        labelWatchers = [];

                        var viewScope = $breadcrumb.$getLastViewScope();
                        var steps = $breadcrumb.getStatesChain();
                        var combinedLabels = [];
                        angular.forEach(steps, function (step) {
                            if (step.ncyBreadcrumb && step.ncyBreadcrumb.label) {
                                var parseLabel = $interpolate(step.ncyBreadcrumb.label);
                                combinedLabels.push(parseLabel(viewScope));
                                // Watcher for further viewScope updates
                                registerWatchersText(labelWatchers, parseLabel, viewScope);
                            } else {
                                combinedLabels.push(step.name);
                            }
                        });

                        scope.ncyBreadcrumbChain = combinedLabels.join(separator);
                    };

                    $rootScope.$on('$viewContentLoaded', function (event) {
                        if(!event.targetScope.ncyBreadcrumbIgnore) {
                            renderLabel();
                        }
                    });

                    // View(s) may be already loaded while the directive's linking
                    renderLabel();
                }
            };

        }
    };
}
BreadcrumbTextDirective.$inject = ['$interpolate', '$breadcrumb', '$rootScope'];

angular.module('ncy-angular-breadcrumb', ['ui.router.state'])
    .provider('$breadcrumb', $Breadcrumb)
    .directive('ncyBreadcrumb', BreadcrumbDirective)
    .directive('ncyBreadcrumbLast', BreadcrumbLastDirective)
    .directive('ncyBreadcrumbText', BreadcrumbTextDirective);
})(window, window.angular);
<|endoftext|>


<commit_before>define(function (require, exports) {
    "use strict";

    // Brackets modules
    var Dialogs = brackets.getModule("widgets/Dialogs");

    // Local modules
    var Strings = require("strings");

    // Templates
    var template = require("text!src/Dialogs/templates/progress-dialog.html");

    // Module variables
    var lines = [],
        $textarea;

    // Implementation
    function addLine(str) {
        lines.push(str);
    }

    function onProgress(str) {
        addLine(str);
        $textarea.val(lines.join("\n"));
        $textarea.scrollTop($textarea[0].scrollHeight - $textarea.height());
    }

    function show(promise, title) {

        if (!promise || !promise.finally || !promise.progressed) {
            throw new Error("Invalid argument for progress dialog!");
        }

        var templateArgs = {
            title: title || Strings.OPERATION_IN_PROGRESS_TITLE,
            Strings: Strings
        };

        var compiledTemplate = Mustache.render(template, templateArgs),
            dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate);

        $textarea = dialog.getElement().find("textarea");

        promise.progressed(function (string) {
            onProgress(string);
        }).finally(function () {
            dialog.close();
        });

        return promise;
    }

    exports.show = show;

});
<commit_msg>clear lines with every progress<commit_after>define(function (require, exports) {
    "use strict";

    // Brackets modules
    var Dialogs = brackets.getModule("widgets/Dialogs");

    // Local modules
    var Strings = require("strings");

    // Templates
    var template = require("text!src/Dialogs/templates/progress-dialog.html");

    // Module variables
    var lines,
        $textarea;

    // Implementation
    function addLine(str) {
        lines.push(str);
    }

    function onProgress(str) {
        addLine(str);
        $textarea.val(lines.join("\n"));
        $textarea.scrollTop($textarea[0].scrollHeight - $textarea.height());
    }

    function show(promise, title) {
        lines = [];

        if (!promise || !promise.finally || !promise.progressed) {
            throw new Error("Invalid argument for progress dialog!");
        }

        var templateArgs = {
            title: title || Strings.OPERATION_IN_PROGRESS_TITLE,
            Strings: Strings
        };

        var compiledTemplate = Mustache.render(template, templateArgs),
            dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate);

        $textarea = dialog.getElement().find("textarea");

        promise.progressed(function (string) {
            onProgress(string);
        }).finally(function () {
            dialog.close();
        });

        return promise;
    }

    exports.show = show;

});
<|endoftext|>


<commit_before>import React from 'react';
import { FormattedMessage, defineMessages, injectIntl } from 'react-intl';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import Switch from '@material-ui/core/Switch';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import MdCancel from 'react-icons/lib/md/cancel';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import styled from 'styled-components';
import Attribution from './Attribution';
import ConfirmRequired from './ConfirmRequired';
import Message from '../Message';
import ProjectSelector from '../project/ProjectSelector';
import { getStatus } from '../../helpers';
import { mediaStatuses, mediaLastStatus } from '../../customHelpers';
import { units, StyledIconButton, caption, black54, Row } from '../../styles/js/shared';

const StyledProjectsArea = styled.div`
  margin-top: ${units(2)};
`;

const StyledTaskAssignment = styled.div`
  margin-top ${units(2)};

  .create-task__add-task-description-label, .create-task__add-assignment-button {
    bottom: ${units(2)};
    font: ${caption};
    padding: 0 ${units(1)};
    color: ${black54};
    cursor: pointer;
  }

  .create-task__add-assignment-button {
    border: 0;
    background: transparent;
  }
`;

const HelperText = styled.div`
  font: ${caption};
`;

const messages = defineMessages({
  addValue: {
    id: 'singleChoiceTask.addValue',
    defaultMessage: 'Add Option',
  },
  value: {
    id: 'singleChoiceTask.value',
    defaultMessage: 'Value',
  },
  addOther: {
    id: 'singleChoiceTask.addOther',
    defaultMessage: 'Add "Other"',
  },
  other: {
    id: 'singleChoiceTask.other',
    defaultMessage: 'Other',
  },
  newTask: {
    id: 'singleChoiceTask.newTask',
    defaultMessage: 'New task',
  },
  editTask: {
    id: 'singleChoiceTask.editTask',
    defaultMessage: 'Edit task',
  },
});

class EditTaskDialog extends React.Component {
  constructor(props) {
    super(props);

    const { task } = props;

    this.state = {
      label: task ? task.label : null,
      description: task ? task.description : null,
      options: task ? task.options : [{ label: '' }, { label: '' }],
      project_ids: task ? task.project_ids : [],
      submitDisabled: true,
      showAssignmentField: false,
      required: task ? task.required : false,
      status: task ? task.status : 'unresolved',
      resolvable: task && task.responses && task.responses.edges.length > 0,
      confirmRequired: false,
      jsonschema: task ? task.json_schema : null,
    };
  }

  handleDescriptionChange(e) {
    this.setState({ description: e.target.value });
    this.validateTask(this.state.label, this.state.options);
  }

  handleAddValue() {
    const options = Array.isArray(this.state.options) ? this.state.options.slice(0) : [];
    if (this.state.hasOther) {
      options.splice(-1, 0, { label: '' });
    } else {
      options.push({ label: '' });
    }
    this.setState({ options });

    this.validateTask(this.state.label, options);
  }

  handleAddOther() {
    const options = Array.isArray(this.state.options) ? this.state.options.slice(0) : [];
    const other = true;
    let label = '';

    if (!this.state.hasOther) {
      label = this.props.intl.formatMessage(messages.other);
      options.push({ label, other });
      this.setState({ options, hasOther: true });
    }

    this.validateTask(this.state.label, options);
  }

  handleEditOption(e) {
    const options = this.state.options.slice(0);
    options[parseInt(e.target.id, 10)].label = e.target.value;
    this.setState({ options });

    this.validateTask(this.state.label, options);
  }

  handleRemoveOption(index) {
    const options = this.state.options.slice(0);
    let hasOther = null;

    if (this.state.hasOther) {
      hasOther = index !== options.length - 1;
    } else {
      hasOther = false;
    }

    options.splice(index, 1);

    this.setState({ options, hasOther });

    this.validateTask(this.state.label, options);
  }

  validateTask(label, options) {
    let valid = false;

    if (this.props.taskType === 'single_choice' ||
        this.props.taskType === 'multiple_choice') {
      valid = !!(label && label.trim()) && options.filter(item => item.label !== '').length > 1;
    } else {
      valid = !!(label && label.trim());
    }

    this.setState({ submitDisabled: !valid });
  }

  handleLabelChange(e) {
    this.setState({ label: e.target.value });
    this.validateTask(e.target.value, this.state.options);
  }

  handleJsonSchemaChange(e) {
    this.setState({ jsonschema: e.target.value });
    this.validateTask(this.state.label, this.state.options);
  }

  handleSelectRequired(e, inputChecked) {
    const { media } = this.props;

    if (media) {
      const status = getStatus(mediaStatuses(media), mediaLastStatus(media));

      if (inputChecked && status.completed && !media.last_status_obj.locked) {
        this.setState({ required: inputChecked, confirmRequired: true, status });
        return;
      }
    }

    this.setState({ required: inputChecked });
    this.validateTask(this.state.label, this.state.options);
  }

  handleSelectResolved(e, inputChecked) {
    if (this.state.resolvable && inputChecked) {
      this.setState({ status: 'resolved' });
    } else if (!inputChecked) {
      this.setState({ status: 'unresolved' });
    }
    this.validateTask(this.state.label, this.state.options);
  }

  handleSelectProjects = (projectsIds) => {
    const project_ids = projectsIds.map(id => parseInt(id, 10));
    this.setState({ project_ids });
    this.validateTask(this.state.label, this.state.options);
  };

  handleSubmitTask() {
    const jsonoptions = this.state.options
      ? JSON.stringify(this.state.options
        .map(item => ({ ...item, label: item.label.trim() }))
        .filter(item => item.label !== ''))
      : undefined;

    const task = {
      label: this.state.label,
      description: this.state.description,
      required: this.state.required,
      status: this.state.status,
      jsonoptions,
      json_project_ids: JSON.stringify(this.state.project_ids),
      jsonschema: this.state.jsonschema,
    };

    if (!this.state.submitDisabled) {
      this.props.onSubmit(task);
      this.setState({ submitDisabled: true });
    }
  }

  toggleAssignmentField() {
    this.setState({ showAssignmentField: !this.state.showAssignmentField });
  }

  renderOptions() {
    if (this.props.noOptions) {
      return null;
    }

    if (this.props.taskType !== 'single_choice' &&
        this.props.taskType !== 'multiple_choice') {
      return null;
    }

    const { formatMessage } = this.props.intl;

    const canRemove = this.state.options.length > 2;

    return (

        {this.state.options.map((item, index) => (
          <div key={`create-task__add-options-radiobutton-${index.toString()}`}>
            <Row>
              <ChevronRightIcon />
              <TextField
                key="create-task__add-option-input"
                className="create-task__add-option-input"
                id={index.toString()}
                onChange={this.handleEditOption.bind(this)}
                placeholder={`${formatMessage(messages.value)} ${index + 1}`}
                value={item.label}
                disabled={item.other}
                style={{ padding: `${units(0.5)} ${units(1)}`, width: '75%' }}
              />
              {canRemove ?

                : null}
            </Row>

        ))}

          <Button onClick={this.handleAddValue.bind(this)}>
            {this.props.intl.formatMessage(messages.addValue)}
          </Button>
          <Button
            onClick={this.handleAddOther.bind(this)}
            disabled={this.state.hasOther}
          >
            {this.props.intl.formatMessage(messages.addOther)}
          </Button>

    );
  }

  render() {
    const dialogTitle = this.props.task ? messages.editTask : messages.newTask;

    return (
      <Dialog
        className="create-task__dialog"
        open
        onClose={this.props.onDismiss}
        scroll="paper"
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>{this.props.intl.formatMessage(dialogTitle)}</DialogTitle>
        <DialogContent>
          <Message message={this.props.message} />

          <TextField
            id="task-label-input"
            className="tasks__task-label-input"
            label={<FormattedMessage id="tasks.taskPrompt" defaultMessage="Prompt" />}
            defaultValue={this.state.label}
            onChange={this.handleLabelChange.bind(this)}
            margin="normal"
            multiline
            fullWidth
          />
          <TextField
            id="task-description-input"
            className="create-task__task-description-input"
            label={
              <FormattedMessage id="tasks.description" defaultMessage="Description (optional)" />
            }
            defaultValue={this.state.description}
            onChange={this.handleDescriptionChange.bind(this)}
            margin="normal"
            multiline
            fullWidth
          />
          <FormattedMessage
            id="tasks.requiredCheckbox"
            defaultMessage="Required"
          />
          <Switch
            id="edit-task__required-switch"
            checked={Boolean(this.state.required)}
            onChange={this.handleSelectRequired.bind(this)}
            value="required"
            color="primary"
          />
          <HelperText>
            <FormattedMessage
              id="tasks.requiredHelper"
              defaultMessage="Items cannot be marked as completed while any of their required tasks remains unresolved"
            />
          </HelperText>

          <FormattedMessage
            id="tasks.resolvedCheckbox"
            defaultMessage="Resolved"
          />
          <Switch
            id="edit-task__resolved-switch"
            checked={this.state.status === 'resolved'}
            disabled={!this.state.resolvable}
            onChange={this.handleSelectResolved.bind(this)}
            value="resolved"
            color="primary"
          />
          <HelperText>
            <FormattedMessage
              id="tasks.resolvedHelper"
              defaultMessage="The task can only be resolved if it has been answered"
            />
          </HelperText>
          { this.props.projects ?

            : null
          }
          <ConfirmRequired
            open={this.state.confirmRequired}
            status={this.state.status}
            handleCancel={() => { this.setState({ required: false, confirmRequired: false }); }}
            handleConfirm={() => { this.setState({ confirmRequired: false }); }}
          />

          {this.renderOptions()}

          { this.props.taskType === 'free_text' ?
            <TextField
              id="task-jsonschema-input"
              className="tasks__task-jsonschema-input"
              label={<FormattedMessage id="tasks.taskJsonSchema" defaultMessage="JSON Schema (optional / advanced)" />}
              defaultValue={this.state.jsonschema}
              onChange={this.handleJsonSchemaChange.bind(this)}
              margin="normal"
              multiline
              fullWidth
            /> : null }
        </DialogContent>
        <DialogActions>
          <Button
            className="create-task__dialog-cancel-button"
            onClick={this.props.onDismiss}
          >
            <FormattedMessage id="tasks.cancelAdd" defaultMessage="Cancel" />
          </Button>
          <Button
            className="create-task__dialog-submit-button"
            onClick={this.handleSubmitTask.bind(this)}
            color="primary"
            disabled={this.state.submitDisabled}
          >
            <FormattedMessage id="tasks.add" defaultMessage="Save" />
          </Button>
        </DialogActions>
      </Dialog>
    );
  }
}

export default injectIntl(EditTaskDialog);
<commit_msg>Fix/8057 task option with trailing space (#546)<commit_after>import React from 'react';
import { FormattedMessage, defineMessages, injectIntl } from 'react-intl';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import Switch from '@material-ui/core/Switch';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import MdCancel from 'react-icons/lib/md/cancel';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import styled from 'styled-components';
import Attribution from './Attribution';
import ConfirmRequired from './ConfirmRequired';
import Message from '../Message';
import ProjectSelector from '../project/ProjectSelector';
import { getStatus } from '../../helpers';
import { mediaStatuses, mediaLastStatus } from '../../customHelpers';
import { units, StyledIconButton, caption, black54, Row } from '../../styles/js/shared';

const StyledProjectsArea = styled.div`
  margin-top: ${units(2)};
`;

const StyledTaskAssignment = styled.div`
  margin-top ${units(2)};

  .create-task__add-task-description-label, .create-task__add-assignment-button {
    bottom: ${units(2)};
    font: ${caption};
    padding: 0 ${units(1)};
    color: ${black54};
    cursor: pointer;
  }

  .create-task__add-assignment-button {
    border: 0;
    background: transparent;
  }
`;

const HelperText = styled.div`
  font: ${caption};
`;

const messages = defineMessages({
  addValue: {
    id: 'singleChoiceTask.addValue',
    defaultMessage: 'Add Option',
  },
  value: {
    id: 'singleChoiceTask.value',
    defaultMessage: 'Value',
  },
  addOther: {
    id: 'singleChoiceTask.addOther',
    defaultMessage: 'Add "Other"',
  },
  other: {
    id: 'singleChoiceTask.other',
    defaultMessage: 'Other',
  },
  newTask: {
    id: 'singleChoiceTask.newTask',
    defaultMessage: 'New task',
  },
  editTask: {
    id: 'singleChoiceTask.editTask',
    defaultMessage: 'Edit task',
  },
});

class EditTaskDialog extends React.Component {
  constructor(props) {
    super(props);

    const { task } = props;

    this.state = {
      label: task ? task.label : null,
      description: task ? task.description : null,
      options: task ? task.options : [{ label: '' }, { label: '' }],
      project_ids: task ? task.project_ids : [],
      submitDisabled: true,
      showAssignmentField: false,
      required: task ? task.required : false,
      status: task ? task.status : 'unresolved',
      resolvable: task && task.responses && task.responses.edges.length > 0,
      confirmRequired: false,
      jsonschema: task ? task.json_schema : null,
    };
  }

  handleDescriptionChange(e) {
    this.setState({ description: e.target.value });
    this.validateTask(this.state.label, this.state.options);
  }

  handleAddValue() {
    const options = Array.isArray(this.state.options) ? this.state.options.slice(0) : [];
    if (this.state.hasOther) {
      options.splice(-1, 0, { label: '' });
    } else {
      options.push({ label: '' });
    }
    this.setState({ options });

    this.validateTask(this.state.label, options);
  }

  handleAddOther() {
    const options = Array.isArray(this.state.options) ? this.state.options.slice(0) : [];
    const other = true;
    let label = '';

    if (!this.state.hasOther) {
      label = this.props.intl.formatMessage(messages.other);
      options.push({ label, other });
      this.setState({ options, hasOther: true });
    }

    this.validateTask(this.state.label, options);
  }

  handleEditOption(e) {
    const options = this.state.options.slice(0);
    options[parseInt(e.target.id, 10)].label = e.target.value;
    this.setState({ options });

    this.validateTask(this.state.label, options);
  }

  handleRemoveOption(index) {
    const options = this.state.options.slice(0);
    let hasOther = null;

    if (this.state.hasOther) {
      hasOther = index !== options.length - 1;
    } else {
      hasOther = false;
    }

    options.splice(index, 1);

    this.setState({ options, hasOther });

    this.validateTask(this.state.label, options);
  }

  validateTask(label, options) {
    let valid = false;

    if (this.props.taskType === 'single_choice' ||
        this.props.taskType === 'multiple_choice') {
      valid = !!(label && label.trim()) && options.filter(item => item.label.trim() !== '').length > 1;
    } else {
      valid = !!(label && label.trim());
    }

    this.setState({ submitDisabled: !valid });
  }

  handleLabelChange(e) {
    this.setState({ label: e.target.value });
    this.validateTask(e.target.value, this.state.options);
  }

  handleJsonSchemaChange(e) {
    this.setState({ jsonschema: e.target.value });
    this.validateTask(this.state.label, this.state.options);
  }

  handleSelectRequired(e, inputChecked) {
    const { media } = this.props;

    if (media) {
      const status = getStatus(mediaStatuses(media), mediaLastStatus(media));

      if (inputChecked && status.completed && !media.last_status_obj.locked) {
        this.setState({ required: inputChecked, confirmRequired: true, status });
        return;
      }
    }

    this.setState({ required: inputChecked });
    this.validateTask(this.state.label, this.state.options);
  }

  handleSelectResolved(e, inputChecked) {
    if (this.state.resolvable && inputChecked) {
      this.setState({ status: 'resolved' });
    } else if (!inputChecked) {
      this.setState({ status: 'unresolved' });
    }
    this.validateTask(this.state.label, this.state.options);
  }

  handleSelectProjects = (projectsIds) => {
    const project_ids = projectsIds.map(id => parseInt(id, 10));
    this.setState({ project_ids });
    this.validateTask(this.state.label, this.state.options);
  };

  handleSubmitTask() {
    const jsonoptions = this.state.options
      ? JSON.stringify(this.state.options
        .map(item => ({ ...item, label: item.label.trim() }))
        .filter(item => item.label !== ''))
      : undefined;

    const task = {
      label: this.state.label,
      description: this.state.description,
      required: this.state.required,
      status: this.state.status,
      jsonoptions,
      json_project_ids: JSON.stringify(this.state.project_ids),
      jsonschema: this.state.jsonschema,
    };

    if (!this.state.submitDisabled) {
      this.props.onSubmit(task);
      this.setState({ submitDisabled: true });
    }
  }

  toggleAssignmentField() {
    this.setState({ showAssignmentField: !this.state.showAssignmentField });
  }

  renderOptions() {
    if (this.props.noOptions) {
      return null;
    }

    if (this.props.taskType !== 'single_choice' &&
        this.props.taskType !== 'multiple_choice') {
      return null;
    }

    const { formatMessage } = this.props.intl;

    const canRemove = this.state.options.length > 2;

    return (

        {this.state.options.map((item, index) => (
          <div key={`create-task__add-options-radiobutton-${index.toString()}`}>
            <Row>
              <ChevronRightIcon />
              <TextField
                key="create-task__add-option-input"
                className="create-task__add-option-input"
                id={index.toString()}
                onChange={this.handleEditOption.bind(this)}
                placeholder={`${formatMessage(messages.value)} ${index + 1}`}
                value={item.label}
                disabled={item.other}
                style={{ padding: `${units(0.5)} ${units(1)}`, width: '75%' }}
              />
              {canRemove ?

                : null}
            </Row>

        ))}

          <Button onClick={this.handleAddValue.bind(this)}>
            {this.props.intl.formatMessage(messages.addValue)}
          </Button>
          <Button
            onClick={this.handleAddOther.bind(this)}
            disabled={this.state.hasOther}
          >
            {this.props.intl.formatMessage(messages.addOther)}
          </Button>

    );
  }

  render() {
    const dialogTitle = this.props.task ? messages.editTask : messages.newTask;

    return (
      <Dialog
        className="create-task__dialog"
        open
        onClose={this.props.onDismiss}
        scroll="paper"
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>{this.props.intl.formatMessage(dialogTitle)}</DialogTitle>
        <DialogContent>
          <Message message={this.props.message} />

          <TextField
            id="task-label-input"
            className="tasks__task-label-input"
            label={<FormattedMessage id="tasks.taskPrompt" defaultMessage="Prompt" />}
            defaultValue={this.state.label}
            onChange={this.handleLabelChange.bind(this)}
            margin="normal"
            multiline
            fullWidth
          />
          <TextField
            id="task-description-input"
            className="create-task__task-description-input"
            label={
              <FormattedMessage id="tasks.description" defaultMessage="Description (optional)" />
            }
            defaultValue={this.state.description}
            onChange={this.handleDescriptionChange.bind(this)}
            margin="normal"
            multiline
            fullWidth
          />
          <FormattedMessage
            id="tasks.requiredCheckbox"
            defaultMessage="Required"
          />
          <Switch
            id="edit-task__required-switch"
            checked={Boolean(this.state.required)}
            onChange={this.handleSelectRequired.bind(this)}
            value="required"
            color="primary"
          />
          <HelperText>
            <FormattedMessage
              id="tasks.requiredHelper"
              defaultMessage="Items cannot be marked as completed while any of their required tasks remains unresolved"
            />
          </HelperText>

          <FormattedMessage
            id="tasks.resolvedCheckbox"
            defaultMessage="Resolved"
          />
          <Switch
            id="edit-task__resolved-switch"
            checked={this.state.status === 'resolved'}
            disabled={!this.state.resolvable}
            onChange={this.handleSelectResolved.bind(this)}
            value="resolved"
            color="primary"
          />
          <HelperText>
            <FormattedMessage
              id="tasks.resolvedHelper"
              defaultMessage="The task can only be resolved if it has been answered"
            />
          </HelperText>
          { this.props.projects ?

            : null
          }
          <ConfirmRequired
            open={this.state.confirmRequired}
            status={this.state.status}
            handleCancel={() => { this.setState({ required: false, confirmRequired: false }); }}
            handleConfirm={() => { this.setState({ confirmRequired: false }); }}
          />

          {this.renderOptions()}

          { this.props.taskType === 'free_text' ?
            <TextField
              id="task-jsonschema-input"
              className="tasks__task-jsonschema-input"
              label={<FormattedMessage id="tasks.taskJsonSchema" defaultMessage="JSON Schema (optional / advanced)" />}
              defaultValue={this.state.jsonschema}
              onChange={this.handleJsonSchemaChange.bind(this)}
              margin="normal"
              multiline
              fullWidth
            /> : null }
        </DialogContent>
        <DialogActions>
          <Button
            className="create-task__dialog-cancel-button"
            onClick={this.props.onDismiss}
          >
            <FormattedMessage id="tasks.cancelAdd" defaultMessage="Cancel" />
          </Button>
          <Button
            className="create-task__dialog-submit-button"
            onClick={this.handleSubmitTask.bind(this)}
            color="primary"
            disabled={this.state.submitDisabled}
          >
            <FormattedMessage id="tasks.add" defaultMessage="Save" />
          </Button>
        </DialogActions>
      </Dialog>
    );
  }
}

export default injectIntl(EditTaskDialog);
<|endoftext|>


<commit_before>const {
  setupBeforeEach,
  username,
  email,
  password,
  snapdev,
  templateFolderWithNoUser,
  templateFolderWithUser,
  templateSchemaDefFileWithUser,
  templateSchemaDefFileWithNoUser,
  readJSON,
  updateJSON,
} = require('./fixtures/setup');

beforeEach(async () => {
  await setupBeforeEach();
});
afterEach(async () => {});

test('snapdev push', async () => {
  let result;

   // create user
   result = await snapdev(
    `register --force --email ${email} --username ${username} --password ${password}`
  );
  expect(result.code).toBe(0);

  // login
  result = await snapdev(`login --username ${username} --password ${password}`);
  expect(result.code).toBe(0);

  // create
  result = await snapdev('create test-app');
  expect(result.code).toBe(0);

  // push
  result = await snapdev('push');
  // console.log(result);
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Pushing...`);
  expect(result.stdout).toContain(`Push Succeeded`);
});

test.only('snapdev push, schema update', async () => {
  let result;

   // create user
   result = await snapdev(
    `register --force --email ${email} --username ${username} --password ${password}`
  );
  expect(result.code).toBe(0);

  // login
  result = await snapdev(`login --username ${username} --password ${password}`);
  expect(result.code).toBe(0);

  // create
  result = await snapdev('create test-app');
  expect(result.code).toBe(0);

  // get schema content
  let schemaDef = await readJSON(templateSchemaDefFileWithUser);
  expect(schemaDef.name).toBe(`${username}/test-app`);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Pushing...`);
  expect(result.stdout).toContain(`Push Succeeded`);

  // pull template
  result = await snapdev(`reset --force`);

  // get schema content
  schemaDef = await readJSON(templateSchemaDefFileWithUser);
  expect(schemaDef.name).toBe(`${username}/test-app`);

  // change schema
  updateJSON(templateSchemaDefFileWithUser, {
    name: 'hello world'
  });

  // push again
  result = await snapdev('push --force');
  expect(result.code).toBe(0);

  // pull template
  result = await snapdev(`reset --force`);

  // get schema content
  schemaDef = await readJSON(templateSchemaDefFileWithUser);
  expect(schemaDef.name).toBe(`hello world`);

});

test('snapdev push, fail when pushing an existing version', async () => {
  let result;

   // create user
   result = await snapdev(
    `register --force --email ${email} --username ${username} --password ${password}`
  );
  expect(result.code).toBe(0);

  // login
  result = await snapdev(`login --username ${username} --password ${password}`);
  expect(result.code).toBe(0);

  // create
  result = await snapdev('create test-app');
  expect(result.code).toBe(0);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Pushing...`);
  expect(result.stdout).toContain(`Push Succeeded`);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(1);
});

test('snapdev push, success when pushing with force', async () => {
  let result;

   // create user
   result = await snapdev(
    `register --force --email ${email} --username ${username} --password ${password}`
  );
  expect(result.code).toBe(0);

  // login
  result = await snapdev(`login --username ${username} --password ${password}`);
  expect(result.code).toBe(0);

  // create
  result = await snapdev('create test-app');
  expect(result.code).toBe(0);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Pushing...`);
  expect(result.stdout).toContain(`Push Succeeded`);

  // push
  result = await snapdev('push --force');
  expect(result.code).toBe(0);

  result = await snapdev('status');
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Template name: ${username}/test-app`);
  expect(result.stdout).toContain(`Template version: 0.0.2`);

});

test('snapdev push, success when pushing a new version', async () => {
  let result;

   // create user
   result = await snapdev(
    `register --force --email ${email} --username ${username} --password ${password}`
  );
  expect(result.code).toBe(0);

  // login
  result = await snapdev(`login --username ${username} --password ${password}`);
  expect(result.code).toBe(0);

  // create
  result = await snapdev('create test-app');
  expect(result.code).toBe(0);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Pushing...`);
  expect(result.stdout).toContain(`Push Succeeded`);

  // tab --version
  result = await snapdev('tag --version 0.0.2');
  expect(result.code).toBe(0);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(0);
});

<commit_msg>Update test<commit_after>const {
  setupBeforeEach,
  username,
  email,
  password,
  snapdev,
  templateSchemaDefFileWithUser,
  readJSON,
  updateJSON,
} = require('./fixtures/setup');

beforeEach(async () => {
  await setupBeforeEach();
});
afterEach(async () => {});

test('snapdev push', async () => {
  let result;

   // create user
   result = await snapdev(
    `register --force --email ${email} --username ${username} --password ${password}`
  );
  expect(result.code).toBe(0);

  // login
  result = await snapdev(`login --username ${username} --password ${password}`);
  expect(result.code).toBe(0);

  // create
  result = await snapdev('create test-app');
  expect(result.code).toBe(0);

  // push
  result = await snapdev('push');
  // console.log(result);
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Pushing...`);
  expect(result.stdout).toContain(`Push Succeeded`);
});

test.only('snapdev push, schema update', async () => {
  let result;

   // create user
   result = await snapdev(
    `register --force --email ${email} --username ${username} --password ${password}`
  );
  expect(result.code).toBe(0);

  // login
  result = await snapdev(`login --username ${username} --password ${password}`);
  expect(result.code).toBe(0);

  // create
  result = await snapdev('create test-app');
  expect(result.code).toBe(0);

  // get schema content
  let schemaDef = await readJSON(templateSchemaDefFileWithUser);
  expect(schemaDef.name).toBe(`${username}/test-app`);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Pushing...`);
  expect(result.stdout).toContain(`Push Succeeded`);

  // pull template
  result = await snapdev(`reset --force`);

  // get schema content
  schemaDef = await readJSON(templateSchemaDefFileWithUser);
  expect(schemaDef.name).toBe(`${username}/test-app`);

  // change schema
  updateJSON(templateSchemaDefFileWithUser, {
    name: 'hello world'
  });

  // push again
  result = await snapdev('push --force');
  expect(result.code).toBe(0);

  // pull template
  result = await snapdev(`reset --force`);

  // get schema content
  schemaDef = await readJSON(templateSchemaDefFileWithUser);
  expect(schemaDef.name).toBe(`hello world`);

});

test('snapdev push, fail when pushing an existing version', async () => {
  let result;

   // create user
   result = await snapdev(
    `register --force --email ${email} --username ${username} --password ${password}`
  );
  expect(result.code).toBe(0);

  // login
  result = await snapdev(`login --username ${username} --password ${password}`);
  expect(result.code).toBe(0);

  // create
  result = await snapdev('create test-app');
  expect(result.code).toBe(0);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Pushing...`);
  expect(result.stdout).toContain(`Push Succeeded`);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(1);
});

test('snapdev push, success when pushing with force', async () => {
  let result;

   // create user
   result = await snapdev(
    `register --force --email ${email} --username ${username} --password ${password}`
  );
  expect(result.code).toBe(0);

  // login
  result = await snapdev(`login --username ${username} --password ${password}`);
  expect(result.code).toBe(0);

  // create
  result = await snapdev('create test-app');
  expect(result.code).toBe(0);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Pushing...`);
  expect(result.stdout).toContain(`Push Succeeded`);

  // push
  result = await snapdev('push --force');
  expect(result.code).toBe(0);

  result = await snapdev('status');
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Template name: ${username}/test-app`);
  expect(result.stdout).toContain(`Template version: 0.0.2`);

});

test('snapdev push, success when pushing a new version', async () => {
  let result;

   // create user
   result = await snapdev(
    `register --force --email ${email} --username ${username} --password ${password}`
  );
  expect(result.code).toBe(0);

  // login
  result = await snapdev(`login --username ${username} --password ${password}`);
  expect(result.code).toBe(0);

  // create
  result = await snapdev('create test-app');
  expect(result.code).toBe(0);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(0);
  expect(result.stdout).toContain(`Pushing...`);
  expect(result.stdout).toContain(`Push Succeeded`);

  // tab --version
  result = await snapdev('tag --version 0.0.2');
  expect(result.code).toBe(0);

  // push
  result = await snapdev('push');
  expect(result.code).toBe(0);
});

<|endoftext|>


<commit_before>export default {
  props: {
    service: {
      type: String,
      required: true
    },
    method: {
      type: String
    },
    query: {
      type: Object
    },
    queryWhen: {
      type: [ Boolean, Function ],
      default: true
    },
    // For get requests
    id: {
      type: [ Number, String ]
    },
    // If a separate query is desired to fetch data, use fetchQuery
    // The watchers will automatically be updated, so you don't have to write 'fetchQuery.propName'
    fetchQuery: {
      type: Object
    },
    watch: {
      type: Array,
      default () {
        return []
      }
    },
    immediate: {
      type: Boolean,
      default: true
    },
    local: {
      type: Boolean,
      default: false
    },
    editScope: {
      type: Function,
      default (scope) {
        return scope
      }
    }
  },
  computed: {
    findItems () {
      return this.$store.getters[`${this.service}/find`]({ query: this.query }).data
    },
    getItem () {
      const getArgs = this.getArgs(this.query)

      return this.$store.getters[`${this.service}/get`](getArgs.length === 1 ? this.id : getArgs)
    },
    items () {
      if (this.method === 'find') {
        return this.findItems
      } else if (this.method === 'get') {
        return this.getItem
      } else if (this.id !== undefined && this.id !== null) {
        return this.getItem
      } else {
        return this.findItems
      }
    }
  },
  methods: {
    getArgs (queryToUse) {
      const query = queryToUse || this.fetchQuery || this.query
      const getArgs = [this.id]

      if (query) {
        getArgs.push({ query })
      }

      return getArgs
    },
    findData () {
      const query = this.fetchQuery || this.query

      if (typeof this.queryWhen === 'function' ? this.queryWhen(this.query) : this.queryWhen) {
        return this.$store.dispatch(`${this.service}/find`, { query })
      }
    },
    getData () {
      const getArgs = this.getArgs()

      if (typeof this.queryWhen === 'function' ? this.queryWhen(...getArgs) : this.queryWhen) {
        return this.$store.dispatch(`${this.service}/get`, getArgs.length === 1 ? this.id : getArgs)
      }
    },
    fetchData () {
      if (!this.local) {
        if (this.method === 'find') {
          return this.findData()
        } else if (this.method === 'get') {
          return this.getData()
        } else if (this.id !== undefined && this.id !== null) {
          return this.getData()
        } else {
          return this.findData()
        }
      }
    }
  },
  watch: {
    id: 'fetchData'
  },
  created () {
    if (!this.$FeathersVuex) {
      throw new Error(`You must first Vue.use the FeathersVuex plugin before using the 'feathers-vuex-data' component.`)
    }
    if (!this.$store.state[this.service]) {
      throw new Error(`The '${this.service}' plugin cannot be found. Did you register the service with feathers-vuex?`)
    }

    if (this.fetchQuery || this.query || (this.id !== null && this.id !== undefined)) {
      this.watch.forEach(prop => {
        if (typeof prop !== 'string') {
          throw new Error(`Values in the 'watch' array must be strings.`)
        }
        if (this.fetchQuery) {
          if (prop.startsWith('query')) {
            prop.replace('query', 'fetchQuery')
          }
        }
        this.$watch(prop, this.fetchData)
      })

      if (this.immediate) {
        this.fetchData()
      }
    }
  },
  render () {
    const defaultScope = { items: this.items }
    const scope = this.editScope(defaultScope)

    return this.$scopedSlots.default(scope || defaultScope)
  }
}
<commit_msg>isFindPending, isGetPending now in component scope<commit_after>export default {
  props: {
    service: {
      type: String,
      required: true
    },
    method: {
      type: String
    },
    query: {
      type: Object
    },
    queryWhen: {
      type: [ Boolean, Function ],
      default: true
    },
    // For get requests
    id: {
      type: [ Number, String ]
    },
    // If a separate query is desired to fetch data, use fetchQuery
    // The watchers will automatically be updated, so you don't have to write 'fetchQuery.propName'
    fetchQuery: {
      type: Object
    },
    watch: {
      type: Array,
      default () {
        return []
      }
    },
    immediate: {
      type: Boolean,
      default: true
    },
    local: {
      type: Boolean,
      default: false
    },
    editScope: {
      type: Function,
      default (scope) {
        return scope
      }
    }
  },
  data: () => ({
    isFindPending: false,
    isGetPending: false
  }),
  computed: {
    findItems () {
      return this.$store.getters[`${this.service}/find`]({ query: this.query }).data
    },
    getItem () {
      const getArgs = this.getArgs(this.query)

      return this.$store.getters[`${this.service}/get`](getArgs.length === 1 ? this.id : getArgs)
    },
    items () {
      if (this.method === 'find') {
        return this.findItems
      } else if (this.method === 'get') {
        return this.getItem
      } else if (this.id !== undefined && this.id !== null) {
        return this.getItem
      } else {
        return this.findItems
      }
    }
  },
  methods: {
    getArgs (queryToUse) {
      const query = queryToUse || this.fetchQuery || this.query
      const getArgs = [this.id]

      if (query) {
        getArgs.push({ query })
      }

      return getArgs
    },
    findData () {
      const query = this.fetchQuery || this.query

      if (typeof this.queryWhen === 'function' ? this.queryWhen(this.query) : this.queryWhen) {
        this.isFindPending = true

        return this.$store.dispatch(`${this.service}/find`, { query })
          .then(() => {
            this.isFindPending = false
          })
      }
    },
    getData () {
      const getArgs = this.getArgs()

      if (typeof this.queryWhen === 'function' ? this.queryWhen(...getArgs) : this.queryWhen) {
        this.isGetPending = true

        return this.$store.dispatch(`${this.service}/get`, getArgs.length === 1 ? this.id : getArgs)
          .then(() => {
            this.isGetPending = false
          })
      }
    },
    fetchData () {
      if (!this.local) {
        if (this.method === 'find') {
          return this.findData()
        } else if (this.method === 'get') {
          return this.getData()
        } else if (this.id !== undefined && this.id !== null) {
          return this.getData()
        } else {
          return this.findData()
        }
      }
    }
  },
  watch: {
    id: 'fetchData'
  },
  created () {
    if (!this.$FeathersVuex) {
      throw new Error(`You must first Vue.use the FeathersVuex plugin before using the 'feathers-vuex-data' component.`)
    }
    if (!this.$store.state[this.service]) {
      throw new Error(`The '${this.service}' plugin cannot be found. Did you register the service with feathers-vuex?`)
    }

    if (this.fetchQuery || this.query || (this.id !== null && this.id !== undefined)) {
      this.watch.forEach(prop => {
        if (typeof prop !== 'string') {
          throw new Error(`Values in the 'watch' array must be strings.`)
        }
        if (this.fetchQuery) {
          if (prop.startsWith('query')) {
            prop.replace('query', 'fetchQuery')
          }
        }
        this.$watch(prop, this.fetchData)
      })

      if (this.immediate) {
        this.fetchData()
      }
    }
  },
  render () {
    const { items, isFindPending, isGetPending } = this
    const defaultScope = { items, isFindPending, isGetPending }
    const scope = this.editScope(defaultScope)

    return this.$scopedSlots.default(scope || defaultScope)
  }
}
<|endoftext|>


<commit_before>Ext.define('TM.view.task.Search', {
	extend: 'Ext.form.Panel',
	xtype: 'task_search',

	border: 0,
  bodyPadding: '5 5 0',

  items: [{
    xtype: 'fieldset',
    id: 'fieldset',
    title: '查询',

    layout: {
      type: 'form',
      border: 0,
      margin: 2
    },
    items: [{
      border: 0,
      items: [{
        layout: 'column',
        border: 0,
        defaults: {
          xtype: 'textfield',
          id: 'textfield',
          labelAlign: 'right',
          width: 300,
          labelWidth: 130
        },
        items: [{
          fieldLabel: '名称',
          name: 'q[name_cont]'
        }, {
          fieldLabel: '周期',
          editable: false,
          xtype: 'combo',
          id: 'types',
          store: 'TM.store.Types',
          valueField: 'value',
          name: 'q[task_type_eq]'
        }, {
          fieldLabel: '状态',
          xtype: 'combo',
          editable: false,
          valueField: 'value',
          store: 'TM.store.Statuses',
          name: 'q[status_eq]'
        }]
      }, {
        layout: 'column',
        border: 0,
        defaults: {
          border: 0,
          labelAlign: 'right',
          width: 300,
          labelWidth: 130
        },
        items: [{
          layout: 'column',
          border: 0,
          defaults: {
            xtype: 'datefield',
            id: 'datefield',
            labelAlign: 'right',
            width: 300,
            labelWidth: 130
          },
          items: [{
            fieldLabel: '完成时间 从',
            format: 'Y-m-d',
            editable: false,
            name: 'q[finished_at_gteq]',
            id: 'last_task'
          }, {
            fieldLabel: '截止时间 从',
            format: 'Y-m-d',
            xtype: 'datefield',
            editable: false,
            name: 'q[deadline_gteq]'
          }]
        }, {
          layout: 'column',
          border: 0,
          defaults: {
            xtype: 'datefield',
            labelAlign: 'right',
            width: 300,
            labelWidth: 130
          },
          items: [{
            fieldLabel: '至',
            format: 'Y-m-d',
            editable: false,
            name: 'q[finished_at_lteq]'
          }, {
            fieldLabel: '至',
            format: 'Y-m-d',
            xtype: 'datefield',
            editable: false,
            name: 'q[deadline_lteq]'
          }]
        }, {
          layout: 'hbox',
          margin: '20 0 0 60',
          items: [{
            xtype: 'button',
            formBind: true,
            width: 60,
            text: '查询',
            action: 'query'
          }, {
            xtype: 'button',
            margin: '0 0 0 20',
            width: 60,
            text: '重置',
            action: 'reset'
          }]
        }]
      }],
    }]
  }],

  // buttons: [{
  //   formBind: true,
  //   width: 60,
  //   text: '查询',
  //   action: 'query'
  // }, {
  //   margin: '0 0 0 20',
  //   width: 60,
  //   text: '重置',
  //   action: 'reset'
  // }],

  hasQueryParams: function() {
    var hasParams = false;
    Ext.Object.each(this.getValues(), function(key, value) {
      if(value) {
       hasParams = true;

       // Break each
       return false;
      }
    });

    return hasParams;
  }
});
<commit_msg>Fixed #298<commit_after>Ext.define('TM.view.task.Search', {
	extend: 'Ext.form.Panel',
	xtype: 'task_search',

	border: 0,
  bodyPadding: '5 5 0',

  items: [{
    xtype: 'fieldset',
    id: 'fieldset',
    title: '查询',

    layout: {
      type: 'form',
      border: 0,
      margin: 2
    },
    items: [{
      border: 0,
      items: [{
        layout: 'column',
        border: 0,
        defaults: {
          xtype: 'textfield',
          labelAlign: 'right',
          width: 300,
          labelWidth: 130
        },
        items: [{
          fieldLabel: '名称',
          name: 'q[name_cont]'
        }, {
          fieldLabel: '周期',
          editable: false,
          xtype: 'combo',
          id: 'types',
          store: 'TM.store.Types',
          valueField: 'value',
          name: 'q[task_type_eq]'
        }, {
          fieldLabel: '状态',
          xtype: 'combo',
          editable: false,
          valueField: 'value',
          store: 'TM.store.Statuses',
          name: 'q[status_eq]'
        }]
      }, {
        layout: 'column',
        border: 0,
        defaults: {
          border: 0,
          labelAlign: 'right',
          width: 300,
          labelWidth: 130
        },
        items: [{
          layout: 'column',
          border: 0,
          defaults: {
            xtype: 'datefield',
            id: 'datefield',
            labelAlign: 'right',
            width: 300,
            labelWidth: 130
          },
          items: [{
            fieldLabel: '完成时间 从',
            format: 'Y-m-d',
            editable: false,
            name: 'q[finished_at_gteq]',
            id: 'last_task'
          }, {
            fieldLabel: '截止时间 从',
            format: 'Y-m-d',
            xtype: 'datefield',
            editable: false,
            name: 'q[deadline_gteq]'
          }]
        }, {
          layout: 'column',
          border: 0,
          defaults: {
            xtype: 'datefield',
            labelAlign: 'right',
            width: 300,
            labelWidth: 130
          },
          items: [{
            fieldLabel: '至',
            format: 'Y-m-d',
            editable: false,
            name: 'q[finished_at_lteq]'
          }, {
            fieldLabel: '至',
            format: 'Y-m-d',
            xtype: 'datefield',
            editable: false,
            name: 'q[deadline_lteq]'
          }]
        }, {
          layout: 'hbox',
          margin: '20 0 0 60',
          items: [{
            xtype: 'button',
            formBind: true,
            width: 60,
            text: '查询',
            action: 'query'
          }, {
            xtype: 'button',
            margin: '0 0 0 20',
            width: 60,
            text: '重置',
            action: 'reset'
          }]
        }]
      }],
    }]
  }],

  // buttons: [{
  //   formBind: true,
  //   width: 60,
  //   text: '查询',
  //   action: 'query'
  // }, {
  //   margin: '0 0 0 20',
  //   width: 60,
  //   text: '重置',
  //   action: 'reset'
  // }],

  hasQueryParams: function() {
    var hasParams = false;
    Ext.Object.each(this.getValues(), function(key, value) {
      if(value) {
       hasParams = true;

       // Break each
       return false;
      }
    });

    return hasParams;
  }
});<|endoftext|>


<commit_before>if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match
                ;
        });
    };
}

toggle_button_loading_text = function($element){
    var btnText = $element.data('loading-text');
    $element
        .data('loading-text', $element.text())
        .data('loading-text', btnText)
    ;
};

$(function() {
    $('#sidebar-wrapper').slimscroll({
        height: '100%',
        width: '500px',
        position: 'right',
        alwaysVisible: true,
        color: '#73715e'
    });

    $('[data-toggle="tooltip"]').tooltip();

    $('select')
        .select2({
            placeholder: "Select a state",
            allowClear: true,
            width: '170px'
        })
        .change(function(e){
            var $target = $(e.target);
            var $img = $target.parents('.row:first').find('img');

            $img.attr('src', $target.children('option:selected').data('photo'));
        });

    $('.event-list>li').click(function(e){
        var $target = $(this);

        $('.background-image').css('background-image', "url('" + $target.data('background') + "')");
        $('#race-title').html($target.data('title'));
        $('input[name="stage"]').val($target.data('slug'));
    });

    $('*[data-event="ajaxRequest"]').click(function(e){
        e.preventDefault();

        var $target = $(e.target);
        var $container = $($target.data('container'));
        var $resultContainer = $($target.data('result-container'));
        var $form = $($target).parents('form:first');

        $.ajax({
            async: true,
            type: $form.attr('method'),
            url: decodeURI($form.attr('action')).format($('input[name="stage"]').val()),
            data: $form.serialize(),
            beforeSend: function(){
                toggle_button_loading_text($target);
            },
            success: function(data){
                if (data.status === "ok") {
                    $container.show();
                    $resultContainer.html(data.view);

                    toggle_button_loading_text($target);
                }
            }
        });
    });
});<commit_msg>quick js fix<commit_after>if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match
                ;
        });
    };
}

toggle_button_loading_text = function($element){
    var btnText = $element.data('loading-text');
    $element
        .data('loading-text', $element.text())
        .text(btnText)
    ;
};

$(function() {
    $('#sidebar-wrapper').slimscroll({
        height: '100%',
        width: '500px',
        position: 'right',
        alwaysVisible: true,
        color: '#73715e'
    });

    $('[data-toggle="tooltip"]').tooltip();

    $('select')
        .select2({
            placeholder: "Select a state",
            allowClear: true,
            width: '170px'
        })
        .change(function(e){
            var $target = $(e.target);
            var $img = $target.parents('.row:first').find('img');

            $img.attr('src', $target.children('option:selected').data('photo'));
        });

    $('.event-list>li').click(function(e){
        var $target = $(this);

        $('.background-image').css('background-image', "url('" + $target.data('background') + "')");
        $('#race-title').html($target.data('title'));
        $('input[name="stage"]').val($target.data('slug'));
    });

    $('*[data-event="ajaxRequest"]').click(function(e){
        e.preventDefault();

        var $target = $(e.target);
        var $container = $($target.data('container'));
        var $resultContainer = $($target.data('result-container'));
        var $form = $($target).parents('form:first');

        $.ajax({
            async: true,
            type: $form.attr('method'),
            url: decodeURI($form.attr('action')).format($('input[name="stage"]').val()),
            data: $form.serialize(),
            beforeSend: function(){
                toggle_button_loading_text($target);
            },
            success: function(data){
                if (data.status === "ok") {
                    $container.show();
                    $resultContainer.html(data.view);

                    toggle_button_loading_text($target);
                }
            }
        });
    });
});<|endoftext|>


<commit_before>import React from 'react';
import { oneOf, node, bool, string } from 'prop-types';
import fieldPropTypes from '../fieldPropTypes';
import defaultFieldPropTypes from '../defaultFieldPropTypes';
import { FieldWrapper, FieldInput } from './styled';
import Icon from '../Icon';
import Text from '../Text';

const propTypes = {
    ...fieldPropTypes,
    type: oneOf(['email', 'text', 'password', 'number', 'url']).isRequired,
    label: node,
    required: bool,
    className: string,
};

const defaultProps = {
    ...defaultFieldPropTypes,
    type: undefined,
    label: undefined,
    required: undefined,
    className: undefined,
};

const InputField = ({ input, meta, type, label, required, className }) => {
    const { touched, error, warning, form } = meta;
    const hasError = (touched && error);
    const hasWarning = (touched && warning);
    const id = `${form}-${input.name}`;
    return (
        <FieldWrapper className={className}>
            {label &&
                <Text.Label htmlFor={id}>{label} {required && <Text.Span color="error">*</Text.Span>}</Text.Label>}
            <FieldInput id={id} type={type} {...input} />
            {hasError &&
                <Text.Span color="error" scale="s"><Icon color="error" scale="s">clear</Icon> {error}</Text.Span>}
            {hasWarning &&
                <Text.Span color="warning" scale="s"><Icon color="warning" scale="s">warning</Icon> {warning}</Text.Span>}
        </FieldWrapper>
    );
};

InputField.propTypes = propTypes;
InputField.defaultProps = defaultProps;

export default InputField;
<commit_msg>added onClick handler to InputField Component<commit_after>import React from 'react';
import { oneOf, node, bool, string, func } from 'prop-types';
import fieldPropTypes from '../fieldPropTypes';
import defaultFieldPropTypes from '../defaultFieldPropTypes';
import { FieldWrapper, FieldInput } from './styled';
import Icon from '../Icon';
import Text from '../Text';

const propTypes = {
    ...fieldPropTypes,
    type: oneOf(['email', 'text', 'password', 'number', 'url']).isRequired,
    label: node,
    required: bool,
    className: string,
    onClick: func,
};

const defaultProps = {
    ...defaultFieldPropTypes,
    type: undefined,
    label: undefined,
    required: undefined,
    className: undefined,
    onClick: undefined,
};

const InputField = ({ input, meta, type, label, required, className, onClick }) => {
    const { touched, error, warning, form } = meta;
    const hasError = (touched && error);
    const hasWarning = (touched && warning);
    const id = `${form}-${input.name}`;
    return (
        <FieldWrapper className={className}>
            {label &&
                <Text.Label htmlFor={id}>{label} {required && <Text.Span color="error">*</Text.Span>}</Text.Label>}
            <FieldInput id={id} type={type} {...input} onClick={onClick} />
            {hasError &&
                <Text.Span color="error" scale="s"><Icon color="error" scale="s">clear</Icon> {error}</Text.Span>}
            {hasWarning &&
                <Text.Span color="warning" scale="s"><Icon color="warning" scale="s">warning</Icon> {warning}</Text.Span>}
        </FieldWrapper>
    );
};

InputField.propTypes = propTypes;
InputField.defaultProps = defaultProps;

export default InputField;
<|endoftext|>