<commit_before>/*
  node-http-proxy.js: Lookup table for proxy targets in node.js

  Copyright (c) 2010 Charlie Robbins

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var util = require('util'),
    events = require('events'),
    fs = require('fs'),
    url = require('url');

//
// ### function ProxyTable (router, silent)
// #### @router {Object} Object containing the host based routes
// #### @silent {Boolean} Value indicating whether we should suppress logs
// #### @hostnameOnly {Boolean} Value indicating if we should route based on __hostname string only__
// Constructor function for the ProxyTable responsible for getting
// locations of proxy targets based on ServerRequest headers; specifically
// the HTTP host header.
//
var ProxyTable = exports.ProxyTable = function (options) {
  events.EventEmitter.call(this);

  this.silent       = options.silent || options.silent !== true;
  this.target       = options.target || {};
  this.hostnameOnly = options.hostnameOnly === true;

  if (typeof options.router === 'object') {
    //
    // If we are passed an object literal setup
    // the routes with RegExps from the router
    //
    this.setRoutes(options.router);
  }
  else if (typeof options.router === 'string') {
    //
    // If we are passed a string then assume it is a
    // file path, parse that file and watch it for changes
    //
    var self = this;
    this.routeFile = options.router;
    this.setRoutes(JSON.parse(fs.readFileSync(options.router)).router);

    fs.watchFile(this.routeFile, function () {
      fs.readFile(self.routeFile, function (err, data) {
        if (err) {
          self.emit('error', err);
        }

        self.setRoutes(JSON.parse(data).router);
        self.emit('routes', self.hostnameOnly === false ? self.routes : self.router);
      });
    });
  }
  else {
    throw new Error('Cannot parse router with unknown type: ' + typeof router);
  }
};

//
// Inherit from `events.EventEmitter`
//
util.inherits(ProxyTable, events.EventEmitter);

//
// ### function setRoutes (router)
// #### @router {Object} Object containing the host based routes
// Sets the host-based routes to be used by this instance.
//
ProxyTable.prototype.setRoutes = function (router) {
  if (!router) {
    throw new Error('Cannot update ProxyTable routes without router.');
  }

  var self = this;
  this.router = router;

  if (this.hostnameOnly === false) {
    this.routes = [];

    Object.keys(router).forEach(function (path) {
      if (!/http[s]?/.test(router[path])) {
        router[path] = (self.target.https ? 'https://' : 'http://')
          + router[path];
      }

      var target = url.parse(router[path]),
          defaultPort = self.target.https ? 443 : 80;

      //
      // Setup a robust lookup table for the route:
      //
      //    {
      //      source: {
      //        regexp: /^foo.com/i,
      //        sref: 'foo.com',
      //        url: {
      //          protocol: 'http:',
      //          slashes: true,
      //          host: 'foo.com',
      //          hostname: 'foo.com',
      //          href: 'http://foo.com/',
      //          pathname: '/',
      //          path: '/'
      //        }
      //    },
      //    {
      //      target: {
      //        sref: '127.0.0.1:8000/',
      //        url: {
      //          protocol: 'http:',
      //          slashes: true,
      //          host: '127.0.0.1:8000',
      //          hostname: '127.0.0.1',
      //          href: 'http://127.0.0.1:8000/',
      //          pathname: '/',
      //          path: '/'
      //        }
      //    },
      //
      self.routes.push({
        source: {
          regexp: new RegExp('^' + path, 'i'),
          sref: path,
          url: url.parse('http://' + path)
        },
        target: {
          sref: target.hostname + ':' + (target.port || defaultPort) + target.path,
          url: target
        }
      });
    });
  }
};

//
// ### function getProxyLocation (req)
// #### @req {ServerRequest} The incoming server request to get proxy information about.
// Returns the proxy location based on the HTTP Headers in the  ServerRequest `req`
// available to this instance.
//
ProxyTable.prototype.getProxyLocation = function (req) {
  if (!req || !req.headers || !req.headers.host) {
    return null;
  }

  var source = req.headers.host.split(':');
  var target = source[0];
  if (this.hostnameOnly === true) {
    if (this.router.hasOwnProperty(target)) {
      var location = this.router[target].split(':'),
          host = location[0],
          port = location.length === 1 ? 80 : location[1];

      return {
        port: port,
        host: host,
        source: {
          host: source[0],
          port: source.length === 1 ? 80 : source[1]
        }
      };
    }
  }
  else {
    target += req.url;
    for (var i in this.routes) {
      var route = this.routes[i];
      if (target.match(route.source.regexp)) {
        //
        // Attempt to perform any path replacement for differences
        // between the source path and the target path. This replaces the
        // path's part of the URL to the target's part of the URL.
        //
        // 1. Parse the request URL
        // 2. Replace any portions of the source path with the target path
        // 3. Set the request URL to the formatted URL with replacements.
        //
        var parsed = url.parse(req.url);

        parsed.pathname = parsed.pathname.replace(
          route.source.url.pathname,
          route.target.url.pathname
        );

        req.url = url.format(parsed);

        return {
          protocol: route.target.url.protocol.replace(':', ''),
          host: route.target.url.hostname,
          port: route.target.url.port
            || (this.target.https ? 443 : 80),
          source: {
            protocol: parsed.protocol.replace(':',''),
            host: parsed.hostname,
            port: parsed.port
              || (parsed.protocol == 'https:' ? 443 : 80),
            pathname: route.source.url.pathname
          }
        };
      }
    }
  }

  return null;
};

//
// ### close function ()
// Cleans up the event listeneners maintained
// by this instance.
//
ProxyTable.prototype.close = function () {
  if (typeof this.routeFile === 'string') {
    fs.unwatchFile(this.routeFile);
  }
};
<commit_msg>ProxyTable bugfix<commit_after>/*
  node-http-proxy.js: Lookup table for proxy targets in node.js

  Copyright (c) 2010 Charlie Robbins

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var util = require('util'),
    events = require('events'),
    fs = require('fs'),
    url = require('url');

//
// ### function ProxyTable (router, silent)
// #### @router {Object} Object containing the host based routes
// #### @silent {Boolean} Value indicating whether we should suppress logs
// #### @hostnameOnly {Boolean} Value indicating if we should route based on __hostname string only__
// Constructor function for the ProxyTable responsible for getting
// locations of proxy targets based on ServerRequest headers; specifically
// the HTTP host header.
//
var ProxyTable = exports.ProxyTable = function (options) {
  events.EventEmitter.call(this);

  this.silent       = options.silent || options.silent !== true;
  this.target       = options.target || {};
  this.hostnameOnly = options.hostnameOnly === true;

  if (typeof options.router === 'object') {
    //
    // If we are passed an object literal setup
    // the routes with RegExps from the router
    //
    this.setRoutes(options.router);
  }
  else if (typeof options.router === 'string') {
    //
    // If we are passed a string then assume it is a
    // file path, parse that file and watch it for changes
    //
    var self = this;
    this.routeFile = options.router;
    this.setRoutes(JSON.parse(fs.readFileSync(options.router)).router);

    fs.watchFile(this.routeFile, function () {
      fs.readFile(self.routeFile, function (err, data) {
        if (err) {
          self.emit('error', err);
        }

        self.setRoutes(JSON.parse(data).router);
        self.emit('routes', self.hostnameOnly === false ? self.routes : self.router);
      });
    });
  }
  else {
    throw new Error('Cannot parse router with unknown type: ' + typeof router);
  }
};

//
// Inherit from `events.EventEmitter`
//
util.inherits(ProxyTable, events.EventEmitter);

//
// ### function setRoutes (router)
// #### @router {Object} Object containing the host based routes
// Sets the host-based routes to be used by this instance.
//
ProxyTable.prototype.setRoutes = function (router) {
  if (!router) {
    throw new Error('Cannot update ProxyTable routes without router.');
  }

  var self = this;
  this.router = router;

  if (this.hostnameOnly === false) {
    this.routes = [];

    Object.keys(router).forEach(function (path) {
      if (!/http[s]?/.test(router[path])) {
        router[path] = (self.target.https ? 'https://' : 'http://')
          + router[path];
      }

      var target = url.parse(router[path]),
          defaultPort = self.target.https ? 443 : 80;

      //
      // Setup a robust lookup table for the route:
      //
      //    {
      //      source: {
      //        regexp: /^foo.com/i,
      //        sref: 'foo.com',
      //        url: {
      //          protocol: 'http:',
      //          slashes: true,
      //          host: 'foo.com',
      //          hostname: 'foo.com',
      //          href: 'http://foo.com/',
      //          pathname: '/',
      //          path: '/'
      //        }
      //    },
      //    {
      //      target: {
      //        sref: '127.0.0.1:8000/',
      //        url: {
      //          protocol: 'http:',
      //          slashes: true,
      //          host: '127.0.0.1:8000',
      //          hostname: '127.0.0.1',
      //          href: 'http://127.0.0.1:8000/',
      //          pathname: '/',
      //          path: '/'
      //        }
      //    },
      //
      self.routes.push({
        source: {
          regexp: new RegExp('^' + path, 'i'),
          sref: path,
          url: url.parse('http://' + path)
        },
        target: {
          sref: target.hostname + ':' + (target.port || defaultPort) + target.path,
          url: target
        }
      });
    });
  }
};

//
// ### function getProxyLocation (req)
// #### @req {ServerRequest} The incoming server request to get proxy information about.
// Returns the proxy location based on the HTTP Headers in the  ServerRequest `req`
// available to this instance.
//
ProxyTable.prototype.getProxyLocation = function (req) {
  if (!req || !req.headers || !req.headers.host) {
    return null;
  }

  var source = req.headers.host.split(':');
  var target = source[0];
  if (this.hostnameOnly === true) {
    if (this.router.hasOwnProperty(target)) {
      var location = this.router[target].split(':'),
          host = location[0],
          port = location.length === 1 ? 80 : location[1];

      return {
        port: port,
        host: host,
        source: {
          host: source[0],
          port: source.length === 1 ? 80 : source[1]
        }
      };
    }
  }
  else {
    target += req.url;
    for (var i in this.routes) {
      var route = this.routes[i];
      if (target.match(route.source.regexp)) {
        //
        // Attempt to perform any path replacement for differences
        // between the source path and the target path. This replaces the
        // path's part of the URL to the target's part of the URL.
        //
        // 1. Parse the request URL
        // 2. Replace any portions of the source path with the target path
        // 3. Set the request URL to the formatted URL with replacements.
        //
        var parsed = url.parse(req.url);

        parsed.pathname = parsed.pathname.replace(
          route.source.url.pathname,
          (route.target.url.pathname!='/' ? route.target.url.pathname : '')
        );

        req.url = url.format(parsed);

        return {
          protocol: route.target.url.protocol.replace(':', ''),
          host: route.target.url.hostname,
          port: route.target.url.port
            || (this.target.https ? 443 : 80),
          // source: {
          //   protocol: parsed.protocol.replace(':',''),
          //   host: parsed.hostname,
          //   port: parsed.port
          //     || (parsed.protocol == 'https:' ? 443 : 80),
          //   pathname: route.source.url.pathname
          // }
        };
      }
    }
  }

  return null;
};

//
// ### close function ()
// Cleans up the event listeneners maintained
// by this instance.
//
ProxyTable.prototype.close = function () {
  if (typeof this.routeFile === 'string') {
    fs.unwatchFile(this.routeFile);
  }
};
<|endoftext|>


<commit_before>var path = require('path');
var node_modules_dir = path.resolve(__dirname, 'node_modules');

var config = {
  entry: path.resolve(__dirname, '../app/main.js'),
  output: {
		 path: path.resolve(__dirname, '../dist'),
		 filename: 'app.js'
  },
  module: {
      loaders: [
        { test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/},/*,
        { test: /\.scss$/, loader: "style-loader!css-loader!sass-loader?includePaths[]="+BS_ASSETS }*/
        {test: /\.less$/, loader: 'style-loader!css-loader!less-loader'},
        {test: /\.css$/, loader: 'style-loader!css-loader'}
      ]
    },
    resolve: {
      extensions: ['', '.js', '.jsx'],
      // root: [path.join(__dirname, "public", "javascripts")],
      modulesDirectories: ['node_modules']
    }

};

module.exports = config;<commit_msg>optimize js for production<commit_after>var path = require('path');
var webpack = require('webpack');

var node_modules_dir = path.resolve(__dirname, 'node_modules');

var config = {
  entry: path.resolve(__dirname, '../app/main.js'),
  output: {
		 path: path.resolve(__dirname, '../dist'),
		 filename: 'app.js'
  },
  module: {
      loaders: [
        { test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/},/*,
        { test: /\.scss$/, loader: "style-loader!css-loader!sass-loader?includePaths[]="+BS_ASSETS }*/
        {test: /\.less$/, loader: 'style-loader!css-loader!less-loader'},
        {test: /\.css$/, loader: 'style-loader!css-loader'}
      ]
    },
    plugins: [
		//optimizations
		new webpack.optimize.DedupePlugin(),
		new webpack.optimize.OccurenceOrderPlugin(),
		new webpack.optimize.UglifyJsPlugin({
		  compress: {
		    warnings: false,
		    screw_ie8: true,
		    sequences: true,
		    dead_code: true,
		    drop_debugger: true,
		    comparisons: true,
		    conditionals: true,
		    evaluate: true,
		    booleans: true,
		    loops: true,
		    unused: true,
		    hoist_funs: true,
		    if_return: true,
		    join_vars: true,
		    cascade: true,
		    drop_console: true
		  },
		  output: {
		    comments: false
		  }
		})
    ],
    resolve: {
      extensions: ['', '.js', '.jsx'],
      // root: [path.join(__dirname, "public", "javascripts")],
      modulesDirectories: ['node_modules']
    }

};

module.exports = config;<|endoftext|>


<commit_before>function PostController(post, Auth) {
  var ctrl = this;

  ctrl.data = post.data;

  var currentUser;

  Auth.currentUser().then(function (user) {
    ctrl.currentUser = user
  })
}

angular
  .module('app')
  .controller('PostController', PostController)
<commit_msg>added post save behavior<commit_after>function PostController(post, Auth, PostsService, $stateParams) {
  var ctrl = this;

  if (post) {
    ctrl.data = post.data;
  }

  var currentUser;

  Auth.currentUser().then(function (user) {
    ctrl.currentUser = user
  })

  ctrl.editPost = function () {
    if (ctrl.currentUser.id === ctrl.data.author.id) {
      return true;
    } else {
      return false;
    }
  }

  ctrl.save = function () {
    if ($stateParams.id && ctrl.editPost()) {
      PostsService.updatePost($stateParams.id, ctrl.data);
    } else {
      PostsService.addPost(ctrl.data)
    }
  }
}

angular
  .module('app')
  .controller('PostController', PostController)
<|endoftext|>


<commit_before>/**
 * Callback at the end of the loop
 *
 * @callback actionCallback
 * @param {Object} options - Values in the end of the path
 * @param {Number} options.indexPath - Current index in the array path
 * @param {Object|Array} options.target - Target object or target array
 * @param {*} [options.current] - Current value in target object
 * @param {*} [options.key] - Current value in the path
 * @param {*} [options.previous] - Previous value in target object
 * @return {*}
 */

/**
 * @module bubble-gum-goto
 */

/**
 *
 * It receives a input path and a callback(actionCallback), It returns the function **_goto**,
 * the *_goto* function receives a target object or target array,
 * when the *_goto* is called, this navigates the target object or target array using the input path,
 * when it reaches the end of the path, *_goto* executs the callback and returns the result
 *
 * @alias module:bubble-gum-goto
 * @example
 *
 * ```javascript
 *
 * const goto = require('bubble-gum-goto');
 *
 * const target = {
 *   root: {
 *     foo: 'bar',
 *   },
 * };
 *
 * goto(['root', 'foo'], (result) => {
 *   const {
 *     indexPath,
 *     previous,
 *     target,
 *     current,
 *     key,
 *   } = result;
 *   console.log(indexPath);  // =>  1
 *   console.log(previous);  // => { foo: 'bar' }
 *   console.log(target);  // => { root: { foo: 'bar' }, arr: [ [ [Object] ] ] }
 *   console.log(current);  // => bar
 *   console.log(key);  // => foo
 * })(target);
 *
 * const result = goto(['root', 'foo'], ({current, key}) => (current + '-' + key))(target);
 * console.log(result); // => bar-foo
 *
 * ```
 *
 * @param {Array} path - Path to property
 * @param {actionCallback} fn - Callback with the action that will be called at the end of the path
 * @return {Function}
 */
export default function goto(path, fn) {
  const { length: len } = path;
  return function _goto(target) {
    let previousValue, currentPath, indexPath;
    let currentValue = target;
    let init = 0;
    while((undefined !== currentValue) && (init < len)) {
      if (init > 0) {
        previousValue = currentValue;
      }
      currentPath = path[init];
      currentValue = currentValue[currentPath];
      indexPath = init;
      init++;
    }
    return fn({
      current: currentValue,
      key: currentPath,
      indexPath,
      previous: previousValue,
      target,
    });
  };
};
<commit_msg>Update index.js<commit_after>/**
 * Callback at the end of the loop
 *
 * @callback actionCallback
 * @param {Object} options - Values in the end of the path
 * @param {Number} options.indexPath - Current index in the array path
 * @param {Object|Array} options.target - Target object or target array
 * @param {*} [options.current] - Current value in target object
 * @param {*} [options.key] - Current value in the path
 * @param {*} [options.previous] - Previous value in target object
 * @return {*}
 */

/**
 * @module bubble-gum-goto
 */

/**
 *
 * It receives a input path and a callback(actionCallback), It returns the function **_goto**,
 * the *_goto* function receives a target object or target array,
 * when the *_goto* is called, this navigates the target object or target array using the input path,
 * when it reaches the end of the path, *_goto* executs the callback and returns the result
 *
 * @alias module:bubble-gum-goto
 * @example
 *
 * ```javascript
 *
 * const goto = require('bubble-gum-goto');
 *
 * const target = {
 *   root: {
 *     foo: 'bar',
 *   },
 * };
 *
 * goto(['root', 'foo'], (result) => {
 *   const {
 *     indexPath,
 *     previous,
 *     target,
 *     current,
 *     key,
 *   } = result;
 *   console.log(indexPath);  // =>  1
 *   console.log(previous);  // => { foo: 'bar' }
 *   console.log(target);  // => { root: { foo: 'bar' }, arr: [ [ [Object] ] ] }
 *   console.log(current);  // => bar
 *   console.log(key);  // => foo
 * })(target);
 *
 * const result = goto(['root', 'foo'], ({current, key}) => (current + '-' + key))(target);
 * console.log(result); // => bar-foo
 *
 * ```
 *
 * @param {Array} path - Path to property
 * @param {actionCallback} fn - Callback with the action that will be called at the end of the path
 * @return {Function}
 */
export default function goto(path, fn) {
  const { length: len } = path;
  return function _goto(target) {
    let previousValue, currentPath, indexPath;
    let currentValue = target;
    let init = 0;
    while((undefined !== currentValue && null !== currentValue) && (init < len)) {
      if (init > 0) {
        previousValue = currentValue;
      }
      currentPath = path[init];
      currentValue = currentValue[currentPath];
      indexPath = init;
      init++;
    }
    return fn({
      current: currentValue,
      key: currentPath,
      indexPath,
      previous: previousValue,
      target,
    });
  };
};
<|endoftext|>


<commit_before>/* global document describe it beforeEach afterEach window */
import sinon from 'sinon';
import { expect } from 'chai';
import { formatSSN, ssnInput, bindUIEvents } from '../base/ssnInput';

describe('ssnInput init', () => {
  afterEach(() => {
    document.querySelectorAll.restore();
  });

  it('should call getElements once with the correct selector', () => {
    sinon.spy(document, 'querySelectorAll');
    ssnInput();
    expect(document.querySelectorAll.getCall(0).args[0])
      .eql('[data-sprk-input="ssn"]');
  });
});

describe('formatSSN tests', () => {
  it('should format the ssn in the XXX-XX-XXXX style', () => {
    const div = document.createElement('input');
    div.value = '123456789';
    expect(formatSSN(div.value)).eql('123-45-6789');
  });
});

describe('ssnInput UI Events tests', () => {
  let inputContainer;
  let input;
  let checkbox;
  let errorContainer;
  let event;

  beforeEach(() => {
    inputContainer = document.createElement('div');
    input = document.createElement('input');
    input.type = 'password';
    input
      .setAttribute(
        'pattern',
        '(^(?!666|000|9\\d{2})'
        + '\\d{3}([- ]{0,1})(?!00)\\d{2}\\1(?!0{4})\\2\\d{4}$)|^$',
      );
    sinon.spy(input, 'addEventListener');
    checkbox = document.createElement('input');
    sinon.spy(checkbox, 'addEventListener');
    checkbox.type = 'checkbox';
    errorContainer = document.createElement('div');
    inputContainer.appendChild(input);
    inputContainer.appendChild(checkbox);
    inputContainer.appendChild(errorContainer);
    document.body.appendChild(inputContainer);
    bindUIEvents(inputContainer);
  });

  afterEach(() => {
    document.body.innerHTML = '';
    input.addEventListener.restore();
    checkbox.addEventListener.restore();
  });

  it('should bind the input event', () => {
    expect(input.addEventListener.getCall(0).args[0]).eql('input');
  });

  it('should format when input is triggered', () => {
    input.value = '123456789';
    event = new window.Event('input');
    input.dispatchEvent(event);
    expect(input.getAttribute('aria-invalid')).eql('false');
    expect(input.value).eql('123-45-6789');
  });

  it('should not format when input is triggered with invalid data', () => {
    input.value = 'asdf';
    event = new window.Event('input');
    input.dispatchEvent(event);
    expect(input.getAttribute('aria-invalid')).eql('true');
    expect(input.value).eql('asdf');
  });

  it('should bind the blur event', () => {
    expect(input.addEventListener.getCall(1).args[0]).eql('blur');
  });

  it('should format when blur is triggered with valid data', () => {
    input.value = '123456789';
    event = new window.Event('blur');
    input.dispatchEvent(event);
    expect(input.getAttribute('aria-invalid')).eql('false');
    expect(input.value).eql('123-45-6789');
  });

  it('should not format when blur is triggered with invalid data', () => {
    input.value = 'asdf';
    event = new window.Event('blur');
    input.dispatchEvent(event);
    expect(input.getAttribute('aria-invalid')).eql('true');
    expect(input.value).eql('asdf');
  });

  it('should bind the change event to the checkbox', () => {
    expect(checkbox.addEventListener.calledOnce).eql(true);
    expect(checkbox.addEventListener.getCall(0).args[0]).eql('change');
  });

  it('should change the type of input when the checkbox is changed', () => {
    expect(input.type).eql('password');
    event = new window.Event('change');
    checkbox.dispatchEvent(event);
    expect(input.type).eql('text');
  });
});
<commit_msg>update ssnInput import path<commit_after>/* global document describe it beforeEach afterEach window */
import sinon from 'sinon';
import { expect } from 'chai';
import { formatSSN, ssnInput, bindUIEvents } from '../base/inputs/ssnInput';

describe('ssnInput init', () => {
  afterEach(() => {
    document.querySelectorAll.restore();
  });

  it('should call getElements once with the correct selector', () => {
    sinon.spy(document, 'querySelectorAll');
    ssnInput();
    expect(document.querySelectorAll.getCall(0).args[0])
      .eql('[data-sprk-input="ssn"]');
  });
});

describe('formatSSN tests', () => {
  it('should format the ssn in the XXX-XX-XXXX style', () => {
    const div = document.createElement('input');
    div.value = '123456789';
    expect(formatSSN(div.value)).eql('123-45-6789');
  });
});

describe('ssnInput UI Events tests', () => {
  let inputContainer;
  let input;
  let checkbox;
  let errorContainer;
  let event;

  beforeEach(() => {
    inputContainer = document.createElement('div');
    input = document.createElement('input');
    input.type = 'password';
    input
      .setAttribute(
        'pattern',
        '(^(?!666|000|9\\d{2})'
        + '\\d{3}([- ]{0,1})(?!00)\\d{2}\\1(?!0{4})\\2\\d{4}$)|^$',
      );
    sinon.spy(input, 'addEventListener');
    checkbox = document.createElement('input');
    sinon.spy(checkbox, 'addEventListener');
    checkbox.type = 'checkbox';
    errorContainer = document.createElement('div');
    inputContainer.appendChild(input);
    inputContainer.appendChild(checkbox);
    inputContainer.appendChild(errorContainer);
    document.body.appendChild(inputContainer);
    bindUIEvents(inputContainer);
  });

  afterEach(() => {
    document.body.innerHTML = '';
    input.addEventListener.restore();
    checkbox.addEventListener.restore();
  });

  it('should bind the input event', () => {
    expect(input.addEventListener.getCall(0).args[0]).eql('input');
  });

  it('should format when input is triggered', () => {
    input.value = '123456789';
    event = new window.Event('input');
    input.dispatchEvent(event);
    expect(input.getAttribute('aria-invalid')).eql('false');
    expect(input.value).eql('123-45-6789');
  });

  it('should not format when input is triggered with invalid data', () => {
    input.value = 'asdf';
    event = new window.Event('input');
    input.dispatchEvent(event);
    expect(input.getAttribute('aria-invalid')).eql('true');
    expect(input.value).eql('asdf');
  });

  it('should bind the blur event', () => {
    expect(input.addEventListener.getCall(1).args[0]).eql('blur');
  });

  it('should format when blur is triggered with valid data', () => {
    input.value = '123456789';
    event = new window.Event('blur');
    input.dispatchEvent(event);
    expect(input.getAttribute('aria-invalid')).eql('false');
    expect(input.value).eql('123-45-6789');
  });

  it('should not format when blur is triggered with invalid data', () => {
    input.value = 'asdf';
    event = new window.Event('blur');
    input.dispatchEvent(event);
    expect(input.getAttribute('aria-invalid')).eql('true');
    expect(input.value).eql('asdf');
  });

  it('should bind the change event to the checkbox', () => {
    expect(checkbox.addEventListener.calledOnce).eql(true);
    expect(checkbox.addEventListener.getCall(0).args[0]).eql('change');
  });

  it('should change the type of input when the checkbox is changed', () => {
    expect(input.type).eql('password');
    event = new window.Event('change');
    checkbox.dispatchEvent(event);
    expect(input.type).eql('text');
  });
});
<|endoftext|>


<commit_before>const apiPutStartTask = {
    schema: {
        summary: 'Start a Qlik Sense task.',
        description:
            "An optional array of zero or more objects can be passed in the message body. It is used to pass additional info related to the reload task being started.\n\nCurrently supported values in this array are:\n\n- A key-value pair that will be stored in Butler's KV store. If Butler's key-value store is not enabled, any key-value information passed in this parameter will simply be ignored.\nSetting `ttl=0` disables the TTL feature, i.e. the KV pair will not expire.\n- A task identified by its taskId that should be started.\n- Tasks identified by tags set on tasks in the QMC.\n- Tasks identified by custom properties set in the QMC.\n\nThis parameter uses a generic JSON/object format (type + payload).\nIt's thus possible to add new integrations in future Butler versions.",
        params: {
            type: 'object',
            properties: {
                taskId: {
                    type: 'string',
                    description: 'ID of Qlik Sense task.',
                    example: '210832b5-6174-4572-bd19-3e61eda675ef',
                },
            },
        },
        querystring: {
            type: 'object',
            properties: {
                allTaskIdsMustExist: {
                    type: 'boolean',
                    description:
                        'If set to `true`, all specified taskIds must exist. If one or more taskIds does not exist in the Sense server, *no* tasks will be started.\n\nIf set to `false`, all existing taskIds will be started. Missing/invalid taskIds will be ignored.\n\nIn either case, missing/invalid taskIds will be reported in the result set back to the client calling the API.\n\nNote: Tasks started by specifying tags and/or custom properties are not affected by this.',
                    example: true,
                },
            },
        },
        body: {
            type: 'array',
            description: 'Optional object with extra info.',
            items: {
                type: 'object',
                properties: {
                    type: {
                        type: 'string',
                        example: 'keyvaluestore',
                        enum: ['keyvaluestore', 'starttaskid', 'starttasktag', 'starttaskcustomproperty'],
                    },
                    payload: {
                        type: 'object',
                    },
                },
            },
            example: [
                {
                    type: 'keyvaluestore',
                    payload: { namespace: 'MyFineNamespace', key: 'AnImportantKey', value: 'TheValue', ttl: 10000 },
                },
                {
                    type: 'starttaskid',
                    payload: {
                        taskId: '7552d9fc-d1bb-4975-9a38-18357de531ea',
                    },
                },
                {
                    type: 'starttaskid',
                    payload: {
                        taskId: 'fb0f317d-da91-4b86-aafa-0174ae1e8c8',
                    },
                },
                {
                    type: 'starttasktag',
                    payload: {
                        tag: 'startTask1',
                    },
                },
                {
                    type: 'starttasktag',
                    payload: {
                        tag: 'startTask2',
                    },
                },
                {
                    type: 'starttaskcustomproperty',
                    payload: {
                        customPropertyName: 'taskGroup',
                        customPropertyValue: 'tasks2',
                    },
                },
            ],
        },
        response: {
            200: {
                description: 'Task successfully started.',
                type: 'object',
                example: {
                    tasksId: {
                        started: [
                            {
                                taskId: 'e3b27f50-b1c0-4879-88fc-c7cdd9c1cf3e',
                                taskName: 'Reload task of App1',
                            },
                            {
                                taskId: '7552d9fc-d1bb-4975-9a38-18357de531ea',
                                taskName: 'Reload task of App2',
                            },
                            {
                                taskId: 'fb0f317d-da91-4b86-aafa-0174ae1e8c8f',
                                taskName: 'Reload task of App3',
                            },
                        ],
                        invalid: [],
                    },
                    tasksTag: [
                        {
                            taskId: 'e3b27f50-b1c0-4879-88fc-c7cdd9c1cf3e',
                            taskName: 'Reload task of App1',
                        },
                        {
                            taskId: '7552d9fc-d1bb-4975-9a38-18357de531ea',
                            taskName: 'Reload task of App2',
                        },
                        {
                            taskId: 'fb0f317d-da91-4b86-aafa-0174ae1e8c8f',
                            taskName: 'Reload task of App3',
                        },
                        {
                            taskId: 'fb0f317d-da91-4b86-aafa-0174ae1e8c8f',
                            taskName: 'Reload task of App3',
                        },
                    ],
                    tasksCP: [
                        {
                            taskId: 'e3b27f50-b1c0-4879-88fc-c7cdd9c1cf3e',
                            taskName: 'Reload task of App1',
                        },
                        {
                            taskId: '7552d9fc-d1bb-4975-9a38-18357de531ea',
                            taskName: 'Reload task of App2',
                        },
                        {
                            taskId: 'fb0f317d-da91-4b86-aafa-0174ae1e8c8f',
                            taskName: 'Reload task of App3',
                        },
                        {
                            taskId: '7552d9fc-d1bb-4975-9a38-18357de531ea',
                            taskName: 'Reload task of App2',
                        },
                    ],
                },
            },
            400: {
                description: 'Required parameter missing.',
                type: 'object',
                properties: {
                    statusCode: { type: 'number' },
                    code: { type: 'string' },
                    error: { type: 'string' },
                    message: { type: 'string' },
                    time: { type: 'string' },
                },
            },
            500: {
                description: 'Internal error.',
                type: 'object',
                properties: {
                    statusCode: { type: 'number' },
                    code: { type: 'string' },
                    error: { type: 'string' },
                    message: { type: 'string' },
                    time: { type: 'string' },
                },
            },
        },
    },
};

module.exports = {
    apiPutStartTask,
};
<commit_msg>docs: Fix API docs for starting tasks<commit_after>const apiPutStartTask = {
    schema: {
        summary: 'Start a Qlik Sense task.',
        description:
            "An optional array of zero or more objects can be passed in the message body. It is used to pass additional info related to the reload task being started.\n\nCurrently supported values in this array are:\n\n- A key-value pair that will be stored in Butler's KV store. If Butler's key-value store is not enabled, any key-value information passed in this parameter will simply be ignored.\nSetting `ttl=0` disables the TTL feature, i.e. the KV pair will not expire.\n- A task identified by its taskId that should be started.\n- Tasks identified by tags set on tasks in the QMC.\n- Tasks identified by custom properties set in the QMC.\n\nThis parameter uses a generic JSON/object format (type + payload).\nIt's thus possible to add new integrations in future Butler versions.",
        params: {
            type: 'object',
            properties: {
                taskId: {
                    type: 'string',
                    description:
                        'ID of Qlik Sense task.\nButler will ignore the "magic" task ID of "-" (=dash, hyphen). This ID will not be reported as invalid.',
                    example: '210832b5-6174-4572-bd19-3e61eda675ef',
                },
            },
        },
        querystring: {
            type: 'object',
            properties: {
                allTaskIdsMustExist: {
                    type: 'boolean',
                    description:
                        'If set to `true`, all specified taskIds must exist. If one or more taskIds does not exist in the Sense server, *no* tasks will be started.\n\nIf set to `false`, all existing taskIds will be started. Missing/invalid taskIds will be ignored.\n\nIn either case, missing/invalid taskIds will be reported in the result set back to the client calling the API.\n\nNote: Tasks started by specifying tags and/or custom properties are not affected by this.',
                    example: true,
                },
            },
        },
        body: {
            type: 'array',
            description: 'Optional object with extra info.',
            items: {
                type: 'object',
                properties: {
                    type: {
                        type: 'string',
                        example: 'keyvaluestore',
                        enum: ['keyvaluestore', 'starttaskid', 'starttasktag', 'starttaskcustomproperty'],
                    },
                    payload: {
                        type: 'object',
                    },
                },
            },
            example: [
                {
                    type: 'starttaskid',
                    payload: {
                        taskId: '7552d9fc-d1bb-4975-9a38-18357de531ea',
                    },
                },
                {
                    type: 'starttasktag',
                    payload: {
                        tag: 'startTask1',
                    },
                },
                {
                    type: 'starttaskcustomproperty',
                    payload: {
                        customPropertyName: 'taskGroup',
                        customPropertyValue: 'tasks2',
                    },
                },
                {
                    type: 'keyvaluestore',
                    payload: { namespace: 'MyFineNamespace', key: 'AnImportantKey', value: 'TheValue', ttl: 10000 },
                },
            ],
        },
        response: {
            200: {
                description: 'Task successfully started.',
                type: 'object',
                example: {
                    tasksId: {
                        started: [
                            {
                                taskId: 'e3b27f50-b1c0-4879-88fc-c7cdd9c1cf3e',
                                taskName: 'Reload task of App1',
                            },
                        ],
                        invalid: [
                            {
                                taskId: 'abc',
                            },
                        ],
                        denied: [
                            {
                                taskId: 'a1a11a11-b1c0-4879-88fc-c7cdd9c1cf3e',
                            },
                        ],
                    },
                    tasksTag: [
                        {
                            taskId: 'e3b27f50-b1c0-4879-88fc-c7cdd9c1cf3e',
                            taskName: 'Reload task of App1',
                        },
                    ],
                    tasksTagDenied: [
                        {
                            tag: 'startTask_invalid1',
                        },
                    ],
                    tasksCP: [
                        {
                            taskId: 'e3b27f50-b1c0-4879-88fc-c7cdd9c1cf3e',
                            taskName: 'Reload task of App1',
                        },
                    ],
                    tasksCPDenied: [
                        {
                            name: 'taskGroup',
                            value: 'cp_value_denied1',
                        },
                    ],
                },
            },
            400: {
                description: 'Required parameter missing.',
                type: 'object',
                properties: {
                    statusCode: { type: 'number' },
                    code: { type: 'string' },
                    error: { type: 'string' },
                    message: { type: 'string' },
                    time: { type: 'string' },
                },
            },
            500: {
                description: 'Internal error.',
                type: 'object',
                properties: {
                    statusCode: { type: 'number' },
                    code: { type: 'string' },
                    error: { type: 'string' },
                    message: { type: 'string' },
                    time: { type: 'string' },
                },
            },
        },
    },
};

module.exports = {
    apiPutStartTask,
};
<|endoftext|>


<commit_before>/* Base phone module for OpenERP
   Copyright (C) 2013-2014 Alexis de Lattre <alexis@via.ecp.fr>
   The licence is in the file __openerp__.py */

openerp.base_phone = function (instance) {

    var _t = instance.web._t;

    instance.base_phone.FieldPhone = instance.web.form.FieldChar.extend({
        template: 'FieldPhone',
        initialize_content: function() {
            this._super();
            var $button = this.$el.find('button');
            $button.click(this.on_button_clicked);
            this.setupFocus($button);
        },
        render_value: function() {
            if (!this.get('effective_readonly')) {
                this._super();
            } else {
                var self = this;
                var phone_num = this.get('value');
                //console.log('BASE_PHONE phone_num = %s', phone_num);
                var href = '#';
                var href_text = '';
                if (phone_num) {
                  href = 'tel:' + phone_num;
                  href_text = formatInternational('', phone_num) || '';
                }
                if (href_text) {
                    this.$el.find('a.oe_form_uri').attr('href', href).text(href_text);
                    this.$el.find('span.oe_form_char_content').text('');
                } else {
                    this.$el.find('a.oe_form_uri').attr('href', '').text('');
                    this.$el.find('span.oe_form_char_content').text(phone_num || '');
                }
                var click2dial_text = '';
                if (href_text && !this.options.dial_button_invisible) {
                  click2dial_text = _t('Dial');
                }
                this.$el.find('#click2dial')
                    .text(click2dial_text)
                    .on('click', function(ev) {
                        self.do_notify(
                            _t('Click2dial started'),
                            _t('Unhook your ringing phone'));
                        var arg = {
                            'phone_number': phone_num,
                            'click2dial_model': self.view.dataset.model,
                            'click2dial_id': self.view.datarecord.id};
                        self.rpc('/base_phone/click2dial', arg).done(function(r) {
                            //console.log('Click2dial r=%s', JSON.stringify(r));
                            if (r === false) {
                                self.do_warn("Click2dial failed");
                            } else if (typeof r === 'object') {
                                self.do_notify(
                                    _t('Click2dial successfull'),
                                    _t('Number dialed:') + ' ' + r.dialed_number);
                                if (r.action_model) {
                                    var context = {
                                        'click2dial_model': self.view.dataset.model,
                                        'click2dial_id': self.view.datarecord.id,
                                        'phone_number': phone_num,
                                        };
                                    var action = {
                                        name: r.action_name,
                                        type: 'ir.actions.act_window',
                                        res_model: r.action_model,
                                        view_mode: 'form',
                                        views: [[false, 'form']],
                                        target: 'new',
                                        context: context,
                                        };
                                    instance.client.action_manager.do_action(action);
                                }
                            }
                        });
                    });
            }
        },
        on_button_clicked: function() {
            location.href = 'tel:' + this.get('value');
        }
    });

    instance.web.form.widgets.add('phone', 'instance.base_phone.FieldPhone');

    instance.base_phone.FieldFax = instance.web.form.FieldChar.extend({
        template: 'FieldFax',
        initialize_content: function() {
            this._super();
            var $button = this.$el.find('button');
            $button.click(this.on_button_clicked);
            this.setupFocus($button);
        },
        render_value: function() {
            if (!this.get('effective_readonly')) {
                this._super();
            } else {
                var fax_num = this.get('value');
                //console.log('BASE_PHONE fax_num = %s', fax_num);
                var href = '#';
                var href_text = '';
                if (fax_num) {
                    href = 'fax:' + fax_num;
                    href_text = formatInternational('', fax_num) || '';
                }
                if (href_text) {
                    this.$el.find('a.oe_form_uri').attr('href', href).text(href_text);
                    this.$el.find('span.oe_form_char_content').text('');
                } else {
                    this.$el.find('a.oe_form_uri').attr('href', '').text('');
                    this.$el.find('span.oe_form_char_content').text(fax_num || '');
                }
            }
        },
        on_button_clicked: function() {
            location.href = 'fax:' + this.get('value');
        }
    });

    instance.web.form.widgets.add('fax', 'instance.base_phone.FieldFax');

    /* ability to add widget="phone" in TREE view */
    var _super_list_char_format_ = instance.web.list.Char.prototype._format;
    instance.web.list.Char.prototype._format = function(row_data, options) {
        res = _super_list_char_format_.call(this, row_data, options);
        var value = row_data[this.id].value;
        if (value && this.widget === 'phone') {
            return formatInternational('', value);
        }
        return res;
    };

};
<commit_msg>Fix bug #20 Multiple click2dial when previous click2dial failed<commit_after>/* Base phone module for OpenERP
   Copyright (C) 2013-2014 Alexis de Lattre <alexis@via.ecp.fr>
   The licence is in the file __openerp__.py */

openerp.base_phone = function (instance) {

    var _t = instance.web._t;

    instance.base_phone.FieldPhone = instance.web.form.FieldChar.extend({
        template: 'FieldPhone',
        initialize_content: function() {
            this._super();
            var $button = this.$el.find('button');
            $button.click(this.on_button_clicked);
            this.setupFocus($button);
        },
        render_value: function() {
            if (!this.get('effective_readonly')) {
                this._super();
            } else {
                var self = this;
                var phone_num = this.get('value');
                //console.log('BASE_PHONE phone_num = %s', phone_num);
                var href = '#';
                var href_text = '';
                if (phone_num) {
                  href = 'tel:' + phone_num;
                  href_text = formatInternational('', phone_num) || '';
                }
                if (href_text) {
                    this.$el.find('a.oe_form_uri').attr('href', href).text(href_text);
                    this.$el.find('span.oe_form_char_content').text('');
                } else {
                    this.$el.find('a.oe_form_uri').attr('href', '').text('');
                    this.$el.find('span.oe_form_char_content').text(phone_num || '');
                }
                var click2dial_text = '';
                if (href_text && !this.options.dial_button_invisible) {
                  click2dial_text = _t('Dial');
                }
                this.$el.find('#click2dial').off('click');
                this.$el.find('#click2dial')
                    .text(click2dial_text)
                    .on('click', function(ev) {
                        self.do_notify(
                            _t('Click2dial started'),
                            _t('Unhook your ringing phone'));
                        var arg = {
                            'phone_number': phone_num,
                            'click2dial_model': self.view.dataset.model,
                            'click2dial_id': self.view.datarecord.id};
                        self.rpc('/base_phone/click2dial', arg).done(function(r) {
                            //console.log('Click2dial r=%s', JSON.stringify(r));
                            if (r === false) {
                                self.do_warn("Click2dial failed");
                            } else if (typeof r === 'object') {
                                self.do_notify(
                                    _t('Click2dial successfull'),
                                    _t('Number dialed:') + ' ' + r.dialed_number);
                                if (r.action_model) {
                                    var context = {
                                        'click2dial_model': self.view.dataset.model,
                                        'click2dial_id': self.view.datarecord.id,
                                        'phone_number': phone_num,
                                        };
                                    var action = {
                                        name: r.action_name,
                                        type: 'ir.actions.act_window',
                                        res_model: r.action_model,
                                        view_mode: 'form',
                                        views: [[false, 'form']],
                                        target: 'new',
                                        context: context,
                                        };
                                    instance.client.action_manager.do_action(action);
                                }
                            }
                        });
                    });
            }
        },
        on_button_clicked: function() {
            location.href = 'tel:' + this.get('value');
        }
    });

    instance.web.form.widgets.add('phone', 'instance.base_phone.FieldPhone');

    instance.base_phone.FieldFax = instance.web.form.FieldChar.extend({
        template: 'FieldFax',
        initialize_content: function() {
            this._super();
            var $button = this.$el.find('button');
            $button.click(this.on_button_clicked);
            this.setupFocus($button);
        },
        render_value: function() {
            if (!this.get('effective_readonly')) {
                this._super();
            } else {
                var fax_num = this.get('value');
                //console.log('BASE_PHONE fax_num = %s', fax_num);
                var href = '#';
                var href_text = '';
                if (fax_num) {
                    href = 'fax:' + fax_num;
                    href_text = formatInternational('', fax_num) || '';
                }
                if (href_text) {
                    this.$el.find('a.oe_form_uri').attr('href', href).text(href_text);
                    this.$el.find('span.oe_form_char_content').text('');
                } else {
                    this.$el.find('a.oe_form_uri').attr('href', '').text('');
                    this.$el.find('span.oe_form_char_content').text(fax_num || '');
                }
            }
        },
        on_button_clicked: function() {
            location.href = 'fax:' + this.get('value');
        }
    });

    instance.web.form.widgets.add('fax', 'instance.base_phone.FieldFax');

    /* ability to add widget="phone" in TREE view */
    var _super_list_char_format_ = instance.web.list.Char.prototype._format;
    instance.web.list.Char.prototype._format = function(row_data, options) {
        res = _super_list_char_format_.call(this, row_data, options);
        var value = row_data[this.id].value;
        if (value && this.widget === 'phone') {
            return formatInternational('', value);
        }
        return res;
    };

};
<|endoftext|>


<commit_before>/** @babel */

import fs from 'fs'
import path from 'path'

import {copyRepositoryDir, buildRepository} from '../helpers'
import GitPanelController from '../../lib/controllers/git-panel-controller'

describe('GitPanelController', () => {
  let atomEnvironment, workspace, commandRegistry

  beforeEach(() => {
    atomEnvironment = global.buildAtomEnvironment()
    workspace = atomEnvironment.workspace
    commandRegistry = atomEnvironment.commands
  })

  afterEach(() => {
    atomEnvironment.destroy()
  })

  it('keeps the state of the GitPanelView in sync with the assigned repository', async (done) => {
    const workdirPath1 = await copyRepositoryDir(1)
    const repository1 = await buildRepository(workdirPath1)
    const workdirPath2 = await copyRepositoryDir(1)
    const repository2 = await buildRepository(workdirPath2)
    fs.writeFileSync(path.join(workdirPath1, 'a.txt'), 'a change\n')
    fs.unlinkSync(path.join(workdirPath1, 'b.txt'))
    const controller = new GitPanelController({workspace, commandRegistry, repository: repository1})

    // Does not render a GitPanelView until initial data is fetched
    assert.isUndefined(controller.refs.gitPanel)
    assert.isUndefined(controller.repository)
    await controller.lastModelDataRefreshPromise
    assert.isDefined(controller.repository)
    assert.equal(controller.refs.gitPanel.unstagedChanges, await repository1.getUnstagedChanges())

    // Fetches data when a new repository is assigned
    // Does not update repository instance variable until that data is fetched
    const updatePromise = controller.update({repository: repository2})
    assert.equal(controller.repository, repository1)
    assert.equal(controller.refs.gitPanel.unstagedChanges, await repository1.getUnstagedChanges())
    await updatePromise
    assert.equal(controller.repository, repository2)
    assert.equal(controller.refs.gitPanel.unstagedChanges, await repository2.getUnstagedChanges())

    // Fetches data and updates child view when the repository is mutated
    fs.writeFileSync(path.join(workdirPath2, 'a.txt'), 'a change\n')
    fs.unlinkSync(path.join(workdirPath2, 'b.txt'))
    await repository2.refresh()
    await controller.lastModelDataRefreshPromise
    assert.equal(controller.refs.gitPanel.unstagedChanges, await repository2.getUnstagedChanges())
  })
})
<commit_msg>Add integration test for staging, upstaging, comitting<commit_after>/** @babel */

import fs from 'fs'
import path from 'path'

import {copyRepositoryDir, buildRepository} from '../helpers'
import GitPanelController from '../../lib/controllers/git-panel-controller'

describe('GitPanelController', () => {
  let atomEnvironment, workspace, commandRegistry

  beforeEach(() => {
    atomEnvironment = global.buildAtomEnvironment()
    workspace = atomEnvironment.workspace
    commandRegistry = atomEnvironment.commands
  })

  afterEach(() => {
    atomEnvironment.destroy()
  })

  it('keeps the state of the GitPanelView in sync with the assigned repository', async (done) => {
    const workdirPath1 = await copyRepositoryDir(1)
    const repository1 = await buildRepository(workdirPath1)
    const workdirPath2 = await copyRepositoryDir(1)
    const repository2 = await buildRepository(workdirPath2)
    fs.writeFileSync(path.join(workdirPath1, 'a.txt'), 'a change\n')
    fs.unlinkSync(path.join(workdirPath1, 'b.txt'))
    const controller = new GitPanelController({workspace, commandRegistry, repository: repository1})

    // Does not render a GitPanelView until initial data is fetched
    assert.isUndefined(controller.refs.gitPanel)
    assert.isUndefined(controller.repository)
    await controller.lastModelDataRefreshPromise
    assert.isDefined(controller.repository)
    assert.equal(controller.refs.gitPanel.unstagedChanges, await repository1.getUnstagedChanges())

    // Fetches data when a new repository is assigned
    // Does not update repository instance variable until that data is fetched
    const updatePromise = controller.update({repository: repository2})
    assert.equal(controller.repository, repository1)
    assert.equal(controller.refs.gitPanel.unstagedChanges, await repository1.getUnstagedChanges())
    await updatePromise
    assert.equal(controller.repository, repository2)
    assert.equal(controller.refs.gitPanel.unstagedChanges, await repository2.getUnstagedChanges())

    // Fetches data and updates child view when the repository is mutated
    fs.writeFileSync(path.join(workdirPath2, 'a.txt'), 'a change\n')
    fs.unlinkSync(path.join(workdirPath2, 'b.txt'))
    await repository2.refresh()
    await controller.lastModelDataRefreshPromise
    assert.equal(controller.refs.gitPanel.unstagedChanges, await repository2.getUnstagedChanges())
  })

  describe('integration tests', () => {
    it('can stage and unstage files and commit', async () => {
      const workdirPath = await copyRepositoryDir(1)
      const repository = await buildRepository(workdirPath)
      fs.writeFileSync(path.join(workdirPath, 'a.txt'), 'a change\n')
      fs.unlinkSync(path.join(workdirPath, 'b.txt'))
      const controller = new GitPanelController({workspace, commandRegistry, repository: repository})
      await controller.lastModelDataRefreshPromise
      const stagingView = controller.refs.gitPanel.refs.stagingView
      const commitView = controller.refs.gitPanel.refs.commitView

      assert.equal(stagingView.unstagedChanges.length, 2)
      assert.equal(stagingView.stagedChanges.length, 0)
      await stagingView.didConfirmUnstagedFilePatch(stagingView.unstagedChanges[0])
      await controller.lastModelDataRefreshPromise
      await stagingView.didConfirmUnstagedFilePatch(stagingView.unstagedChanges[0])
      await controller.lastModelDataRefreshPromise
      assert.equal(stagingView.unstagedChanges.length, 0)
      assert.equal(stagingView.stagedChanges.length, 2)
      await stagingView.didConfirmStagedFilePatch(stagingView.stagedChanges[1])
      await controller.lastModelDataRefreshPromise
      assert.equal(stagingView.unstagedChanges.length, 1)
      assert.equal(stagingView.stagedChanges.length, 1)

      commitView.refs.editor.setText('Make it so')
      await commitView.commit()
      await controller.lastModelDataRefreshPromise

      assert.equal(await repository.getLastCommitMessage(), 'Make it so')
    })
  })
})
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Vin Wong @ vinexs.com
 *
 * All rights reserved.
 */

(function(jQuery){

	jQuery.extend({
		url: (function(){
			var data = {};
			var $meta = $('meta[name=data-url]');
			if ($meta.length > 0) {
				var content = $meta.attr('content').split(',');
				for (var i=0; i < content.length; i++) {
					var variable = content[i].trim().split('=');
					data[variable[0]] = variable[1];
				}
			}
			return data;
		})()
	});

})(jQuery);

DOWNLOAD = {
	initLogin: function(){
		$('#login-form button[data-event=login]').click(function(e){
			e.preventDefault();
			DOWNLOAD.login();
		});
	},
	initList: function(){
		DOWNLOAD.setListEvent();
		DOWNLOAD.loadList();
		DOWNLOAD.initRequestDialog();
		DOWNLOAD.initRemoveDialog();

		$('a[data-event=add-request]').click(function(e){
			e.preventDefault();
			DOWNLOAD.openRequestDialog();
		});

		$('a[data-event=remove_all]').click(function(e){
			e.preventDefault();
			DOWNLOAD.removeRequest('all_signature');
		});

		$('a[data-event=logout]').click(function(e){
			e.preventDefault();
			DOWNLOAD.logout();
		});

		$(".button-collapse").sideNav();

		setInterval(function(){
			if ($('#download-list .card[data-status=downloading]').length > 0) {
				DOWNLOAD.loadList();
			}
		}, 5000);

	},
	login: function(){
		var hasError = false;
		var $username = $('input#username');
		var $password = $('input#password');
		if ($username.isEmpty()) {
			$username.addClass('invalid');
			hasError = true;
		}
		if ($password.isEmpty()) {
			$password.addClass('invalid');
			hasError = true;
		}
		if (hasError) {
			return;
		}
		$.ajax({
			url : $.url.activity + 'session/login?'+ $.now(),
			type: 'POST',
			data: {
				username: $username.val(),
				password: $password.val(),
				keep_login: ($('#login-form #remember:checked').length == 1)
			},
			dataType: 'json',
			success: function(json){
				if (json.status != 'OK') {
					return Materialize.toast($.lang('username_not_exist'), 4000);
				}
				location.href = $.url.activity;
			}
		});
	},
	logout: function(){
		$.cookie.remove('RD_TOKEN');
		location.reload();
	},
	getMimeIcon: function(mime) {
		switch (mime) {
		// Type application
			case 'application/msword':
				return 'fa-file-word-o';
			case 'application/pdf':
				return 'fa-file-pdf-o';
			case 'application/vnd.ms-excel':
				return 'fa-file-excel-o';
			case 'application/vnd.ms-powerpoint':
				return 'fa-file-powerpoint-o';
			case 'application/x-dvi':
				return 'fa-file-video-o';
			case 'application/x-shockwave-flash':
			case 'application/xhtml+xml':
				return 'fa-file-o';
			case 'application/x-rar-compressed':
			case 'application/x-7z-compressed':
			case 'application/x-tar':
			case 'application/zip':
				return 'fa-file-archive-o';
		// Type audio
			case 'audio/mpeg':
			case 'audio/vnd.rn-realaudio':
			case 'audio/x-wav':
			case 'audio/x-ms-wma':
				return 'fa-file-audio-o';
		// Type image
			case 'image/gif':
			case 'image/vnd.microsoft.icon':
			case 'image/jpeg':
			case 'image/png':
			case 'image/tiff':
			case 'image/webp':
				return 'fa-file-image-o';
		// Type text
			case 'text/plain':
				return 'fa-file-text-o';
			case 'text/css':
			case 'text/html':
			case 'text/javascript':
			case 'text/xml':
				return 'fa-file-code-o';
		// Type video
			case 'video/flv':
			case 'video/x-flv':
			case 'video/quicktime':
			case 'video/mpeg':
			case 'video/mp4':
			case 'video/quicktime':
			case 'video/webm':
			case 'video/x-ms-wmv':
			case 'video/3gpp':
				return 'fa-file-video-o';
		// Type binary
			case 'application/octet-stream':
				return 'fa-file-o';
		// Type font
			case 'application/vnd.ms-fontobject':
			case 'application/x-font-opentype':
			case 'image/svg+xml':
			case 'application/x-font-ttf':
			case 'application/x-font-woff':
				return 'fa-font';
		}
		return 'fa-file-o';
	},
	getFileSize(bytes) {
		var size = "";
		if (bytes >= Math.pow(1024, 3)) {
			return Math.round((parseInt((bytes / Math.pow(1024, 2)).toFixed()) / 1000) * 100) / 100 + ' GB'
		} else if (bytes >= Math.pow(1024, 2)) {
			return Math.round((parseInt((bytes / Math.pow(1024, 1)).toFixed()) / 1000) * 10) / 10 + ' MB';
		} else if (bytes >= 1024) {
			return Math.round(parseInt((bytes).toFixed()) / 1000) + ' KB';
		} else {
			return bytes + ' B';
		}
	},
	loadList: function(){
		$.ajax({
			url: $.url.activity +'get_list?'+ $.now(),
			dataType: 'json',
			success: function(json){
				if (json.status != 'OK') {
					if (json.data == 'list_empty') {
						$('#download-list').hide().html('');
						$('#no-downloads').show();
					}
					return;
				}
				$('#no-downloads').hide();
				$('#download-list').show();
				var list = json.data;
				var $cardTemplate = $('#item-template');
				for (var signature in list) {
					if ($('.card[data-signature='+ signature +']').length == 0) {
						var card = $cardTemplate.html();
						var $card = $(card.replaceAll('{SIGNATURE}', signature)
												.replaceAll('{STATUS}', list[signature].status)
												.replaceAll('{FILENAME}', list[signature].filename)
												.replaceAll('{URL}', list[signature].url)
												.replaceAll('{FILESIZE}', DOWNLOAD.getFileSize(list[signature].filesize))
												.replaceAll('{ETA}', list[signature].estimated_time)
												.replaceAll('{SPEED}', list[signature].speed));
						$card.find('.file-icon i.fa').addClass(DOWNLOAD.getMimeIcon(list[signature].filetype));
						$card.find('a.filename, a.url').attr('href', list[signature].url);
						$('#download-list').prepend($card);
					} else {
						$card = $('.card[data-signature='+ signature +']');
					}
					$card.attr('data-status', list[signature].status);
					switch (list[signature].status) {
						case 'finished':
							$card.find('.download-progress, .action-ctrl a[data-event]').hide();
							$card.find('[data-event=download]').show();
							break;
						case 'cancel':
						case 'error':
							$card.find('.download-progress, .action-ctrl a[data-event]').hide();
							$card.find('[data-event=retry]').show();
							break;
						case 'downloading':
							$card.find('.download-progress .speed').html(list[signature].estimated_time +' - '+ list[signature].speed);
							$card.find('.download-progress .determinate').css('width', list[signature].precentage +'%');
							$card.find('.download-progress, [data-event=cancel]').show();
							break;
					}
				}
			}
		});
	},
	setListEvent: function(){
		$('#download-list').on('click', '.card [data-event]', function(e){
			e.preventDefault();
			var $btn = $(this);
			var $card = $btn.parents('.card[data-signature]');
			var signature = $card.attr('data-signature');
			switch ($btn.attr('data-event')) {
				case 'download':
					DOWNLOAD.fileRequest(signature);
					break;
				case 'retry':
					DOWNLOAD.retryRequest($card, signature);
					break;
				case 'cancel':
					DOWNLOAD.cancelRequest($card, signature);
					break;
				case 'remove':
					DOWNLOAD.openRemoveDialog(signature);
					break;
			}
		});
	},
	initRequestDialog: function(){
		$('#request-modal a[data-event=download]').click(function(e){
			e.preventDefault();
			var hasError = false;
			var $url = $('input#url');
			var $filename = $('input#filename');
			if ($url.isEmpty() || !$url.val().isURL()) {
				$url.addClass('invalid');
				hasError = true;
			}
			if (hasError) {
				return;
			}
			DOWNLOAD.downloadRequest($url.val(), $filename.val());
		});

		$('#request-modal a[data-event=cancel]').click(function(e){
			e.preventDefault();
			$('#request-modal').closeModal();
		});
	},
	initRemoveDialog: function(){
		$('#remove-modal [data-event=remove]').click(function(e){
			e.preventDefault();
			var signature = $('#remove-modal [data-signature]').attr('data-signature');
			DOWNLOAD.removeRequest(signature);
		});

		$('#remove-modal [data-event=cancel]').click(function(e){
			e.preventDefault();
			$('#remove-modal').closeModal();
		});
	},
	openRequestDialog: function() {
		$('#request-modal input').val('');
		$('#request-modal').openModal({
			dismissible: false
		});
	},
	openRemoveDialog: function(signature){
		$('#remove-modal').find('[data-signature]').attr('data-signature', signature);
		$('#remove-modal').openModal();
	},
	downloadRequest: function(url_link, filename) {
		$.ajax({
			url: $.url.activity + 'request?'+ $.now(),
			type: 'POST',
			data: {
				url_link: url_link,
				filename: filename
			},
			beforeSend: function(){
				$('#request-modal').closeModal();
			},
			dataType: 'json',
			success: function(json){
				if (json.status != 'OK') {
					return;
				}
				setTimeout(function(){
					DOWNLOAD.loadList();
				}, 500)
			}
		});
	},
	fileRequest: function(signature) {
		post($.url.activity + 'get_file', {'signature': signature}, signature);
	},
	cancelRequest: function($card, signature){
		$.ajax({
			url: $.url.activity +'request_cancel?'+ $.now(),
			type: 'POST',
			data: {
				'signature': signature
			},
			dataType: 'json',
			success: function(json) {
				if (json.status == 'OK') {
					$card.find('.download-progress, .action-ctrl a[data-event]').hide();
					$card.find('.action-ctrl [data-event=retry]').show();
				}
			}
		});
	},
	retryRequest: function($card, signature){
		$.ajax({
			url: $.url.activity +'request_retry?'+ $.now(),
			type: 'POST',
			data: {
				'signature': signature
			},
			dataType: 'json',
			success: function(json) {
				$card.find('.action-ctrl [data-event]').hide();
				$card.find('.download-progress .determinate').css('width', '0%');
				$card.find('.download-progress, .action-ctrl [data-event=cancel]').show();
				DOWNLOAD.loadList();
			}
		});
	},
	removeRequest: function(signature){
		$.ajax({
			url: $.url.activity +'request_remove?'+ $.now(),
			type: 'POST',
			data: {
				'signature': signature
			},
			beforeSend: function(){
				$('#remove-modal').closeModal();
			},
			dataType: 'json',
			success: function(json) {
				$('#remove-modal [data-signature]').attr('data-signature', '');
				if (json.status == 'OK') {
					if ( signature == 'all_signature') {
						$('#download-list .item.row').remove();
					} else {
						$('.card[data-signature='+ signature +']').parents('.item.row').remove();
					}
					if ($('#download-list .card[data-signature]').length == 0) {
						$('#download-list').hide().html('');
						$('#no-downloads').show();
					}
				}
			}
		});
	}
};
<commit_msg>Fix bytes data type exception.<commit_after>/*
 * Copyright 2015 Vin Wong @ vinexs.com
 *
 * All rights reserved.
 */

(function(jQuery){

	jQuery.extend({
		url: (function(){
			var data = {};
			var $meta = $('meta[name=data-url]');
			if ($meta.length > 0) {
				var content = $meta.attr('content').split(',');
				for (var i=0; i < content.length; i++) {
					var variable = content[i].trim().split('=');
					data[variable[0]] = variable[1];
				}
			}
			return data;
		})()
	});

})(jQuery);

DOWNLOAD = {
	initLogin: function(){
		$('#login-form button[data-event=login]').click(function(e){
			e.preventDefault();
			DOWNLOAD.login();
		});
	},
	initList: function(){
		DOWNLOAD.setListEvent();
		DOWNLOAD.loadList();
		DOWNLOAD.initRequestDialog();
		DOWNLOAD.initRemoveDialog();

		$('a[data-event=add-request]').click(function(e){
			e.preventDefault();
			DOWNLOAD.openRequestDialog();
		});

		$('a[data-event=remove_all]').click(function(e){
			e.preventDefault();
			DOWNLOAD.removeRequest('all_signature');
		});

		$('a[data-event=logout]').click(function(e){
			e.preventDefault();
			DOWNLOAD.logout();
		});

		$(".button-collapse").sideNav();

		setInterval(function(){
			if ($('#download-list .card[data-status=downloading]').length > 0) {
				DOWNLOAD.loadList();
			}
		}, 5000);

	},
	login: function(){
		var hasError = false;
		var $username = $('input#username');
		var $password = $('input#password');
		if ($username.isEmpty()) {
			$username.addClass('invalid');
			hasError = true;
		}
		if ($password.isEmpty()) {
			$password.addClass('invalid');
			hasError = true;
		}
		if (hasError) {
			return;
		}
		$.ajax({
			url : $.url.activity + 'session/login?'+ $.now(),
			type: 'POST',
			data: {
				username: $username.val(),
				password: $password.val(),
				keep_login: ($('#login-form #remember:checked').length == 1)
			},
			dataType: 'json',
			success: function(json){
				if (json.status != 'OK') {
					return Materialize.toast($.lang('username_not_exist'), 4000);
				}
				location.href = $.url.activity;
			}
		});
	},
	logout: function(){
		$.cookie.remove('RD_TOKEN');
		location.reload();
	},
	getMimeIcon: function(mime) {
		switch (mime) {
		// Type application
			case 'application/msword':
				return 'fa-file-word-o';
			case 'application/pdf':
				return 'fa-file-pdf-o';
			case 'application/vnd.ms-excel':
				return 'fa-file-excel-o';
			case 'application/vnd.ms-powerpoint':
				return 'fa-file-powerpoint-o';
			case 'application/x-dvi':
				return 'fa-file-video-o';
			case 'application/x-shockwave-flash':
			case 'application/xhtml+xml':
				return 'fa-file-o';
			case 'application/x-rar-compressed':
			case 'application/x-7z-compressed':
			case 'application/x-tar':
			case 'application/zip':
				return 'fa-file-archive-o';
		// Type audio
			case 'audio/mpeg':
			case 'audio/vnd.rn-realaudio':
			case 'audio/x-wav':
			case 'audio/x-ms-wma':
				return 'fa-file-audio-o';
		// Type image
			case 'image/gif':
			case 'image/vnd.microsoft.icon':
			case 'image/jpeg':
			case 'image/png':
			case 'image/tiff':
			case 'image/webp':
				return 'fa-file-image-o';
		// Type text
			case 'text/plain':
				return 'fa-file-text-o';
			case 'text/css':
			case 'text/html':
			case 'text/javascript':
			case 'text/xml':
				return 'fa-file-code-o';
		// Type video
			case 'video/flv':
			case 'video/x-flv':
			case 'video/quicktime':
			case 'video/mpeg':
			case 'video/mp4':
			case 'video/quicktime':
			case 'video/webm':
			case 'video/x-ms-wmv':
			case 'video/3gpp':
				return 'fa-file-video-o';
		// Type binary
			case 'application/octet-stream':
				return 'fa-file-o';
		// Type font
			case 'application/vnd.ms-fontobject':
			case 'application/x-font-opentype':
			case 'image/svg+xml':
			case 'application/x-font-ttf':
			case 'application/x-font-woff':
				return 'fa-font';
		}
		return 'fa-file-o';
	},
	getFileSize(bytes) {
		var size = "";
		if (bytes >= Math.pow(1024, 3)) {
			return Math.round((parseInt((bytes / Math.pow(1024, 2)).toFixed()) / 1000) * 100) / 100 + ' GB'
		} else if (bytes >= Math.pow(1024, 2)) {
			return Math.round((parseInt((bytes / Math.pow(1024, 1)).toFixed()) / 1000) * 10) / 10 + ' MB';
		} else if (bytes >= 1024) {
			return Math.round(parseInt((bytes)).toFixed() / 1000) + ' KB';
		} else {
			return bytes + ' B';
		}
	},
	loadList: function(){
		$.ajax({
			url: $.url.activity +'get_list?'+ $.now(),
			dataType: 'json',
			success: function(json){
				if (json.status != 'OK') {
					if (json.data == 'list_empty') {
						$('#download-list').hide().html('');
						$('#no-downloads').show();
					}
					return;
				}
				$('#no-downloads').hide();
				$('#download-list').show();
				var list = json.data;
				var $cardTemplate = $('#item-template');
				for (var signature in list) {
					if ($('.card[data-signature='+ signature +']').length == 0) {
						var card = $cardTemplate.html();
						var $card = $(card.replaceAll('{SIGNATURE}', signature)
												.replaceAll('{STATUS}', list[signature].status)
												.replaceAll('{FILENAME}', list[signature].filename)
												.replaceAll('{URL}', list[signature].url)
												.replaceAll('{FILESIZE}', DOWNLOAD.getFileSize(list[signature].filesize))
												.replaceAll('{ETA}', list[signature].estimated_time)
												.replaceAll('{SPEED}', list[signature].speed));
						$card.find('.file-icon i.fa').addClass(DOWNLOAD.getMimeIcon(list[signature].filetype));
						$card.find('a.filename, a.url').attr('href', list[signature].url);
						$('#download-list').prepend($card);
					} else {
						$card = $('.card[data-signature='+ signature +']');
					}
					$card.attr('data-status', list[signature].status);
					switch (list[signature].status) {
						case 'finished':
							$card.find('.download-progress, .action-ctrl a[data-event]').hide();
							$card.find('[data-event=download]').show();
							break;
						case 'cancel':
						case 'error':
							$card.find('.download-progress, .action-ctrl a[data-event]').hide();
							$card.find('[data-event=retry]').show();
							break;
						case 'downloading':
							$card.find('.download-progress .speed').html(list[signature].estimated_time +' - '+ list[signature].speed);
							$card.find('.download-progress .determinate').css('width', list[signature].precentage +'%');
							$card.find('.download-progress, [data-event=cancel]').show();
							break;
					}
				}
			}
		});
	},
	setListEvent: function(){
		$('#download-list').on('click', '.card [data-event]', function(e){
			e.preventDefault();
			var $btn = $(this);
			var $card = $btn.parents('.card[data-signature]');
			var signature = $card.attr('data-signature');
			switch ($btn.attr('data-event')) {
				case 'download':
					DOWNLOAD.fileRequest(signature);
					break;
				case 'retry':
					DOWNLOAD.retryRequest($card, signature);
					break;
				case 'cancel':
					DOWNLOAD.cancelRequest($card, signature);
					break;
				case 'remove':
					DOWNLOAD.openRemoveDialog(signature);
					break;
			}
		});
	},
	initRequestDialog: function(){
		$('#request-modal a[data-event=download]').click(function(e){
			e.preventDefault();
			var hasError = false;
			var $url = $('input#url');
			var $filename = $('input#filename');
			if ($url.isEmpty() || !$url.val().isURL()) {
				$url.addClass('invalid');
				hasError = true;
			}
			if (hasError) {
				return;
			}
			DOWNLOAD.downloadRequest($url.val(), $filename.val());
		});

		$('#request-modal a[data-event=cancel]').click(function(e){
			e.preventDefault();
			$('#request-modal').closeModal();
		});
	},
	initRemoveDialog: function(){
		$('#remove-modal [data-event=remove]').click(function(e){
			e.preventDefault();
			var signature = $('#remove-modal [data-signature]').attr('data-signature');
			DOWNLOAD.removeRequest(signature);
		});

		$('#remove-modal [data-event=cancel]').click(function(e){
			e.preventDefault();
			$('#remove-modal').closeModal();
		});
	},
	openRequestDialog: function() {
		$('#request-modal input').val('');
		$('#request-modal').openModal({
			dismissible: false
		});
	},
	openRemoveDialog: function(signature){
		$('#remove-modal').find('[data-signature]').attr('data-signature', signature);
		$('#remove-modal').openModal();
	},
	downloadRequest: function(url_link, filename) {
		$.ajax({
			url: $.url.activity + 'request?'+ $.now(),
			type: 'POST',
			data: {
				url_link: url_link,
				filename: filename
			},
			beforeSend: function(){
				$('#request-modal').closeModal();
			},
			dataType: 'json',
			success: function(json){
				if (json.status != 'OK') {
					return;
				}
				setTimeout(function(){
					DOWNLOAD.loadList();
				}, 500)
			}
		});
	},
	fileRequest: function(signature) {
		post($.url.activity + 'get_file', {'signature': signature}, signature);
	},
	cancelRequest: function($card, signature){
		$.ajax({
			url: $.url.activity +'request_cancel?'+ $.now(),
			type: 'POST',
			data: {
				'signature': signature
			},
			dataType: 'json',
			success: function(json) {
				if (json.status == 'OK') {
					$card.find('.download-progress, .action-ctrl a[data-event]').hide();
					$card.find('.action-ctrl [data-event=retry]').show();
				}
			}
		});
	},
	retryRequest: function($card, signature){
		$.ajax({
			url: $.url.activity +'request_retry?'+ $.now(),
			type: 'POST',
			data: {
				'signature': signature
			},
			dataType: 'json',
			success: function(json) {
				$card.find('.action-ctrl [data-event]').hide();
				$card.find('.download-progress .determinate').css('width', '0%');
				$card.find('.download-progress, .action-ctrl [data-event=cancel]').show();
				DOWNLOAD.loadList();
			}
		});
	},
	removeRequest: function(signature){
		$.ajax({
			url: $.url.activity +'request_remove?'+ $.now(),
			type: 'POST',
			data: {
				'signature': signature
			},
			beforeSend: function(){
				$('#remove-modal').closeModal();
			},
			dataType: 'json',
			success: function(json) {
				$('#remove-modal [data-signature]').attr('data-signature', '');
				if (json.status == 'OK') {
					if ( signature == 'all_signature') {
						$('#download-list .item.row').remove();
					} else {
						$('.card[data-signature='+ signature +']').parents('.item.row').remove();
					}
					if ($('#download-list .card[data-signature]').length == 0) {
						$('#download-list').hide().html('');
						$('#no-downloads').show();
					}
				}
			}
		});
	}
};
<|endoftext|>


<commit_before>

(function () {
	var $host;

	$host = $('[mag-thumb="inner"]');
	$host.mag({
	  toggle: true
	});

})();

(function () {
	var $host;

	$host = $('[mag-thumb="outer"]');
	$host.mag({
	  mode: 'outer'
	});
})();

(function () {
	var $host;

	$host = $('[mag-thumb="outer-drag"]');
	$host.mag({
	  mode: 'outer',
	  position: 'drag',
	  toggle: false
	});
})();

(function () {
	var $host;
	var $controls;
	var $hud;

	$host = $('[mag-thumb="drag"]');
	$host.mag({
	  position: 'drag',
	  toggle: false
	});

	$hudLeft = $('

');
	$hudLeft.appendTo($host.parent());

	$hudRight = $('

');
	$hudRight.appendTo($host.parent());

	var toPerc = function (p) {
		return (p * 100).toFixed(1) + '%';
	};

	$host.on('compute', function (e) {
		var mag = $(this).data('mag');
		var m = mag.model;
		$hudLeft.html(
			'
' + m.zoom.toFixed(1) + 'x
'
		);
		$hudRight.html(
			'
(' + toPerc(m.focus.x) + ', ' + toPerc(m.focus.y) + ')
'
		);
	});
})();

(function () {
	var $host;
	var $controls;

	$host = $('[mag-thumb="controls"]');
	$host.mag({
		toggle: false,
		position: false
	});

	$controls = $('[mag-ctrl="controls"]');

	$controls.magCtrl({
		mag: $host
	});

	$host.closest('.col').append($controls);

})();

<commit_msg>examples - remove old controls append<commit_after>

(function () {
	var $host;

	$host = $('[mag-thumb="inner"]');
	$host.mag({
	  toggle: true
	});

})();

(function () {
	var $host;

	$host = $('[mag-thumb="outer"]');
	$host.mag({
	  mode: 'outer'
	});
})();

(function () {
	var $host;

	$host = $('[mag-thumb="outer-drag"]');
	$host.mag({
	  mode: 'outer',
	  position: 'drag',
	  toggle: false
	});
})();

(function () {
	var $host;
	var $controls;
	var $hud;

	$host = $('[mag-thumb="drag"]');
	$host.mag({
	  position: 'drag',
	  toggle: false
	});

	$hudLeft = $('

');
	$hudLeft.appendTo($host.parent());

	$hudRight = $('

');
	$hudRight.appendTo($host.parent());

	var toPerc = function (p) {
		return (p * 100).toFixed(1) + '%';
	};

	$host.on('compute', function (e) {
		var mag = $(this).data('mag');
		var m = mag.model;
		$hudLeft.html(
			'
' + m.zoom.toFixed(1) + 'x
'
		);
		$hudRight.html(
			'
(' + toPerc(m.focus.x) + ', ' + toPerc(m.focus.y) + ')
'
		);
	});
})();

(function () {
	var $host;
	var $controls;

	$host = $('[mag-thumb="controls"]');
	$host.mag({
		toggle: false,
		position: false
	});

	$controls = $('[mag-ctrl="controls"]');
	$controls.magCtrl({
		mag: $host
	});

})();

<|endoftext|>