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

  /*POLICY OUTPUTS CONTROLLER*/
  angular
    .module('webApp')
    .controller('PolicyOutputCtrl', PolicyOutputCtrl);

  PolicyOutputCtrl.$inject = ['FragmentFactory', 'PolicyModelFactory', '$q', 'PolicyStaticDataFactory'];

  function PolicyOutputCtrl(FragmentFactory, PolicyModelFactory, $q, PolicyStaticDataFactory) {
    var vm = this;
    vm.checkOutputs = checkOutputs;
    vm.checkSelected = checkSelected;
    vm.formSubmmited = false;
    vm.error = false;
    vm.outputList = [];
    init();

    ////////////////////////////////////

    function init() {
      vm.helpLink = PolicyStaticDataFactory.helpLinks.outputs;

      var defer = $q.defer();
      vm.policy = PolicyModelFactory.GetCurrentPolicy();

      var outputList = FragmentFactory.GetFragments("output");
      outputList.then(function (result) {
        vm.outputList = result;
        defer.resolve();
      }, function () {
        defer.reject();
      });
      return defer.promise;

    }

    function checkSelected() {
      var outputsSelected = checkOutputsSelected();

      vm.error = (outputsSelected>0)? false : true;
    }

    function checkOutputs() {
      vm.formSubmmited = true;
      var outputsSelected = checkOutputsSelected();

      if (outputsSelected > 0) {
        vm.error = false;
        PolicyModelFactory.NextStep();
      }
      else {
        vm.error = true;
      }
    };

    function checkOutputsSelected() {
      var outputsCount = 0;
      var outputsLength = vm.policy.outputs.length;

      for (var i = outputsLength-1; i>=0; i--) {
        if (vm.policy.outputs[i]) {
          outputsCount++;
        }
      }
      return outputsCount;
    };

  }
})();
<commit_msg>feature(wizard-outputs): change controller funcionality<commit_after>(function () {
  'use strict';

  /*POLICY OUTPUTS CONTROLLER*/
  angular
    .module('webApp')
    .controller('PolicyOutputCtrl', PolicyOutputCtrl);

  PolicyOutputCtrl.$inject = ['FragmentFactory', 'PolicyModelFactory', '$q', 'PolicyStaticDataFactory'];

  function PolicyOutputCtrl(FragmentFactory, PolicyModelFactory, $q, PolicyStaticDataFactory) {
    var vm = this;
    vm.setOutput = setOutput;
    vm.validateForm = validateForm;

    vm.formSubmmited = false;
    vm.error = false;
    vm.outputList = [];
    init();

    ////////////////////////////////////

    function init() {
      vm.helpLink = PolicyStaticDataFactory.helpLinks.outputs;

      var defer = $q.defer();
      vm.policy = PolicyModelFactory.GetCurrentPolicy();

      var outputList = FragmentFactory.GetFragments("output");
      outputList.then(function (result) {
        vm.outputList = result;
        defer.resolve();
      }, function () {
        defer.reject();
      });
      return defer.promise;

    }

    function setOutput(index) {
      if (vm.policy.outputs[index]) {
        vm.policy.outputs[index] = null;
      }
      else {
        vm.policy.outputs[index] = vm.outputList[index];
      }

      var outputsSelected = checkOutputsSelected();
      vm.error = (outputsSelected>0)? false : true;
    };

    function validateForm() {
      vm.formSubmmited = true;
      var outputsSelected = checkOutputsSelected();

      if (outputsSelected > 0) {
        vm.error = false;
        PolicyModelFactory.NextStep();
      }
      else {
        vm.error = true;
      }
    }

    function checkOutputsSelected() {
      var outputsCount = 0;
      var outputsLength = vm.policy.outputs.length;

      for (var i = outputsLength-1; i>=0; i--) {
        if (vm.policy.outputs[i]) {
          outputsCount++;
        }
      }
      return outputsCount;
    };
  }
})();
<|endoftext|>


<commit_before>if (Meteor.isServer) {
  Meteor.methods({
    // call giblet methods to run the giblet jobs
    runGiblet: function ( gibletID ) {
      var giblet = Giblets.findOne({_id: gibletID});
      var urlArray = giblet.url;
      urlArray.forEach( function ( url ) {
        console.log("each url in array", url);
        if (url) {
          var webpageText = scrapePage(url);
          if (webpageText = '') {
            return;
          }
          var hash = hashText(webpageText);
          var pageHasChanged = compareHash(giblet, url, hash);
          if (pageHasChanged) {
            var newKeywordCounts = findKeywords(giblet.keywords, webpageText);
            var keywordDiffs = compareKeywordCounts(giblet, url, newKeywordCounts);
            if (keywordDiffs.length) {
              Meteor.call('createNotification', giblet, url, keywordDiffs);
            }
            Meteor.call('updateWebData', giblet, url, hash, newKeywordCounts);
          }
        }
      });
    },

    // update the database with the updated webpage data
    updateWebData: function ( giblet, url, hash, keywordObj ) {
      var updatedUrlObj = {
        url: url,
        hash: hash,
        keywordCounts: keywordObj
      };
      var webDataCopy = giblet.webData;
      var urlProp = removeDots(url);
      webDataCopy[urlProp] = updatedUrlObj;
      Giblets.update({_id: giblet._id}, {$set: { webData: webDataCopy }});
    },

    createNotification: function ( giblet, url, notificationKeys) {
      Notifications.insert({
        createdAt: new Date(),
        owner: giblet.owner,
        gibletID: giblet._id,
        keywords: notificationKeys,
        url: url
      });
    }
  });
}

/*
 * Scraping helper functions
 */

// remove dots from urls in order to store url strings as properties
function removeDots ( url ) {
  var dots = /\./g;
  return url.replace(/\./g, '');
}

// get all text from a url
function scrapePage ( url ) {
  var webpage = Scrape.url(url);
  if (webpage) {
    var $ = cheerio.load(webpage);
    $('script').remove();
    var webpageText = $('body').text().replace(/\n/g, ' ').replace(/\t/g, ' ').replace('  ', ' ');
  }
  return webpageText || '';
}

// hash the page text for constant time checking for updates
function hashText ( pageText ) {
  return CryptoJS.SHA1(pageText).toString();
}

// compare the current webpage hash to the previous webpage hash
function compareHash ( giblet, url, newHash ) {
  var urlProp = removeDots(url);
  return ( !giblet.webData[urlProp] || giblet.webData[urlProp].hash !== newHash );
}

// get the keyword count
function findKeywords ( keywordsArray, pageText ) {
  var cleanTags = Tags.clean( keywordsArray );
  // convert tags to case-insensitive regular expressions
  var tagRegexArr = [];
  cleanTags.forEach( function(tag) {
    tagRegexArr.push(new RegExp(tag, 'gi'));
  });

  var foundKeywords = [];
  tagRegexArr.forEach( function(tagRegex) {
    var matchingArr = pageText.match(tagRegex);
    foundKeywords.push(matchingArr);
  });

  var keywordsObj = {}
  foundKeywords.forEach(function(array) {
    if (array) {
      keywordsObj[array[0]] = array.length;
    }
  });

  return keywordsObj;
}

// compare the keyword count
function compareKeywordCounts ( giblet, url, newKeywordCounts ) {
  var urlProp = removeDots(url);
  var oldKeywordCounts = {};
  if (giblet.webData[urlProp]) {
    oldKeywordCounts = giblet.webData[urlProp].keywordCounts;
  }
  var keywordDiffs = [];
  for (var key in newKeywordCounts) {
    if ( !(key in oldKeywordCounts) || newKeywordCounts[key] > oldKeywordCounts[key] ) {
      keywordDiffs.push(key);
    }
  }
  return keywordDiffs;
}
<commit_msg>removes redundent create notifications function<commit_after>if (Meteor.isServer) {
  Meteor.methods({
    // call giblet methods to run the giblet jobs
    runGiblet: function ( gibletID ) {
      var giblet = Giblets.findOne({_id: gibletID});
      var urlArray = giblet.url;
      urlArray.forEach( function ( url ) {
        console.log("each url in array", url);
        if (url) {
          var webpageText = scrapePage(url);
          if (webpageText = '') {
            return;
          }
          var hash = hashText(webpageText);
          var pageHasChanged = compareHash(giblet, url, hash);
          if (pageHasChanged) {
            var newKeywordCounts = findKeywords(giblet.keywords, webpageText);
            var keywordDiffs = compareKeywordCounts(giblet, url, newKeywordCounts);
            if (keywordDiffs.length) {
              Meteor.call('createNotification', giblet, url, keywordDiffs);
            }
            Meteor.call('updateWebData', giblet, url, hash, newKeywordCounts);
          }
        }
      });
    },

    // update the database with the updated webpage data
    updateWebData: function ( giblet, url, hash, keywordObj ) {
      var updatedUrlObj = {
        url: url,
        hash: hash,
        keywordCounts: keywordObj
      };
      var webDataCopy = giblet.webData;
      var urlProp = removeDots(url);
      webDataCopy[urlProp] = updatedUrlObj;
      Giblets.update({_id: giblet._id}, {$set: { webData: webDataCopy }});
    }
  });
}

/*
 * Scraping helper functions
 */

// remove dots from urls in order to store url strings as properties
function removeDots ( url ) {
  var dots = /\./g;
  return url.replace(/\./g, '');
}

// get all text from a url
function scrapePage ( url ) {
  var webpage = Scrape.url(url);
  if (webpage) {
    var $ = cheerio.load(webpage);
    $('script').remove();
    var webpageText = $('body').text().replace(/\n/g, ' ').replace(/\t/g, ' ').replace('  ', ' ');
  }
  return webpageText || '';
}

// hash the page text for constant time checking for updates
function hashText ( pageText ) {
  return CryptoJS.SHA1(pageText).toString();
}

// compare the current webpage hash to the previous webpage hash
function compareHash ( giblet, url, newHash ) {
  var urlProp = removeDots(url);
  return ( !giblet.webData[urlProp] || giblet.webData[urlProp].hash !== newHash );
}

// get the keyword count
function findKeywords ( keywordsArray, pageText ) {
  var cleanTags = Tags.clean( keywordsArray );
  // convert tags to case-insensitive regular expressions
  var tagRegexArr = [];
  cleanTags.forEach( function(tag) {
    tagRegexArr.push(new RegExp(tag, 'gi'));
  });

  var foundKeywords = [];
  tagRegexArr.forEach( function(tagRegex) {
    var matchingArr = pageText.match(tagRegex);
    foundKeywords.push(matchingArr);
  });

  var keywordsObj = {}
  foundKeywords.forEach(function(array) {
    if (array) {
      keywordsObj[array[0]] = array.length;
    }
  });

  return keywordsObj;
}

// compare the keyword count
function compareKeywordCounts ( giblet, url, newKeywordCounts ) {
  var urlProp = removeDots(url);
  var oldKeywordCounts = {};
  if (giblet.webData[urlProp]) {
    oldKeywordCounts = giblet.webData[urlProp].keywordCounts;
  }
  var keywordDiffs = [];
  for (var key in newKeywordCounts) {
    if ( !(key in oldKeywordCounts) || newKeywordCounts[key] > oldKeywordCounts[key] ) {
      keywordDiffs.push(key);
    }
  }
  return keywordDiffs;
}
<|endoftext|>


<commit_before>/**
 * AuthController
 *
 * @module      :: Controller
 * @description :: A set of functions called `actions`.
 *
 *                 Actions contain code telling Sails how to respond to a certain type of request.
 *                 (i.e. do stuff, then send some JSON, show an HTML page, or redirect to another URL)
 *
 *                 You can configure the blueprint URLs which trigger these actions (`config/controllers.js`)
 *                 and/or override them with custom routes (`config/routes.js`)
 *
 *                 NOTE: The code you write here supports both HTTP and Socket.io automatically.
 *
 * @docs        :: http://sailsjs.org/#!documentation/controllers
 */

var passport = require('passport');

module.exports = {

    //GET (login page)
    index: function(req, res) {
        res.view();
    },

    //GET + POST
    signup: function(req, res) {
        if (req.method === "GET") {
            res.view("auth/signup");
        }
        // sign-up POST.
        // Creates a userprofile bases on username/password
        // redirects on success.
        //
        // TODO: deprecate in favor of user.create
        // which is called through ajax. Then we can redirect on client
        else if (req.method === "POST") {

            req.body = req.body || {};
            req.body.provider = "local";

            User.create(req.body).exec(function(err, result) {
                if (err) {
                    req.flash('message', JSON.stringify(err));
                    return res.redirect('/signup');
                }
                //login after signup
                req.logIn(result, function(err) {
                    if (err) return next(err);
                    res.redirect('/');
                });
            });
        } else {
            res.send(405);
        }
    },

    //GET
    logout: function(req, res) {
        req.logout();
        req.flash('message', "Successfully logged out");
        res.redirect('/');
    },

    //adapted from: http://jethrokuan.github.io/2013/12/19/Using-Passport-With-Sails-JS.html
    local: function(req, res) {
        if (req.method === "POST") {
            passport.authenticate('local', function(err, user, info) {
                if ((err) || (!user)) {
                    req.flash('message', info.message);
                    res.redirect('/login');
                    return;
                }
                req.logIn(user, function(err) {
                    if (err) res.redirect('/login');
                    return res.redirect('/');
                });
            })(req, res);
        } else {
            res.send(405); //Method Not Allowed
        }
    },

    // http://developer.github.com/v3/
    // http://developer.github.com/v3/oauth/#scopes
    github: function(req, res) {
        passport.authenticate('github', {
                failureRedirect: '/login'
            },
            function(err, user) {
                req.logIn(user, function(err) {
                    if (err) {
                        console.log(err);
                        res.view('500');
                        return;
                    }

                    res.redirect('/');
                    return;
                });
            })(req, res);
    },

    // https://developers.facebook.com/docs/
    // https://developers.facebook.com/docs/reference/login/
    facebook: function(req, res) {
        passport.authenticate('facebook', {
                failureRedirect: '/login',
                scope: ['email']
            },
            function(err, user) {
                req.logIn(user, function(err) {
                    if (err) {
                        console.log(err);
                        res.view('500');
                        return;
                    }

                    res.redirect('/');
                    return;
                });
            })(req, res);
    },

    // https://developers.google.com/
    // https://developers.google.com/accounts/docs/OAuth2Login#scope-param
    google: function(req, res) {
        passport.authenticate('google', {
                failureRedirect: '/login',
                scope: ['https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email']
            },
            function(err, user) {
                req.logIn(user, function(err) {
                    if (err) {
                        console.log(err);
                        res.view('500');
                        return;
                    }

                    res.redirect('/');
                    return;
                });
            })(req, res);
    },

    /**
     * Overrides for the settings in `config/controllers.js`
     * (specific to AuthController)
     */
    //DON'T LIKE EXPOSING THIS, BUT OTHERWISE ALL THOSE SOCIAL CALLBASKS NEED TO
    //BE EPLXICILT DEFINED IN ROUTES.
    //FOR NOW THERE'S ONLY A COUPLE OF METHODS THAT NEED TO BE CLOSED
    //(I.E.: THOSE THAT ARE MEANS FOR NON-GETS)
    // _config: {
    //     blueprints: {
    //         actions: false //don't allow ALL VERBS per controller action
    //     }
    // }
    //

    _config: {
        blueprints: {
            actions: true //allow ALL verbs per controller action. We make use manually only allowed sutff is exposed.
        }
    }

};<commit_msg>signup cleanup<commit_after>/**
 * AuthController
 *
 * @module      :: Controller
 * @description :: A set of functions called `actions`.
 *
 *                 Actions contain code telling Sails how to respond to a certain type of request.
 *                 (i.e. do stuff, then send some JSON, show an HTML page, or redirect to another URL)
 *
 *                 You can configure the blueprint URLs which trigger these actions (`config/controllers.js`)
 *                 and/or override them with custom routes (`config/routes.js`)
 *
 *                 NOTE: The code you write here supports both HTTP and Socket.io automatically.
 *
 * @docs        :: http://sailsjs.org/#!documentation/controllers
 */

var passport = require('passport');

module.exports = {

    //GET (login page)
    index: function(req, res) {
        res.view();
    },

    //GET + POST
    signup: function(req, res) {
        if (req.method === "GET") {
            res.view("auth/signup");
        }
        // sign-up POST.
        // Creates a userprofile bases on username/password
        // redirects on success.
        //
        // TODO: deprecate in favor of user.create
        // which is called through ajax. Then we can redirect on client
        else if (req.method === "POST") {

            req.body = req.body || {};
            req.body.provider = "local";

            User.create(req.body).exec(function(err, result) {
                if (err) {
                    req.flash('message', JSON.stringify(err));
                    return res.redirect('/signup');
                }
                //login after signup
                req.logIn(result, function(err) {
                    if (err) return next(err);
                    res.redirect('/');
                });
            });
        } else {
            res.send(405);
        }
    },

    //GET
    logout: function(req, res) {
        req.logout();
        req.flash('message', "Successfully logged out");
        res.redirect('/login');
    },

    //adapted from: http://jethrokuan.github.io/2013/12/19/Using-Passport-With-Sails-JS.html
    local: function(req, res) {
        if (req.method === "POST") {
            passport.authenticate('local', function(err, user, info) {
                if ((err) || (!user)) {
                    req.flash('message', info.message);
                    res.redirect('/login');
                    return;
                }
                req.logIn(user, function(err) {
                    if (err) res.redirect('/login');
                    return res.redirect('/');
                });
            })(req, res);
        } else {
            res.send(405); //Method Not Allowed
        }
    },

    // http://developer.github.com/v3/
    // http://developer.github.com/v3/oauth/#scopes
    github: function(req, res) {
        passport.authenticate('github', {
                failureRedirect: '/login'
            },
            function(err, user) {
                req.logIn(user, function(err) {
                    if (err) {
                        console.log(err);
                        res.view('500');
                        return;
                    }

                    res.redirect('/');
                    return;
                });
            })(req, res);
    },

    // https://developers.facebook.com/docs/
    // https://developers.facebook.com/docs/reference/login/
    facebook: function(req, res) {
        passport.authenticate('facebook', {
                failureRedirect: '/login',
                scope: ['email']
            },
            function(err, user) {
                req.logIn(user, function(err) {
                    if (err) {
                        console.log(err);
                        res.view('500');
                        return;
                    }

                    res.redirect('/');
                    return;
                });
            })(req, res);
    },

    // https://developers.google.com/
    // https://developers.google.com/accounts/docs/OAuth2Login#scope-param
    google: function(req, res) {
        passport.authenticate('google', {
                failureRedirect: '/login',
                scope: ['https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email']
            },
            function(err, user) {
                req.logIn(user, function(err) {
                    if (err) {
                        console.log(err);
                        res.view('500');
                        return;
                    }

                    res.redirect('/');
                    return;
                });
            })(req, res);
    },

    /**
     * Overrides for the settings in `config/controllers.js`
     * (specific to AuthController)
     */
    //DON'T LIKE EXPOSING THIS, BUT OTHERWISE ALL THOSE SOCIAL CALLBASKS NEED TO
    //BE EPLXICILT DEFINED IN ROUTES.
    //FOR NOW THERE'S ONLY A COUPLE OF METHODS THAT NEED TO BE CLOSED
    //(I.E.: THOSE THAT ARE MEANS FOR NON-GETS)
    // _config: {
    //     blueprints: {
    //         actions: false //don't allow ALL VERBS per controller action
    //     }
    // }
    //

    _config: {
        blueprints: {
            actions: true //allow ALL verbs per controller action. We make use manually only allowed sutff is exposed.
        }
    }

};<|endoftext|>


<commit_before>const should = require('chai').should();

const utils = require('./goo.utils');

describe('deepCopy', () => {
    const deepCopy = utils.deepCopy;

    it('should copy an object', () => {
        let obj = {};
        deepCopy(obj).should.not.equal(obj);
    });

    it('should not mutate inputs', () => {
        let obj = {a: 1};
        let wrapper = {b: obj};
        deepCopy(wrapper);
        wrapper.b.should.equal(obj);
    });

    it('should deep copy an object', () => {
        let obj = {a: 1};
        deepCopy({b: obj}).b.should.not.equal(obj);
    });

    it('should copy strings', () => {
        deepCopy('a').should.equal('a');
    });

    it('should copy numbers', () => {
        deepCopy(1).should.equal(1);
    });

    it('should copy arrays', () => {
        let arr = [1, 2, 3];
        deepCopy(arr).should.be.an('array');
        deepCopy({a: arr}).a.should.not.equal(arr);
    });

    it('should not copy functions', () => {
        let func = () => {};
        deepCopy({a: func}).a.should.equal(func);
    });
});

describe('isDefined', () => {
    const isDefined = utils.isDefined;

    it('should return false when undefined', () => {
        isDefined(undefined).should.equal(false);
    });

    it('should return true for all other values', () => {
        isDefined(null).should.equal(true);
        isDefined(0).should.equal(true);
        isDefined('a').should.equal(true);
        isDefined({}).should.equal(true);
        isDefined([]).should.equal(true);
        isDefined(() => {}).should.equal(true);
    });
});

describe('isArray', () => {
    const isArray = utils.isArray;

    it('should return true when array', () => {
        isArray([]).should.equal(true);
    });

    it('should return false for all other values', () => {
        isArray(undefined).should.equal(false);
        isArray(null).should.equal(false);
        isArray(0).should.equal(false);
        isArray('a').should.equal(false);
        isArray({}).should.equal(false);
        isArray(() => {}).should.equal(false);
    });
});

describe('isString', () => {
    const isString = utils.isString;

    it('should return true when string', () => {
        isString('a').should.equal(true);
    });

    it('should return false for all other values', () => {
        isString(undefined).should.equal(false);
        isString(null).should.equal(false);
        isString(0).should.equal(false);
        isString([]).should.equal(false);
        isString({}).should.equal(false);
        isString(() => {}).should.equal(false);
    });
});

describe('isFunction', () => {
    const isFunction = utils.isFunction;

    it('should return true when function', () => {
        isFunction(() => {}).should.equal(true);
    });

    it('should return false for all other values', () => {
        isFunction(undefined).should.equal(false);
        isFunction(null).should.equal(false);
        isFunction(0).should.equal(false);
        isFunction('a').should.equal(false);
        isFunction([]).should.equal(false);
        isFunction({}).should.equal(false);
    });
});

describe('isObject', () => {
    const isObject = utils.isObject;

    it('should return true when object', () => {
        isObject({}).should.equal(true);
    });

    it('should return false for all other values', () => {
        isObject(undefined).should.equal(false);
        isObject(null).should.equal(false);
        isObject(0).should.equal(false);
        isObject('a').should.equal(false);
        isObject([]).should.equal(false);
        isObject(() => {}).should.equal(false);
        isObject(new Date()).should.equal(false);
    });
});

describe('isNode', () => {
    const isNode = utils.isNode;

    it('should return false for all other values', () => {
        isNode(undefined).should.equal(false);
        isNode(null).should.equal(false);
        isNode(0).should.equal(false);
        isNode('a').should.equal(false);
        isNode([]).should.equal(false);
        isNode({}).should.equal(false);
        isNode(() => {}).should.equal(false);
    });
});

describe('err', () => {
    const err = utils.err;

    it('should throw an error', () => {
        err.should.throw(Error);
    });

    it('should throw an error that blames goo', () => {
        err.should.throw(Error, /goo/);
    });

    it('should throw an error that includes the custom message', () => {
        let message = 'test123';
        (() => {
            err(message);
        }).should.throw(Error, new RegExp(message));
    });
});

describe('assert', () => {
    const assert = utils.assert;

    it('should throw an error when false', () => {
        (() => {
            assert(false);
        }).should.throw(Error);
    });

    it('should not throw an error when true', () => {
        (() => {
            assert(true);
        }).should.not.throw(Error);
    });

    it('should throw an error that blames goo', () => {
        (() => {
            assert(false);
        }).should.throw(Error, /goo/);
    });

    it('should throw an error that includes the custom message', () => {
        let message = 'test123';
        (() => {
            assert(false, message);
        }).should.throw(Error, new RegExp(message));
    });
});

describe('makeQueue', () => {
    const makeQueue = utils.makeQueue;

    it('should immediately call new functions when empty', () => {
        const queue = makeQueue();
        let test = false;
        queue.add(() => {
            test = true;
        });
        test.should.equal(true);
    });

    it('should not proceed until the first function calls done', () => {
        const queue = makeQueue();
        let test = false;
        queue.add(() => {
            test = true;
        });
        queue.add(() => {
            test = false;
        });
        test.should.equal(true);
    });

    it('should call functions in the order they were added', (done) => {
        const queue = makeQueue();
        let callOrder = [];
        let numTests = 2 + Math.floor(Math.random()*8);
        for(let i = 0; i < numTests; ++i) {
            queue.add(() => {
                setTimeout(() => {
                    callOrder.push(i);
                    queue.done();
                }, Math.random()*numTests*2);
            });
        }
        queue.add(() => {
            for (let i = 0; i < numTests; ++i) {
                callOrder[i].should.equal(i);
            }
            done();
        });
    });
});

describe('blobHandler', () => {
    const blobHandler = utils.blobHandler;

    it('should call the function described in the blob', () => {
        let test = false;
        blobHandler({
            test: () => {
                test = true;
            },
        }, {test: null});
        test.should.equal(true);
    });

    it('should pass the object to the blob handler function', () => {
        blobHandler({
            test: (obj) => {
                obj.a.should.equal('test123');
            },
        }, {test: {a: 'test123'}});
    });

    it('should call the blob handler function multiple times for an array', () => {
        let test = 0;
        blobHandler({
            test: (num) => {
                test += num;
            },
        }, {
            test: [1, 2],
        });
        test.should.equal(3);
    });

    it('should call the blob handler for each key in the blob object', () => {
        let test = 0;
        blobHandler({
            a: (num) => {
                test += num;
            },
            b: (num) => {
                test -= num;
            },
        }, {
            a: 1,
            b: 2,
        });
        test.should.equal(-1);
    });

    it('should do nothing if there are no blob handler function for a key in the blob object', () => {
        let test = false;
        (() => {
            blobHandler({
                test: () => {
                    test = true;
                },
            }, {differentTest: null});
        }).should.not.throw(Error);
        test.should.equal(false);
    });

    it('should use a queue if provided', (done) => {
        let queue = utils.makeQueue();
        let test = false;
        queue.add(() => {
            setTimeout(() => {
                queue.done();
            }, 30);
        });
        blobHandler({
            test: (num) => {
                test = true;
            },
        }, {test: null}, queue);
        queue.add(() => {
            test.should.equal(true);
            done();
        });
        test.should.equal(false);
    });
});
<commit_msg>closes #27<commit_after>const should = require('chai').should();

const utils = require('./goo.utils');

describe('deepCopy', () => {
    const deepCopy = utils.deepCopy;

    it('should copy an object', () => {
        let obj = {};
        deepCopy(obj).should.not.equal(obj);
    });

    it('should not mutate inputs', () => {
        let obj = {a: 1};
        let wrapper = {b: obj};
        deepCopy(wrapper);
        wrapper.b.should.equal(obj);
    });

    it('should deep copy an object', () => {
        let obj = {a: 1};
        deepCopy({b: obj}).b.should.not.equal(obj);
    });

    it('should copy strings', () => {
        deepCopy('a').should.equal('a');
    });

    it('should copy numbers', () => {
        deepCopy(1).should.equal(1);
    });

    it('should copy arrays', () => {
        let arr = [1, 2, 3];
        deepCopy(arr).should.be.an('array');
        deepCopy({a: arr}).a.should.not.equal(arr);
    });

    it('should not copy functions', () => {
        let func = () => {};
        deepCopy({a: func}).a.should.equal(func);
    });

    it('should handle null and undefined', () => {
        should.equal(deepCopy(undefined), undefined);
        should.equal(deepCopy(null), null);
    });
});

describe('isDefined', () => {
    const isDefined = utils.isDefined;

    it('should return false when undefined', () => {
        isDefined(undefined).should.equal(false);
    });

    it('should return true for all other values', () => {
        isDefined(null).should.equal(true);
        isDefined(0).should.equal(true);
        isDefined('a').should.equal(true);
        isDefined({}).should.equal(true);
        isDefined([]).should.equal(true);
        isDefined(() => {}).should.equal(true);
    });
});

describe('isArray', () => {
    const isArray = utils.isArray;

    it('should return true when array', () => {
        isArray([]).should.equal(true);
    });

    it('should return false for all other values', () => {
        isArray(undefined).should.equal(false);
        isArray(null).should.equal(false);
        isArray(0).should.equal(false);
        isArray('a').should.equal(false);
        isArray({}).should.equal(false);
        isArray(() => {}).should.equal(false);
    });
});

describe('isString', () => {
    const isString = utils.isString;

    it('should return true when string', () => {
        isString('a').should.equal(true);
    });

    it('should return false for all other values', () => {
        isString(undefined).should.equal(false);
        isString(null).should.equal(false);
        isString(0).should.equal(false);
        isString([]).should.equal(false);
        isString({}).should.equal(false);
        isString(() => {}).should.equal(false);
    });
});

describe('isFunction', () => {
    const isFunction = utils.isFunction;

    it('should return true when function', () => {
        isFunction(() => {}).should.equal(true);
    });

    it('should return false for all other values', () => {
        isFunction(undefined).should.equal(false);
        isFunction(null).should.equal(false);
        isFunction(0).should.equal(false);
        isFunction('a').should.equal(false);
        isFunction([]).should.equal(false);
        isFunction({}).should.equal(false);
    });
});

describe('isObject', () => {
    const isObject = utils.isObject;

    it('should return true when object', () => {
        isObject({}).should.equal(true);
    });

    it('should return false for all other values', () => {
        isObject(undefined).should.equal(false);
        isObject(null).should.equal(false);
        isObject(0).should.equal(false);
        isObject('a').should.equal(false);
        isObject([]).should.equal(false);
        isObject(() => {}).should.equal(false);
        isObject(new Date()).should.equal(false);
    });
});

describe('isNode', () => {
    const isNode = utils.isNode;

    it('should return false for all other values', () => {
        isNode(undefined).should.equal(false);
        isNode(null).should.equal(false);
        isNode(0).should.equal(false);
        isNode('a').should.equal(false);
        isNode([]).should.equal(false);
        isNode({}).should.equal(false);
        isNode(() => {}).should.equal(false);
    });
});

describe('err', () => {
    const err = utils.err;

    it('should throw an error', () => {
        err.should.throw(Error);
    });

    it('should throw an error that blames goo', () => {
        err.should.throw(Error, /goo/);
    });

    it('should throw an error that includes the custom message', () => {
        let message = 'test123';
        (() => {
            err(message);
        }).should.throw(Error, new RegExp(message));
    });
});

describe('assert', () => {
    const assert = utils.assert;

    it('should throw an error when false', () => {
        (() => {
            assert(false);
        }).should.throw(Error);
    });

    it('should not throw an error when true', () => {
        (() => {
            assert(true);
        }).should.not.throw(Error);
    });

    it('should throw an error that blames goo', () => {
        (() => {
            assert(false);
        }).should.throw(Error, /goo/);
    });

    it('should throw an error that includes the custom message', () => {
        let message = 'test123';
        (() => {
            assert(false, message);
        }).should.throw(Error, new RegExp(message));
    });
});

describe('makeQueue', () => {
    const makeQueue = utils.makeQueue;

    it('should immediately call new functions when empty', () => {
        const queue = makeQueue();
        let test = false;
        queue.add(() => {
            test = true;
        });
        test.should.equal(true);
    });

    it('should not proceed until the first function calls done', () => {
        const queue = makeQueue();
        let test = false;
        queue.add(() => {
            test = true;
        });
        queue.add(() => {
            test = false;
        });
        test.should.equal(true);
    });

    it('should call functions in the order they were added', (done) => {
        const queue = makeQueue();
        let callOrder = [];
        let numTests = 2 + Math.floor(Math.random()*8);
        for(let i = 0; i < numTests; ++i) {
            queue.add(() => {
                setTimeout(() => {
                    callOrder.push(i);
                    queue.done();
                }, Math.random()*numTests*2);
            });
        }
        queue.add(() => {
            for (let i = 0; i < numTests; ++i) {
                callOrder[i].should.equal(i);
            }
            done();
        });
    });
});

describe('blobHandler', () => {
    const blobHandler = utils.blobHandler;

    it('should call the function described in the blob', () => {
        let test = false;
        blobHandler({
            test: () => {
                test = true;
            },
        }, {test: null});
        test.should.equal(true);
    });

    it('should pass the object to the blob handler function', () => {
        blobHandler({
            test: (obj) => {
                obj.a.should.equal('test123');
            },
        }, {test: {a: 'test123'}});
    });

    it('should call the blob handler function multiple times for an array', () => {
        let test = 0;
        blobHandler({
            test: (num) => {
                test += num;
            },
        }, {
            test: [1, 2],
        });
        test.should.equal(3);
    });

    it('should call the blob handler for each key in the blob object', () => {
        let test = 0;
        blobHandler({
            a: (num) => {
                test += num;
            },
            b: (num) => {
                test -= num;
            },
        }, {
            a: 1,
            b: 2,
        });
        test.should.equal(-1);
    });

    it('should do nothing if there are no blob handler function for a key in the blob object', () => {
        let test = false;
        (() => {
            blobHandler({
                test: () => {
                    test = true;
                },
            }, {differentTest: null});
        }).should.not.throw(Error);
        test.should.equal(false);
    });

    it('should use a queue if provided', (done) => {
        let queue = utils.makeQueue();
        let test = false;
        queue.add(() => {
            setTimeout(() => {
                queue.done();
            }, 30);
        });
        blobHandler({
            test: (num) => {
                test = true;
            },
        }, {test: null}, queue);
        queue.add(() => {
            test.should.equal(true);
            done();
        });
        test.should.equal(false);
    });
});
<|endoftext|>


<commit_before>import fs from 'fs-promise'
import {join} from 'path'
import * as Validators from '../../src/services/validators'

describe('Standard plugins package.json format check', () => {
    const pluginsRoot = join(__dirname, '../../src/plugins/')

    it('audio-layer', async () => {
        Validators.delirPackageJson(require(join(pluginsRoot, 'audio-layer/package.json')))
    })

    it('composition-layer', async () => {
        Validators.delirPackageJson(require(join(pluginsRoot, 'composition-layer/package.json')))
    })

    it('html5-video-layer', async () => {
        Validators.delirPackageJson(require(join(pluginsRoot, 'html5-video-layer/package.json')))
    })

    it('plane', async () => {
        Validators.delirPackageJson(require(join(pluginsRoot, 'plane/package.json')))
    })

    it('test', async () => {
        Validators.delirPackageJson(require(join(pluginsRoot, 'text/package.json')))
    })
})
<commit_msg>Fix test<commit_after>import fs from 'fs-promise'
import {join} from 'path'
import * as Validators from '../../src/services/validators'

describe('Standard plugins package.json format check', () => {
    const pluginsRoot = join(__dirname, '../../src/plugins/')

    it('audio-layer', async () => {
        Validators.delirPackageJson(require(join(pluginsRoot, 'audio-layer/package.json')))
    })

    it('composition-layer', async () => {
        Validators.delirPackageJson(require(join(pluginsRoot, 'composition-layer/package.json')))
    })

    it('video', async () => {
        Validators.delirPackageJson(require(join(pluginsRoot, 'video/package.json')))
    })

    it('plane', async () => {
        Validators.delirPackageJson(require(join(pluginsRoot, 'plane/package.json')))
    })

    it('test', async () => {
        Validators.delirPackageJson(require(join(pluginsRoot, 'text/package.json')))
    })
})
<|endoftext|>


<commit_before>/**
 * Created by ksinger on 19.02.2016.
 */

import  won from '../won-es6';
import Immutable from 'immutable';
import { actionTypes, actionCreators } from './actions';
import { fetchOwnedData } from '../won-message-utils';
import {
    registerAccount,
    login,
    privateId2Credentials,
} from '../won-utils';
import {
   resetParams,
} from '../configRouting';

import {
    checkHttpStatus,
} from '../utils';

export function anonAccountLogin(privateId) {
    const {email, password} = privateId2Credentials(privateId);
    return accountLogin(email, password);
}
export function accountLogin(username, password) {
    return (dispatch) =>
        login(username, password)
        .then( response =>
            fetchOwnedData(username)
        )
        .then(allThatData =>
            dispatch({
                type: actionTypes.login,
                payload: allThatData.merge({email: username, loggedIn: true})
            })
        )
        .then(() => {
            /**
             * TODO this action is part of the session-upgrade hack documented in:
             * https://github.com/researchstudio-sat/webofneeds/issues/381#issuecomment-172569377
             */
            dispatch(actionCreators.reconnect());
            dispatch(actionCreators.router__stateGoResetParams("feed"));
        })
        .catch(error => {
            console.log("accountLogin ErrorObject", error);
            //TODO load data of non-owned need!!!
            dispatch({
                type: actionTypes.login,
                payload: Immutable.fromJS({loggedIn: false})
            })
            dispatch(actionCreators.loginFailed({loginError: error.msg? error.msg : "Unknown Username/Password Combination", error}))
        })
}

export function accountLogout() {
    return (dispatch) =>
        fetch('/owner/rest/users/signout', {
            method: 'post',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            credentials: 'include',
            body: JSON.stringify({})
        })
        .then(
            checkHttpStatus
        )
        .catch(
            //TODO: PRINT ERROR MESSAGE AND CHANGE STATE ACCORDINGLY
                error => {
                console.log(error);
            }
        )
        .then(response =>
            dispatch({
                type: actionTypes.logout,
                payload: Immutable.fromJS({loggedIn: false})
            })
        )
        .then(() => {
            won.clearStore();
            /**
             * TODO this action is part of the session-upgrade hack documented in:
             * https://github.com/researchstudio-sat/webofneeds/issues/381#issuecomment-172569377
             */
            dispatch(actionCreators.reconnect());
        })
        .then(() => { /* finally */
            dispatch(actionCreators.router__stateGoResetParams("landingpage"));

            // for the case that we've been logged in to an anonymous account, we need to remove the privateId here.
            dispatch(actionCreators.router__stateGoCurrent({privateId: undefined}));
        })
}

export function accountRegister(username, password) {
    return (dispatch) =>
        registerAccount(username, password)
        .then(response => {
            /* TODO shouldn't we already have a valid
            * session at this point and thus just need
            * to execute the data-fetching part of login
            * (the fetchDataForOwnedNeeds, redirect
            * and wsReset)
            */
            dispatch(actionCreators.login(username, password));
        })
        .catch(
            //TODO: PRINT MORE SPECIFIC ERROR MESSAGE, already registered/password to short etc.
                error =>
                    dispatch(actionCreators.registerFailed({registerError: "Registration failed (E-Mail might already be used)", error}))
        )
}
<commit_msg>Checking access control after logout instead of blindly redirecting.<commit_after>/**
 * Created by ksinger on 19.02.2016.
 */

import  won from '../won-es6';
import Immutable from 'immutable';
import { actionTypes, actionCreators } from './actions';
import { fetchOwnedData } from '../won-message-utils';
import {
    registerAccount,
    login,
    privateId2Credentials,
} from '../won-utils';
import {
    resetParams,
    checkAccessToCurrentRoute,
} from '../configRouting';

import {
    checkHttpStatus,
} from '../utils';

export function anonAccountLogin(privateId) {
    const {email, password} = privateId2Credentials(privateId);
    return accountLogin(email, password);
}
export function accountLogin(username, password) {
    return (dispatch) =>
        login(username, password)
        .then( response =>
            fetchOwnedData(username)
        )
        .then(allThatData =>
            dispatch({
                type: actionTypes.login,
                payload: allThatData.merge({email: username, loggedIn: true})
            })
        )
        .then(() => {
            /**
             * TODO this action is part of the session-upgrade hack documented in:
             * https://github.com/researchstudio-sat/webofneeds/issues/381#issuecomment-172569377
             */
            dispatch(actionCreators.reconnect());
            dispatch(actionCreators.router__stateGoResetParams("feed"));
        })
        .catch(error => {
            console.log("accountLogin ErrorObject", error);
            //TODO load data of non-owned need!!!
            dispatch({
                type: actionTypes.login,
                payload: Immutable.fromJS({loggedIn: false})
            })
            dispatch(actionCreators.loginFailed({loginError: error.msg? error.msg : "Unknown Username/Password Combination", error}))
        })
}

export function accountLogout() {
    return (dispatch, getState) =>
        fetch('/owner/rest/users/signout', {
            method: 'post',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            credentials: 'include',
            body: JSON.stringify({})
        })
        .then(
            checkHttpStatus
        )
        .catch(
            //TODO: PRINT ERROR MESSAGE AND CHANGE STATE ACCORDINGLY
                error => {
                console.log(error);
            }
        )
        .then(response =>
            dispatch({
                type: actionTypes.logout,
                payload: Immutable.fromJS({loggedIn: false})
            })
        )
        .then(() => {
            won.clearStore();
            /**
             * TODO this action is part of the session-upgrade hack documented in:
             * https://github.com/researchstudio-sat/webofneeds/issues/381#issuecomment-172569377
             */
            dispatch(actionCreators.reconnect());
        })
        .then(() => { /* finally */
            // for the case that we've been logged in to an anonymous account, we need to remove the privateId here.
            dispatch(actionCreators.router__stateGoCurrent({privateId: undefined}));

            checkAccessToCurrentRoute(dispatch, getState);
        })
}

export function accountRegister(username, password) {
    return (dispatch) =>
        registerAccount(username, password)
        .then(response => {
            /* TODO shouldn't we already have a valid
            * session at this point and thus just need
            * to execute the data-fetching part of login
            * (the fetchDataForOwnedNeeds, redirect
            * and wsReset)
            */
            dispatch(actionCreators.login(username, password));
        })
        .catch(
            //TODO: PRINT MORE SPECIFIC ERROR MESSAGE, already registered/password to short etc.
                error =>
                    dispatch(actionCreators.registerFailed({registerError: "Registration failed (E-Mail might already be used)", error}))
        )
}
<|endoftext|>


<commit_before>/* global describe: true, it; true */

'use strict';

var expect = require('expect.js'),
	perfMarkerSingleton = require('../lib/performanceMarker').provider('test.perfMarker'),
	perfMarkerFactory = require('../lib/performanceMarker').factory();

describe('performanceMarker', function () {

	it('Should create a new entry in the time map', function () {
		perfMarkerSingleton.start('testEntry');
		var i = 0;
		while (i < 20000000) {
			i++;
		}
		perfMarkerSingleton.end('testEntry');
		var testTimeline = perfMarkerSingleton.getTimeline();
		expect(testTimeline).to.have.length(1);
		expect(testTimeline[0].startTime).to.be.a('number');
		expect(testTimeline[0].duration).to.be.a('number');
	});

	it('Should find a duration', function () {
		perfMarkerFactory.start('durationTest');
		var i = 0;
		while (i < 20000000) {
			i++;
		}
		perfMarkerFactory.end('durationTest');
		var testTimeline = perfMarkerFactory.getTimeline();
		expect(testTimeline).to.have.length(1);
		expect(testTimeline[0].duration).to.be.above(0);
	});

	it('Run should execute the function', function () {
		var newPerfFactory = require('../lib/performanceMarker').factory();
		newPerfFactory.start('runTest')
			.run(function () {
				var i = 0;
				while (i < 20000000) {
					i++;
				}
			})
			.end('runTest');
		var testTimeline = newPerfFactory.getTimeline();
		expect(testTimeline).to.have.length(1);
		expect(testTimeline[0].duration).to.be.above(0);
	});

	it('Run should execute multiple times', function () {
		this.timeout(5000);
		var newPerfFactory = require('../lib/performanceMarker').factory();
		newPerfFactory.start('runTestMultiple')
			.run(function () {
				var i = 0;
				while(i < 20000000) {
					i++;
				}
			}, 20)
			.end('runTestMultiple');
		var testTimeline = newPerfFactory.getTimeline();
		expect(testTimeline).to.have.length(1);
		expect(testTimeline[0].duration).to.be.above(0);
	});

});

<commit_msg>Remove timeout override<commit_after>/* global describe: true, it; true */

'use strict';

var expect = require('expect.js'),
	perfMarkerSingleton = require('../lib/performanceMarker').provider('test.perfMarker'),
	perfMarkerFactory = require('../lib/performanceMarker').factory();

describe('performanceMarker', function () {

	it('Should create a new entry in the time map', function () {
		perfMarkerSingleton.start('testEntry');
		var i = 0;
		while (i < 20000000) {
			i++;
		}
		perfMarkerSingleton.end('testEntry');
		var testTimeline = perfMarkerSingleton.getTimeline();
		expect(testTimeline).to.have.length(1);
		expect(testTimeline[0].startTime).to.be.a('number');
		expect(testTimeline[0].duration).to.be.a('number');
	});

	it('Should find a duration', function () {
		perfMarkerFactory.start('durationTest');
		var i = 0;
		while (i < 20000000) {
			i++;
		}
		perfMarkerFactory.end('durationTest');
		var testTimeline = perfMarkerFactory.getTimeline();
		expect(testTimeline).to.have.length(1);
		expect(testTimeline[0].duration).to.be.above(0);
	});

	it('Run should execute the function', function () {
		var newPerfFactory = require('../lib/performanceMarker').factory();
		newPerfFactory.start('runTest')
			.run(function () {
				var i = 0;
				while (i < 20000000) {
					i++;
				}
			})
			.end('runTest');
		var testTimeline = newPerfFactory.getTimeline();
		expect(testTimeline).to.have.length(1);
		expect(testTimeline[0].duration).to.be.above(0);
	});

	it('Run should execute multiple times', function () {
		var newPerfFactory = require('../lib/performanceMarker').factory();
		newPerfFactory.start('runTestMultiple')
			.run(function () {
				var i = 0;
				while(i < 20000000) {
					i++;
				}
			}, 20)
			.end('runTestMultiple');
		var testTimeline = newPerfFactory.getTimeline();
		expect(testTimeline).to.have.length(1);
		expect(testTimeline[0].duration).to.be.above(0);
	});

});

<|endoftext|>


<commit_before>module('plugins.copy');

test('检查IE下复制命令是否执行正常', function () {

    if (browser.ie) {
        var editor = te.obj[0];
        editor.setContent('
hello
');
        editor.focus();

        editor.execCommand('selectall');
        editor.execCommand('copy');
        editor.body.innerHTML = '';
        editor.execCommand('selectall');
        editor.body.document.execCommand('paste');

        equal(utils.trim(window.clipboardData.getData('text')), 'hello', '检查粘贴板内容,IE下成功复制内容');
        setTimeout(function(){
            equal(editor.getContent(), '
hello
', '检查原生粘贴命令,IE下成功复制内容');
            start();
        },100);

        stop();
    }

});

test('检查非IE下是否正常加载zeroclipboard粘贴板插件', function () {

    if (!browser.ie) {

        setTimeout(function(){
            ok(ZeroClipboard, '是否正常加载zeroclipboard粘贴板插件');
            start();
        }, 300);

        stop();

    }

});<commit_msg>添加copy和paste用例<commit_after>module('plugins.copy');

//需要点击授权弹出框,暂时去除
//test('检查IE下复制命令是否执行正常', function () {
//
//    if (browser.ie) {
//        var editor = te.obj[0];
//        editor.setContent('
hello
');
//        editor.focus();
//
//        editor.execCommand('selectall');
//        editor.execCommand('copy');
//        editor.body.innerHTML = '';
//        editor.execCommand('selectall');
//        editor.body.document.execCommand('paste');
//
//        equal(utils.trim(window.clipboardData.getData('text')), 'hello', '检查粘贴板内容,IE下成功复制内容');
//        setTimeout(function(){
//            equal(editor.getContent(), '
hello
', '检查原生粘贴命令,IE下成功复制内容');
//            start();
//        },100);
//
//        stop();
//    }
//
//});

test('检查非IE下是否正常加载zeroclipboard粘贴板插件', function () {

    if (!browser.ie) {

        setTimeout(function(){
            ok(ZeroClipboard, '是否正常加载zeroclipboard粘贴板插件');
            start();
        }, 300);

        stop();

    }

});<|endoftext|>


<commit_before>// This file has been autogenerated.

exports.setEnvironment = function() {
  process.env['AZURE_SUBSCRIPTION_ID'] = '33855c90-c8cf-44a0-a266-9b548fb8e7b0';
};

exports.scopes = [[function (nock) {
var result =
nock('http://management.azure.com:443')
  .get('/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/KeepIntegrationTestResources/providers/Microsoft.DevTestLab/labs/LabForIntegration?api-version=2016-05-15')
  .reply(200, "{\"properties\":{\"defaultStorageAccount\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.Storage/storageAccounts/msdtlvm1114508600\",\"artifactsStorageAccount\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.Storage/storageAccounts/msdtlvm1287512904\",\"vaultName\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.KeyVault/vaults/msdtl2063424927\",\"labStorageType\":\"Standard\",\"createdDate\":\"2016-05-04T23:05:53.560711+00:00\",\"provisioningState\":\"Succeeded\"},\"id\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourcegroups/keepintegrationtestresources/providers/microsoft.devtestlab/labs/labforintegration\",\"name\":\"LabForIntegration\",\"type\":\"Microsoft.DevTestLab/labs\",\"location\":\"Southeast Asia\",\"tags\":{\"CreatedOn\":\"5/4/2016 11:05:50 PM +00:00\"}}", { 'cache-control': 'no-cache',
  pragma: 'no-cache',
  'content-length': '955',
  'content-type': 'application/json; charset=utf-8',
  expires: '-1',
  vary: 'Accept-Encoding',
  'x-rp-requesturi': 'https://dtl-dev-rp.azurewebsites.net/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/KeepIntegrationTestResources/providers/Microsoft.DevTestLab/labs/LabForIntegration?api-version=2016-05-15',
  'x-dtl-processedby': 'dtl-dev-rp.azurewebsites.net',
  'set-cookie':
   [ 'ARRAffinity=aa7a076a03f0cc68ff10821062cd9951acb337c68ed7becf8367b21e1910d41c;Path=/;Domain=dev.rp1.vsdth.visualstudio.com',
     'ARRAffinity=2892eb122969bb1f3024dd9fea9a68afca18700f3b0b7fb304a40d427e67ea2f;Path=/;Domain=dev.rp1.vsdth.visualstudio.com' ],
  server: 'Microsoft-IIS/8.0',
  'x-aspnet-version': '4.0.30319',
  'x-powered-by': 'ASP.NET, ASP.NET',
  'x-ms-ratelimit-remaining-subscription-reads': '14999',
  'x-ms-request-id': '59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'x-ms-correlation-request-id': '59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'x-ms-routing-request-id': 'CENTRALUS:20160520T173546Z:59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'strict-transport-security': 'max-age=31536000; includeSubDomains',
  date: 'Fri, 20 May 2016 17:35:45 GMT',
  connection: 'close' });
 return result; },
function (nock) {
var result =
nock('https://management.azure.com:443')
  .get('/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/KeepIntegrationTestResources/providers/Microsoft.DevTestLab/labs/LabForIntegration?api-version=2016-05-15')
  .reply(200, "{\"properties\":{\"defaultStorageAccount\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.Storage/storageAccounts/msdtlvm1114508600\",\"artifactsStorageAccount\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.Storage/storageAccounts/msdtlvm1287512904\",\"vaultName\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.KeyVault/vaults/msdtl2063424927\",\"labStorageType\":\"Standard\",\"createdDate\":\"2016-05-04T23:05:53.560711+00:00\",\"provisioningState\":\"Succeeded\"},\"id\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourcegroups/keepintegrationtestresources/providers/microsoft.devtestlab/labs/labforintegration\",\"name\":\"LabForIntegration\",\"type\":\"Microsoft.DevTestLab/labs\",\"location\":\"Southeast Asia\",\"tags\":{\"CreatedOn\":\"5/4/2016 11:05:50 PM +00:00\"}}", { 'cache-control': 'no-cache',
  pragma: 'no-cache',
  'content-length': '955',
  'content-type': 'application/json; charset=utf-8',
  expires: '-1',
  vary: 'Accept-Encoding',
  'x-rp-requesturi': 'https://dtl-dev-rp.azurewebsites.net/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/KeepIntegrationTestResources/providers/Microsoft.DevTestLab/labs/LabForIntegration?api-version=2016-05-15',
  'x-dtl-processedby': 'dtl-dev-rp.azurewebsites.net',
  'set-cookie':
   [ 'ARRAffinity=aa7a076a03f0cc68ff10821062cd9951acb337c68ed7becf8367b21e1910d41c;Path=/;Domain=dev.rp1.vsdth.visualstudio.com',
     'ARRAffinity=2892eb122969bb1f3024dd9fea9a68afca18700f3b0b7fb304a40d427e67ea2f;Path=/;Domain=dev.rp1.vsdth.visualstudio.com' ],
  server: 'Microsoft-IIS/8.0',
  'x-aspnet-version': '4.0.30319',
  'x-powered-by': 'ASP.NET, ASP.NET',
  'x-ms-ratelimit-remaining-subscription-reads': '14999',
  'x-ms-request-id': '59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'x-ms-correlation-request-id': '59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'x-ms-routing-request-id': 'CENTRALUS:20160520T173546Z:59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'strict-transport-security': 'max-age=31536000; includeSubDomains',
  date: 'Fri, 20 May 2016 17:35:45 GMT',
  connection: 'close' });
 return result; }]];<commit_msg>Fix tests<commit_after>// This file has been autogenerated.

exports.setEnvironment = function() {
  process.env['AZURE_SUBSCRIPTION_ID'] = '33855c90-c8cf-44a0-a266-9b548fb8e7b0';
};

exports.scopes = [[function (nock) {
var result =
nock('http://management.azure.com:443')
  .get('/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/KeepIntegrationTestResources/providers/Microsoft.DevTestLab/labs/LabForIntegration?api-version=2018-09-15')
  .reply(200, "{\"properties\":{\"defaultStorageAccount\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.Storage/storageAccounts/msdtlvm1114508600\",\"artifactsStorageAccount\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.Storage/storageAccounts/msdtlvm1287512904\",\"vaultName\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.KeyVault/vaults/msdtl2063424927\",\"labStorageType\":\"Standard\",\"createdDate\":\"2016-05-04T23:05:53.560711+00:00\",\"provisioningState\":\"Succeeded\"},\"id\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourcegroups/keepintegrationtestresources/providers/microsoft.devtestlab/labs/labforintegration\",\"name\":\"LabForIntegration\",\"type\":\"Microsoft.DevTestLab/labs\",\"location\":\"Southeast Asia\",\"tags\":{\"CreatedOn\":\"5/4/2016 11:05:50 PM +00:00\"}}", { 'cache-control': 'no-cache',
  pragma: 'no-cache',
  'content-length': '955',
  'content-type': 'application/json; charset=utf-8',
  expires: '-1',
  vary: 'Accept-Encoding',
  'x-rp-requesturi': 'https://dtl-dev-rp.azurewebsites.net/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/KeepIntegrationTestResources/providers/Microsoft.DevTestLab/labs/LabForIntegration?api-version=2018-09-15',
  'x-dtl-processedby': 'dtl-dev-rp.azurewebsites.net',
  'set-cookie':
   [ 'ARRAffinity=aa7a076a03f0cc68ff10821062cd9951acb337c68ed7becf8367b21e1910d41c;Path=/;Domain=dev.rp1.vsdth.visualstudio.com',
     'ARRAffinity=2892eb122969bb1f3024dd9fea9a68afca18700f3b0b7fb304a40d427e67ea2f;Path=/;Domain=dev.rp1.vsdth.visualstudio.com' ],
  server: 'Microsoft-IIS/8.0',
  'x-aspnet-version': '4.0.30319',
  'x-powered-by': 'ASP.NET, ASP.NET',
  'x-ms-ratelimit-remaining-subscription-reads': '14999',
  'x-ms-request-id': '59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'x-ms-correlation-request-id': '59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'x-ms-routing-request-id': 'CENTRALUS:20160520T173546Z:59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'strict-transport-security': 'max-age=31536000; includeSubDomains',
  date: 'Fri, 20 May 2016 17:35:45 GMT',
  connection: 'close' });
 return result; },
function (nock) {
var result =
nock('https://management.azure.com:443')
  .get('/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/KeepIntegrationTestResources/providers/Microsoft.DevTestLab/labs/LabForIntegration?api-version=2018-09-15')
  .reply(200, "{\"properties\":{\"defaultStorageAccount\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.Storage/storageAccounts/msdtlvm1114508600\",\"artifactsStorageAccount\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.Storage/storageAccounts/msdtlvm1287512904\",\"vaultName\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/keepintegrationtestresources/providers/Microsoft.KeyVault/vaults/msdtl2063424927\",\"labStorageType\":\"Standard\",\"createdDate\":\"2016-05-04T23:05:53.560711+00:00\",\"provisioningState\":\"Succeeded\"},\"id\":\"/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourcegroups/keepintegrationtestresources/providers/microsoft.devtestlab/labs/labforintegration\",\"name\":\"LabForIntegration\",\"type\":\"Microsoft.DevTestLab/labs\",\"location\":\"Southeast Asia\",\"tags\":{\"CreatedOn\":\"5/4/2016 11:05:50 PM +00:00\"}}", { 'cache-control': 'no-cache',
  pragma: 'no-cache',
  'content-length': '955',
  'content-type': 'application/json; charset=utf-8',
  expires: '-1',
  vary: 'Accept-Encoding',
  'x-rp-requesturi': 'https://dtl-dev-rp.azurewebsites.net/subscriptions/33855c90-c8cf-44a0-a266-9b548fb8e7b0/resourceGroups/KeepIntegrationTestResources/providers/Microsoft.DevTestLab/labs/LabForIntegration?api-version=2018-09-15',
  'x-dtl-processedby': 'dtl-dev-rp.azurewebsites.net',
  'set-cookie':
   [ 'ARRAffinity=aa7a076a03f0cc68ff10821062cd9951acb337c68ed7becf8367b21e1910d41c;Path=/;Domain=dev.rp1.vsdth.visualstudio.com',
     'ARRAffinity=2892eb122969bb1f3024dd9fea9a68afca18700f3b0b7fb304a40d427e67ea2f;Path=/;Domain=dev.rp1.vsdth.visualstudio.com' ],
  server: 'Microsoft-IIS/8.0',
  'x-aspnet-version': '4.0.30319',
  'x-powered-by': 'ASP.NET, ASP.NET',
  'x-ms-ratelimit-remaining-subscription-reads': '14999',
  'x-ms-request-id': '59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'x-ms-correlation-request-id': '59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'x-ms-routing-request-id': 'CENTRALUS:20160520T173546Z:59d6f88c-be54-43b9-b395-31ce6c2ce0d5',
  'strict-transport-security': 'max-age=31536000; includeSubDomains',
  date: 'Fri, 20 May 2016 17:35:45 GMT',
  connection: 'close' });
 return result; }]];<|endoftext|>


<commit_before>/**
 * define a tree used to see all content, move nodes and select things to edit
 */
var AdminTree = (function () {

    var my = {},
        generateDialog;

    generateDialog = function (url, closeCallback) {
        var treeDialog = jQuery("");// iframe is needed because the delivered form might need some additional JS

        jQuery(document.body).append(treeDialog);
        treeDialog.attr('src', url);

        treeDialog.dialog({
            width: 800,
            modal: true,
            autoOpen: true,
            resizable: true,
            close: function(event, ui) {
                if (closeCallback) {
                    closeCallback(event, ui);
                }
            },
            zIndex: 9999
        });

        treeDialog.attr('style', 'height: 500px');

        return treeDialog;
    };

    my.generateTreeStateArray = function (path) {

        var start, pos, segments, curSegment, curItem;

        curSegment = '';
        segments = [];
        start = 1;
        pos = path.indexOf('/', start);

        while (pos > 0) {
            curItem = path.substr(start, pos - start);
            if (curItem !== '') {
                curSegment = curSegment + '/' + curItem;
                segments.push(curSegment);
            }
            start = pos + 1;
            pos = path.indexOf('/', start);
        }

        curItem = path.substr(start);

        if (curItem !== '') {
            curSegment = curSegment + '/' + curItem;
            segments.push(curSegment);
        }

        return segments;
    };

    my.initTree = function (config) {
        if (! 'rootNode' in config) {
            config.rootNode = "/";
        }
        if (! 'selected' in config) {
            config.selected = config.rootNode;
        }
        if (! 'routing_defaults' in config) {
            config.routing_defaults = {};
        }
        var treeInst = jQuery(config.selector).jstree({
            "core": {
                "initially_load": config.path.expanded,
                "initially_open": config.path.preloaded
            },
            "plugins": [ "contextmenu", "themes", "types", "ui", "json_data", "crrm", "dnd", "cookies" ],
            "json_data": {
                "ajax": {
                    "url": config.ajax.children_url,
                    "data": function (node) {
                        if (node == -1) {
                            return { 'root' : config.rootNode };
                        } else {
                            return { 'root' : jQuery(node).attr('id') };
                        }
                    }
                }
            },
            "types": {
                "max_depth":        -1,
                "max_children":     -1,
                "valid_children":  "all",
                "types": config.types
            },
            "ui": {
                "initially_select" : [ config.selected ]
            },
            "contextmenu": {
                "items": function(node) {
                    var result = {};
                    var nodetype = node.attr("rel");
                    if (nodetype in config.types) {
                        var createItem = {};
                        var found = false;
                        createItem.label = config.labels.createItem;
                        createItem.submenu = {};
                        $.each(config.types[nodetype].valid_children, function(i, val) {
                            if (val in config.types) {
                                createItem.submenu[val] = {};
                                createItem.submenu[val].label = config.types[val].label;
                                createItem.submenu[val].action = function (node) {
                                    routing_defaults = config.routing_defaults;
                                    routing_defaults["parent"] = node.attr("url_safe_id");

                                    if (config.createInOverlay) {
                                        generateDialog(
                                            Routing.generate(config.types[val].routes.create_route, routing_defaults),
                                            function () {
                                                treeInst.jstree('refresh', node);
                                            }
                                        );
                                    } else {
                                        window.location = Routing.generate(config.types[val].routes.create_route, routing_defaults);
                                    }
                                };
                                found = true;
                            }
                        });
                        if (found) {
                            result.createItem = createItem;
                        }
                    }
                    if (undefined !== config.types[node.attr("rel")].routes.delete_route) {
                        result.deleteItem = {};
                        result.deleteItem.label = config.labels.deleteItem;
                        result.deleteItem.action = function (node) {
                            routing_defaults = config.routing_defaults;
                            routing_defaults["id"] = node.attr("url_safe_id");
                            window.location = Routing.generate(config.types[node.attr("rel")].routes.delete_route, routing_defaults);
                        };
                    }
                    return result;
                }
            },
            "dnd" : {
                "drop_target" : false,
                "drag_target" : false
            },
            "crrm": {
                "move": { }
            },
            "cookies": {
                "save_selected": false
            }
        });

        treeInst.bind("select_node.jstree", function (event, data) {
            if (data.rslt.obj.attr("rel") in config.types
                && data.rslt.obj.attr("id") != config.selected
                && undefined != config.types[data.rslt.obj.attr("rel")].routes.select_route
            ) {
                routing_defaults = config.routing_defaults;
                routing_defaults["id"] = data.rslt.obj.attr("url_safe_id");

                if (config.editInOverlay) {
                    generateDialog(
                        Routing.generate(config.types[data.rslt.obj.attr("rel")].routes.select_route, routing_defaults),
                        function () {
                            treeInst.jstree('refresh');
                        }
                    );
                } else {
                    window.location = Routing.generate(config.types[data.rslt.obj.attr("rel")].routes.select_route, routing_defaults);
                }
            } else {
                // TODO: overlay?
                console.log('This node is not editable');
            }
        })
        .bind("before.jstree", function (e, data) {
            if (data.func === "move_node" && data.plugin === "crrm" && data.args[1] == false) {
                var confirmEvent = jQuery.Event('symfony_cmf_tree.move', data.inst);
                $(this).trigger(confirmEvent);
                if (confirmEvent.isDefaultPrevented()) {
                    e.stopImmediatePropagation();
                    return false;
                }
            }
        })
        .bind("move_node.jstree", function (event, data) {
            var dropped = data.rslt.o;
            var target = data.rslt.r;
            var position = data.rslt.p;
            var oldParent = data.rslt.op;
            var newParent = data.rslt.np;

            // parent could be the tree
            var parent = newParent.attr("id");
            if (treeInst.is(newParent)) {
                parent = config.rootNode;
            }

            if (!oldParent.is(newParent)) {
                $.post(
                    config.ajax.move_url,
                    { "dropped": dropped.attr("id"), "target": parent },
                    function (data) {
                        dropped.attr("id", data.id);
                        dropped.attr("url_safe_id", data.url_safe_id);
                    }
                );
            } else {
                $.post(
                    config.ajax.reorder_url,
                    { "dropped": dropped.attr("id"), "target": target.attr("id"), "parent": parent, "position": position }
                );
            }
        })

        .delegate("a", "click", function (event, data) { event.preventDefault(); });
    };

    return my;

}());
<commit_msg>fix problem of overlay reopening immediately after closing it<commit_after>/**
 * define a tree used to see all content, move nodes and select things to edit
 */
var AdminTree = (function () {

    var my = {},
        generateDialog;

    generateDialog = function (url, closeCallback) {
        var treeDialog = jQuery("");// iframe is needed because the delivered form might need some additional JS

        jQuery(document.body).append(treeDialog);
        treeDialog.attr('src', url);

        treeDialog.dialog({
            width: 800,
            modal: true,
            autoOpen: true,
            resizable: true,
            close: function(event, ui) {
                if (closeCallback) {
                    closeCallback(event, ui);
                }
            },
            zIndex: 9999
        });

        treeDialog.attr('style', 'height: 500px');

        return treeDialog;
    };

    my.generateTreeStateArray = function (path) {

        var start, pos, segments, curSegment, curItem;

        curSegment = '';
        segments = [];
        start = 1;
        pos = path.indexOf('/', start);

        while (pos > 0) {
            curItem = path.substr(start, pos - start);
            if (curItem !== '') {
                curSegment = curSegment + '/' + curItem;
                segments.push(curSegment);
            }
            start = pos + 1;
            pos = path.indexOf('/', start);
        }

        curItem = path.substr(start);

        if (curItem !== '') {
            curSegment = curSegment + '/' + curItem;
            segments.push(curSegment);
        }

        return segments;
    };

    my.initTree = function (config) {
        if (! 'rootNode' in config) {
            config.rootNode = "/";
        }
        if (! 'selected' in config) {
            config.selected = config.rootNode;
        }
        if (! 'routing_defaults' in config) {
            config.routing_defaults = {};
        }
        var treeInst = jQuery(config.selector).jstree({
            "core": {
                "initially_load": config.path.expanded,
                "initially_open": config.path.preloaded
            },
            "plugins": [ "contextmenu", "themes", "types", "ui", "json_data", "crrm", "dnd", "cookies" ],
            "json_data": {
                "ajax": {
                    "url": config.ajax.children_url,
                    "data": function (node) {
                        if (node == -1) {
                            return { 'root' : config.rootNode };
                        } else {
                            return { 'root' : jQuery(node).attr('id') };
                        }
                    }
                }
            },
            "types": {
                "max_depth":        -1,
                "max_children":     -1,
                "valid_children":  "all",
                "types": config.types
            },
            "ui": {
                "initially_select" : [ config.selected ]
            },
            "contextmenu": {
                "items": function(node) {
                    var result = {};
                    var nodetype = node.attr("rel");
                    if (nodetype in config.types) {
                        var createItem = {};
                        var found = false;
                        createItem.label = config.labels.createItem;
                        createItem.submenu = {};
                        $.each(config.types[nodetype].valid_children, function(i, val) {
                            if (val in config.types) {
                                createItem.submenu[val] = {};
                                createItem.submenu[val].label = config.types[val].label;
                                createItem.submenu[val].action = function (node) {
                                    routing_defaults = config.routing_defaults;
                                    routing_defaults["parent"] = node.attr("url_safe_id");

                                    if (config.createInOverlay) {
                                        generateDialog(
                                            Routing.generate(config.types[val].routes.create_route, routing_defaults),
                                            function () {
                                                treeInst.jstree('refresh', node);
                                            }
                                        );
                                    } else {
                                        window.location = Routing.generate(config.types[val].routes.create_route, routing_defaults);
                                    }
                                };
                                found = true;
                            }
                        });
                        if (found) {
                            result.createItem = createItem;
                        }
                    }
                    if (undefined !== config.types[node.attr("rel")].routes.delete_route) {
                        result.deleteItem = {};
                        result.deleteItem.label = config.labels.deleteItem;
                        result.deleteItem.action = function (node) {
                            routing_defaults = config.routing_defaults;
                            routing_defaults["id"] = node.attr("url_safe_id");
                            window.location = Routing.generate(config.types[node.attr("rel")].routes.delete_route, routing_defaults);
                        };
                    }
                    return result;
                }
            },
            "dnd" : {
                "drop_target" : false,
                "drag_target" : false
            },
            "crrm": {
                "move": { }
            },
            "cookies": {
                "save_selected": false
            }
        });

        treeInst.bind("select_node.jstree", function (event, data) {
            if (data.rslt.obj.attr("rel") in config.types
                && data.rslt.obj.attr("id") != config.selected
                && undefined != config.types[data.rslt.obj.attr("rel")].routes.select_route
            ) {
                routing_defaults = config.routing_defaults;
                routing_defaults["id"] = data.rslt.obj.attr("url_safe_id");

                if (config.editInOverlay) {
                    generateDialog(
                        Routing.generate(config.types[data.rslt.obj.attr("rel")].routes.select_route, routing_defaults)
                    );
                } else {
                    window.location = Routing.generate(config.types[data.rslt.obj.attr("rel")].routes.select_route, routing_defaults);
                }
            } else {
                // TODO: overlay?
                console.log('This node is not editable');
            }
        })
        .bind("before.jstree", function (e, data) {
            if (data.func === "move_node" && data.plugin === "crrm" && data.args[1] == false) {
                var confirmEvent = jQuery.Event('symfony_cmf_tree.move', data.inst);
                $(this).trigger(confirmEvent);
                if (confirmEvent.isDefaultPrevented()) {
                    e.stopImmediatePropagation();
                    return false;
                }
            }
        })
        .bind("move_node.jstree", function (event, data) {
            var dropped = data.rslt.o;
            var target = data.rslt.r;
            var position = data.rslt.p;
            var oldParent = data.rslt.op;
            var newParent = data.rslt.np;

            // parent could be the tree
            var parent = newParent.attr("id");
            if (treeInst.is(newParent)) {
                parent = config.rootNode;
            }

            if (!oldParent.is(newParent)) {
                $.post(
                    config.ajax.move_url,
                    { "dropped": dropped.attr("id"), "target": parent },
                    function (data) {
                        dropped.attr("id", data.id);
                        dropped.attr("url_safe_id", data.url_safe_id);
                    }
                );
            } else {
                $.post(
                    config.ajax.reorder_url,
                    { "dropped": dropped.attr("id"), "target": target.attr("id"), "parent": parent, "position": position }
                );
            }
        })

        .delegate("a", "click", function (event, data) { event.preventDefault(); });
    };

    return my;

}());
<|endoftext|>


<commit_before>import { addDecorator, addParameters } from '@storybook/react';
import { withInfo } from '@storybook/addon-info';
import { COLOR } from '../src/constants';
import styles from '@sambego/storybook-styles';
import PropTable from './components/propTable';

addParameters({
  backgrounds: [
    { name: 'Aqua lightest', value: COLOR.AQUA.LIGHTEST },
    { name: 'Neutral light', value: COLOR.NEUTRAL.LIGHT },
    { name: 'Gold lightest', value: COLOR.GOLD.LIGHTEST },
    { name: 'Mint lightest', value: COLOR.MINT.LIGHTEST },
    { name: 'Ruby lightest', value: COLOR.RUBY.LIGHTEST },
    { name: 'Teal lightest', value: COLOR.TEAL.LIGHTEST },
    { name: 'Violet lightest', value: COLOR.VIOLET.LIGHTEST },
    { name: 'Teal darkest', value: COLOR.TEAL.DARKEST },
  ],
});

addParameters({
  options: {
    showRoots: true,
    storySort: (a, b) => (a[1].kind === b[1].kind ? 0 : a[1].id.localeCompare(b[1].id, undefined, { numeric: true })),
  },
});

// addon-info
addDecorator(
  withInfo({
    inline: true,
    source: true,
    styles: (stylesheet) => {
      stylesheet.infoBody = {
        color: COLOR.TEAL.DARKEST,
        fontFamily: 'Inter-Regular',
        fontSize: '14px',
        margin: '24px 0',
        padding: '0',
      };

      stylesheet.header = {
        h1: {
          fontFamily: 'Inter-Medium',
          fontSize: '24px',
          fontWeight: 500,
          lineHeight: '30px',
          margin: 0,
        },
        h2: {
          color: COLOR.NEUTRAL.DARKEST,
          fontFamily: 'Inter-Medium',
          fontSize: '18px',
          fontWeight: 500,
          lineHeight: '24px',
          margin: '24px 0 10px 0',
        },
        body: {
          paddingTop: 10,
          marginBottom: 10,
        },
      };

      stylesheet.source = {
        h1: {
          color: COLOR.NEUTRAL.DARKEST,
          fontFamily: 'Inter-Medium',
          margin: '24px 0 10px 0',
          fontWeight: 500,
          fontSize: '18px',
          lineHeight: '24px',
          padding: '12px 0',
        },
      };

      stylesheet.propTableHead = {
        color: COLOR.TEAL.DARKEST,
        fontFamily: 'Inter-Medium',
        fontWeight: 500,
        fontSize: '16px',
        lineHeight: '21px',
        margin: '20px 0 0 0',
      };

      return stylesheet;
    },
    TableComponent: PropTable,
  }),
);

// addon-styles
addDecorator(
  styles({
    margin: '24px auto',
    maxWidth: '90%',
  }),
);
<commit_msg>Add withDesign globally as a decorator<commit_after>import { addDecorator, addParameters } from '@storybook/react';
import { withDesign } from 'storybook-addon-designs';
import { withInfo } from '@storybook/addon-info';
import { COLOR } from '../src/constants';
import styles from '@sambego/storybook-styles';
import PropTable from './components/propTable';

addParameters({
  backgrounds: [
    { name: 'Aqua lightest', value: COLOR.AQUA.LIGHTEST },
    { name: 'Neutral light', value: COLOR.NEUTRAL.LIGHT },
    { name: 'Gold lightest', value: COLOR.GOLD.LIGHTEST },
    { name: 'Mint lightest', value: COLOR.MINT.LIGHTEST },
    { name: 'Ruby lightest', value: COLOR.RUBY.LIGHTEST },
    { name: 'Teal lightest', value: COLOR.TEAL.LIGHTEST },
    { name: 'Violet lightest', value: COLOR.VIOLET.LIGHTEST },
    { name: 'Teal darkest', value: COLOR.TEAL.DARKEST },
  ],
});

addParameters({
  options: {
    showRoots: true,
    storySort: (a, b) => (a[1].kind === b[1].kind ? 0 : a[1].id.localeCompare(b[1].id, undefined, { numeric: true })),
  },
});

// addon-info
addDecorator(
  withInfo({
    inline: true,
    source: true,
    styles: (stylesheet) => {
      stylesheet.infoBody = {
        color: COLOR.TEAL.DARKEST,
        fontFamily: 'Inter-Regular',
        fontSize: '14px',
        margin: '24px 0',
        padding: '0',
      };

      stylesheet.header = {
        h1: {
          fontFamily: 'Inter-Medium',
          fontSize: '24px',
          fontWeight: 500,
          lineHeight: '30px',
          margin: 0,
        },
        h2: {
          color: COLOR.NEUTRAL.DARKEST,
          fontFamily: 'Inter-Medium',
          fontSize: '18px',
          fontWeight: 500,
          lineHeight: '24px',
          margin: '24px 0 10px 0',
        },
        body: {
          paddingTop: 10,
          marginBottom: 10,
        },
      };

      stylesheet.source = {
        h1: {
          color: COLOR.NEUTRAL.DARKEST,
          fontFamily: 'Inter-Medium',
          margin: '24px 0 10px 0',
          fontWeight: 500,
          fontSize: '18px',
          lineHeight: '24px',
          padding: '12px 0',
        },
      };

      stylesheet.propTableHead = {
        color: COLOR.TEAL.DARKEST,
        fontFamily: 'Inter-Medium',
        fontWeight: 500,
        fontSize: '16px',
        lineHeight: '21px',
        margin: '20px 0 0 0',
      };

      return stylesheet;
    },
    TableComponent: PropTable,
  }),
);

// addon-styles
addDecorator(
  styles({
    margin: '24px auto',
    maxWidth: '90%',
  }),
);

// addon-designs
addDecorator(withDesign());
<|endoftext|>


<commit_before>// @flow
import * as Constants from '../../../../constants/chat'
import * as Creators from '../../../../actions/chat/creators'
import Attachment from '.'
import createCachedSelector from 're-reselect'
import shallowEqual from 'shallowequal'
import {List} from 'immutable'
import {chatTab} from '../../../../constants/tabs'
import {compose, lifecycle} from 'recompose'
import {connect} from 'react-redux'
import {getPath} from '../../../../route-tree'

import type {OpenInFileUI} from '../../../../constants/kbfs'
import type {OwnProps} from './container'
import type {Props} from '.'
import type {TypedState} from '../../../../constants/reducer'

const getProps = createCachedSelector(
  [Constants.getMessageFromMessageKey],
  (message: Constants.TextMessage) => ({
    message: message,
  })
)((state, messageKey) => messageKey)

const mapStateToProps = (state: TypedState, {messageKey}: OwnProps) => {
  return {
    ...getProps(state, messageKey),
    // We derive the route path instead of having it passed in. We have to ensure its the path of this chat view and not any children so
    // lets just extract the root path. This makes sure the openInPopup doesn't try and push multiple attachment views if you click quickly
    routePath: getPath(state.routeTree.routeState, [chatTab]).slice(0, 2),
  }
}

const mapDispatchToProps = (dispatch: Dispatch) => ({
  _onDownloadAttachment: (selectedConversation, messageID) => {
    if (selectedConversation && messageID) {
      dispatch(Creators.saveAttachment(selectedConversation, messageID))
    }
  },
  _onEnsurePreviewLoaded: (message: Constants.AttachmentMessage) => dispatch(Creators.loadAttachmentPreview(message)),
  _onOpenInFileUI: (path: string) => dispatch(({payload: {path}, type: 'fs:openInFileUI'}: OpenInFileUI)),
  _onOpenInPopup: (message: Constants.AttachmentMessage, routePath: List<string>) => dispatch(Creators.openAttachmentPopup(message, routePath)),
})

const mergeProps = (stateProps, dispatchProps, {measure, onAction}: OwnProps) => ({
  ...stateProps,
  ...dispatchProps,
  measure,
  onAction,
  onEnsurePreviewLoaded: () => {
    const {message} = stateProps
    if (message && message.filename && !message.previewPath) {
      setImmediate(() => dispatchProps._onEnsurePreviewLoaded(message))
    }
  },
  onDownloadAttachment: () => { dispatchProps._onDownloadAttachment(stateProps.selectedConversation, stateProps.message.messageID) },
  onOpenInFileUI: () => { dispatchProps._onOpenInFileUI(stateProps.message.downloadedPath) },
  onOpenInPopup: () => { dispatchProps._onOpenInPopup(stateProps.message, stateProps.routePath) },
})

export default compose(
  connect(mapStateToProps, mapDispatchToProps, mergeProps),
  lifecycle({
    componentDidMount: function () {
      this.props.onEnsurePreviewLoaded()
    },

    componentDidUpdate: function (prevProps: Props) {
      if (this.props.measure &&
        this.props.message.previewPath !== prevProps.message.previewPath &&
        !shallowEqual(this.props.message.previewSize !== prevProps.message.previewSize)) {
        this.props.measure()
      }

      this.props.onEnsurePreviewLoaded()
    },
  })
)(Attachment)
<commit_msg>Fix outdated openInFileUi dispatchFn (#6919)<commit_after>// @flow
import * as Constants from '../../../../constants/chat'
import * as Creators from '../../../../actions/chat/creators'
import Attachment from '.'
import createCachedSelector from 're-reselect'
import shallowEqual from 'shallowequal'
import {List} from 'immutable'
import {chatTab} from '../../../../constants/tabs'
import {compose, lifecycle} from 'recompose'
import {connect} from 'react-redux'
import {getPath} from '../../../../route-tree'

import type {OpenInFileUI} from '../../../../constants/kbfs'
import type {OwnProps} from './container'
import type {Props} from '.'
import type {TypedState} from '../../../../constants/reducer'

const getProps = createCachedSelector(
  [Constants.getMessageFromMessageKey],
  (message: Constants.TextMessage) => ({
    message: message,
  })
)((state, messageKey) => messageKey)

const mapStateToProps = (state: TypedState, {messageKey}: OwnProps) => {
  return {
    ...getProps(state, messageKey),
    // We derive the route path instead of having it passed in. We have to ensure its the path of this chat view and not any children so
    // lets just extract the root path. This makes sure the openInPopup doesn't try and push multiple attachment views if you click quickly
    routePath: getPath(state.routeTree.routeState, [chatTab]).slice(0, 2),
  }
}

const mapDispatchToProps = (dispatch: Dispatch) => ({
  _onDownloadAttachment: (selectedConversation, messageID) => {
    if (selectedConversation && messageID) {
      dispatch(Creators.saveAttachment(selectedConversation, messageID))
    }
  },
  _onEnsurePreviewLoaded: (message: Constants.AttachmentMessage) => dispatch(Creators.loadAttachmentPreview(message)),
  _onOpenInFileUI: (path: string) => dispatch(({payload: {path}, type: 'fs:openInFileUI'}: OpenInFileUI)),
  _onOpenInPopup: (message: Constants.AttachmentMessage, routePath: List<string>) => dispatch(Creators.openAttachmentPopup(message, routePath)),
})

const mergeProps = (stateProps, dispatchProps, {measure, onAction}: OwnProps) => ({
  ...stateProps,
  ...dispatchProps,
  measure,
  onAction,
  onEnsurePreviewLoaded: () => {
    const {message} = stateProps
    if (message && message.filename && !message.previewPath) {
      setImmediate(() => dispatchProps._onEnsurePreviewLoaded(message))
    }
  },
  onDownloadAttachment: () => { dispatchProps._onDownloadAttachment(stateProps.selectedConversation, stateProps.message.messageID) },
  onOpenInFileUI: () => { dispatchProps._onOpenInFileUI(stateProps.message.savedPath) },
  onOpenInPopup: () => { dispatchProps._onOpenInPopup(stateProps.message, stateProps.routePath) },
})

export default compose(
  connect(mapStateToProps, mapDispatchToProps, mergeProps),
  lifecycle({
    componentDidMount: function () {
      this.props.onEnsurePreviewLoaded()
    },

    componentDidUpdate: function (prevProps: Props) {
      if (this.props.measure &&
        this.props.message.previewPath !== prevProps.message.previewPath &&
        !shallowEqual(this.props.message.previewSize !== prevProps.message.previewSize)) {
        this.props.measure()
      }

      this.props.onEnsurePreviewLoaded()
    },
  })
)(Attachment)
<|endoftext|>